repo
stringlengths
2
152
file
stringlengths
15
239
code
stringlengths
0
58.4M
file_length
int64
0
58.4M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringclasses
364 values
rmsd
rmsd-master/rmsd/__init__.py
# flake8: noqa from .calculate_rmsd import * from .calculate_rmsd import __doc__, __version__ __all__ = [ "str_atom", "int_atom", "rmsd", "kabsch_rmsd", "kabsch_rotate", "kabsch_fit", "kabsch", "kabsch_weighted", "kabsch_weighted_fit", "kabsch_weighted_rmsd", "quaternion_rmsd", "quaternion_transform", "makeW", "makeQ", "quaternion_rotate", "centroid", "hungarian_vectors", "reorder_similarity", "reorder_distance", "hungarian", "reorder_hungarian", "reorder_inertia_hungarian", "generate_permutations", "brute_permutation", "reorder_brute", "check_reflections", "rotation_matrix_vectors", "get_cm", "get_inertia_tensor", "get_principal_axis", "set_coordinates", "get_coordinates", "get_coordinates_pdb", "get_coordinates_xyz_lines", "get_coordinates_xyz", "main", ] if __name__ == "__main__": main() # pragma: no cover
972
20.152174
48
py
rmsd
rmsd-master/rmsd/calculate_rmsd.py
#!/usr/bin/env python __doc__ = """ Calculate Root-mean-square deviation (RMSD) between structure A and B, in XYZ or PDB format, using transformation and rotation. For more information, usage, example and citation read more at https://github.com/charnley/rmsd """ __version__ = "1.5.1" import argparse import copy import gzip import re import sys from pathlib import Path from typing import Any, Iterator, List, Optional, Protocol, Set, Tuple, Union import numpy as np from numpy import ndarray from scipy.optimize import linear_sum_assignment # type: ignore from scipy.spatial import distance_matrix # type: ignore from scipy.spatial.distance import cdist # type: ignore try: import qml # type: ignore except ImportError: # pragma: no cover qml = None # pragma: no cover METHOD_KABSCH = "kabsch" METHOD_QUATERNION = "quaternion" METHOD_NOROTATION = "none" ROTATION_METHODS = [METHOD_KABSCH, METHOD_QUATERNION, METHOD_NOROTATION] REORDER_NONE = "none" REORDER_QML = "qml" REORDER_HUNGARIAN = "hungarian" REORDER_INERTIA_HUNGARIAN = "inertia-hungarian" REORDER_BRUTE = "brute" REORDER_DISTANCE = "distance" REORDER_METHODS = [ REORDER_NONE, REORDER_QML, REORDER_HUNGARIAN, REORDER_INERTIA_HUNGARIAN, REORDER_BRUTE, REORDER_DISTANCE, ] AXIS_SWAPS = np.array([[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 1, 0], [2, 0, 1]]) AXIS_REFLECTIONS = np.array( [ [1, 1, 1], [-1, 1, 1], [1, -1, 1], [1, 1, -1], [-1, -1, 1], [-1, 1, -1], [1, -1, -1], [-1, -1, -1], ] ) ELEMENT_WEIGHTS = { 1: 1.00797, 2: 4.00260, 3: 6.941, 4: 9.01218, 5: 10.81, 6: 12.011, 7: 14.0067, 8: 15.9994, 9: 18.998403, 10: 20.179, 11: 22.98977, 12: 24.305, 13: 26.98154, 14: 28.0855, 15: 30.97376, 16: 32.06, 17: 35.453, 19: 39.0983, 18: 39.948, 20: 40.08, 21: 44.9559, 22: 47.90, 23: 50.9415, 24: 51.996, 25: 54.9380, 26: 55.847, 28: 58.70, 27: 58.9332, 29: 63.546, 30: 65.38, 31: 69.72, 32: 72.59, 33: 74.9216, 34: 78.96, 35: 79.904, 36: 83.80, 37: 85.4678, 38: 87.62, 39: 88.9059, 40: 91.22, 41: 92.9064, 42: 95.94, 43: 98, 44: 101.07, 45: 102.9055, 46: 106.4, 47: 107.868, 48: 112.41, 49: 114.82, 50: 118.69, 51: 121.75, 53: 126.9045, 52: 127.60, 54: 131.30, 55: 132.9054, 56: 137.33, 57: 138.9055, 58: 140.12, 59: 140.9077, 60: 144.24, 61: 145, 62: 150.4, 63: 151.96, 64: 157.25, 65: 158.9254, 66: 162.50, 67: 164.9304, 68: 167.26, 69: 168.9342, 70: 173.04, 71: 174.967, 72: 178.49, 73: 180.9479, 74: 183.85, 75: 186.207, 76: 190.2, 77: 192.22, 78: 195.09, 79: 196.9665, 80: 200.59, 81: 204.37, 82: 207.2, 83: 208.9804, 84: 209, 85: 210, 86: 222, 87: 223, 88: 226.0254, 89: 227.0278, 91: 231.0359, 90: 232.0381, 93: 237.0482, 92: 238.029, 94: 242, 95: 243, 97: 247, 96: 247, 102: 250, 98: 251, 99: 252, 108: 255, 109: 256, 100: 257, 101: 258, 103: 260, 104: 261, 107: 262, 105: 262, 106: 263, 110: 269, 111: 272, 112: 277, } ELEMENT_NAMES = { 1: "H", 2: "He", 3: "Li", 4: "Be", 5: "B", 6: "C", 7: "N", 8: "O", 9: "F", 10: "Ne", 11: "Na", 12: "Mg", 13: "Al", 14: "Si", 15: "P", 16: "S", 17: "Cl", 18: "Ar", 19: "K", 20: "Ca", 21: "Sc", 22: "Ti", 23: "V", 24: "Cr", 25: "Mn", 26: "Fe", 27: "Co", 28: "Ni", 29: "Cu", 30: "Zn", 31: "Ga", 32: "Ge", 33: "As", 34: "Se", 35: "Br", 36: "Kr", 37: "Rb", 38: "Sr", 39: "Y", 40: "Zr", 41: "Nb", 42: "Mo", 43: "Tc", 44: "Ru", 45: "Rh", 46: "Pd", 47: "Ag", 48: "Cd", 49: "In", 50: "Sn", 51: "Sb", 52: "Te", 53: "I", 54: "Xe", 55: "Cs", 56: "Ba", 57: "La", 58: "Ce", 59: "Pr", 60: "Nd", 61: "Pm", 62: "Sm", 63: "Eu", 64: "Gd", 65: "Tb", 66: "Dy", 67: "Ho", 68: "Er", 69: "Tm", 70: "Yb", 71: "Lu", 72: "Hf", 73: "Ta", 74: "W", 75: "Re", 76: "Os", 77: "Ir", 78: "Pt", 79: "Au", 80: "Hg", 81: "Tl", 82: "Pb", 83: "Bi", 84: "Po", 85: "At", 86: "Rn", 87: "Fr", 88: "Ra", 89: "Ac", 90: "Th", 91: "Pa", 92: "U", 93: "Np", 94: "Pu", 95: "Am", 96: "Cm", 97: "Bk", 98: "Cf", 99: "Es", 100: "Fm", 101: "Md", 102: "No", 103: "Lr", 104: "Rf", 105: "Db", 106: "Sg", 107: "Bh", 108: "Hs", 109: "Mt", 110: "Ds", 111: "Rg", 112: "Cn", 114: "Uuq", 116: "Uuh", } NAMES_ELEMENT = {value: key for key, value in ELEMENT_NAMES.items()} class ReorderCallable(Protocol): def __call__( self, p_atoms: ndarray, q_atoms: ndarray, p_coord: ndarray, q_coord: ndarray, **kwargs: Any, ) -> ndarray: """ Protocol for a reorder callable function Return: ndarray dtype=int # Array of indices """ ... # pragma: no cover class RmsdCallable(Protocol): def __call__( self, P: ndarray, Q: ndarray, **kwargs: Any, ) -> float: """ Protocol for a rotation callable function return: RMSD after rotation """ ... # pragma: no cover def str_atom(atom: int) -> str: """ Convert atom type from integer to string Parameters ---------- atoms : string Returns ------- atoms : integer """ return ELEMENT_NAMES[atom] def int_atom(atom: str) -> int: """ Convert atom type from string to integer Parameters ---------- atoms : string Returns ------- atoms : integer """ atom = atom.capitalize().strip() return NAMES_ELEMENT[atom] def rmsd(P: ndarray, Q: ndarray, **kwargs) -> float: """ Calculate Root-mean-square deviation from two sets of vectors V and W. Parameters ---------- V : array (N,D) matrix, where N is points and D is dimension. W : array (N,D) matrix, where N is points and D is dimension. Returns ------- rmsd : float Root-mean-square deviation between the two vectors """ diff = P - Q return np.sqrt((diff * diff).sum() / P.shape[0]) def kabsch_rmsd( P: ndarray, Q: ndarray, W: Optional[ndarray] = None, translate: bool = False, **kwargs: Any, ) -> float: """ Rotate matrix P unto Q using Kabsch algorithm and calculate the RMSD. An optional vector of weights W may be provided. Parameters ---------- P : array (N,D) matrix, where N is points and D is dimension. Q : array (N,D) matrix, where N is points and D is dimension. W : array or None (N) vector, where N is points. translate : bool Use centroids to translate vector P and Q unto each other. Returns ------- rmsd : float root-mean squared deviation """ if translate: Q = Q - centroid(Q) P = P - centroid(P) if W is not None: return kabsch_weighted_rmsd(P, Q, W) P = kabsch_rotate(P, Q) return rmsd(P, Q) def kabsch_rotate(P: ndarray, Q: ndarray) -> ndarray: """ Rotate matrix P unto matrix Q using Kabsch algorithm. Parameters ---------- P : array (N,D) matrix, where N is points and D is dimension. Q : array (N,D) matrix, where N is points and D is dimension. Returns ------- P : array (N,D) matrix, where N is points and D is dimension, rotated """ U = kabsch(P, Q) # Rotate P P = np.dot(P, U) return P def kabsch_fit(P: ndarray, Q: ndarray, W: Optional[ndarray] = None) -> ndarray: """ Rotate and translate matrix P unto matrix Q using Kabsch algorithm. An optional vector of weights W may be provided. Parameters ---------- P : array (N,D) matrix, where N is points and D is dimension. Q : array (N,D) matrix, where N is points and D is dimension. W : array or None (N) vector, where N is points. Returns ------- P : array (N,D) matrix, where N is points and D is dimension, rotated and translated. """ if W is not None: P, _ = kabsch_weighted_fit(P, Q, W, return_rmsd=False) else: QC = centroid(Q) Q = Q - QC P = P - centroid(P) P = kabsch_rotate(P, Q) + QC return P def kabsch(P: ndarray, Q: ndarray) -> ndarray: """ Using the Kabsch algorithm with two sets of paired point P and Q, centered around the centroid. Each vector set is represented as an NxD matrix, where D is the the dimension of the space. The algorithm works in three steps: - a centroid translation of P and Q (assumed done before this function call) - the computation of a covariance matrix C - computation of the optimal rotation matrix U For more info see http://en.wikipedia.org/wiki/Kabsch_algorithm Parameters ---------- P : array (N,D) matrix, where N is points and D is dimension. Q : array (N,D) matrix, where N is points and D is dimension. Returns ------- U : matrix Rotation matrix (D,D) """ # Computation of the covariance matrix C = np.dot(np.transpose(P), Q) # Computation of the optimal rotation matrix # This can be done using singular value decomposition (SVD) # Getting the sign of the det(V)*(W) to decide # whether we need to correct our rotation matrix to ensure a # right-handed coordinate system. # And finally calculating the optimal rotation matrix U # see http://en.wikipedia.org/wiki/Kabsch_algorithm V, S, W = np.linalg.svd(C) d = (np.linalg.det(V) * np.linalg.det(W)) < 0.0 if d: S[-1] = -S[-1] V[:, -1] = -V[:, -1] # Create Rotation matrix U U: ndarray = np.dot(V, W) return U def kabsch_weighted( P: ndarray, Q: ndarray, W: Optional[ndarray] = None ) -> Tuple[ndarray, ndarray, float]: """ Using the Kabsch algorithm with two sets of paired point P and Q. Each vector set is represented as an NxD matrix, where D is the dimension of the space. An optional vector of weights W may be provided. Note that this algorithm does not require that P and Q have already been overlayed by a centroid translation. The function returns the rotation matrix U, translation vector V, and RMS deviation between Q and P', where P' is: P' = P * U + V For more info see http://en.wikipedia.org/wiki/Kabsch_algorithm Parameters ---------- P : array (N,D) matrix, where N is points and D is dimension. Q : array (N,D) matrix, where N is points and D is dimension. W : array or None (N) vector, where N is points. Returns ------- U : matrix Rotation matrix (D,D) V : vector Translation vector (D) RMSD : float Root mean squared deviation between P and Q """ # Computation of the weighted covariance matrix CMP = np.zeros(3) CMQ = np.zeros(3) C = np.zeros((3, 3)) if W is None: W = np.ones(len(P)) / len(P) W = np.array([W, W, W]).T # NOTE UNUSED psq = 0.0 # NOTE UNUSED qsq = 0.0 iw = 3.0 / W.sum() n = len(P) for i in range(3): for j in range(n): for k in range(3): C[i, k] += P[j, i] * Q[j, k] * W[j, i] CMP = (P * W).sum(axis=0) CMQ = (Q * W).sum(axis=0) PSQ = (P * P * W).sum() - (CMP * CMP).sum() * iw QSQ = (Q * Q * W).sum() - (CMQ * CMQ).sum() * iw C = (C - np.outer(CMP, CMQ) * iw) * iw # Computation of the optimal rotation matrix # This can be done using singular value decomposition (SVD) # Getting the sign of the det(V)*(W) to decide # whether we need to correct our rotation matrix to ensure a # right-handed coordinate system. # And finally calculating the optimal rotation matrix U # see http://en.wikipedia.org/wiki/Kabsch_algorithm V, S, W = np.linalg.svd(C) d = (np.linalg.det(V) * np.linalg.det(W)) < 0.0 if d: S[-1] = -S[-1] V[:, -1] = -V[:, -1] # Create Rotation matrix U, translation vector V, and calculate RMSD: U = np.dot(V, W) msd = (PSQ + QSQ) * iw - 2.0 * S.sum() if msd < 0.0: msd = 0.0 rmsd_ = np.sqrt(msd) V = np.zeros(3) for i in range(3): t = (U[i, :] * CMQ).sum() V[i] = CMP[i] - t V = V * iw return U, V, rmsd_ def kabsch_weighted_fit( P: ndarray, Q: ndarray, W: Optional[ndarray] = None, return_rmsd: bool = False, ) -> Tuple[ndarray, Optional[float]]: """ Fit P to Q with optional weights W. Also returns the RMSD of the fit if return_rmsd=True. Parameters ---------- P : array (N,D) matrix, where N is points and D is dimension. Q : array (N,D) matrix, where N is points and D is dimension. W : vector (N) vector, where N is points rmsd : Bool If True, rmsd is returned as well as the fitted coordinates. Returns ------- P' : array (N,D) matrix, where N is points and D is dimension. RMSD : float if the function is called with rmsd=True """ rmsd_: float R, T, rmsd_ = kabsch_weighted(Q, P, W) PNEW: ndarray = np.dot(P, R.T) + T if return_rmsd: return (PNEW, rmsd_) else: return (PNEW, None) def kabsch_weighted_rmsd(P: ndarray, Q: ndarray, W: Optional[ndarray] = None) -> float: """ Calculate the RMSD between P and Q with optional weighhts W Parameters ---------- P : array (N,D) matrix, where N is points and D is dimension. Q : array (N,D) matrix, where N is points and D is dimension. W : vector (N) vector, where N is points Returns ------- RMSD : float """ _, _, w_rmsd = kabsch_weighted(P, Q, W) return w_rmsd def quaternion_rmsd(P: ndarray, Q: ndarray, **kwargs: Any) -> float: """ Rotate matrix P unto Q and calculate the RMSD based on doi:10.1016/1049-9660(91)90036-O Parameters ---------- P : array (N,D) matrix, where N is points and D is dimension. Q : array (N,D) matrix, where N is points and D is dimension. Returns ------- rmsd : float """ rot = quaternion_rotate(P, Q) P = np.dot(P, rot) return rmsd(P, Q) def quaternion_transform(r: ndarray) -> ndarray: """ Get optimal rotation note: translation will be zero when the centroids of each molecule are the same """ Wt_r = makeW(*r).T Q_r = makeQ(*r) rot: ndarray = Wt_r.dot(Q_r)[:3, :3] return rot def makeW(r1: float, r2: float, r3: float, r4: float = 0) -> ndarray: """ matrix involved in quaternion rotation """ W = np.asarray( [ [r4, r3, -r2, r1], [-r3, r4, r1, r2], [r2, -r1, r4, r3], [-r1, -r2, -r3, r4], ] ) return W def makeQ(r1: float, r2: float, r3: float, r4: float = 0) -> ndarray: """ matrix involved in quaternion rotation """ Q = np.asarray( [ [r4, -r3, r2, r1], [r3, r4, -r1, r2], [-r2, r1, r4, r3], [-r1, -r2, -r3, r4], ] ) return Q def quaternion_rotate(X: ndarray, Y: ndarray) -> ndarray: """ Calculate the rotation Parameters ---------- X : array (N,D) matrix, where N is points and D is dimension. Y: array (N,D) matrix, where N is points and D is dimension. Returns ------- rot : matrix Rotation matrix (D,D) """ N = X.shape[0] W = np.asarray([makeW(*Y[k]) for k in range(N)]) Q = np.asarray([makeQ(*X[k]) for k in range(N)]) Qt_dot_W = np.asarray([np.dot(Q[k].T, W[k]) for k in range(N)]) # NOTE UNUSED W_minus_Q = np.asarray([W[k] - Q[k] for k in range(N)]) A = np.sum(Qt_dot_W, axis=0) eigen = np.linalg.eigh(A) r = eigen[1][:, eigen[0].argmax()] rot = quaternion_transform(r) return rot def centroid(X: ndarray) -> ndarray: """ Centroid is the mean position of all the points in all of the coordinate directions, from a vectorset X. https://en.wikipedia.org/wiki/Centroid C = sum(X)/len(X) Parameters ---------- X : array (N,D) matrix, where N is points and D is dimension. Returns ------- C : ndarray centroid """ C: ndarray = X.mean(axis=0) return C def hungarian_vectors( p_vecs: ndarray, q_vecs: ndarray, sigma: float = 1e-0, use_kernel: bool = True ) -> ndarray: """ Hungarian cost assignment of a similiarty molecule kernel. Note: Assumes p and q are atoms of same type Parameters ---------- p_vecs : array (N,L) matrix, where N is no. of atoms and L is representation length q_vecs : array (N,L) matrix, where N is no. of atoms and L is representation length Returns ------- indices_b : array (N) view vector of reordered assignment """ if use_kernel: # Calculate cost matrix from similarity kernel K = qml.kernels.laplacian_kernel(p_vecs, q_vecs, sigma) K *= -1.0 K += 1.0 else: K = distance_matrix(p_vecs, q_vecs) # Perform Hungarian analysis on distance matrix between atoms of 1st # structure and trial structure indices_b: ndarray indices_a: ndarray indices_a, indices_b = linear_sum_assignment(K) return indices_b def reorder_similarity( p_atoms: ndarray, q_atoms: ndarray, p_coord: ndarray, q_coord: ndarray, use_kernel: bool = True, **kwargs: Any, ) -> ndarray: """ Re-orders the input atom list and xyz coordinates using QML similarity the Hungarian method for assignment. Parameters ---------- p_atoms : array (N,1) matrix, where N is points holding the atoms' names p_atoms : array (N,1) matrix, where N is points holding the atoms' names p_coord : array (N,D) matrix, where N is points and D is dimension q_coord : array (N,D) matrix, where N is points and D is dimension Returns ------- view_reorder : array (N,1) matrix, reordered indexes of atom alignment based on the coordinates of the atoms """ if qml is None: raise ImportError( # pragma: no cover "QML is not installed. Package is avaliable from" "\n github.com/qmlcode/qml" "\n pip install qml" ) elements = np.unique(p_atoms) n_atoms = p_atoms.shape[0] distance_cut = 20.0 parameters = { "elements": elements, "pad": n_atoms, "rcut": distance_cut, "acut": distance_cut, } p_vecs = qml.representations.generate_fchl_acsf(p_atoms, p_coord, **parameters) q_vecs = qml.representations.generate_fchl_acsf(q_atoms, q_coord, **parameters) # generate full view from q shape to fill in atom view on the fly view_reorder = np.zeros(q_atoms.shape, dtype=int) for atom in elements: (p_atom_idx,) = np.where(p_atoms == atom) (q_atom_idx,) = np.where(q_atoms == atom) p_vecs_atom = p_vecs[p_atom_idx] q_vecs_atom = q_vecs[q_atom_idx] view = hungarian_vectors(p_vecs_atom, q_vecs_atom, use_kernel=use_kernel) view_reorder[p_atom_idx] = q_atom_idx[view] return view_reorder def reorder_distance( p_atoms: ndarray, q_atoms: ndarray, p_coord: ndarray, q_coord: ndarray, **kwargs: Any, ) -> ndarray: """ Re-orders the input atom list and xyz coordinates by atom type and then by distance of each atom from the centroid. Parameters ---------- atoms : array (N,1) matrix, where N is points holding the atoms' names coord : array (N,D) matrix, where N is points and D is dimension Returns ------- atoms_reordered : array (N,1) matrix, where N is points holding the ordered atoms' names coords_reordered : array (N,D) matrix, where N is points and D is dimension (rows re-ordered) """ # Find unique atoms unique_atoms = np.unique(p_atoms) # generate full view from q shape to fill in atom view on the fly view_reorder = np.zeros(q_atoms.shape, dtype=int) for atom in unique_atoms: (p_atom_idx,) = np.where(p_atoms == atom) (q_atom_idx,) = np.where(q_atoms == atom) A_coord = p_coord[p_atom_idx] B_coord = q_coord[q_atom_idx] # Calculate distance from each atom to centroid A_norms = np.linalg.norm(A_coord, axis=1) B_norms = np.linalg.norm(B_coord, axis=1) reorder_indices_A = np.argsort(A_norms) reorder_indices_B = np.argsort(B_norms) # Project the order of P onto Q translator = np.argsort(reorder_indices_A) view = reorder_indices_B[translator] view_reorder[p_atom_idx] = q_atom_idx[view] return view_reorder def hungarian(A: ndarray, B: ndarray) -> ndarray: """ Hungarian reordering. Assume A and B are coordinates for atoms of SAME type only """ # should be kabasch here i think distances = cdist(A, B, "euclidean") # Perform Hungarian analysis on distance matrix between atoms of 1st # structure and trial structure indices_b: ndarray indices_a: ndarray indices_a, indices_b = linear_sum_assignment(distances) return indices_b def reorder_hungarian( p_atoms: ndarray, q_atoms: ndarray, p_coord: ndarray, q_coord: ndarray, **kwargs: Any, ) -> ndarray: """ Re-orders the input atom list and xyz coordinates using the Hungarian method (using optimized column results) Parameters ---------- p_atoms : array (N,1) matrix, where N is points holding the atoms' names p_atoms : array (N,1) matrix, where N is points holding the atoms' names p_coord : array (N,D) matrix, where N is points and D is dimension q_coord : array (N,D) matrix, where N is points and D is dimension Returns ------- view_reorder : array (N,1) matrix, reordered indexes of atom alignment based on the coordinates of the atoms """ # Find unique atoms unique_atoms = np.unique(p_atoms) # generate full view from q shape to fill in atom view on the fly view_reorder = np.zeros(q_atoms.shape, dtype=int) view_reorder -= 1 for atom in unique_atoms: (p_atom_idx,) = np.where(p_atoms == atom) (q_atom_idx,) = np.where(q_atoms == atom) A_coord = p_coord[p_atom_idx] B_coord = q_coord[q_atom_idx] view = hungarian(A_coord, B_coord) view_reorder[p_atom_idx] = q_atom_idx[view] return view_reorder def reorder_inertia_hungarian( p_atoms: ndarray, q_atoms: ndarray, p_coord: ndarray, q_coord: ndarray, **kwargs: Any, ) -> ndarray: """ Align the principal intertia axis and then re-orders the input atom list and xyz coordinates using the Hungarian method (using optimized column results) Parameters ---------- p_atoms : array (N,1) matrix, where N is points holding the atoms' names p_atoms : array (N,1) matrix, where N is points holding the atoms' names p_coord : array (N,D) matrix, where N is points and D is dimension q_coord : array (N,D) matrix, where N is points and D is dimension Returns ------- view_reorder : array (N,1) matrix, reordered indexes of atom alignment based on the coordinates of the atoms """ # get the principal axis of P and Q p_axis = get_principal_axis(p_atoms, p_coord) q_axis = get_principal_axis(q_atoms, q_coord) # rotate Q onto P considering that the axis are parallel and antiparallel U1 = rotation_matrix_vectors(p_axis, q_axis) U2 = rotation_matrix_vectors(p_axis, -q_axis) q_coord1 = np.dot(q_coord, U1) q_coord2 = np.dot(q_coord, U2) q_review1 = reorder_hungarian(p_atoms, q_atoms, p_coord, q_coord1) q_review2 = reorder_hungarian(p_atoms, q_atoms, p_coord, q_coord2) q_coord1 = q_coord1[q_review1] q_coord2 = q_coord2[q_review2] rmsd1 = kabsch_rmsd(p_coord, q_coord1) rmsd2 = kabsch_rmsd(p_coord, q_coord2) if rmsd1 < rmsd2: return q_review1 else: return q_review2 def generate_permutations(elements: List[int], n: int) -> Iterator[List[int]]: """ Heap's algorithm for generating all n! permutations in a list https://en.wikipedia.org/wiki/Heap%27s_algorithm """ c = [0] * n yield elements i = 0 while i < n: if c[i] < i: if i % 2 == 0: elements[0], elements[i] = elements[i], elements[0] else: elements[c[i]], elements[i] = elements[i], elements[c[i]] yield elements c[i] += 1 i = 0 else: c[i] = 0 i += 1 def brute_permutation(A: ndarray, B: ndarray) -> ndarray: """ Re-orders the input atom list and xyz coordinates using the brute force method of permuting all rows of the input coordinates Parameters ---------- A : array (N,D) matrix, where N is points and D is dimension B : array (N,D) matrix, where N is points and D is dimension Returns ------- view : array (N,1) matrix, reordered view of B projected to A """ rmsd_min = np.inf view_min: ndarray # Sets initial ordering for row indices to [0, 1, 2, ..., len(A)], used in # brute-force method num_atoms = A.shape[0] initial_order = list(range(num_atoms)) for reorder_indices in generate_permutations(initial_order, num_atoms): # Re-order the atom array and coordinate matrix coords_ordered = B[reorder_indices] # Calculate the RMSD between structure 1 and the Hungarian re-ordered # structure 2 rmsd_temp = kabsch_rmsd(A, coords_ordered) # Replaces the atoms and coordinates with the current structure if the # RMSD is lower if rmsd_temp < rmsd_min: rmsd_min = rmsd_temp view_min = np.asarray(copy.deepcopy(reorder_indices)) return view_min def reorder_brute( p_atoms: ndarray, q_atoms: ndarray, p_coord: ndarray, q_coord: ndarray, **kwargs: Any, ) -> ndarray: """ Re-orders the input atom list and xyz coordinates using all permutation of rows (using optimized column results) Parameters ---------- p_atoms : array (N,1) matrix, where N is points holding the atoms' names q_atoms : array (N,1) matrix, where N is points holding the atoms' names p_coord : array (N,D) matrix, where N is points and D is dimension q_coord : array (N,D) matrix, where N is points and D is dimension Returns ------- view_reorder : array (N,1) matrix, reordered indexes of atom alignment based on the coordinates of the atoms """ # Find unique atoms unique_atoms = np.unique(p_atoms) # generate full view from q shape to fill in atom view on the fly view_reorder = np.zeros(q_atoms.shape, dtype=int) view_reorder -= 1 for atom in unique_atoms: (p_atom_idx,) = np.where(p_atoms == atom) (q_atom_idx,) = np.where(q_atoms == atom) A_coord = p_coord[p_atom_idx] B_coord = q_coord[q_atom_idx] view = brute_permutation(A_coord, B_coord) view_reorder[p_atom_idx] = q_atom_idx[view] return view_reorder def check_reflections( p_atoms: ndarray, q_atoms: ndarray, p_coord: ndarray, q_coord: ndarray, reorder_method: Optional[ReorderCallable] = None, rmsd_method: RmsdCallable = kabsch_rmsd, keep_stereo: bool = False, ) -> Tuple[float, ndarray, ndarray, ndarray]: """ Minimize RMSD using reflection planes for molecule P and Q Warning: This will affect stereo-chemistry Parameters ---------- p_atoms : array (N,1) matrix, where N is points holding the atoms' names q_atoms : array (N,1) matrix, where N is points holding the atoms' names p_coord : array (N,D) matrix, where N is points and D is dimension q_coord : array (N,D) matrix, where N is points and D is dimension Returns ------- min_rmsd min_swap min_reflection min_review """ if reorder_method is None: assert (p_atoms == q_atoms).all(), "No reorder method selected, but atoms are not ordered" min_rmsd = np.inf min_swap: ndarray min_reflection: ndarray min_review: ndarray = np.array(range(len(p_atoms))) tmp_review: ndarray = min_review swap_mask = [1, -1, -1, 1, -1, 1] reflection_mask = [1, -1, -1, -1, 1, 1, 1, -1] for swap, i in zip(AXIS_SWAPS, swap_mask): for reflection, j in zip(AXIS_REFLECTIONS, reflection_mask): # skip enantiomers if keep_stereo and i * j == -1: continue tmp_atoms = copy.copy(q_atoms) tmp_coord = copy.deepcopy(q_coord) tmp_coord = tmp_coord[:, swap] tmp_coord = np.dot(tmp_coord, np.diag(reflection)) tmp_coord -= centroid(tmp_coord) # Reorder if reorder_method is not None: tmp_review = reorder_method(p_atoms, tmp_atoms, p_coord, tmp_coord) tmp_coord = tmp_coord[tmp_review] tmp_atoms = tmp_atoms[tmp_review] # Rotation this_rmsd = rmsd_method(p_coord, tmp_coord) if this_rmsd < min_rmsd: min_rmsd = this_rmsd min_swap = swap min_reflection = reflection min_review = tmp_review assert (p_atoms == q_atoms[min_review]).all(), "error: Not aligned" return min_rmsd, min_swap, min_reflection, min_review def rotation_matrix_vectors(v1: ndarray, v2: ndarray) -> ndarray: """ Returns the rotation matrix that rotates v1 onto v2 using Rodrigues' rotation formula. (see https://math.stackexchange.com/a/476311) ---------- v1 : array Dim 3 float array v2 : array Dim 3 float array Return ------ output : 3x3 matrix Rotation matrix """ rot: ndarray if (v1 == v2).all(): rot = np.eye(3) # return a rotation of pi around the y-axis elif (v1 == -v2).all(): rot = np.array([[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]]) else: v = np.cross(v1, v2) s = np.linalg.norm(v) c = np.vdot(v1, v2) vx = np.array([[0.0, -v[2], v[1]], [v[2], 0.0, -v[0]], [-v[1], v[0], 0.0]]) rot = np.eye(3) + vx + np.dot(vx, vx) * ((1.0 - c) / (s * s)) return rot def get_cm(atoms: ndarray, V: ndarray) -> ndarray: """ Get the center of mass of V. ---------- atoms : list List of atomic types V : array (N,3) matrix of atomic coordinates Return ------ output : (3) array The CM vector """ weights: Union[List[float], ndarray] = [ELEMENT_WEIGHTS[x] for x in atoms] weights = np.asarray(weights) center_of_mass: ndarray = np.average(V, axis=0, weights=weights) return center_of_mass def get_inertia_tensor(atoms: ndarray, V: ndarray) -> ndarray: """ Get the tensor of intertia of V. ---------- atoms : list List of atomic types V : array (N,3) matrix of atomic coordinates Return ------ output : 3x3 float matrix The tensor of inertia """ CV = V - get_cm(atoms, V) Ixx = 0.0 Iyy = 0.0 Izz = 0.0 Ixy = 0.0 Ixz = 0.0 Iyz = 0.0 for sp, acoord in zip(atoms, CV): amass = ELEMENT_WEIGHTS[sp] Ixx += amass * (acoord[1] * acoord[1] + acoord[2] * acoord[2]) Iyy += amass * (acoord[0] * acoord[0] + acoord[2] * acoord[2]) Izz += amass * (acoord[0] * acoord[0] + acoord[1] * acoord[1]) Ixy += -amass * acoord[0] * acoord[1] Ixz += -amass * acoord[0] * acoord[2] Iyz += -amass * acoord[1] * acoord[2] return np.array([[Ixx, Ixy, Ixz], [Ixy, Iyy, Iyz], [Ixz, Iyz, Izz]]) def get_principal_axis(atoms: ndarray, V: ndarray) -> ndarray: """ Get the molecule's principal axis. ---------- atoms : list List of atomic types V : array (N,3) matrix of atomic coordinates Return ------ output : array Array of dim 3 containing the principal axis """ inertia = get_inertia_tensor(atoms, V) eigval, eigvec = np.linalg.eig(inertia) principal_axis: ndarray = eigvec[np.argmax(eigval)] return principal_axis def set_coordinates(atoms: ndarray, V: ndarray, title: str = "", decimals: int = 8) -> str: """ Print coordinates V with corresponding atoms to stdout in XYZ format. Parameters ---------- atoms : list List of atomic types V : array (N,3) matrix of atomic coordinates title : string (optional) Title of molecule decimals : int (optional) number of decimals for the coordinates Return ------ output : str Molecule in XYZ format """ N, D = V.shape fmt = "{:<2}" + (" {:15." + str(decimals) + "f}") * 3 out = list() out += [str(N)] out += [title] for i in range(N): atom = atoms[i] out += [fmt.format(atom, V[i, 0], V[i, 1], V[i, 2])] return "\n".join(out) def get_coordinates( filename: Path, fmt: str, is_gzip: bool = False, return_atoms_as_int: bool = False ) -> Tuple[ndarray, ndarray]: """ Get coordinates from filename in format fmt. Supports XYZ and PDB. Parameters ---------- filename : string Filename to read fmt : string Format of filename. Either xyz or pdb. Returns ------- atoms : list List of atomic types V : array (N,3) where N is number of atoms """ if fmt == "xyz": get_func = get_coordinates_xyz elif fmt == "pdb": get_func = get_coordinates_pdb else: raise ValueError("Could not recognize file format: {:s}".format(fmt)) val = get_func(filename, is_gzip=is_gzip, return_atoms_as_int=return_atoms_as_int) return val def get_coordinates_pdb( filename: Path, is_gzip: bool = False, return_atoms_as_int: bool = False ) -> Tuple[ndarray, ndarray]: """ Get coordinates from the first chain in a pdb file and return a vectorset with all the coordinates. Parameters ---------- filename : string Filename to read Returns ------- atoms : list List of atomic types V : array (N,3) where N is number of atoms """ # PDB files tend to be a bit of a mess. The x, y and z coordinates # are supposed to be in column 31-38, 39-46 and 47-54, but this is # not always the case. # Because of this the three first columns containing a decimal is used. # Since the format doesn't require a space between columns, we use the # above column indices as a fallback. x_column: Optional[int] = None V: Union[List[ndarray], ndarray] = list() assert isinstance(V, list) # Same with atoms and atom naming. # The most robust way to do this is probably # to assume that the atomtype is given in column 3. atoms: Union[List[int], ndarray] = list() assert isinstance(atoms, list) openfunc: Any if is_gzip: openfunc = gzip.open openarg = "rt" else: openfunc = open openarg = "r" with openfunc(filename, openarg) as f: lines = f.readlines() for line in lines: if line.startswith("TER") or line.startswith("END"): break if line.startswith("ATOM") or line.startswith("HETATM"): tokens = line.split() # Try to get the atomtype try: atom = tokens[2][0] if atom in ("H", "C", "N", "O", "S", "P"): atoms.append(atom) else: # e.g. 1HD1 atom = tokens[2][1] if atom == "H": atoms.append(atom) else: raise Exception except ValueError: msg = f"error: Parsing atomtype for the following line:" f" \n{line}" exit(msg) if x_column is None: try: # look for x column for i, x in enumerate(tokens): if "." in x and "." in tokens[i + 1] and "." in tokens[i + 2]: x_column = i break except IndexError: msg = "error: Parsing coordinates " "for the following line:" f"\n{line}" exit(msg) assert x_column is not None # Try to read the coordinates try: V.append(np.asarray(tokens[x_column : x_column + 3], dtype=float)) except ValueError: # If that doesn't work, use hardcoded indices try: x = line[30:38] y = line[38:46] z = line[46:54] V.append(np.asarray([x, y, z], dtype=float)) except ValueError: msg = f"error: Parsing input for the following line \n{line}" exit(msg) if return_atoms_as_int: atoms = [int_atom(str(atom)) for atom in atoms] V = np.asarray(V) assert isinstance(V, ndarray) atoms = np.asarray(atoms) assert isinstance(atoms, ndarray) assert V.shape[0] == atoms.size return atoms, V def get_coordinates_xyz_lines( lines: List[str], return_atoms_as_int: bool = False ) -> Tuple[ndarray, ndarray]: V: Union[List[ndarray], ndarray] = list() atoms: Union[List[str], ndarray] = list() n_atoms = 0 assert isinstance(V, list) assert isinstance(atoms, list) # Read the first line to obtain the number of atoms to read try: n_atoms = int(lines[0]) except ValueError: exit("error: Could not obtain the number of atoms in the .xyz file.") # Skip the title line # Use the number of atoms to not read beyond the end of a file for lines_read, line in enumerate(lines[2:]): line = line.strip() if lines_read == n_atoms: break values = line.split() if len(values) < 4: atom = re.findall(r"[a-zA-Z]+", line)[0] atom = atom.upper() numbers = re.findall(r"[-]?\d+\.\d*(?:[Ee][-\+]\d+)?", line) numbers = [float(number) for number in numbers] else: atom = values[0] numbers = [float(number) for number in values[1:]] # The numbers are not valid unless we obtain exacly three if len(numbers) >= 3: V.append(np.array(numbers)[:3]) atoms.append(atom) else: msg = ( f"Reading the .xyz file failed in line {lines_read + 2}." "Please check the format." ) exit(msg) try: # I've seen examples where XYZ are written with integer atoms types atoms_ = [int(atom) for atom in atoms] atoms = [str_atom(atom) for atom in atoms_] except ValueError: # Correct atom spelling atoms = [atom.capitalize() for atom in atoms] if return_atoms_as_int: atoms_ = [int_atom(atom) for atom in atoms] atoms = np.array(atoms_) else: atoms = np.array(atoms) V = np.array(V) return atoms, V def get_coordinates_xyz( filename: Path, is_gzip: bool = False, return_atoms_as_int: bool = False, ) -> Tuple[ndarray, ndarray]: """ Get coordinates from filename and return a vectorset with all the coordinates, in XYZ format. Parameters ---------- filename : string Filename to read Returns ------- atoms : list List of atomic types V : array (N,3) where N is number of atoms """ openfunc: Any if is_gzip: openfunc = gzip.open openarg = "rt" else: openfunc = open openarg = "r" with openfunc(filename, openarg) as f: lines = f.readlines() atoms, V = get_coordinates_xyz_lines(lines, return_atoms_as_int=return_atoms_as_int) return atoms, V def parse_arguments(arguments: Optional[Union[str, List[str]]] = None) -> argparse.Namespace: description = __doc__ version_msg = f""" rmsd {__version__} See https://github.com/charnley/rmsd for citation information """ epilog = """ """ valid_reorder_methods = ", ".join(REORDER_METHODS) valid_rotation_methods = ", ".join(ROTATION_METHODS) parser = argparse.ArgumentParser( usage="calculate_rmsd [options] FILE_A FILE_B", description=description, formatter_class=argparse.RawDescriptionHelpFormatter, epilog=epilog, ) # Input structures parser.add_argument( "structure_a", metavar="FILE_A", type=str, help="structures in .xyz or .pdb format", ) parser.add_argument("structure_b", metavar="FILE_B", type=str) # Admin parser.add_argument("-v", "--version", action="version", version=version_msg) # Rotation parser.add_argument( "-r", "--rotation", action="store", default="kabsch", help=( "select rotation method. Valid methods are " f"{valid_rotation_methods}. " "Default is Kabsch." ), metavar="METHOD", ) # Reorder arguments parser.add_argument( "-e", "--reorder", action="store_true", help="align the atoms of molecules", ) parser.add_argument( "--reorder-method", action="store", default="hungarian", metavar="METHOD", help=( "select reorder method. Valid method are " f"{valid_reorder_methods}. " "Default is Hungarian." ), ) parser.add_argument( "-ur", "--use-reflections", action="store_true", help=( "scan through reflections in planes " "(eg Y transformed to -Y -> X, -Y, Z) " "and axis changes, (eg X and Z coords exchanged -> Z, Y, X). " "This will affect stereo-chemistry." ), ) parser.add_argument( "-urks", "--use-reflections-keep-stereo", action="store_true", help=( "scan through reflections in planes " "(eg Y transformed to -Y -> X, -Y, Z) " "and axis changes, (eg X and Z coords exchanged -> Z, Y, X). " "Stereo-chemistry will be kept." ), ) # Filter index_group = parser.add_mutually_exclusive_group() index_group.add_argument( "-nh", "--ignore-hydrogen", "--no-hydrogen", action="store_true", help="ignore hydrogens when calculating RMSD", ) index_group.add_argument( "--remove-idx", nargs="+", type=int, help="index list of atoms NOT to consider", metavar="IDX", ) index_group.add_argument( "--add-idx", nargs="+", type=int, help="index list of atoms to consider", metavar="IDX", ) parser.add_argument( "--format", action="store", help="format of input files. valid format are xyz and pdb", metavar="FMT", ) parser.add_argument( "--format-is-gzip", action="store_true", default=False, help=argparse.SUPPRESS, ) parser.add_argument( "-p", "--output", "--print", action="store_true", help=( "print out structure B, " "centered and rotated unto structure A's coordinates " "in XYZ format" ), ) args = parser.parse_args(arguments) # Check illegal combinations if args.output and args.reorder and (args.ignore_hydrogen or args.add_idx or args.remove_idx): print( "error: Cannot reorder atoms and print structure, " "when excluding atoms (such as --ignore-hydrogen)" ) sys.exit() if ( args.use_reflections and args.output and (args.ignore_hydrogen or args.add_idx or args.remove_idx) ): print( "error: Cannot use reflections on atoms and print, " "when excluding atoms (such as --ignore-hydrogen)" ) sys.exit() # Check methods args.rotation = args.rotation.lower() if args.rotation not in ROTATION_METHODS: print( f"error: Unknown rotation method: '{args.rotation}'. " f"Please use {valid_rotation_methods}" ) sys.exit() # Check reorder methods args.reorder_method = args.reorder_method.lower() if args.reorder_method not in REORDER_METHODS: print( f'error: Unknown reorder method: "{args.reorder_method}". ' f"Please use {valid_reorder_methods}" ) sys.exit() # Check fileformat if args.format is None: filename = args.structure_a suffixes = Path(filename).suffixes if len(suffixes) == 0: ext = None elif suffixes[-1] == ".gz": args.format_is_gzip = True ext = suffixes[-2].strip(".") else: ext = suffixes[-1].strip(".") args.format = ext return args def main(args: Optional[List[str]] = None) -> None: # Parse arguments settings = parse_arguments(args) # As default, load the extension as format # Parse pdb.gz and xyz.gz as pdb and xyz formats p_all_atoms, p_all = get_coordinates( settings.structure_a, settings.format, is_gzip=settings.format_is_gzip, return_atoms_as_int=True, ) q_all_atoms, q_all = get_coordinates( settings.structure_b, settings.format, is_gzip=settings.format_is_gzip, return_atoms_as_int=True, ) p_size = p_all.shape[0] q_size = q_all.shape[0] if not p_size == q_size: print("error: Structures not same size") sys.exit() if np.count_nonzero(p_all_atoms != q_all_atoms) and not settings.reorder: msg = """ error: Atoms are not in the same order. Use --reorder to align the atoms (can be expensive for large structures). Please see --help or documentation for more information or https://github.com/charnley/rmsd for further examples. """ print(msg) sys.exit() # Typing index: Union[Set[int], List[int], ndarray] # Set local view p_view: Optional[ndarray] = None q_view: Optional[ndarray] = None if settings.ignore_hydrogen: assert type(p_all_atoms[0]) != str assert type(q_all_atoms[0]) != str p_view = np.where(p_all_atoms != 1) # type: ignore q_view = np.where(q_all_atoms != 1) # type: ignore elif settings.remove_idx: index = np.array(list(set(range(p_size)) - set(settings.remove_idx))) p_view = index q_view = index elif settings.add_idx: p_view = settings.add_idx q_view = settings.add_idx # Set local view if p_view is None: p_coord = copy.deepcopy(p_all) q_coord = copy.deepcopy(q_all) p_atoms = copy.deepcopy(p_all_atoms) q_atoms = copy.deepcopy(q_all_atoms) else: assert p_view is not None assert q_view is not None p_coord = copy.deepcopy(p_all[p_view]) q_coord = copy.deepcopy(q_all[q_view]) p_atoms = copy.deepcopy(p_all_atoms[p_view]) q_atoms = copy.deepcopy(q_all_atoms[q_view]) # Recenter to centroid p_cent = centroid(p_coord) q_cent = centroid(q_coord) p_coord -= p_cent q_coord -= q_cent rmsd_method: RmsdCallable reorder_method: Optional[ReorderCallable] # set rotation method if settings.rotation == METHOD_KABSCH: rmsd_method = kabsch_rmsd elif settings.rotation == METHOD_QUATERNION: rmsd_method = quaternion_rmsd else: rmsd_method = rmsd # set reorder method reorder_method = None if settings.reorder_method == REORDER_QML: reorder_method = reorder_similarity elif settings.reorder_method == REORDER_HUNGARIAN: reorder_method = reorder_hungarian elif settings.reorder_method == REORDER_INERTIA_HUNGARIAN: reorder_method = reorder_inertia_hungarian elif settings.reorder_method == REORDER_BRUTE: reorder_method = reorder_brute # pragma: no cover elif settings.reorder_method == REORDER_DISTANCE: reorder_method = reorder_distance # Save the resulting RMSD result_rmsd = None # Collect changes to be done on q coords q_swap = None q_reflection = None q_review = None if settings.use_reflections: result_rmsd, q_swap, q_reflection, q_review = check_reflections( p_atoms, q_atoms, p_coord, q_coord, reorder_method=reorder_method, rmsd_method=rmsd_method, ) elif settings.use_reflections_keep_stereo: result_rmsd, q_swap, q_reflection, q_review = check_reflections( p_atoms, q_atoms, p_coord, q_coord, reorder_method=reorder_method, rmsd_method=rmsd_method, keep_stereo=True, ) elif settings.reorder: assert reorder_method is not None, "Cannot reorder without selecting --reorder method" q_review = reorder_method(p_atoms, q_atoms, p_coord, q_coord) # If there is a reorder, then apply before print if q_review is not None: q_all_atoms = q_all_atoms[q_review] q_atoms = q_atoms[q_review] q_coord = q_coord[q_review] assert all( p_atoms == q_atoms ), "error: Structure not aligned. Please submit bug report at http://github.com/charnley/rmsd" # print result if settings.output: if q_swap is not None: q_coord = q_coord[:, q_swap] if q_reflection is not None: q_coord = np.dot(q_coord, np.diag(q_reflection)) q_coord -= centroid(q_coord) # Rotate q coordinates # TODO Should actually follow rotation method q_coord = kabsch_rotate(q_coord, p_coord) # center q on p's original coordinates q_coord += p_cent # done and done xyz = set_coordinates(q_all_atoms, q_coord, title=f"{settings.structure_b} - modified") print(xyz) else: if not result_rmsd: result_rmsd = rmsd_method(p_coord, q_coord) print("{0}".format(result_rmsd)) if __name__ == "__main__": main() # pragma: no cover
52,179
24.281008
102
py
rmsd
rmsd-master/tests/context.py
import subprocess from pathlib import Path from typing import List RESOURCE_PATH = Path("tests/resources") def call_main(args: List[str]) -> List[str]: root_path = Path("./") filename = root_path / "rmsd/calculate_rmsd.py" cmd = ["python", f"{filename}", *args] proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = proc.communicate() if stderr is not None: print(stderr.decode()) return stdout.decode().strip().split("\n")
510
22.227273
82
py
rmsd
rmsd-master/tests/test_args.py
import pytest from rmsd import calculate_rmsd def test_formats() -> None: args_ = "filename.xyz.gz filename2.xyz.gz".split() args = calculate_rmsd.parse_arguments(args_) assert args.format_is_gzip def test_legal_arguments() -> None: args_ = "--rotation kabsch --ignore-hydrogen FILE_A FILE_B".split() args = calculate_rmsd.parse_arguments(args_) assert args.reorder is False assert args.ignore_hydrogen is True assert args.rotation == "kabsch" def test_illegal_arguments() -> None: with pytest.raises(SystemExit): args = calculate_rmsd.parse_arguments( "--reorder --ignore-hydrogen --print filea fileb".split() ) print(args) with pytest.raises(SystemExit): args = calculate_rmsd.parse_arguments( "--print --ignore-hydrogen --use-reflections filea fileb".split() ) print(args) with pytest.raises(SystemExit): args = calculate_rmsd.parse_arguments("--rotation do-not-exists filea fileb".split()) print(args) with pytest.raises(SystemExit): args = calculate_rmsd.parse_arguments( "--reorder --reorder-method do-not-exists filea fileb".split() ) print(args) def test_illegal_reflection() -> None: args = [ "--rotation kabsch", "--use-reflections", "--print", "--ignore-hydrogen", "FILE_A", "FILE_B", ] with pytest.raises(SystemExit) as exception: _ = calculate_rmsd.parse_arguments(args) assert exception.type == SystemExit def test_illegal_rotation_method() -> None: args = ["--rotation NeverHeardOfThisMethod", "FILE_A", "FILE_B"] with pytest.raises(SystemExit) as exception: _ = calculate_rmsd.parse_arguments(args) assert exception.type == SystemExit def test_illegal_reorder_method() -> None: args = ["--reorder-method NotImplementedYet", "FILE_A", "FILE_B"] with pytest.raises(SystemExit) as exception: _ = calculate_rmsd.parse_arguments(args) assert exception.type == SystemExit
2,096
23.964286
93
py
rmsd
rmsd-master/tests/test_centroid.py
import numpy as np import rmsd as rmsdlib def test_centroid() -> None: a1 = np.array([-19.658, 17.18, 25.163], dtype=float) a2 = np.array([-20.573, 18.059, 25.88], dtype=float) a3 = np.array([-22.018, 17.551, 26.0], dtype=float) atms = np.asarray([a1, a2, a3]) centroid = rmsdlib.centroid(atms) assert 3 == len(centroid) np.testing.assert_array_almost_equal([-20.7496, 17.5966, 25.6810], centroid, decimal=3)
443
25.117647
91
py
rmsd
rmsd-master/tests/test_file_reading.py
import gzip from pathlib import Path import numpy as np import pytest from context import RESOURCE_PATH import rmsd as rmsdlib def test_get_coordinates_pdb_hetatm() -> None: filename = Path(RESOURCE_PATH) / "issue88" / "native.pdb" atoms, _ = rmsdlib.get_coordinates_pdb(filename) assert len(atoms) assert atoms[0] == "C" assert atoms[-1] == "C" def test_get_coordinates_pdb() -> None: filename = RESOURCE_PATH / "ci2_1.pdb" atoms, coords = rmsdlib.get_coordinates_pdb(filename) assert "N" == atoms[0] assert [-7.173, -13.891, -6.266] == coords[0].tolist() def test_get_coordinates_wrong() -> None: filename = RESOURCE_PATH / "ci2_1.pdb" with pytest.raises(ValueError): _, _ = rmsdlib.get_coordinates(filename, "qqq") def test_get_coordinates_xyz() -> None: filename = RESOURCE_PATH / "ethane.xyz" atoms, coords = rmsdlib.get_coordinates_xyz(filename) assert "C" == atoms[0] assert [-0.98353, 1.81095, -0.0314] == coords[0].tolist() def test_get_coordinates_xyz_bad() -> None: filename = RESOURCE_PATH / "bad_format.xyz" _, _ = rmsdlib.get_coordinates(filename, "xyz") def test_get_coordinates() -> None: filename = RESOURCE_PATH / "ethane.xyz" atoms, coords = rmsdlib.get_coordinates(filename, "xyz") assert "C" == atoms[0] assert [-0.98353, 1.81095, -0.0314] == coords[0].tolist() def test_get_coordinates_gzip(tmp_path: Path) -> None: filename = RESOURCE_PATH / "ci2_1.pdb" with open(filename, "r") as f: content = f.read() content_byte = content.encode() filename_gzip = tmp_path / "molecule.pdb.gz" with gzip.open(filename_gzip, "wb") as f: # type: ignore f.write(content_byte) # type: ignore atoms, coords = rmsdlib.get_coordinates( filename_gzip, "pdb", is_gzip=True, return_atoms_as_int=True ) assert 7 == atoms[0] assert [-7.173, -13.891, -6.266] == coords[0].tolist() def test_get_coordinates_gzip_pdb(tmp_path: Path) -> None: filename = RESOURCE_PATH / "ethane.xyz" with open(filename, "r") as f: content = f.read() content_byte = content.encode() filename_gzip = tmp_path / "ethane.xyz.gz" with gzip.open(filename_gzip, "wb") as f: # type: ignore f.write(content_byte) # type: ignore atoms, coords = rmsdlib.get_coordinates(filename_gzip, "xyz", is_gzip=True) assert "C" == atoms[0] assert [-0.98353, 1.81095, -0.0314] == coords[0].tolist() def test_rmsd_pdb() -> None: filename_1 = RESOURCE_PATH / "ci2_1.pdb" filename_2 = RESOURCE_PATH / "ci2_2.pdb" _, p_coord = rmsdlib.get_coordinates_pdb(filename_1) _, q_coord = rmsdlib.get_coordinates_pdb(filename_2) pure_rmsd = rmsdlib.rmsd(p_coord, q_coord) np.testing.assert_almost_equal(26.9750, pure_rmsd, decimal=3) def test_rmsd_xyz() -> None: filename_1 = RESOURCE_PATH / "ethane.xyz" filename_2 = RESOURCE_PATH / "ethane_mini.xyz" _, p_coord = rmsdlib.get_coordinates_xyz(filename_1) _, q_coord = rmsdlib.get_coordinates_xyz(filename_2) pure_rmsd = rmsdlib.rmsd(p_coord, q_coord) np.testing.assert_almost_equal(0.33512, pure_rmsd, decimal=3)
3,204
25.487603
79
py
rmsd
rmsd-master/tests/test_kabsch.py
import numpy as np from context import RESOURCE_PATH import rmsd as rmsdlib def test_kabash_algorith_rmsd() -> None: filename_1 = RESOURCE_PATH / "ci2_1.pdb" filename_2 = RESOURCE_PATH / "ci2_2.pdb" _, p_coord = rmsdlib.get_coordinates(filename_1, "pdb") _, q_coord = rmsdlib.get_coordinates(filename_2, "pdb") value = rmsdlib.kabsch_rmsd(p_coord, q_coord, translate=True) np.testing.assert_almost_equal(value, 11.7768, decimal=4) def test_kabash_algorith_pdb() -> None: filename_1 = RESOURCE_PATH / "ci2_1.pdb" filename_2 = RESOURCE_PATH / "ci2_2.pdb" _, p_coord = rmsdlib.get_coordinates_pdb(filename_1) _, q_coord = rmsdlib.get_coordinates_pdb(filename_2) rotation_matrix = rmsdlib.kabsch(p_coord, q_coord) np.testing.assert_array_almost_equal([-0.5124, 0.8565, 0.0608], rotation_matrix[0], decimal=3) def test_kabash_rotate_pdb() -> None: filename_1 = RESOURCE_PATH / "ci2_1.pdb" filename_2 = RESOURCE_PATH / "ci2_2.pdb" _, p_coord = rmsdlib.get_coordinates_pdb(filename_1) _, q_coord = rmsdlib.get_coordinates_pdb(filename_2) new_p_coord = rmsdlib.kabsch_rotate(p_coord, q_coord) np.testing.assert_array_almost_equal([10.6822, -2.8867, 12.6977], new_p_coord[0], decimal=3)
1,269
27.863636
98
py
rmsd
rmsd-master/tests/test_kabsch_weighted.py
import numpy as np from context import RESOURCE_PATH import rmsd as rmsdlib def test_kabash_fit_pdb() -> None: filename_p = RESOURCE_PATH / "ci2_1r+t.pdb" filename_q = RESOURCE_PATH / "ci2_1.pdb" _, p_coord = rmsdlib.get_coordinates_pdb(filename_p) _, q_coord = rmsdlib.get_coordinates_pdb(filename_q) new_p_coord = rmsdlib.kabsch_fit(p_coord, q_coord) np.testing.assert_array_almost_equal(q_coord[0], new_p_coord[0], decimal=2) def test_kabash_weighted_fit_pdb() -> None: filename_1 = RESOURCE_PATH / "ci2_12.pdb" filename_2 = RESOURCE_PATH / "ci2_2.pdb" _, p_coord = rmsdlib.get_coordinates_pdb(filename_1) _, q_coord = rmsdlib.get_coordinates_pdb(filename_2) weights = np.zeros(len(p_coord)) residue13_start = 200 residue24_start = 383 weights[residue13_start:residue24_start] = 1.0 new_p_coord = rmsdlib.kabsch_fit(p_coord, q_coord, weights) np.testing.assert_array_almost_equal(q_coord[300], new_p_coord[300], decimal=2)
1,005
26.189189
83
py
rmsd
rmsd-master/tests/test_main.py
import copy import numpy as np import pytest from context import RESOURCE_PATH, call_main import rmsd as rmsdlib def test_print_reflection_reorder() -> None: # Test issue 78 filename_a = RESOURCE_PATH / "issue78" / "a.xyz" filename_b = RESOURCE_PATH / "issue78" / "b.xyz" # Function call atoms_a, coord_a = rmsdlib.get_coordinates_xyz(filename_a, return_atoms_as_int=True) atoms_b, coord_b = rmsdlib.get_coordinates_xyz(filename_b, return_atoms_as_int=True) # re-center molecules coord_a -= rmsdlib.centroid(coord_a) coord_b -= rmsdlib.centroid(coord_b) rmsd_method = rmsdlib.kabsch_rmsd reorder_method = rmsdlib.reorder_hungarian result_rmsd, q_swap, q_reflection, q_review = rmsdlib.check_reflections( atoms_a, atoms_b, coord_a, coord_b, reorder_method=reorder_method, rmsd_method=rmsd_method, ) print(result_rmsd) print(q_swap) print(q_reflection) print(q_review) # Apply the swap, reflection and review tmp_coord = copy.deepcopy(coord_b) tmp_coord = tmp_coord[:, q_swap] tmp_coord = np.dot(tmp_coord, np.diag(q_reflection)) tmp_coord -= rmsdlib.centroid(tmp_coord) tmp_coord = tmp_coord[q_review] tmp_coord = rmsdlib.kabsch_rotate(tmp_coord, coord_a) rmsd_ = rmsdlib.rmsd(coord_a, tmp_coord) print(rmsd_) print(tmp_coord) # Main call rmsd value args = f"--use-reflections --reorder {filename_a} {filename_b}" stdout = call_main(args.split()) value = float(stdout[-1]) print(value) assert value is not None np.testing.assert_almost_equal(result_rmsd, value) # Main call print, check rmsd is still the same # Note, that --print is translating b to a center args = f"--use-reflections --reorder --print {filename_a} {filename_b}" stdout = call_main(args.split()) _, coord = rmsdlib.get_coordinates_xyz_lines(stdout) coord -= rmsdlib.centroid(coord) # fix translation print(coord) rmsd_check1 = rmsdlib.kabsch_rmsd(coord, coord_a) rmsd_check2 = rmsdlib.rmsd(coord, coord_a) print(rmsd_check1) print(rmsd_check2) np.testing.assert_almost_equal(rmsd_check2, rmsd_check1) np.testing.assert_almost_equal(rmsd_check2, result_rmsd) def test_bad_different_molcules() -> None: filename_a = RESOURCE_PATH / "ethane.xyz" filename_b = RESOURCE_PATH / "water.xyz" args = f"{filename_a} {filename_b}" with pytest.raises(SystemExit): rmsdlib.main(args.split()) def test_bad_different_order() -> None: filename_a = RESOURCE_PATH / "CHEMBL3039407.xyz" filename_b = RESOURCE_PATH / "CHEMBL3039407_order.xyz" args = f"{filename_a} {filename_b}" with pytest.raises(SystemExit): rmsdlib.main(args.split()) def test_rotation_methods() -> None: filename_a = RESOURCE_PATH / "ethane_translate.xyz" filename_b = RESOURCE_PATH / "ethane.xyz" rmsdlib.main(f"{filename_a} {filename_b} --rotation quaternion".split()) rmsdlib.main(f"{filename_a} {filename_b} --rotation none".split()) def test_reorder_methods() -> None: filename_a = RESOURCE_PATH / "CHEMBL3039407.xyz" filename_b = RESOURCE_PATH / "CHEMBL3039407_order.xyz" methods = ["hungarian", "inertia-hungarian", "distance"] for method in methods: rmsdlib.main(f"--reorder --reorder-method {method} {filename_a} {filename_b}".split()) def test_reflections() -> None: filename_a = RESOURCE_PATH / "CHEMBL3039407.xyz" filename_b = RESOURCE_PATH / "CHEMBL3039407.xyz" rmsdlib.main(f"--use-reflections {filename_a} {filename_b}".split()) rmsdlib.main(f"--use-reflections-keep-stereo {filename_a} {filename_b}".split()) def test_ignore() -> None: filename_a = RESOURCE_PATH / "CHEMBL3039407.xyz" filename_b = RESOURCE_PATH / "CHEMBL3039407.xyz" rmsdlib.main(f"--no-hydrogen {filename_a} {filename_b}".split()) rmsdlib.main(f"{filename_a} {filename_b} --remove-idx 0 5".split()) rmsdlib.main(f"{filename_a} {filename_b} --add-idx 0 1 2 3 4".split())
4,079
28.352518
94
py
rmsd
rmsd-master/tests/test_quaternion.py
import numpy as np from context import RESOURCE_PATH import rmsd as rmsdlib def test_quaternion_rmsd_pdb() -> None: filename_p = RESOURCE_PATH / "ci2_1.pdb" filename_q = RESOURCE_PATH / "ci2_2.pdb" _, p_coord = rmsdlib.get_coordinates_pdb(filename_p) _, q_coord = rmsdlib.get_coordinates_pdb(filename_q) p_center = rmsdlib.centroid(p_coord) q_center = rmsdlib.centroid(q_coord) p_coord -= p_center q_coord -= q_center result = rmsdlib.quaternion_rmsd(p_coord, q_coord) np.testing.assert_almost_equal(11.7768, result, decimal=3) def test_quaternion_rotate_pdb() -> None: filename_p = RESOURCE_PATH / "ci2_1.pdb" filename_q = RESOURCE_PATH / "ci2_2.pdb" _, p_coord = rmsdlib.get_coordinates_pdb(filename_p) _, q_coord = rmsdlib.get_coordinates_pdb(filename_q) new_p_coord = rmsdlib.quaternion_rotate(p_coord, q_coord) np.testing.assert_array_almost_equal([-0.5124, 0.8565, 0.0608], new_p_coord[0], decimal=3) def test_quaternion_transform() -> None: r = np.array([-0.31019, -0.59291, 0.63612, -0.38415]) U = rmsdlib.quaternion_transform(r) np.testing.assert_array_almost_equal([-0.5124, 0.8565, 0.0608], U[0], decimal=3) def test_makeQ() -> None: r = [-0.31019, -0.59291, 0.63612, -0.38415] Q_r = rmsdlib.makeQ(*r) np.testing.assert_array_almost_equal([-0.3841, -0.6361, -0.5929, -0.3101], Q_r[0], decimal=3) def test_makeW() -> None: r = [-0.31019, -0.59291, 0.63612, -0.38415] Wt_r = rmsdlib.makeW(*r) np.testing.assert_array_almost_equal([-0.3841, 0.6361, 0.5929, -0.3101], Wt_r[0], decimal=3)
1,620
26.474576
97
py
rmsd
rmsd-master/tests/test_reflections.py
import copy import numpy as np from context import RESOURCE_PATH import rmsd as rmsdlib def test_reflections() -> None: atoms = np.array(["C", "H", "H", "H", "F"]) p_coord = np.array( [ [-0.000000, -0.000000, -0.000000], [1.109398, -0.000000, 0.000000], [-0.3697920, -0.7362220, -0.7429600], [-0.3698020, 1.011538, -0.2661100], [-0.3698020, -0.2753120, 1.009070], ] ) q_coord = copy.deepcopy(p_coord) # insert reflection # TODO Insert a rotation on q q_coord[:, [0, 2]] = q_coord[:, [2, 0]] min_rmsd, _, _, _ = rmsdlib.check_reflections( atoms, atoms, p_coord, q_coord, reorder_method=None ) assert np.isclose(min_rmsd, 0.0, atol=1e-6) def test_reflections_norotation() -> None: atoms = np.array(["C", "H", "H", "H", "F"]) p_coord = np.array( [ [-0.000000, -0.000000, -0.000000], [1.109398, -0.000000, 0.000000], [-0.3697920, -0.7362220, -0.7429600], [-0.3698020, 1.011538, -0.2661100], [-0.3698020, -0.2753120, 1.009070], ] ) q_coord = copy.deepcopy(p_coord) # Insert reflection q_coord[:, [0, 2]] = q_coord[:, [2, 0]] min_rmsd, _, _, _ = rmsdlib.check_reflections( atoms, atoms, p_coord, q_coord, reorder_method=None, ) assert np.isclose(min_rmsd, 0.0, atol=1e-6) def test_reflections_reorder() -> None: p_atoms = np.array(["C", "H", "H", "H", "F"]) p_coord = np.array( [ [-0.000000, -0.000000, -0.000000], [1.109398, -0.000000, 0.000000], [-0.3697920, -0.7362220, -0.7429600], [-0.3698020, 1.011538, -0.2661100], [-0.3698020, -0.2753120, 1.009070], ] ) # random reflection q_coord = copy.deepcopy(p_coord) q_coord[:, [0, 2]] = q_coord[:, [2, 0]] # random order # review = list(range(len(atoms))) review = [1, 4, 2, 0, 3] q_coord = q_coord[review] q_atoms = p_atoms[review] min_rmsd, _, _, _ = rmsdlib.check_reflections( p_atoms, q_atoms, p_coord, q_coord, reorder_method=rmsdlib.reorder_hungarian ) assert np.isclose(min_rmsd, 0.0, atol=1e-6) def test_reflections_keep_stereo() -> None: atoms = np.array(["C", "H", "H", "H", "F"]) p_coord = np.array( [ [-0.000000, -0.000000, -0.000000], [1.109398, -0.000000, 0.000000], [-0.3697920, -0.7362220, -0.7429600], [-0.3698020, 1.011538, -0.2661100], [-0.3698020, -0.2753120, 1.009070], ] ) q_coord = copy.deepcopy(p_coord) # swap [2,1,0]: prepare enantiomer coordinates (which is named as q_coord) # of p_coord q_coord[:, [0, 2]] = q_coord[:, [2, 0]] # If keep_stereo is off, enantiomer coordinates of q_coord are considered, # resulting into identical coordinates of p_coord. min_rmsd, _, _, _ = rmsdlib.check_reflections( atoms, atoms, p_coord, q_coord, reorder_method=None, keep_stereo=False ) # the enantiomer of the enantiomer of the original molecule has zero RMSD # with the original molecule. assert np.isclose(min_rmsd, 0.0, atol=1e-6) # No enantiomer coordinates, non-zero rmsdlib. min_rmsd, _, _, _ = rmsdlib.check_reflections( atoms, atoms, p_coord, q_coord, reorder_method=None, keep_stereo=True ) assert np.isclose(min_rmsd, 1.1457797, atol=1e-6) def test_reflection_issue_78(): """ Issue 78 Using the --use-reflections option with the calculate_rmsd script affects the computed rmsd, but it doesn't seem to affect the output structure when -p is used too Moreover, with the latest pip version, --use-reflections does almost nothing at all """ xyz_a = RESOURCE_PATH / "ethane-1-2-diolate_a.xyz" xyz_b = RESOURCE_PATH / "ethane-1-2-diolate_b.xyz" atoms_a, coordinates_a = rmsdlib.get_coordinates_xyz(xyz_a) atoms_b, coordinates_b = rmsdlib.get_coordinates_xyz(xyz_b) coordinates_a -= rmsdlib.centroid(coordinates_a) coordinates_b -= rmsdlib.centroid(coordinates_b) reorder_method = None rmsd_method = rmsdlib.kabsch_rmsd print(np.sum(coordinates_a)) print(np.sum(coordinates_b)) result_rmsd = rmsdlib.kabsch_rmsd( coordinates_a, coordinates_b, ) print(result_rmsd) result_rmsd, _, _, q_review = rmsdlib.check_reflections( atoms_a, atoms_b, coordinates_a, coordinates_b, reorder_method=reorder_method, rmsd_method=rmsd_method, ) print(result_rmsd) return
4,710
24.884615
84
py
rmsd
rmsd-master/tests/test_reorder.py
import copy import numpy as np import rmsd as rmsdlib def test_reorder_distance() -> None: N = 5 atoms = np.array(["H"] * N) p_coord = np.arange(N * 3) p_coord = p_coord.reshape((5, 3)) q_coord = copy.deepcopy(p_coord) np.random.seed(6) np.random.shuffle(q_coord) review = rmsdlib.reorder_hungarian(atoms, atoms, p_coord, q_coord) assert p_coord.tolist() == q_coord[review].tolist() def test_reorder_brute() -> None: N = 5 atoms = np.array(["H"] * N) p_coord = np.arange(N * 3) p_coord = p_coord.reshape((N, 3)) q_coord = copy.deepcopy(p_coord) np.random.seed(6) np.random.shuffle(q_coord) review = rmsdlib.reorder_brute(atoms, atoms, p_coord, q_coord) assert p_coord.tolist() == q_coord[review].tolist() def test_reorder_brute_ch() -> None: N = 6 p_atoms_str = ["C"] * 3 + ["H"] * 3 p_atoms_int = [rmsdlib.int_atom(atom) for atom in p_atoms_str] p_atoms = np.array(p_atoms_int) p_coord = np.arange(N * 3) p_coord = p_coord.reshape((N, 3)) # random index np.random.seed(6) idx = np.arange(N, dtype=int) np.random.shuffle(idx) q_coord = copy.deepcopy(p_coord) q_atoms = copy.deepcopy(p_atoms) q_coord = q_coord[idx] q_atoms = q_atoms[idx] review = rmsdlib.reorder_brute(p_atoms, q_atoms, p_coord, q_coord) assert p_coord.tolist() == q_coord[review].tolist() assert p_atoms.tolist() == q_atoms[review].tolist() def test_reorder_hungarian() -> None: N = 5 atoms = np.array(["H"] * N) p_coord = np.arange(N * 3) p_coord = p_coord.reshape((5, 3)) q_coord = copy.deepcopy(p_coord) np.random.seed(6) np.random.shuffle(q_coord) review = rmsdlib.reorder_distance(atoms, atoms, p_coord, q_coord) assert p_coord.tolist() == q_coord[review].tolist() def test_reorder_inertia_hungarian() -> None: # coordinates of scrambled and rotated butane atoms = np.array(["C", "C", "C", "C", "H", "H", "H", "H", "H", "H", "H", "H", "H", "H"]) atoms_ = [rmsdlib.int_atom(atom) for atom in atoms] atoms = np.array(atoms_) p_coord = np.array( [ [2.142e00, 1.395e00, -8.932e00], [3.631e00, 1.416e00, -8.537e00], [4.203e00, -1.200e-02, -8.612e00], [5.691e00, 9.000e-03, -8.218e00], [1.604e00, 7.600e-01, -8.260e00], [1.745e00, 2.388e00, -8.880e00], [2.043e00, 1.024e00, -9.930e00], [4.169e00, 2.051e00, -9.210e00], [3.731e00, 1.788e00, -7.539e00], [3.665e00, -6.470e-01, -7.940e00], [4.104e00, -3.840e-01, -9.610e00], [6.088e00, -9.830e-01, -8.270e00], [5.791e00, 3.810e-01, -7.220e00], [6.230e00, 6.440e-01, -8.890e00], ] ) q_coord = np.array( [ [6.71454, -5.53848, -3.50851], [6.95865, -6.22697, -2.15264], [8.16747, -5.57632, -1.45606], [5.50518, -6.19016, -4.20589], [5.33617, -5.71137, -5.14853], [7.58263, -5.64795, -4.12498], [6.51851, -4.49883, -3.35011], [6.09092, -6.11832, -1.53660], [5.70232, -7.22908, -4.36475], [7.15558, -7.26640, -2.31068], [8.33668, -6.05459, -0.51425], [7.97144, -4.53667, -1.29765], [4.63745, -6.08152, -3.58986], [9.03610, -5.68475, -2.07173], ] ) p_coord -= rmsdlib.centroid(p_coord) q_coord -= rmsdlib.centroid(q_coord) review = rmsdlib.reorder_inertia_hungarian(atoms, atoms, p_coord, q_coord) result_rmsd = rmsdlib.kabsch_rmsd(p_coord, q_coord[review]) np.testing.assert_almost_equal(0, result_rmsd, decimal=2)
3,753
27.439394
92
py
rmsd
rmsd-master/tests/test_reorder_inertia.py
import numpy as np import rmsd as rmsdlib def test_reorder_inertia_hungarian() -> None: # coordinates of scrambled and rotated butane atoms = np.array(["C", "C", "C", "C", "H", "H", "H", "H", "H", "H", "H", "H", "H", "H"]) atoms_ = [rmsdlib.int_atom(atom) for atom in atoms] atoms = np.array(atoms_) p_coord = np.array( [ [2.142e00, 1.395e00, -8.932e00], [3.631e00, 1.416e00, -8.537e00], [4.203e00, -1.200e-02, -8.612e00], [5.691e00, 9.000e-03, -8.218e00], [1.604e00, 7.600e-01, -8.260e00], [1.745e00, 2.388e00, -8.880e00], [2.043e00, 1.024e00, -9.930e00], [4.169e00, 2.051e00, -9.210e00], [3.731e00, 1.788e00, -7.539e00], [3.665e00, -6.470e-01, -7.940e00], [4.104e00, -3.840e-01, -9.610e00], [6.088e00, -9.830e-01, -8.270e00], [5.791e00, 3.810e-01, -7.220e00], [6.230e00, 6.440e-01, -8.890e00], ] ) q_coord = np.array( [ [6.71454, -5.53848, -3.50851], [6.95865, -6.22697, -2.15264], [8.16747, -5.57632, -1.45606], [5.50518, -6.19016, -4.20589], [5.33617, -5.71137, -5.14853], [7.58263, -5.64795, -4.12498], [6.51851, -4.49883, -3.35011], [6.09092, -6.11832, -1.53660], [5.70232, -7.22908, -4.36475], [7.15558, -7.26640, -2.31068], [8.33668, -6.05459, -0.51425], [7.97144, -4.53667, -1.29765], [4.63745, -6.08152, -3.58986], [9.03610, -5.68475, -2.07173], ] ) p_coord -= rmsdlib.centroid(p_coord) q_coord -= rmsdlib.centroid(q_coord) review = rmsdlib.reorder_inertia_hungarian(atoms, atoms, p_coord, q_coord) result_rmsd = rmsdlib.kabsch_rmsd(p_coord, q_coord[review]) np.testing.assert_almost_equal(0, result_rmsd, decimal=2)
1,956
32.741379
92
py
rmsd
rmsd-master/tests/test_reorder_print.py
import numpy as np from context import RESOURCE_PATH, call_main import rmsd as rmsdlib from rmsd import get_coordinates_xyz, get_coordinates_xyz_lines def test_reorder_print_and_rmsd() -> None: # Issue 93, problem with printed structure after reorder. # - Calculate rmsd with --reorder (structure a and b) # - Calculate --print and --reorder to structure c.xyz # - Calculate normal rmsd a.xyz and c.xyz filename_a = RESOURCE_PATH / "issue93" / "a.xyz" filename_b = RESOURCE_PATH / "issue93" / "b.xyz" # Get reorder rmsd args = ["--reorder", f"{filename_a}", f"{filename_b}"] stdout = call_main(args) rmsd_ab = float(stdout[-1]) print(rmsd_ab) # Get printed structure stdout = call_main(args + ["--print"]) atoms_a, coord_a = get_coordinates_xyz(filename_a) atoms_c, coord_c = get_coordinates_xyz_lines(stdout) print(coord_a) print(atoms_a) print(coord_c) print(atoms_c) rmsd_ac = rmsdlib.rmsd(coord_a, coord_c) print(rmsd_ac) np.testing.assert_almost_equal(rmsd_ab, rmsd_ac, decimal=8)
1,086
26.175
63
py
rmsd
rmsd-master/tests/test_reorder_qml.py
import copy import numpy as np import pytest from context import RESOURCE_PATH import rmsd as rmsdlib qml = pytest.importorskip("qml") def test_reorder_qml() -> None: filename_1 = RESOURCE_PATH / "CHEMBL3039407.xyz" p_atoms, p_coord = rmsdlib.get_coordinates_xyz(filename_1, return_atoms_as_int=True) # Reorder atoms n_atoms = len(p_atoms) random_reorder = np.arange(n_atoms, dtype=int) np.random.seed(5) np.random.shuffle(random_reorder) q_atoms = copy.deepcopy(p_atoms) q_coord = copy.deepcopy(p_coord) q_atoms = q_atoms[random_reorder] q_coord = q_coord[random_reorder] # Mess up the distance matrix by rotating the molecule theta = 180.0 rotation_y = np.array( [ [np.cos(theta), 0, np.sin(theta)], [0, 1, 0], [-np.sin(theta), 0, np.cos(theta)], ] ) q_coord = np.dot(q_coord, rotation_y) # Reorder with standard hungarian, this will fail reorder and give large # RMSD view_dist = rmsdlib.reorder_hungarian(p_atoms, q_atoms, p_coord, q_coord) q_atoms_dist = q_atoms[view_dist] q_coord_dist = q_coord[view_dist] _rmsd_dist = rmsdlib.kabsch_rmsd(p_coord, q_coord_dist) assert q_atoms_dist.tolist() == p_atoms.tolist() assert _rmsd_dist > 3.0 # Reorder based in chemical similarity view = rmsdlib.reorder_similarity(p_atoms, q_atoms, p_coord, q_coord) q_atoms = q_atoms[view] q_coord = q_coord[view] # Calculate new RMSD with correct atom order _rmsd = rmsdlib.kabsch_rmsd(p_coord, q_coord) # Assert correct atom order assert q_atoms.tolist() == p_atoms.tolist() # Assert this is the same molecule pytest.approx(0.0) == _rmsd def test_reorder_qml_distmat() -> None: filename_1 = RESOURCE_PATH / "CHEMBL3039407.xyz" p_atoms, p_coord = rmsdlib.get_coordinates_xyz(filename_1, return_atoms_as_int=True) # Reorder atoms n_atoms = len(p_atoms) random_reorder = np.arange(n_atoms, dtype=int) np.random.seed(5) np.random.shuffle(random_reorder) q_atoms = copy.deepcopy(p_atoms) q_coord = copy.deepcopy(p_coord) q_atoms = q_atoms[random_reorder] q_coord = q_coord[random_reorder] # Mess up the distance matrix by rotating the molecule theta = 180.0 rotation_y = np.array( [ [np.cos(theta), 0, np.sin(theta)], [0, 1, 0], [-np.sin(theta), 0, np.cos(theta)], ] ) q_coord = np.dot(q_coord, rotation_y) # Reorder based in chemical similarity view = rmsdlib.reorder_similarity(p_atoms, q_atoms, p_coord, q_coord, use_kernel=False) q_atoms = q_atoms[view] q_coord = q_coord[view] # Calculate new RMSD with correct atom order _rmsd = rmsdlib.kabsch_rmsd(p_coord, q_coord) # Assert correct atom order assert q_atoms.tolist() == p_atoms.tolist() # Assert this is the same molecule pytest.approx(0.0) == _rmsd
2,962
26.691589
91
py
rmsd
rmsd-master/tests/test_rmsd.py
0
0
0
py
FIt-SNE
FIt-SNE-master/README.md
# FFT-accelerated Interpolation-based t-SNE (FIt-SNE) ## Introduction t-Stochastic Neighborhood Embedding ([t-SNE](https://lvdmaaten.github.io/tsne/)) is a highly successful method for dimensionality reduction and visualization of high dimensional datasets. A popular [implementation](https://github.com/lvdmaaten/bhtsne) of t-SNE uses the Barnes-Hut algorithm to approximate the gradient at each iteration of gradient descent. We accelerated this implementation as follows: * Computation of the N-body Simulation: Instead of approximating the N-body simulation using Barnes-Hut, we interpolate onto an equispaced grid and use FFT to perform the convolution, dramatically reducing the time to compute the gradient at each iteration of gradient descent. See the [this](http://gauss.math.yale.edu/~gcl22/blog/numerics/low-rank/t-sne/2018/01/11/low-rank-kernels.html) post for some intuition on how it works. * Computation of Input Similarities: Instead of computing nearest neighbors using vantage-point trees, we approximate nearest neighbors using the [Annoy](https://github.com/spotify/annoy) library. The neighbor lookups are multithreaded to take advantage of machines with multiple cores. Using "near" neighbors as opposed to strictly "nearest" neighbors is faster, but also has a smoothing effect, which can be useful for embedding some datasets (see [Linderman et al. (2017)](https://arxiv.org/abs/1711.04712)). If subtle detail is required (e.g. in identifying small clusters), then use vantage-point trees (which is also multithreaded in this implementation). Check out our [paper](https://www.nature.com/articles/s41592-018-0308-4) or [preprint](https://arxiv.org/abs/1712.09005) for more details and some benchmarks. ## Features Additionally, this implementation includes the following features: * Early exaggeration: In [Linderman and Steinerberger (2018)](https://epubs.siam.org/doi/abs/10.1137/18M1216134), we showed that appropriately choosing the early exaggeration coefficient can lead to improved embedding of swissrolls and other synthetic datasets. Early exaggeration is built into all t-SNE implementations; here we highlight its importance as a parameter. * Late exaggeration: Increasing the exaggeration coefficient late in the optimization process can improve separation of the clusters. [Kobak and Berens (2019)](https://www.nature.com/articles/s41467-019-13056-x) suggest starting late exaggeration immediately following early exaggeration. * Initialization: Custom initialization can be provided from Python/Matlab/R. As suggested by [Kobak and Berens (2019)](https://www.nature.com/articles/s41467-019-13056-x), initializing t-SNE with the first two principal components (scaled to have standard deviation 0.0001) results in an embedding which often preserves the global structure more effectively than the default random normalization. See there for other initialisation tricks. * Variable degrees of freedom: [Kobak et al. (2019)](https://ecmlpkdd2019.org/downloads/paper/327.pdf) show that decreasing the degree of freedom (df) of the t-distribution (resulting in heavier tails) reveals fine structure that is not visible in standard t-SNE. * Perplexity combination: The perplexity parameter determines the width of the Gaussian kernel, such that small perplexity values uncover local structure while larger values reveal global structure. [Kobak and Berens (2019)](https://www.nature.com/articles/s41467-019-13056-x) show that using combination of several perplexity values, resulting in a multi-scale embedding, can be useful. * All optimisation parameters can be controlled from Python/Matlab/R. For example, [Belkina et al. (2019)](https://www.nature.com/articles/s41467-019-13055-y) highlight the importance of increasing the learning rate when embedding large data sets. ## Installation R, Matlab, and Python wrappers are `fast_tsne.R`, `fast_tsne.m`, and `fast_tsne.py` respectively. Each of these wrappers can be used after installing FFTW and compiling the C++ code, as below. [Gioele La Manno](https://twitter.com/GioeleLaManno) implemented a Python (Cython) wrapper, which is available on PyPI [here](https://pypi.python.org/pypi/fitsne). **Note:** If you update to a new version of FIt-SNE using `git pull`, be sure to recompile. ### OSX and Linux The only prerequisite is [FFTW](http://www.fftw.org/), which can be downloaded and installed from the website. Then, from the root directory compile the code as: ```bash g++ -std=c++11 -O3 src/sptree.cpp src/tsne.cpp src/nbodyfft.cpp -o bin/fast_tsne -pthread -lfftw3 -lm -Wno-address-of-packed-member ``` See [here](https://github.com/KlugerLab/FIt-SNE/issues/35) for instructions in case one does not have `sudo` rights (one can install `FFTW` in the home directory and provide its path to `g++`). Check out `examples/` for usage. The [Python demo notebook](https://github.com/KlugerLab/FIt-SNE/blob/master/examples/test.ipynb) walks one through the most of the available options using the MNIST data set. ### Windows A Windows binary is available [here](https://github.com/KlugerLab/FIt-SNE/releases/download/v1.2.1/FItSNE-Windows-1.2.1.zip). Please extract to the `bin/` folder, and you should be all set. If you would like to compile it yourself see below. The code has been currently tested with MS Visual Studio 2015 (i.e., MS Visual Studio Version 14). 1. First open the provided FItSNE solution (FItSNE.sln) using MS Visual Studio and build the Release configuration. 2. Copy the binary file ( e.g. `x64/Release/FItSNE.exe`) generated by the build process to the `bin/` folder 3. For Windows, we have added all dependencies, including the [FFTW library](http://www.fftw.org/), which is distributed under the GNU General Public License. For the binary to find the FFTW DLLs, you need to either add `src/winlibs/fftw/` to your PATH, or to copy the DLLs into the `bin/` directory. As of this commit, only the R wrapper properly calls the Windows executable. The Python and Matlab wrappers can be trivially changed to call it (just changing `bin/fast_tsne` to `bin/FItSNE.exe` in the code), and will be changed in future commits. Many thanks to [Josef Spidlen](https://github.com/jspidlen) for this Windows implementation! ## Acknowledgements and References We are grateful for members of the community who have [contributed](https://github.com/KlugerLab/FIt-SNE/graphs/contributors) to improving FIt-SNE, especially [Dmitry Kobak](https://github.com/dkobak), [Pavlin Poličar](https://github.com/pavlin-policar), and [Josef Spidlen](https://github.com/jspidlen). If you use FIt-SNE, please cite: George C. Linderman, Manas Rachh, Jeremy G. Hoskins, Stefan Steinerberger, Yuval Kluger. (2019). Fast interpolation-based t-SNE for improved visualization of single-cell RNA-seq data. Nature Methods. ([link](https://www.nature.com/articles/s41592-018-0308-4)) Our implementation is derived from the Barnes-Hut implementation: Laurens van der Maaten (2014). Accelerating t-SNE using tree-based algorithms. Journal of Machine Learning Research, 15(1):3221–3245. ([link](https://dl.acm.org/citation.cfm?id=2627435.2697068))
7,149
118.166667
662
md
FIt-SNE
FIt-SNE-master/fast_tsne.m
function [mappedX, costs, initialError] = fast_tsne(X, opts) %FAST_TSNE Runs the C++ implementation of FMM t-SNE % % mappedX = fast_tsne(X, opts, initial_data) % X - Input dataset, rows are observations and columns are % variables % opts - a struct with the following possible parameters % opts.no_dims - dimensionality of the embedding % Default 2. % opts.perplexity - perplexity is used to determine the % bandwidth of the Gaussian kernel in the input % space. Default 30. % opts.theta - Set to 0 for exact. If non-zero, then will use either % Barnes Hut or FIt-SNE based on opts.nbody_algo. If Barnes Hut, then % this determins the accuracy of BH approximation. % Default 0.5. % opts.max_iter - Number of iterations of t-SNE to run. % Default 750. % opts.nbody_algo - if theta is nonzero, this determins whether to % use FIt-SNE or Barnes Hut approximation. Default is FIt-SNE. % set to be 'bh' for Barnes Hut % opts.knn_algo - use vp-trees (as in bhtsne) or approximate nearest neighbors (default). % set to be 'vptree' for vp-trees % opts.early_exag_coeff - coefficient for early exaggeration % (>1). Default 12. % opts.stop_early_exag_iter - When to switch off early % exaggeration. % Default 250. % opts.start_late_exag_iter - When to start late exaggeration. % 'auto' means that late exaggeration is not used, unless % late_exag_coeff>0. In that case, start_late_exag_iter is % set to stop_early_exag_iter. Otherwise, set to equal the % iteration at which late exaggeration should begin. % Default: 'auto' % opts.start_late_exag_iter - When to start late % exaggeration. set to -1 to not use late exaggeration % Default -1. % opts.late_exag_coeff - Late exaggeration coefficient. % Set to -1 to not use late exaggeration. % Default -1 % opts.learning_rate - Set to desired learning rate or 'auto', % which sets learning rate to N/early_exag_coeff where % N is the sample size, or to 200 if N/early_exag_coeff % < 200. % Default 'auto' % opts.max_step_norm - Maximum distance that a point is % allowed to move on one iteration. Larger steps are clipped % to this value. This prevents possible instabilities during % gradient descent. Set to -1 to switch it off. % Default: 5 % opts.no_momentum_during_exag - Set to 0 to use momentum % and other optimization tricks. 1 to do plain,vanilla % gradient descent (useful for testing large exaggeration % coefficients) % opts.nterms - If using FIt-SNE, this is the number of % interpolation points per sub-interval % opts.intervals_per_integer - See opts.min_num_intervals % opts.min_num_intervals - Let maxloc = ceil(max(max(X))) % and minloc = floor(min(min(X))). i.e. the points are in % a [minloc]^no_dims by [maxloc]^no_dims interval/square. % The number of intervals in each dimension is either % opts.min_num_intervals or ceil((maxloc - % minloc)/opts.intervals_per_integer), whichever is % larger. opts.min_num_intervals must be an integer >0, % and opts.intervals_per_integer must be >0. Default: % opts.min_num_intervals=50, opts.intervals_per_integer = % 1 % % opts.sigma - Fixed sigma value to use when perplexity==-1 % Default -1 (None) % opts.K - Number of nearest neighbours to get when using fixed sigma % Default -30 (None) % % opts.initialization - 'pca', 'random', or N x no_dims array % to intialize the solution % Default: 'pca' % % opts.load_affinities - can be 'load', 'save', or 'none' (default) % If 'save', input similarities are saved into a file. % If 'load', input similarities are loaded from a file and not computed % % opts.perplexity_list - if perplexity==0 then perplexity % combination will be used with values taken from % perplexity_list. Default: [] % opts.df - Degree of freedom of t-distribution, must be greater than 0. % Values smaller than 1 correspond to heavier tails, which can often % resolve substructure in the embedding. See Kobak et al. (2019) for % details. Default is 1.0 % Runs the C++ implementation of fast t-SNE using either the IFt-SNE % implementation or Barnes Hut % Copyright (c) 2014, Laurens van der Maaten (Delft University of Technology) % All rights reserved. % % Redistribution and use in source and binary forms, with or without % modification, are permitted provided that the following conditions are met: % 1. Redistributions of source code must retain the above copyright % notice, this list of conditions and the following disclaimer. % 2. Redistributions in binary form must reproduce the above copyright % notice, this list of conditions and the following disclaimer in the % documentation and/or other materials provided with the distribution. % 3. All advertising materials mentioning features or use of this software % must display the following acknowledgement: % This product includes software developed by the Delft University of Technology. % 4. Neither the name of the Delft University of Technology nor the names of % its contributors may be used to endorse or promote products derived from % this software without specific prior written permission. % % THIS SOFTWARE IS PROVIDED BY LAURENS VAN DER MAATEN ''AS IS'' AND ANY EXPRESS % OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES % OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO % EVENT SHALL LAURENS VAN DER MAATEN BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, % SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, % PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR % BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN % CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING % IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY % OF SUCH DAMAGE. version_number = '1.2.1'; % default parameters and flags p.perplexity = 30; p.no_dims = 2; p.theta = .5; p.stop_early_exag_iter = 250; % stop_lying_iter p.mom_switch_iter = 250; p.momentum = .5; p.final_momentum = .8; p.learning_rate = 'auto'; p.max_step_norm = 5; p.max_iter = 750; p.early_exag_coeff = 12; p.start_late_exag_iter = 'auto'; p.late_exag_coeff = -1; p.rand_seed = -1; p.nbody_algo = 2; p.knn_algo = 1; p.K = -1; p.sigma = -30; p.no_momentum_during_exag = 0; p.n_trees = 50; p.perplexity_list = []; p.nterms = 3; p.intervals_per_integer = 1; p.min_num_intervals = 50; p.nthreads = 0; p.df = 1; p.search_k = []; p.initialization = 'auto'; p.load_affinities = 0; if nargin == 2 % options provided assert(isstruct(opts),'2nd argument must be a structure') % copy over user-supplied parameters and options fn = fieldnames(p); for i = 1:length(fn) if isfield(opts,fn{i}) p.(fn{i}) = opts.(fn{i}); end end end if strcmpi(p.learning_rate,'auto') p.learning_rate = max(200, size(X,1)/p.early_exag_coeff) end if strcmpi(p.start_late_exag_iter,'auto') if p.late_exag_coeff > 0 p.start_late_exag_iter = p.stop_early_exag_iter else p.start_late_exag_iter = -1 end end if strcmpi(p.initialization,'auto') if p.rand_seed>0 rng(p.rand_seed) end X_c = mean(X ,1); X_c = bsxfun(@minus,X,X_c); p.no_dims = 2 [U, S,V ] = svds(X_c, p.no_dims); PCs = U * S; p.initialization = 0.0001*(PCs/std(PCs(:,1))) elseif strcmpi(p.initialization,'random') p.initialization = NaN; end % parse some optional text labels if strcmpi(p.nbody_algo,'bh') p.nbody_algo = 1; end if strcmpi(p.knn_algo,'vptree') p.knn_algo = 2; end if isempty(p.search_k) if p.perplexity > 0 p.search_k = 3*p.perplexity*p.n_trees; elseif p.perplexity == 0 p.search_k = 3 * max(p.perplexity_list) * p.n_trees; else p.search_k = 3*p.K*p.n_trees; end end if p.load_affinities == 'load' p.load_affinities = 1; elseif p.load_affinities == 'save' p.load_affinities = 2; else p.load_affinities = 0; end X = double(X); tsne_path = which('fast_tsne'); tsne_path = strcat(tsne_path(1:end-11), 'bin') % Compile t-SNE C code if(~exist(fullfile(tsne_path,'./fast_tsne'),'file') && isunix) system(sprintf('g++ -std=c++11 -O3 src/sptree.cpp src/tsne.cpp src/nbodyfft.cpp -o bin/fast_tsne -pthread -lfftw3 -lm')); end % Compile t-SNE C code on Windows if(~exist(fullfile(tsne_path,'FItSNE.exe'),'file') && ispc) system(sprintf('g++ -std=c++11 -O3 src/sptree.cpp src/tsne.cpp src/nbodyfft.cpp -o bin/FItSNE.exe -pthread -lfftw3 -lm')); end % Run the fast diffusion SNE implementation write_data('data.dat', X, p.no_dims, p.theta, p.perplexity, p.max_iter, ... p.stop_early_exag_iter, p.K, p.sigma, p.nbody_algo, p.no_momentum_during_exag, p.knn_algo,... p.early_exag_coeff, p.n_trees, p.search_k, p.start_late_exag_iter, p.late_exag_coeff, p.rand_seed,... p.nterms, p.intervals_per_integer, p.min_num_intervals, p.initialization, p.load_affinities, ... p.perplexity_list, p.mom_switch_iter, p.momentum, p.final_momentum, p.learning_rate,p.max_step_norm,p.df); disp('Data written'); tic %[flag, cmdout] = system(fullfile(tsne_path,'/fast_tsne'), '-echo'); cmd = sprintf('%s %s data.dat result.dat %d',fullfile(tsne_path,'/fast_tsne'), version_number, p.nthreads); [flag, cmdout] = system(cmd, '-echo'); if(flag~=0) error(cmdout); end toc [mappedX, costs] = read_data('result.dat', p.max_iter); delete('data.dat'); delete('result.dat'); end % Writes the datafile for the fast t-SNE implementation function write_data(filename, X, no_dims, theta, perplexity, max_iter,... stop_lying_iter, K, sigma, nbody_algo, no_momentum_during_exag, knn_algo,... early_exag_coeff, n_trees, search_k, start_late_exag_iter, late_exag_coeff, rand_seed,... nterms, intervals_per_integer, min_num_intervals, initialization, load_affinities, ... perplexity_list, mom_switch_iter, momentum, final_momentum, learning_rate,max_step_norm,df) [n, d] = size(X); h = fopen(filename, 'wb'); fwrite(h, n, 'integer*4'); fwrite(h, d, 'integer*4'); fwrite(h, theta, 'double'); fwrite(h, perplexity, 'double'); if perplexity == 0 fwrite(h, length(perplexity_list), 'integer*4'); fwrite(h, perplexity_list, 'double'); end fwrite(h, no_dims, 'integer*4'); fwrite(h, max_iter, 'integer*4'); fwrite(h, stop_lying_iter, 'integer*4'); fwrite(h, mom_switch_iter, 'integer*4'); fwrite(h, momentum, 'double'); fwrite(h, final_momentum, 'double'); fwrite(h, learning_rate, 'double'); fwrite(h, max_step_norm, 'double'); fwrite(h, K, 'int'); fwrite(h, sigma, 'double'); fwrite(h, nbody_algo, 'int'); fwrite(h, knn_algo, 'int'); fwrite(h, early_exag_coeff, 'double'); fwrite(h, no_momentum_during_exag, 'int'); fwrite(h, n_trees, 'int'); fwrite(h, search_k, 'int'); fwrite(h, start_late_exag_iter, 'int'); fwrite(h, late_exag_coeff, 'double'); fwrite(h, nterms, 'int'); fwrite(h, intervals_per_integer, 'double'); fwrite(h, min_num_intervals, 'int'); fwrite(h, X', 'double'); fwrite(h, rand_seed, 'integer*4'); fwrite(h, df, 'double'); fwrite(h, load_affinities, 'integer*4'); if ~isnan(initialization) fwrite(h, initialization', 'double'); end fclose(h); end % Reads the result file from the fast t-SNE implementation function [X, costs] = read_data(file_name, max_iter) h = fopen(file_name, 'rb'); n = fread(h, 1, 'integer*4'); d = fread(h, 1, 'integer*4'); X = fread(h, n * d, 'double'); max_iter = fread(h, 1, 'integer*4'); costs = fread(h, max_iter, 'double'); X = reshape(X, [d n])'; fclose(h); end
13,724
40.717325
132
m
FIt-SNE
FIt-SNE-master/fast_tsne.py
# This is a really basic function that does not do almost any sanity checks # # Usage example: # import sys; sys.path.append('../FIt-SNE/') # from fast_tsne import fast_tsne # import numpy as np # X = np.random.randn(1000, 50) # Z = fast_tsne(X) # # Written by Dmitry Kobak import os import subprocess import struct import numpy as np from datetime import datetime def fast_tsne( X, theta=0.5, perplexity=30, map_dims=2, max_iter=750, stop_early_exag_iter=250, K=-1, sigma=-1, nbody_algo="FFT", knn_algo="annoy", mom_switch_iter=250, momentum=0.5, final_momentum=0.8, learning_rate="auto", early_exag_coeff=12, no_momentum_during_exag=False, n_trees=50, search_k=None, start_late_exag_iter="auto", late_exag_coeff=-1, nterms=3, intervals_per_integer=1, min_num_intervals=50, seed=-1, initialization="pca", load_affinities=None, perplexity_list=None, df=1, return_loss=False, nthreads=-1, max_step_norm=5, ): """Run t-SNE. This implementation supports exact t-SNE, Barnes-Hut t-SNE and FFT-accelerated interpolation-based t-SNE (FIt-SNE). This is a Python wrapper to a C++ executable. Parameters ---------- X: 2D numpy array Array of observations (n times p) perplexity: double Perplexity is used to determine the bandwidth of the Gaussian kernel in the input space. Default 30. theta: double Set to 0 for exact t-SNE. If non-zero, then the code will use either Barnes Hut or FIt-SNE based on `nbody_algo`. If Barnes Hut, then theta determins the accuracy of BH approximation. Default 0.5. map_dims: int Number of embedding dimensions. Default 2. FIt-SNE supports only 1 or 2 dimensions. max_iter: int Number of gradient descent iterations. Default 750. nbody_algo: {'Barnes-Hut', 'FFT'} If theta is nonzero, this determines whether to use FIt-SNE (default) or Barnes-Hut approximation. knn_algo: {'vp-tree', 'annoy'} Use exact nearest neighbours with VP trees (as in BH t-SNE) or approximate nearest neighbors with Annoy. Default is 'annoy'. early_exag_coeff: double Coefficient for early exaggeration. Default 12. stop_early_exag_iter: int When to switch off early exaggeration. Default 250. late_exag_coeff: double Coefficient for late exaggeration. Set to -1 in order not to use late exaggeration. Default -1. start_late_exag_iter: int or 'auto' When to start late exaggeration. Default 'auto'; it sets start_late_exag_iter to -1 meaning that late exaggeration is not used, unless late_exag_coeff>0. In that case start_late_exag_iter is set to stop_early_exag_iter. momentum: double Initial value of momentum. Default 0.5. final_momentum: double The value of momentum to use later in the optimisation. Default 0.8. mom_switch_iter: int Iteration number to switch from momentum to final_momentum. Default 250. learning_rate: double or 'auto' Learning rate. Default 'auto'; it sets learning rate to N/early_exag_coeff where N is the sample size, or to 200 if N/early_exag_coeff < 200. max_step_norm: double or 'none' (default: 5) Maximum distance that a point is allowed to move on one iteration. Larger steps are clipped to this value. This prevents possible instabilities during gradient descent. Set to 'none' to switch it off. no_mometum_during_exag: boolean Whether to switch off momentum during the early exaggeration phase (can be useful for experiments with large exaggeration coefficients). Default is False. sigma: boolean The standard deviation of the Gaussian kernel to be used for all points instead of choosing it adaptively via perplexity. Set to -1 to use perplexity. Default is -1. K: int The number of nearest neighbours to use when using fixed sigma instead of perplexity calibration. Set to -1 when perplexity is used. Default is -1. nterms: int If using FIt-SNE, this is the number of interpolation points per sub-interval intervals_per_integer: double See min_num_intervals min_num_intervals: int The interpolation grid is chosen on each step of the gradient descent. If Y is the current embedding, let maxloc = ceiling(max(Y.flatten)) and minloc = floor(min(Y.flatten)), i.e. the points are contained in a [minloc, maxloc]^no_dims box. The number of intervals in each dimension is either min_num_intervals or ceiling((maxloc-minloc)/intervals_per_integer), whichever is larger. min_num_intervals must be a positive integer and intervals_per_integer must be positive real value. Defaults: min_num_intervals=50, intervals_per_integer = 1. n_trees: int When using Annoy, the number of search trees to use. Default is 50. search_k: int When using Annoy, the number of nodes to inspect during search. Default is 3*perplexity*n_trees (or K*n_trees when using fixed sigma). seed: int Seed for random initialisation. Use -1 to initialise random number generator with current time. Default -1. initialization: 'random', 'pca', or numpy array N x no_dims array to intialize the solution. Default: 'pca'. load_affinities: {'load', 'save', None} If 'save', input similarities (p_ij) are saved into a file. If 'load', they are loaded from a file and not recomputed. If None, they are not saved and not loaded. Default is None. perplexity_list: list A list of perplexities to used as a perplexity combination. Input affinities are computed with each perplexity on the list and then averaged. Default is None. nthreads: int Number of threads to use. Default is -1, i.e. use all available threads. df: double Controls the degree of freedom of t-distribution. Must be positive. The actual degree of freedom is 2*df-1. The standard t-SNE choice of 1 degree of freedom corresponds to df=1. Large df approximates Gaussian kernel. df<1 corresponds to heavier tails, which can often resolve substructure in the embedding. See Kobak et al. (2019) for details. Default is 1.0. return_loss: boolean If True, the function returns the loss values computed during optimisation together with the final embedding. If False, only the embedding is returned. Default is False. Returns ------- Y: numpy array The embedding. loss: numpy array Loss values computed during optimisation. Only returned if return_loss is True. """ version_number = "1.2.1" # X should be a numpy array of 64-bit doubles X = np.array(X).astype(float) if learning_rate == "auto": learning_rate = np.max((200, X.shape[0] / early_exag_coeff)) if start_late_exag_iter == "auto": if late_exag_coeff > 0: start_late_exag_iter = stop_early_exag_iter else: start_late_exag_iter = -1 if isinstance(initialization, str) and initialization == "pca": from sklearn.decomposition import PCA solver = "arpack" if X.shape[1] > map_dims else "auto" pca = PCA( n_components=map_dims, svd_solver=solver, random_state=seed if seed != -1 else None, ) initialization = pca.fit_transform(X) initialization /= np.std(initialization[:, 0]) initialization *= 0.0001 if perplexity_list is not None: perplexity = 0 # C++ requires perplexity=0 in order to use perplexity_list if sigma > 0 and K > 0: perplexity = -1 # C++ requires perplexity=-1 in order to use sigma if search_k is None: if perplexity > 0: search_k = 3 * perplexity * n_trees elif perplexity == 0: search_k = 3 * np.max(perplexity_list) * n_trees else: search_k = K * n_trees # Not much of a speed up, at least on some machines, so I'm removing it. # # if nbody_algo == 'auto': # if X.shape[0] < 8000: # nbody_algo = 'Barnes-Hut' # else: # nbody_algo = 'FFT' if nbody_algo == "Barnes-Hut": nbody_algo = 1 elif nbody_algo == "FFT": nbody_algo = 2 else: raise ValueError("nbody_algo should be 'Barnes-Hut' or 'FFT'") if knn_algo == "vp-tree": knn_algo = 2 elif knn_algo == "annoy": knn_algo = 1 else: raise ValueError("knn_algo should be 'vp-tree' or 'annoy'") if load_affinities == "load": load_affinities = 1 elif load_affinities == "save": load_affinities = 2 else: load_affinities = 0 if nthreads == -1: nthreads = 0 if max_step_norm == "none": max_step_norm = -1 if no_momentum_during_exag: no_momentum_during_exag = 1 else: no_momentum_during_exag = 0 # create unique i/o-filenames timestamp = str(datetime.now()) + '-' + str(np.random.randint(0,1000000000)) infile = 'data_%s.dat' % timestamp outfile = 'result_%s.dat' % timestamp # write data file with open(os.getcwd() + '/' + infile, 'wb') as f: n, d = X.shape f.write(struct.pack("=i", n)) f.write(struct.pack("=i", d)) f.write(struct.pack("=d", theta)) f.write(struct.pack("=d", perplexity)) if perplexity == 0: f.write(struct.pack("=i", len(perplexity_list))) for perpl in perplexity_list: f.write(struct.pack("=d", perpl)) f.write(struct.pack("=i", map_dims)) f.write(struct.pack("=i", max_iter)) f.write(struct.pack("=i", stop_early_exag_iter)) f.write(struct.pack("=i", mom_switch_iter)) f.write(struct.pack("=d", momentum)) f.write(struct.pack("=d", final_momentum)) f.write(struct.pack("=d", learning_rate)) f.write(struct.pack("=d", max_step_norm)) f.write(struct.pack("=i", K)) f.write(struct.pack("=d", sigma)) f.write(struct.pack("=i", nbody_algo)) f.write(struct.pack("=i", knn_algo)) f.write(struct.pack("=d", early_exag_coeff)) f.write(struct.pack("=i", no_momentum_during_exag)) f.write(struct.pack("=i", n_trees)) f.write(struct.pack("=i", search_k)) f.write(struct.pack("=i", start_late_exag_iter)) f.write(struct.pack("=d", late_exag_coeff)) f.write(struct.pack("=i", nterms)) f.write(struct.pack("=d", intervals_per_integer)) f.write(struct.pack("=i", min_num_intervals)) f.write(X.tobytes()) f.write(struct.pack("=i", seed)) f.write(struct.pack("=d", df)) f.write(struct.pack("=i", load_affinities)) if not isinstance(initialization, str) or initialization != "random": initialization = np.array(initialization).astype(float) f.write(initialization.tobytes()) # run t-sne subprocess.call( [ os.path.dirname(os.path.realpath(__file__)) + "/bin/fast_tsne", version_number, infile, outfile, "{}".format(nthreads), ] ) # read data file with open(os.getcwd() + '/' + outfile, 'rb') as f: (n,) = struct.unpack("=i", f.read(4)) (md,) = struct.unpack("=i", f.read(4)) sz = struct.calcsize("=d") buf = f.read(sz * n * md) x_tsne = [ struct.unpack_from("=d", buf, sz * offset) for offset in range(n * md) ] x_tsne = np.array(x_tsne).reshape((n, md)) (_,) = struct.unpack("=i", f.read(4)) buf = f.read(sz * max_iter) loss = [ struct.unpack_from("=d", buf, sz * offset) for offset in range(max_iter) ] loss = np.array(loss).squeeze() if loss.size == 1: loss = loss[np.newaxis] loss[np.arange(1, max_iter + 1) % 50 > 0] = np.nan # remove i/o-files os.remove(os.getcwd() + '/' + infile) os.remove(os.getcwd() + '/' + outfile) if return_loss: return (x_tsne, loss) else: return x_tsne
12,556
36.041298
84
py
FIt-SNE
FIt-SNE-master/examples/test.m
% This should be the path to the FIt-SNE folder where fast_tsne.m is located addpath('../') % Generate a toy dataset dim = 3; sigma_0 = .0001; cluster_num = 2; cluster_size = 1E4; X_clusters = []; col_clusters = repmat(1:cluster_num,cluster_size,1); col_clusters = col_clusters(:); for i = 1:cluster_num X_clusters = [X_clusters; mvnrnd(rand(dim,1)', diag(sigma_0*ones(dim,1)), cluster_size)]; end N_clusters = size(X_clusters,1); figure(19988) subplot(121) scatter3(X_clusters(:,1), X_clusters(:,2), X_clusters(:,3),10, col_clusters, 'filled'); title('Original Data') % Run t-SNE clear opts opts.max_iter = 400; cluster_firstphase = fast_tsne(X_clusters, opts); subplot(122) scatter(cluster_firstphase(:,1), cluster_firstphase(:,2), 10, col_clusters, 'filled'); title('After t-SNE') colormap(lines(cluster_num))
826
21.972222
93
m
FIt-SNE
FIt-SNE-master/src/annoylib.h
// Copyright (c) 2013 Spotify AB // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. #ifndef ANNOYLIB_H #define ANNOYLIB_H #include <stdio.h> #include <sys/stat.h> #ifndef _MSC_VER #include <unistd.h> #endif #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <fcntl.h> #include <stddef.h> #if defined(_MSC_VER) && _MSC_VER == 1500 typedef unsigned char uint8_t; typedef signed __int32 int32_t; typedef unsigned __int64 uint64_t; #else #include <stdint.h> #endif #if defined(_MSC_VER) || defined(__MINGW32__) #ifndef NOMINMAX #define NOMINMAX #endif #include "winlibs/mman.h" #include <windows.h> #else #include <sys/mman.h> #endif #include <cerrno> #include <string.h> #include <math.h> #include <vector> #include <algorithm> #include <queue> #include <limits> #ifdef _MSC_VER // Needed for Visual Studio to disable runtime checks for mempcy #pragma runtime_checks("s", off) #endif // This allows others to supply their own logger / error printer without // requiring Annoy to import their headers. See RcppAnnoy for a use case. #ifndef __ERROR_PRINTER_OVERRIDE__ #define showUpdate(...) { fprintf(stderr, __VA_ARGS__ ); } #else #define showUpdate(...) { __ERROR_PRINTER_OVERRIDE__( __VA_ARGS__ ); } #endif #ifndef _MSC_VER #define popcount __builtin_popcountll #else // See #293, #358 #define isnan(x) _isnan(x) #define popcount cole_popcount #endif #if !defined(NO_MANUAL_VECTORIZATION) && defined(__GNUC__) && (__GNUC__ >6) && defined(__AVX512F__) // See #402 #pragma message "Using 512-bit AVX instructions" #define USE_AVX512 #elif !defined(NO_MANUAL_VECTORIZATION) && defined(__AVX__) && defined (__SSE__) && defined(__SSE2__) && defined(__SSE3__) #pragma message "Using 128-bit AVX instructions" #define USE_AVX #else #pragma message "Using no AVX instructions" #endif #if defined(USE_AVX) || defined(USE_AVX512) #if defined(_MSC_VER) #include <intrin.h> #elif defined(__GNUC__) #include <x86intrin.h> #endif #endif #ifndef ANNOY_NODE_ATTRIBUTE #ifndef _MSC_VER #define ANNOY_NODE_ATTRIBUTE __attribute__((__packed__)) // TODO: this is turned on by default, but may not work for all architectures! Need to investigate. #else #define ANNOY_NODE_ATTRIBUTE #endif #endif using std::vector; using std::pair; using std::numeric_limits; using std::make_pair; inline void* remap_memory(void* _ptr, int _fd, size_t old_size, size_t new_size) { #ifdef __linux__ _ptr = mremap(_ptr, old_size, new_size, MREMAP_MAYMOVE); #else munmap(_ptr, old_size); #ifdef MAP_POPULATE _ptr = mmap(_ptr, new_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, _fd, 0); #else _ptr = mmap(_ptr, new_size, PROT_READ | PROT_WRITE, MAP_SHARED, _fd, 0); #endif #endif return _ptr; } namespace { template<typename S, typename Node> inline Node* get_node_ptr(const void* _nodes, const size_t _s, const S i) { return (Node*)((uint8_t *)_nodes + (_s * i)); } template<typename T> inline T dot(const T* x, const T* y, int f) { T s = 0; for (int z = 0; z < f; z++) { s += (*x) * (*y); x++; y++; } return s; } template<typename T> inline T manhattan_distance(const T* x, const T* y, int f) { T d = 0.0; for (int i = 0; i < f; i++) d += fabs(x[i] - y[i]); return d; } template<typename T> inline T euclidean_distance(const T* x, const T* y, int f) { // Don't use dot-product: avoid catastrophic cancellation in #314. T d = 0.0; for (int i = 0; i < f; ++i) { const T tmp=*x - *y; d += tmp * tmp; ++x; ++y; } return d; } #ifdef USE_AVX // Horizontal single sum of 256bit vector. inline float hsum256_ps_avx(__m256 v) { const __m128 x128 = _mm_add_ps(_mm256_extractf128_ps(v, 1), _mm256_castps256_ps128(v)); const __m128 x64 = _mm_add_ps(x128, _mm_movehl_ps(x128, x128)); const __m128 x32 = _mm_add_ss(x64, _mm_shuffle_ps(x64, x64, 0x55)); return _mm_cvtss_f32(x32); } template<> inline float dot<float>(const float* x, const float *y, int f) { float result = 0; if (f > 7) { __m256 d = _mm256_setzero_ps(); for (; f > 7; f -= 8) { d = _mm256_add_ps(d, _mm256_mul_ps(_mm256_loadu_ps(x), _mm256_loadu_ps(y))); x += 8; y += 8; } // Sum all floats in dot register. result += hsum256_ps_avx(d); } // Don't forget the remaining values. for (; f > 0; f--) { result += *x * *y; x++; y++; } return result; } template<> inline float manhattan_distance<float>(const float* x, const float* y, int f) { float result = 0; int i = f; if (f > 7) { __m256 manhattan = _mm256_setzero_ps(); __m256 minus_zero = _mm256_set1_ps(-0.0f); for (; i > 7; i -= 8) { const __m256 x_minus_y = _mm256_sub_ps(_mm256_loadu_ps(x), _mm256_loadu_ps(y)); const __m256 distance = _mm256_andnot_ps(minus_zero, x_minus_y); // Absolute value of x_minus_y (forces sign bit to zero) manhattan = _mm256_add_ps(manhattan, distance); x += 8; y += 8; } // Sum all floats in manhattan register. result = hsum256_ps_avx(manhattan); } // Don't forget the remaining values. for (; i > 0; i--) { result += fabsf(*x - *y); x++; y++; } return result; } template<> inline float euclidean_distance<float>(const float* x, const float* y, int f) { float result=0; if (f > 7) { __m256 d = _mm256_setzero_ps(); for (; f > 7; f -= 8) { const __m256 diff = _mm256_sub_ps(_mm256_loadu_ps(x), _mm256_loadu_ps(y)); d = _mm256_add_ps(d, _mm256_mul_ps(diff, diff)); // no support for fmadd in AVX... x += 8; y += 8; } // Sum all floats in dot register. result = hsum256_ps_avx(d); } // Don't forget the remaining values. for (; f > 0; f--) { float tmp = *x - *y; result += tmp * tmp; x++; y++; } return result; } #endif #ifdef USE_AVX512 template<> inline float dot<float>(const float* x, const float *y, int f) { float result = 0; if (f > 15) { __m512 d = _mm512_setzero_ps(); for (; f > 15; f -= 16) { //AVX512F includes FMA d = _mm512_fmadd_ps(_mm512_loadu_ps(x), _mm512_loadu_ps(y), d); x += 16; y += 16; } // Sum all floats in dot register. result += _mm512_reduce_add_ps(d); } // Don't forget the remaining values. for (; f > 0; f--) { result += *x * *y; x++; y++; } return result; } template<> inline float manhattan_distance<float>(const float* x, const float* y, int f) { float result = 0; int i = f; if (f > 15) { __m512 manhattan = _mm512_setzero_ps(); for (; i > 15; i -= 16) { const __m512 x_minus_y = _mm512_sub_ps(_mm512_loadu_ps(x), _mm512_loadu_ps(y)); manhattan = _mm512_add_ps(manhattan, _mm512_abs_ps(x_minus_y)); x += 16; y += 16; } // Sum all floats in manhattan register. result = _mm512_reduce_add_ps(manhattan); } // Don't forget the remaining values. for (; i > 0; i--) { result += fabsf(*x - *y); x++; y++; } return result; } template<> inline float euclidean_distance<float>(const float* x, const float* y, int f) { float result=0; if (f > 15) { __m512 d = _mm512_setzero_ps(); for (; f > 15; f -= 16) { const __m512 diff = _mm512_sub_ps(_mm512_loadu_ps(x), _mm512_loadu_ps(y)); d = _mm512_fmadd_ps(diff, diff, d); x += 16; y += 16; } // Sum all floats in dot register. result = _mm512_reduce_add_ps(d); } // Don't forget the remaining values. for (; f > 0; f--) { float tmp = *x - *y; result += tmp * tmp; x++; y++; } return result; } #endif template<typename T> inline T get_norm(T* v, int f) { return sqrt(dot(v, v, f)); } template<typename T, typename Random, typename Distance, typename Node> inline void two_means(const vector<Node*>& nodes, int f, Random& random, bool cosine, Node* p, Node* q) { /* This algorithm is a huge heuristic. Empirically it works really well, but I can't motivate it well. The basic idea is to keep two centroids and assign points to either one of them. We weight each centroid by the number of points assigned to it, so to balance it. */ static int iteration_steps = 200; size_t count = nodes.size(); size_t i = random.index(count); size_t j = random.index(count-1); j += (j >= i); // ensure that i != j Distance::template copy_node<T, Node>(p, nodes[i], f); Distance::template copy_node<T, Node>(q, nodes[j], f); if (cosine) { Distance::template normalize<T, Node>(p, f); Distance::template normalize<T, Node>(q, f); } Distance::init_node(p, f); Distance::init_node(q, f); int ic = 1, jc = 1; for (int l = 0; l < iteration_steps; l++) { size_t k = random.index(count); T di = ic * Distance::distance(p, nodes[k], f), dj = jc * Distance::distance(q, nodes[k], f); T norm = cosine ? get_norm(nodes[k]->v, f) : 1.0; if (!(norm > T(0))) { continue; } if (di < dj) { for (int z = 0; z < f; z++) p->v[z] = (p->v[z] * ic + nodes[k]->v[z] / norm) / (ic + 1); Distance::init_node(p, f); ic++; } else if (dj < di) { for (int z = 0; z < f; z++) q->v[z] = (q->v[z] * jc + nodes[k]->v[z] / norm) / (jc + 1); Distance::init_node(q, f); jc++; } } } } // namespace struct Base { template<typename T, typename S, typename Node> static inline void preprocess(void* nodes, size_t _s, const S node_count, const int f) { // Override this in specific metric structs below if you need to do any pre-processing // on the entire set of nodes passed into this index. } template<typename Node> static inline void zero_value(Node* dest) { // Initialize any fields that require sane defaults within this node. } template<typename T, typename Node> static inline void copy_node(Node* dest, const Node* source, const int f) { memcpy(dest->v, source->v, f * sizeof(T)); } template<typename T, typename Node> static inline void normalize(Node* node, int f) { T norm = get_norm(node->v, f); if (norm > 0) { for (int z = 0; z < f; z++) node->v[z] /= norm; } } }; struct Angular : Base { template<typename S, typename T> struct ANNOY_NODE_ATTRIBUTE Node { /* * We store a binary tree where each node has two things * - A vector associated with it * - Two children * All nodes occupy the same amount of memory * All nodes with n_descendants == 1 are leaf nodes. * A memory optimization is that for nodes with 2 <= n_descendants <= K, * we skip the vector. Instead we store a list of all descendants. K is * determined by the number of items that fits in the space of the vector. * For nodes with n_descendants == 1 the vector is a data point. * For nodes with n_descendants > K the vector is the normal of the split plane. * Note that we can't really do sizeof(node<T>) because we cheat and allocate * more memory to be able to fit the vector outside */ S n_descendants; union { S children[2]; // Will possibly store more than 2 T norm; }; T v[1]; // We let this one overflow intentionally. Need to allocate at least 1 to make GCC happy }; template<typename S, typename T> static inline T distance(const Node<S, T>* x, const Node<S, T>* y, int f) { // want to calculate (a/|a| - b/|b|)^2 // = a^2 / a^2 + b^2 / b^2 - 2ab/|a||b| // = 2 - 2cos T pp = x->norm ? x->norm : dot(x->v, x->v, f); // For backwards compatibility reasons, we need to fall back and compute the norm here T qq = y->norm ? y->norm : dot(y->v, y->v, f); T pq = dot(x->v, y->v, f); T ppqq = pp * qq; if (ppqq > 0) return 2.0 - 2.0 * pq / sqrt(ppqq); else return 2.0; // cos is 0 } template<typename S, typename T> static inline T margin(const Node<S, T>* n, const T* y, int f) { return dot(n->v, y, f); } template<typename S, typename T, typename Random> static inline bool side(const Node<S, T>* n, const T* y, int f, Random& random) { T dot = margin(n, y, f); if (dot != 0) return (dot > 0); else return random.flip(); } template<typename S, typename T, typename Random> static inline void create_split(const vector<Node<S, T>*>& nodes, int f, size_t s, Random& random, Node<S, T>* n) { Node<S, T>* p = (Node<S, T>*)alloca(s); Node<S, T>* q = (Node<S, T>*)alloca(s); two_means<T, Random, Angular, Node<S, T> >(nodes, f, random, true, p, q); for (int z = 0; z < f; z++) n->v[z] = p->v[z] - q->v[z]; Base::normalize<T, Node<S, T> >(n, f); } template<typename T> static inline T normalized_distance(T distance) { // Used when requesting distances from Python layer // Turns out sometimes the squared distance is -0.0 // so we have to make sure it's a positive number. return sqrt(std::max(distance, T(0))); } template<typename T> static inline T pq_distance(T distance, T margin, int child_nr) { if (child_nr == 0) margin = -margin; return std::min(distance, margin); } template<typename T> static inline T pq_initial_value() { return numeric_limits<T>::infinity(); } template<typename S, typename T> static inline void init_node(Node<S, T>* n, int f) { n->norm = dot(n->v, n->v, f); } static const char* name() { return "angular"; } }; struct DotProduct : Angular { template<typename S, typename T> struct ANNOY_NODE_ATTRIBUTE Node { /* * This is an extension of the Angular node with an extra attribute for the scaled norm. */ S n_descendants; S children[2]; // Will possibly store more than 2 T dot_factor; T v[1]; // We let this one overflow intentionally. Need to allocate at least 1 to make GCC happy }; static const char* name() { return "dot"; } template<typename S, typename T> static inline T distance(const Node<S, T>* x, const Node<S, T>* y, int f) { return -dot(x->v, y->v, f); } template<typename Node> static inline void zero_value(Node* dest) { dest->dot_factor = 0; } template<typename S, typename T> static inline void init_node(Node<S, T>* n, int f) { } template<typename T, typename Node> static inline void copy_node(Node* dest, const Node* source, const int f) { memcpy(dest->v, source->v, f * sizeof(T)); dest->dot_factor = source->dot_factor; } template<typename S, typename T, typename Random> static inline void create_split(const vector<Node<S, T>*>& nodes, int f, size_t s, Random& random, Node<S, T>* n) { Node<S, T>* p = (Node<S, T>*)alloca(s); Node<S, T>* q = (Node<S, T>*)alloca(s); DotProduct::zero_value(p); DotProduct::zero_value(q); two_means<T, Random, DotProduct, Node<S, T> >(nodes, f, random, true, p, q); for (int z = 0; z < f; z++) n->v[z] = p->v[z] - q->v[z]; n->dot_factor = p->dot_factor - q->dot_factor; DotProduct::normalize<T, Node<S, T> >(n, f); } template<typename T, typename Node> static inline void normalize(Node* node, int f) { T norm = sqrt(dot(node->v, node->v, f) + pow(node->dot_factor, 2)); if (norm > 0) { for (int z = 0; z < f; z++) node->v[z] /= norm; node->dot_factor /= norm; } } template<typename S, typename T> static inline T margin(const Node<S, T>* n, const T* y, int f) { return dot(n->v, y, f) + (n->dot_factor * n->dot_factor); } template<typename S, typename T, typename Random> static inline bool side(const Node<S, T>* n, const T* y, int f, Random& random) { T dot = margin(n, y, f); if (dot != 0) return (dot > 0); else return random.flip(); } template<typename T> static inline T normalized_distance(T distance) { return -distance; } template<typename T, typename S, typename Node> static inline void preprocess(void* nodes, size_t _s, const S node_count, const int f) { // This uses a method from Microsoft Research for transforming inner product spaces to cosine/angular-compatible spaces. // (Bachrach et al., 2014, see https://www.microsoft.com/en-us/research/wp-content/uploads/2016/02/XboxInnerProduct.pdf) // Step one: compute the norm of each vector and store that in its extra dimension (f-1) for (S i = 0; i < node_count; i++) { Node* node = get_node_ptr<S, Node>(nodes, _s, i); T norm = sqrt(dot(node->v, node->v, f)); if (isnan(norm)) norm = 0; node->dot_factor = norm; } // Step two: find the maximum norm T max_norm = 0; for (S i = 0; i < node_count; i++) { Node* node = get_node_ptr<S, Node>(nodes, _s, i); if (node->dot_factor > max_norm) { max_norm = node->dot_factor; } } // Step three: set each vector's extra dimension to sqrt(max_norm^2 - norm^2) for (S i = 0; i < node_count; i++) { Node* node = get_node_ptr<S, Node>(nodes, _s, i); T node_norm = node->dot_factor; T dot_factor = sqrt(pow(max_norm, static_cast<T>(2.0)) - pow(node_norm, static_cast<T>(2.0))); if (isnan(dot_factor)) dot_factor = 0; node->dot_factor = dot_factor; } } }; struct Hamming : Base { template<typename S, typename T> struct ANNOY_NODE_ATTRIBUTE Node { S n_descendants; S children[2]; T v[1]; }; static const size_t max_iterations = 20; template<typename T> static inline T pq_distance(T distance, T margin, int child_nr) { return distance - (margin != (unsigned int) child_nr); } template<typename T> static inline T pq_initial_value() { return numeric_limits<T>::max(); } template<typename T> static inline int cole_popcount(T v) { // Note: Only used with MSVC 9, which lacks intrinsics and fails to // calculate std::bitset::count for v > 32bit. Uses the generalized // approach by Eric Cole. // See https://graphics.stanford.edu/~seander/bithacks.html#CountBitsSet64 v = v - ((v >> 1) & (T)~(T)0/3); v = (v & (T)~(T)0/15*3) + ((v >> 2) & (T)~(T)0/15*3); v = (v + (v >> 4)) & (T)~(T)0/255*15; return (T)(v * ((T)~(T)0/255)) >> (sizeof(T) - 1) * 8; } template<typename S, typename T> static inline T distance(const Node<S, T>* x, const Node<S, T>* y, int f) { size_t dist = 0; for (int i = 0; i < f; i++) { dist += popcount(x->v[i] ^ y->v[i]); } return dist; } template<typename S, typename T> static inline bool margin(const Node<S, T>* n, const T* y, int f) { static const size_t n_bits = sizeof(T) * 8; T chunk = n->v[0] / n_bits; return (y[chunk] & (static_cast<T>(1) << (n_bits - 1 - (n->v[0] % n_bits)))) != 0; } template<typename S, typename T, typename Random> static inline bool side(const Node<S, T>* n, const T* y, int f, Random& random) { return margin(n, y, f); } template<typename S, typename T, typename Random> static inline void create_split(const vector<Node<S, T>*>& nodes, int f, size_t s, Random& random, Node<S, T>* n) { size_t cur_size = 0; size_t i = 0; int dim = f * 8 * sizeof(T); for (; i < max_iterations; i++) { // choose random position to split at n->v[0] = random.index(dim); cur_size = 0; for (typename vector<Node<S, T>*>::const_iterator it = nodes.begin(); it != nodes.end(); ++it) { if (margin(n, (*it)->v, f)) { cur_size++; } } if (cur_size > 0 && cur_size < nodes.size()) { break; } } // brute-force search for splitting coordinate if (i == max_iterations) { int j = 0; for (; j < dim; j++) { n->v[0] = j; cur_size = 0; for (typename vector<Node<S, T>*>::const_iterator it = nodes.begin(); it != nodes.end(); ++it) { if (margin(n, (*it)->v, f)) { cur_size++; } } if (cur_size > 0 && cur_size < nodes.size()) { break; } } } } template<typename T> static inline T normalized_distance(T distance) { return distance; } template<typename S, typename T> static inline void init_node(Node<S, T>* n, int f) { } static const char* name() { return "hamming"; } }; struct Minkowski : Base { template<typename S, typename T> struct ANNOY_NODE_ATTRIBUTE Node { S n_descendants; T a; // need an extra constant term to determine the offset of the plane S children[2]; T v[1]; }; template<typename S, typename T> static inline T margin(const Node<S, T>* n, const T* y, int f) { return n->a + dot(n->v, y, f); } template<typename S, typename T, typename Random> static inline bool side(const Node<S, T>* n, const T* y, int f, Random& random) { T dot = margin(n, y, f); if (dot != 0) return (dot > 0); else return random.flip(); } template<typename T> static inline T pq_distance(T distance, T margin, int child_nr) { if (child_nr == 0) margin = -margin; return std::min(distance, margin); } template<typename T> static inline T pq_initial_value() { return numeric_limits<T>::infinity(); } }; struct Euclidean : Minkowski { template<typename S, typename T> static inline T distance(const Node<S, T>* x, const Node<S, T>* y, int f) { return euclidean_distance(x->v, y->v, f); } template<typename S, typename T, typename Random> static inline void create_split(const vector<Node<S, T>*>& nodes, int f, size_t s, Random& random, Node<S, T>* n) { Node<S, T>* p = (Node<S, T>*)alloca(s); Node<S, T>* q = (Node<S, T>*)alloca(s); two_means<T, Random, Euclidean, Node<S, T> >(nodes, f, random, false, p, q); for (int z = 0; z < f; z++) n->v[z] = p->v[z] - q->v[z]; Base::normalize<T, Node<S, T> >(n, f); n->a = 0.0; for (int z = 0; z < f; z++) n->a += -n->v[z] * (p->v[z] + q->v[z]) / 2; } template<typename T> static inline T normalized_distance(T distance) { return sqrt(std::max(distance, T(0))); } template<typename S, typename T> static inline void init_node(Node<S, T>* n, int f) { } static const char* name() { return "euclidean"; } }; struct Manhattan : Minkowski { template<typename S, typename T> static inline T distance(const Node<S, T>* x, const Node<S, T>* y, int f) { return manhattan_distance(x->v, y->v, f); } template<typename S, typename T, typename Random> static inline void create_split(const vector<Node<S, T>*>& nodes, int f, size_t s, Random& random, Node<S, T>* n) { Node<S, T>* p = (Node<S, T>*)alloca(s); Node<S, T>* q = (Node<S, T>*)alloca(s); two_means<T, Random, Manhattan, Node<S, T> >(nodes, f, random, false, p, q); for (int z = 0; z < f; z++) n->v[z] = p->v[z] - q->v[z]; Base::normalize<T, Node<S, T> >(n, f); n->a = 0.0; for (int z = 0; z < f; z++) n->a += -n->v[z] * (p->v[z] + q->v[z]) / 2; } template<typename T> static inline T normalized_distance(T distance) { return std::max(distance, T(0)); } template<typename S, typename T> static inline void init_node(Node<S, T>* n, int f) { } static const char* name() { return "manhattan"; } }; template<typename S, typename T> class AnnoyIndexInterface { public: virtual ~AnnoyIndexInterface() {}; virtual bool add_item(S item, const T* w, char** error=NULL) = 0; virtual bool build(int q, char** error=NULL) = 0; virtual bool unbuild(char** error=NULL) = 0; virtual bool save(const char* filename, bool prefault=false, char** error=NULL) = 0; virtual void unload() = 0; virtual bool load(const char* filename, bool prefault=false, char** error=NULL) = 0; virtual T get_distance(S i, S j) const = 0; virtual void get_nns_by_item(S item, size_t n, size_t search_k, vector<S>* result, vector<T>* distances) const = 0; virtual void get_nns_by_vector(const T* w, size_t n, size_t search_k, vector<S>* result, vector<T>* distances) const = 0; virtual S get_n_items() const = 0; virtual S get_n_trees() const = 0; virtual void verbose(bool v) = 0; virtual void get_item(S item, T* v) const = 0; virtual void set_seed(int q) = 0; virtual bool on_disk_build(const char* filename, char** error=NULL) = 0; }; template<typename S, typename T, typename Distance, typename Random> class AnnoyIndex : public AnnoyIndexInterface<S, T> { /* * We use random projection to build a forest of binary trees of all items. * Basically just split the hyperspace into two sides by a hyperplane, * then recursively split each of those subtrees etc. * We create a tree like this q times. The default q is determined automatically * in such a way that we at most use 2x as much memory as the vectors take. */ public: typedef Distance D; typedef typename D::template Node<S, T> Node; protected: const int _f; size_t _s; S _n_items; Random _random; void* _nodes; // Could either be mmapped, or point to a memory buffer that we reallocate S _n_nodes; S _nodes_size; vector<S> _roots; S _K; bool _loaded; bool _verbose; int _fd; bool _on_disk; bool _built; public: AnnoyIndex(int f) : _f(f), _random() { _s = offsetof(Node, v) + _f * sizeof(T); // Size of each node _verbose = false; _built = false; _K = (S) (((size_t) (_s - offsetof(Node, children))) / sizeof(S)); // Max number of descendants to fit into node reinitialize(); // Reset everything } ~AnnoyIndex() { unload(); } int get_f() const { return _f; } bool add_item(S item, const T* w, char** error=NULL) { return add_item_impl(item, w, error); } template<typename W> bool add_item_impl(S item, const W& w, char** error=NULL) { if (_loaded) { showUpdate("You can't add an item to a loaded index\n"); if (error) *error = (char *)"You can't add an item to a loaded index"; return false; } _allocate_size(item + 1); Node* n = _get(item); D::zero_value(n); n->children[0] = 0; n->children[1] = 0; n->n_descendants = 1; for (int z = 0; z < _f; z++) n->v[z] = w[z]; D::init_node(n, _f); if (item >= _n_items) _n_items = item + 1; return true; } bool on_disk_build(const char* file, char** error=NULL) { _on_disk = true; #ifdef _WIN32 _fd = _open(file, O_RDWR | O_CREAT | O_TRUNC, (int)0600); #else _fd = open(file, O_RDWR | O_CREAT | O_TRUNC, (int)0600); #endif if (_fd == -1) { showUpdate("Error: file descriptor is -1\n"); if (error) *error = strerror(errno); _fd = 0; return false; } _nodes_size = 1; if (ftruncate(_fd, _s * _nodes_size) == -1) { showUpdate("Error truncating file: %s\n", strerror(errno)); if (error) *error = strerror(errno); return false; } #ifdef MAP_POPULATE _nodes = (Node*) mmap(0, _s * _nodes_size, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_POPULATE, _fd, 0); #else _nodes = (Node*) mmap(0, _s * _nodes_size, PROT_READ | PROT_WRITE, MAP_SHARED, _fd, 0); #endif return true; } bool build(int q, char** error=NULL) { if (_loaded) { showUpdate("You can't build a loaded index\n"); if (error) *error = (char *)"You can't build a loaded index"; return false; } if (_built) { showUpdate("You can't build a built index\n"); if (error) *error = (char *)"You can't build a built index"; return false; } D::template preprocess<T, S, Node>(_nodes, _s, _n_items, _f); _n_nodes = _n_items; while (1) { if (q == -1 && _n_nodes >= _n_items * 2) break; if (q != -1 && _roots.size() >= (size_t)q) break; if (_verbose) showUpdate("pass %zd...\n", _roots.size()); vector<S> indices; for (S i = 0; i < _n_items; i++) { if (_get(i)->n_descendants >= 1) // Issue #223 indices.push_back(i); } _roots.push_back(_make_tree(indices, true)); } // Also, copy the roots into the last segment of the array // This way we can load them faster without reading the whole file _allocate_size(_n_nodes + (S)_roots.size()); for (size_t i = 0; i < _roots.size(); i++) memcpy(_get(_n_nodes + (S)i), _get(_roots[i]), _s); _n_nodes += _roots.size(); if (_verbose) showUpdate("has %d nodes\n", _n_nodes); if (_on_disk) { _nodes = remap_memory(_nodes, _fd, _s * _nodes_size, _s * _n_nodes); if (ftruncate(_fd, _s * _n_nodes)) { // TODO: this probably creates an index in a corrupt state... not sure what to do showUpdate("Error truncating file: %s\n", strerror(errno)); if (error) *error = strerror(errno); return false; } _nodes_size = _n_nodes; } _built = true; return true; } bool unbuild(char** error=NULL) { if (_loaded) { showUpdate("You can't unbuild a loaded index\n"); if (error) *error = (char *)"You can't unbuild a loaded index"; return false; } _roots.clear(); _n_nodes = _n_items; _built = false; return true; } bool save(const char* filename, bool prefault=false, char** error=NULL) { if (!_built) { showUpdate("You can't save an index that hasn't been built\n"); if (error) *error = (char *)"You can't save an index that hasn't been built"; return false; } if (_on_disk) { return true; } else { // Delete file if it already exists (See issue #335) #ifdef _WIN32 _unlink(filename); #else unlink(filename); #endif printf("path: %s\n", filename); FILE *f = fopen(filename, "wb"); if (f == NULL) { showUpdate("Unable to open: %s\n", strerror(errno)); if (error) *error = strerror(errno); return false; } if (fwrite(_nodes, _s, _n_nodes, f) != (size_t) _n_nodes) { showUpdate("Unable to write: %s\n", strerror(errno)); if (error) *error = strerror(errno); return false; } if (fclose(f) == EOF) { showUpdate("Unable to close: %s\n", strerror(errno)); if (error) *error = strerror(errno); return false; } unload(); return load(filename, prefault, error); } } void reinitialize() { _fd = 0; _nodes = NULL; _loaded = false; _n_items = 0; _n_nodes = 0; _nodes_size = 0; _on_disk = false; _roots.clear(); } void unload() { if (_on_disk && _fd) { #ifdef _WIN32 _close(_fd); #else close(_fd); #endif munmap(_nodes, _s * _nodes_size); } else { if (_fd) { // we have mmapped data #ifdef _WIN32 _close(_fd); #else close(_fd); #endif munmap(_nodes, _n_nodes * _s); } else if (_nodes) { // We have heap allocated data free(_nodes); } } reinitialize(); if (_verbose) showUpdate("unloaded\n"); } bool load(const char* filename, bool prefault=false, char** error=NULL) { #ifdef _WIN32 _fd = _open(filename, O_RDONLY, (int)0400); #else _fd = open(filename, O_RDONLY, (int)0400); #endif if (_fd == -1) { showUpdate("Error: file descriptor is -1\n"); if (error) *error = strerror(errno); _fd = 0; return false; } #ifdef _WIN32 off_t size = _lseek(_fd, 0, SEEK_END); #else off_t size = lseek(_fd, 0, SEEK_END); #endif if (size == -1) { showUpdate("lseek returned -1\n"); if (error) *error = strerror(errno); return false; } else if (size == 0) { showUpdate("Size of file is zero\n"); if (error) *error = (char *)"Size of file is zero"; return false; } else if (size % _s) { // Something is fishy with this index! showUpdate("Error: index size %zu is not a multiple of vector size %zu\n", (size_t)size, _s); if (error) *error = (char *)"Index size is not a multiple of vector size"; return false; } int flags = MAP_SHARED; if (prefault) { #ifdef MAP_POPULATE flags |= MAP_POPULATE; #else showUpdate("prefault is set to true, but MAP_POPULATE is not defined on this platform"); #endif } _nodes = (Node*)mmap(0, size, PROT_READ, flags, _fd, 0); _n_nodes = (S)(size / _s); // Find the roots by scanning the end of the file and taking the nodes with most descendants _roots.clear(); S m = -1; for (S i = _n_nodes - 1; i >= 0; i--) { S k = _get(i)->n_descendants; if (m == -1 || k == m) { _roots.push_back(i); m = k; } else { break; } } // hacky fix: since the last root precedes the copy of all roots, delete it if (_roots.size() > 1 && _get(_roots.front())->children[0] == _get(_roots.back())->children[0]) _roots.pop_back(); _loaded = true; _built = true; _n_items = m; if (_verbose) showUpdate("found %lu roots with degree %d\n", _roots.size(), m); return true; } T get_distance(S i, S j) const { return D::normalized_distance(D::distance(_get(i), _get(j), _f)); } void get_nns_by_item(S item, size_t n, size_t search_k, vector<S>* result, vector<T>* distances) const { // TODO: handle OOB const Node* m = _get(item); _get_all_nns(m->v, n, search_k, result, distances); } void get_nns_by_vector(const T* w, size_t n, size_t search_k, vector<S>* result, vector<T>* distances) const { _get_all_nns(w, n, search_k, result, distances); } S get_n_items() const { return _n_items; } S get_n_trees() const { return _roots.size(); } void verbose(bool v) { _verbose = v; } void get_item(S item, T* v) const { // TODO: handle OOB Node* m = _get(item); memcpy(v, m->v, (_f) * sizeof(T)); } void set_seed(int seed) { _random.set_seed(seed); } protected: void _allocate_size(S n) { if (n > _nodes_size) { const double reallocation_factor = 1.3; S new_nodes_size = std::max(n, (S) ((_nodes_size + 1) * reallocation_factor)); void *old = _nodes; if (_on_disk) { int rc = ftruncate(_fd, _s * new_nodes_size); if (_verbose && rc) showUpdate("File truncation error\n"); _nodes = remap_memory(_nodes, _fd, _s * _nodes_size, _s * new_nodes_size); } else { _nodes = realloc(_nodes, _s * new_nodes_size); memset((char *) _nodes + (_nodes_size * _s) / sizeof(char), 0, (new_nodes_size - _nodes_size) * _s); } _nodes_size = new_nodes_size; if (_verbose) showUpdate("Reallocating to %d nodes: old_address=%p, new_address=%p\n", new_nodes_size, old, _nodes); } } inline Node* _get(const S i) const { return get_node_ptr<S, Node>(_nodes, _s, i); } S _make_tree(const vector<S >& indices, bool is_root) { // The basic rule is that if we have <= _K items, then it's a leaf node, otherwise it's a split node. // There's some regrettable complications caused by the problem that root nodes have to be "special": // 1. We identify root nodes by the arguable logic that _n_items == n->n_descendants, regardless of how many descendants they actually have // 2. Root nodes with only 1 child need to be a "dummy" parent // 3. Due to the _n_items "hack", we need to be careful with the cases where _n_items <= _K or _n_items > _K if (indices.size() == 1 && !is_root) return indices[0]; if (indices.size() <= (size_t)_K && (!is_root || (size_t)_n_items <= (size_t)_K || indices.size() == 1)) { _allocate_size(_n_nodes + 1); S item = _n_nodes++; Node* m = _get(item); m->n_descendants = is_root ? _n_items : (S)indices.size(); // Using std::copy instead of a loop seems to resolve issues #3 and #13, // probably because gcc 4.8 goes overboard with optimizations. // Using memcpy instead of std::copy for MSVC compatibility. #235 // Only copy when necessary to avoid crash in MSVC 9. #293 if (!indices.empty()) memcpy(m->children, &indices[0], indices.size() * sizeof(S)); return item; } vector<Node*> children; for (size_t i = 0; i < indices.size(); i++) { S j = indices[i]; Node* n = _get(j); if (n) children.push_back(n); } vector<S> children_indices[2]; Node* m = (Node*)alloca(_s); D::create_split(children, _f, _s, _random, m); for (size_t i = 0; i < indices.size(); i++) { S j = indices[i]; Node* n = _get(j); if (n) { bool side = D::side(m, n->v, _f, _random); children_indices[side].push_back(j); } else { showUpdate("No node for index %d?\n", j); } } // If we didn't find a hyperplane, just randomize sides as a last option while (children_indices[0].size() == 0 || children_indices[1].size() == 0) { if (_verbose) showUpdate("\tNo hyperplane found (left has %ld children, right has %ld children)\n", children_indices[0].size(), children_indices[1].size()); if (_verbose && indices.size() > 100000) showUpdate("Failed splitting %lu items\n", indices.size()); children_indices[0].clear(); children_indices[1].clear(); // Set the vector to 0.0 for (int z = 0; z < _f; z++) m->v[z] = 0.0; for (size_t i = 0; i < indices.size(); i++) { S j = indices[i]; // Just randomize... children_indices[_random.flip()].push_back(j); } } int flip = (children_indices[0].size() > children_indices[1].size()); m->n_descendants = is_root ? _n_items : (S)indices.size(); for (int side = 0; side < 2; side++) { // run _make_tree for the smallest child first (for cache locality) m->children[side^flip] = _make_tree(children_indices[side^flip], false); } _allocate_size(_n_nodes + 1); S item = _n_nodes++; memcpy(_get(item), m, _s); return item; } void _get_all_nns(const T* v, size_t n, size_t search_k, vector<S>* result, vector<T>* distances) const { Node* v_node = (Node *)alloca(_s); D::template zero_value<Node>(v_node); memcpy(v_node->v, v, sizeof(T) * _f); D::init_node(v_node, _f); std::priority_queue<pair<T, S> > q; if (search_k == (size_t)-1) { search_k = n * _roots.size(); } for (size_t i = 0; i < _roots.size(); i++) { q.push(make_pair(Distance::template pq_initial_value<T>(), _roots[i])); } std::vector<S> nns; while (nns.size() < search_k && !q.empty()) { const pair<T, S>& top = q.top(); T d = top.first; S i = top.second; Node* nd = _get(i); q.pop(); if (nd->n_descendants == 1 && i < _n_items) { nns.push_back(i); } else if (nd->n_descendants <= _K) { const S* dst = nd->children; nns.insert(nns.end(), dst, &dst[nd->n_descendants]); } else { T margin = D::margin(nd, v, _f); q.push(make_pair(D::pq_distance(d, margin, 1), static_cast<S>(nd->children[1]))); q.push(make_pair(D::pq_distance(d, margin, 0), static_cast<S>(nd->children[0]))); } } // Get distances for all items // To avoid calculating distance multiple times for any items, sort by id std::sort(nns.begin(), nns.end()); vector<pair<T, S> > nns_dist; S last = -1; for (size_t i = 0; i < nns.size(); i++) { S j = nns[i]; if (j == last) continue; last = j; if (_get(j)->n_descendants == 1) // This is only to guard a really obscure case, #284 nns_dist.push_back(make_pair(D::distance(v_node, _get(j), _f), j)); } size_t m = nns_dist.size(); size_t p = n < m ? n : m; // Return this many items std::partial_sort(nns_dist.begin(), nns_dist.begin() + p, nns_dist.end()); for (size_t i = 0; i < p; i++) { if (distances) distances->push_back(D::normalized_distance(nns_dist[i].first)); result->push_back(nns_dist[i].second); } } }; #endif // vim: tabstop=2 shiftwidth=2
40,303
29.303759
143
h
FIt-SNE
FIt-SNE-master/src/kissrandom.h
#ifndef KISSRANDOM_H #define KISSRANDOM_H #if defined(_MSC_VER) && _MSC_VER == 1500 typedef unsigned __int32 uint32_t; typedef unsigned __int64 uint64_t; #else #include <stdint.h> #endif // KISS = "keep it simple, stupid", but high quality random number generator // http://www0.cs.ucl.ac.uk/staff/d.jones/GoodPracticeRNG.pdf -> "Use a good RNG and build it into your code" // http://mathforum.org/kb/message.jspa?messageID=6627731 // https://de.wikipedia.org/wiki/KISS_(Zufallszahlengenerator) // 32 bit KISS struct Kiss32Random { uint32_t x; uint32_t y; uint32_t z; uint32_t c; // seed must be != 0 Kiss32Random(uint32_t seed = 123456789) { x = seed; y = 362436000; z = 521288629; c = 7654321; } uint32_t kiss() { // Linear congruence generator x = 69069 * x + 12345; // Xor shift y ^= y << 13; y ^= y >> 17; y ^= y << 5; // Multiply-with-carry uint64_t t = 698769069ULL * z + c; c = t >> 32; z = (uint32_t) t; return x + y + z; } inline int flip() { // Draw random 0 or 1 return kiss() & 1; } inline size_t index(size_t n) { // Draw random integer between 0 and n-1 where n is at most the number of data points you have return kiss() % n; } inline void set_seed(uint32_t seed) { x = seed; } }; // 64 bit KISS. Use this if you have more than about 2^24 data points ("big data" ;) ) struct Kiss64Random { uint64_t x; uint64_t y; uint64_t z; uint64_t c; // seed must be != 0 Kiss64Random(uint64_t seed = 1234567890987654321ULL) { x = seed; y = 362436362436362436ULL; z = 1066149217761810ULL; c = 123456123456123456ULL; } uint64_t kiss() { // Linear congruence generator z = 6906969069LL*z+1234567; // Xor shift y ^= (y<<13); y ^= (y>>17); y ^= (y<<43); // Multiply-with-carry (uint128_t t = (2^58 + 1) * x + c; c = t >> 64; x = (uint64_t) t) uint64_t t = (x<<58)+c; c = (x>>6); x += t; c += (x<t); return x + y + z; } inline int flip() { // Draw random 0 or 1 return kiss() & 1; } inline size_t index(size_t n) { // Draw random integer between 0 and n-1 where n is at most the number of data points you have return kiss() % n; } inline void set_seed(uint32_t seed) { x = seed; } }; #endif // vim: tabstop=2 shiftwidth=2
2,365
21.11215
109
h
FIt-SNE
FIt-SNE-master/src/nbodyfft.cpp
#include "winlibs/stdafx.h" #include "parallel_for.h" #include "time_code.h" #include "nbodyfft.h" void precompute_2d(double x_max, double x_min, double y_max, double y_min, int n_boxes, int n_interpolation_points, kernel_type_2d kernel, double *box_lower_bounds, double *box_upper_bounds, double *y_tilde_spacings, double *y_tilde, double *x_tilde, complex<double> *fft_kernel_tilde, double df ) { /* * Set up the boxes */ int n_total_boxes = n_boxes * n_boxes; double box_width = (x_max - x_min) / (double) n_boxes; // Left and right bounds of each box, first the lower bounds in the x direction, then in the y direction for (int i = 0; i < n_boxes; i++) { for (int j = 0; j < n_boxes; j++) { box_lower_bounds[i * n_boxes + j] = j * box_width + x_min; box_upper_bounds[i * n_boxes + j] = (j + 1) * box_width + x_min; box_lower_bounds[n_total_boxes + i * n_boxes + j] = i * box_width + y_min; box_upper_bounds[n_total_boxes + i * n_boxes + j] = (i + 1) * box_width + y_min; } } // Coordinates of each (equispaced) interpolation node for a single box double h = 1 / (double) n_interpolation_points; y_tilde_spacings[0] = h / 2; for (int i = 1; i < n_interpolation_points; i++) { y_tilde_spacings[i] = y_tilde_spacings[i - 1] + h; } // Coordinates of all the equispaced interpolation points int n_interpolation_points_1d = n_interpolation_points * n_boxes; int n_fft_coeffs = 2 * n_interpolation_points_1d; h = h * box_width; x_tilde[0] = x_min + h / 2; y_tilde[0] = y_min + h / 2; for (int i = 1; i < n_interpolation_points_1d; i++) { x_tilde[i] = x_tilde[i - 1] + h; y_tilde[i] = y_tilde[i - 1] + h; } /* * Evaluate the kernel at the interpolation nodes and form the embedded generating kernel vector for a circulant * matrix */ auto *kernel_tilde = new double[n_fft_coeffs * n_fft_coeffs](); for (int i = 0; i < n_interpolation_points_1d; i++) { for (int j = 0; j < n_interpolation_points_1d; j++) { double tmp = kernel(y_tilde[0], x_tilde[0], y_tilde[i], x_tilde[j],df ); kernel_tilde[(n_interpolation_points_1d + i) * n_fft_coeffs + (n_interpolation_points_1d + j)] = tmp; kernel_tilde[(n_interpolation_points_1d - i) * n_fft_coeffs + (n_interpolation_points_1d + j)] = tmp; kernel_tilde[(n_interpolation_points_1d + i) * n_fft_coeffs + (n_interpolation_points_1d - j)] = tmp; kernel_tilde[(n_interpolation_points_1d - i) * n_fft_coeffs + (n_interpolation_points_1d - j)] = tmp; } } // Precompute the FFT of the kernel generating matrix fftw_plan p = fftw_plan_dft_r2c_2d(n_fft_coeffs, n_fft_coeffs, kernel_tilde, reinterpret_cast<fftw_complex *>(fft_kernel_tilde), FFTW_ESTIMATE); fftw_execute(p); fftw_destroy_plan(p); delete[] kernel_tilde; } void n_body_fft_2d(int N, int n_terms, double *xs, double *ys, double *chargesQij, int n_boxes, int n_interpolation_points, double *box_lower_bounds, double *box_upper_bounds, double *y_tilde_spacings, complex<double> *fft_kernel_tilde, double *potentialQij, unsigned int nthreads) { int n_total_boxes = n_boxes * n_boxes; int total_interpolation_points = n_total_boxes * n_interpolation_points * n_interpolation_points; double coord_min = box_lower_bounds[0]; double box_width = box_upper_bounds[0] - box_lower_bounds[0]; auto *point_box_idx = new int[N]; // Determine which box each point belongs to for (int i = 0; i < N; i++) { auto x_idx = static_cast<int>((xs[i] - coord_min) / box_width); auto y_idx = static_cast<int>((ys[i] - coord_min) / box_width); // TODO: Figure out how on earth x_idx can be less than zero... // It's probably something to do with the fact that we use the single lowest coord for both dims? Probably not // this, more likely negative 0 if rounding errors if (x_idx >= n_boxes) { x_idx = n_boxes - 1; } else if (x_idx < 0) { x_idx = 0; } if (y_idx >= n_boxes) { y_idx = n_boxes - 1; } else if (y_idx < 0) { y_idx = 0; } point_box_idx[i] = y_idx * n_boxes + x_idx; } // Compute the relative position of each point in its box in the interval [0, 1] auto *x_in_box = new double[N]; auto *y_in_box = new double[N]; for (int i = 0; i < N; i++) { int box_idx = point_box_idx[i]; double x_min = box_lower_bounds[box_idx]; double y_min = box_lower_bounds[n_total_boxes + box_idx]; x_in_box[i] = (xs[i] - x_min) / box_width; y_in_box[i] = (ys[i] - y_min) / box_width; } INITIALIZE_TIME START_TIME /* * Step 1: Interpolate kernel using Lagrange polynomials and compute the w coefficients */ // Compute the interpolated values at each real point with each Lagrange polynomial in the `x` direction auto *x_interpolated_values = new double[N * n_interpolation_points]; interpolate(n_interpolation_points, N, x_in_box, y_tilde_spacings, x_interpolated_values); // Compute the interpolated values at each real point with each Lagrange polynomial in the `y` direction auto *y_interpolated_values = new double[N * n_interpolation_points]; interpolate(n_interpolation_points, N, y_in_box, y_tilde_spacings, y_interpolated_values); auto *w_coefficients = new double[total_interpolation_points * n_terms](); for (int i = 0; i < N; i++) { int box_idx = point_box_idx[i]; int box_j = box_idx / n_boxes; int box_i = box_idx % n_boxes; for (int interp_i = 0; interp_i < n_interpolation_points; interp_i++) { for (int interp_j = 0; interp_j < n_interpolation_points; interp_j++) { // Compute the index of the point in the interpolation grid of points int idx = (box_i * n_interpolation_points + interp_i) * (n_boxes * n_interpolation_points) + (box_j * n_interpolation_points) + interp_j; for (int d = 0; d < n_terms; d++) { w_coefficients[idx * n_terms + d] += y_interpolated_values[interp_j * N + i] * x_interpolated_values[interp_i * N + i] * chargesQij[i * n_terms + d]; } } } } END_TIME("Step 1"); START_TIME; /* * Step 2: Compute the values v_{m, n} at the equispaced nodes, multiply the kernel matrix with the coefficients w */ auto *y_tilde_values = new double[total_interpolation_points * n_terms](); int n_fft_coeffs_half = n_interpolation_points * n_boxes; int n_fft_coeffs = 2 * n_interpolation_points * n_boxes; auto *mpol_sort = new double[total_interpolation_points]; // FFT of fft_input auto *fft_input = new double[n_fft_coeffs * n_fft_coeffs](); auto *fft_w_coefficients = new complex<double>[n_fft_coeffs * (n_fft_coeffs / 2 + 1)]; auto *fft_output = new double[n_fft_coeffs * n_fft_coeffs](); fftw_plan plan_dft, plan_idft; plan_dft = fftw_plan_dft_r2c_2d(n_fft_coeffs, n_fft_coeffs, fft_input, reinterpret_cast<fftw_complex *>(fft_w_coefficients), FFTW_ESTIMATE); plan_idft = fftw_plan_dft_c2r_2d(n_fft_coeffs, n_fft_coeffs, reinterpret_cast<fftw_complex *>(fft_w_coefficients), fft_output, FFTW_ESTIMATE); for (int d = 0; d < n_terms; d++) { for (int i = 0; i < total_interpolation_points; i++) { mpol_sort[i] = w_coefficients[i * n_terms + d]; } for (int i = 0; i < n_fft_coeffs_half; i++) { for (int j = 0; j < n_fft_coeffs_half; j++) { fft_input[i * n_fft_coeffs + j] = mpol_sort[i * n_fft_coeffs_half + j]; } } fftw_execute(plan_dft); // Take the Hadamard product of two complex vectors for (int i = 0; i < n_fft_coeffs * (n_fft_coeffs / 2 + 1); i++) { double x_ = fft_w_coefficients[i].real(); double y_ = fft_w_coefficients[i].imag(); double u_ = fft_kernel_tilde[i].real(); double v_ = fft_kernel_tilde[i].imag(); fft_w_coefficients[i].real(x_ * u_ - y_ * v_); fft_w_coefficients[i].imag(x_ * v_ + y_ * u_); } // Invert the computed values at the interpolated nodes fftw_execute(plan_idft); for (int i = 0; i < n_fft_coeffs_half; i++) { for (int j = 0; j < n_fft_coeffs_half; j++) { int row = n_fft_coeffs_half + i; int col = n_fft_coeffs_half + j; // FFTW doesn't perform IDFT normalization, so we have to do it ourselves. This is done by dividing // the result with the number of points in the input mpol_sort[i * n_fft_coeffs_half + j] = fft_output[row * n_fft_coeffs + col] / (double) (n_fft_coeffs * n_fft_coeffs); } } for (int i = 0; i < n_fft_coeffs_half * n_fft_coeffs_half; i++) { y_tilde_values[i * n_terms + d] = mpol_sort[i]; } } fftw_destroy_plan(plan_dft); fftw_destroy_plan(plan_idft); delete[] fft_w_coefficients; delete[] fft_input; delete[] fft_output; delete[] mpol_sort; END_TIME("FFT"); START_TIME /* * Step 3: Compute the potentials \tilde{\phi} */ PARALLEL_FOR(nthreads,N, { int box_idx = point_box_idx[loop_i]; int box_i = box_idx % n_boxes; int box_j = box_idx / n_boxes; for (int interp_i = 0; interp_i < n_interpolation_points; interp_i++) { for (int interp_j = 0; interp_j < n_interpolation_points; interp_j++) { for (int d = 0; d < n_terms; d++) { // Compute the index of the point in the interpolation grid of points int idx = (box_i * n_interpolation_points + interp_i) * (n_boxes * n_interpolation_points) + (box_j * n_interpolation_points) + interp_j; potentialQij[loop_i * n_terms + d] += x_interpolated_values[interp_i * N + loop_i] * y_interpolated_values[interp_j * N + loop_i] * y_tilde_values[idx * n_terms + d]; } } } }); END_TIME("Step 3"); delete[] point_box_idx; delete[] x_interpolated_values; delete[] y_interpolated_values; delete[] w_coefficients; delete[] y_tilde_values; delete[] x_in_box; delete[] y_in_box; } void precompute(double y_min, double y_max, int n_boxes, int n_interpolation_points, kernel_type kernel, double *box_lower_bounds, double *box_upper_bounds, double *y_tilde_spacing, double *y_tilde, complex<double> *fft_kernel_vector, double df) { /* * Set up the boxes */ double box_width = (y_max - y_min) / (double) n_boxes; // Compute the left and right bounds of each box for (int box_idx = 0; box_idx < n_boxes; box_idx++) { box_lower_bounds[box_idx] = box_idx * box_width + y_min; box_upper_bounds[box_idx] = (box_idx + 1) * box_width + y_min; } int total_interpolation_points = n_interpolation_points * n_boxes; // Coordinates of each equispaced interpolation point for a single box. This equally spaces them between [0, 1] // with equal space between the points and half that space between the boundary point and the closest boundary point // e.g. [0.1, 0.3, 0.5, 0.7, 0.9] with spacings [0.1, 0.2, 0.2, 0.2, 0.2, 0.1], respectively. This ensures that the // nodes will still be equispaced across box boundaries double h = 1 / (double) n_interpolation_points; y_tilde_spacing[0] = h / 2; for (int i = 1; i < n_interpolation_points; i++) { y_tilde_spacing[i] = y_tilde_spacing[i - 1] + h; } // Coordinates of all the equispaced interpolation points h = h * box_width; y_tilde[0] = y_min + h / 2; for (int i = 1; i < total_interpolation_points; i++) { y_tilde[i] = y_tilde[i - 1] + h; } /* * Evaluate the kernel at the interpolation nodes and form the embedded generating kernel vector for a circulant * matrix */ auto *kernel_vector = new complex<double>[2 * total_interpolation_points](); // Compute the generating vector x between points K(y_i, y_j) where i = 0, j = 0:N-1 // [0 0 0 0 0 5 4 3 2 1] for linear kernel // This evaluates the Cauchy kernel centered on y_tilde[0] to all the other points for (int i = 0; i < total_interpolation_points; i++) { kernel_vector[total_interpolation_points + i].real(kernel(y_tilde[0], y_tilde[i], df)); } // This part symmetrizes the vector, this embeds the Toeplitz generating vector into the circulant generating vector // but also has the nice property of symmetrizing the Cauchy kernel, which is probably planned // [0 1 2 3 4 5 4 3 2 1] for linear kernel for (int i = 1; i < total_interpolation_points; i++) { kernel_vector[i].real(kernel_vector[2 * total_interpolation_points - i].real()); } // Precompute the FFT of the kernel generating vector fftw_plan p = fftw_plan_dft_1d(2 * total_interpolation_points, reinterpret_cast<fftw_complex *>(kernel_vector), reinterpret_cast<fftw_complex *>(fft_kernel_vector), FFTW_FORWARD, FFTW_ESTIMATE); fftw_execute(p); fftw_destroy_plan(p); delete[] kernel_vector; } void interpolate(int n_interpolation_points, int N, const double *y_in_box, const double *y_tilde_spacings, double *interpolated_values) { // The denominators are the same across the interpolants, so we only need to compute them once auto *denominator = new double[n_interpolation_points]; for (int i = 0; i < n_interpolation_points; i++) { denominator[i] = 1; for (int j = 0; j < n_interpolation_points; j++) { if (i != j) { denominator[i] *= y_tilde_spacings[i] - y_tilde_spacings[j]; } } } // Compute the numerators and the interpolant value for (int i = 0; i < N; i++) { for (int j = 0; j < n_interpolation_points; j++) { interpolated_values[j * N + i] = 1; for (int k = 0; k < n_interpolation_points; k++) { if (j != k) { interpolated_values[j * N + i] *= y_in_box[i] - y_tilde_spacings[k]; } } interpolated_values[j * N + i] /= denominator[j]; } } delete[] denominator; } void nbodyfft(int N, int n_terms, double *Y, double *chargesQij, int n_boxes, int n_interpolation_points, double *box_lower_bounds, double *box_upper_bounds, double *y_tilde_spacings, double *y_tilde, complex<double> *fft_kernel_vector, double *potentialsQij) { int total_interpolation_points = n_interpolation_points * n_boxes; double coord_min = box_lower_bounds[0]; double box_width = box_upper_bounds[0] - box_lower_bounds[0]; // Determine which box each point belongs to auto *point_box_idx = new int[N]; for (int i = 0; i < N; i++) { auto box_idx = static_cast<int>((Y[i] - coord_min) / box_width); // The right most point maps directly into `n_boxes`, while it should belong to the last box if (box_idx >= n_boxes) { box_idx = n_boxes - 1; } point_box_idx[i] = box_idx; } // Compute the relative position of each point in its box in the interval [0, 1] auto *y_in_box = new double[N]; for (int i = 0; i < N; i++) { int box_idx = point_box_idx[i]; double box_min = box_lower_bounds[box_idx]; y_in_box[i] = (Y[i] - box_min) / box_width; } /* * Step 1: Interpolate kernel using Lagrange polynomials and compute the w coefficients */ // Compute the interpolated values at each real point with each Lagrange polynomial auto *interpolated_values = new double[n_interpolation_points * N]; interpolate(n_interpolation_points, N, y_in_box, y_tilde_spacings, interpolated_values); auto *w_coefficients = new double[total_interpolation_points * n_terms](); for (int i = 0; i < N; i++) { int box_idx = point_box_idx[i] * n_interpolation_points; for (int interp_idx = 0; interp_idx < n_interpolation_points; interp_idx++) { for (int d = 0; d < n_terms; d++) { w_coefficients[(box_idx + interp_idx) * n_terms + d] += interpolated_values[interp_idx * N + i] * chargesQij[i * n_terms + d]; } } } // `embedded_w_coefficients` is just a vector of zeros prepended to `w_coefficients`, this (probably) matches the // dimensions of the kernel matrix K and since we embedded the generating vector by prepending values, we have to do // the same here auto *embedded_w_coefficients = new double[2 * total_interpolation_points * n_terms](); for (int i = 0; i < total_interpolation_points; i++) { for (int d = 0; d < n_terms; d++) { embedded_w_coefficients[(total_interpolation_points + i) * n_terms + d] = w_coefficients[i * n_terms + d]; } } /* * Step 2: Compute the values v_{m, n} at the equispaced nodes, multiply the kernel matrix with the coefficients w */ auto *fft_w_coefficients = new complex<double>[2 * total_interpolation_points]; auto *y_tilde_values = new double[total_interpolation_points * n_terms](); fftw_plan plan_dft, plan_idft; plan_dft = fftw_plan_dft_1d(2 * total_interpolation_points, reinterpret_cast<fftw_complex *>(fft_w_coefficients), reinterpret_cast<fftw_complex *>(fft_w_coefficients), FFTW_FORWARD, FFTW_ESTIMATE); plan_idft = fftw_plan_dft_1d(2 * total_interpolation_points, reinterpret_cast<fftw_complex *>(fft_w_coefficients), reinterpret_cast<fftw_complex *>(fft_w_coefficients), FFTW_BACKWARD, FFTW_ESTIMATE); for (int d = 0; d < n_terms; d++) { for (int i = 0; i < 2 * total_interpolation_points; i++) { fft_w_coefficients[i].real(embedded_w_coefficients[i * n_terms + d]); } fftw_execute(plan_dft); // Take the Hadamard product of two complex vectors for (int i = 0; i < 2 * total_interpolation_points; i++) { double x_ = fft_w_coefficients[i].real(); double y_ = fft_w_coefficients[i].imag(); double u_ = fft_kernel_vector[i].real(); double v_ = fft_kernel_vector[i].imag(); fft_w_coefficients[i].real(x_ * u_ - y_ * v_); fft_w_coefficients[i].imag(x_ * v_ + y_ * u_); } // Invert the computed values at the interpolated nodes, unfortunate naming but it's better to do IDFT inplace fftw_execute(plan_idft); for (int i = 0; i < total_interpolation_points; i++) { // FFTW doesn't perform IDFT normalization, so we have to do it ourselves. This is done by multiplying the // result with the number of points in the input y_tilde_values[i * n_terms + d] = fft_w_coefficients[i].real() / (total_interpolation_points * 2.0); } } fftw_destroy_plan(plan_dft); fftw_destroy_plan(plan_idft); delete[] fft_w_coefficients; /* * Step 3: Compute the potentials \tilde{\phi} */ for (int i = 0; i < N; i++) { int box_idx = point_box_idx[i] * n_interpolation_points; for (int j = 0; j < n_interpolation_points; j++) { for (int d = 0; d < n_terms; d++) { potentialsQij[i * n_terms + d] += interpolated_values[j * N + i] * y_tilde_values[(box_idx + j) * n_terms + d]; } } } delete[] point_box_idx; delete[] y_in_box; delete[] interpolated_values; delete[] w_coefficients; delete[] y_tilde_values; delete[] embedded_w_coefficients; }
20,456
43.861842
126
cpp
FIt-SNE
FIt-SNE-master/src/nbodyfft.h
#ifndef NBODYFFT_H #define NBODYFFT_H #ifdef _WIN32 #include "winlibs/fftw3.h" #else #include <fftw3.h> #endif #include <complex> using namespace std; typedef double (*kernel_type)(double, double, double); typedef double (*kernel_type_2d)(double, double, double, double, double); void precompute_2d(double x_max, double x_min, double y_max, double y_min, int n_boxes, int n_interpolation_points, kernel_type_2d kernel, double *box_lower_bounds, double *box_upper_bounds, double *y_tilde_spacings, double *y_tilde, double *x_tilde, complex<double> *fft_kernel_tilde, double df); void n_body_fft_2d(int N, int n_terms, double *xs, double *ys, double *chargesQij, int n_boxes, int n_interpolation_points, double *box_lower_bounds, double *box_upper_bounds, double *y_tilde_spacings, complex<double> *fft_kernel_tilde, double *potentialQij, unsigned int nthreads); void precompute(double y_min, double y_max, int n_boxes, int n_interpolation_points, kernel_type kernel, double *box_lower_bounds, double *box_upper_bounds, double *y_tilde_spacing, double *y_tilde, complex<double> *fft_kernel_vector, double df); void nbodyfft(int N, int n_terms, double *Y, double *chargesQij, int n_boxes, int n_interpolation_points, double *box_lower_bounds, double *box_upper_bounds, double *y_tilde_spacings, double *y_tilde, complex<double> *fft_kernel_vector, double *potentialsQij); void interpolate(int n_interpolation_points, int N, const double *y_in_box, const double *y_tilde_spacings, double *interpolated_values); #endif
1,677
44.351351
125
h
FIt-SNE
FIt-SNE-master/src/parallel_for.h
#ifndef PARALLEL_FOR_H #define PARALLEL_FOR_H #include<algorithm> #include <functional> #include <thread> #include <vector> #if defined(_OPENMP) #pragma message "Using OpenMP threading." #define PARALLEL_FOR(nthreads,LOOP_END,O) { \ if (nthreads >1 ) { \ _Pragma("omp parallel num_threads(nthreads)") \ { \ _Pragma("omp for") \ for (int loop_i=0; loop_i<LOOP_END; loop_i++) { \ O; \ } \ } \ }else{ \ for (int loop_i=0; loop_i<LOOP_END; loop_i++) { \ O; \ } \ } \ } #else #define PARALLEL_FOR(nthreads,LOOP_END,O) { \ if (nthreads >1 ) { \ std::vector<std::thread> threads(nthreads); \ for (int t = 0; t < nthreads; t++) { \ threads[t] = std::thread(std::bind( \ [&](const int bi, const int ei, const int t) { \ for(int loop_i = bi;loop_i<ei;loop_i++) { O; } \ },t*LOOP_END/nthreads,(t+1)==nthreads?LOOP_END:(t+1)*LOOP_END/nthreads,t)); \ } \ std::for_each(threads.begin(),threads.end(),[](std::thread& x){x.join();});\ }else{ \ for (int loop_i=0; loop_i<LOOP_END; loop_i++) { \ O; \ } \ } \ } #endif #endif
1,222
26.177778
83
h
FIt-SNE
FIt-SNE-master/src/sptree.cpp
/* * * Copyright (c) 2014, Laurens van der Maaten (Delft University of Technology) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the Delft University of Technology. * 4. Neither the name of the Delft University of Technology nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY LAURENS VAN DER MAATEN ''AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL LAURENS VAN DER MAATEN BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * */ #include "winlibs/stdafx.h" #include <math.h> #include <float.h> #include <stdlib.h> #include <stdio.h> #include <cmath> #include "sptree.h" #include "parallel_for.h" // Constructs cell Cell::Cell(unsigned int inp_dimension) { dimension = inp_dimension; corner = (double *) malloc(dimension * sizeof(double)); width = (double *) malloc(dimension * sizeof(double)); } Cell::Cell(unsigned int inp_dimension, double *inp_corner, double *inp_width) { dimension = inp_dimension; corner = (double *) malloc(dimension * sizeof(double)); width = (double *) malloc(dimension * sizeof(double)); for (int d = 0; d < dimension; d++) setCorner(d, inp_corner[d]); for (int d = 0; d < dimension; d++) setWidth(d, inp_width[d]); } // Destructs cell Cell::~Cell() { free(corner); free(width); } double Cell::getCorner(unsigned int d) { return corner[d]; } double Cell::getWidth(unsigned int d) { return width[d]; } void Cell::setCorner(unsigned int d, double val) { corner[d] = val; } void Cell::setWidth(unsigned int d, double val) { width[d] = val; } // Checks whether a point lies in a cell bool Cell::containsPoint(double point[]) { for (int d = 0; d < dimension; d++) { if (corner[d] - width[d] > point[d]) return false; if (corner[d] + width[d] < point[d]) return false; } return true; } // Default constructor for SPTree -- build tree, too! SPTree::SPTree(unsigned int D, double *inp_data, unsigned int N) { // Compute mean, width, and height of current map (boundaries of SPTree) int nD = 0; double *mean_Y = (double *) calloc(D, sizeof(double)); double *min_Y = (double *) malloc(D * sizeof(double)); for (unsigned int d = 0; d < D; d++) min_Y[d] = DBL_MAX; double *max_Y = (double *) malloc(D * sizeof(double)); for (unsigned int d = 0; d < D; d++) max_Y[d] = -DBL_MAX; for (unsigned int n = 0; n < N; n++) { for (unsigned int d = 0; d < D; d++) { mean_Y[d] += inp_data[n * D + d]; if (inp_data[nD + d] < min_Y[d]) min_Y[d] = inp_data[nD + d]; if (inp_data[nD + d] > max_Y[d]) max_Y[d] = inp_data[nD + d]; } nD += D; } for (int d = 0; d < D; d++) mean_Y[d] /= (double) N; // Construct SPTree double *width = (double *) malloc(D * sizeof(double)); for (int d = 0; d < D; d++) width[d] = fmax(max_Y[d] - mean_Y[d], mean_Y[d] - min_Y[d]) + 1e-5; init(NULL, D, inp_data, mean_Y, width); fill(N); // Clean up memory free(mean_Y); free(max_Y); free(min_Y); free(width); } // Constructor for SPTree with particular size and parent -- build the tree, too! SPTree::SPTree(unsigned int D, double *inp_data, unsigned int N, double *inp_corner, double *inp_width) { init(NULL, D, inp_data, inp_corner, inp_width); fill(N); } // Constructor for SPTree with particular size (do not fill the tree) SPTree::SPTree(unsigned int D, double *inp_data, double *inp_corner, double *inp_width) { init(NULL, D, inp_data, inp_corner, inp_width); } // Constructor for SPTree with particular size and parent (do not fill tree) SPTree::SPTree(SPTree *inp_parent, unsigned int D, double *inp_data, double *inp_corner, double *inp_width) { init(inp_parent, D, inp_data, inp_corner, inp_width); } // Constructor for SPTree with particular size and parent -- build the tree, too! SPTree::SPTree(SPTree *inp_parent, unsigned int D, double *inp_data, unsigned int N, double *inp_corner, double *inp_width) { init(inp_parent, D, inp_data, inp_corner, inp_width); fill(N); } // Main initialization function void SPTree::init(SPTree *inp_parent, unsigned int D, double *inp_data, double *inp_corner, double *inp_width) { parent = inp_parent; dimension = D; no_children = 2; for (unsigned int d = 1; d < D; d++) no_children *= 2; data = inp_data; is_leaf = true; size = 0; cum_size = 0; boundary = new Cell(dimension); for (unsigned int d = 0; d < D; d++) boundary->setCorner(d, inp_corner[d]); for (unsigned int d = 0; d < D; d++) boundary->setWidth(d, inp_width[d]); children = (SPTree **) malloc(no_children * sizeof(SPTree *)); for (unsigned int i = 0; i < no_children; i++) children[i] = NULL; center_of_mass = (double *) malloc(D * sizeof(double)); for (unsigned int d = 0; d < D; d++) center_of_mass[d] = .0; } // Destructor for SPTree SPTree::~SPTree() { for (unsigned int i = 0; i < no_children; i++) { if (children[i] != NULL) delete children[i]; } free(children); free(center_of_mass); delete boundary; } // Update the data underlying this tree void SPTree::setData(double *inp_data) { data = inp_data; } // Get the parent of the current tree SPTree *SPTree::getParent() { return parent; } // Insert a point into the SPTree bool SPTree::insert(unsigned int new_index) { // Ignore objects which do not belong in this quad tree double *point = data + new_index * dimension; if (!boundary->containsPoint(point)) return false; // Online update of cumulative size and center-of-mass cum_size++; double mult1 = (double) (cum_size - 1) / (double) cum_size; double mult2 = 1.0 / (double) cum_size; for (unsigned int d = 0; d < dimension; d++) center_of_mass[d] *= mult1; for (unsigned int d = 0; d < dimension; d++) center_of_mass[d] += mult2 * point[d]; // If there is space in this quad tree and it is a leaf, add the object here if (is_leaf && size < QT_NODE_CAPACITY) { index[size] = new_index; size++; return true; } // Don't add duplicates for now (this is not very nice) bool any_duplicate = false; for (unsigned int n = 0; n < size; n++) { bool duplicate = true; for (unsigned int d = 0; d < dimension; d++) { if (point[d] != data[index[n] * dimension + d]) { duplicate = false; break; } } any_duplicate = any_duplicate | duplicate; } if (any_duplicate) return true; // Otherwise, we need to subdivide the current cell if (is_leaf) subdivide(); // Find out where the point can be inserted for (unsigned int i = 0; i < no_children; i++) { if (children[i]->insert(new_index)) return true; } // Otherwise, the point cannot be inserted (this should never happen) return false; } // Create four children which fully divide this cell into four quads of equal area void SPTree::subdivide() { // Create new children double *new_corner = (double *) malloc(dimension * sizeof(double)); double *new_width = (double *) malloc(dimension * sizeof(double)); for (unsigned int i = 0; i < no_children; i++) { unsigned int div = 1; for (unsigned int d = 0; d < dimension; d++) { new_width[d] = .5 * boundary->getWidth(d); if ((i / div) % 2 == 1) new_corner[d] = boundary->getCorner(d) - .5 * boundary->getWidth(d); else new_corner[d] = boundary->getCorner(d) + .5 * boundary->getWidth(d); div *= 2; } children[i] = new SPTree(this, dimension, data, new_corner, new_width); } free(new_corner); free(new_width); // Move existing points to correct children for (unsigned int i = 0; i < size; i++) { bool success = false; for (unsigned int j = 0; j < no_children; j++) { if (!success) success = children[j]->insert(index[i]); } index[i] = -1; } // Empty parent node size = 0; is_leaf = false; } // Build SPTree on dataset void SPTree::fill(unsigned int N) { for (unsigned int i = 0; i < N; i++) insert(i); } // Checks whether the specified tree is correct bool SPTree::isCorrect() { for (unsigned int n = 0; n < size; n++) { double *point = data + index[n] * dimension; if (!boundary->containsPoint(point)) return false; } if (!is_leaf) { bool correct = true; for (int i = 0; i < no_children; i++) correct = correct && children[i]->isCorrect(); return correct; } else return true; } // Build a list of all indices in SPTree void SPTree::getAllIndices(unsigned int *indices) { getAllIndices(indices, 0); } // Build a list of all indices in SPTree unsigned int SPTree::getAllIndices(unsigned int *indices, unsigned int loc) { // Gather indices in current quadrant for (unsigned int i = 0; i < size; i++) indices[loc + i] = index[i]; loc += size; // Gather indices in children if (!is_leaf) { for (int i = 0; i < no_children; i++) loc = children[i]->getAllIndices(indices, loc); } return loc; } unsigned int SPTree::getDepth() { if (is_leaf) return 1; int depth = 0; for (unsigned int i = 0; i < no_children; i++) depth = fmax(depth, children[i]->getDepth()); return 1 + depth; } // Compute non-edge forces using Barnes-Hut algorithm void SPTree::computeNonEdgeForces(unsigned int point_index, double theta, double neg_f[], double *sum_Q) { // Make sure that we spend no time on empty nodes or self-interactions if (cum_size == 0 || (is_leaf && size == 1 && index[0] == point_index)) return; // Compute distance between point and center-of-mass double D = .0; unsigned int ind = point_index * dimension; for (unsigned int d = 0; d < dimension; d++) D += (data[ind + d] - center_of_mass[d]) * (data[ind + d] - center_of_mass[d]); // Check whether we can use this node as a "summary" double max_width = 0.0; double cur_width; for (unsigned int d = 0; d < dimension; d++) { cur_width = boundary->getWidth(d); max_width = (max_width > cur_width) ? max_width : cur_width; } if (is_leaf || max_width / sqrt(D) < theta) { // Compute and add t-SNE force between point and current node D = 1.0 / (1.0 + D); double mult = cum_size * D; *sum_Q += mult; mult *= D; for (unsigned int d = 0; d < dimension; d++) neg_f[d] += mult * (data[ind + d] - center_of_mass[d]); } else { // Recursively apply Barnes-Hut to children for (unsigned int i = 0; i < no_children; i++) children[i]->computeNonEdgeForces(point_index, theta, neg_f, sum_Q); } } // Computes edge forces void SPTree::computeEdgeForces(unsigned int *row_P, unsigned int *col_P, double *val_P, int N, double *pos_f, unsigned int nthreads) { // Loop over all edges in the graph PARALLEL_FOR(nthreads, N, { unsigned int ind1 = loop_i * dimension; for (unsigned int i = row_P[loop_i]; i < row_P[loop_i + 1]; i++) { // Compute pairwise distance and Q-value double D = 1.0; unsigned int ind2 = col_P[i] * dimension; for (unsigned int d = 0; d < dimension; d++) D += (data[ind1 + d] - data[ind2 + d]) * (data[ind1 + d] - data[ind2 + d]); D = val_P[i] / D; // Sum positive force for (unsigned int d = 0; d < dimension; d++) pos_f[ind1 + d] += D * (data[ind1 + d] - data[ind2 + d]); } }); } // Print out tree void SPTree::print() { if (cum_size == 0) { printf("Empty node\n"); return; } if (is_leaf) { printf("Leaf node; data = ["); for (int i = 0; i < size; i++) { double *point = data + index[i] * dimension; for (int d = 0; d < dimension; d++) printf("%f, ", point[d]); printf(" (index = %d)", index[i]); if (i < size - 1) printf("\n"); else printf("]\n"); } } else { printf("Intersection node with center-of-mass = ["); for (int d = 0; d < dimension; d++) printf("%f, ", center_of_mass[d]); printf("]; children are:\n"); for (int i = 0; i < no_children; i++) children[i]->print(); } }
13,754
33.216418
134
cpp
FIt-SNE
FIt-SNE-master/src/sptree.h
/* * * Copyright (c) 2014, Laurens van der Maaten (Delft University of Technology) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the Delft University of Technology. * 4. Neither the name of the Delft University of Technology nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY LAURENS VAN DER MAATEN ''AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL LAURENS VAN DER MAATEN BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * */ #ifndef SPTREE_H #define SPTREE_H using namespace std; class Cell { unsigned int dimension; double *corner; double *width; public: Cell(unsigned int inp_dimension); Cell(unsigned int inp_dimension, double *inp_corner, double *inp_width); ~Cell(); double getCorner(unsigned int d); double getWidth(unsigned int d); void setCorner(unsigned int d, double val); void setWidth(unsigned int d, double val); bool containsPoint(double point[]); }; class SPTree { // Fixed constants static const unsigned int QT_NODE_CAPACITY = 1; // A buffer we use when doing force computations double *buff; // Properties of this node in the tree SPTree *parent; unsigned int dimension; bool is_leaf; unsigned int size; unsigned int cum_size; // Axis-aligned bounding box stored as a center with half-dimensions to represent the boundaries of this quad tree Cell *boundary; // Indices in this space-partitioning tree node, corresponding center-of-mass, and list of all children double *data; double *center_of_mass; unsigned int index[QT_NODE_CAPACITY]; // Children SPTree **children; unsigned int no_children; public: SPTree(unsigned int D, double *inp_data, unsigned int N); SPTree(unsigned int D, double *inp_data, double *inp_corner, double *inp_width); SPTree(unsigned int D, double *inp_data, unsigned int N, double *inp_corner, double *inp_width); SPTree(SPTree *inp_parent, unsigned int D, double *inp_data, unsigned int N, double *inp_corner, double *inp_width); SPTree(SPTree *inp_parent, unsigned int D, double *inp_data, double *inp_corner, double *inp_width); ~SPTree(); void setData(double *inp_data); SPTree *getParent(); void construct(Cell boundary); bool insert(unsigned int new_index); void subdivide(); bool isCorrect(); void rebuildTree(); void getAllIndices(unsigned int *indices); unsigned int getDepth(); void computeNonEdgeForces(unsigned int point_index, double theta, double neg_f[], double *sum_Q); void computeEdgeForces(unsigned int *row_P, unsigned int *col_P, double *val_P, int N, double *pos_f, unsigned int nthreads); void print(); private: void init(SPTree *inp_parent, unsigned int D, double *inp_data, double *inp_corner, double *inp_width); void fill(unsigned int N); unsigned int getAllIndices(unsigned int *indices, unsigned int loc); bool isChild(unsigned int test_index, unsigned int start, unsigned int end); }; #endif
4,413
30.304965
129
h
FIt-SNE
FIt-SNE-master/src/time_code.h
#ifndef TIME_CODE_H #define TIME_CODE_H #include <chrono> #if defined(TIME_CODE) #pragma message "Timing code" #define INITIALIZE_TIME std::chrono::steady_clock::time_point STARTVAR; #define START_TIME \ STARTVAR = std::chrono::steady_clock::now(); #define END_TIME(LABEL) { \ std::chrono::steady_clock::time_point ENDVAR = std::chrono::steady_clock::now(); \ printf("%s: %ld ms\n",LABEL, std::chrono::duration_cast<std::chrono::milliseconds>(ENDVAR-STARTVAR).count()); \ } #else #define INITIALIZE_TIME #define START_TIME #define END_TIME(LABEL) {} #endif #endif
950
44.285714
133
h
FIt-SNE
FIt-SNE-master/src/tsne.cpp
/* * * Copyright (c) 2014, Laurens van der Maaten (Delft University of Technology) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the Delft University of Technology. * 4. Neither the name of the Delft University of Technology nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY LAURENS VAN DER MAATEN ''AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL LAURENS VAN DER MAATEN BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * */ #include "winlibs/stdafx.h" #ifdef _WIN32 #define _CRT_SECURE_NO_DEPRECATE #endif #include <iostream> #include <fstream> #include "nbodyfft.h" #include <math.h> #include "annoylib.h" #include "kissrandom.h" #include <thread> #include <float.h> #include <cstring> #include "vptree.h" #include "sptree.h" #include "tsne.h" #include "progress_bar/ProgressBar.hpp" #include "parallel_for.h" #include "time_code.h" using namespace std::chrono; #ifdef _WIN32 #include "winlibs/unistd.h" #else #include <unistd.h> #endif #include <functional> #define _CRT_SECURE_NO_WARNINGS int itTest = 0; bool measure_accuracy = false; double squared_cauchy(double x, double y, double df) { return pow(1.0 + pow(x - y, 2), -2); } double general_kernel(double x, double y, double df) { return pow(1.0 + ((x - y)*(x-y) )/df, -(df)); } double squared_general_kernel(double x, double y, double df) { return pow(1.0 + ((x - y)*(x-y) )/df, -(df+1.0)); } double squared_cauchy_2d(double x1, double x2, double y1, double y2,double df) { return pow(1.0 + pow(x1 - y1, 2) + pow(x2 - y2, 2), -2); } double general_kernel_2d(double x1, double x2, double y1, double y2, double df) { return pow(1.0 + ((x1 - y1)*(x1-y1) + (x2 - y2)*(x2-y2))/df, -(df)); } double squared_general_kernel_2d(double x1, double x2, double y1, double y2, double df) { return pow(1.0 + ((x1 - y1)*(x1-y1) + (x2 - y2)*(x2-y2))/df, -(df+1.0)); } using namespace std; //Helper function for printing Y at each iteration. Useful for debugging void print_progress(int iter, double *Y, int N, int no_dims) { ofstream myfile; std::ostringstream stringStream; stringStream << "dat/intermediate" << iter << ".txt"; std::string copyOfStr = stringStream.str(); myfile.open(stringStream.str().c_str()); for (int j = 0; j < N; j++) { for (int i = 0; i < no_dims; i++) { myfile << Y[j * no_dims + i] << " "; } myfile << "\n"; } myfile.close(); } // Perform t-SNE int TSNE::run(double *X, int N, int D, double *Y, int no_dims, double perplexity, double theta, int rand_seed, bool skip_random_init, int max_iter, int stop_lying_iter, int mom_switch_iter, double momentum, double final_momentum, double learning_rate, int K, double sigma, int nbody_algorithm, int knn_algo, double early_exag_coeff, double *costs, bool no_momentum_during_exag, int start_late_exag_iter, double late_exag_coeff, int n_trees, int search_k, int nterms, double intervals_per_integer, int min_num_intervals, unsigned int nthreads, int load_affinities, int perplexity_list_length, double *perplexity_list, double df, double max_step_norm) { // Some logging messages if (N - 1 < 3 * perplexity) { printf("Perplexity too large for the number of data points!\n"); exit(1); } if (no_momentum_during_exag) { printf("No momentum during the exaggeration phase.\n"); } else { printf("Will use momentum during exaggeration phase\n"); } // Determine whether we are using an exact algorithm bool exact = theta == .0; // Allocate some memory auto *dY = (double *) malloc(N * no_dims * sizeof(double)); auto *uY = (double *) malloc(N * no_dims * sizeof(double)); auto *gains = (double *) malloc(N * no_dims * sizeof(double)); if (dY == nullptr || uY == nullptr || gains == nullptr) throw std::bad_alloc(); // Initialize gradient to zeros and gains to ones. for (int i = 0; i < N * no_dims; i++) uY[i] = .0; for (int i = 0; i < N * no_dims; i++) gains[i] = 1.0; printf("Computing input similarities...\n"); zeroMean(X, N, D); if (perplexity > 0 || perplexity_list_length > 0) { printf("Using perplexity, so normalizing input data (to prevent numerical problems)\n"); double max_X = .0; for (unsigned long i = 0; i < N * D; i++) { if (fabs(X[i]) > max_X) max_X = fabs(X[i]); } for (unsigned long i = 0; i < N * D; i++) X[i] /= max_X; } else { printf("Not using perplexity, so data are left un-normalized.\n"); } // Compute input similarities for exact t-SNE double *P = nullptr; unsigned int *row_P = nullptr; unsigned int *col_P = nullptr; double *val_P = nullptr; if (exact) { // Loading input similarities if load_affinities == 1 if (load_affinities == 1) { printf("Loading exact input similarities from file...\n"); P = (double *) malloc(N * N * sizeof(double)); if (P == NULL) { printf("Memory allocation failed!\n"); exit(1); } FILE *h; size_t result; if ((h = fopen("P.dat", "rb")) == NULL) { printf("Error: could not open data file.\n"); return -2; } result = fread(P, sizeof(double), N * N, h); fclose(h); } else { // Compute similarities printf("Theta set to 0, so running exact algorithm\n"); P = (double *) malloc(N * N * sizeof(double)); if (P == NULL) { printf("Memory allocation failed!\n"); exit(1); } computeGaussianPerplexity(X, N, D, P, perplexity, sigma, perplexity_list_length, perplexity_list); // Symmetrize input similarities printf("Symmetrizing...\n"); int nN = 0; for (int n = 0; n < N; n++) { int mN = (n + 1) * N; for (int m = n + 1; m < N; m++) { P[nN + m] += P[mN + n]; P[mN + n] = P[nN + m]; mN += N; } nN += N; } double sum_P = .0; for (int i = 0; i < N * N; i++) sum_P += P[i]; for (int i = 0; i < N * N; i++) P[i] /= sum_P; //sum_P is just a cute way of writing 2N printf("Finished exact calculation of the P. Sum_p: %lf \n", sum_P); } // Saving input similarities if load_affinities == 2 if (load_affinities == 2) { printf("Saving exact input similarities to file...\n"); FILE *h; if ((h = fopen("P.dat", "w+b")) == NULL) { printf("Error: could not open data file.\n"); return -2; } fwrite(P, sizeof(double), N * N, h); fclose(h); } } // Compute input similarities for approximate t-SNE else { // Loading input similarities if load_affinities == 1 if (load_affinities == 1) { printf("Loading approximate input similarities from files...\n"); row_P = (unsigned int *) malloc((N + 1) * sizeof(unsigned int)); if (row_P == NULL) { printf("Memory allocation failed!\n"); exit(1); } FILE *h; size_t result; if ((h = fopen("P_row.dat", "rb")) == NULL) { printf("Error: could not open data file.\n"); return -2; } result = fread(row_P, sizeof(unsigned int), N + 1, h); fclose(h); int numel = row_P[N]; col_P = (unsigned int *) calloc(numel, sizeof(unsigned int)); val_P = (double *) calloc(numel, sizeof(double)); if (col_P == NULL || val_P == NULL) { printf("Memory allocation failed!\n"); exit(1); } if ((h = fopen("P_val.dat", "rb")) == NULL) { printf("Error: could not open data file.\n"); return -2; } result = fread(val_P, sizeof(double), numel, h); fclose(h); if ((h = fopen("P_col.dat", "rb")) == NULL) { printf("Error: could not open data file.\n"); return -2; } result = fread(col_P, sizeof(unsigned int), numel, h); fclose(h); printf(" val_P: %f %f %f ... %f %f %f\n", val_P[0], val_P[1], val_P[2], val_P[numel - 3], val_P[numel - 2], val_P[numel - 1]); printf(" col_P: %d %d %d ... %d %d %d\n", col_P[0], col_P[1], col_P[2], col_P[numel - 3], col_P[numel - 2], col_P[numel - 1]); printf(" row_P: %d %d %d ... %d %d %d\n", row_P[0], row_P[1], row_P[2], row_P[N - 2], row_P[N - 1], row_P[N]); } else { // Compute asymmetric pairwise input similarities int K_to_use; double sigma_to_use; if (perplexity < 0) { printf("Using manually set kernel width\n"); K_to_use = K; sigma_to_use = sigma; } else { printf("Using perplexity, not the manually set kernel width. K (number of nearest neighbors) and sigma (bandwidth) parameters are going to be ignored.\n"); if (perplexity > 0) { K_to_use = (int) 3 * perplexity; } else { K_to_use = (int) 3 * perplexity_list[0]; for (int pp = 1; pp < perplexity_list_length; pp++) { if ((int) 3* perplexity_list[pp] > K_to_use) { K_to_use = (int) 3 * perplexity_list[pp]; } } } sigma_to_use = -1; } if (knn_algo == 1) { printf("Using ANNOY for knn search, with parameters: n_trees %d and search_k %d\n", n_trees, search_k); int error_code = 0; error_code = computeGaussianPerplexity(X, N, D, &row_P, &col_P, &val_P, perplexity, K_to_use, sigma_to_use, n_trees, search_k, nthreads, perplexity_list_length, perplexity_list, rand_seed); if (error_code < 0) return error_code; } else if (knn_algo == 2) { printf("Using VP trees for nearest neighbor search\n"); computeGaussianPerplexity(X, N, D, &row_P, &col_P, &val_P, perplexity, K_to_use, sigma_to_use, nthreads, perplexity_list_length, perplexity_list); } else { printf("Invalid knn_algo param\n"); free(dY); free(uY); free(gains); exit(1); } // Symmetrize input similarities printf("Symmetrizing...\n"); symmetrizeMatrix(&row_P, &col_P, &val_P, N); double sum_P = .0; for (int i = 0; i < row_P[N]; i++) sum_P += val_P[i]; for (int i = 0; i < row_P[N]; i++) val_P[i] /= sum_P; } // Saving input similarities if load_affinities == 2 if (load_affinities == 2) { printf("Saving approximate input similarities to files...\n"); int numel = row_P[N]; FILE *h; if ((h = fopen("P_val.dat", "w+b")) == NULL) { printf("Error: could not open data file.\n"); return -2; } fwrite(val_P, sizeof(double), numel, h); fclose(h); if ((h = fopen("P_col.dat", "w+b")) == NULL) { printf("Error: could not open data file.\n"); return -2; } fwrite(col_P, sizeof(unsigned int), numel, h); fclose(h); if ((h = fopen("P_row.dat", "w+b")) == NULL) { printf("Error: could not open data file.\n"); return -2; } fwrite(row_P, sizeof(unsigned int), N + 1, h); fclose(h); printf(" val_P: %f %f %f ... %f %f %f\n", val_P[0], val_P[1], val_P[2], val_P[numel - 3], val_P[numel - 2], val_P[numel - 1]); printf(" col_P: %d %d %d ... %d %d %d\n", col_P[0], col_P[1], col_P[2], col_P[numel - 3], col_P[numel - 2], col_P[numel - 1]); printf(" row_P: %d %d %d ... %d %d %d\n", row_P[0], row_P[1], row_P[2], row_P[N - 2], row_P[N - 1], row_P[N]); } } // Set random seed if (skip_random_init != true) { if (rand_seed >= 0) { printf("Using random seed: %d\n", rand_seed); srand((unsigned int) rand_seed); } else { printf("Using current time as random seed...\n"); srand(time(NULL)); } } // Initialize solution (randomly) if (skip_random_init != true) { printf("Randomly initializing the solution.\n"); for (int i = 0; i < N * no_dims; i++) Y[i] = randn() * .0001; printf("Y[0] = %lf\n", Y[0]); } else { printf("Using the given initialization.\n"); } // If we are doing early exaggeration, we pre-multiply all the P by the coefficient of early exaggeration double max_sum_cols = 0; // Compute maximum possible exaggeration coefficient, if user requests if (early_exag_coeff == 0) { for (int n = 0; n < N; n++) { double running_sum = 0; for (int i = row_P[n]; i < row_P[n + 1]; i++) { running_sum += val_P[i]; } if (running_sum > max_sum_cols) max_sum_cols = running_sum; } early_exag_coeff = (1.0 / (learning_rate * max_sum_cols)); printf("Max of the val_Ps is: %lf\n", max_sum_cols); } printf("Exaggerating Ps by %f\n", early_exag_coeff); if (exact) { for (int i = 0; i < N * N; i++) { P[i] *= early_exag_coeff; } } else { for (int i = 0; i < row_P[N]; i++) val_P[i] *= early_exag_coeff; } print_progress(0, Y, N, no_dims); // Perform main training loop if (exact) { printf("Input similarities computed \nLearning embedding...\n"); } else { printf("Input similarities computed (sparsity = %f)!\nLearning embedding...\n", (double) row_P[N] / ((double) N * (double) N)); } std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now(); if (!exact) { if (nbody_algorithm == 2) { printf("Using FIt-SNE approximation.\n"); } else if (nbody_algorithm == 1) { printf("Using the Barnes-Hut approximation.\n"); } else { printf("Error: Undefined algorithm"); exit(2); } } for (int iter = 0; iter < max_iter; iter++) { itTest = iter; if (exact) { // Compute the exact gradient using full P matrix computeExactGradient(P, Y, N, no_dims, dY,df); } else { if (nbody_algorithm == 2) { // Use FFT accelerated interpolation based negative gradients if (no_dims == 1) { if (df ==1.0) { computeFftGradientOneD(P, row_P, col_P, val_P, Y, N, no_dims, dY, nterms, intervals_per_integer, min_num_intervals, nthreads); }else { computeFftGradientOneDVariableDf(P, row_P, col_P, val_P, Y, N, no_dims, dY, nterms, intervals_per_integer, min_num_intervals, nthreads,df ); } } else { if (df ==1.0) { computeFftGradient(P, row_P, col_P, val_P, Y, N, no_dims, dY, nterms, intervals_per_integer, min_num_intervals, nthreads); }else { computeFftGradientVariableDf(P, row_P, col_P, val_P, Y, N, no_dims, dY, nterms, intervals_per_integer, min_num_intervals, nthreads,df ); } } } else if (nbody_algorithm == 1) { // Otherwise, compute the negative gradient using the Barnes-Hut approximation computeGradient(P, row_P, col_P, val_P, Y, N, no_dims, dY, theta, nthreads); } } if (measure_accuracy) { computeGradient(P, row_P, col_P, val_P, Y, N, no_dims, dY, theta, nthreads); computeFftGradient(P, row_P, col_P, val_P, Y, N, no_dims, dY, nterms, intervals_per_integer, min_num_intervals, nthreads); computeExactGradientTest(Y, N, no_dims,df); } // We can turn off momentum/gains until after the early exaggeration phase is completed if (no_momentum_during_exag) { if (iter > stop_lying_iter) { for (int i = 0; i < N * no_dims; i++) gains[i] = (sign(dY[i]) != sign(uY[i])) ? (gains[i] + .2) : (gains[i] * .8); for (int i = 0; i < N * no_dims; i++) if (gains[i] < .01) gains[i] = .01; for (int i = 0; i < N * no_dims; i++) uY[i] = momentum * uY[i] - learning_rate * gains[i] * dY[i]; for (int i = 0; i < N * no_dims; i++) Y[i] = Y[i] + uY[i]; } else { // During early exaggeration or compression, no trickery (i.e. no momentum, or gains). Just good old // fashion gradient descent for (int i = 0; i < N * no_dims; i++) Y[i] = Y[i] - dY[i]; } } else { for (int i = 0; i < N * no_dims; i++) gains[i] = (sign(dY[i]) != sign(uY[i])) ? (gains[i] + .2) : (gains[i] * .8); for (int i = 0; i < N * no_dims; i++) if (gains[i] < .01) gains[i] = .01; for (int i = 0; i < N * no_dims; i++) uY[i] = momentum * uY[i] - learning_rate * gains[i] * dY[i]; // Clip the step sizes if max_step_norm is provided if (max_step_norm > 0) { for (int i=0; i<N; i++) { double step = 0; for (int j=0; j<no_dims; j++) { step += uY[i*no_dims + j] * uY[i*no_dims + j]; } step = sqrt(step); if (step > max_step_norm) { for (int j=0; j<no_dims; j++) { uY[i*no_dims + j] *= (max_step_norm/step); } } } } for (int i = 0; i < N * no_dims; i++) Y[i] = Y[i] + uY[i]; } /* // Print step norms (for debugging) double maxstepnorm = 0; for (int i=0; i<N; i++) { double step = 0; for (int j=0; j<no_dims; j++) { step += uY[i*no_dims + j] * uY[i*no_dims + j]; } step = sqrt(step); if (step > maxstepnorm) { maxstepnorm = step; } } printf("%d: %f\n", iter, maxstepnorm); */ // Make solution zero-mean zeroMean(Y, N, no_dims); // Switch off early exaggeration if (iter == stop_lying_iter) { printf("Unexaggerating Ps by %f\n", early_exag_coeff); if (exact) { for (int i = 0; i < N * N; i++) P[i] /= early_exag_coeff; } else { for (int i = 0; i < row_P[N]; i++) val_P[i] /= early_exag_coeff; } } if (iter == start_late_exag_iter) { printf("Exaggerating Ps by %f\n", late_exag_coeff); if (exact) { for (int i = 0; i < N * N; i++) P[i] *= late_exag_coeff; } else { for (int i = 0; i < row_P[N]; i++) val_P[i] *= late_exag_coeff; } } if (iter == mom_switch_iter) momentum = final_momentum; // Print out progress if ((iter+1) % 50 == 0 || iter == max_iter - 1) { INITIALIZE_TIME; START_TIME; double C = .0; if (exact) { C = evaluateError(P, Y, N, no_dims,df); }else{ if (nbody_algorithm == 2) { C = evaluateErrorFft(row_P, col_P, val_P, Y, N, no_dims,nthreads,df); }else { C = evaluateError(row_P, col_P, val_P, Y, N, no_dims,theta, nthreads); } } // Adjusting the KL divergence if exaggeration is currently turned on // See https://github.com/pavlin-policar/fastTSNE/blob/master/notes/notes.pdf, Section 3.2 if (iter < stop_lying_iter && stop_lying_iter != -1) { C = C/early_exag_coeff - log(early_exag_coeff); } if (iter >= start_late_exag_iter && start_late_exag_iter != -1) { C = C/late_exag_coeff - log(late_exag_coeff); } costs[iter] = C; END_TIME("Computing Error"); std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); printf("Iteration %d (50 iterations in %.2f seconds), cost %f\n", iter+1, std::chrono::duration_cast<std::chrono::milliseconds>(now-start_time).count()/(float)1000.0, C); start_time = std::chrono::steady_clock::now(); } } // Clean up memory free(dY); free(uY); free(gains); if (exact) { free(P); } else { free(row_P); free(col_P); free(val_P); } return 0; } // Compute gradient of the t-SNE cost function (using Barnes-Hut algorithm) void TSNE::computeGradient(double *P, unsigned int *inp_row_P, unsigned int *inp_col_P, double *inp_val_P, double *Y, int N, int D, double *dC, double theta, unsigned int nthreads) { // Construct space-partitioning tree on current map SPTree *tree = new SPTree(D, Y, N); // Compute all terms required for t-SNE gradient unsigned long SIZE = (unsigned long) N * (unsigned long) D; double sum_Q = .0; double *pos_f = (double *) calloc(SIZE, sizeof(double)); double *neg_f = (double *) calloc(SIZE, sizeof(double)); double *Q = (double *) calloc(N, sizeof(double)); if (pos_f == NULL || neg_f == NULL || Q == NULL) { printf("Memory allocation failed!\n"); exit(1); } tree->computeEdgeForces(inp_row_P, inp_col_P, inp_val_P, N, pos_f, nthreads); PARALLEL_FOR(nthreads, N, { tree->computeNonEdgeForces(loop_i, theta, neg_f + loop_i * D, Q + loop_i); }); for (int i=0; i<N; i++) { sum_Q += Q[i]; } // Compute final t-SNE gradient FILE *fp = nullptr; if (measure_accuracy) { char buffer[500]; sprintf(buffer, "temp/bh_gradient%d.txt", itTest); fp = fopen(buffer, "w"); // Open file for writing } for (unsigned long i = 0; i < N * D; i++) { dC[i] = pos_f[i] - (neg_f[i] / sum_Q); if (measure_accuracy) { if (i < N) { fprintf(fp, "%d, %.12e, %.12e, %.12e,%.12e,%.12e %.12e\n", i, dC[i * 2], dC[i * 2 + 1], pos_f[i * 2], pos_f[i * 2 + 1], neg_f[i * 2] / sum_Q, neg_f[i * 2 + 1] / sum_Q); } } } if (measure_accuracy) { fclose(fp); } free(pos_f); free(neg_f); delete tree; } // Compute the gradient of the t-SNE cost function using the FFT interpolation based approximation for for one // dimensional Ys void TSNE::computeFftGradientOneDVariableDf(double *P, unsigned int *inp_row_P, unsigned int *inp_col_P, double *inp_val_P, double *Y, int N, int D, double *dC, int n_interpolation_points, double intervals_per_integer, int min_num_intervals, unsigned int nthreads, double df) { // Zero out the gradient for (unsigned long i = 0; i < N * D; i++) dC[i] = 0.0; // Push all the points at which we will evaluate // Y is stored row major, with a row corresponding to a single point // Find the min and max values of Ys double y_min = INFINITY; double y_max = -INFINITY; for (unsigned long i = 0; i < N; i++) { if (Y[i] < y_min) y_min = Y[i]; if (Y[i] > y_max) y_max = Y[i]; } auto n_boxes = static_cast<int>(fmax(min_num_intervals, (y_max - y_min) / intervals_per_integer)); int squared_n_terms = 2; auto *SquaredChargesQij = new double[N * squared_n_terms]; auto *SquaredPotentialsQij = new double[N * squared_n_terms](); for (unsigned long j = 0; j < N; j++) { SquaredChargesQij[j * squared_n_terms + 0] = Y[j]; SquaredChargesQij[j * squared_n_terms + 1] = 1; } auto *box_lower_bounds = new double[n_boxes]; auto *box_upper_bounds = new double[n_boxes]; auto *y_tilde_spacings = new double[n_interpolation_points]; auto *y_tilde = new double[n_interpolation_points * n_boxes](); auto *fft_kernel_vector = new complex<double>[2 * n_interpolation_points * n_boxes]; precompute(y_min, y_max, n_boxes, n_interpolation_points, &squared_general_kernel, box_lower_bounds, box_upper_bounds, y_tilde_spacings, y_tilde, fft_kernel_vector, df); nbodyfft(N, squared_n_terms, Y, SquaredChargesQij, n_boxes, n_interpolation_points, box_lower_bounds, box_upper_bounds, y_tilde_spacings, y_tilde, fft_kernel_vector, SquaredPotentialsQij); int not_squared_n_terms = 1; auto *NotSquaredChargesQij = new double[N * not_squared_n_terms]; auto *NotSquaredPotentialsQij = new double[N * not_squared_n_terms](); for (unsigned long j = 0; j < N; j++) { NotSquaredChargesQij[j * not_squared_n_terms + 0] = 1; } precompute(y_min, y_max, n_boxes, n_interpolation_points, &general_kernel, box_lower_bounds, box_upper_bounds, y_tilde_spacings, y_tilde, fft_kernel_vector, df); nbodyfft(N, not_squared_n_terms, Y, NotSquaredChargesQij, n_boxes, n_interpolation_points, box_lower_bounds, box_upper_bounds, y_tilde_spacings, y_tilde, fft_kernel_vector, NotSquaredPotentialsQij); // Compute the normalization constant Z or sum of q_{ij}. double sum_Q = 0; for (unsigned long i = 0; i < N; i++) { double h1 = NotSquaredPotentialsQij[i * not_squared_n_terms+ 0]; sum_Q += h1; } sum_Q -= N; this->current_sum_Q = sum_Q; // Now, figure out the Gaussian component of the gradient. This corresponds to the "attraction" term of the // gradient. It was calculated using a fast KNN approach, so here we just use the results that were passed to this // function // unsigned int ind2 = 0; double *pos_f = new double[N]; PARALLEL_FOR(nthreads, N, { double dim1 = 0; for (unsigned int i = inp_row_P[loop_i]; i < inp_row_P[loop_i + 1]; i++) { // Compute pairwise distance and Q-value unsigned int ind3 = inp_col_P[i]; double d_ij = Y[loop_i] - Y[ind3]; double q_ij = 1 / (1 + (d_ij * d_ij)/df); dim1 += inp_val_P[i] * q_ij * d_ij; } pos_f[loop_i] = dim1; }); double *neg_f = new double[N * 2]; for (unsigned int i = 0; i < N; i++) { double h2 = SquaredPotentialsQij[i * squared_n_terms]; double h4 = SquaredPotentialsQij[i * squared_n_terms + 1]; neg_f[i] = ( Y[i] *h4 - h2 ) / sum_Q; dC[i ] = (pos_f[i] - neg_f[i ]); } delete[] SquaredChargesQij; delete[] SquaredPotentialsQij; delete[] NotSquaredChargesQij; delete[] NotSquaredPotentialsQij; delete[] pos_f; delete[] neg_f; delete[] box_lower_bounds; delete[] box_upper_bounds; delete[] y_tilde_spacings; delete[] y_tilde; delete[] fft_kernel_vector; } // Compute the gradient of the t-SNE cost function using the FFT interpolation based approximation for for one // dimensional Ys void TSNE::computeFftGradientOneD(double *P, unsigned int *inp_row_P, unsigned int *inp_col_P, double *inp_val_P, double *Y, int N, int D, double *dC, int n_interpolation_points, double intervals_per_integer, int min_num_intervals, unsigned int nthreads) { // Zero out the gradient for (unsigned long i = 0; i < N * D; i++) dC[i] = 0.0; // Push all the points at which we will evaluate // Y is stored row major, with a row corresponding to a single point // Find the min and max values of Ys double y_min = INFINITY; double y_max = -INFINITY; for (unsigned long i = 0; i < N; i++) { if (Y[i] < y_min) y_min = Y[i]; if (Y[i] > y_max) y_max = Y[i]; } auto n_boxes = static_cast<int>(fmax(min_num_intervals, (y_max - y_min) / intervals_per_integer)); // The number of "charges" or s+2 sums i.e. number of kernel sums int n_terms = 3; auto *chargesQij = new double[N * n_terms]; auto *potentialsQij = new double[N * n_terms](); // Prepare the terms that we'll use to compute the sum i.e. the repulsive forces for (unsigned long j = 0; j < N; j++) { chargesQij[j * n_terms + 0] = 1; chargesQij[j * n_terms + 1] = Y[j]; chargesQij[j * n_terms + 2] = Y[j] * Y[j]; } auto *box_lower_bounds = new double[n_boxes]; auto *box_upper_bounds = new double[n_boxes]; auto *y_tilde_spacings = new double[n_interpolation_points]; auto *y_tilde = new double[n_interpolation_points * n_boxes](); auto *fft_kernel_vector = new complex<double>[2 * n_interpolation_points * n_boxes]; precompute(y_min, y_max, n_boxes, n_interpolation_points, &squared_cauchy, box_lower_bounds, box_upper_bounds, y_tilde_spacings, y_tilde, fft_kernel_vector, 1.0); nbodyfft(N, n_terms, Y, chargesQij, n_boxes, n_interpolation_points, box_lower_bounds, box_upper_bounds, y_tilde_spacings, y_tilde, fft_kernel_vector, potentialsQij); delete[] box_lower_bounds; delete[] box_upper_bounds; delete[] y_tilde_spacings; delete[] y_tilde; delete[] fft_kernel_vector; // Compute the normalization constant Z or sum of q_{ij}. This expression is different from the one in the original // paper, but equivalent. This is done so we need only use a single kernel (K_2 in the paper) instead of two // different ones. We subtract N at the end because the following sums over all i, j, whereas Z contains i \neq j double sum_Q = 0; for (unsigned long i = 0; i < N; i++) { double phi1 = potentialsQij[i * n_terms + 0]; double phi2 = potentialsQij[i * n_terms + 1]; double phi3 = potentialsQij[i * n_terms + 2]; sum_Q += (1 + Y[i] * Y[i]) * phi1 - 2 * (Y[i] * phi2) + phi3; } sum_Q -= N; this->current_sum_Q = sum_Q; // Now, figure out the Gaussian component of the gradient. This corresponds to the "attraction" term of the // gradient. It was calculated using a fast KNN approach, so here we just use the results that were passed to this // function // unsigned int ind2 = 0; double *pos_f = new double[N]; PARALLEL_FOR(nthreads, N, { double dim1 = 0; for (unsigned int i = inp_row_P[loop_i]; i < inp_row_P[loop_i + 1]; i++) { // Compute pairwise distance and Q-value unsigned int ind3 = inp_col_P[i]; double d_ij = Y[loop_i] - Y[ind3]; double q_ij = 1 / (1 + d_ij * d_ij); dim1 += inp_val_P[i] * q_ij * d_ij; } pos_f[loop_i] = dim1; }); // Make the negative term, or F_rep in the equation 3 of the paper double *neg_f = new double[N]; for (unsigned int n = 0; n < N; n++) { neg_f[n] = (Y[n] * potentialsQij[n * n_terms] - potentialsQij[n * n_terms + 1]) / sum_Q; dC[n] = pos_f[n] - neg_f[n]; } delete[] chargesQij; delete[] potentialsQij; delete[] pos_f; delete[] neg_f; } // Compute the gradient of the t-SNE cost function using the FFT interpolation // based approximation, with variable degree of freedom df void TSNE::computeFftGradientVariableDf(double *P, unsigned int *inp_row_P, unsigned int *inp_col_P, double *inp_val_P, double *Y, int N, int D, double *dC, int n_interpolation_points, double intervals_per_integer, int min_num_intervals, unsigned int nthreads, double df) { // Zero out the gradient for (unsigned long i = 0; i < N * D; i++) dC[i] = 0.0; // For convenience, split the x and y coordinate values auto *xs = new double[N]; auto *ys = new double[N]; double min_coord = INFINITY; double max_coord = -INFINITY; // Find the min/max values of the x and y coordinates for (unsigned long i = 0; i < N; i++) { xs[i] = Y[i * 2 + 0]; ys[i] = Y[i * 2 + 1]; if (xs[i] > max_coord) max_coord = xs[i]; else if (xs[i] < min_coord) min_coord = xs[i]; if (ys[i] > max_coord) max_coord = ys[i]; else if (ys[i] < min_coord) min_coord = ys[i]; } // Compute the number of boxes in a single dimension and the total number of boxes in 2d auto n_boxes_per_dim = static_cast<int>(fmax(min_num_intervals, (max_coord - min_coord) / intervals_per_integer)); //printf("min_coord: %lf, max_coord: %lf, n_boxes_per_dim: %d, (max_coord - min_coord) / intervals_per_integer) %d\n", min_coord, max_coord, n_boxes_per_dim, static_cast<int>( (max_coord - min_coord) / intervals_per_integer)); // FFTW works faster on numbers that can be written as 2^a 3^b 5^c 7^d // 11^e 13^f, where e+f is either 0 or 1, and the other exponents are // arbitrary int allowed_n_boxes_per_dim[20] = {25,36, 50, 55, 60, 65, 70, 75, 80, 85, 90, 96, 100, 110, 120, 130, 140,150, 175, 200}; if ( n_boxes_per_dim < allowed_n_boxes_per_dim[19] ) { //Round up to nearest grid point int chosen_i; for (chosen_i =0; allowed_n_boxes_per_dim[chosen_i]< n_boxes_per_dim; chosen_i++); n_boxes_per_dim = allowed_n_boxes_per_dim[chosen_i]; } //printf(" n_boxes_per_dim: %d\n", n_boxes_per_dim ); // The number of "charges" or s+2 sums i.e. number of kernel sums int squared_n_terms = 3; auto *SquaredChargesQij = new double[N * squared_n_terms]; auto *SquaredPotentialsQij = new double[N * squared_n_terms](); // Prepare the terms that we'll use to compute the sum i.e. the repulsive forces for (unsigned long j = 0; j < N; j++) { SquaredChargesQij[j * squared_n_terms + 0] = xs[j]; SquaredChargesQij[j * squared_n_terms + 1] = ys[j]; SquaredChargesQij[j * squared_n_terms + 2] = 1; } // Compute the number of boxes in a single dimension and the total number of boxes in 2d int n_boxes = n_boxes_per_dim * n_boxes_per_dim; auto *box_lower_bounds = new double[2 * n_boxes]; auto *box_upper_bounds = new double[2 * n_boxes]; auto *y_tilde_spacings = new double[n_interpolation_points]; int n_interpolation_points_1d = n_interpolation_points * n_boxes_per_dim; auto *x_tilde = new double[n_interpolation_points_1d](); auto *y_tilde = new double[n_interpolation_points_1d](); auto *fft_kernel_tilde = new complex<double>[2 * n_interpolation_points_1d * 2 * n_interpolation_points_1d]; INITIALIZE_TIME; START_TIME; precompute_2d(max_coord, min_coord, max_coord, min_coord, n_boxes_per_dim, n_interpolation_points, &squared_general_kernel_2d, box_lower_bounds, box_upper_bounds, y_tilde_spacings, x_tilde, y_tilde, fft_kernel_tilde, df); n_body_fft_2d(N, squared_n_terms, xs, ys, SquaredChargesQij, n_boxes_per_dim, n_interpolation_points, box_lower_bounds, box_upper_bounds, y_tilde_spacings, fft_kernel_tilde, SquaredPotentialsQij, nthreads); int not_squared_n_terms = 1; auto *NotSquaredChargesQij = new double[N * not_squared_n_terms]; auto *NotSquaredPotentialsQij = new double[N * not_squared_n_terms](); // Prepare the terms that we'll use to compute the sum i.e. the repulsive forces for (unsigned long j = 0; j < N; j++) { NotSquaredChargesQij[j * not_squared_n_terms + 0] = 1; } precompute_2d(max_coord, min_coord, max_coord, min_coord, n_boxes_per_dim, n_interpolation_points, &general_kernel_2d, box_lower_bounds, box_upper_bounds, y_tilde_spacings, x_tilde, y_tilde, fft_kernel_tilde,df); n_body_fft_2d(N, not_squared_n_terms, xs, ys, NotSquaredChargesQij, n_boxes_per_dim, n_interpolation_points, box_lower_bounds, box_upper_bounds, y_tilde_spacings, fft_kernel_tilde, NotSquaredPotentialsQij, nthreads); // Compute the normalization constant Z or sum of q_{ij}. double sum_Q = 0; for (unsigned long i = 0; i < N; i++) { double h1 = NotSquaredPotentialsQij[i * not_squared_n_terms+ 0]; sum_Q += h1; } sum_Q -= N; // Now, figure out the Gaussian component of the gradient. This corresponds to the "attraction" term of the // gradient. It was calculated using a fast KNN approach, so here we just use the results that were passed to this // function unsigned int ind2 = 0; double *pos_f = new double[N * 2]; END_TIME("Total Interpolation"); START_TIME; // Loop over all edges in the graph PARALLEL_FOR(nthreads, N, { double dim1 = 0; double dim2 = 0; for (unsigned int i = inp_row_P[loop_i]; i < inp_row_P[loop_i + 1]; i++) { // Compute pairwise distance and Q-value unsigned int ind3 = inp_col_P[i]; double d_ij = (xs[loop_i] - xs[ind3]) * (xs[loop_i] - xs[ind3]) + (ys[loop_i] - ys[ind3]) * (ys[loop_i] - ys[ind3]); double q_ij = 1 / (1 + d_ij/df); dim1 += inp_val_P[i] * q_ij * (xs[loop_i] - xs[ind3]); dim2 += inp_val_P[i] * q_ij * (ys[loop_i] - ys[ind3]); } pos_f[loop_i * 2 + 0] = dim1; pos_f[loop_i * 2 + 1] = dim2; }); // Make the negative term, or F_rep in the equation 3 of the paper END_TIME("Attractive Forces"); double *neg_f = new double[N * 2]; for (unsigned int i = 0; i < N; i++) { double h2 = SquaredPotentialsQij[i * squared_n_terms]; double h3 = SquaredPotentialsQij[i * squared_n_terms + 1]; double h4 = SquaredPotentialsQij[i * squared_n_terms + 2]; neg_f[i * 2 + 0] = ( xs[i] *h4 - h2 ) / sum_Q; neg_f[i * 2 + 1] = (ys[i] *h4 - h3 ) / sum_Q; dC[i * 2 + 0] = (pos_f[i * 2] - neg_f[i * 2]); dC[i * 2 + 1] = (pos_f[i * 2 + 1] - neg_f[i * 2 + 1]); } this->current_sum_Q = sum_Q; /* FILE *fp = nullptr; char buffer[500]; sprintf(buffer, "temp/fft_gradient%d.txt", itTest); fp = fopen(buffer, "w"); // Open file for writing for (int i = 0; i < N; i++) { fprintf(fp, "%d,%.12e,%.12e\n", i, neg_f[i * 2] , neg_f[i * 2 + 1]); } fclose(fp);*/ delete[] pos_f; delete[] neg_f; delete[] SquaredPotentialsQij; delete[] NotSquaredPotentialsQij; delete[] SquaredChargesQij; delete[] NotSquaredChargesQij; delete[] xs; delete[] ys; delete[] box_lower_bounds; delete[] box_upper_bounds; delete[] y_tilde_spacings; delete[] y_tilde; delete[] x_tilde; delete[] fft_kernel_tilde; } // Compute the gradient of the t-SNE cost function using the FFT interpolation based approximation void TSNE::computeFftGradient(double *P, unsigned int *inp_row_P, unsigned int *inp_col_P, double *inp_val_P, double *Y, int N, int D, double *dC, int n_interpolation_points, double intervals_per_integer, int min_num_intervals, unsigned int nthreads) { // Zero out the gradient for (unsigned long i = 0; i < N * D; i++) dC[i] = 0.0; // For convenience, split the x and y coordinate values auto *xs = new double[N]; auto *ys = new double[N]; double min_coord = INFINITY; double max_coord = -INFINITY; // Find the min/max values of the x and y coordinates for (unsigned long i = 0; i < N; i++) { xs[i] = Y[i * 2 + 0]; ys[i] = Y[i * 2 + 1]; if (xs[i] > max_coord) max_coord = xs[i]; else if (xs[i] < min_coord) min_coord = xs[i]; if (ys[i] > max_coord) max_coord = ys[i]; else if (ys[i] < min_coord) min_coord = ys[i]; } // The number of "charges" or s+2 sums i.e. number of kernel sums int n_terms = 4; auto *chargesQij = new double[N * n_terms]; auto *potentialsQij = new double[N * n_terms](); // Prepare the terms that we'll use to compute the sum i.e. the repulsive forces for (unsigned long j = 0; j < N; j++) { chargesQij[j * n_terms + 0] = 1; chargesQij[j * n_terms + 1] = xs[j]; chargesQij[j * n_terms + 2] = ys[j]; chargesQij[j * n_terms + 3] = xs[j] * xs[j] + ys[j] * ys[j]; } // Compute the number of boxes in a single dimension and the total number of boxes in 2d auto n_boxes_per_dim = static_cast<int>(fmax(min_num_intervals, (max_coord - min_coord) / intervals_per_integer)); // FFTW works faster on numbers that can be written as 2^a 3^b 5^c 7^d // 11^e 13^f, where e+f is either 0 or 1, and the other exponents are // arbitrary int allowed_n_boxes_per_dim[20] = {25,36, 50, 55, 60, 65, 70, 75, 80, 85, 90, 96, 100, 110, 120, 130, 140,150, 175, 200}; if ( n_boxes_per_dim < allowed_n_boxes_per_dim[19] ) { //Round up to nearest grid point int chosen_i; for (chosen_i =0; allowed_n_boxes_per_dim[chosen_i]< n_boxes_per_dim; chosen_i++); n_boxes_per_dim = allowed_n_boxes_per_dim[chosen_i]; } int n_boxes = n_boxes_per_dim * n_boxes_per_dim; auto *box_lower_bounds = new double[2 * n_boxes]; auto *box_upper_bounds = new double[2 * n_boxes]; auto *y_tilde_spacings = new double[n_interpolation_points]; int n_interpolation_points_1d = n_interpolation_points * n_boxes_per_dim; auto *x_tilde = new double[n_interpolation_points_1d](); auto *y_tilde = new double[n_interpolation_points_1d](); auto *fft_kernel_tilde = new complex<double>[2 * n_interpolation_points_1d * 2 * n_interpolation_points_1d]; INITIALIZE_TIME; START_TIME; precompute_2d(max_coord, min_coord, max_coord, min_coord, n_boxes_per_dim, n_interpolation_points, &squared_cauchy_2d, box_lower_bounds, box_upper_bounds, y_tilde_spacings, x_tilde, y_tilde, fft_kernel_tilde,1.0); n_body_fft_2d(N, n_terms, xs, ys, chargesQij, n_boxes_per_dim, n_interpolation_points, box_lower_bounds, box_upper_bounds, y_tilde_spacings, fft_kernel_tilde, potentialsQij,nthreads); // Compute the normalization constant Z or sum of q_{ij}. This expression is different from the one in the original // paper, but equivalent. This is done so we need only use a single kernel (K_2 in the paper) instead of two // different ones. We subtract N at the end because the following sums over all i, j, whereas Z contains i \neq j double sum_Q = 0; for (unsigned long i = 0; i < N; i++) { double phi1 = potentialsQij[i * n_terms + 0]; double phi2 = potentialsQij[i * n_terms + 1]; double phi3 = potentialsQij[i * n_terms + 2]; double phi4 = potentialsQij[i * n_terms + 3]; sum_Q += (1 + xs[i] * xs[i] + ys[i] * ys[i]) * phi1 - 2 * (xs[i] * phi2 + ys[i] * phi3) + phi4; } sum_Q -= N; this->current_sum_Q = sum_Q; double *pos_f = new double[N * 2]; END_TIME("Total Interpolation"); START_TIME; // Now, figure out the Gaussian component of the gradient. This corresponds to the "attraction" term of the // gradient. It was calculated using a fast KNN approach, so here we just use the results that were passed to this // function PARALLEL_FOR(nthreads, N, { double dim1 = 0; double dim2 = 0; for (unsigned int i = inp_row_P[loop_i]; i < inp_row_P[loop_i + 1]; i++) { // Compute pairwise distance and Q-value unsigned int ind3 = inp_col_P[i]; double d_ij = (xs[loop_i] - xs[ind3]) * (xs[loop_i] - xs[ind3]) + (ys[loop_i] - ys[ind3]) * (ys[loop_i] - ys[ind3]); double q_ij = 1 / (1 + d_ij); dim1 += inp_val_P[i] * q_ij * (xs[loop_i] - xs[ind3]); dim2 += inp_val_P[i] * q_ij * (ys[loop_i] - ys[ind3]); } pos_f[loop_i * 2 + 0] = dim1; pos_f[loop_i * 2 + 1] = dim2; }); END_TIME("Attractive Forces"); //printf("Attractive forces took %lf\n", (diff(start20,end20))/(double)1E6); // Make the negative term, or F_rep in the equation 3 of the paper double *neg_f = new double[N * 2]; for (unsigned int i = 0; i < N; i++) { neg_f[i * 2 + 0] = (xs[i] * potentialsQij[i * n_terms] - potentialsQij[i * n_terms + 1]) / sum_Q; neg_f[i * 2 + 1] = (ys[i] * potentialsQij[i * n_terms] - potentialsQij[i * n_terms + 2]) / sum_Q; dC[i * 2 + 0] = pos_f[i * 2] - neg_f[i * 2]; dC[i * 2 + 1] = pos_f[i * 2 + 1] - neg_f[i * 2 + 1]; } delete[] pos_f; delete[] neg_f; delete[] potentialsQij; delete[] chargesQij; delete[] xs; delete[] ys; delete[] box_lower_bounds; delete[] box_upper_bounds; delete[] y_tilde_spacings; delete[] y_tilde; delete[] x_tilde; delete[] fft_kernel_tilde; } void TSNE::computeExactGradientTest(double *Y, int N, int D, double df ) { // Compute the squared Euclidean distance matrix double *DD = (double *) malloc(N * N * sizeof(double)); if (DD == NULL) { printf("Memory allocation failed!\n"); exit(1); } computeSquaredEuclideanDistance(Y, N, D, DD); // Compute Q-matrix and normalization sum double *Q = (double *) malloc(N * N * sizeof(double)); if (Q == NULL) { printf("Memory allocation failed!\n"); exit(1); } double sum_Q = .0; int nN = 0; for (int n = 0; n < N; n++) { for (int m = 0; m < N; m++) { if (n != m) { Q[nN + m] = 1.0 / pow(1.0 + DD[nN + m]/(double)df, (df)); sum_Q += Q[nN + m]; } } nN += N; } // Perform the computation of the gradient char buffer[500]; sprintf(buffer, "temp/exact_gradient%d.txt", itTest); FILE *fp = fopen(buffer, "w"); // Open file for writing nN = 0; int nD = 0; for (int n = 0; n < N; n++) { double testQij = 0; double testPos = 0; double testNeg1 = 0; double testNeg2 = 0; double testdC = 0; int mD = 0; for (int m = 0; m < N; m++) { if (n != m) { testNeg1 += pow(Q[nN + m],(df +1.0)/df) * (Y[nD + 0] - Y[mD + 0]) / sum_Q; testNeg2 += pow(Q[nN + m],(df +1.0)/df) * (Y[nD + 1] - Y[mD + 1]) / sum_Q; } mD += D; } fprintf(fp, "%d, %.12e, %.12e\n", n, testNeg1,testNeg2); nN += N; nD += D; } fclose(fp); free(DD); free(Q); } // Compute the exact gradient of the t-SNE cost function void TSNE::computeExactGradient(double *P, double *Y, int N, int D, double *dC, double df) { // Make sure the current gradient contains zeros for (unsigned long i = 0; i < N * D; i++) dC[i] = 0.0; // Compute the squared Euclidean distance matrix auto *DD = (double *) malloc(N * N * sizeof(double)); if (DD == nullptr) throw std::bad_alloc(); computeSquaredEuclideanDistance(Y, N, D, DD); // Compute Q-matrix and normalization sum auto *Q = (double *) malloc(N * N * sizeof(double)); if (Q == nullptr) throw std::bad_alloc(); auto *Qpow = (double *) malloc(N * N * sizeof(double)); if (Qpow == nullptr) throw std::bad_alloc(); double sum_Q = .0; int nN = 0; for (int n = 0; n < N; n++) { for (int m = 0; m < N; m++) { if (n != m) { //Q[nN + m] = 1.0 / pow(1.0 + DD[nN + m]/(double)df, df); Q[nN + m] = 1.0 / (1.0 + DD[nN + m]/(double)df); Qpow[nN + m] = pow(Q[nN + m], df); sum_Q += Qpow[nN + m]; } } nN += N; } // Perform the computation of the gradient nN = 0; int nD = 0; for (int n = 0; n < N; n++) { int mD = 0; for (int m = 0; m < N; m++) { if (n != m) { double mult = (P[nN + m] - (Qpow[nN + m] / sum_Q)) * (Q[nN + m]); for (int d = 0; d < D; d++) { dC[nD + d] += (Y[nD + d] - Y[mD + d]) * mult; } } mD += D; } nN += N; nD += D; } free(Q); free(Qpow); free(DD); } // Evaluate t-SNE cost function (exactly) double TSNE::evaluateError(double *P, double *Y, int N, int D, double df) { // Compute the squared Euclidean distance matrix double *DD = (double *) malloc(N * N * sizeof(double)); double *Q = (double *) malloc(N * N * sizeof(double)); if (DD == NULL || Q == NULL) { printf("Memory allocation failed!\n"); exit(1); } computeSquaredEuclideanDistance(Y, N, D, DD); // Compute Q-matrix and normalization sum int nN = 0; double sum_Q = DBL_MIN; for (int n = 0; n < N; n++) { for (int m = 0; m < N; m++) { if (n != m) { //Q[nN + m] = 1.0 / pow(1.0 + DD[nN + m]/(double)df, df); Q[nN + m] = 1.0 / (1.0 + DD[nN + m]/(double)df); Q[nN +m ] = pow(Q[nN +m ], df); sum_Q += Q[nN + m]; } else Q[nN + m] = DBL_MIN; } nN += N; } //printf("sum_Q: %e", sum_Q); for (int i = 0; i < N * N; i++) Q[i] /= sum_Q; // for (int i = 0; i < N; i++) printf("Q[%d]: %e\n", i, Q[i]); //printf("Q[N*N/2+1]: %e, Q[N*N-1]: %e\n", Q[N*N/2+1], Q[N*N/2+2]); // Sum t-SNE error double C = .0; for (int n = 0; n < N * N; n++) { C += P[n] * log((P[n] + FLT_MIN) / (Q[n] + FLT_MIN)); } // Clean up memory free(DD); free(Q); return C; } // Evaluate t-SNE cost function (approximately) using FFT double TSNE::evaluateErrorFft(unsigned int *row_P, unsigned int *col_P, double *val_P, double *Y, int N, int D,unsigned int nthreads, double df) { // Get estimate of normalization term double sum_Q = this->current_sum_Q; // Loop over all edges to compute t-SNE error double C = .0; PARALLEL_FOR(nthreads,N,{ double *buff = (double *) calloc(D, sizeof(double)); int ind1 = loop_i * D; double temp = 0; for (int i = row_P[loop_i]; i < row_P[loop_i + 1]; i++) { double Q = .0; int ind2 = col_P[i] * D; for (int d = 0; d < D; d++) buff[d] = Y[ind1 + d]; for (int d = 0; d < D; d++) buff[d] -= Y[ind2 + d]; for (int d = 0; d < D; d++) Q += buff[d] * buff[d]; Q = pow(1.0 / (1.0 + Q/df), df) / sum_Q; temp += val_P[i] * log((val_P[i] + FLT_MIN) / (Q + FLT_MIN)); } C += temp; free(buff); }); // Clean up memory return C; } // Evaluate t-SNE cost function (approximately) double TSNE::evaluateError(unsigned int *row_P, unsigned int *col_P, double *val_P, double *Y, int N, int D, double theta, unsigned int nthreads) { // Get estimate of normalization term SPTree *tree = new SPTree(D, Y, N); double *buff = (double *) calloc(D, sizeof(double)); double sum_Q = .0; for (int n = 0; n < N; n++) tree->computeNonEdgeForces(n, theta, buff, &sum_Q); double C = .0; PARALLEL_FOR(nthreads,N,{ double *buff = (double *) calloc(D, sizeof(double)); int ind1 = loop_i * D; double temp = 0; for (int i = row_P[loop_i]; i < row_P[loop_i + 1]; i++) { double Q = .0; int ind2 = col_P[i] * D; for (int d = 0; d < D; d++) buff[d] = Y[ind1 + d]; for (int d = 0; d < D; d++) buff[d] -= Y[ind2 + d]; for (int d = 0; d < D; d++) Q += buff[d] * buff[d]; Q = (1.0 / (1.0 + Q)) / sum_Q; temp += val_P[i] * log((val_P[i] + FLT_MIN) / (Q + FLT_MIN)); } C += temp; free(buff); }); // Clean up memory free(buff); delete tree; return C; } // Converts an array of [squared] Euclidean distances into similarities aka affinities // using a specified perplexity value (or a specified kernel width) double TSNE::distances2similarities(double *D, double *P, int N, int n, double perplexity, double sigma, bool ifSquared) { /* D - a pointer to the array of distances P - a pointer to the array of similarities N - length of D and P n - index of the point that should have D = 0 perplexity - target perplexity sigma - kernel width if perplexity == -1 ifSquared - if D contains squared distances (TRUE) or not (FALSE) */ double sum_P; double beta; if (perplexity > 0) { // Using binary search to find the appropriate kernel width double min_beta = -DBL_MAX; double max_beta = DBL_MAX; double tol = 1e-5; int max_iter = 200; int iter = 0; bool found = false; beta = 1.0; // Iterate until we found a good kernel width while(!found && iter < max_iter) { // Apply Gaussian kernel for(int m = 0; m < N; m++) P[m] = exp(-beta * (ifSquared ? D[m] : D[m]*D[m])); if (n>=0) P[n] = DBL_MIN; // Compute entropy sum_P = DBL_MIN; for(int m = 0; m < N; m++) sum_P += P[m]; double H = 0.0; for(int m = 0; m < N; m++) H += beta * ((ifSquared ? D[m] : D[m]*D[m]) * P[m]); H = (H / sum_P) + log(sum_P); // Evaluate whether the entropy is within the tolerance level double Hdiff = H - log(perplexity); if(Hdiff < tol && -Hdiff < tol) { found = true; } else { if(Hdiff > 0) { min_beta = beta; if(max_beta == DBL_MAX || max_beta == -DBL_MAX) beta *= 2.0; else beta = (beta + max_beta) / 2.0; } else { max_beta = beta; if(min_beta == -DBL_MAX || min_beta == DBL_MAX) beta /= 2.0; else beta = (beta + min_beta) / 2.0; } } // Update iteration counter iter++; } }else{ // Using fixed kernel width: no iterations needed beta = 1/(2*sigma*sigma); for(int m = 0; m < N; m++) P[m] = exp(-beta * (ifSquared ? D[m] : D[m]*D[m])); if (n >= 0) P[n] = DBL_MIN; sum_P = DBL_MIN; for(int m = 0; m < N; m++) sum_P += P[m]; } // Normalize for(int m = 0; m < N; m++) P[m] /= sum_P; return beta; } // Converts an array of [squared] Euclidean distances into similarities aka affinities // using a list of perplexities double TSNE::distances2similarities(double *D, double *P, int N, int n, double perplexity, double sigma, bool ifSquared, int perplexity_list_length, double *perplexity_list) { // if perplexity != 0 then defaulting to using this perplexity (or fixed sigma) if (perplexity != 0) { double beta = distances2similarities(D, P, N, n, perplexity, sigma, true); return beta; } // otherwise averaging similarities using all perplexities in perplexity_list double *tmp = (double*) malloc(N * sizeof(double)); if(tmp == NULL) { printf("Memory allocation failed!\n"); exit(1); } double beta = distances2similarities(D, P, N, n, perplexity_list[0], sigma, true); for (int m=1; m < perplexity_list_length; m++){ beta = distances2similarities(D, tmp, N, n, perplexity_list[m], sigma, true); for (int i=0; i<N; i++){ P[i] += tmp[i]; } } for (int i=0; i<N; i++){ P[i] /= perplexity_list_length; } return beta; } // Compute input similarities using exact algorithm void TSNE::computeGaussianPerplexity(double *X, int N, int D, double *P, double perplexity, double sigma, int perplexity_list_length, double *perplexity_list) { if (perplexity < 0) { printf("Using manually set kernel width\n"); } else { printf("Using perplexity, not the manually set kernel width\n"); } // Compute the squared Euclidean distance matrix double *DD = (double *) malloc(N * N * sizeof(double)); if (DD == NULL) { printf("Memory allocation failed!\n"); exit(1); } computeSquaredEuclideanDistance(X, N, D, DD); // Convert distances to similarities using Gaussian kernel row by row int nN = 0; double beta; for (int n = 0; n < N; n++) { beta = distances2similarities(&DD[nN], &P[nN], N, n, perplexity, sigma, true, perplexity_list_length, perplexity_list); nN += N; } // Clean up memory free(DD); } // Compute input similarities using ANNOY int TSNE::computeGaussianPerplexity(double *X, int N, int D, unsigned int **_row_P, unsigned int **_col_P, double **_val_P, double perplexity, int K, double sigma, int num_trees, int search_k, unsigned int nthreads, int perplexity_list_length, double *perplexity_list, int rand_seed) { if(perplexity > K) printf("Perplexity should be lower than K!\n"); // Allocate the memory we need printf("Going to allocate memory. N: %d, K: %d, N*K = %d\n", N, K, N*K); *_row_P = (unsigned int*) malloc((N + 1) * sizeof(unsigned int)); *_col_P = (unsigned int*) calloc(N * K, sizeof(unsigned int)); *_val_P = (double*) calloc(N * K, sizeof(double)); if(*_row_P == NULL || *_col_P == NULL || *_val_P == NULL) { printf("Memory allocation failed!\n"); exit(1); } unsigned int* row_P = *_row_P; unsigned int* col_P = *_col_P; double* val_P = *_val_P; row_P[0] = 0; for(int n = 0; n < N; n++) row_P[n + 1] = row_P[n] + (unsigned int) K; printf("Building Annoy tree...\n"); AnnoyIndex<int, double, Euclidean, Kiss32Random> tree = AnnoyIndex<int, double, Euclidean, Kiss32Random>(D); if (rand_seed > 0) { tree.set_seed(rand_seed); } for(unsigned long i=0; i<N; ++i){ double *vec = (double *) malloc( D * sizeof(double) ); for(unsigned long z=0; z<D; ++z){ vec[z] = X[i*D+z]; } tree.add_item(i, vec); } tree.build(num_trees); //Check if it returns enough neighbors std::vector<int> closest; std::vector<double> closest_distances; for (int n = 0; n < 100; n++){ tree.get_nns_by_item(n, K+1, search_k, &closest, &closest_distances); unsigned int neighbors_count = closest.size(); if (neighbors_count < K+1 ) { printf("Requesting perplexity*3=%d neighbors, but ANNOY is only giving us %u. Please increase search_k\n", K, neighbors_count); return -1; } } printf("Done building tree. Beginning nearest neighbor search... \n"); ProgressBar bar(N,60); //const size_t nthreads = 1; { // Pre loop std::cout << "parallel (" << nthreads << " threads):" << std::endl; std::vector<std::thread> threads(nthreads); for (int t = 0; t < nthreads; t++) { threads[t] = std::thread(std::bind( [&](const int bi, const int ei, const int t) { // loop over all items for(int n = bi;n<ei;n++) { // inner loop { // Find nearest neighbors std::vector<int> closest; std::vector<double> closest_distances; tree.get_nns_by_item(n, K+1, search_k, &closest, &closest_distances); double* cur_P = (double*) malloc((N - 1) * sizeof(double)); if(cur_P == NULL) { printf("Memory allocation failed!\n"); exit(1); } double beta = distances2similarities(&closest_distances[1], cur_P, K, -1, perplexity, sigma, false, perplexity_list_length, perplexity_list); ++bar; if(t == 0 && n % 100 == 0) { bar.display(); // if (perplexity >= 0) { // printf(" - point %d of %d, most recent beta calculated is %lf \n", n, N, beta); // } else { // printf(" - point %d of %d, beta is set to %lf \n", n, N, 1/sigma); // } } // Store current row of P in matrix for(unsigned int m = 0; m < K; m++) { col_P[row_P[n] + m] = (unsigned int) closest[m + 1]; val_P[row_P[n] + m] = cur_P[m]; } free(cur_P); closest.clear(); closest_distances.clear(); } } },t*N/nthreads,(t+1)==nthreads?N:(t+1)*N/nthreads,t)); } std::for_each(threads.begin(),threads.end(),[](std::thread& x){x.join();}); // Post loop } bar.display(); printf("\n"); return 0; } // Compute input similarities with a fixed perplexity using ball trees (this function allocates memory another function should free) void TSNE::computeGaussianPerplexity(double *X, int N, int D, unsigned int **_row_P, unsigned int **_col_P, double **_val_P, double perplexity, int K, double sigma, unsigned int nthreads, int perplexity_list_length, double *perplexity_list) { if(perplexity > K) printf("Perplexity should be lower than K!\n"); // Allocate the memory we need printf("Going to allocate memory. N: %d, K: %d, N*K = %d\n", N, K, N*K); *_row_P = (unsigned int*) malloc((N + 1) * sizeof(unsigned int)); *_col_P = (unsigned int*) calloc(N * K, sizeof(unsigned int)); *_val_P = (double*) calloc(N * K, sizeof(double)); if(*_row_P == NULL || *_col_P == NULL || *_val_P == NULL) { printf("Memory allocation failed!\n"); exit(1); } unsigned int* row_P = *_row_P; unsigned int* col_P = *_col_P; double* val_P = *_val_P; row_P[0] = 0; for(int n = 0; n < N; n++) row_P[n + 1] = row_P[n] + (unsigned int) K; // Build ball tree on data set printf("Building VP tree...\n"); VpTree<DataPoint, euclidean_distance> *tree = new VpTree<DataPoint, euclidean_distance>(); vector<DataPoint> obj_X(N, DataPoint(D, -1, X)); for (int n = 0; n < N; n++) obj_X[n] = DataPoint(D, n, X + n * D); tree->create(obj_X); printf("Done building tree. Beginning nearest neighbor search... \n"); ProgressBar bar(N,60); //const size_t nthreads = 1; { // Pre loop std::cout << "parallel (" << nthreads << " threads):" << std::endl; std::vector<std::thread> threads(nthreads); for (int t = 0; t < nthreads; t++) { threads[t] = std::thread(std::bind( [&](const int bi, const int ei, const int t) { // loop over all items for(int n = bi;n<ei;n++) { // inner loop { // Find nearest neighbors std::vector<double> cur_P(K); vector<DataPoint> indices; vector<double> distances; tree->search(obj_X[n], K + 1, &indices, &distances); double beta = distances2similarities(&distances[1], &cur_P[0], K, -1, perplexity, sigma, false, perplexity_list_length, perplexity_list); ++bar; if(t == 0 && n % 100 == 0) { bar.display(); // if (perplexity >= 0) { // printf(" - point %d of %d, most recent beta calculated is %lf \n", n, N, beta); // } else { // printf(" - point %d of %d, beta is set to %lf \n", n, N, 1/sigma); // } } for(unsigned int m = 0; m < K; m++) { col_P[row_P[n] + m] = (unsigned int) indices[m + 1].index(); val_P[row_P[n] + m] = cur_P[m]; } indices.clear(); distances.clear(); cur_P.clear(); } } },t*N/nthreads,(t+1)==nthreads?N:(t+1)*N/nthreads,t)); } std::for_each(threads.begin(),threads.end(),[](std::thread& x){x.join();}); // Post loop } bar.display(); printf("\n"); // Clean up memory obj_X.clear(); delete tree; } // Symmetrizes a sparse matrix void TSNE::symmetrizeMatrix(unsigned int **_row_P, unsigned int **_col_P, double **_val_P, int N) { // Get sparse matrix unsigned int *row_P = *_row_P; unsigned int *col_P = *_col_P; double *val_P = *_val_P; // Count number of elements and row counts of symmetric matrix int *row_counts = (int *) calloc(N, sizeof(int)); if (row_counts == NULL) { printf("Memory allocation failed!\n"); exit(1); } for (int n = 0; n < N; n++) { for (int i = row_P[n]; i < row_P[n + 1]; i++) { // Check whether element (col_P[i], n) is present bool present = false; for (int m = row_P[col_P[i]]; m < row_P[col_P[i] + 1]; m++) { if (col_P[m] == n) present = true; } if (present) row_counts[n]++; else { row_counts[n]++; row_counts[col_P[i]]++; } } } int no_elem = 0; for (int n = 0; n < N; n++) no_elem += row_counts[n]; // Allocate memory for symmetrized matrix unsigned int *sym_row_P = (unsigned int *) malloc((N + 1) * sizeof(unsigned int)); unsigned int *sym_col_P = (unsigned int *) malloc(no_elem * sizeof(unsigned int)); double *sym_val_P = (double *) malloc(no_elem * sizeof(double)); if (sym_row_P == NULL || sym_col_P == NULL || sym_val_P == NULL) { printf("Memory allocation failed!\n"); exit(1); } // Construct new row indices for symmetric matrix sym_row_P[0] = 0; for (int n = 0; n < N; n++) sym_row_P[n + 1] = sym_row_P[n] + (unsigned int) row_counts[n]; // Fill the result matrix int *offset = (int *) calloc(N, sizeof(int)); if (offset == NULL) { printf("Memory allocation failed!\n"); exit(1); } for (int n = 0; n < N; n++) { for (unsigned int i = row_P[n]; i < row_P[n + 1]; i++) { // considering element(n, col_P[i]) // Check whether element (col_P[i], n) is present bool present = false; for (unsigned int m = row_P[col_P[i]]; m < row_P[col_P[i] + 1]; m++) { if (col_P[m] == n) { present = true; if (n <= col_P[i]) { // make sure we do not add elements twice sym_col_P[sym_row_P[n] + offset[n]] = col_P[i]; sym_col_P[sym_row_P[col_P[i]] + offset[col_P[i]]] = n; sym_val_P[sym_row_P[n] + offset[n]] = val_P[i] + val_P[m]; sym_val_P[sym_row_P[col_P[i]] + offset[col_P[i]]] = val_P[i] + val_P[m]; } } } // If (col_P[i], n) is not present, there is no addition involved if (!present) { sym_col_P[sym_row_P[n] + offset[n]] = col_P[i]; sym_col_P[sym_row_P[col_P[i]] + offset[col_P[i]]] = n; sym_val_P[sym_row_P[n] + offset[n]] = val_P[i]; sym_val_P[sym_row_P[col_P[i]] + offset[col_P[i]]] = val_P[i]; } // Update offsets if (!present || (n <= col_P[i])) { offset[n]++; if (col_P[i] != n) offset[col_P[i]]++; } } } // Divide the result by two for (int i = 0; i < no_elem; i++) sym_val_P[i] /= 2.0; // Return symmetrized matrices free(*_row_P); *_row_P = sym_row_P; free(*_col_P); *_col_P = sym_col_P; free(*_val_P); *_val_P = sym_val_P; // Free up some memory free(offset); free(row_counts); } // Compute squared Euclidean distance matrix void TSNE::computeSquaredEuclideanDistance(double *X, int N, int D, double *DD) { const double *XnD = X; for (int n = 0; n < N; ++n, XnD += D) { const double *XmD = XnD + D; double *curr_elem = &DD[n * N + n]; *curr_elem = 0.0; double *curr_elem_sym = curr_elem + N; for (int m = n + 1; m < N; ++m, XmD += D, curr_elem_sym += N) { *(++curr_elem) = 0.0; for (int d = 0; d < D; ++d) { *curr_elem += (XnD[d] - XmD[d]) * (XnD[d] - XmD[d]); } *curr_elem_sym = *curr_elem; } } } // Makes data zero-mean void TSNE::zeroMean(double *X, int N, int D) { // Compute data mean double *mean = (double *) calloc(D, sizeof(double)); if (mean == NULL) throw std::bad_alloc(); unsigned long nD = 0; for (int n = 0; n < N; n++) { for (int d = 0; d < D; d++) { mean[d] += X[nD + d]; } nD += D; } for (int d = 0; d < D; d++) { mean[d] /= (double) N; } // Subtract data mean nD = 0; for (int n = 0; n < N; n++) { for (int d = 0; d < D; d++) { X[nD + d] -= mean[d]; } nD += D; } free(mean); } // Generates a Gaussian random number double TSNE::randn() { double x, y, radius; do { x = 2 * (rand() / ((double) RAND_MAX + 1)) - 1; y = 2 * (rand() / ((double) RAND_MAX + 1)) - 1; radius = (x * x) + (y * y); } while ((radius >= 1.0) || (radius == 0.0)); radius = sqrt(-2 * log(radius) / radius); x *= radius; return x; } // Function that loads data from a t-SNE file // Note: this function does a malloc that should be freed elsewhere bool TSNE::load_data(const char *data_path, double **data, double **Y, int *n, int *d, int *no_dims, double *theta, double *perplexity, int *rand_seed, int *max_iter, int *stop_lying_iter, int *mom_switch_iter, double* momentum, double* final_momentum, double* learning_rate, int *K, double *sigma, int *nbody_algo, int *knn_algo, double *early_exag_coeff, int *no_momentum_during_exag, int *n_trees, int *search_k, int *start_late_exag_iter, double *late_exag_coeff, int *nterms, double *intervals_per_integer, int *min_num_intervals, bool *skip_random_init, int *load_affinities, int *perplexity_list_length, double **perplexity_list, double * df, double *max_step_norm) { FILE *h; if((h = fopen(data_path, "r+b")) == NULL) { printf("Error: could not open data file.\n"); return false; } size_t result; // need this to get rid of warnings that otherwise appear result = fread(n, sizeof(int), 1, h); // number of datapoints result = fread(d, sizeof(int), 1, h); // original dimensionality result = fread(theta, sizeof(double), 1, h); // gradient accuracy result = fread(perplexity, sizeof(double), 1, h); // perplexity // if perplexity == 0, then what follows is the number of perplexities // to combine and then the list of these perpexities if (*perplexity == 0) { result = fread(perplexity_list_length, sizeof(int), 1, h); *perplexity_list = (double*) malloc(*perplexity_list_length * sizeof(double)); if(*perplexity_list == NULL) { printf("Memory allocation failed!\n"); exit(1); } result = fread(*perplexity_list, sizeof(double), *perplexity_list_length, h); } else { perplexity_list_length = 0; perplexity_list = NULL; } result = fread(no_dims, sizeof(int), 1, h); // output dimensionality result = fread(max_iter, sizeof(int),1,h); // maximum number of iterations result = fread(stop_lying_iter, sizeof(int),1,h); // when to stop early exaggeration result = fread(mom_switch_iter, sizeof(int),1,h); // when to switch the momentum value result = fread(momentum, sizeof(double),1,h); // initial momentum result = fread(final_momentum, sizeof(double),1,h); // final momentum result = fread(learning_rate, sizeof(double),1,h); // learning rate result = fread(max_step_norm, sizeof(double),1,h); // max step norm result = fread(K, sizeof(int),1,h); // number of neighbours to compute result = fread(sigma, sizeof(double),1,h); // input kernel width result = fread(nbody_algo, sizeof(int),1,h); // Barnes-Hut or FFT result = fread(knn_algo, sizeof(int),1,h); // VP-trees or Annoy result = fread(early_exag_coeff, sizeof(double),1,h); // early exaggeration result = fread(no_momentum_during_exag, sizeof(int),1,h); // if to use momentum during early exagg result = fread(n_trees, sizeof(int),1,h); // number of trees for Annoy result = fread(search_k, sizeof(int),1,h); // search_k for Annoy result = fread(start_late_exag_iter, sizeof(int),1,h); // when to start late exaggeration result = fread(late_exag_coeff, sizeof(double),1,h); // late exaggeration result = fread(nterms, sizeof(int),1,h); // FFT parameter result = fread(intervals_per_integer, sizeof(double),1,h); // FFT parameter result = fread(min_num_intervals, sizeof(int),1,h); // FFT parameter if((*nbody_algo == 2) && (*no_dims > 2)){ printf("FFT interpolation scheme supports only 1 or 2 output dimensions, not %d\n", *no_dims); exit(1); } *data = (double*) malloc((unsigned long)*d * (unsigned long) *n * sizeof(double)); if(*data == NULL) { printf("Memory allocation failed!\n"); exit(1); } result = fread(*data, sizeof(double), (unsigned long) *n * (unsigned long) *d, h); // the data if(!feof(h)) { result = fread(rand_seed, sizeof(int), 1, h); // random seed } if(!feof(h)) { result = fread(df, sizeof(double),1,h); // Number of degrees of freedom of the kernel } if(!feof(h)) { result = fread(load_affinities, sizeof(int), 1, h); // to load or to save affinities } // allocating space for the t-sne solution *Y = (double*) malloc(*n * *no_dims * sizeof(double)); if(*Y == NULL) { printf("Memory allocation failed!\n"); exit(1); } // if the file has not ended, the remaining part is the initialization if(!feof(h)){ result = fread(*Y, sizeof(double), *n * *no_dims, h); if(result < *n * *no_dims){ *skip_random_init = false; }else{ *skip_random_init = true; } } else{ *skip_random_init = false; } fclose(h); printf("Read the following parameters:\n\t n %d by d %d dataset, theta %lf,\n" "\t perplexity %lf, no_dims %d, max_iter %d,\n" "\t stop_lying_iter %d, mom_switch_iter %d,\n" "\t momentum %lf, final_momentum %lf,\n" "\t learning_rate %lf, max_step_norm %lf,\n" "\t K %d, sigma %lf, nbody_algo %d,\n" "\t knn_algo %d, early_exag_coeff %lf,\n" "\t no_momentum_during_exag %d, n_trees %d, search_k %d,\n" "\t start_late_exag_iter %d, late_exag_coeff %lf\n" "\t nterms %d, interval_per_integer %lf, min_num_intervals %d, t-dist df %lf\n", *n, *d, *theta, *perplexity, *no_dims, *max_iter,*stop_lying_iter, *mom_switch_iter, *momentum, *final_momentum, *learning_rate, *max_step_norm, *K, *sigma, *nbody_algo, *knn_algo, *early_exag_coeff, *no_momentum_during_exag, *n_trees, *search_k, *start_late_exag_iter, *late_exag_coeff, *nterms, *intervals_per_integer, *min_num_intervals, *df); printf("Read the %i x %i data matrix successfully. X[0,0] = %lf\n", *n, *d, *data[0]); if(*perplexity == 0){ printf("Read the list of perplexities: "); for (int m=0; m<*perplexity_list_length; m++){ printf("%f ", (*perplexity_list)[m]); } printf("\n"); } if(*skip_random_init){ printf("Read the initialization successfully.\n"); } return true; } // Function that saves map to a t-SNE file void TSNE::save_data(const char *result_path, double* data, double* costs, int n, int d, int max_iter) { // Open file, write first 2 integers and then the data FILE *h; if((h = fopen(result_path, "w+b")) == NULL) { printf("Error: could not open data file.\n"); return; } fwrite(&n, sizeof(int), 1, h); fwrite(&d, sizeof(int), 1, h); fwrite(data, sizeof(double), n * d, h); fwrite(&max_iter, sizeof(int), 1, h); fwrite(costs, sizeof(double), max_iter, h); fclose(h); printf("Wrote the %i x %i data matrix successfully.\n", n, d); } int main(int argc, char *argv[]) { const char version_number[] = "1.2.1"; printf("=============== t-SNE v%s ===============\n", version_number); // Define some variables int N, D, no_dims, max_iter, stop_lying_iter; int K, nbody_algo, knn_algo, no_momentum_during_exag; int mom_switch_iter; double momentum, final_momentum, learning_rate, max_step_norm; int n_trees, search_k, start_late_exag_iter; double sigma, early_exag_coeff, late_exag_coeff; double perplexity, theta, *data, *initial_data; int nterms, min_num_intervals; double intervals_per_integer; int rand_seed = 0; int load_affinities = 0; const char *data_path, *result_path; unsigned int nthreads; TSNE* tsne = new TSNE(); double *Y; bool skip_random_init; double *perplexity_list; int perplexity_list_length; double df; data_path = "data.dat"; result_path = "result.dat"; nthreads = 0; if (argc >=2 ) { if ( strcmp(argv[1],version_number)) { std::cout<<"Wrapper passed wrong version number: "<< argv[1] <<std::endl; exit(-1); } }else{ std::cout<<"Please pass version number as first argument." <<std::endl; exit(-1); } if(argc >= 3) { data_path = argv[2]; } if(argc >= 4) { result_path = argv[3]; } if(argc >= 5) { nthreads = (unsigned int)strtoul(argv[4], (char **)NULL, 10); } if (nthreads == 0) { nthreads = std::thread::hardware_concurrency(); } std::cout<<"fast_tsne data_path: "<< data_path <<std::endl; std::cout<<"fast_tsne result_path: "<< result_path <<std::endl; std::cout<<"fast_tsne nthreads: "<< nthreads <<std::endl; // Read the parameters and the dataset if(tsne->load_data(data_path, &data, &Y, &N, &D, &no_dims, &theta, &perplexity, &rand_seed, &max_iter, &stop_lying_iter, &mom_switch_iter, &momentum, &final_momentum, &learning_rate, &K, &sigma, &nbody_algo, &knn_algo, &early_exag_coeff, &no_momentum_during_exag, &n_trees, &search_k, &start_late_exag_iter, &late_exag_coeff, &nterms, &intervals_per_integer, &min_num_intervals, &skip_random_init, &load_affinities, &perplexity_list_length, &perplexity_list, &df, &max_step_norm)) { bool no_momentum_during_exag_bool = true; if (no_momentum_during_exag == 0) no_momentum_during_exag_bool = false; // Now fire up the SNE implementation double* costs = (double*) calloc(max_iter, sizeof(double)); if(costs == NULL) { printf("Memory allocation failed!\n"); exit(1); } int error_code = 0; error_code = tsne->run(data, N, D, Y, no_dims, perplexity, theta, rand_seed, skip_random_init, max_iter, stop_lying_iter, mom_switch_iter, momentum, final_momentum, learning_rate, K, sigma, nbody_algo, knn_algo, early_exag_coeff, costs, no_momentum_during_exag_bool, start_late_exag_iter, late_exag_coeff, n_trees,search_k, nterms, intervals_per_integer, min_num_intervals, nthreads, load_affinities, perplexity_list_length, perplexity_list, df, max_step_norm); if (error_code < 0) { exit(error_code); } // Save the results tsne->save_data(result_path, Y, costs, N, no_dims, max_iter); // Clean up the memory free(data); data = NULL; free(Y); Y = NULL; free(costs); costs = NULL; } delete(tsne); printf("Done.\n\n"); }
82,871
37.779598
231
cpp
FIt-SNE
FIt-SNE-master/src/tsne.h
/* * * Copyright (c) 2014, Laurens van der Maaten (Delft University of Technology) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the Delft University of Technology. * 4. Neither the name of the Delft University of Technology nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY LAURENS VAN DER MAATEN ''AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL LAURENS VAN DER MAATEN BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * */ #ifndef TSNE_H #define TSNE_H static inline double sign(double x) { return (x == .0 ? .0 : (x < .0 ? -1.0 : 1.0)); } class TSNE { public: int run(double *X, int N, int D, double *Y, int no_dims, double perplexity, double theta, int rand_seed, bool skip_random_init, int max_iter, int stop_lying_iter, int mom_switch_iter, double momentum, double final_momentum, double learning_rate, int K, double sigma, int nbody_algorithm, int knn_algo, double early_exag_coeff, double *costs, bool no_momentum_during_exag, int start_late_exag_iter, double late_exag_coeff, int n_trees, int search_k, int nterms, double intervals_per_integer, int min_num_intervals, unsigned int nthreads, int load_affinities, int perplexity_list_length, double *perplexity_list, double df, double max_step_norm); bool load_data(const char *data_path, double **data, double **Y, int *n, int *d, int *no_dims, double *theta, double *perplexity, int *rand_seed, int *max_iter, int *stop_lying_iter, int *mom_switch_iter, double* momentum, double* final_momentum, double* learning_rate, int *K, double *sigma, int *nbody_algo, int *knn_algo, double* early_exag_coeff, int *no_momentum_during_exag, int *n_trees, int *search_k, int *start_late_exag_iter, double *late_exag_coeff, int *nterms, double *intervals_per_integer, int *min_num_intervals, bool *skip_random_init, int *load_affinities, int *perplexity_list_length, double **perplexity_list, double *df, double *max_step_norm); void save_data(const char *result_path, double *data, double *costs, int n, int d, int max_iter); void symmetrizeMatrix(unsigned int **row_P, unsigned int **col_P, double **val_P, int N); // should be static! private: double current_sum_Q; void computeGradient(double *P, unsigned int *inp_row_P, unsigned int *inp_col_P, double *inp_val_P, double *Y, int N, int D, double *dC, double theta, unsigned int nthreads); void computeFftGradientVariableDf(double *P, unsigned int *inp_row_P, unsigned int *inp_col_P, double *inp_val_P, double *Y, int N, int D, double *dC, int n_interpolation_points, double intervals_per_integer, int min_num_intervals, unsigned int nthreads, double df); void computeFftGradient(double *P, unsigned int *inp_row_P, unsigned int *inp_col_P, double *inp_val_P, double *Y, int N, int D, double *dC, int n_interpolation_points, double intervals_per_integer, int min_num_intervals, unsigned int nthreads); void computeFftGradientOneDVariableDf(double *P, unsigned int *inp_row_P, unsigned int *inp_col_P, double *inp_val_P, double *Y, int N, int D, double *dC, int n_interpolation_points, double intervals_per_integer, int min_num_intervals, unsigned int nthreads, double df); void computeFftGradientOneD(double *P, unsigned int *inp_row_P, unsigned int *inp_col_P, double *inp_val_P, double *Y, int N, int D, double *dC, int n_interpolation_points, double intervals_per_integer, int min_num_intervals, unsigned int nthreads); void computeExactGradient(double *P, double *Y, int N, int D, double *dC, double df); void computeExactGradientTest(double *Y, int N, int D, double df); double evaluateError(double *P, double *Y, int N, int D, double df); double evaluateError(unsigned int *row_P, unsigned int *col_P, double *val_P, double *Y, int N, int D, double theta, unsigned int nthreads); double evaluateErrorFft(unsigned int *row_P, unsigned int *col_P, double *val_P, double *Y, int N, int D, unsigned int nthreads, double df); void zeroMean(double *X, int N, int D); double distances2similarities(double *D, double *P, int N, int n, double perplexity, double sigma, bool ifSquared); double distances2similarities(double *D, double *P, int N, int n, double perplexity, double sigma, bool ifSquared, int perplexity_list_length, double *perplexity_list); void computeGaussianPerplexity(double *X, int N, int D, double *P, double perplexity, double sigma, int perplexity_list_length, double *perplexity_list); void computeGaussianPerplexity(double *X, int N, int D, unsigned int **_row_P, unsigned int **_col_P, double **_val_P, double perplexity, int K, double sigma, unsigned int nthreads, int perplexity_list_length, double *perplexity_list); int computeGaussianPerplexity(double *X, int N, int D, unsigned int **_row_P, unsigned int **_col_P, double **_val_P, double perplexity, int K, double sigma, int num_trees, int search_k, unsigned int nthreads, int perplexity_list_length, double *perplexity_list, int rand_seed); void computeSquaredEuclideanDistance(double *X, int N, int D, double *DD); double randn(); }; #endif
7,140
59.516949
144
h
FIt-SNE
FIt-SNE-master/src/vptree.h
/* * * Copyright (c) 2014, Laurens van der Maaten (Delft University of Technology) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the Delft University of Technology. * 4. Neither the name of the Delft University of Technology nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY LAURENS VAN DER MAATEN ''AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL LAURENS VAN DER MAATEN BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY * OF SUCH DAMAGE. * */ /* This code was adopted with minor modifications from Steve Hanov's great tutorial at http://stevehanov.ca/blog/index.php?id=130 */ #include <stdlib.h> #include <algorithm> #include <vector> #include <stdio.h> #include <queue> #include <limits> #include <cmath> #ifndef VPTREE_H #define VPTREE_H class DataPoint { int _ind; public: double *_x; int _D; DataPoint() { _D = 1; _ind = -1; _x = NULL; } DataPoint(int D, int ind, double *x) { _D = D; _ind = ind; _x = (double *) malloc(_D * sizeof(double)); for (int d = 0; d < _D; d++) _x[d] = x[d]; } DataPoint(const DataPoint &other) { // this makes a deep copy -- should not free anything if (this != &other) { _D = other.dimensionality(); _ind = other.index(); _x = (double *) malloc(_D * sizeof(double)); for (int d = 0; d < _D; d++) _x[d] = other.x(d); } } ~DataPoint() { if (_x != NULL) free(_x); } DataPoint &operator=(const DataPoint &other) { // asignment should free old object if (this != &other) { if (_x != NULL) free(_x); _D = other.dimensionality(); _ind = other.index(); _x = (double *) malloc(_D * sizeof(double)); for (int d = 0; d < _D; d++) _x[d] = other.x(d); } return *this; } int index() const { return _ind; } int dimensionality() const { return _D; } double x(int d) const { return _x[d]; } }; double euclidean_distance(const DataPoint &t1, const DataPoint &t2) { double dd = .0; double *x1 = t1._x; double *x2 = t2._x; double diff; for (int d = 0; d < t1._D; d++) { diff = (x1[d] - x2[d]); dd += diff * diff; } return sqrt(dd); } template<typename T, double (*distance)(const T &, const T &)> class VpTree { public: // Default constructor VpTree() : _root(0) {} // Destructor ~VpTree() { delete _root; } // Function to create a new VpTree from data void create(const std::vector <T> &items) { delete _root; _items = items; _root = buildFromPoints(0, items.size()); } // Function that uses the tree to find the k nearest neighbors of target void search(const T &target, int k, std::vector <T> *results, std::vector<double> *distances) { // Use a priority queue to store intermediate results on std::priority_queue <HeapItem> heap; // Variable that tracks the distance to the farthest point in our results // Perform the search double _tau = DBL_MAX; search(_root, target, k, heap, _tau); // Gather final results results->clear(); distances->clear(); while (!heap.empty()) { results->push_back(_items[heap.top().index]); distances->push_back(heap.top().dist); heap.pop(); } // Results are in reverse order std::reverse(results->begin(), results->end()); std::reverse(distances->begin(), distances->end()); } private: std::vector <T> _items; // Single node of a VP tree (has a point and radius; left children are closer to point than the radius) struct Node { int index; // index of point in node double threshold; // radius(?) Node *left; // points closer by than threshold Node *right; // points farther away than threshold Node() : index(0), threshold(0.), left(0), right(0) {} ~Node() { // destructor delete left; delete right; } } *_root; // An item on the intermediate result queue struct HeapItem { HeapItem(int index, double dist) : index(index), dist(dist) {} int index; double dist; bool operator<(const HeapItem &o) const { return dist < o.dist; } }; // Distance comparator for use in std::nth_element struct DistanceComparator { const T &item; DistanceComparator(const T &item) : item(item) {} bool operator()(const T &a, const T &b) { return distance(item, a) < distance(item, b); } }; // Function that (recursively) fills the tree Node *buildFromPoints(int lower, int upper) { if (upper == lower) { // indicates that we're done here! return NULL; } // Lower index is center of current node Node *node = new Node(); node->index = lower; if (upper - lower > 1) { // if we did not arrive at leaf yet // Choose an arbitrary point and move it to the start int i = (int) ((double) rand() / RAND_MAX * (upper - lower - 1)) + lower; std::swap(_items[lower], _items[i]); // Partition around the median distance int median = (upper + lower) / 2; std::nth_element(_items.begin() + lower + 1, _items.begin() + median, _items.begin() + upper, DistanceComparator(_items[lower])); // Threshold of the new node will be the distance to the median node->threshold = distance(_items[lower], _items[median]); // Recursively build tree node->index = lower; node->left = buildFromPoints(lower + 1, median); node->right = buildFromPoints(median, upper); } // Return result return node; } // Helper function that searches the tree void search(Node *node, const T &target, int k, std::priority_queue <HeapItem> &heap, double &_tau) { if (node == NULL) return; // indicates that we're done here // Compute distance between target and current node double dist = distance(_items[node->index], target); // If current node within radius tau if (dist < _tau) { if (heap.size() == k) heap.pop(); // remove furthest node from result list (if we already have k results) heap.push(HeapItem(node->index, dist)); // add current node to result list if (heap.size() == k) _tau = heap.top().dist; // update value of tau (farthest point in result list) } // Return if we arrived at a leaf if (node->left == NULL && node->right == NULL) { return; } // If the target lies within the radius of ball if (dist < node->threshold) { if (dist - _tau <= node->threshold) { // if there can still be neighbors inside the ball, recursively search left child first search(node->left, target, k, heap, _tau); } if (dist + _tau >= node->threshold) { // if there can still be neighbors outside the ball, recursively search right child search(node->right, target, k, heap, _tau); } // If the target lies outsize the radius of the ball } else { if (dist + _tau >= node->threshold) { // if there can still be neighbors outside the ball, recursively search right child first search(node->right, target, k, heap, _tau); } if (dist - _tau <= node->threshold) { // if there can still be neighbors inside the ball, recursively search left child search(node->left, target, k, heap, _tau); } } } }; #endif
9,593
32.90106
132
h
FIt-SNE
FIt-SNE-master/src/progress_bar/ProgressBar.hpp
#ifndef PROGRESSBAR_PROGRESSBAR_HPP #define PROGRESSBAR_PROGRESSBAR_HPP #include <chrono> #include <iostream> class ProgressBar { private: unsigned int ticks = 0; const unsigned int total_ticks; const unsigned int bar_width; const char complete_char = '='; const char incomplete_char = ' '; const std::chrono::steady_clock::time_point start_time = std::chrono::steady_clock::now(); public: ProgressBar(unsigned int total, unsigned int width, char complete, char incomplete) : total_ticks {total}, bar_width {width}, complete_char {complete}, incomplete_char {incomplete} {} ProgressBar(unsigned int total, unsigned int width) : total_ticks {total}, bar_width {width} {} unsigned int operator++() { return ++ticks; } void display() const { float progress = (float) ticks / total_ticks; int pos = (int) (bar_width * progress); std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now(); auto time_elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(now-start_time).count(); std::cout << "["; for (int i = 0; i < bar_width; ++i) { if (i < pos) std::cout << complete_char; else if (i == pos) std::cout << ">"; else std::cout << incomplete_char; } std::cout << "] " << int(progress * 100.0) << "% " << float(time_elapsed) / 1000.0 << "s\r"; std::cout.flush(); } void done() const { display(); std::cout << std::endl; } }; #endif //PROGRESSBAR_PROGRESSBAR_HPP
1,610
29.396226
109
hpp
FIt-SNE
FIt-SNE-master/src/winlibs/fftw3.h
/* * Copyright (c) 2003, 2007-14 Matteo Frigo * Copyright (c) 2003, 2007-14 Massachusetts Institute of Technology * * The following statement of license applies *only* to this header file, * and *not* to the other files distributed with FFTW or derived therefrom: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /***************************** NOTE TO USERS ********************************* * * THIS IS A HEADER FILE, NOT A MANUAL * * If you want to know how to use FFTW, please read the manual, * online at http://www.fftw.org/doc/ and also included with FFTW. * For a quick start, see the manual's tutorial section. * * (Reading header files to learn how to use a library is a habit * stemming from code lacking a proper manual. Arguably, it's a * *bad* habit in most cases, because header files can contain * interfaces that are not part of the public, stable API.) * ****************************************************************************/ #ifndef FFTW3_H #define FFTW3_H #include <stdio.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* If <complex.h> is included, use the C99 complex type. Otherwise define a type bit-compatible with C99 complex */ #if !defined(FFTW_NO_Complex) && defined(_Complex_I) && defined(complex) && defined(I) # define FFTW_DEFINE_COMPLEX(R, C) typedef R _Complex C #else # define FFTW_DEFINE_COMPLEX(R, C) typedef R C[2] #endif #define FFTW_CONCAT(prefix, name) prefix ## name #define FFTW_MANGLE_DOUBLE(name) FFTW_CONCAT(fftw_, name) #define FFTW_MANGLE_FLOAT(name) FFTW_CONCAT(fftwf_, name) #define FFTW_MANGLE_LONG_DOUBLE(name) FFTW_CONCAT(fftwl_, name) #define FFTW_MANGLE_QUAD(name) FFTW_CONCAT(fftwq_, name) /* IMPORTANT: for Windows compilers, you should add a line */ #define FFTW_DLL /* here and in kernel/ifftw.h if you are compiling/using FFTW as a DLL, in order to do the proper importing/exporting, or alternatively compile with -DFFTW_DLL or the equivalent command-line flag. This is not necessary under MinGW/Cygwin, where libtool does the imports/exports automatically. */ #if defined(FFTW_DLL) && (defined(_WIN32) || defined(__WIN32__)) /* annoying Windows syntax for shared-library declarations */ # if defined(COMPILING_FFTW) /* defined in api.h when compiling FFTW */ # define FFTW_EXTERN extern __declspec(dllexport) # else /* user is calling FFTW; import symbol */ # define FFTW_EXTERN extern __declspec(dllimport) # endif #else # define FFTW_EXTERN extern #endif enum fftw_r2r_kind_do_not_use_me { FFTW_R2HC=0, FFTW_HC2R=1, FFTW_DHT=2, FFTW_REDFT00=3, FFTW_REDFT01=4, FFTW_REDFT10=5, FFTW_REDFT11=6, FFTW_RODFT00=7, FFTW_RODFT01=8, FFTW_RODFT10=9, FFTW_RODFT11=10 }; struct fftw_iodim_do_not_use_me { int n; /* dimension size */ int is; /* input stride */ int os; /* output stride */ }; #include <stddef.h> /* for ptrdiff_t */ struct fftw_iodim64_do_not_use_me { ptrdiff_t n; /* dimension size */ ptrdiff_t is; /* input stride */ ptrdiff_t os; /* output stride */ }; typedef void (*fftw_write_char_func_do_not_use_me)(char c, void *); typedef int (*fftw_read_char_func_do_not_use_me)(void *); /* huge second-order macro that defines prototypes for all API functions. We expand this macro for each supported precision X: name-mangling macro R: real data type C: complex data type */ #define FFTW_DEFINE_API(X, R, C) \ \ FFTW_DEFINE_COMPLEX(R, C); \ \ typedef struct X(plan_s) *X(plan); \ \ typedef struct fftw_iodim_do_not_use_me X(iodim); \ typedef struct fftw_iodim64_do_not_use_me X(iodim64); \ \ typedef enum fftw_r2r_kind_do_not_use_me X(r2r_kind); \ \ typedef fftw_write_char_func_do_not_use_me X(write_char_func); \ typedef fftw_read_char_func_do_not_use_me X(read_char_func); \ \ FFTW_EXTERN void X(execute)(const X(plan) p); \ \ FFTW_EXTERN X(plan) X(plan_dft)(int rank, const int *n, \ C *in, C *out, int sign, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_dft_1d)(int n, C *in, C *out, int sign, \ unsigned flags); \ FFTW_EXTERN X(plan) X(plan_dft_2d)(int n0, int n1, \ C *in, C *out, int sign, unsigned flags); \ FFTW_EXTERN X(plan) X(plan_dft_3d)(int n0, int n1, int n2, \ C *in, C *out, int sign, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_many_dft)(int rank, const int *n, \ int howmany, \ C *in, const int *inembed, \ int istride, int idist, \ C *out, const int *onembed, \ int ostride, int odist, \ int sign, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru_dft)(int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ C *in, C *out, \ int sign, unsigned flags); \ FFTW_EXTERN X(plan) X(plan_guru_split_dft)(int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ R *ri, R *ii, R *ro, R *io, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru64_dft)(int rank, \ const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ C *in, C *out, \ int sign, unsigned flags); \ FFTW_EXTERN X(plan) X(plan_guru64_split_dft)(int rank, \ const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ R *ri, R *ii, R *ro, R *io, \ unsigned flags); \ \ FFTW_EXTERN void X(execute_dft)(const X(plan) p, C *in, C *out); \ FFTW_EXTERN void X(execute_split_dft)(const X(plan) p, R *ri, R *ii, \ R *ro, R *io); \ \ FFTW_EXTERN X(plan) X(plan_many_dft_r2c)(int rank, const int *n, \ int howmany, \ R *in, const int *inembed, \ int istride, int idist, \ C *out, const int *onembed, \ int ostride, int odist, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_dft_r2c)(int rank, const int *n, \ R *in, C *out, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_dft_r2c_1d)(int n,R *in,C *out,unsigned flags); \ FFTW_EXTERN X(plan) X(plan_dft_r2c_2d)(int n0, int n1, \ R *in, C *out, unsigned flags); \ FFTW_EXTERN X(plan) X(plan_dft_r2c_3d)(int n0, int n1, \ int n2, \ R *in, C *out, unsigned flags); \ \ \ FFTW_EXTERN X(plan) X(plan_many_dft_c2r)(int rank, const int *n, \ int howmany, \ C *in, const int *inembed, \ int istride, int idist, \ R *out, const int *onembed, \ int ostride, int odist, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_dft_c2r)(int rank, const int *n, \ C *in, R *out, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_dft_c2r_1d)(int n,C *in,R *out,unsigned flags); \ FFTW_EXTERN X(plan) X(plan_dft_c2r_2d)(int n0, int n1, \ C *in, R *out, unsigned flags); \ FFTW_EXTERN X(plan) X(plan_dft_c2r_3d)(int n0, int n1, \ int n2, \ C *in, R *out, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru_dft_r2c)(int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ R *in, C *out, \ unsigned flags); \ FFTW_EXTERN X(plan) X(plan_guru_dft_c2r)(int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ C *in, R *out, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru_split_dft_r2c)( \ int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ R *in, R *ro, R *io, \ unsigned flags); \ FFTW_EXTERN X(plan) X(plan_guru_split_dft_c2r)( \ int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ R *ri, R *ii, R *out, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru64_dft_r2c)(int rank, \ const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ R *in, C *out, \ unsigned flags); \ FFTW_EXTERN X(plan) X(plan_guru64_dft_c2r)(int rank, \ const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ C *in, R *out, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru64_split_dft_r2c)( \ int rank, const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ R *in, R *ro, R *io, \ unsigned flags); \ FFTW_EXTERN X(plan) X(plan_guru64_split_dft_c2r)( \ int rank, const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ R *ri, R *ii, R *out, \ unsigned flags); \ \ FFTW_EXTERN void X(execute_dft_r2c)(const X(plan) p, R *in, C *out); \ FFTW_EXTERN void X(execute_dft_c2r)(const X(plan) p, C *in, R *out); \ \ FFTW_EXTERN void X(execute_split_dft_r2c)(const X(plan) p, \ R *in, R *ro, R *io); \ FFTW_EXTERN void X(execute_split_dft_c2r)(const X(plan) p, \ R *ri, R *ii, R *out); \ \ FFTW_EXTERN X(plan) X(plan_many_r2r)(int rank, const int *n, \ int howmany, \ R *in, const int *inembed, \ int istride, int idist, \ R *out, const int *onembed, \ int ostride, int odist, \ const X(r2r_kind) *kind, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_r2r)(int rank, const int *n, R *in, R *out, \ const X(r2r_kind) *kind, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_r2r_1d)(int n, R *in, R *out, \ X(r2r_kind) kind, unsigned flags); \ FFTW_EXTERN X(plan) X(plan_r2r_2d)(int n0, int n1, R *in, R *out, \ X(r2r_kind) kind0, X(r2r_kind) kind1, \ unsigned flags); \ FFTW_EXTERN X(plan) X(plan_r2r_3d)(int n0, int n1, int n2, \ R *in, R *out, X(r2r_kind) kind0, \ X(r2r_kind) kind1, X(r2r_kind) kind2, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru_r2r)(int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ R *in, R *out, \ const X(r2r_kind) *kind, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru64_r2r)(int rank, const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ R *in, R *out, \ const X(r2r_kind) *kind, unsigned flags); \ \ FFTW_EXTERN void X(execute_r2r)(const X(plan) p, R *in, R *out); \ \ FFTW_EXTERN void X(destroy_plan)(X(plan) p); \ FFTW_EXTERN void X(forget_wisdom)(void); \ FFTW_EXTERN void X(cleanup)(void); \ \ FFTW_EXTERN void X(set_timelimit)(double t); \ \ FFTW_EXTERN void X(plan_with_nthreads)(int nthreads); \ FFTW_EXTERN int X(init_threads)(void); \ FFTW_EXTERN void X(cleanup_threads)(void); \ FFTW_EXTERN void X(make_planner_thread_safe)(void); \ \ FFTW_EXTERN int X(export_wisdom_to_filename)(const char *filename); \ FFTW_EXTERN void X(export_wisdom_to_file)(FILE *output_file); \ FFTW_EXTERN char *X(export_wisdom_to_string)(void); \ FFTW_EXTERN void X(export_wisdom)(X(write_char_func) write_char, \ void *data); \ FFTW_EXTERN int X(import_system_wisdom)(void); \ FFTW_EXTERN int X(import_wisdom_from_filename)(const char *filename); \ FFTW_EXTERN int X(import_wisdom_from_file)(FILE *input_file); \ FFTW_EXTERN int X(import_wisdom_from_string)(const char *input_string); \ FFTW_EXTERN int X(import_wisdom)(X(read_char_func) read_char, void *data); \ \ FFTW_EXTERN void X(fprint_plan)(const X(plan) p, FILE *output_file); \ FFTW_EXTERN void X(print_plan)(const X(plan) p); \ FFTW_EXTERN char *X(sprint_plan)(const X(plan) p); \ \ FFTW_EXTERN void *X(malloc)(size_t n); \ FFTW_EXTERN R *X(alloc_real)(size_t n); \ FFTW_EXTERN C *X(alloc_complex)(size_t n); \ FFTW_EXTERN void X(free)(void *p); \ \ FFTW_EXTERN void X(flops)(const X(plan) p, \ double *add, double *mul, double *fmas); \ FFTW_EXTERN double X(estimate_cost)(const X(plan) p); \ FFTW_EXTERN double X(cost)(const X(plan) p); \ \ FFTW_EXTERN int X(alignment_of)(R *p); \ FFTW_EXTERN const char X(version)[]; \ FFTW_EXTERN const char X(cc)[]; \ FFTW_EXTERN const char X(codelet_optim)[]; /* end of FFTW_DEFINE_API macro */ FFTW_DEFINE_API(FFTW_MANGLE_DOUBLE, double, fftw_complex) FFTW_DEFINE_API(FFTW_MANGLE_FLOAT, float, fftwf_complex) FFTW_DEFINE_API(FFTW_MANGLE_LONG_DOUBLE, long double, fftwl_complex) /* __float128 (quad precision) is a gcc extension on i386, x86_64, and ia64 for gcc >= 4.6 (compiled in FFTW with --enable-quad-precision) */ #if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) \ && !(defined(__ICC) || defined(__INTEL_COMPILER) || defined(__CUDACC__) || defined(__PGI)) \ && (defined(__i386__) || defined(__x86_64__) || defined(__ia64__)) # if !defined(FFTW_NO_Complex) && defined(_Complex_I) && defined(complex) && defined(I) /* note: __float128 is a typedef, which is not supported with the _Complex keyword in gcc, so instead we use this ugly __attribute__ version. However, we can't simply pass the __attribute__ version to FFTW_DEFINE_API because the __attribute__ confuses gcc in pointer types. Hence redefining FFTW_DEFINE_COMPLEX. Ugh. */ # undef FFTW_DEFINE_COMPLEX # define FFTW_DEFINE_COMPLEX(R, C) typedef _Complex float __attribute__((mode(TC))) C # endif FFTW_DEFINE_API(FFTW_MANGLE_QUAD, __float128, fftwq_complex) #endif #define FFTW_FORWARD (-1) #define FFTW_BACKWARD (+1) #define FFTW_NO_TIMELIMIT (-1.0) /* documented flags */ #define FFTW_MEASURE (0U) #define FFTW_DESTROY_INPUT (1U << 0) #define FFTW_UNALIGNED (1U << 1) #define FFTW_CONSERVE_MEMORY (1U << 2) #define FFTW_EXHAUSTIVE (1U << 3) /* NO_EXHAUSTIVE is default */ #define FFTW_PRESERVE_INPUT (1U << 4) /* cancels FFTW_DESTROY_INPUT */ #define FFTW_PATIENT (1U << 5) /* IMPATIENT is default */ #define FFTW_ESTIMATE (1U << 6) #define FFTW_WISDOM_ONLY (1U << 21) /* undocumented beyond-guru flags */ #define FFTW_ESTIMATE_PATIENT (1U << 7) #define FFTW_BELIEVE_PCOST (1U << 8) #define FFTW_NO_DFT_R2HC (1U << 9) #define FFTW_NO_NONTHREADED (1U << 10) #define FFTW_NO_BUFFERING (1U << 11) #define FFTW_NO_INDIRECT_OP (1U << 12) #define FFTW_ALLOW_LARGE_GENERIC (1U << 13) /* NO_LARGE_GENERIC is default */ #define FFTW_NO_RANK_SPLITS (1U << 14) #define FFTW_NO_VRANK_SPLITS (1U << 15) #define FFTW_NO_VRECURSE (1U << 16) #define FFTW_NO_SIMD (1U << 17) #define FFTW_NO_SLOW (1U << 18) #define FFTW_NO_FIXED_RADIX_LARGE_N (1U << 19) #define FFTW_ALLOW_PRUNING (1U << 20) #ifdef __cplusplus } /* extern "C" */ #endif /* __cplusplus */ #endif /* FFTW3_H */
18,102
42.516827
93
h
FIt-SNE
FIt-SNE-master/src/winlibs/mman.c
#include <windows.h> #include <errno.h> #include <io.h> #include "mman.h" #ifndef FILE_MAP_EXECUTE #define FILE_MAP_EXECUTE 0x0020 #endif /* FILE_MAP_EXECUTE */ static int __map_mman_error(const DWORD err, const int deferr) { if (err == 0) return 0; //TODO: implement return err; } static DWORD __map_mmap_prot_page(const int prot) { DWORD protect = 0; if (prot == PROT_NONE) return protect; if ((prot & PROT_EXEC) != 0) { protect = ((prot & PROT_WRITE) != 0) ? PAGE_EXECUTE_READWRITE : PAGE_EXECUTE_READ; } else { protect = ((prot & PROT_WRITE) != 0) ? PAGE_READWRITE : PAGE_READONLY; } return protect; } static DWORD __map_mmap_prot_file(const int prot) { DWORD desiredAccess = 0; if (prot == PROT_NONE) return desiredAccess; if ((prot & PROT_READ) != 0) desiredAccess |= FILE_MAP_READ; if ((prot & PROT_WRITE) != 0) desiredAccess |= FILE_MAP_WRITE; if ((prot & PROT_EXEC) != 0) desiredAccess |= FILE_MAP_EXECUTE; return desiredAccess; } void* mmap(void *addr, size_t len, int prot, int flags, int fildes, OffsetType off) { HANDLE fm, h; void * map = MAP_FAILED; #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4293) #endif const DWORD dwFileOffsetLow = (sizeof(OffsetType) <= sizeof(DWORD)) ? (DWORD)off : (DWORD)(off & 0xFFFFFFFFL); const DWORD dwFileOffsetHigh = (sizeof(OffsetType) <= sizeof(DWORD)) ? (DWORD)0 : (DWORD)((off >> 32) & 0xFFFFFFFFL); const DWORD protect = __map_mmap_prot_page(prot); const DWORD desiredAccess = __map_mmap_prot_file(prot); const OffsetType maxSize = off + (OffsetType)len; const DWORD dwMaxSizeLow = (sizeof(OffsetType) <= sizeof(DWORD)) ? (DWORD)maxSize : (DWORD)(maxSize & 0xFFFFFFFFL); const DWORD dwMaxSizeHigh = (sizeof(OffsetType) <= sizeof(DWORD)) ? (DWORD)0 : (DWORD)((maxSize >> 32) & 0xFFFFFFFFL); #ifdef _MSC_VER #pragma warning(pop) #endif errno = 0; if (len == 0 /* Unsupported flag combinations */ || (flags & MAP_FIXED) != 0 /* Usupported protection combinations */ || prot == PROT_EXEC) { errno = EINVAL; return MAP_FAILED; } h = ((flags & MAP_ANONYMOUS) == 0) ? (HANDLE)_get_osfhandle(fildes) : INVALID_HANDLE_VALUE; if ((flags & MAP_ANONYMOUS) == 0 && h == INVALID_HANDLE_VALUE) { errno = EBADF; return MAP_FAILED; } fm = CreateFileMapping(h, NULL, protect, dwMaxSizeHigh, dwMaxSizeLow, NULL); if (fm == NULL) { errno = __map_mman_error(GetLastError(), EPERM); return MAP_FAILED; } map = MapViewOfFile(fm, desiredAccess, dwFileOffsetHigh, dwFileOffsetLow, len); CloseHandle(fm); if (map == NULL) { errno = __map_mman_error(GetLastError(), EPERM); return MAP_FAILED; } return map; } int munmap(void *addr, size_t len) { if (UnmapViewOfFile(addr)) return 0; errno = __map_mman_error(GetLastError(), EPERM); return -1; } int _mprotect(void *addr, size_t len, int prot) { DWORD newProtect = __map_mmap_prot_page(prot); DWORD oldProtect = 0; if (VirtualProtect(addr, len, newProtect, &oldProtect)) return 0; errno = __map_mman_error(GetLastError(), EPERM); return -1; } int msync(void *addr, size_t len, int flags) { if (FlushViewOfFile(addr, len)) return 0; errno = __map_mman_error(GetLastError(), EPERM); return -1; } int mlock(const void *addr, size_t len) { if (VirtualLock((LPVOID)addr, len)) return 0; errno = __map_mman_error(GetLastError(), EPERM); return -1; } int munlock(const void *addr, size_t len) { if (VirtualUnlock((LPVOID)addr, len)) return 0; errno = __map_mman_error(GetLastError(), EPERM); return -1; } #if !defined(__MINGW32__) int ftruncate(int fd, unsigned int size) { if (fd < 0) { errno = EBADF; return -1; } HANDLE h = (HANDLE)_get_osfhandle(fd); unsigned int cur = SetFilePointer(h, 0, NULL, FILE_CURRENT); if (cur == ~0 || SetFilePointer(h, size, NULL, FILE_BEGIN) == ~0 || !SetEndOfFile(h)) { int error = GetLastError(); switch (GetLastError()) { case ERROR_INVALID_HANDLE: errno = EBADF; break; default: errno = EIO; break; } return -1; } return 0; } #endif
4,644
21.658537
88
c
FIt-SNE
FIt-SNE-master/src/winlibs/mman.h
/* * sys/mman.h * mman-win32 */ #ifndef _SYS_MMAN_H_ #define _SYS_MMAN_H_ #ifndef _WIN32_WINNT // Allow use of features specific to Windows XP or later. #define _WIN32_WINNT 0x0501 // Change this to the appropriate value to target other versions of Windows. #endif /* All the headers include this file. */ #ifndef _MSC_VER #include <_mingw.h> #endif #if defined(MMAN_LIBRARY_DLL) /* Windows shared libraries (DLL) must be declared export when building the lib and import when building the application which links against the library. */ #if defined(MMAN_LIBRARY) #define MMANSHARED_EXPORT __declspec(dllexport) #else #define MMANSHARED_EXPORT __declspec(dllimport) #endif /* MMAN_LIBRARY */ #else /* Static libraries do not require a __declspec attribute.*/ #define MMANSHARED_EXPORT #endif /* MMAN_LIBRARY_DLL */ /* Determine offset type */ #include <stdint.h> #if defined(_WIN64) typedef int64_t OffsetType; #else typedef uint32_t OffsetType; #endif #include <sys/types.h> #ifdef __cplusplus extern "C" { #endif #define PROT_NONE 0 #define PROT_READ 1 #define PROT_WRITE 2 #define PROT_EXEC 4 #define MAP_FILE 0 #define MAP_SHARED 1 #define MAP_PRIVATE 2 #define MAP_TYPE 0xf #define MAP_FIXED 0x10 #define MAP_ANONYMOUS 0x20 #define MAP_ANON MAP_ANONYMOUS #define MAP_FAILED ((void *)-1) /* Flags for msync. */ #define MS_ASYNC 1 #define MS_SYNC 2 #define MS_INVALIDATE 4 MMANSHARED_EXPORT void* mmap(void *addr, size_t len, int prot, int flags, int fildes, OffsetType off); MMANSHARED_EXPORT int munmap(void *addr, size_t len); MMANSHARED_EXPORT int _mprotect(void *addr, size_t len, int prot); MMANSHARED_EXPORT int msync(void *addr, size_t len, int flags); MMANSHARED_EXPORT int mlock(const void *addr, size_t len); MMANSHARED_EXPORT int munlock(const void *addr, size_t len); #if !defined(__MINGW32__) MMANSHARED_EXPORT int ftruncate(int fd, unsigned int size); #endif #ifdef __cplusplus } #endif #endif /* _SYS_MMAN_H_ */
2,083
24.108434
109
h
FIt-SNE
FIt-SNE-master/src/winlibs/stdafx.cpp
// stdafx.cpp : source file that includes just the standard includes // FItSNE.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
285
30.777778
68
cpp
FIt-SNE
FIt-SNE-master/src/winlibs/stdafx.h
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #ifdef _WIN32 #define _CRT_SECURE_NO_WARNINGS #define _CRT_SECURE_NO_DEPRECATE #include "targetver.h" #include <stdio.h> #include <tchar.h> #endif
327
15.4
66
h
FIt-SNE
FIt-SNE-master/src/winlibs/targetver.h
#pragma once // Including SDKDDKVer.h defines the highest available Windows platform. // If you wish to build your application for a previous Windows platform, include WinSDKVer.h and // set the _WIN32_WINNT macro to the platform you wish to support before including SDKDDKVer.h. #include <SDKDDKVer.h>
306
33.111111
97
h
FIt-SNE
FIt-SNE-master/src/winlibs/unistd.h
#ifndef _UNISTD_H #define _UNISTD_H 1 /* This is intended as a drop-in replacement for unistd.h on Windows. * Please add functionality as neeeded. * https://stackoverflow.com/a/826027/1202830 */ #include <stdlib.h> #include <io.h> //#include <getopt.h> /* getopt at: https://gist.github.com/ashelly/7776712 */ #include <process.h> /* for getpid() and the exec..() family */ #include <direct.h> /* for _getcwd() and _chdir() */ #define srandom srand #define random rand /* Values for the second argument to access. These may be OR'd together. */ #define R_OK 4 /* Test for read permission. */ #define W_OK 2 /* Test for write permission. */ //#define X_OK 1 /* execute permission - unsupported in windows*/ #define F_OK 0 /* Test for existence. */ #define access _access #define dup2 _dup2 #define execve _execve #define ftruncate _chsize #define unlink _unlink #define fileno _fileno #define getcwd _getcwd #define chdir _chdir #define isatty _isatty #define lseek _lseek /* read, write, and close are NOT being #defined here, because while there are file handle specific versions for Windows, they probably don't work for sockets. You need to look at your app and consider whether to call e.g. closesocket(). */ #ifdef _WIN64 #define ssize_t __int64 #else #define ssize_t long #endif #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #define STDERR_FILENO 2 /* should be in some equivalent to <sys/types.h> */ //typedef __int8 int8_t; //typedef __int16 int16_t; //typedef __int32 int32_t; //typedef __int64 int64_t; //typedef unsigned __int8 uint8_t; //typedef unsigned __int16 uint16_t; //typedef unsigned __int32 uint32_t; //typedef unsigned __int64 uint64_t; #endif /* unistd.h */
1,788
30.946429
240
h
FIt-SNE
FIt-SNE-master/src/winlibs/fftw/fftw3.f
INTEGER FFTW_R2HC PARAMETER (FFTW_R2HC=0) INTEGER FFTW_HC2R PARAMETER (FFTW_HC2R=1) INTEGER FFTW_DHT PARAMETER (FFTW_DHT=2) INTEGER FFTW_REDFT00 PARAMETER (FFTW_REDFT00=3) INTEGER FFTW_REDFT01 PARAMETER (FFTW_REDFT01=4) INTEGER FFTW_REDFT10 PARAMETER (FFTW_REDFT10=5) INTEGER FFTW_REDFT11 PARAMETER (FFTW_REDFT11=6) INTEGER FFTW_RODFT00 PARAMETER (FFTW_RODFT00=7) INTEGER FFTW_RODFT01 PARAMETER (FFTW_RODFT01=8) INTEGER FFTW_RODFT10 PARAMETER (FFTW_RODFT10=9) INTEGER FFTW_RODFT11 PARAMETER (FFTW_RODFT11=10) INTEGER FFTW_FORWARD PARAMETER (FFTW_FORWARD=-1) INTEGER FFTW_BACKWARD PARAMETER (FFTW_BACKWARD=+1) INTEGER FFTW_MEASURE PARAMETER (FFTW_MEASURE=0) INTEGER FFTW_DESTROY_INPUT PARAMETER (FFTW_DESTROY_INPUT=1) INTEGER FFTW_UNALIGNED PARAMETER (FFTW_UNALIGNED=2) INTEGER FFTW_CONSERVE_MEMORY PARAMETER (FFTW_CONSERVE_MEMORY=4) INTEGER FFTW_EXHAUSTIVE PARAMETER (FFTW_EXHAUSTIVE=8) INTEGER FFTW_PRESERVE_INPUT PARAMETER (FFTW_PRESERVE_INPUT=16) INTEGER FFTW_PATIENT PARAMETER (FFTW_PATIENT=32) INTEGER FFTW_ESTIMATE PARAMETER (FFTW_ESTIMATE=64) INTEGER FFTW_WISDOM_ONLY PARAMETER (FFTW_WISDOM_ONLY=2097152) INTEGER FFTW_ESTIMATE_PATIENT PARAMETER (FFTW_ESTIMATE_PATIENT=128) INTEGER FFTW_BELIEVE_PCOST PARAMETER (FFTW_BELIEVE_PCOST=256) INTEGER FFTW_NO_DFT_R2HC PARAMETER (FFTW_NO_DFT_R2HC=512) INTEGER FFTW_NO_NONTHREADED PARAMETER (FFTW_NO_NONTHREADED=1024) INTEGER FFTW_NO_BUFFERING PARAMETER (FFTW_NO_BUFFERING=2048) INTEGER FFTW_NO_INDIRECT_OP PARAMETER (FFTW_NO_INDIRECT_OP=4096) INTEGER FFTW_ALLOW_LARGE_GENERIC PARAMETER (FFTW_ALLOW_LARGE_GENERIC=8192) INTEGER FFTW_NO_RANK_SPLITS PARAMETER (FFTW_NO_RANK_SPLITS=16384) INTEGER FFTW_NO_VRANK_SPLITS PARAMETER (FFTW_NO_VRANK_SPLITS=32768) INTEGER FFTW_NO_VRECURSE PARAMETER (FFTW_NO_VRECURSE=65536) INTEGER FFTW_NO_SIMD PARAMETER (FFTW_NO_SIMD=131072) INTEGER FFTW_NO_SLOW PARAMETER (FFTW_NO_SLOW=262144) INTEGER FFTW_NO_FIXED_RADIX_LARGE_N PARAMETER (FFTW_NO_FIXED_RADIX_LARGE_N=524288) INTEGER FFTW_ALLOW_PRUNING PARAMETER (FFTW_ALLOW_PRUNING=1048576)
2,447
32.534247
52
f
FIt-SNE
FIt-SNE-master/src/winlibs/fftw/fftw3.h
/* * Copyright (c) 2003, 2007-14 Matteo Frigo * Copyright (c) 2003, 2007-14 Massachusetts Institute of Technology * * The following statement of license applies *only* to this header file, * and *not* to the other files distributed with FFTW or derived therefrom: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /***************************** NOTE TO USERS ********************************* * * THIS IS A HEADER FILE, NOT A MANUAL * * If you want to know how to use FFTW, please read the manual, * online at http://www.fftw.org/doc/ and also included with FFTW. * For a quick start, see the manual's tutorial section. * * (Reading header files to learn how to use a library is a habit * stemming from code lacking a proper manual. Arguably, it's a * *bad* habit in most cases, because header files can contain * interfaces that are not part of the public, stable API.) * ****************************************************************************/ #ifndef FFTW3_H #define FFTW3_H #include <stdio.h> #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ /* If <complex.h> is included, use the C99 complex type. Otherwise define a type bit-compatible with C99 complex */ #if !defined(FFTW_NO_Complex) && defined(_Complex_I) && defined(complex) && defined(I) # define FFTW_DEFINE_COMPLEX(R, C) typedef R _Complex C #else # define FFTW_DEFINE_COMPLEX(R, C) typedef R C[2] #endif #define FFTW_CONCAT(prefix, name) prefix ## name #define FFTW_MANGLE_DOUBLE(name) FFTW_CONCAT(fftw_, name) #define FFTW_MANGLE_FLOAT(name) FFTW_CONCAT(fftwf_, name) #define FFTW_MANGLE_LONG_DOUBLE(name) FFTW_CONCAT(fftwl_, name) #define FFTW_MANGLE_QUAD(name) FFTW_CONCAT(fftwq_, name) /* IMPORTANT: for Windows compilers, you should add a line */ #define FFTW_DLL /* here and in kernel/ifftw.h if you are compiling/using FFTW as a DLL, in order to do the proper importing/exporting, or alternatively compile with -DFFTW_DLL or the equivalent command-line flag. This is not necessary under MinGW/Cygwin, where libtool does the imports/exports automatically. */ #if defined(FFTW_DLL) && (defined(_WIN32) || defined(__WIN32__)) /* annoying Windows syntax for shared-library declarations */ # if defined(COMPILING_FFTW) /* defined in api.h when compiling FFTW */ # define FFTW_EXTERN extern __declspec(dllexport) # else /* user is calling FFTW; import symbol */ # define FFTW_EXTERN extern __declspec(dllimport) # endif #else # define FFTW_EXTERN extern #endif enum fftw_r2r_kind_do_not_use_me { FFTW_R2HC=0, FFTW_HC2R=1, FFTW_DHT=2, FFTW_REDFT00=3, FFTW_REDFT01=4, FFTW_REDFT10=5, FFTW_REDFT11=6, FFTW_RODFT00=7, FFTW_RODFT01=8, FFTW_RODFT10=9, FFTW_RODFT11=10 }; struct fftw_iodim_do_not_use_me { int n; /* dimension size */ int is; /* input stride */ int os; /* output stride */ }; #include <stddef.h> /* for ptrdiff_t */ struct fftw_iodim64_do_not_use_me { ptrdiff_t n; /* dimension size */ ptrdiff_t is; /* input stride */ ptrdiff_t os; /* output stride */ }; typedef void (*fftw_write_char_func_do_not_use_me)(char c, void *); typedef int (*fftw_read_char_func_do_not_use_me)(void *); /* huge second-order macro that defines prototypes for all API functions. We expand this macro for each supported precision X: name-mangling macro R: real data type C: complex data type */ #define FFTW_DEFINE_API(X, R, C) \ \ FFTW_DEFINE_COMPLEX(R, C); \ \ typedef struct X(plan_s) *X(plan); \ \ typedef struct fftw_iodim_do_not_use_me X(iodim); \ typedef struct fftw_iodim64_do_not_use_me X(iodim64); \ \ typedef enum fftw_r2r_kind_do_not_use_me X(r2r_kind); \ \ typedef fftw_write_char_func_do_not_use_me X(write_char_func); \ typedef fftw_read_char_func_do_not_use_me X(read_char_func); \ \ FFTW_EXTERN void X(execute)(const X(plan) p); \ \ FFTW_EXTERN X(plan) X(plan_dft)(int rank, const int *n, \ C *in, C *out, int sign, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_dft_1d)(int n, C *in, C *out, int sign, \ unsigned flags); \ FFTW_EXTERN X(plan) X(plan_dft_2d)(int n0, int n1, \ C *in, C *out, int sign, unsigned flags); \ FFTW_EXTERN X(plan) X(plan_dft_3d)(int n0, int n1, int n2, \ C *in, C *out, int sign, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_many_dft)(int rank, const int *n, \ int howmany, \ C *in, const int *inembed, \ int istride, int idist, \ C *out, const int *onembed, \ int ostride, int odist, \ int sign, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru_dft)(int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ C *in, C *out, \ int sign, unsigned flags); \ FFTW_EXTERN X(plan) X(plan_guru_split_dft)(int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ R *ri, R *ii, R *ro, R *io, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru64_dft)(int rank, \ const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ C *in, C *out, \ int sign, unsigned flags); \ FFTW_EXTERN X(plan) X(plan_guru64_split_dft)(int rank, \ const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ R *ri, R *ii, R *ro, R *io, \ unsigned flags); \ \ FFTW_EXTERN void X(execute_dft)(const X(plan) p, C *in, C *out); \ FFTW_EXTERN void X(execute_split_dft)(const X(plan) p, R *ri, R *ii, \ R *ro, R *io); \ \ FFTW_EXTERN X(plan) X(plan_many_dft_r2c)(int rank, const int *n, \ int howmany, \ R *in, const int *inembed, \ int istride, int idist, \ C *out, const int *onembed, \ int ostride, int odist, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_dft_r2c)(int rank, const int *n, \ R *in, C *out, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_dft_r2c_1d)(int n,R *in,C *out,unsigned flags); \ FFTW_EXTERN X(plan) X(plan_dft_r2c_2d)(int n0, int n1, \ R *in, C *out, unsigned flags); \ FFTW_EXTERN X(plan) X(plan_dft_r2c_3d)(int n0, int n1, \ int n2, \ R *in, C *out, unsigned flags); \ \ \ FFTW_EXTERN X(plan) X(plan_many_dft_c2r)(int rank, const int *n, \ int howmany, \ C *in, const int *inembed, \ int istride, int idist, \ R *out, const int *onembed, \ int ostride, int odist, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_dft_c2r)(int rank, const int *n, \ C *in, R *out, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_dft_c2r_1d)(int n,C *in,R *out,unsigned flags); \ FFTW_EXTERN X(plan) X(plan_dft_c2r_2d)(int n0, int n1, \ C *in, R *out, unsigned flags); \ FFTW_EXTERN X(plan) X(plan_dft_c2r_3d)(int n0, int n1, \ int n2, \ C *in, R *out, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru_dft_r2c)(int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ R *in, C *out, \ unsigned flags); \ FFTW_EXTERN X(plan) X(plan_guru_dft_c2r)(int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ C *in, R *out, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru_split_dft_r2c)( \ int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ R *in, R *ro, R *io, \ unsigned flags); \ FFTW_EXTERN X(plan) X(plan_guru_split_dft_c2r)( \ int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ R *ri, R *ii, R *out, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru64_dft_r2c)(int rank, \ const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ R *in, C *out, \ unsigned flags); \ FFTW_EXTERN X(plan) X(plan_guru64_dft_c2r)(int rank, \ const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ C *in, R *out, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru64_split_dft_r2c)( \ int rank, const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ R *in, R *ro, R *io, \ unsigned flags); \ FFTW_EXTERN X(plan) X(plan_guru64_split_dft_c2r)( \ int rank, const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ R *ri, R *ii, R *out, \ unsigned flags); \ \ FFTW_EXTERN void X(execute_dft_r2c)(const X(plan) p, R *in, C *out); \ FFTW_EXTERN void X(execute_dft_c2r)(const X(plan) p, C *in, R *out); \ \ FFTW_EXTERN void X(execute_split_dft_r2c)(const X(plan) p, \ R *in, R *ro, R *io); \ FFTW_EXTERN void X(execute_split_dft_c2r)(const X(plan) p, \ R *ri, R *ii, R *out); \ \ FFTW_EXTERN X(plan) X(plan_many_r2r)(int rank, const int *n, \ int howmany, \ R *in, const int *inembed, \ int istride, int idist, \ R *out, const int *onembed, \ int ostride, int odist, \ const X(r2r_kind) *kind, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_r2r)(int rank, const int *n, R *in, R *out, \ const X(r2r_kind) *kind, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_r2r_1d)(int n, R *in, R *out, \ X(r2r_kind) kind, unsigned flags); \ FFTW_EXTERN X(plan) X(plan_r2r_2d)(int n0, int n1, R *in, R *out, \ X(r2r_kind) kind0, X(r2r_kind) kind1, \ unsigned flags); \ FFTW_EXTERN X(plan) X(plan_r2r_3d)(int n0, int n1, int n2, \ R *in, R *out, X(r2r_kind) kind0, \ X(r2r_kind) kind1, X(r2r_kind) kind2, \ unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru_r2r)(int rank, const X(iodim) *dims, \ int howmany_rank, \ const X(iodim) *howmany_dims, \ R *in, R *out, \ const X(r2r_kind) *kind, unsigned flags); \ \ FFTW_EXTERN X(plan) X(plan_guru64_r2r)(int rank, const X(iodim64) *dims, \ int howmany_rank, \ const X(iodim64) *howmany_dims, \ R *in, R *out, \ const X(r2r_kind) *kind, unsigned flags); \ \ FFTW_EXTERN void X(execute_r2r)(const X(plan) p, R *in, R *out); \ \ FFTW_EXTERN void X(destroy_plan)(X(plan) p); \ FFTW_EXTERN void X(forget_wisdom)(void); \ FFTW_EXTERN void X(cleanup)(void); \ \ FFTW_EXTERN void X(set_timelimit)(double t); \ \ FFTW_EXTERN void X(plan_with_nthreads)(int nthreads); \ FFTW_EXTERN int X(init_threads)(void); \ FFTW_EXTERN void X(cleanup_threads)(void); \ FFTW_EXTERN void X(make_planner_thread_safe)(void); \ \ FFTW_EXTERN int X(export_wisdom_to_filename)(const char *filename); \ FFTW_EXTERN void X(export_wisdom_to_file)(FILE *output_file); \ FFTW_EXTERN char *X(export_wisdom_to_string)(void); \ FFTW_EXTERN void X(export_wisdom)(X(write_char_func) write_char, \ void *data); \ FFTW_EXTERN int X(import_system_wisdom)(void); \ FFTW_EXTERN int X(import_wisdom_from_filename)(const char *filename); \ FFTW_EXTERN int X(import_wisdom_from_file)(FILE *input_file); \ FFTW_EXTERN int X(import_wisdom_from_string)(const char *input_string); \ FFTW_EXTERN int X(import_wisdom)(X(read_char_func) read_char, void *data); \ \ FFTW_EXTERN void X(fprint_plan)(const X(plan) p, FILE *output_file); \ FFTW_EXTERN void X(print_plan)(const X(plan) p); \ FFTW_EXTERN char *X(sprint_plan)(const X(plan) p); \ \ FFTW_EXTERN void *X(malloc)(size_t n); \ FFTW_EXTERN R *X(alloc_real)(size_t n); \ FFTW_EXTERN C *X(alloc_complex)(size_t n); \ FFTW_EXTERN void X(free)(void *p); \ \ FFTW_EXTERN void X(flops)(const X(plan) p, \ double *add, double *mul, double *fmas); \ FFTW_EXTERN double X(estimate_cost)(const X(plan) p); \ FFTW_EXTERN double X(cost)(const X(plan) p); \ \ FFTW_EXTERN int X(alignment_of)(R *p); \ FFTW_EXTERN const char X(version)[]; \ FFTW_EXTERN const char X(cc)[]; \ FFTW_EXTERN const char X(codelet_optim)[]; /* end of FFTW_DEFINE_API macro */ FFTW_DEFINE_API(FFTW_MANGLE_DOUBLE, double, fftw_complex) FFTW_DEFINE_API(FFTW_MANGLE_FLOAT, float, fftwf_complex) FFTW_DEFINE_API(FFTW_MANGLE_LONG_DOUBLE, long double, fftwl_complex) /* __float128 (quad precision) is a gcc extension on i386, x86_64, and ia64 for gcc >= 4.6 (compiled in FFTW with --enable-quad-precision) */ #if (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) \ && !(defined(__ICC) || defined(__INTEL_COMPILER) || defined(__CUDACC__) || defined(__PGI)) \ && (defined(__i386__) || defined(__x86_64__) || defined(__ia64__)) # if !defined(FFTW_NO_Complex) && defined(_Complex_I) && defined(complex) && defined(I) /* note: __float128 is a typedef, which is not supported with the _Complex keyword in gcc, so instead we use this ugly __attribute__ version. However, we can't simply pass the __attribute__ version to FFTW_DEFINE_API because the __attribute__ confuses gcc in pointer types. Hence redefining FFTW_DEFINE_COMPLEX. Ugh. */ # undef FFTW_DEFINE_COMPLEX # define FFTW_DEFINE_COMPLEX(R, C) typedef _Complex float __attribute__((mode(TC))) C # endif FFTW_DEFINE_API(FFTW_MANGLE_QUAD, __float128, fftwq_complex) #endif #define FFTW_FORWARD (-1) #define FFTW_BACKWARD (+1) #define FFTW_NO_TIMELIMIT (-1.0) /* documented flags */ #define FFTW_MEASURE (0U) #define FFTW_DESTROY_INPUT (1U << 0) #define FFTW_UNALIGNED (1U << 1) #define FFTW_CONSERVE_MEMORY (1U << 2) #define FFTW_EXHAUSTIVE (1U << 3) /* NO_EXHAUSTIVE is default */ #define FFTW_PRESERVE_INPUT (1U << 4) /* cancels FFTW_DESTROY_INPUT */ #define FFTW_PATIENT (1U << 5) /* IMPATIENT is default */ #define FFTW_ESTIMATE (1U << 6) #define FFTW_WISDOM_ONLY (1U << 21) /* undocumented beyond-guru flags */ #define FFTW_ESTIMATE_PATIENT (1U << 7) #define FFTW_BELIEVE_PCOST (1U << 8) #define FFTW_NO_DFT_R2HC (1U << 9) #define FFTW_NO_NONTHREADED (1U << 10) #define FFTW_NO_BUFFERING (1U << 11) #define FFTW_NO_INDIRECT_OP (1U << 12) #define FFTW_ALLOW_LARGE_GENERIC (1U << 13) /* NO_LARGE_GENERIC is default */ #define FFTW_NO_RANK_SPLITS (1U << 14) #define FFTW_NO_VRANK_SPLITS (1U << 15) #define FFTW_NO_VRECURSE (1U << 16) #define FFTW_NO_SIMD (1U << 17) #define FFTW_NO_SLOW (1U << 18) #define FFTW_NO_FIXED_RADIX_LARGE_N (1U << 19) #define FFTW_ALLOW_PRUNING (1U << 20) #ifdef __cplusplus } /* extern "C" */ #endif /* __cplusplus */ #endif /* FFTW3_H */
18,102
42.516827
93
h
FIt-SNE
FIt-SNE-master/src/winlibs/fftw/ffwt_license-and-copyright.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <!-- This manual is for FFTW (version 3.3.8, 24 May 2018). Copyright (C) 2003 Matteo Frigo. Copyright (C) 2003 Massachusetts Institute of Technology. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies. Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one. Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions, except that this permission notice may be stated in a translation approved by the Free Software Foundation. --> <!-- Created by GNU Texinfo 6.3, http://www.gnu.org/software/texinfo/ --> <head> <title>FFTW 3.3.8: License and Copyright</title> <meta name="description" content="FFTW 3.3.8: License and Copyright"> <meta name="keywords" content="FFTW 3.3.8: License and Copyright"> <meta name="resource-type" content="document"> <meta name="distribution" content="global"> <meta name="Generator" content="makeinfo"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link href="index.html#Top" rel="start" title="Top"> <link href="Concept-Index.html#Concept-Index" rel="index" title="Concept Index"> <link href="index.html#SEC_Contents" rel="contents" title="Table of Contents"> <link href="index.html#Top" rel="up" title="Top"> <link href="Concept-Index.html#Concept-Index" rel="next" title="Concept Index"> <link href="Acknowledgments.html#Acknowledgments" rel="prev" title="Acknowledgments"> <style type="text/css"> <!-- a.summary-letter {text-decoration: none} blockquote.indentedblock {margin-right: 0em} blockquote.smallindentedblock {margin-right: 0em; font-size: smaller} blockquote.smallquotation {font-size: smaller} div.display {margin-left: 3.2em} div.example {margin-left: 3.2em} div.lisp {margin-left: 3.2em} div.smalldisplay {margin-left: 3.2em} div.smallexample {margin-left: 3.2em} div.smalllisp {margin-left: 3.2em} kbd {font-style: oblique} pre.display {font-family: inherit} pre.format {font-family: inherit} pre.menu-comment {font-family: serif} pre.menu-preformatted {font-family: serif} pre.smalldisplay {font-family: inherit; font-size: smaller} pre.smallexample {font-size: smaller} pre.smallformat {font-family: inherit; font-size: smaller} pre.smalllisp {font-size: smaller} span.nolinebreak {white-space: nowrap} span.roman {font-family: initial; font-weight: normal} span.sansserif {font-family: sans-serif; font-weight: normal} ul.no-bullet {list-style: none} --> </style> </head> <body lang="en"> <a name="License-and-Copyright"></a> <div class="header"> <p> Next: <a href="Concept-Index.html#Concept-Index" accesskey="n" rel="next">Concept Index</a>, Previous: <a href="Acknowledgments.html#Acknowledgments" accesskey="p" rel="prev">Acknowledgments</a>, Up: <a href="index.html#Top" accesskey="u" rel="up">Top</a> &nbsp; [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Concept-Index.html#Concept-Index" title="Index" rel="index">Index</a>]</p> </div> <hr> <a name="License-and-Copyright-1"></a> <h2 class="chapter">12 License and Copyright</h2> <p>FFTW is Copyright &copy; 2003, 2007-11 Matteo Frigo, Copyright &copy; 2003, 2007-11 Massachusetts Institute of Technology. </p> <p>FFTW is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. </p> <p>This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. </p> <p>You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA You can also find the <a href="http://www.gnu.org/licenses/gpl-2.0.html">GPL on the GNU web site</a>. </p> <p>In addition, we kindly ask you to acknowledge FFTW and its authors in any program or publication in which you use FFTW. (You are not <em>required</em> to do so; it is up to your common sense to decide whether you want to comply with this request or not.) For general publications, we suggest referencing: Matteo Frigo and Steven G. Johnson, &ldquo;The design and implementation of FFTW3,&rdquo; <i>Proc. IEEE</i> <b>93</b> (2), 216&ndash;231 (2005). </p> <p>Non-free versions of FFTW are available under terms different from those of the General Public License. (e.g. they do not require you to accompany any object code using FFTW with the corresponding source code.) For these alternative terms you must purchase a license from MIT&rsquo;s Technology Licensing Office. Users interested in such a license should contact us (<a href="mailto:[email protected]">[email protected]</a>) for more information. </p> <hr> <div class="header"> <p> Next: <a href="Concept-Index.html#Concept-Index" accesskey="n" rel="next">Concept Index</a>, Previous: <a href="Acknowledgments.html#Acknowledgments" accesskey="p" rel="prev">Acknowledgments</a>, Up: <a href="index.html#Top" accesskey="u" rel="up">Top</a> &nbsp; [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Concept-Index.html#Concept-Index" title="Index" rel="index">Index</a>]</p> </div> </body> </html>
5,796
45.376
436
html
octomap
octomap-master/.travis.yml
language: cpp sudo: required dist: bionic compiler: - gcc - clang before_install: - sudo apt-get update -qq - sudo apt-get install -qq libqglviewer-dev-qt5 before_script: script: ./scripts/travis_build_jobs.sh $VARIANT env: - VARIANT=dist - VARIANT=components matrix: exclude: - compiler: clang env: VARIANT=components
344
16.25
49
yml
octomap
octomap-master/README.md
OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees. =========================================================================== http://octomap.github.io Originally developed by Kai M. Wurm and Armin Hornung, University of Freiburg, Copyright (C) 2009-2014. Currently maintained by [Armin Hornung](https://github.com/ahornung). See the [list of contributors](octomap/AUTHORS.txt) for further authors. License: * octomap: [New BSD License](octomap/LICENSE.txt) * octovis and related libraries: [GPL](octovis/LICENSE.txt) Download the latest releases: https://github.com/octomap/octomap/releases API documentation: https://octomap.github.io/octomap/doc/ Build status: [![Build Status](https://travis-ci.org/OctoMap/octomap.png?branch=devel)](https://travis-ci.org/OctoMap/octomap) Report bugs and request features in our tracker: https://github.com/OctoMap/octomap/issues A list of changes is available in the [octomap changelog](octomap/CHANGELOG.txt) OVERVIEW -------- OctoMap consists of two separate libraries each in its own subfolder: **octomap**, the actual library, and **octovis**, our visualization libraries and tools. This README provides an overview of both, for details on compiling each please see [octomap/README.md](octomap/README.md) and [octovis/README.md](octovis/README.md) respectively. See http://www.ros.org/wiki/octomap and http://www.ros.org/wiki/octovis if you want to use OctoMap in ROS; there are pre-compiled packages available. You can build each library separately with CMake by running it from the subdirectories, or build octomap and octovis together from this top-level directory. E.g., to only compile the library, run: cd octomap mkdir build cd build cmake .. make To compile the complete package, run: cd build cmake .. make Binaries and libs will end up in the directories `bin` and `lib` of the top-level directory where you started the build. See [octomap README](octomap/README.md) and [octovis README](octovis/README.md) for further details and hints on compiling, especially under Windows.
2,131
33.387097
114
md
octomap
octomap-master/.github/workflows/industrial_ci_action.yml
# This config uses industrial_ci (https://github.com/ros-industrial/industrial_ci.git). # For troubleshooting, see readme (https://github.com/ros-industrial/industrial_ci/blob/master/README.rst) name: CI # This determines when this workflow is run on: [push, pull_request] # on all pushes and PRs jobs: CI: strategy: matrix: env: - {ROS_DISTRO: melodic} - {ROS_DISTRO: noetic} - {ROS_DISTRO: foxy, PRERELEASE: true} - {ROS_DISTRO: rolling, PRERELEASE: true} env: CCACHE_DIR: /github/home/.ccache # Enable ccache BUILDER: colcon runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 # This step will fetch/store the directory used by ccache before/after the ci run - uses: actions/cache@v2 with: path: ${{ env.CCACHE_DIR }} key: ccache-${{ matrix.env.ROS_DISTRO }}-${{ matrix.env.ROS_REPO }} # Run industrial_ci - uses: 'ros-industrial/industrial_ci@master' env: ${{ matrix.env }}
1,037
31.4375
106
yml
octomap
octomap-master/dynamicEDT3D/doxygen.h
/** * \namespace dynamicEDT3D Namespace of the dynamicEDT3D library * */ /** \mainpage dynamicEDT3D \section intro_sec Introduction The <a href="http://octomap.sourceforge.net/">dynamicEDT3D library</a> implements an inrementally updatable Euclidean distance transform (EDT) in 3D. It comes with a wrapper to use the OctoMap 3D representation and hooks into the change detection of the OctoMap library to propagate changes to the EDT. \section install_sec Installation <p>See the file README.txt in the main folder. </p> \section gettingstarted_sec Getting Started <p>There are two example programs in the src/examples directory that show the basic functionality of the library.</p> \section changelog_sec Changelog <p>See the file CHANGELOG.txt in the main folder or the <a href="http://octomap.svn.sourceforge.net/viewvc/octomap/trunk/dynamicEDT3D/CHANGELOG.txt">latest version online</a> </p> \section using_sec Using dynamicEDT3D? <p> Please let us know if you are using dynamicEDT3D, as we are curious to find out how it enables other people's work or research. Additionally, please cite our paper if you use dynamicEDT3D in your research: </p> <p>B. Lau, C. Sprunk, and W. Burgard, <strong>"Efficient Grid-based Spatial Representations for Robot Navigation in Dynamic Environments"</strong> in <em>Robotics and Autonomous Systems</em>, 2012. Accepted for publication. Software available at <a href="http://octomap.sf.net/">http://octomap.sf.net/</a>. </p> <p>BibTeX:</p> <pre>@@article{lau12ras, author = {Boris Lau and Christoph Sprunk and Wolfram Burgard}, title = {Efficient Grid-based Spatial Representations for Robot Navigation in Dynamic Environments}, journal = {Robotics and Autonomous Systems (RAS)}, year = {2012}, url = {http://octomap.sf.net/}, note = {Accepted for publication. Software available at \url{http://octomap.sf.net/}} }</pre> **/
1,923
39.083333
304
h
octomap
octomap-master/dynamicEDT3D/include/dynamicEDT3D/bucketedqueue.h
/** * dynamicEDT3D: * A library for incrementally updatable Euclidean distance transforms in 3D. * @author C. Sprunk, B. Lau, W. Burgard, University of Freiburg, Copyright (C) 2011. * @see http://octomap.sourceforge.net/ * License: New BSD License */ /* * Copyright (c) 2011-2012, C. Sprunk, B. Lau, W. Burgard, University of Freiburg * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef _PRIORITYQUEUE2_H_ #define _PRIORITYQUEUE2_H_ #include <vector> #include <set> #include <queue> #include <assert.h> #include "point.h" #include <map> //! Priority queue for integer coordinates with squared distances as priority. /** A priority queue that uses buckets to group elements with the same priority. * The individual buckets are unsorted, which increases efficiency if these groups are large. * The elements are assumed to be integer coordinates, and the priorities are assumed * to be squared euclidean distances (integers). */ template <typename T> class BucketPrioQueue { public: //! Standard constructor /** Standard constructor. When called for the first time it creates a look up table * that maps square distanes to bucket numbers, which might take some time... */ BucketPrioQueue(); void clear() { buckets.clear(); } //! Checks whether the Queue is empty bool empty(); //! push an element void push(int prio, T t); //! return and pop the element with the lowest squared distance */ T pop(); int size() { return count; } int getNumBuckets() { return buckets.size(); } private: int count; typedef std::map< int, std::queue<T> > BucketType; BucketType buckets; typename BucketType::iterator nextPop; }; #include "bucketedqueue.hxx" #endif
3,237
34.582418
94
h
octomap
octomap-master/dynamicEDT3D/include/dynamicEDT3D/bucketedqueue.hxx
/** * dynamicEDT3D: * A library for incrementally updatable Euclidean distance transforms in 3D. * @author C. Sprunk, B. Lau, W. Burgard, University of Freiburg, Copyright (C) 2011. * @see http://octomap.sourceforge.net/ * License: New BSD License */ /* * Copyright (c) 2011-2012, C. Sprunk, B. Lau, W. Burgard, University of Freiburg * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "bucketedqueue.h" #include "limits.h" template <class T> BucketPrioQueue<T>::BucketPrioQueue() { nextPop = buckets.end(); count = 0; } template <class T> bool BucketPrioQueue<T>::empty() { return (count==0); } template <class T> void BucketPrioQueue<T>::push(int prio, T t) { buckets[prio].push(t); if (nextPop == buckets.end() || prio < nextPop->first) nextPop = buckets.find(prio); count++; } template <class T> T BucketPrioQueue<T>::pop() { while (nextPop!=buckets.end() && nextPop->second.empty()) ++nextPop; T p = nextPop->second.front(); nextPop->second.pop(); if (nextPop->second.empty()) { typename BucketType::iterator it = nextPop; nextPop++; buckets.erase(it); } count--; return p; }
2,656
33.960526
86
hxx
octomap
octomap-master/dynamicEDT3D/include/dynamicEDT3D/dynamicEDT3D.h
/** * dynamicEDT3D: * A library for incrementally updatable Euclidean distance transforms in 3D. * @author C. Sprunk, B. Lau, W. Burgard, University of Freiburg, Copyright (C) 2011. * @see http://octomap.sourceforge.net/ * License: New BSD License */ /* * Copyright (c) 2011-2012, C. Sprunk, B. Lau, W. Burgard, University of Freiburg * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef _DYNAMICEDT3D_H_ #define _DYNAMICEDT3D_H_ #include <limits.h> #include <queue> #include "bucketedqueue.h" //! A DynamicEDT3D object computes and updates a 3D distance map. class DynamicEDT3D { public: DynamicEDT3D(int _maxdist_squared); ~DynamicEDT3D(); //! Initialization with an empty map void initializeEmpty(int _sizeX, int _sizeY, int sizeZ, bool initGridMap=true); //! Initialization with a given binary map (false==free, true==occupied) void initializeMap(int _sizeX, int _sizeY, int sizeZ, bool*** _gridMap); //! add an obstacle at the specified cell coordinate void occupyCell(int x, int y, int z); //! remove an obstacle at the specified cell coordinate void clearCell(int x, int y, int z); //! remove old dynamic obstacles and add the new ones void exchangeObstacles(std::vector<INTPOINT3D> newObstacles); //! update distance map to reflect the changes virtual void update(bool updateRealDist=true); //! returns the obstacle distance at the specified location float getDistance( int x, int y, int z ) const; //! gets the closest occupied cell for that location INTPOINT3D getClosestObstacle( int x, int y, int z ) const; //! returns the squared obstacle distance in cell units at the specified location int getSQCellDistance( int x, int y, int z ) const; //! checks whether the specficied location is occupied bool isOccupied(int x, int y, int z) const; //! returns the x size of the workspace/map unsigned int getSizeX() const {return sizeX;} //! returns the y size of the workspace/map unsigned int getSizeY() const {return sizeY;} //! returns the z size of the workspace/map unsigned int getSizeZ() const {return sizeZ;} typedef enum {invalidObstData = INT_MAX} ObstDataState; ///distance value returned when requesting distance for a cell outside the map static float distanceValue_Error; ///distance value returned when requesting distance in cell units for a cell outside the map static int distanceInCellsValue_Error; protected: struct dataCell { float dist; int obstX; int obstY; int obstZ; int sqdist; char queueing; bool needsRaise; }; typedef enum {free=0, occupied=1} State; typedef enum {fwNotQueued=1, fwQueued=2, fwProcessed=3, bwQueued=4, bwProcessed=1} QueueingState; // methods inline void raiseCell(INTPOINT3D &p, dataCell &c, bool updateRealDist); inline void propagateCell(INTPOINT3D &p, dataCell &c, bool updateRealDist); inline void inspectCellRaise(int &nx, int &ny, int &nz, bool updateRealDist); inline void inspectCellPropagate(int &nx, int &ny, int &nz, dataCell &c, bool updateRealDist); void setObstacle(int x, int y, int z); void removeObstacle(int x, int y, int z); private: void commitAndColorize(bool updateRealDist=true); inline bool isOccupied(int &x, int &y, int &z, dataCell &c); // queues BucketPrioQueue<INTPOINT3D> open; std::vector<INTPOINT3D> removeList; std::vector<INTPOINT3D> addList; std::vector<INTPOINT3D> lastObstacles; // maps protected: int sizeX; int sizeY; int sizeZ; int sizeXm1; int sizeYm1; int sizeZm1; dataCell*** data; bool*** gridMap; // parameters int padding; double doubleThreshold; double sqrt2; double maxDist; int maxDist_squared; }; #endif
5,228
33.401316
99
h
octomap
octomap-master/dynamicEDT3D/include/dynamicEDT3D/dynamicEDTOctomap.h
/** * dynamicEDT3D: * A library for incrementally updatable Euclidean distance transforms in 3D. * @author C. Sprunk, B. Lau, W. Burgard, University of Freiburg, Copyright (C) 2011. * @see http://octomap.sourceforge.net/ * License: New BSD License */ /* * Copyright (c) 2011-2012, C. Sprunk, B. Lau, W. Burgard, University of Freiburg * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef DYNAMICEDTOCTOMAP_H_ #define DYNAMICEDTOCTOMAP_H_ #include "dynamicEDT3D.h" #include <octomap/OcTree.h> #include <octomap/OcTreeStamped.h> /// A DynamicEDTOctomapBase object connects a DynamicEDT3D object to an octomap. template <class TREE> class DynamicEDTOctomapBase: private DynamicEDT3D { public: /** Create a DynamicEDTOctomapBase object that maintains a distance transform in the bounding box given by bbxMin, bbxMax and clamps distances at maxdist. * treatUnknownAsOccupied configures the treatment of unknown cells in the distance computation. * * The constructor copies occupancy data but does not yet compute the distance map. You need to call udpate to do this. * * The distance map is maintained in a full three-dimensional array, i.e., there exists a float field in memory for every voxel inside the bounding box given by bbxMin and bbxMax. Consider this when computing distance maps for large octomaps, they will use much more memory than the octomap itself! */ DynamicEDTOctomapBase(float maxdist, TREE* _octree, octomap::point3d bbxMin, octomap::point3d bbxMax, bool treatUnknownAsOccupied); virtual ~DynamicEDTOctomapBase(); ///trigger updating of the distance map. This will query the octomap for the set of changes since the last update. ///If you set updateRealDist to false, computations will be faster (square root will be omitted), but you can only retrieve squared distances virtual void update(bool updateRealDist=true); ///retrieves distance and closestObstacle (closestObstacle is to be discarded if distance is maximum distance, the method does not write closestObstacle in this case). ///Returns DynamicEDTOctomapBase::distanceValue_Error if point is outside the map. void getDistanceAndClosestObstacle(const octomap::point3d& p, float &distance, octomap::point3d& closestObstacle) const; ///retrieves distance at point. Returns DynamicEDTOctomapBase::distanceValue_Error if point is outside the map. float getDistance(const octomap::point3d& p) const; ///retrieves distance at key. Returns DynamicEDTOctomapBase::distanceValue_Error if key is outside the map. float getDistance(const octomap::OcTreeKey& k) const; ///retrieves squared distance in cells at point. Returns DynamicEDTOctomapBase::distanceInCellsValue_Error if point is outside the map. int getSquaredDistanceInCells(const octomap::point3d& p) const; //variant of getDistanceAndClosestObstacle that ommits the check whether p is inside the area of the distance map. Use only if you are certain that p is covered by the distance map and if you need to save the time of the check. void getDistanceAndClosestObstacle_unsafe(const octomap::point3d& p, float &distance, octomap::point3d& closestObstacle) const; //variant of getDistance that ommits the check whether p is inside the area of the distance map. Use only if you are certain that p is covered by the distance map and if you need to save the time of the check. float getDistance_unsafe(const octomap::point3d& p) const; //variant of getDistance that ommits the check whether p is inside the area of the distance map. Use only if you are certain that p is covered by the distance map and if you need to save the time of the check. float getDistance_unsafe(const octomap::OcTreeKey& k) const; //variant of getSquaredDistanceInCells that ommits the check whether p is inside the area of the distance map. Use only if you are certain that p is covered by the distance map and if you need to save the time of the check. int getSquaredDistanceInCells_unsafe(const octomap::point3d& p) const; ///retrieve maximum distance value float getMaxDist() const { return maxDist*octree->getResolution(); } ///retrieve squared maximum distance value in grid cells int getSquaredMaxDistCells() const { return maxDist_squared; } ///Brute force method used for debug purposes. Checks occupancy state consistency between octomap and internal representation. bool checkConsistency() const; ///distance value returned when requesting distance for a cell outside the map static float distanceValue_Error; ///distance value returned when requesting distance in cell units for a cell outside the map static int distanceInCellsValue_Error; private: void initializeOcTree(octomap::point3d bbxMin, octomap::point3d bbxMax); void insertMaxDepthLeafAtInitialize(octomap::OcTreeKey key); void updateMaxDepthLeaf(octomap::OcTreeKey& key, bool occupied); void worldToMap(const octomap::point3d &p, int &x, int &y, int &z) const; void mapToWorld(int x, int y, int z, octomap::point3d &p) const; void mapToWorld(int x, int y, int z, octomap::OcTreeKey &key) const; TREE* octree; bool unknownOccupied; int treeDepth; double treeResolution; octomap::OcTreeKey boundingBoxMinKey; octomap::OcTreeKey boundingBoxMaxKey; int offsetX, offsetY, offsetZ; }; typedef DynamicEDTOctomapBase<octomap::OcTree> DynamicEDTOctomap; typedef DynamicEDTOctomapBase<octomap::OcTreeStamped> DynamicEDTOctomapStamped; #include "dynamicEDTOctomap.hxx" #endif /* DYNAMICEDTOCTOMAP_H_ */
7,002
52.458015
303
h
octomap
octomap-master/dynamicEDT3D/include/dynamicEDT3D/dynamicEDTOctomap.hxx
/** * dynamicEDT3D: * A library for incrementally updatable Euclidean distance transforms in 3D. * @author C. Sprunk, B. Lau, W. Burgard, University of Freiburg, Copyright (C) 2011. * @see http://octomap.sourceforge.net/ * License: New BSD License */ /* * Copyright (c) 2011-2012, C. Sprunk, B. Lau, W. Burgard, University of Freiburg * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ template <class TREE> float DynamicEDTOctomapBase<TREE>::distanceValue_Error = -1.0; template <class TREE> int DynamicEDTOctomapBase<TREE>::distanceInCellsValue_Error = -1; template <class TREE> DynamicEDTOctomapBase<TREE>::DynamicEDTOctomapBase(float maxdist, TREE* _octree, octomap::point3d bbxMin, octomap::point3d bbxMax, bool treatUnknownAsOccupied) : DynamicEDT3D(((int) (maxdist/_octree->getResolution()+1)*((int) (maxdist/_octree->getResolution()+1)))), octree(_octree), unknownOccupied(treatUnknownAsOccupied) { treeDepth = octree->getTreeDepth(); treeResolution = octree->getResolution(); initializeOcTree(bbxMin, bbxMax); octree->enableChangeDetection(true); } template <class TREE> DynamicEDTOctomapBase<TREE>::~DynamicEDTOctomapBase() { } template <class TREE> void DynamicEDTOctomapBase<TREE>::update(bool updateRealDist){ for(octomap::KeyBoolMap::const_iterator it = octree->changedKeysBegin(), end=octree->changedKeysEnd(); it!=end; ++it){ //the keys in this list all go down to the lowest level! octomap::OcTreeKey key = it->first; //ignore changes outside of bounding box if(key[0] < boundingBoxMinKey[0] || key[1] < boundingBoxMinKey[1] || key[2] < boundingBoxMinKey[2]) continue; if(key[0] > boundingBoxMaxKey[0] || key[1] > boundingBoxMaxKey[1] || key[2] > boundingBoxMaxKey[2]) continue; typename TREE::NodeType* node = octree->search(key); assert(node); //"node" is not necessarily at lowest level, BUT: the occupancy value of this node //has to be the same as of the node indexed by the key *it updateMaxDepthLeaf(key, octree->isNodeOccupied(node)); } octree->resetChangeDetection(); DynamicEDT3D::update(updateRealDist); } template <class TREE> void DynamicEDTOctomapBase<TREE>::initializeOcTree(octomap::point3d bbxMin, octomap::point3d bbxMax){ boundingBoxMinKey = octree->coordToKey(bbxMin); boundingBoxMaxKey = octree->coordToKey(bbxMax); offsetX = -boundingBoxMinKey[0]; offsetY = -boundingBoxMinKey[1]; offsetZ = -boundingBoxMinKey[2]; int _sizeX = boundingBoxMaxKey[0] - boundingBoxMinKey[0] + 1; int _sizeY = boundingBoxMaxKey[1] - boundingBoxMinKey[1] + 1; int _sizeZ = boundingBoxMaxKey[2] - boundingBoxMinKey[2] + 1; initializeEmpty(_sizeX, _sizeY, _sizeZ, false); if(unknownOccupied == false){ for(typename TREE::leaf_bbx_iterator it = octree->begin_leafs_bbx(bbxMin,bbxMax), end=octree->end_leafs_bbx(); it!= end; ++it){ if(octree->isNodeOccupied(*it)){ int nodeDepth = it.getDepth(); if( nodeDepth == treeDepth){ insertMaxDepthLeafAtInitialize(it.getKey()); } else { int cubeSize = 1 << (treeDepth - nodeDepth); octomap::OcTreeKey key=it.getIndexKey(); for(int dx = 0; dx < cubeSize; dx++) for(int dy = 0; dy < cubeSize; dy++) for(int dz = 0; dz < cubeSize; dz++){ unsigned short int tmpx = key[0]+dx; unsigned short int tmpy = key[1]+dy; unsigned short int tmpz = key[2]+dz; if(boundingBoxMinKey[0] > tmpx || boundingBoxMinKey[1] > tmpy || boundingBoxMinKey[2] > tmpz) continue; if(boundingBoxMaxKey[0] < tmpx || boundingBoxMaxKey[1] < tmpy || boundingBoxMaxKey[2] < tmpz) continue; insertMaxDepthLeafAtInitialize(octomap::OcTreeKey(tmpx, tmpy, tmpz)); } } } } } else { octomap::OcTreeKey key; for(int dx=0; dx<sizeX; dx++){ key[0] = boundingBoxMinKey[0] + dx; for(int dy=0; dy<sizeY; dy++){ key[1] = boundingBoxMinKey[1] + dy; for(int dz=0; dz<sizeZ; dz++){ key[2] = boundingBoxMinKey[2] + dz; typename TREE::NodeType* node = octree->search(key); if(!node || octree->isNodeOccupied(node)){ insertMaxDepthLeafAtInitialize(key); } } } } } } template <class TREE> void DynamicEDTOctomapBase<TREE>::insertMaxDepthLeafAtInitialize(octomap::OcTreeKey key){ bool isSurrounded = true; for(int dx=-1; dx<=1; dx++) for(int dy=-1; dy<=1; dy++) for(int dz=-1; dz<=1; dz++){ if(dx==0 && dy==0 && dz==0) continue; typename TREE::NodeType* node = octree->search(octomap::OcTreeKey(key[0]+dx, key[1]+dy, key[2]+dz)); if((!unknownOccupied && node==NULL) || ((node!=NULL) && (octree->isNodeOccupied(node)==false))){ isSurrounded = false; break; } } if(isSurrounded){ //obstacles that are surrounded by obstacles do not need to be put in the queues, //hence this initialization dataCell c; int x = key[0]+offsetX; int y = key[1]+offsetY; int z = key[2]+offsetZ; c.obstX = x; c.obstY = y; c.obstZ = z; c.sqdist = 0; c.dist = 0.0; c.queueing = fwProcessed; c.needsRaise = false; data[x][y][z] = c; } else { setObstacle(key[0]+offsetX, key[1]+offsetY, key[2]+offsetZ); } } template <class TREE> void DynamicEDTOctomapBase<TREE>::updateMaxDepthLeaf(octomap::OcTreeKey& key, bool occupied){ if(occupied) setObstacle(key[0]+offsetX, key[1]+offsetY, key[2]+offsetZ); else removeObstacle(key[0]+offsetX, key[1]+offsetY, key[2]+offsetZ); } template <class TREE> void DynamicEDTOctomapBase<TREE>::worldToMap(const octomap::point3d &p, int &x, int &y, int &z) const { octomap::OcTreeKey key = octree->coordToKey(p); x = key[0] + offsetX; y = key[1] + offsetY; z = key[2] + offsetZ; } template <class TREE> void DynamicEDTOctomapBase<TREE>::mapToWorld(int x, int y, int z, octomap::point3d &p) const { p = octree->keyToCoord(octomap::OcTreeKey(x-offsetX, y-offsetY, z-offsetZ)); } template <class TREE> void DynamicEDTOctomapBase<TREE>::mapToWorld(int x, int y, int z, octomap::OcTreeKey &key) const { key = octomap::OcTreeKey(x-offsetX, y-offsetY, z-offsetZ); } template <class TREE> void DynamicEDTOctomapBase<TREE>::getDistanceAndClosestObstacle(const octomap::point3d& p, float &distance, octomap::point3d& closestObstacle) const { int x,y,z; worldToMap(p, x, y, z); if(x>=0 && x<sizeX && y>=0 && y<sizeY && z>=0 && z<sizeZ){ dataCell c= data[x][y][z]; distance = c.dist*treeResolution; if(c.obstX != invalidObstData){ mapToWorld(c.obstX, c.obstY, c.obstZ, closestObstacle); } else { //If we are at maxDist, it can very well be that there is no valid closest obstacle data for this cell, this is not an error. } } else { distance = distanceValue_Error; } } template <class TREE> void DynamicEDTOctomapBase<TREE>::getDistanceAndClosestObstacle_unsafe(const octomap::point3d& p, float &distance, octomap::point3d& closestObstacle) const { int x,y,z; worldToMap(p, x, y, z); dataCell c= data[x][y][z]; distance = c.dist*treeResolution; if(c.obstX != invalidObstData){ mapToWorld(c.obstX, c.obstY, c.obstZ, closestObstacle); } else { //If we are at maxDist, it can very well be that there is no valid closest obstacle data for this cell, this is not an error. } } template <class TREE> float DynamicEDTOctomapBase<TREE>::getDistance(const octomap::point3d& p) const { int x,y,z; worldToMap(p, x, y, z); if(x>=0 && x<sizeX && y>=0 && y<sizeY && z>=0 && z<sizeZ){ return data[x][y][z].dist*treeResolution; } else { return distanceValue_Error; } } template <class TREE> float DynamicEDTOctomapBase<TREE>::getDistance_unsafe(const octomap::point3d& p) const { int x,y,z; worldToMap(p, x, y, z); return data[x][y][z].dist*treeResolution; } template <class TREE> float DynamicEDTOctomapBase<TREE>::getDistance(const octomap::OcTreeKey& k) const { int x = k[0] + offsetX; int y = k[1] + offsetY; int z = k[2] + offsetZ; if(x>=0 && x<sizeX && y>=0 && y<sizeY && z>=0 && z<sizeZ){ return data[x][y][z].dist*treeResolution; } else { return distanceValue_Error; } } template <class TREE> float DynamicEDTOctomapBase<TREE>::getDistance_unsafe(const octomap::OcTreeKey& k) const { int x = k[0] + offsetX; int y = k[1] + offsetY; int z = k[2] + offsetZ; return data[x][y][z].dist*treeResolution; } template <class TREE> int DynamicEDTOctomapBase<TREE>::getSquaredDistanceInCells(const octomap::point3d& p) const { int x,y,z; worldToMap(p, x, y, z); if(x>=0 && x<sizeX && y>=0 && y<sizeY && z>=0 && z<sizeZ){ return data[x][y][z].sqdist; } else { return distanceInCellsValue_Error; } } template <class TREE> int DynamicEDTOctomapBase<TREE>::getSquaredDistanceInCells_unsafe(const octomap::point3d& p) const { int x,y,z; worldToMap(p, x, y, z); return data[x][y][z].sqdist; } template <class TREE> bool DynamicEDTOctomapBase<TREE>::checkConsistency() const { for(octomap::KeyBoolMap::const_iterator it = octree->changedKeysBegin(), end=octree->changedKeysEnd(); it!=end; ++it){ //std::cerr<<"Cannot check consistency, you must execute the update() method first."<<std::endl; return false; } for(int x=0; x<sizeX; x++){ for(int y=0; y<sizeY; y++){ for(int z=0; z<sizeZ; z++){ octomap::point3d point; mapToWorld(x,y,z,point); typename TREE::NodeType* node = octree->search(point); bool mapOccupied = isOccupied(x,y,z); bool treeOccupied = false; if(node){ treeOccupied = octree->isNodeOccupied(node); } else { if(unknownOccupied) treeOccupied = true; } if(mapOccupied != treeOccupied){ //std::cerr<<"OCCUPANCY MISMATCH BETWEEN TREE AND MAP at "<<x<<","<<y<<","<<z<<std::endl; //std::cerr<<"Tree "<<treeOccupied<<std::endl; //std::cerr<<"Map "<<mapOccupied<<std::endl; return false; } } } } return true; }
11,291
32.309735
163
hxx
octomap
octomap-master/dynamicEDT3D/include/dynamicEDT3D/point.h
/** * dynamicEDT3D: * A library for incrementally updatable Euclidean distance transforms in 3D. * @author C. Sprunk, B. Lau, W. Burgard, University of Freiburg, Copyright (C) 2011. * @see http://octomap.sourceforge.net/ * License: New BSD License */ /* * Copyright (c) 2011-2012, C. Sprunk, B. Lau, W. Burgard, University of Freiburg * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef _VOROPOINT_H_ #define _VOROPOINT_H_ #define INTPOINT IntPoint #define INTPOINT3D IntPoint3D /*! A light-weight integer point with fields x,y */ class IntPoint { public: IntPoint() : x(0), y(0) {} IntPoint(int _x, int _y) : x(_x), y(_y) {} int x,y; }; /*! A light-weight integer point with fields x,y,z */ class IntPoint3D { public: IntPoint3D() : x(0), y(0), z(0) {} IntPoint3D(int _x, int _y, int _z) : x(_x), y(_y), z(_z) {} int x,y,z; }; #endif
2,379
37.387097
84
h
octomap
octomap-master/dynamicEDT3D/src/dynamicEDT3D.cpp
/** * dynamicEDT3D: * A library for incrementally updatable Euclidean distance transforms in 3D. * @author C. Sprunk, B. Lau, W. Burgard, University of Freiburg, Copyright (C) 2011. * @see http://octomap.sourceforge.net/ * License: New BSD License */ /* * Copyright (c) 2011-2012, C. Sprunk, B. Lau, W. Burgard, University of Freiburg * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <dynamicEDT3D/dynamicEDT3D.h> #include <math.h> #include <stdlib.h> #define FOR_EACH_NEIGHBOR_WITH_CHECK(function, p, ...) \ int x=p.x;\ int y=p.y;\ int z=p.z;\ int xp1 = x+1;\ int xm1 = x-1;\ int yp1 = y+1;\ int ym1 = y-1;\ int zp1 = z+1;\ int zm1 = z-1;\ \ if(z<sizeZm1) function(x, y, zp1, ##__VA_ARGS__);\ if(z>0) function(x, y, zm1, ##__VA_ARGS__);\ \ if(y<sizeYm1){\ function(x, yp1, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(x, yp1, zp1, ##__VA_ARGS__);\ if(z>0) function(x, yp1, zm1, ##__VA_ARGS__);\ }\ \ if(y>0){\ function(x, ym1, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(x, ym1, zp1, ##__VA_ARGS__);\ if(z>0) function(x, ym1, zm1, ##__VA_ARGS__);\ }\ \ \ if(x<sizeXm1){\ function(xp1, y, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(xp1, y, zp1, ##__VA_ARGS__);\ if(z>0) function(xp1, y, zm1, ##__VA_ARGS__);\ \ if(y<sizeYm1){\ function(xp1, yp1, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(xp1, yp1, zp1, ##__VA_ARGS__);\ if(z>0) function(xp1, yp1, zm1, ##__VA_ARGS__);\ }\ \ if(y>0){\ function(xp1, ym1, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(xp1, ym1, zp1, ##__VA_ARGS__);\ if(z>0) function(xp1, ym1, zm1, ##__VA_ARGS__);\ }\ }\ \ if(x>0){\ function(xm1, y, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(xm1, y, zp1, ##__VA_ARGS__);\ if(z>0) function(xm1, y, zm1, ##__VA_ARGS__);\ \ if(y<sizeYm1){\ function(xm1, yp1, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(xm1, yp1, zp1, ##__VA_ARGS__);\ if(z>0) function(xm1, yp1, zm1, ##__VA_ARGS__);\ }\ \ if(y>0){\ function(xm1, ym1, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(xm1, ym1, zp1, ##__VA_ARGS__);\ if(z>0) function(xm1, ym1, zm1, ##__VA_ARGS__);\ }\ } float DynamicEDT3D::distanceValue_Error = -1.0; int DynamicEDT3D::distanceInCellsValue_Error = -1; DynamicEDT3D::DynamicEDT3D(int _maxdist_squared) { sqrt2 = sqrt(2.0); maxDist_squared = _maxdist_squared; maxDist = sqrt((double) maxDist_squared); data = NULL; gridMap = NULL; } DynamicEDT3D::~DynamicEDT3D() { if (data) { for (int x=0; x<sizeX; x++){ for (int y=0; y<sizeY; y++) delete[] data[x][y]; delete[] data[x]; } delete[] data; } if (gridMap) { for (int x=0; x<sizeX; x++){ for (int y=0; y<sizeY; y++) delete[] gridMap[x][y]; delete[] gridMap[x]; } delete[] gridMap; } } void DynamicEDT3D::initializeEmpty(int _sizeX, int _sizeY, int _sizeZ, bool initGridMap) { sizeX = _sizeX; sizeY = _sizeY; sizeZ = _sizeZ; sizeXm1 = sizeX-1; sizeYm1 = sizeY-1; sizeZm1 = sizeZ-1; if (data) { for (int x=0; x<sizeX; x++){ for (int y=0; y<sizeY; y++) delete[] data[x][y]; delete[] data[x]; } delete[] data; } data = new dataCell**[sizeX]; for (int x=0; x<sizeX; x++){ data[x] = new dataCell*[sizeY]; for(int y=0; y<sizeY; y++) data[x][y] = new dataCell[sizeZ]; } if (initGridMap) { if (gridMap) { for (int x=0; x<sizeX; x++){ for (int y=0; y<sizeY; y++) delete[] gridMap[x][y]; delete[] gridMap[x]; } delete[] gridMap; } gridMap = new bool**[sizeX]; for (int x=0; x<sizeX; x++){ gridMap[x] = new bool*[sizeY]; for (int y=0; y<sizeY; y++) gridMap[x][y] = new bool[sizeZ]; } } dataCell c; c.dist = maxDist; c.sqdist = maxDist_squared; c.obstX = invalidObstData; c.obstY = invalidObstData; c.obstZ = invalidObstData; c.queueing = fwNotQueued; c.needsRaise = false; for (int x=0; x<sizeX; x++){ for (int y=0; y<sizeY; y++){ for (int z=0; z<sizeZ; z++){ data[x][y][z] = c; } } } if (initGridMap) { for (int x=0; x<sizeX; x++) for (int y=0; y<sizeY; y++) for (int z=0; z<sizeZ; z++) gridMap[x][y][z] = 0; } } void DynamicEDT3D::initializeMap(int _sizeX, int _sizeY, int _sizeZ, bool*** _gridMap) { gridMap = _gridMap; initializeEmpty(_sizeX, _sizeY, _sizeZ, false); for (int x=0; x<sizeX; x++) { for (int y=0; y<sizeY; y++) { for (int z=0; z<sizeZ; z++) { if (gridMap[x][y][z]) { dataCell c = data[x][y][z]; if (!isOccupied(x,y,z,c)) { bool isSurrounded = true; for (int dx=-1; dx<=1; dx++) { int nx = x+dx; if (nx<0 || nx>sizeX-1) continue; for (int dy=-1; dy<=1; dy++) { int ny = y+dy; if (ny<0 || ny>sizeY-1) continue; for (int dz=-1; dz<=1; dz++) { if (dx==0 && dy==0 && dz==0) continue; int nz = z+dz; if (nz<0 || nz>sizeZ-1) continue; if (!gridMap[nx][ny][nz]) { isSurrounded = false; break; } } } } if (isSurrounded) { c.obstX = x; c.obstY = y; c.obstZ = z; c.sqdist = 0; c.dist = 0; c.queueing = fwProcessed; data[x][y][z] = c; } else setObstacle(x,y,z); } } } } } } void DynamicEDT3D::occupyCell(int x, int y, int z) { gridMap[x][y][z] = 1; setObstacle(x,y,z); } void DynamicEDT3D::clearCell(int x, int y, int z) { gridMap[x][y][z] = 0; removeObstacle(x,y,z); } void DynamicEDT3D::setObstacle(int x, int y, int z) { dataCell c = data[x][y][z]; if(isOccupied(x,y,z,c)) return; addList.push_back(INTPOINT3D(x,y,z)); c.obstX = x; c.obstY = y; c.obstZ = z; data[x][y][z] = c; } void DynamicEDT3D::removeObstacle(int x, int y, int z) { dataCell c = data[x][y][z]; if(isOccupied(x,y,z,c) == false) return; removeList.push_back(INTPOINT3D(x,y,z)); c.obstX = invalidObstData; c.obstY = invalidObstData; c.obstZ = invalidObstData; c.queueing = bwQueued; data[x][y][z] = c; } void DynamicEDT3D::exchangeObstacles(std::vector<INTPOINT3D> points) { for (unsigned int i=0; i<lastObstacles.size(); i++) { int x = lastObstacles[i].x; int y = lastObstacles[i].y; int z = lastObstacles[i].z; bool v = gridMap[x][y][z]; if (v) continue; removeObstacle(x,y,z); } lastObstacles.clear(); for (unsigned int i=0; i<points.size(); i++) { int x = points[i].x; int y = points[i].y; int z = points[i].z; bool v = gridMap[x][y][z]; if (v) continue; setObstacle(x,y,z); lastObstacles.push_back(points[i]); } } void DynamicEDT3D::update(bool updateRealDist) { commitAndColorize(updateRealDist); while (!open.empty()) { INTPOINT3D p = open.pop(); int x = p.x; int y = p.y; int z = p.z; dataCell c = data[x][y][z]; if(c.queueing==fwProcessed) continue; if (c.needsRaise) { // RAISE raiseCell(p, c, updateRealDist); data[x][y][z] = c; } else if (c.obstX != invalidObstData && isOccupied(c.obstX,c.obstY,c.obstZ,data[c.obstX][c.obstY][c.obstZ])) { // LOWER propagateCell(p, c, updateRealDist); data[x][y][z] = c; } } } void DynamicEDT3D::raiseCell(INTPOINT3D &p, dataCell &c, bool updateRealDist){ /* for (int dx=-1; dx<=1; dx++) { int nx = p.x+dx; if (nx<0 || nx>sizeX-1) continue; for (int dy=-1; dy<=1; dy++) { int ny = p.y+dy; if (ny<0 || ny>sizeY-1) continue; for (int dz=-1; dz<=1; dz++) { if (dx==0 && dy==0 && dz==0) continue; int nz = p.z+dz; if (nz<0 || nz>sizeZ-1) continue; inspectCellRaise(nx,ny,nz, updateRealDist); } } } */ FOR_EACH_NEIGHBOR_WITH_CHECK(inspectCellRaise,p, updateRealDist) c.needsRaise = false; c.queueing = bwProcessed; } void DynamicEDT3D::inspectCellRaise(int &nx, int &ny, int &nz, bool updateRealDist){ dataCell nc = data[nx][ny][nz]; if (nc.obstX!=invalidObstData && !nc.needsRaise) { if(!isOccupied(nc.obstX,nc.obstY,nc.obstZ,data[nc.obstX][nc.obstY][nc.obstZ])) { open.push(nc.sqdist, INTPOINT3D(nx,ny,nz)); nc.queueing = fwQueued; nc.needsRaise = true; nc.obstX = invalidObstData; nc.obstY = invalidObstData; nc.obstZ = invalidObstData; if (updateRealDist) nc.dist = maxDist; nc.sqdist = maxDist_squared; data[nx][ny][nz] = nc; } else { if(nc.queueing != fwQueued){ open.push(nc.sqdist, INTPOINT3D(nx,ny,nz)); nc.queueing = fwQueued; data[nx][ny][nz] = nc; } } } } void DynamicEDT3D::propagateCell(INTPOINT3D &p, dataCell &c, bool updateRealDist){ c.queueing = fwProcessed; /* for (int dx=-1; dx<=1; dx++) { int nx = p.x+dx; if (nx<0 || nx>sizeX-1) continue; for (int dy=-1; dy<=1; dy++) { int ny = p.y+dy; if (ny<0 || ny>sizeY-1) continue; for (int dz=-1; dz<=1; dz++) { if (dx==0 && dy==0 && dz==0) continue; int nz = p.z+dz; if (nz<0 || nz>sizeZ-1) continue; inspectCellPropagate(nx, ny, nz, c, updateRealDist); } } } */ if(c.sqdist==0){ FOR_EACH_NEIGHBOR_WITH_CHECK(inspectCellPropagate, p, c, updateRealDist) } else { int x=p.x; int y=p.y; int z=p.z; int xp1 = x+1; int xm1 = x-1; int yp1 = y+1; int ym1 = y-1; int zp1 = z+1; int zm1 = z-1; int dpx = (x - c.obstX); int dpy = (y - c.obstY); int dpz = (z - c.obstZ); // dpy=0; // dpz=0; if(dpz >=0 && z<sizeZm1) inspectCellPropagate(x, y, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(x, y, zm1, c, updateRealDist); if(dpy>=0 && y<sizeYm1){ inspectCellPropagate(x, yp1, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(x, yp1, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(x, yp1, zm1, c, updateRealDist); } if(dpy<=0 && y>0){ inspectCellPropagate(x, ym1, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(x, ym1, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(x, ym1, zm1, c, updateRealDist); } if(dpx>=0 && x<sizeXm1){ inspectCellPropagate(xp1, y, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(xp1, y, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(xp1, y, zm1, c, updateRealDist); if(dpy>=0 && y<sizeYm1){ inspectCellPropagate(xp1, yp1, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(xp1, yp1, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(xp1, yp1, zm1, c, updateRealDist); } if(dpy<=0 && y>0){ inspectCellPropagate(xp1, ym1, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(xp1, ym1, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(xp1, ym1, zm1, c, updateRealDist); } } if(dpx<=0 && x>0){ inspectCellPropagate(xm1, y, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(xm1, y, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(xm1, y, zm1, c, updateRealDist); if(dpy>=0 && y<sizeYm1){ inspectCellPropagate(xm1, yp1, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(xm1, yp1, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(xm1, yp1, zm1, c, updateRealDist); } if(dpy<=0 && y>0){ inspectCellPropagate(xm1, ym1, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(xm1, ym1, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(xm1, ym1, zm1, c, updateRealDist); } } } } void DynamicEDT3D::inspectCellPropagate(int &nx, int &ny, int &nz, dataCell &c, bool updateRealDist){ dataCell nc = data[nx][ny][nz]; if(!nc.needsRaise) { int distx = nx-c.obstX; int disty = ny-c.obstY; int distz = nz-c.obstZ; int newSqDistance = distx*distx + disty*disty + distz*distz; if(newSqDistance > maxDist_squared) newSqDistance = maxDist_squared; bool overwrite = (newSqDistance < nc.sqdist); if(!overwrite && newSqDistance==nc.sqdist) { //the neighbor cell is marked to be raised, has no valid source obstacle if (nc.obstX == invalidObstData){ overwrite = true; } else { //the neighbor has no valid source obstacle but the raise wave has not yet reached it dataCell tmp = data[nc.obstX][nc.obstY][nc.obstZ]; if((tmp.obstX==nc.obstX && tmp.obstY==nc.obstY && tmp.obstZ==nc.obstZ)==false) overwrite = true; } } if (overwrite) { if(newSqDistance < maxDist_squared){ open.push(newSqDistance, INTPOINT3D(nx,ny,nz)); nc.queueing = fwQueued; } if (updateRealDist) { nc.dist = sqrt((double) newSqDistance); } nc.sqdist = newSqDistance; nc.obstX = c.obstX; nc.obstY = c.obstY; nc.obstZ = c.obstZ; } data[nx][ny][nz] = nc; } } float DynamicEDT3D::getDistance( int x, int y, int z ) const { if( (x>=0) && (x<sizeX) && (y>=0) && (y<sizeY) && (z>=0) && (z<sizeZ)){ return data[x][y][z].dist; } else return distanceValue_Error; } INTPOINT3D DynamicEDT3D::getClosestObstacle( int x, int y, int z ) const { if( (x>=0) && (x<sizeX) && (y>=0) && (y<sizeY) && (z>=0) && (z<sizeZ)){ dataCell c = data[x][y][z]; return INTPOINT3D(c.obstX, c.obstY, c.obstZ); } else return INTPOINT3D(invalidObstData, invalidObstData, invalidObstData); } int DynamicEDT3D::getSQCellDistance( int x, int y, int z ) const { if( (x>=0) && (x<sizeX) && (y>=0) && (y<sizeY) && (z>=0) && (z<sizeZ)){ return data[x][y][z].sqdist; } else return distanceInCellsValue_Error; } void DynamicEDT3D::commitAndColorize(bool updateRealDist) { // ADD NEW OBSTACLES for (unsigned int i=0; i<addList.size(); i++) { INTPOINT3D p = addList[i]; int x = p.x; int y = p.y; int z = p.z; dataCell c = data[x][y][z]; if(c.queueing != fwQueued){ if (updateRealDist) c.dist = 0; c.sqdist = 0; c.obstX = x; c.obstY = y; c.obstZ = z; c.queueing = fwQueued; data[x][y][z] = c; open.push(0, INTPOINT3D(x,y,z)); } } // REMOVE OLD OBSTACLES for (unsigned int i=0; i<removeList.size(); i++) { INTPOINT3D p = removeList[i]; int x = p.x; int y = p.y; int z = p.z; dataCell c = data[x][y][z]; if (isOccupied(x,y,z,c)==true) continue; // obstacle was removed and reinserted open.push(0, INTPOINT3D(x,y,z)); if (updateRealDist) c.dist = maxDist; c.sqdist = maxDist_squared; c.needsRaise = true; data[x][y][z] = c; } removeList.clear(); addList.clear(); } bool DynamicEDT3D::isOccupied(int x, int y, int z) const { dataCell c = data[x][y][z]; return (c.obstX==x && c.obstY==y && c.obstZ==z); } bool DynamicEDT3D::isOccupied(int &x, int &y, int &z, dataCell &c) { return (c.obstX==x && c.obstY==y && c.obstZ==z); }
16,104
26.204392
112
cpp
octomap
octomap-master/dynamicEDT3D/src/examples/exampleEDT3D.cpp
/** * dynamicEDT3D: * A library for incrementally updatable Euclidean distance transforms in 3D. * @author C. Sprunk, B. Lau, W. Burgard, University of Freiburg, Copyright (C) 2011. * @see http://octomap.sourceforge.net/ * License: New BSD License */ /* * Copyright (c) 2011-2012, C. Sprunk, B. Lau, W. Burgard, University of Freiburg * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <dynamicEDT3D/dynamicEDT3D.h> #include <iostream> #include <stdlib.h> int main( int , char** ) { //we build a sample map int sizeX, sizeY, sizeZ; sizeX=100; sizeY=100; sizeZ=100; bool*** map; map = new bool**[sizeX]; for(int x=0; x<sizeX; x++){ map[x] = new bool*[sizeY]; for(int y=0; y<sizeY; y++){ map[x][y] = new bool[sizeZ]; for(int z=0; z<sizeZ; z++){ if(x<2 || x > sizeX-3 || y < 2 || y > sizeY-3 || z<2 || z > sizeZ-3) map[x][y][z] = 1; else map[x][y][z] = 0; } } } map[51][45][67] = 1; map[50][50][68] = 1; // create the EDT object and initialize it with the map int maxDistInCells = 20; DynamicEDT3D distmap(maxDistInCells*maxDistInCells); distmap.initializeMap(sizeX, sizeY, sizeZ, map); //compute the distance map distmap.update(); // now perform some updates with random obstacles int numPoints = 20; for (int frame=1; frame<=10; frame++) { std::cout<<"\n\nthis is frame #"<<frame<<std::endl; std::vector<IntPoint3D> newObstacles; for (int i=0; i<numPoints; i++) { double x = 2+rand()/(double)RAND_MAX*(sizeX-4); double y = 2+rand()/(double)RAND_MAX*(sizeY-4); double z = 2+rand()/(double)RAND_MAX*(sizeZ-4); newObstacles.push_back(IntPoint3D(x,y,z)); } // register the new obstacles (old ones will be removed) distmap.exchangeObstacles(newObstacles); //update the distance map distmap.update(); //retrieve distance at a point float dist = distmap.getDistance(30,67,33); int distSquared = distmap.getSQCellDistance(30,67,33); std::cout<<"distance at 30,67,33: "<< dist << " squared: "<< distSquared << std::endl; if(distSquared == maxDistInCells*maxDistInCells) std::cout<<"we hit a cell with d = dmax, distance value is clamped."<<std::endl; //retrieve closest occupied cell at a point IntPoint3D closest = distmap.getClosestObstacle(30,67,33); if(closest.x == DynamicEDT3D::invalidObstData) std::cout<<"we hit a cell with d = dmax, no information about closest occupied cell."<<std::endl; else std::cout<<"closest occupied cell to 30,67,33: "<< closest.x<<","<<closest.y<<","<<closest.z<<std::endl; } std::cout<<"\n\nthis is the last frame"<<std::endl; // now remove all random obstacles again. std::vector<IntPoint3D> empty; distmap.exchangeObstacles(empty); distmap.update(); //retrieve distance at a point float dist = distmap.getDistance(30,67,33); int distSquared = distmap.getSQCellDistance(30,67,33); std::cout<<"distance at 30,67,33: "<< dist << " squared: "<< distSquared << std::endl; if(distSquared == maxDistInCells*maxDistInCells) std::cout<<"we hit a cell with d = dmax, distance value is clamped."<<std::endl; //retrieve closest occupied cell at a point IntPoint3D closest = distmap.getClosestObstacle(30,67,33); if(closest.x == DynamicEDT3D::invalidObstData) std::cout<<"we hit a cell with d = dmax, no information about closest occupied cell."<<std::endl; else std::cout<<"closest occupied cell to 30,67,33: "<< closest.x<<","<<closest.y<<","<<closest.z<<std::endl; return 0; }
5,086
36.404412
108
cpp
octomap
octomap-master/dynamicEDT3D/src/examples/exampleEDTOctomap.cpp
/** * dynamicEDT3D: * A library for incrementally updatable Euclidean distance transforms in 3D. * @author C. Sprunk, B. Lau, W. Burgard, University of Freiburg, Copyright (C) 2011. * @see http://octomap.sourceforge.net/ * License: New BSD License */ /* * Copyright (c) 2011-2012, C. Sprunk, B. Lau, W. Burgard, University of Freiburg * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <dynamicEDT3D/dynamicEDTOctomap.h> #include <iostream> int main( int argc, char *argv[] ) { if(argc<=1){ std::cout<<"usage: "<<argv[0]<<" <octoMap.bt>"<<std::endl; exit(0); } octomap::OcTree *tree = NULL; tree = new octomap::OcTree(0.05); //read in octotree tree->readBinary(argv[1]); std::cout<<"read in tree, "<<tree->getNumLeafNodes()<<" leaves "<<std::endl; double x,y,z; tree->getMetricMin(x,y,z); octomap::point3d min(x,y,z); //std::cout<<"Metric min: "<<x<<","<<y<<","<<z<<std::endl; tree->getMetricMax(x,y,z); octomap::point3d max(x,y,z); //std::cout<<"Metric max: "<<x<<","<<y<<","<<z<<std::endl; bool unknownAsOccupied = true; unknownAsOccupied = false; float maxDist = 1.0; //- the first argument ist the max distance at which distance computations are clamped //- the second argument is the octomap //- arguments 3 and 4 can be used to restrict the distance map to a subarea //- argument 5 defines whether unknown space is treated as occupied or free //The constructor copies data but does not yet compute the distance map DynamicEDTOctomap distmap(maxDist, tree, min, max, unknownAsOccupied); //This computes the distance map distmap.update(); //This is how you can query the map octomap::point3d p(5.0,5.0,0.6); //As we don't know what the dimension of the loaded map are, we modify this point p.x() = min.x() + 0.3 * (max.x() - min.x()); p.y() = min.y() + 0.6 * (max.y() - min.y()); p.z() = min.z() + 0.5 * (max.z() - min.z()); octomap::point3d closestObst; float distance; distmap.getDistanceAndClosestObstacle(p, distance, closestObst); std::cout<<"\n\ndistance at point "<<p.x()<<","<<p.y()<<","<<p.z()<<" is "<<distance<<std::endl; if(distance < distmap.getMaxDist()) std::cout<<"closest obstacle to "<<p.x()<<","<<p.y()<<","<<p.z()<<" is at "<<closestObst.x()<<","<<closestObst.y()<<","<<closestObst.z()<<std::endl; //if you modify the octree via tree->insertScan() or tree->updateNode() //just call distmap.update() again to adapt the distance map to the changes made delete tree; return 0; }
4,039
38.607843
152
cpp
octomap
octomap-master/dynamicEDT3D/src/examples/exampleEDTOctomapStamped.cpp
/** * dynamicEDT3D: * A library for incrementally updatable Euclidean distance transforms in 3D. * @author C. Sprunk, B. Lau, W. Burgard, University of Freiburg, Copyright (C) 2011. * @see http://octomap.sourceforge.net/ * License: New BSD License */ /* * Copyright (c) 2011-2012, C. Sprunk, B. Lau, W. Burgard, University of Freiburg * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <dynamicEDT3D/dynamicEDTOctomap.h> #include <iostream> int main( int argc, char *argv[] ) { if(argc<=1){ std::cout<<"usage: "<<argv[0]<<" <octoMap.bt>"<<std::endl; exit(0); } typedef octomap::OcTreeStamped OcTreeType; OcTreeType *tree = NULL; tree = new OcTreeType(0.05); //read in octotree tree->readBinary(argv[1]); std::cout<<"read in tree, "<<tree->getNumLeafNodes()<<" leaves "<<std::endl; double x,y,z; tree->getMetricMin(x,y,z); octomap::point3d min(x,y,z); //std::cout<<"Metric min: "<<x<<","<<y<<","<<z<<std::endl; tree->getMetricMax(x,y,z); octomap::point3d max(x,y,z); //std::cout<<"Metric max: "<<x<<","<<y<<","<<z<<std::endl; bool unknownAsOccupied = true; unknownAsOccupied = false; float maxDist = 1.0; //- the first argument is the max distance at which distance computations are clamped //- the second argument is the octomap //- arguments 3 and 4 can be used to restrict the distance map to a subarea //- argument 5 defines whether unknown space is treated as occupied or free //The constructor copies data but does not yet compute the distance map DynamicEDTOctomapStamped distmap(maxDist, tree, min, max, unknownAsOccupied); //This computes the distance map distmap.update(); //This is how you can query the map octomap::point3d p(5.0,5.0,0.6); //As we don't know what the dimension of the loaded map are, we modify this point p.x() = min.x() + 0.3 * (max.x() - min.x()); p.y() = min.y() + 0.6 * (max.y() - min.y()); p.z() = min.z() + 0.5 * (max.z() - min.z()); octomap::point3d closestObst; float distance; distmap.getDistanceAndClosestObstacle(p, distance, closestObst); std::cout<<"\n\ndistance at point "<<p.x()<<","<<p.y()<<","<<p.z()<<" is "<<distance<<std::endl; if(distance < distmap.getMaxDist()) std::cout<<"closest obstacle to "<<p.x()<<","<<p.y()<<","<<p.z()<<" is at "<<closestObst.x()<<","<<closestObst.y()<<","<<closestObst.z()<<std::endl; //if you modify the octree via tree->insertScan() or tree->updateNode() //just call distmap.update() again to adapt the distance map to the changes made delete tree; return 0; }
4,080
38.621359
152
cpp
octomap
octomap-master/octomap/README.md
Octomap - A probabilistic, flexible, and compact 3D mapping library for robotic systems ======================================================================================= Authors: Kai M. Wurm and Armin Hornung, University of Freiburg, Copyright (C) 2009-2013. https://octomap.github.io See the [list of contributors](https://github.com/OctoMap/octomap/blob/devel/octomap/AUTHORS.txt) for further authors. License for octomap: [New BSD License](https://github.com/OctoMap/octomap/blob/devel/octomap/LICENSE.txt) REQUIREMENTS ------------ * For only the octomap library: cmake and a regular build environment (gcc) * For HTML documentation: doxygen (optional) * For the viewer octovis: Qt4, OpenGL, QGLViewer (optional) Skip to WINDOWS for tips on compilation under Windows. You can install all dependencies on Ubuntu by running: sudo apt-get install cmake doxygen libqt4-dev libqt4-opengl-dev libqglviewer-dev-qt4 (Note: for older releases of Ubuntu you need to exchange the last package name with `libqglviewer-qt4-dev`) INSTALLATION ------------ See http://www.ros.org/wiki/octomap if you want to use OctoMap in ROS! There are pre-compiled packages for octomap, octovis, and ROS integration available. Build the complete project by changing into the "build" directory and running cmake: mkdir build && cd build cmake .. Type `make` to compile afterwards. This will create all CMake files cleanly in the `build` folder (Out-of-source build). Executables will end up in `bin`, libraries in `lib`. A debug configuration can be created by running: cmake -DCMAKE_BUILD_TYPE=Debug .. in `build` or a different directory (e.g. `build-debug`). You can install the library by running `make install`, though it is usually not necessary. Be sure to adjust `CMAKE_INSTALL_PREFIX` before. The target `make test` executes the unit tests for the octomap library, if you are interested in verifying the functionality on your machine. DOCUMENTATION ------------- The documentation for the latest stable release is available online: https://octomap.github.io/octomap/doc/index.html You can build the most current HTML-Documentation for your current source with Doxygen by running `make docs` in the build directory. The documentation will end up in `doc/html/index.html` in the main directory. GETTING STARTED --------------- Jump right in and have a look at the example src/octomap/simple_example.cpp Or start the 3D viewer with `bin/octovis` You will find an example scan and binary tree to load in the directory `share`. Further examples can be downloaded from the project website. USE IN OTHER PROJECTS --------------------- A CMake-project config is generated for OctoMap which allows OctoMap to be used from other CMake-Projects easily. Point CMake to your octomap installation so that it finds the file octomap/lib/cmake/octomap/octomap-config.cmake, e.g. by setting the environment variable `octomap_DIR`to the directory containing it. Then add the following to your CMakeLists.txt: find_package(octomap REQUIRED) include_directories(${OCTOMAP_INCLUDE_DIRS}) link_libraries(${OCTOMAP_LIBRARIES}) In addition to this cmake-module we also provide a pkgconfig-file. For convenience, there is a minimal example project included in the file share/example-project.tgz ECLIPSE PROJECT FILES --------------------- Eclipse project files can be generated (with some limitations, see: https://gitlab.kitware.com/cmake/community/-/wikis/doc/editors/Eclipse-CDT4-Generator) by running: cmake -G"Eclipse CDT4 - Unix Makefiles" .. Import the project (existing project, root is the build folder, do not copy contents) into Eclipse afterwards. For full Eclipse compatibility, it might be necessary to build in the main source directory. WINDOWS ------- The octomap library and tools can be compiled and used under Windows although this has not been tested in-depth. Feedback is welcome. To compile the library you need cmake (https://www.cmake.org) and either MinGW or Visual Studio. ### MinGW ### 1. Download the MinGW distribution (http://www.mingw.org) 2. Install C++ compiler and add MingGW/bin to your system PATH 3. Start the cmake-gui and set the code directory to the library root (e.g. `/octomap`) 4. Create and set the build directory to, e.g., `/octomap/build`. 5. Press "Configure" then "Generate", select the appropriate generator, "MinGW Makefiles". 6. Start a command shell and "make" the project: octomap> cd build octomap/build> mingw32-make.exe As verification, you can run the unit tests using ctest on the command prompt: octomap/build> ctest.exe ### Microsoft Visual Studio (2013 or later recommended) ### Last tested with MSVC 2013 and 2015 (Community Edition). 1. Start the cmake-gui and set the source code directory to the library root (e.g. `\octomap`) 2. Create a build directory and set it in CMake ("Where to build the binaries"), e.g. `\octomap\build`. 3. Press "Configure" then "Generate", select the appropriate generator, e.g. "Visual Studio 2015". This generates a solution file `octomap.sln` in the build directory. 4. Load this file and build the project `ALL_BUILD` in Visual Studio. Instead of building the complete distribution (octomap, octovis, and dynamicEDT3D) you can only build octomap by proceeding as described above but in the `octomap` subdirectory. This can help you getting started when there are problems with octovis and Qt4. As verification, you can run the unit tests in Visual Studio by building the `RUN_TESTS` project or by using ctest on the command prompt: octomap/build> ctest.exe -C Release
5,700
32.733728
118
md
octomap
octomap-master/octomap/doxygen.h
/** * \namespace octomath Namespace of the math library in OctoMap * */ /** * \namespace octomap Namespace the OctoMap library and visualization tools * */ /** \mainpage OctoMap \section intro_sec Introduction The <a href="https://octomap.github.io/">OctoMap library</a> implements a 3D occupancy grid mapping approach. It provides data structures and mapping algorithms. The map is implemented using an \ref octomap::OcTree "Octree". It is designed to meet the following requirements: </p> <ul> <li> <b>Full 3D model.</b> The map is able to model arbitrary environments without prior assumptions about it. The representation models occupied areas as well as free space. If no information is available about an area (commonly denoted as <i>unknown areas</i>), this information is encoded as well. While the distinction between free and occupied space is essential for safe robot navigation, information about unknown areas is important, e.g., for autonomous exploration of an environment. </li> <li> <b>Updatable.</b> It is possible to add new information or sensor readings at any time. Modeling and updating is done in a <i>probabilistic</i> fashion. This accounts for sensor noise or measurements which result from dynamic changes in the environment, e.g., because of dynamic objects. Furthermore, multiple robots are able to contribute to the same map and a previously recorded map is extendable when new areas are explored. </li> <li> <b>Flexible.</b> The extent of the map does not have to be known in advance. Instead, the map is dynamically expanded as needed. The map is multi-resolution so that, for instance, a high-level planner is able to use a coarse map, while a local planner may operate using a fine resolution. This also allows for efficient visualizations which scale from coarse overviews to detailed close-up views. </li> <li> <b>Compact.</b> The is stored efficiently, both in memory and on disk. It is possible to generate compressed files for later usage or convenient exchange between robots even under bandwidth constraints. </li> </ul> <p> Octomap was developed by <a href="http://www.informatik.uni-freiburg.de/~wurm">Kai M. Wurm</a> and <a href="http://www.arminhornung.de">Armin Hornung</a>, and is currently maintained by Armin Hornung. A tracker for bug reports and feature requests is available available <a href="https://github.com/OctoMap/octomap/issues">on GitHub</a>. You can find an overview at https://octomap.github.io/ and the code repository at https://github.com/OctoMap/octomap.</p> \section install_sec Installation <p>See the file README.txt in the main folder. </p> \section changelog_sec Changelog <p>See the file CHANGELOG.txt in the main folder or the <a href="https://raw.github.com/OctoMap/octomap/master/octomap/CHANGELOG.txt">latest version online</a>. </p> \section gettingstarted_sec Getting Started <p> Jump right in and have a look at the main class \ref octomap::OcTree OcTree and the examples in src/octomap/simple_example.cpp. To integrate single measurements into the 3D map have a look at \ref octomap::OcTree::insertRay "OcTree::insertRay(...)", to insert full 3D scans (pointclouds) please have a look at \ref octomap::OcTree::insertPointCloud "OcTree::insertPointCloud(...)". Queries can be performed e.g. with \ref octomap::OcTree::search "OcTree::search(...)" or \ref octomap::OcTree::castRay "OcTree::castRay(...)". The preferred way to batch-access or process nodes in an Octree is with the iterators \ref leaf_iterator "leaf_iterator", \ref tree_iterator "tree_iterator", or \ref leaf_bbx_iterator "leaf_bbx_iterator".</p> \image html uml_overview.png <p>The \ref octomap::OcTree "OcTree" class is derived from \ref octomap::OccupancyOcTreeBase "OccupancyOcTreeBase", with most functionality in the parent class. Also derive from OccupancyOcTreeBase if you you want to implement your own Octree and node classes. You can have a look at the classes \ref octomap::OcTreeStamped "OcTreeStamped" and \ref octomap::OcTreeNodeStamped "OcTreeNodeStamped" as examples. </p> <p> Start the 3D visualization with: <b>bin/octovis</b> </p> <p> You will find an example 3D scan (please bunzip2 first) and an example OctoMap .bt file in the directory <b>share/data</b> to try. More data sets are available at http://ais.informatik.uni-freiburg.de/projects/datasets/octomap/. </p> **/
4,441
38.309735
228
h
octomap
octomap-master/octomap/include/octomap/AbstractOcTree.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMAP_ABSTRACT_OCTREE_H #define OCTOMAP_ABSTRACT_OCTREE_H #include <cstddef> #include <fstream> #include <string> #include <iostream> #include <map> namespace octomap { /** * This abstract class is an interface to all octrees and provides a * factory design pattern for readin and writing all kinds of OcTrees * to files (see read()). */ class AbstractOcTree { friend class StaticMapInit; public: AbstractOcTree(); virtual ~AbstractOcTree() {}; /// virtual constructor: creates a new object of same type virtual AbstractOcTree* create() const = 0; /// returns actual class name as string for identification virtual std::string getTreeType() const = 0; virtual double getResolution() const = 0; virtual void setResolution(double res) = 0; virtual size_t size() const = 0; virtual size_t memoryUsage() const = 0; virtual size_t memoryUsageNode() const = 0; virtual void getMetricMin(double& x, double& y, double& z) = 0; virtual void getMetricMin(double& x, double& y, double& z) const = 0; virtual void getMetricMax(double& x, double& y, double& z) = 0; virtual void getMetricMax(double& x, double& y, double& z) const = 0; virtual void getMetricSize(double& x, double& y, double& z) = 0; virtual void prune() = 0; virtual void expand() = 0; virtual void clear() = 0; //-- Iterator tree access // default iterator is leaf_iterator // class leaf_iterator; // class tree_iterator; // class leaf_bbx_iterator; // typedef leaf_iterator iterator; class iterator_base; // /// @return beginning of the tree as leaf iterator //virtual iterator_base begin(unsigned char maxDepth=0) const = 0; // /// @return end of the tree as leaf iterator // virtual const iterator end() const = 0; // /// @return beginning of the tree as leaf iterator // virtual leaf_iterator begin_leafs(unsigned char maxDepth=0) const = 0; // /// @return end of the tree as leaf iterator // virtual const leaf_iterator end_leafs() const = 0; // /// @return beginning of the tree as leaf iterator in a bounding box // virtual leaf_bbx_iterator begin_leafs_bbx(const OcTreeKey& min, const OcTreeKey& max, unsigned char maxDepth=0) const = 0; // /// @return beginning of the tree as leaf iterator in a bounding box // virtual leaf_bbx_iterator begin_leafs_bbx(const point3d& min, const point3d& max, unsigned char maxDepth=0) const = 0; // /// @return end of the tree as leaf iterator in a bounding box // virtual const leaf_bbx_iterator end_leafs_bbx() const = 0; // /// @return beginning of the tree as iterator to all nodes (incl. inner) // virtual tree_iterator begin_tree(unsigned char maxDepth=0) const = 0; // /// @return end of the tree as iterator to all nodes (incl. inner) // const tree_iterator end_tree() const = 0; /// Write file header and complete tree to file (serialization) bool write(const std::string& filename) const; /// Write file header and complete tree to stream (serialization) bool write(std::ostream& s) const; /** * Creates a certain OcTree (factory pattern) * * @param id unique ID of OcTree * @param res resolution of OcTree * @return pointer to newly created OcTree (empty). NULL if the ID is unknown! */ static AbstractOcTree* createTree(const std::string id, double res); /** * Read the file header, create the appropriate class and deserialize. * This creates a new octree which you need to delete yourself. If you * expect or requre a specific kind of octree, use dynamic_cast afterwards: * @code * AbstractOcTree* tree = AbstractOcTree::read("filename.ot"); * OcTree* octree = dynamic_cast<OcTree*>(tree); * * @endcode */ static AbstractOcTree* read(const std::string& filename); /// Read the file header, create the appropriate class and deserialize. /// This creates a new octree which you need to delete yourself. static AbstractOcTree* read(std::istream &s); /** * Read all nodes from the input stream (without file header), * for this the tree needs to be already created. * For general file IO, you * should probably use AbstractOcTree::read() instead. */ virtual std::istream& readData(std::istream &s) = 0; /// Write complete state of tree to stream (without file header) unmodified. /// Pruning the tree first produces smaller files (lossless compression) virtual std::ostream& writeData(std::ostream &s) const = 0; private: /// create private store, Construct on first use static std::map<std::string, AbstractOcTree*>& classIDMapping(); protected: static bool readHeader(std::istream &s, std::string& id, unsigned& size, double& res); static void registerTreeType(AbstractOcTree* tree); static const std::string fileHeader; }; } // end namespace #endif
6,748
39.90303
128
h
octomap
octomap-master/octomap/include/octomap/AbstractOccupancyOcTree.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMAP_ABSTRACT_OCCUPANCY_OCTREE_H #define OCTOMAP_ABSTRACT_OCCUPANCY_OCTREE_H #include "AbstractOcTree.h" #include "octomap_utils.h" #include "OcTreeNode.h" #include "OcTreeKey.h" #include <cassert> #include <fstream> namespace octomap { /** * Interface class for all octree types that store occupancy. This serves * as a common base class e.g. for polymorphism and contains common code * for reading and writing binary trees. */ class AbstractOccupancyOcTree : public AbstractOcTree { public: AbstractOccupancyOcTree(); virtual ~AbstractOccupancyOcTree() {}; //-- IO /** * Writes OcTree to a binary file using writeBinary(). * The OcTree is first converted to the maximum likelihood estimate and pruned. * @return success of operation */ bool writeBinary(const std::string& filename); /** * Writes compressed maximum likelihood OcTree to a binary stream. * The OcTree is first converted to the maximum likelihood estimate and pruned * for maximum compression. * @return success of operation */ bool writeBinary(std::ostream &s); /** * Writes OcTree to a binary file using writeBinaryConst(). * The OcTree is not changed, in particular not pruned first. * Files will be smaller when the tree is pruned first or by using * writeBinary() instead. * @return success of operation */ bool writeBinaryConst(const std::string& filename) const; /** * Writes the maximum likelihood OcTree to a binary stream (const variant). * Files will be smaller when the tree is pruned first or by using * writeBinary() instead. * @return success of operation */ bool writeBinaryConst(std::ostream &s) const; /// Writes the actual data, implemented in OccupancyOcTreeBase::writeBinaryData() virtual std::ostream& writeBinaryData(std::ostream &s) const = 0; /** * Reads an OcTree from an input stream. * Existing nodes of the tree are deleted before the tree is read. * @return success of operation */ bool readBinary(std::istream &s); /** * Reads OcTree from a binary file. * Existing nodes of the tree are deleted before the tree is read. * @return success of operation */ bool readBinary(const std::string& filename); /// Reads the actual data, implemented in OccupancyOcTreeBase::readBinaryData() virtual std::istream& readBinaryData(std::istream &s) = 0; // -- occupancy queries /// queries whether a node is occupied according to the tree's parameter for "occupancy" inline bool isNodeOccupied(const OcTreeNode* occupancyNode) const{ return (occupancyNode->getLogOdds() >= this->occ_prob_thres_log); } /// queries whether a node is occupied according to the tree's parameter for "occupancy" inline bool isNodeOccupied(const OcTreeNode& occupancyNode) const{ return (occupancyNode.getLogOdds() >= this->occ_prob_thres_log); } /// queries whether a node is at the clamping threshold according to the tree's parameter inline bool isNodeAtThreshold(const OcTreeNode* occupancyNode) const{ return (occupancyNode->getLogOdds() >= this->clamping_thres_max || occupancyNode->getLogOdds() <= this->clamping_thres_min); } /// queries whether a node is at the clamping threshold according to the tree's parameter inline bool isNodeAtThreshold(const OcTreeNode& occupancyNode) const{ return (occupancyNode.getLogOdds() >= this->clamping_thres_max || occupancyNode.getLogOdds() <= this->clamping_thres_min); } // - update functions /** * Manipulate log_odds value of voxel directly * * @param key of the NODE that is to be updated * @param log_odds_update value to be added (+) to log_odds value of node * @param lazy_eval whether update of inner nodes is omitted after the update (default: false). * This speeds up the insertion, but you need to call updateInnerOccupancy() when done. * @return pointer to the updated NODE */ virtual OcTreeNode* updateNode(const OcTreeKey& key, float log_odds_update, bool lazy_eval = false) = 0; /** * Manipulate log_odds value of voxel directly. * Looks up the OcTreeKey corresponding to the coordinate and then calls udpateNode() with it. * * @param value 3d coordinate of the NODE that is to be updated * @param log_odds_update value to be added (+) to log_odds value of node * @param lazy_eval whether update of inner nodes is omitted after the update (default: false). * This speeds up the insertion, but you need to call updateInnerOccupancy() when done. * @return pointer to the updated NODE */ virtual OcTreeNode* updateNode(const point3d& value, float log_odds_update, bool lazy_eval = false) = 0; /** * Integrate occupancy measurement. * * @param key of the NODE that is to be updated * @param occupied true if the node was measured occupied, else false * @param lazy_eval whether update of inner nodes is omitted after the update (default: false). * This speeds up the insertion, but you need to call updateInnerOccupancy() when done. * @return pointer to the updated NODE */ virtual OcTreeNode* updateNode(const OcTreeKey& key, bool occupied, bool lazy_eval = false) = 0; /** * Integrate occupancy measurement. * Looks up the OcTreeKey corresponding to the coordinate and then calls udpateNode() with it. * * @param value 3d coordinate of the NODE that is to be updated * @param occupied true if the node was measured occupied, else false * @param lazy_eval whether update of inner nodes is omitted after the update (default: false). * This speeds up the insertion, but you need to call updateInnerOccupancy() when done. * @return pointer to the updated NODE */ virtual OcTreeNode* updateNode(const point3d& value, bool occupied, bool lazy_eval = false) = 0; virtual void toMaxLikelihood() = 0; //-- parameters for occupancy and sensor model: /// sets the threshold for occupancy (sensor model) void setOccupancyThres(double prob){occ_prob_thres_log = logodds(prob); } /// sets the probability for a "hit" (will be converted to logodds) - sensor model void setProbHit(double prob){prob_hit_log = logodds(prob); assert(prob_hit_log >= 0.0);} /// sets the probability for a "miss" (will be converted to logodds) - sensor model void setProbMiss(double prob){prob_miss_log = logodds(prob); assert(prob_miss_log <= 0.0);} /// sets the minimum threshold for occupancy clamping (sensor model) void setClampingThresMin(double thresProb){clamping_thres_min = logodds(thresProb); } /// sets the maximum threshold for occupancy clamping (sensor model) void setClampingThresMax(double thresProb){clamping_thres_max = logodds(thresProb); } /// @return threshold (probability) for occupancy - sensor model double getOccupancyThres() const {return probability(occ_prob_thres_log); } /// @return threshold (logodds) for occupancy - sensor model float getOccupancyThresLog() const {return occ_prob_thres_log; } /// @return probability for a "hit" in the sensor model (probability) double getProbHit() const {return probability(prob_hit_log); } /// @return probability for a "hit" in the sensor model (logodds) float getProbHitLog() const {return prob_hit_log; } /// @return probability for a "miss" in the sensor model (probability) double getProbMiss() const {return probability(prob_miss_log); } /// @return probability for a "miss" in the sensor model (logodds) float getProbMissLog() const {return prob_miss_log; } /// @return minimum threshold for occupancy clamping in the sensor model (probability) double getClampingThresMin() const {return probability(clamping_thres_min); } /// @return minimum threshold for occupancy clamping in the sensor model (logodds) float getClampingThresMinLog() const {return clamping_thres_min; } /// @return maximum threshold for occupancy clamping in the sensor model (probability) double getClampingThresMax() const {return probability(clamping_thres_max); } /// @return maximum threshold for occupancy clamping in the sensor model (logodds) float getClampingThresMaxLog() const {return clamping_thres_max; } protected: /// Try to read the old binary format for conversion, will be removed in the future bool readBinaryLegacyHeader(std::istream &s, unsigned int& size, double& res); // occupancy parameters of tree, stored in logodds: float clamping_thres_min; float clamping_thres_max; float prob_hit_log; float prob_miss_log; float occ_prob_thres_log; static const std::string binaryFileHeader; }; } // end namespace #endif
10,721
43.305785
108
h
octomap
octomap-master/octomap/include/octomap/ColorOcTree.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMAP_COLOR_OCTREE_H #define OCTOMAP_COLOR_OCTREE_H #include <iostream> #include <octomap/OcTreeNode.h> #include <octomap/OccupancyOcTreeBase.h> namespace octomap { // forward declaraton for "friend" class ColorOcTree; // node definition class ColorOcTreeNode : public OcTreeNode { public: friend class ColorOcTree; // needs access to node children (inherited) class Color { public: Color() : r(255), g(255), b(255) {} Color(uint8_t _r, uint8_t _g, uint8_t _b) : r(_r), g(_g), b(_b) {} inline bool operator== (const Color &other) const { return (r==other.r && g==other.g && b==other.b); } inline bool operator!= (const Color &other) const { return (r!=other.r || g!=other.g || b!=other.b); } uint8_t r, g, b; }; public: ColorOcTreeNode() : OcTreeNode() {} ColorOcTreeNode(const ColorOcTreeNode& rhs) : OcTreeNode(rhs), color(rhs.color) {} bool operator==(const ColorOcTreeNode& rhs) const{ return (rhs.value == value && rhs.color == color); } void copyData(const ColorOcTreeNode& from){ OcTreeNode::copyData(from); this->color = from.getColor(); } inline Color getColor() const { return color; } inline void setColor(Color c) {this->color = c; } inline void setColor(uint8_t r, uint8_t g, uint8_t b) { this->color = Color(r,g,b); } Color& getColor() { return color; } // has any color been integrated? (pure white is very unlikely...) inline bool isColorSet() const { return ((color.r != 255) || (color.g != 255) || (color.b != 255)); } void updateColorChildren(); ColorOcTreeNode::Color getAverageChildColor() const; // file I/O std::istream& readData(std::istream &s); std::ostream& writeData(std::ostream &s) const; protected: Color color; }; // tree definition class ColorOcTree : public OccupancyOcTreeBase <ColorOcTreeNode> { public: /// Default constructor, sets resolution of leafs ColorOcTree(double resolution); /// virtual constructor: creates a new object of same type /// (Covariant return type requires an up-to-date compiler) ColorOcTree* create() const {return new ColorOcTree(resolution); } std::string getTreeType() const {return "ColorOcTree";} /** * Prunes a node when it is collapsible. This overloaded * version only considers the node occupancy for pruning, * different colors of child nodes are ignored. * @return true if pruning was successful */ virtual bool pruneNode(ColorOcTreeNode* node); virtual bool isNodeCollapsible(const ColorOcTreeNode* node) const; // set node color at given key or coordinate. Replaces previous color. ColorOcTreeNode* setNodeColor(const OcTreeKey& key, uint8_t r, uint8_t g, uint8_t b); ColorOcTreeNode* setNodeColor(float x, float y, float z, uint8_t r, uint8_t g, uint8_t b) { OcTreeKey key; if (!this->coordToKeyChecked(point3d(x,y,z), key)) return NULL; return setNodeColor(key,r,g,b); } // integrate color measurement at given key or coordinate. Average with previous color ColorOcTreeNode* averageNodeColor(const OcTreeKey& key, uint8_t r, uint8_t g, uint8_t b); ColorOcTreeNode* averageNodeColor(float x, float y, float z, uint8_t r, uint8_t g, uint8_t b) { OcTreeKey key; if (!this->coordToKeyChecked(point3d(x,y,z), key)) return NULL; return averageNodeColor(key,r,g,b); } // integrate color measurement at given key or coordinate. Average with previous color ColorOcTreeNode* integrateNodeColor(const OcTreeKey& key, uint8_t r, uint8_t g, uint8_t b); ColorOcTreeNode* integrateNodeColor(float x, float y, float z, uint8_t r, uint8_t g, uint8_t b) { OcTreeKey key; if (!this->coordToKeyChecked(point3d(x,y,z), key)) return NULL; return integrateNodeColor(key,r,g,b); } // update inner nodes, sets color to average child color void updateInnerOccupancy(); // uses gnuplot to plot a RGB histogram in EPS format void writeColorHistogram(std::string filename); protected: void updateInnerOccupancyRecurs(ColorOcTreeNode* node, unsigned int depth); /** * Static member object which ensures that this OcTree's prototype * ends up in the classIDMapping only once. You need this as a * static member in any derived octree class in order to read .ot * files through the AbstractOcTree factory. You should also call * ensureLinking() once from the constructor. */ class StaticMemberInitializer{ public: StaticMemberInitializer() { ColorOcTree* tree = new ColorOcTree(0.1); tree->clearKeyRays(); AbstractOcTree::registerTreeType(tree); } /** * Dummy function to ensure that MSVC does not drop the * StaticMemberInitializer, causing this tree failing to register. * Needs to be called from the constructor of this octree. */ void ensureLinking() {}; }; /// static member to ensure static initialization (only once) static StaticMemberInitializer colorOcTreeMemberInit; }; //! user friendly output in format (r g b) std::ostream& operator<<(std::ostream& out, ColorOcTreeNode::Color const& c); } // end namespace #endif
7,563
35.365385
90
h
octomap
octomap-master/octomap/include/octomap/CountingOcTree.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMAP_COUNTING_OCTREE_HH #define OCTOMAP_COUNTING_OCTREE_HH #include <stdio.h> #include "OcTreeBase.h" #include "OcTreeDataNode.h" namespace octomap { /** * An Octree-node which stores an internal counter per node / volume. * * Count is recursive, parent nodes have the summed count of their * children. * * \note In our mapping system this data structure is used in * CountingOcTree in the sensor model only */ class CountingOcTreeNode : public OcTreeDataNode<unsigned int> { public: CountingOcTreeNode(); ~CountingOcTreeNode(); inline unsigned int getCount() const { return getValue(); } inline void increaseCount() { value++; } inline void setCount(unsigned c) {this->setValue(c); } }; /** * An AbstractOcTree which stores an internal counter per node / volume. * * Count is recursive, parent nodes have the summed count of their * children. * * \note Was only used internally, not used anymore */ class CountingOcTree : public OcTreeBase <CountingOcTreeNode> { public: /// Default constructor, sets resolution of leafs CountingOcTree(double resolution); virtual CountingOcTreeNode* updateNode(const point3d& value); CountingOcTreeNode* updateNode(const OcTreeKey& k); void getCentersMinHits(point3d_list& node_centers, unsigned int min_hits) const; protected: void getCentersMinHitsRecurs( point3d_list& node_centers, unsigned int& min_hits, unsigned int max_depth, CountingOcTreeNode* node, unsigned int depth, const OcTreeKey& parent_key) const; /** * Static member object which ensures that this OcTree's prototype * ends up in the classIDMapping only once. You need this as a * static member in any derived octree class in order to read .ot * files through the AbstractOcTree factory. You should also call * ensureLinking() once from the constructor. */ class StaticMemberInitializer{ public: StaticMemberInitializer() { CountingOcTree* tree = new CountingOcTree(0.1); tree->clearKeyRays(); AbstractOcTree::registerTreeType(tree); } /** * Dummy function to ensure that MSVC does not drop the * StaticMemberInitializer, causing this tree failing to register. * Needs to be called from the constructor of this octree. */ void ensureLinking() {}; }; /// static member to ensure static initialization (only once) static StaticMemberInitializer countingOcTreeMemberInit; }; } #endif
4,512
35.395161
84
h
octomap
octomap-master/octomap/include/octomap/MCTables.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2013, F-M. De Rainville, P. Bourke * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMAP_MCTABLES_H #define OCTOMAP_MCTABLES_H /** * Tables used by the Marching Cubes Algorithm * The tables are from Paul Bourke's web page * http://paulbourke.net/geometry/polygonise/ * Used with permission here under BSD license. */ namespace octomap { static const int edgeTable[256]={ 0x0 , 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c, 0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00, 0x190, 0x99 , 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c, 0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90, 0x230, 0x339, 0x33 , 0x13a, 0x636, 0x73f, 0x435, 0x53c, 0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30, 0x3a0, 0x2a9, 0x1a3, 0xaa , 0x7a6, 0x6af, 0x5a5, 0x4ac, 0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0, 0x460, 0x569, 0x663, 0x76a, 0x66 , 0x16f, 0x265, 0x36c, 0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60, 0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0xff , 0x3f5, 0x2fc, 0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0, 0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x55 , 0x15c, 0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950, 0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0xcc , 0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0, 0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc, 0xcc , 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0, 0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c, 0x15c, 0x55 , 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650, 0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc, 0x2fc, 0x3f5, 0xff , 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0, 0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c, 0x36c, 0x265, 0x16f, 0x66 , 0x76a, 0x663, 0x569, 0x460, 0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac, 0x4ac, 0x5a5, 0x6af, 0x7a6, 0xaa , 0x1a3, 0x2a9, 0x3a0, 0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c, 0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x33 , 0x339, 0x230, 0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c, 0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x99 , 0x190, 0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c, 0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x0 }; static const int triTable[256][16] = {{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 8, 3, 9, 8, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 2, 10, 0, 2, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 8, 3, 2, 10, 8, 10, 9, 8, -1, -1, -1, -1, -1, -1, -1}, {3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 11, 2, 8, 11, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 9, 0, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 11, 2, 1, 9, 11, 9, 8, 11, -1, -1, -1, -1, -1, -1, -1}, {3, 10, 1, 11, 10, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 10, 1, 0, 8, 10, 8, 11, 10, -1, -1, -1, -1, -1, -1, -1}, {3, 9, 0, 3, 11, 9, 11, 10, 9, -1, -1, -1, -1, -1, -1, -1}, {9, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 3, 0, 7, 3, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 1, 9, 4, 7, 1, 7, 3, 1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 4, 7, 3, 0, 4, 1, 2, 10, -1, -1, -1, -1, -1, -1, -1}, {9, 2, 10, 9, 0, 2, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, {2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4, -1, -1, -1, -1}, {8, 4, 7, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 4, 7, 11, 2, 4, 2, 0, 4, -1, -1, -1, -1, -1, -1, -1}, {9, 0, 1, 8, 4, 7, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, {4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1, -1, -1, -1, -1}, {3, 10, 1, 3, 11, 10, 7, 8, 4, -1, -1, -1, -1, -1, -1, -1}, {1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4, -1, -1, -1, -1}, {4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3, -1, -1, -1, -1}, {4, 7, 11, 4, 11, 9, 9, 11, 10, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 4, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 5, 4, 1, 5, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 5, 4, 8, 3, 5, 3, 1, 5, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 8, 1, 2, 10, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, {5, 2, 10, 5, 4, 2, 4, 0, 2, -1, -1, -1, -1, -1, -1, -1}, {2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8, -1, -1, -1, -1}, {9, 5, 4, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 11, 2, 0, 8, 11, 4, 9, 5, -1, -1, -1, -1, -1, -1, -1}, {0, 5, 4, 0, 1, 5, 2, 3, 11, -1, -1, -1, -1, -1, -1, -1}, {2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5, -1, -1, -1, -1}, {10, 3, 11, 10, 1, 3, 9, 5, 4, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10, -1, -1, -1, -1}, {5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3, -1, -1, -1, -1}, {5, 4, 8, 5, 8, 10, 10, 8, 11, -1, -1, -1, -1, -1, -1, -1}, {9, 7, 8, 5, 7, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 3, 0, 9, 5, 3, 5, 7, 3, -1, -1, -1, -1, -1, -1, -1}, {0, 7, 8, 0, 1, 7, 1, 5, 7, -1, -1, -1, -1, -1, -1, -1}, {1, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 7, 8, 9, 5, 7, 10, 1, 2, -1, -1, -1, -1, -1, -1, -1}, {10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3, -1, -1, -1, -1}, {8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2, -1, -1, -1, -1}, {2, 10, 5, 2, 5, 3, 3, 5, 7, -1, -1, -1, -1, -1, -1, -1}, {7, 9, 5, 7, 8, 9, 3, 11, 2, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11, -1, -1, -1, -1}, {2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7, -1, -1, -1, -1}, {11, 2, 1, 11, 1, 7, 7, 1, 5, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11, -1, -1, -1, -1}, {5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0, -1}, {11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0, -1}, {11, 10, 5, 7, 11, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 0, 1, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 8, 3, 1, 9, 8, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, {1, 6, 5, 2, 6, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 6, 5, 1, 2, 6, 3, 0, 8, -1, -1, -1, -1, -1, -1, -1}, {9, 6, 5, 9, 0, 6, 0, 2, 6, -1, -1, -1, -1, -1, -1, -1}, {5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8, -1, -1, -1, -1}, {2, 3, 11, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 0, 8, 11, 2, 0, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1, -1, -1, -1}, {5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11, -1, -1, -1, -1}, {6, 3, 11, 6, 5, 3, 5, 1, 3, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6, -1, -1, -1, -1}, {3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9, -1, -1, -1, -1}, {6, 5, 9, 6, 9, 11, 11, 9, 8, -1, -1, -1, -1, -1, -1, -1}, {5, 10, 6, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 3, 0, 4, 7, 3, 6, 5, 10, -1, -1, -1, -1, -1, -1, -1}, {1, 9, 0, 5, 10, 6, 8, 4, 7, -1, -1, -1, -1, -1, -1, -1}, {10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4, -1, -1, -1, -1}, {6, 1, 2, 6, 5, 1, 4, 7, 8, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7, -1, -1, -1, -1}, {8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6, -1, -1, -1, -1}, {7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9, -1}, {3, 11, 2, 7, 8, 4, 10, 6, 5, -1, -1, -1, -1, -1, -1, -1}, {5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11, -1, -1, -1, -1}, {0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6, -1, -1, -1, -1}, {9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6, -1}, {8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6, -1, -1, -1, -1}, {5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11, -1}, {0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7, -1}, {6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9, -1, -1, -1, -1}, {10, 4, 9, 6, 4, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 10, 6, 4, 9, 10, 0, 8, 3, -1, -1, -1, -1, -1, -1, -1}, {10, 0, 1, 10, 6, 0, 6, 4, 0, -1, -1, -1, -1, -1, -1, -1}, {8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10, -1, -1, -1, -1}, {1, 4, 9, 1, 2, 4, 2, 6, 4, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4, -1, -1, -1, -1}, {0, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 3, 2, 8, 2, 4, 4, 2, 6, -1, -1, -1, -1, -1, -1, -1}, {10, 4, 9, 10, 6, 4, 11, 2, 3, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6, -1, -1, -1, -1}, {3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10, -1, -1, -1, -1}, {6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1, -1}, {9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3, -1, -1, -1, -1}, {8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1, -1}, {3, 11, 6, 3, 6, 0, 0, 6, 4, -1, -1, -1, -1, -1, -1, -1}, {6, 4, 8, 11, 6, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 10, 6, 7, 8, 10, 8, 9, 10, -1, -1, -1, -1, -1, -1, -1}, {0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10, -1, -1, -1, -1}, {10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0, -1, -1, -1, -1}, {10, 6, 7, 10, 7, 1, 1, 7, 3, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7, -1, -1, -1, -1}, {2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9, -1}, {7, 8, 0, 7, 0, 6, 6, 0, 2, -1, -1, -1, -1, -1, -1, -1}, {7, 3, 2, 6, 7, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7, -1, -1, -1, -1}, {2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7, -1}, {1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11, -1}, {11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1, -1, -1, -1, -1}, {8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6, -1}, {0, 9, 1, 11, 6, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0, -1, -1, -1, -1}, {7, 11, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 8, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 9, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 1, 9, 8, 3, 1, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, {10, 1, 2, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 3, 0, 8, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, {2, 9, 0, 2, 10, 9, 6, 11, 7, -1, -1, -1, -1, -1, -1, -1}, {6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8, -1, -1, -1, -1}, {7, 2, 3, 6, 2, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {7, 0, 8, 7, 6, 0, 6, 2, 0, -1, -1, -1, -1, -1, -1, -1}, {2, 7, 6, 2, 3, 7, 0, 1, 9, -1, -1, -1, -1, -1, -1, -1}, {1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6, -1, -1, -1, -1}, {10, 7, 6, 10, 1, 7, 1, 3, 7, -1, -1, -1, -1, -1, -1, -1}, {10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8, -1, -1, -1, -1}, {0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7, -1, -1, -1, -1}, {7, 6, 10, 7, 10, 8, 8, 10, 9, -1, -1, -1, -1, -1, -1, -1}, {6, 8, 4, 11, 8, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 6, 11, 3, 0, 6, 0, 4, 6, -1, -1, -1, -1, -1, -1, -1}, {8, 6, 11, 8, 4, 6, 9, 0, 1, -1, -1, -1, -1, -1, -1, -1}, {9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6, -1, -1, -1, -1}, {6, 8, 4, 6, 11, 8, 2, 10, 1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6, -1, -1, -1, -1}, {4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9, -1, -1, -1, -1}, {10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3, -1}, {8, 2, 3, 8, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1}, {0, 4, 2, 4, 6, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8, -1, -1, -1, -1}, {1, 9, 4, 1, 4, 2, 2, 4, 6, -1, -1, -1, -1, -1, -1, -1}, {8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1, -1, -1, -1, -1}, {10, 1, 0, 10, 0, 6, 6, 0, 4, -1, -1, -1, -1, -1, -1, -1}, {4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3, -1}, {10, 9, 4, 6, 10, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 5, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 4, 9, 5, 11, 7, 6, -1, -1, -1, -1, -1, -1, -1}, {5, 0, 1, 5, 4, 0, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, {11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5, -1, -1, -1, -1}, {9, 5, 4, 10, 1, 2, 7, 6, 11, -1, -1, -1, -1, -1, -1, -1}, {6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5, -1, -1, -1, -1}, {7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2, -1, -1, -1, -1}, {3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6, -1}, {7, 2, 3, 7, 6, 2, 5, 4, 9, -1, -1, -1, -1, -1, -1, -1}, {9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7, -1, -1, -1, -1}, {3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0, -1, -1, -1, -1}, {6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8, -1}, {9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7, -1, -1, -1, -1}, {1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4, -1}, {4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10, -1}, {7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10, -1, -1, -1, -1}, {6, 9, 5, 6, 11, 9, 11, 8, 9, -1, -1, -1, -1, -1, -1, -1}, {3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5, -1, -1, -1, -1}, {0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11, -1, -1, -1, -1}, {6, 11, 3, 6, 3, 5, 5, 3, 1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6, -1, -1, -1, -1}, {0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10, -1}, {11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5, -1}, {6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3, -1, -1, -1, -1}, {5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2, -1, -1, -1, -1}, {9, 5, 6, 9, 6, 0, 0, 6, 2, -1, -1, -1, -1, -1, -1, -1}, {1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8, -1}, {1, 5, 6, 2, 1, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6, -1}, {10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0, -1, -1, -1, -1}, {0, 3, 8, 5, 6, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {10, 5, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 5, 10, 7, 5, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {11, 5, 10, 11, 7, 5, 8, 3, 0, -1, -1, -1, -1, -1, -1, -1}, {5, 11, 7, 5, 10, 11, 1, 9, 0, -1, -1, -1, -1, -1, -1, -1}, {10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1, -1, -1, -1, -1}, {11, 1, 2, 11, 7, 1, 7, 5, 1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11, -1, -1, -1, -1}, {9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7, -1, -1, -1, -1}, {7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2, -1}, {2, 5, 10, 2, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1}, {8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5, -1, -1, -1, -1}, {9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2, -1, -1, -1, -1}, {9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2, -1}, {1, 3, 5, 3, 7, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 7, 0, 7, 1, 1, 7, 5, -1, -1, -1, -1, -1, -1, -1}, {9, 0, 3, 9, 3, 5, 5, 3, 7, -1, -1, -1, -1, -1, -1, -1}, {9, 8, 7, 5, 9, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {5, 8, 4, 5, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1}, {5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0, -1, -1, -1, -1}, {0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5, -1, -1, -1, -1}, {10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4, -1}, {2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8, -1, -1, -1, -1}, {0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11, -1}, {0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5, -1}, {9, 4, 5, 2, 11, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4, -1, -1, -1, -1}, {5, 10, 2, 5, 2, 4, 4, 2, 0, -1, -1, -1, -1, -1, -1, -1}, {3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9, -1}, {5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2, -1, -1, -1, -1}, {8, 4, 5, 8, 5, 3, 3, 5, 1, -1, -1, -1, -1, -1, -1, -1}, {0, 4, 5, 1, 0, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5, -1, -1, -1, -1}, {9, 4, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 11, 7, 4, 9, 11, 9, 10, 11, -1, -1, -1, -1, -1, -1, -1}, {0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11, -1, -1, -1, -1}, {1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11, -1, -1, -1, -1}, {3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4, -1}, {4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2, -1, -1, -1, -1}, {9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3, -1}, {11, 7, 4, 11, 4, 2, 2, 4, 0, -1, -1, -1, -1, -1, -1, -1}, {11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4, -1, -1, -1, -1}, {2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9, -1, -1, -1, -1}, {9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7, -1}, {3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10, -1}, {1, 10, 2, 8, 7, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 1, 4, 1, 7, 7, 1, 3, -1, -1, -1, -1, -1, -1, -1}, {4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1, -1, -1, -1, -1}, {4, 0, 3, 7, 4, 3, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {4, 8, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {9, 10, 8, 10, 11, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 9, 3, 9, 11, 11, 9, 10, -1, -1, -1, -1, -1, -1, -1}, {0, 1, 10, 0, 10, 8, 8, 10, 11, -1, -1, -1, -1, -1, -1, -1}, {3, 1, 10, 11, 3, 10, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 2, 11, 1, 11, 9, 9, 11, 8, -1, -1, -1, -1, -1, -1, -1}, {3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9, -1, -1, -1, -1}, {0, 2, 11, 8, 0, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {3, 2, 11, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 3, 8, 2, 8, 10, 10, 8, 9, -1, -1, -1, -1, -1, -1, -1}, {9, 10, 2, 0, 9, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8, -1, -1, -1, -1}, {1, 10, 2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {1, 3, 8, 9, 1, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 9, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {0, 3, 8, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}}; static const point3d vertexList[12] = { point3d(1, 0, -1), point3d(0, -1, -1), point3d(-1, 0, -1), point3d(0, 1, -1), point3d(1, 0, 1), point3d(0, -1, 1), point3d(-1, 0, 1), point3d(0, 1, 1), point3d(1, 1, 0), point3d(1, -1, 0), point3d(-1, -1, 0), point3d(-1, 1, 0), }; } #endif
19,345
53.342697
78
h
octomap
octomap-master/octomap/include/octomap/MapCollection.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMAP_MAP_COLLECTION_H #define OCTOMAP_MAP_COLLECTION_H #include <vector> #include <octomap/MapNode.h> namespace octomap { template <class MAPNODE> class MapCollection { public: MapCollection(); MapCollection(std::string filename); ~MapCollection(); void addNode( MAPNODE* node); MAPNODE* addNode(const Pointcloud& cloud, point3d sensor_origin); bool removeNode(const MAPNODE* n); MAPNODE* queryNode(const point3d& p); bool isOccupied(const point3d& p) const; bool isOccupied(float x, float y, float z) const; double getOccupancy(const point3d& p); bool castRay(const point3d& origin, const point3d& direction, point3d& end, bool ignoreUnknownCells=false, double maxRange=-1.0) const; bool writePointcloud(std::string filename); bool write(std::string filename); // TODO void insertScan(const Pointcloud& scan, const octomap::point3d& sensor_origin, double maxrange=-1., bool pruning=true, bool lazy_eval = false); // TODO MAPNODE* queryNode(std::string id); typedef typename std::vector<MAPNODE*>::iterator iterator; typedef typename std::vector<MAPNODE*>::const_iterator const_iterator; iterator begin() { return nodes.begin(); } iterator end() { return nodes.end(); } const_iterator begin() const { return nodes.begin(); } const_iterator end() const { return nodes.end(); } size_t size() const { return nodes.size(); } protected: void clear(); bool read(std::string filename); // TODO std::vector<Pointcloud*> segment(const Pointcloud& scan) const; // TODO MAPNODE* associate(const Pointcloud& scan); static void splitPathAndFilename(std::string &filenamefullpath, std::string* path, std::string *filename); static std::string combinePathAndFilename(std::string path, std::string filename); static bool readTagValue(std::string tag, std::ifstream &infile, std::string* value); protected: std::vector<MAPNODE*> nodes; }; } // end namespace #include "octomap/MapCollection.hxx" #endif
3,897
36.480769
110
h
octomap
octomap-master/octomap/include/octomap/MapCollection.hxx
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <sstream> #include <fstream> namespace octomap { template <class MAPNODE> MapCollection<MAPNODE>::MapCollection() { } template <class MAPNODE> MapCollection<MAPNODE>::MapCollection(std::string filename) { this->read(filename); } template <class MAPNODE> MapCollection<MAPNODE>::~MapCollection() { this->clear(); } template <class MAPNODE> void MapCollection<MAPNODE>::clear() { // FIXME: memory leak, else we run into double frees in, e.g., the viewer... // for(typename std::vector<MAPNODE*>::iterator it= nodes.begin(); it != nodes.end(); ++it) // delete *it; nodes.clear(); } template <class MAPNODE> bool MapCollection<MAPNODE>::read(std::string filenamefullpath) { std::string path; std::string filename; splitPathAndFilename(filenamefullpath, &path, &filename); std::ifstream infile; infile.open(filenamefullpath.c_str(), std::ifstream::in); if(!infile.is_open()){ OCTOMAP_ERROR_STR("Could not open "<< filenamefullpath << ". MapCollection not loaded."); return false; } bool ok = true; while(ok){ std::string nodeID; ok = readTagValue("MAPNODEID", infile, &nodeID); if(!ok){ //do not throw error, you could be at the end of the file break; } std::string mapNodeFilename; ok = readTagValue("MAPNODEFILENAME", infile, &mapNodeFilename); if(!ok){ OCTOMAP_ERROR_STR("Could not read MAPNODEFILENAME."); break; } std::string poseStr; ok = readTagValue("MAPNODEPOSE", infile, &poseStr); std::istringstream poseStream(poseStr); float x,y,z; poseStream >> x >> y >> z; double roll,pitch,yaw; poseStream >> roll >> pitch >> yaw; ok = ok && !poseStream.fail(); if(!ok){ OCTOMAP_ERROR_STR("Could not read MAPNODEPOSE."); break; } octomap::pose6d origin(x, y, z, roll, pitch, yaw); MAPNODE* node = new MAPNODE(combinePathAndFilename(path,mapNodeFilename), origin); node->setId(nodeID); if(!ok){ for(unsigned int i=0; i<nodes.size(); i++){ delete nodes[i]; } infile.close(); return false; } else { nodes.push_back(node); } } infile.close(); return true; } template <class MAPNODE> void MapCollection<MAPNODE>::addNode( MAPNODE* node){ nodes.push_back(node); } template <class MAPNODE> MAPNODE* MapCollection<MAPNODE>::addNode(const Pointcloud& cloud, point3d sensor_origin) { // TODO... return 0; } template <class MAPNODE> bool MapCollection<MAPNODE>::removeNode(const MAPNODE* n) { // TODO... return false; } template <class MAPNODE> MAPNODE* MapCollection<MAPNODE>::queryNode(const point3d& p) { for (const_iterator it = this->begin(); it != this->end(); ++it) { point3d ptrans = (*it)->getOrigin().inv().transform(p); typename MAPNODE::TreeType::NodeType* n = (*it)->getMap()->search(ptrans); if (!n) continue; if ((*it)->getMap()->isNodeOccupied(n)) return (*it); } return 0; } template <class MAPNODE> bool MapCollection<MAPNODE>::isOccupied(const point3d& p) const { for (const_iterator it = this->begin(); it != this->end(); ++it) { point3d ptrans = (*it)->getOrigin().inv().transform(p); typename MAPNODE::TreeType::NodeType* n = (*it)->getMap()->search(ptrans); if (!n) continue; if ((*it)->getMap()->isNodeOccupied(n)) return true; } return false; } template <class MAPNODE> bool MapCollection<MAPNODE>::isOccupied(float x, float y, float z) const { point3d q(x,y,z); return this->isOccupied(q); } template <class MAPNODE> double MapCollection<MAPNODE>::getOccupancy(const point3d& p) { double max_occ_val = 0; bool is_unknown = true; for (const_iterator it = this->begin(); it != this->end(); ++it) { point3d ptrans = (*it)->getOrigin().inv().transform(p); typename MAPNODE::TreeType::NodeType* n = (*it)->getMap()->search(ptrans); if (n) { double occ = n->getOccupancy(); if (occ > max_occ_val) max_occ_val = occ; is_unknown = false; } } if (is_unknown) return 0.5; return max_occ_val; } template <class MAPNODE> bool MapCollection<MAPNODE>::castRay(const point3d& origin, const point3d& direction, point3d& end, bool ignoreUnknownCells, double maxRange) const { bool hit_obstacle = false; double min_dist = 1e6; // SPEEDUP: use openMP to do raycasting in parallel // SPEEDUP: use bounding boxes to determine submaps for (const_iterator it = this->begin(); it != this->end(); ++it) { point3d origin_trans = (*it)->getOrigin().inv().transform(origin); point3d direction_trans = (*it)->getOrigin().inv().rot().rotate(direction); printf("ray from %.2f,%.2f,%.2f in dir %.2f,%.2f,%.2f in node %s\n", origin_trans.x(), origin_trans.y(), origin_trans.z(), direction_trans.x(), direction_trans.y(), direction_trans.z(), (*it)->getId().c_str()); point3d temp_endpoint; if ((*it)->getMap()->castRay(origin_trans, direction_trans, temp_endpoint, ignoreUnknownCells, maxRange)) { printf("hit obstacle in node %s\n", (*it)->getId().c_str()); double current_dist = origin_trans.distance(temp_endpoint); if (current_dist < min_dist) { min_dist = current_dist; end = (*it)->getOrigin().transform(temp_endpoint); } hit_obstacle = true; } // end if hit obst } // end for return hit_obstacle; } template <class MAPNODE> bool MapCollection<MAPNODE>::writePointcloud(std::string filename) { Pointcloud pc; for(typename std::vector<MAPNODE* >::iterator it = nodes.begin(); it != nodes.end(); ++it){ Pointcloud tmp = (*it)->generatePointcloud(); pc.push_back(tmp); } pc.writeVrml(filename); return true; } template <class MAPNODE> bool MapCollection<MAPNODE>::write(std::string filename) { bool ok = true; std::ofstream outfile(filename.c_str()); outfile << "#This file was generated by the write-method of MapCollection\n"; for(typename std::vector<MAPNODE* >::iterator it = nodes.begin(); it != nodes.end(); ++it){ std::string id = (*it)->getId(); pose6d origin = (*it)->getOrigin(); std::string nodemapFilename = "nodemap_"; nodemapFilename.append(id); nodemapFilename.append(".bt"); outfile << "MAPNODEID " << id << "\n"; outfile << "MAPNODEFILENAME "<< nodemapFilename << "\n"; outfile << "MAPNODEPOSE " << origin.x() << " " << origin.y() << " " << origin.z() << " " << origin.roll() << " " << origin.pitch() << " " << origin.yaw() << std::endl; ok = ok && (*it)->writeMap(nodemapFilename); } outfile.close(); return ok; } // TODO template <class MAPNODE> void MapCollection<MAPNODE>::insertScan(const Pointcloud& scan, const octomap::point3d& sensor_origin, double maxrange, bool pruning, bool lazy_eval) { fprintf(stderr, "ERROR: MapCollection::insertScan is not implemented yet.\n"); } template <class MAPNODE> MAPNODE* MapCollection<MAPNODE>::queryNode(std::string id) { for (const_iterator it = this->begin(); it != this->end(); ++it) { if ((*it)->getId() == id) return *(it); } return 0; } // TODO template <class MAPNODE> std::vector<Pointcloud*> MapCollection<MAPNODE>::segment(const Pointcloud& scan) const { std::vector<Pointcloud*> result; fprintf(stderr, "ERROR: MapCollection::segment is not implemented yet.\n"); return result; } // TODO template <class MAPNODE> MAPNODE* MapCollection<MAPNODE>::associate(const Pointcloud& scan) { fprintf(stderr, "ERROR: MapCollection::associate is not implemented yet.\n"); return 0; } template <class MAPNODE> void MapCollection<MAPNODE>::splitPathAndFilename(std::string &filenamefullpath, std::string* path, std::string *filename) { #ifdef WIN32 std::string::size_type lastSlash = filenamefullpath.find_last_of('\\'); #else std::string::size_type lastSlash = filenamefullpath.find_last_of('/'); #endif if (lastSlash != std::string::npos){ *filename = filenamefullpath.substr(lastSlash + 1); *path = filenamefullpath.substr(0, lastSlash); } else { *filename = filenamefullpath; *path = ""; } } template <class MAPNODE> std::string MapCollection<MAPNODE>::combinePathAndFilename(std::string path, std::string filename) { std::string result = path; if(path != ""){ #ifdef WIN32 result.append("\\"); #else result.append("/"); #endif } result.append(filename); return result; } template <class MAPNODE> bool MapCollection<MAPNODE>::readTagValue(std::string /*tag*/, std::ifstream& infile, std::string* value) { std::string line; while( getline(infile, line) ){ if(line.length() != 0 && line[0] != '#') break; } *value = ""; std::string::size_type firstSpace = line.find(' '); if(firstSpace != std::string::npos && firstSpace != line.size()-1){ *value = line.substr(firstSpace + 1); return true; } else return false; } } // namespace
11,272
33.057402
113
hxx
octomap
octomap-master/octomap/include/octomap/MapNode.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMAP_MAP_NODE_H #define OCTOMAP_MAP_NODE_H #include <string> #include <octomap/OcTree.h> namespace octomap { template <class TREETYPE> class MapNode { public: MapNode(); MapNode(TREETYPE* node_map, pose6d origin); MapNode(std::string filename, pose6d origin); MapNode(const Pointcloud& cloud, pose6d origin); ~MapNode(); typedef TREETYPE TreeType; TREETYPE* getMap() { return node_map; } void updateMap(const Pointcloud& cloud, point3d sensor_origin); inline std::string getId() { return id; } inline void setId(std::string newid) { id = newid; } inline pose6d getOrigin() { return origin; } // returns cloud of voxel centers in global reference frame Pointcloud generatePointcloud(); bool writeMap(std::string filename); protected: TREETYPE* node_map; // occupancy grid map pose6d origin; // origin and orientation relative to parent std::string id; void clear(); bool readMap(std::string filename); }; } // end namespace #include "octomap/MapNode.hxx" #endif
2,880
33.710843
78
h
octomap
octomap-master/octomap/include/octomap/MapNode.hxx
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ namespace octomap { template <class TREETYPE> MapNode<TREETYPE>::MapNode(): node_map(0) { } template <class TREETYPE> MapNode<TREETYPE>::MapNode(TREETYPE* in_node_map, pose6d in_origin) { this->node_map = in_node_map; this->origin = in_origin; } template <class TREETYPE> MapNode<TREETYPE>::MapNode(const Pointcloud& in_cloud, pose6d in_origin): node_map(0) { } template <class TREETYPE> MapNode<TREETYPE>::MapNode(std::string filename, pose6d in_origin): node_map(0){ readMap(filename); this->origin = in_origin; id = filename; } template <class TREETYPE> MapNode<TREETYPE>::~MapNode() { clear(); } template <class TREETYPE> void MapNode<TREETYPE>::updateMap(const Pointcloud& cloud, point3d sensor_origin) { } template <class TREETYPE> Pointcloud MapNode<TREETYPE>::generatePointcloud() { Pointcloud pc; point3d_list occs; node_map->getOccupied(occs); for(point3d_list::iterator it = occs.begin(); it != occs.end(); ++it){ pc.push_back(*it); } return pc; } template <class TREETYPE> void MapNode<TREETYPE>::clear(){ if(node_map != 0){ delete node_map; node_map = 0; id = ""; origin = pose6d(0.0,0.0,0.0,0.0,0.0,0.0); } } template <class TREETYPE> bool MapNode<TREETYPE>::readMap(std::string filename){ if(node_map != 0) delete node_map; node_map = new TREETYPE(0.05); return node_map->readBinary(filename); } template <class TREETYPE> bool MapNode<TREETYPE>::writeMap(std::string filename){ return node_map->writeBinary(filename); } } // namespace
3,389
32.235294
89
hxx
octomap
octomap-master/octomap/include/octomap/OcTree.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMAP_OCTREE_H #define OCTOMAP_OCTREE_H #include "OccupancyOcTreeBase.h" #include "OcTreeNode.h" #include "ScanGraph.h" namespace octomap { /** * octomap main map data structure, stores 3D occupancy grid map in an OcTree. * Basic functionality is implemented in OcTreeBase. * */ class OcTree : public OccupancyOcTreeBase <OcTreeNode> { public: /// Default constructor, sets resolution of leafs OcTree(double resolution); /** * Reads an OcTree from a binary file * @param _filename * */ OcTree(std::string _filename); virtual ~OcTree(){}; /// virtual constructor: creates a new object of same type /// (Covariant return type requires an up-to-date compiler) OcTree* create() const {return new OcTree(resolution); } std::string getTreeType() const {return "OcTree";} protected: /** * Static member object which ensures that this OcTree's prototype * ends up in the classIDMapping only once. You need this as a * static member in any derived octree class in order to read .ot * files through the AbstractOcTree factory. You should also call * ensureLinking() once from the constructor. */ class StaticMemberInitializer{ public: StaticMemberInitializer() { OcTree* tree = new OcTree(0.1); tree->clearKeyRays(); AbstractOcTree::registerTreeType(tree); } /** * Dummy function to ensure that MSVC does not drop the * StaticMemberInitializer, causing this tree failing to register. * Needs to be called from the constructor of this octree. */ void ensureLinking() {}; }; /// to ensure static initialization (only once) static StaticMemberInitializer ocTreeMemberInit; }; } // end namespace #endif
3,597
34.27451
80
h
octomap
octomap-master/octomap/include/octomap/OcTreeBase.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMAP_OCTREE_BASE_H #define OCTOMAP_OCTREE_BASE_H #include "OcTreeBaseImpl.h" #include "AbstractOcTree.h" namespace octomap { template <class NODE> class OcTreeBase : public OcTreeBaseImpl<NODE,AbstractOcTree> { public: OcTreeBase<NODE>(double res) : OcTreeBaseImpl<NODE,AbstractOcTree>(res) {}; /// virtual constructor: creates a new object of same type /// (Covariant return type requires an up-to-date compiler) OcTreeBase<NODE>* create() const {return new OcTreeBase<NODE>(this->resolution); } std::string getTreeType() const {return "OcTreeBase";} }; } #endif
2,391
40.241379
86
h
octomap
octomap-master/octomap/include/octomap/OcTreeBaseImpl.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMAP_OCTREE_BASE_IMPL_H #define OCTOMAP_OCTREE_BASE_IMPL_H #include <list> #include <limits> #include <iterator> #include <stack> #include <bitset> #include "octomap_types.h" #include "OcTreeKey.h" #include "ScanGraph.h" namespace octomap { // forward declaration for NODE children array class AbstractOcTreeNode; /** * OcTree base class, to be used with with any kind of OcTreeDataNode. * * This tree implementation currently has a maximum depth of 16 * nodes. For this reason, coordinates values have to be, e.g., * below +/- 327.68 meters (2^15) at a maximum resolution of 0.01m. * * This limitation enables the use of an efficient key generation * method which uses the binary representation of the data point * coordinates. * * \note You should probably not use this class directly, but * OcTreeBase or OccupancyOcTreeBase instead * * \tparam NODE Node class to be used in tree (usually derived from * OcTreeDataNode) * \tparam INTERFACE Interface to be derived from, should be either * AbstractOcTree or AbstractOccupancyOcTree */ template <class NODE,class INTERFACE> class OcTreeBaseImpl : public INTERFACE { public: /// Make the templated NODE type available from the outside typedef NODE NodeType; // the actual iterator implementation is included here // as a member from this file #include <octomap/OcTreeIterator.hxx> OcTreeBaseImpl(double resolution); virtual ~OcTreeBaseImpl(); /// Deep copy constructor OcTreeBaseImpl(const OcTreeBaseImpl<NODE,INTERFACE>& rhs); /** * Swap contents of two octrees, i.e., only the underlying * pointer / tree structure. You have to ensure yourself that the * metadata (resolution etc) matches. No memory is cleared * in this function */ void swapContent(OcTreeBaseImpl<NODE,INTERFACE>& rhs); /// Comparison between two octrees, all meta data, all /// nodes, and the structure must be identical bool operator== (const OcTreeBaseImpl<NODE,INTERFACE>& rhs) const; std::string getTreeType() const {return "OcTreeBaseImpl";} /// Change the resolution of the octree, scaling all voxels. /// This will not preserve the (metric) scale! void setResolution(double r); inline double getResolution() const { return resolution; } inline unsigned int getTreeDepth () const { return tree_depth; } inline double getNodeSize(unsigned depth) const {assert(depth <= tree_depth); return sizeLookupTable[depth];} /** * Clear KeyRay vector to minimize unneeded memory. This is only * useful for the StaticMemberInitializer classes, don't call it for * an octree that is actually used. */ void clearKeyRays(){ keyrays.clear(); } // -- Tree structure operations formerly contained in the nodes --- /// Creates (allocates) the i-th child of the node. @return ptr to newly create NODE NODE* createNodeChild(NODE* node, unsigned int childIdx); /// Deletes the i-th child of the node void deleteNodeChild(NODE* node, unsigned int childIdx); /// @return ptr to child number childIdx of node NODE* getNodeChild(NODE* node, unsigned int childIdx) const; /// @return const ptr to child number childIdx of node const NODE* getNodeChild(const NODE* node, unsigned int childIdx) const; /// A node is collapsible if all children exist, don't have children of their own /// and have the same occupancy value virtual bool isNodeCollapsible(const NODE* node) const; /** * Safe test if node has a child at index childIdx. * First tests if there are any children. Replaces node->childExists(...) * \return true if the child at childIdx exists */ bool nodeChildExists(const NODE* node, unsigned int childIdx) const; /** * Safe test if node has any children. Replaces node->hasChildren(...) * \return true if node has at least one child */ bool nodeHasChildren(const NODE* node) const; /** * Expands a node (reverse of pruning): All children are created and * their occupancy probability is set to the node's value. * * You need to verify that this is indeed a pruned node (i.e. not a * leaf at the lowest level) * */ virtual void expandNode(NODE* node); /** * Prunes a node when it is collapsible * @return true if pruning was successful */ virtual bool pruneNode(NODE* node); // -------- /** * \return Pointer to the root node of the tree. This pointer * should not be modified or deleted externally, the OcTree * manages its memory itself. In an empty tree, root is NULL. */ inline NODE* getRoot() const { return root; } /** * Search node at specified depth given a 3d point (depth=0: search full tree depth). * You need to check if the returned node is NULL, since it can be in unknown space. * @return pointer to node if found, NULL otherwise */ NODE* search(double x, double y, double z, unsigned int depth = 0) const; /** * Search node at specified depth given a 3d point (depth=0: search full tree depth) * You need to check if the returned node is NULL, since it can be in unknown space. * @return pointer to node if found, NULL otherwise */ NODE* search(const point3d& value, unsigned int depth = 0) const; /** * Search a node at specified depth given an addressing key (depth=0: search full tree depth) * You need to check if the returned node is NULL, since it can be in unknown space. * @return pointer to node if found, NULL otherwise */ NODE* search(const OcTreeKey& key, unsigned int depth = 0) const; /** * Delete a node (if exists) given a 3d point. Will always * delete at the lowest level unless depth !=0, and expand pruned inner nodes as needed. * Pruned nodes at level "depth" will directly be deleted as a whole. */ bool deleteNode(double x, double y, double z, unsigned int depth = 0); /** * Delete a node (if exists) given a 3d point. Will always * delete at the lowest level unless depth !=0, and expand pruned inner nodes as needed. * Pruned nodes at level "depth" will directly be deleted as a whole. */ bool deleteNode(const point3d& value, unsigned int depth = 0); /** * Delete a node (if exists) given an addressing key. Will always * delete at the lowest level unless depth !=0, and expand pruned inner nodes as needed. * Pruned nodes at level "depth" will directly be deleted as a whole. */ bool deleteNode(const OcTreeKey& key, unsigned int depth = 0); /// Deletes the complete tree structure void clear(); /** * Lossless compression of the octree: A node will replace all of its eight * children if they have identical values. You usually don't have to call * prune() after a regular occupancy update, updateNode() incrementally * prunes all affected nodes. */ virtual void prune(); /// Expands all pruned nodes (reverse of prune()) /// \note This is an expensive operation, especially when the tree is nearly empty! virtual void expand(); // -- statistics ---------------------- /// \return The number of nodes in the tree virtual inline size_t size() const { return tree_size; } /// \return Memory usage of the complete octree in bytes (may vary between architectures) virtual size_t memoryUsage() const; /// \return Memory usage of a single octree node virtual inline size_t memoryUsageNode() const {return sizeof(NODE); }; /// \return Memory usage of a full grid of the same size as the OcTree in bytes (for comparison) /// \note this can be larger than the adressable memory - size_t may not be enough to hold it! unsigned long long memoryFullGrid() const; double volume(); /// Size of OcTree (all known space) in meters for x, y and z dimension virtual void getMetricSize(double& x, double& y, double& z); /// Size of OcTree (all known space) in meters for x, y and z dimension virtual void getMetricSize(double& x, double& y, double& z) const; /// minimum value of the bounding box of all known space in x, y, z virtual void getMetricMin(double& x, double& y, double& z); /// minimum value of the bounding box of all known space in x, y, z void getMetricMin(double& x, double& y, double& z) const; /// maximum value of the bounding box of all known space in x, y, z virtual void getMetricMax(double& x, double& y, double& z); /// maximum value of the bounding box of all known space in x, y, z void getMetricMax(double& x, double& y, double& z) const; /// Traverses the tree to calculate the total number of nodes size_t calcNumNodes() const; /// Traverses the tree to calculate the total number of leaf nodes size_t getNumLeafNodes() const; // -- access tree nodes ------------------ /// return centers of leafs that do NOT exist (but could) in a given bounding box void getUnknownLeafCenters(point3d_list& node_centers, point3d pmin, point3d pmax, unsigned int depth = 0) const; // -- raytracing ----------------------- /** * Traces a ray from origin to end (excluding), returning an * OcTreeKey of all nodes traversed by the beam. You still need to check * if a node at that coordinate exists (e.g. with search()). * * @param origin start coordinate of ray * @param end end coordinate of ray * @param ray KeyRay structure that holds the keys of all nodes traversed by the ray, excluding "end" * @return Success of operation. Returning false usually means that one of the coordinates is out of the OcTree's range */ bool computeRayKeys(const point3d& origin, const point3d& end, KeyRay& ray) const; /** * Traces a ray from origin to end (excluding), returning the * coordinates of all nodes traversed by the beam. You still need to check * if a node at that coordinate exists (e.g. with search()). * @note: use the faster computeRayKeys method if possible. * * @param origin start coordinate of ray * @param end end coordinate of ray * @param ray KeyRay structure that holds the keys of all nodes traversed by the ray, excluding "end" * @return Success of operation. Returning false usually means that one of the coordinates is out of the OcTree's range */ bool computeRay(const point3d& origin, const point3d& end, std::vector<point3d>& ray); // file IO /** * Read all nodes from the input stream (without file header), * for this the tree needs to be already created. * For general file IO, you * should probably use AbstractOcTree::read() instead. */ std::istream& readData(std::istream &s); /// Write complete state of tree to stream (without file header) unmodified. /// Pruning the tree first produces smaller files (lossless compression) std::ostream& writeData(std::ostream &s) const; typedef leaf_iterator iterator; /// @return beginning of the tree as leaf iterator iterator begin(unsigned char maxDepth=0) const {return iterator(this, maxDepth);}; /// @return end of the tree as leaf iterator const iterator end() const {return leaf_iterator_end;}; // TODO: RVE? /// @return beginning of the tree as leaf iterator leaf_iterator begin_leafs(unsigned char maxDepth=0) const {return leaf_iterator(this, maxDepth);}; /// @return end of the tree as leaf iterator const leaf_iterator end_leafs() const {return leaf_iterator_end;} /// @return beginning of the tree as leaf iterator in a bounding box leaf_bbx_iterator begin_leafs_bbx(const OcTreeKey& min, const OcTreeKey& max, unsigned char maxDepth=0) const { return leaf_bbx_iterator(this, min, max, maxDepth); } /// @return beginning of the tree as leaf iterator in a bounding box leaf_bbx_iterator begin_leafs_bbx(const point3d& min, const point3d& max, unsigned char maxDepth=0) const { return leaf_bbx_iterator(this, min, max, maxDepth); } /// @return end of the tree as leaf iterator in a bounding box const leaf_bbx_iterator end_leafs_bbx() const {return leaf_iterator_bbx_end;} /// @return beginning of the tree as iterator to all nodes (incl. inner) tree_iterator begin_tree(unsigned char maxDepth=0) const {return tree_iterator(this, maxDepth);} /// @return end of the tree as iterator to all nodes (incl. inner) const tree_iterator end_tree() const {return tree_iterator_end;} // // Key / coordinate conversion functions // /// Converts from a single coordinate into a discrete key inline key_type coordToKey(double coordinate) const{ return ((int) floor(resolution_factor * coordinate)) + tree_max_val; } /// Converts from a single coordinate into a discrete key at a given depth key_type coordToKey(double coordinate, unsigned depth) const; /// Converts from a 3D coordinate into a 3D addressing key inline OcTreeKey coordToKey(const point3d& coord) const{ return OcTreeKey(coordToKey(coord(0)), coordToKey(coord(1)), coordToKey(coord(2))); } /// Converts from a 3D coordinate into a 3D addressing key inline OcTreeKey coordToKey(double x, double y, double z) const{ return OcTreeKey(coordToKey(x), coordToKey(y), coordToKey(z)); } /// Converts from a 3D coordinate into a 3D addressing key at a given depth inline OcTreeKey coordToKey(const point3d& coord, unsigned depth) const{ if (depth == tree_depth) return coordToKey(coord); else return OcTreeKey(coordToKey(coord(0), depth), coordToKey(coord(1), depth), coordToKey(coord(2), depth)); } /// Converts from a 3D coordinate into a 3D addressing key at a given depth inline OcTreeKey coordToKey(double x, double y, double z, unsigned depth) const{ if (depth == tree_depth) return coordToKey(x,y,z); else return OcTreeKey(coordToKey(x, depth), coordToKey(y, depth), coordToKey(z, depth)); } /** * Adjusts a 3D key from the lowest level to correspond to a higher depth (by * shifting the key values) * * @param key Input key, at the lowest tree level * @param depth Target depth level for the new key * @return Key for the new depth level */ inline OcTreeKey adjustKeyAtDepth(const OcTreeKey& key, unsigned int depth) const{ if (depth == tree_depth) return key; assert(depth <= tree_depth); return OcTreeKey(adjustKeyAtDepth(key[0], depth), adjustKeyAtDepth(key[1], depth), adjustKeyAtDepth(key[2], depth)); } /** * Adjusts a single key value from the lowest level to correspond to a higher depth (by * shifting the key value) * * @param key Input key, at the lowest tree level * @param depth Target depth level for the new key * @return Key for the new depth level */ key_type adjustKeyAtDepth(key_type key, unsigned int depth) const; /** * Converts a 3D coordinate into a 3D OcTreeKey, with boundary checking. * * @param coord 3d coordinate of a point * @param key values that will be computed, an array of fixed size 3. * @return true if point is within the octree (valid), false otherwise */ bool coordToKeyChecked(const point3d& coord, OcTreeKey& key) const; /** * Converts a 3D coordinate into a 3D OcTreeKey at a certain depth, with boundary checking. * * @param coord 3d coordinate of a point * @param depth level of the key from the top * @param key values that will be computed, an array of fixed size 3. * @return true if point is within the octree (valid), false otherwise */ bool coordToKeyChecked(const point3d& coord, unsigned depth, OcTreeKey& key) const; /** * Converts a 3D coordinate into a 3D OcTreeKey, with boundary checking. * * @param x * @param y * @param z * @param key values that will be computed, an array of fixed size 3. * @return true if point is within the octree (valid), false otherwise */ bool coordToKeyChecked(double x, double y, double z, OcTreeKey& key) const; /** * Converts a 3D coordinate into a 3D OcTreeKey at a certain depth, with boundary checking. * * @param x * @param y * @param z * @param depth level of the key from the top * @param key values that will be computed, an array of fixed size 3. * @return true if point is within the octree (valid), false otherwise */ bool coordToKeyChecked(double x, double y, double z, unsigned depth, OcTreeKey& key) const; /** * Converts a single coordinate into a discrete addressing key, with boundary checking. * * @param coordinate 3d coordinate of a point * @param key discrete 16 bit adressing key, result * @return true if coordinate is within the octree bounds (valid), false otherwise */ bool coordToKeyChecked(double coordinate, key_type& key) const; /** * Converts a single coordinate into a discrete addressing key, with boundary checking. * * @param coordinate 3d coordinate of a point * @param depth level of the key from the top * @param key discrete 16 bit adressing key, result * @return true if coordinate is within the octree bounds (valid), false otherwise */ bool coordToKeyChecked(double coordinate, unsigned depth, key_type& key) const; /// converts from a discrete key at a given depth into a coordinate /// corresponding to the key's center double keyToCoord(key_type key, unsigned depth) const; /// converts from a discrete key at the lowest tree level into a coordinate /// corresponding to the key's center inline double keyToCoord(key_type key) const{ return (double( (int) key - (int) this->tree_max_val ) +0.5) * this->resolution; } /// converts from an addressing key at the lowest tree level into a coordinate /// corresponding to the key's center inline point3d keyToCoord(const OcTreeKey& key) const{ return point3d(float(keyToCoord(key[0])), float(keyToCoord(key[1])), float(keyToCoord(key[2]))); } /// converts from an addressing key at a given depth into a coordinate /// corresponding to the key's center inline point3d keyToCoord(const OcTreeKey& key, unsigned depth) const{ return point3d(float(keyToCoord(key[0], depth)), float(keyToCoord(key[1], depth)), float(keyToCoord(key[2], depth))); } protected: /// Constructor to enable derived classes to change tree constants. /// This usually requires a re-implementation of some core tree-traversal functions as well! OcTreeBaseImpl(double resolution, unsigned int tree_depth, unsigned int tree_max_val); /// initialize non-trivial members, helper for constructors void init(); /// recalculates min and max in x, y, z. Does nothing when tree size didn't change. void calcMinMax(); void calcNumNodesRecurs(NODE* node, size_t& num_nodes) const; /// recursive call of readData() std::istream& readNodesRecurs(NODE*, std::istream &s); /// recursive call of writeData() std::ostream& writeNodesRecurs(const NODE*, std::ostream &s) const; /// Recursively delete a node and all children. Deallocates memory /// but does NOT set the node ptr to NULL nor updates tree size. void deleteNodeRecurs(NODE* node); /// recursive call of deleteNode() bool deleteNodeRecurs(NODE* node, unsigned int depth, unsigned int max_depth, const OcTreeKey& key); /// recursive call of prune() void pruneRecurs(NODE* node, unsigned int depth, unsigned int max_depth, unsigned int& num_pruned); /// recursive call of expand() void expandRecurs(NODE* node, unsigned int depth, unsigned int max_depth); size_t getNumLeafNodesRecurs(const NODE* parent) const; private: /// Assignment operator is private: don't (re-)assign octrees /// (const-parameters can't be changed) - use the copy constructor instead. OcTreeBaseImpl<NODE,INTERFACE>& operator=(const OcTreeBaseImpl<NODE,INTERFACE>&); protected: void allocNodeChildren(NODE* node); NODE* root; ///< Pointer to the root NODE, NULL for empty tree // constants of the tree const unsigned int tree_depth; ///< Maximum tree depth is fixed to 16 currently const unsigned int tree_max_val; double resolution; ///< in meters double resolution_factor; ///< = 1. / resolution size_t tree_size; ///< number of nodes in tree /// flag to denote whether the octree extent changed (for lazy min/max eval) bool size_changed; point3d tree_center; // coordinate offset of tree double max_value[3]; ///< max in x, y, z double min_value[3]; ///< min in x, y, z /// contains the size of a voxel at level i (0: root node). tree_depth+1 levels (incl. 0) std::vector<double> sizeLookupTable; /// data structure for ray casting, array for multithreading std::vector<KeyRay> keyrays; const leaf_iterator leaf_iterator_end; const leaf_bbx_iterator leaf_iterator_bbx_end; const tree_iterator tree_iterator_end; }; } #include <octomap/OcTreeBaseImpl.hxx> #endif
23,307
39.465278
123
h
octomap
octomap-master/octomap/include/octomap/OcTreeBaseImpl.hxx
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #undef max #undef min #include <limits> #ifdef _OPENMP #include <omp.h> #endif namespace octomap { template <class NODE,class I> OcTreeBaseImpl<NODE,I>::OcTreeBaseImpl(double in_resolution) : I(), root(NULL), tree_depth(16), tree_max_val(32768), resolution(in_resolution), tree_size(0) { init(); // no longer create an empty root node - only on demand } template <class NODE,class I> OcTreeBaseImpl<NODE,I>::OcTreeBaseImpl(double in_resolution, unsigned int in_tree_depth, unsigned int in_tree_max_val) : I(), root(NULL), tree_depth(in_tree_depth), tree_max_val(in_tree_max_val), resolution(in_resolution), tree_size(0) { init(); // no longer create an empty root node - only on demand } template <class NODE,class I> OcTreeBaseImpl<NODE,I>::~OcTreeBaseImpl(){ clear(); } template <class NODE,class I> OcTreeBaseImpl<NODE,I>::OcTreeBaseImpl(const OcTreeBaseImpl<NODE,I>& rhs) : root(NULL), tree_depth(rhs.tree_depth), tree_max_val(rhs.tree_max_val), resolution(rhs.resolution), tree_size(rhs.tree_size) { init(); // copy nodes recursively: if (rhs.root) root = new NODE(*(rhs.root)); } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::init(){ this->setResolution(this->resolution); for (unsigned i = 0; i< 3; i++){ max_value[i] = -(std::numeric_limits<double>::max( )); min_value[i] = std::numeric_limits<double>::max( ); } size_changed = true; // create as many KeyRays as there are OMP_THREADS defined, // one buffer for each thread #ifdef _OPENMP #pragma omp parallel #pragma omp critical { if (omp_get_thread_num() == 0){ this->keyrays.resize(omp_get_num_threads()); } } #else this->keyrays.resize(1); #endif } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::swapContent(OcTreeBaseImpl<NODE,I>& other){ NODE* this_root = root; root = other.root; other.root = this_root; size_t this_size = this->tree_size; this->tree_size = other.tree_size; other.tree_size = this_size; } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::operator== (const OcTreeBaseImpl<NODE,I>& other) const{ if (tree_depth != other.tree_depth || tree_max_val != other.tree_max_val || resolution != other.resolution || tree_size != other.tree_size){ return false; } // traverse all nodes, check if structure the same typename OcTreeBaseImpl<NODE,I>::tree_iterator it = this->begin_tree(); typename OcTreeBaseImpl<NODE,I>::tree_iterator end = this->end_tree(); typename OcTreeBaseImpl<NODE,I>::tree_iterator other_it = other.begin_tree(); typename OcTreeBaseImpl<NODE,I>::tree_iterator other_end = other.end_tree(); for (; it != end; ++it, ++other_it){ if (other_it == other_end) return false; if (it.getDepth() != other_it.getDepth() || it.getKey() != other_it.getKey() || !(*it == *other_it)) { return false; } } if (other_it != other_end) return false; return true; } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::setResolution(double r) { resolution = r; resolution_factor = 1. / resolution; tree_center(0) = tree_center(1) = tree_center(2) = (float) (((double) tree_max_val) / resolution_factor); // init node size lookup table: sizeLookupTable.resize(tree_depth+1); for(unsigned i = 0; i <= tree_depth; ++i){ sizeLookupTable[i] = resolution * double(1 << (tree_depth - i)); } size_changed = true; } template <class NODE,class I> NODE* OcTreeBaseImpl<NODE,I>::createNodeChild(NODE* node, unsigned int childIdx){ assert(childIdx < 8); if (node->children == NULL) { allocNodeChildren(node); } assert (node->children[childIdx] == NULL); NODE* newNode = new NODE(); node->children[childIdx] = static_cast<AbstractOcTreeNode*>(newNode); tree_size++; size_changed = true; return newNode; } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::deleteNodeChild(NODE* node, unsigned int childIdx){ assert((childIdx < 8) && (node->children != NULL)); assert(node->children[childIdx] != NULL); delete static_cast<NODE*>(node->children[childIdx]); // TODO delete check if empty node->children[childIdx] = NULL; tree_size--; size_changed = true; } template <class NODE,class I> NODE* OcTreeBaseImpl<NODE,I>::getNodeChild(NODE* node, unsigned int childIdx) const{ assert((childIdx < 8) && (node->children != NULL)); assert(node->children[childIdx] != NULL); return static_cast<NODE*>(node->children[childIdx]); } template <class NODE,class I> const NODE* OcTreeBaseImpl<NODE,I>::getNodeChild(const NODE* node, unsigned int childIdx) const{ assert((childIdx < 8) && (node->children != NULL)); assert(node->children[childIdx] != NULL); return static_cast<const NODE*>(node->children[childIdx]); } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::isNodeCollapsible(const NODE* node) const{ // all children must exist, must not have children of // their own and have the same occupancy probability if (!nodeChildExists(node, 0)) return false; const NODE* firstChild = getNodeChild(node, 0); if (nodeHasChildren(firstChild)) return false; for (unsigned int i = 1; i<8; i++) { // comparison via getChild so that casts of derived classes ensure // that the right == operator gets called if (!nodeChildExists(node, i) || nodeHasChildren(getNodeChild(node, i)) || !(*(getNodeChild(node, i)) == *(firstChild))) return false; } return true; } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::nodeChildExists(const NODE* node, unsigned int childIdx) const{ assert(childIdx < 8); if ((node->children != NULL) && (node->children[childIdx] != NULL)) return true; else return false; } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::nodeHasChildren(const NODE* node) const { if (node->children == NULL) return false; for (unsigned int i = 0; i<8; i++){ if (node->children[i] != NULL) return true; } return false; } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::expandNode(NODE* node){ assert(!nodeHasChildren(node)); for (unsigned int k=0; k<8; k++) { NODE* newNode = createNodeChild(node, k); newNode->copyData(*node); } } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::pruneNode(NODE* node){ if (!isNodeCollapsible(node)) return false; // set value to children's values (all assumed equal) node->copyData(*(getNodeChild(node, 0))); // delete children (known to be leafs at this point!) for (unsigned int i=0;i<8;i++) { deleteNodeChild(node, i); } delete[] node->children; node->children = NULL; return true; } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::allocNodeChildren(NODE* node){ // TODO NODE* node->children = new AbstractOcTreeNode*[8]; for (unsigned int i=0; i<8; i++) { node->children[i] = NULL; } } template <class NODE,class I> inline key_type OcTreeBaseImpl<NODE,I>::coordToKey(double coordinate, unsigned depth) const{ assert (depth <= tree_depth); int keyval = ((int) floor(resolution_factor * coordinate)); unsigned int diff = tree_depth - depth; if(!diff) // same as coordToKey without depth return keyval + tree_max_val; else // shift right and left => erase last bits. Then add offset. return ((keyval >> diff) << diff) + (1 << (diff-1)) + tree_max_val; } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::coordToKeyChecked(double coordinate, key_type& keyval) const { // scale to resolution and shift center for tree_max_val int scaled_coord = ((int) floor(resolution_factor * coordinate)) + tree_max_val; // keyval within range of tree? if (( scaled_coord >= 0) && (((unsigned int) scaled_coord) < (2*tree_max_val))) { keyval = scaled_coord; return true; } return false; } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::coordToKeyChecked(double coordinate, unsigned depth, key_type& keyval) const { // scale to resolution and shift center for tree_max_val int scaled_coord = ((int) floor(resolution_factor * coordinate)) + tree_max_val; // keyval within range of tree? if (( scaled_coord >= 0) && (((unsigned int) scaled_coord) < (2*tree_max_val))) { keyval = scaled_coord; keyval = adjustKeyAtDepth(keyval, depth); return true; } return false; } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::coordToKeyChecked(const point3d& point, OcTreeKey& key) const{ for (unsigned int i=0;i<3;i++) { if (!coordToKeyChecked( point(i), key[i])) return false; } return true; } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::coordToKeyChecked(const point3d& point, unsigned depth, OcTreeKey& key) const{ for (unsigned int i=0;i<3;i++) { if (!coordToKeyChecked( point(i), depth, key[i])) return false; } return true; } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::coordToKeyChecked(double x, double y, double z, OcTreeKey& key) const{ if (!(coordToKeyChecked(x, key[0]) && coordToKeyChecked(y, key[1]) && coordToKeyChecked(z, key[2]))) { return false; } else { return true; } } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::coordToKeyChecked(double x, double y, double z, unsigned depth, OcTreeKey& key) const{ if (!(coordToKeyChecked(x, depth, key[0]) && coordToKeyChecked(y, depth, key[1]) && coordToKeyChecked(z, depth, key[2]))) { return false; } else { return true; } } template <class NODE,class I> key_type OcTreeBaseImpl<NODE,I>::adjustKeyAtDepth(key_type key, unsigned int depth) const{ unsigned int diff = tree_depth - depth; if(diff == 0) return key; else return (((key-tree_max_val) >> diff) << diff) + (1 << (diff-1)) + tree_max_val; } template <class NODE,class I> double OcTreeBaseImpl<NODE,I>::keyToCoord(key_type key, unsigned depth) const{ assert(depth <= tree_depth); // root is centered on 0 = 0.0 if (depth == 0) { return 0.0; } else if (depth == tree_depth) { return keyToCoord(key); } else { return (floor( (double(key)-double(this->tree_max_val)) /double(1 << (tree_depth - depth)) ) + 0.5 ) * this->getNodeSize(depth); } } template <class NODE,class I> NODE* OcTreeBaseImpl<NODE,I>::search(const point3d& value, unsigned int depth) const { OcTreeKey key; if (!coordToKeyChecked(value, key)){ OCTOMAP_ERROR_STR("Error in search: ["<< value <<"] is out of OcTree bounds!"); return NULL; } else { return this->search(key, depth); } } template <class NODE,class I> NODE* OcTreeBaseImpl<NODE,I>::search(double x, double y, double z, unsigned int depth) const { OcTreeKey key; if (!coordToKeyChecked(x, y, z, key)){ OCTOMAP_ERROR_STR("Error in search: ["<< x <<" "<< y << " " << z << "] is out of OcTree bounds!"); return NULL; } else { return this->search(key, depth); } } template <class NODE,class I> NODE* OcTreeBaseImpl<NODE,I>::search (const OcTreeKey& key, unsigned int depth) const { assert(depth <= tree_depth); if (root == NULL) return NULL; if (depth == 0) depth = tree_depth; // generate appropriate key_at_depth for queried depth OcTreeKey key_at_depth = key; if (depth != tree_depth) key_at_depth = adjustKeyAtDepth(key, depth); NODE* curNode (root); int diff = tree_depth - depth; // follow nodes down to requested level (for diff = 0 it's the last level) for (int i=(tree_depth-1); i>=diff; --i) { unsigned int pos = computeChildIdx(key_at_depth, i); if (nodeChildExists(curNode, pos)) { // cast needed: (nodes need to ensure it's the right pointer) curNode = getNodeChild(curNode, pos); } else { // we expected a child but did not get it // is the current node a leaf already? if (!nodeHasChildren(curNode)) { // TODO similar check to nodeChildExists? return curNode; } else { // it is not, search failed return NULL; } } } // end for return curNode; } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::deleteNode(const point3d& value, unsigned int depth) { OcTreeKey key; if (!coordToKeyChecked(value, key)){ OCTOMAP_ERROR_STR("Error in deleteNode: ["<< value <<"] is out of OcTree bounds!"); return false; } else { return this->deleteNode(key, depth); } } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::deleteNode(double x, double y, double z, unsigned int depth) { OcTreeKey key; if (!coordToKeyChecked(x, y, z, key)){ OCTOMAP_ERROR_STR("Error in deleteNode: ["<< x <<" "<< y << " " << z << "] is out of OcTree bounds!"); return false; } else { return this->deleteNode(key, depth); } } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::deleteNode(const OcTreeKey& key, unsigned int depth) { if (root == NULL) return true; if (depth == 0) depth = tree_depth; return deleteNodeRecurs(root, 0, depth, key); } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::clear() { if (this->root){ deleteNodeRecurs(root); this->tree_size = 0; this->root = NULL; // max extent of tree changed: this->size_changed = true; } } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::prune() { if (root == NULL) return; for (unsigned int depth=tree_depth-1; depth > 0; --depth) { unsigned int num_pruned = 0; pruneRecurs(this->root, 0, depth, num_pruned); if (num_pruned == 0) break; } } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::expand() { if (root) expandRecurs(root,0, tree_depth); } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::computeRayKeys(const point3d& origin, const point3d& end, KeyRay& ray) const { // see "A Faster Voxel Traversal Algorithm for Ray Tracing" by Amanatides & Woo // basically: DDA in 3D ray.reset(); OcTreeKey key_origin, key_end; if ( !OcTreeBaseImpl<NODE,I>::coordToKeyChecked(origin, key_origin) || !OcTreeBaseImpl<NODE,I>::coordToKeyChecked(end, key_end) ) { OCTOMAP_WARNING_STR("coordinates ( " << origin << " -> " << end << ") out of bounds in computeRayKeys"); return false; } if (key_origin == key_end) return true; // same tree cell, we're done. ray.addKey(key_origin); // Initialization phase ------------------------------------------------------- point3d direction = (end - origin); float length = (float) direction.norm(); direction /= length; // normalize vector int step[3]; double tMax[3]; double tDelta[3]; OcTreeKey current_key = key_origin; for(unsigned int i=0; i < 3; ++i) { // compute step direction if (direction(i) > 0.0) step[i] = 1; else if (direction(i) < 0.0) step[i] = -1; else step[i] = 0; // compute tMax, tDelta if (step[i] != 0) { // corner point of voxel (in direction of ray) double voxelBorder = this->keyToCoord(current_key[i]); voxelBorder += (float) (step[i] * this->resolution * 0.5); tMax[i] = ( voxelBorder - origin(i) ) / direction(i); tDelta[i] = this->resolution / fabs( direction(i) ); } else { tMax[i] = std::numeric_limits<double>::max( ); tDelta[i] = std::numeric_limits<double>::max( ); } } // Incremental phase --------------------------------------------------------- bool done = false; while (!done) { unsigned int dim; // find minimum tMax: if (tMax[0] < tMax[1]){ if (tMax[0] < tMax[2]) dim = 0; else dim = 2; } else { if (tMax[1] < tMax[2]) dim = 1; else dim = 2; } // advance in direction "dim" current_key[dim] += step[dim]; tMax[dim] += tDelta[dim]; assert (current_key[dim] < 2*this->tree_max_val); // reached endpoint, key equv? if (current_key == key_end) { done = true; break; } else { // reached endpoint world coords? // dist_from_origin now contains the length of the ray when traveled until the border of the current voxel double dist_from_origin = std::min(std::min(tMax[0], tMax[1]), tMax[2]); // if this is longer than the expected ray length, we should have already hit the voxel containing the end point with the code above (key_end). // However, we did not hit it due to accumulating discretization errors, so this is the point here to stop the ray as we would never reach the voxel key_end if (dist_from_origin > length) { done = true; break; } else { // continue to add freespace cells ray.addKey(current_key); } } assert ( ray.size() < ray.sizeMax() - 1); } // end while return true; } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::computeRay(const point3d& origin, const point3d& end, std::vector<point3d>& _ray) { _ray.clear(); if (!computeRayKeys(origin, end, keyrays.at(0))) return false; for (KeyRay::const_iterator it = keyrays[0].begin(); it != keyrays[0].end(); ++it) { _ray.push_back(keyToCoord(*it)); } return true; } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::deleteNodeRecurs(NODE* node){ assert(node); // TODO: maintain tree size? if (node->children != NULL) { for (unsigned int i=0; i<8; i++) { if (node->children[i] != NULL){ this->deleteNodeRecurs(static_cast<NODE*>(node->children[i])); } } delete[] node->children; node->children = NULL; } // else: node has no children delete node; } template <class NODE,class I> bool OcTreeBaseImpl<NODE,I>::deleteNodeRecurs(NODE* node, unsigned int depth, unsigned int max_depth, const OcTreeKey& key){ if (depth >= max_depth) // on last level: delete child when going up return true; assert(node); unsigned int pos = computeChildIdx(key, this->tree_depth-1-depth); if (!nodeChildExists(node, pos)) { // child does not exist, but maybe it's a pruned node? if ((!nodeHasChildren(node)) && (node != this->root)) { // TODO double check for exists / root exception? // current node does not have children AND it's not the root node // -> expand pruned node expandNode(node); // tree_size and size_changed adjusted in createNodeChild(...) } else { // no branch here, node does not exist return false; } } // follow down further, fix inner nodes on way back up bool deleteChild = deleteNodeRecurs(getNodeChild(node, pos), depth+1, max_depth, key); if (deleteChild){ // TODO: lazy eval? // TODO delete check depth, what happens to inner nodes with children? this->deleteNodeChild(node, pos); if (!nodeHasChildren(node)) return true; else{ node->updateOccupancyChildren(); // TODO: occupancy? } } // node did not lose a child, or still has other children return false; } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::pruneRecurs(NODE* node, unsigned int depth, unsigned int max_depth, unsigned int& num_pruned) { assert(node); if (depth < max_depth) { for (unsigned int i=0; i<8; i++) { if (nodeChildExists(node, i)) { pruneRecurs(getNodeChild(node, i), depth+1, max_depth, num_pruned); } } } // end if depth else { // max level reached if (pruneNode(node)) { num_pruned++; } } } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::expandRecurs(NODE* node, unsigned int depth, unsigned int max_depth) { if (depth >= max_depth) return; assert(node); // current node has no children => can be expanded if (!nodeHasChildren(node)){ expandNode(node); } // recursively expand children for (unsigned int i=0; i<8; i++) { if (nodeChildExists(node, i)) { // TODO double check (node != NULL) expandRecurs(getNodeChild(node, i), depth+1, max_depth); } } } template <class NODE,class I> std::ostream& OcTreeBaseImpl<NODE,I>::writeData(std::ostream &s) const{ if (root) writeNodesRecurs(root, s); return s; } template <class NODE,class I> std::ostream& OcTreeBaseImpl<NODE,I>::writeNodesRecurs(const NODE* node, std::ostream &s) const{ node->writeData(s); // 1 bit for each children; 0: empty, 1: allocated std::bitset<8> children; for (unsigned int i=0; i<8; i++) { if (nodeChildExists(node, i)) children[i] = 1; else children[i] = 0; } char children_char = (char) children.to_ulong(); s.write((char*)&children_char, sizeof(char)); // std::cout << "wrote: " << value << " " // << children.to_string<char,std::char_traits<char>,std::allocator<char> >() // << std::endl; // recursively write children for (unsigned int i=0; i<8; i++) { if (children[i] == 1) { this->writeNodesRecurs(getNodeChild(node, i), s); } } return s; } template <class NODE,class I> std::istream& OcTreeBaseImpl<NODE,I>::readData(std::istream &s) { if (!s.good()){ OCTOMAP_WARNING_STR(__FILE__ << ":" << __LINE__ << "Warning: Input filestream not \"good\""); } this->tree_size = 0; size_changed = true; // tree needs to be newly created or cleared externally if (root) { OCTOMAP_ERROR_STR("Trying to read into an existing tree."); return s; } root = new NODE(); readNodesRecurs(root, s); tree_size = calcNumNodes(); // compute number of nodes return s; } template <class NODE,class I> std::istream& OcTreeBaseImpl<NODE,I>::readNodesRecurs(NODE* node, std::istream &s) { node->readData(s); char children_char; s.read((char*)&children_char, sizeof(char)); std::bitset<8> children ((unsigned long long) children_char); //std::cout << "read: " << node->getValue() << " " // << children.to_string<char,std::char_traits<char>,std::allocator<char> >() // << std::endl; for (unsigned int i=0; i<8; i++) { if (children[i] == 1){ NODE* newNode = createNodeChild(node, i); readNodesRecurs(newNode, s); } } return s; } template <class NODE,class I> unsigned long long OcTreeBaseImpl<NODE,I>::memoryFullGrid() const{ if (root == NULL) return 0; double size_x, size_y, size_z; this->getMetricSize(size_x, size_y,size_z); // assuming best case (one big array and efficient addressing) // we can avoid "ceil" since size already accounts for voxels // Note: this can be larger than the adressable memory // - size_t may not be enough to hold it! return (unsigned long long)((size_x/resolution) * (size_y/resolution) * (size_z/resolution) * sizeof(root->getValue())); } // non-const versions, // change min/max/size_changed members template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::getMetricSize(double& x, double& y, double& z){ double minX, minY, minZ; double maxX, maxY, maxZ; getMetricMax(maxX, maxY, maxZ); getMetricMin(minX, minY, minZ); x = maxX - minX; y = maxY - minY; z = maxZ - minZ; } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::getMetricSize(double& x, double& y, double& z) const{ double minX, minY, minZ; double maxX, maxY, maxZ; getMetricMax(maxX, maxY, maxZ); getMetricMin(minX, minY, minZ); x = maxX - minX; y = maxY - minY; z = maxZ - minZ; } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::calcMinMax() { if (!size_changed) return; // empty tree if (root == NULL){ min_value[0] = min_value[1] = min_value[2] = 0.0; max_value[0] = max_value[1] = max_value[2] = 0.0; size_changed = false; return; } for (unsigned i = 0; i< 3; i++){ max_value[i] = -std::numeric_limits<double>::max(); min_value[i] = std::numeric_limits<double>::max(); } for(typename OcTreeBaseImpl<NODE,I>::leaf_iterator it = this->begin(), end=this->end(); it!= end; ++it) { double size = it.getSize(); double halfSize = size/2.0; double x = it.getX() - halfSize; double y = it.getY() - halfSize; double z = it.getZ() - halfSize; if (x < min_value[0]) min_value[0] = x; if (y < min_value[1]) min_value[1] = y; if (z < min_value[2]) min_value[2] = z; x += size; y += size; z += size; if (x > max_value[0]) max_value[0] = x; if (y > max_value[1]) max_value[1] = y; if (z > max_value[2]) max_value[2] = z; } size_changed = false; } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::getMetricMin(double& x, double& y, double& z){ calcMinMax(); x = min_value[0]; y = min_value[1]; z = min_value[2]; } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::getMetricMax(double& x, double& y, double& z){ calcMinMax(); x = max_value[0]; y = max_value[1]; z = max_value[2]; } // const versions template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::getMetricMin(double& mx, double& my, double& mz) const { mx = my = mz = std::numeric_limits<double>::max( ); if (size_changed) { // empty tree if (root == NULL){ mx = my = mz = 0.0; return; } for(typename OcTreeBaseImpl<NODE,I>::leaf_iterator it = this->begin(), end=this->end(); it!= end; ++it) { double halfSize = it.getSize()/2.0; double x = it.getX() - halfSize; double y = it.getY() - halfSize; double z = it.getZ() - halfSize; if (x < mx) mx = x; if (y < my) my = y; if (z < mz) mz = z; } } // end if size changed else { mx = min_value[0]; my = min_value[1]; mz = min_value[2]; } } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::getMetricMax(double& mx, double& my, double& mz) const { mx = my = mz = -std::numeric_limits<double>::max( ); if (size_changed) { // empty tree if (root == NULL){ mx = my = mz = 0.0; return; } for(typename OcTreeBaseImpl<NODE,I>::leaf_iterator it = this->begin(), end=this->end(); it!= end; ++it) { double halfSize = it.getSize()/2.0; double x = it.getX() + halfSize; double y = it.getY() + halfSize; double z = it.getZ() + halfSize; if (x > mx) mx = x; if (y > my) my = y; if (z > mz) mz = z; } } else { mx = max_value[0]; my = max_value[1]; mz = max_value[2]; } } template <class NODE,class I> size_t OcTreeBaseImpl<NODE,I>::calcNumNodes() const { size_t retval = 0; // root node if (root){ retval++; calcNumNodesRecurs(root, retval); } return retval; } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::calcNumNodesRecurs(NODE* node, size_t& num_nodes) const { assert (node); if (nodeHasChildren(node)) { for (unsigned int i=0; i<8; ++i) { if (nodeChildExists(node, i)) { num_nodes++; calcNumNodesRecurs(getNodeChild(node, i), num_nodes); } } } } template <class NODE,class I> size_t OcTreeBaseImpl<NODE,I>::memoryUsage() const{ size_t num_leaf_nodes = this->getNumLeafNodes(); size_t num_inner_nodes = tree_size - num_leaf_nodes; return (sizeof(OcTreeBaseImpl<NODE,I>) + memoryUsageNode() * tree_size + num_inner_nodes * sizeof(NODE*[8])); } template <class NODE,class I> void OcTreeBaseImpl<NODE,I>::getUnknownLeafCenters(point3d_list& node_centers, point3d pmin, point3d pmax, unsigned int depth) const { assert(depth <= tree_depth); if (depth == 0) depth = tree_depth; point3d pmin_clamped = this->keyToCoord(this->coordToKey(pmin, depth), depth); point3d pmax_clamped = this->keyToCoord(this->coordToKey(pmax, depth), depth); float diff[3]; unsigned int steps[3]; float step_size = this->resolution * pow(2, tree_depth-depth); for (int i=0;i<3;++i) { diff[i] = pmax_clamped(i) - pmin_clamped(i); steps[i] = static_cast<unsigned int>(floor(diff[i] / step_size)); // std::cout << "bbx " << i << " size: " << diff[i] << " " << steps[i] << " steps\n"; } point3d p = pmin_clamped; NODE* res; for (unsigned int x=0; x<steps[0]; ++x) { p.x() += step_size; for (unsigned int y=0; y<steps[1]; ++y) { p.y() += step_size; for (unsigned int z=0; z<steps[2]; ++z) { // std::cout << "querying p=" << p << std::endl; p.z() += step_size; res = this->search(p,depth); if (res == NULL) { node_centers.push_back(p); } } p.z() = pmin_clamped.z(); } p.y() = pmin_clamped.y(); } } template <class NODE,class I> size_t OcTreeBaseImpl<NODE,I>::getNumLeafNodes() const { if (root == NULL) return 0; return getNumLeafNodesRecurs(root); } template <class NODE,class I> size_t OcTreeBaseImpl<NODE,I>::getNumLeafNodesRecurs(const NODE* parent) const { assert(parent); if (!nodeHasChildren(parent)) // this is a leaf -> terminate return 1; size_t sum_leafs_children = 0; for (unsigned int i=0; i<8; ++i) { if (nodeChildExists(parent, i)) { sum_leafs_children += getNumLeafNodesRecurs(getNodeChild(parent, i)); } } return sum_leafs_children; } template <class NODE,class I> double OcTreeBaseImpl<NODE,I>::volume() { double x, y, z; getMetricSize(x, y, z); return x*y*z; } }
32,739
28.232143
164
hxx
octomap
octomap-master/octomap/include/octomap/OcTreeDataNode.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMAP_OCTREE_DATA_NODE_H #define OCTOMAP_OCTREE_DATA_NODE_H #include "octomap_types.h" #include "assert.h" namespace octomap { class AbstractOcTreeNode { }; // forward declaration for friend in OcTreeDataNode template<typename NODE,typename I> class OcTreeBaseImpl; /** * Basic node in the OcTree that can hold arbitrary data of type T in value. * This is the base class for nodes used in an OcTree. The used implementation * for occupancy mapping is in OcTreeNode.# * \tparam T data to be stored in the node (e.g. a float for probabilities) * * Note: If you derive a class (directly or indirectly) from OcTreeDataNode, * you have to implement (at least) the following functions to avoid slicing * errors and memory-related bugs: * createChild(), getChild(), getChild() const, expandNode() * See ColorOcTreeNode in ColorOcTree.h for an example. */ template<typename T> class OcTreeDataNode: public AbstractOcTreeNode { template<typename NODE, typename I> friend class OcTreeBaseImpl; public: OcTreeDataNode(); OcTreeDataNode(T initVal); /// Copy constructor, performs a recursive deep-copy of all children /// including node data in "value" OcTreeDataNode(const OcTreeDataNode& rhs); /// Delete only own members. /// OcTree maintains tree structure and must have deleted children already ~OcTreeDataNode(); /// Copy the payload (data in "value") from rhs into this node /// Opposed to copy ctor, this does not clone the children as well void copyData(const OcTreeDataNode& from); /// Equals operator, compares if the stored value is identical bool operator==(const OcTreeDataNode& rhs) const; // -- children ---------------------------------- /// Test whether the i-th child exists. /// @deprecated Replaced by tree->nodeChildExists(...) /// \return true if the i-th child exists OCTOMAP_DEPRECATED(bool childExists(unsigned int i) const); /// @deprecated Replaced by tree->nodeHasChildren(...) /// \return true if the node has at least one child OCTOMAP_DEPRECATED(bool hasChildren() const); /// @return value stored in the node T getValue() const{return value;}; /// sets value to be stored in the node void setValue(T v) {value = v;}; // file IO: /// Read node payload (data only) from binary stream std::istream& readData(std::istream &s); /// Write node payload (data only) to binary stream std::ostream& writeData(std::ostream &s) const; /// Make the templated data type available from the outside typedef T DataType; protected: void allocChildren(); /// pointer to array of children, may be NULL /// @note The tree class manages this pointer, the array, and the memory for it! /// The children of a node are always enforced to be the same type as the node AbstractOcTreeNode** children; /// stored data (payload) T value; }; } // end namespace #include "octomap/OcTreeDataNode.hxx" #endif
4,866
34.268116
84
h
octomap
octomap-master/octomap/include/octomap/OcTreeDataNode.hxx
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ namespace octomap { template <typename T> OcTreeDataNode<T>::OcTreeDataNode() : children(NULL) { } template <typename T> OcTreeDataNode<T>::OcTreeDataNode(T initVal) : children(NULL), value(initVal) { } template <typename T> OcTreeDataNode<T>::OcTreeDataNode(const OcTreeDataNode<T>& rhs) : children(NULL), value(rhs.value) { if (rhs.children != NULL){ allocChildren(); for (unsigned i = 0; i<8; ++i){ if (rhs.children[i] != NULL) children[i] = new OcTreeDataNode<T>(*(static_cast<OcTreeDataNode<T>*>(rhs.children[i]))); } } } template <typename T> OcTreeDataNode<T>::~OcTreeDataNode() { // Delete only own members. OcTree maintains tree structure and must have deleted // children already assert(children == NULL); } template <typename T> void OcTreeDataNode<T>::copyData(const OcTreeDataNode<T>& from){ value = from.value; } template <typename T> bool OcTreeDataNode<T>::operator== (const OcTreeDataNode<T>& rhs) const{ return rhs.value == value; } // ============================================================ // = children ======================================= // ============================================================ template <typename T> bool OcTreeDataNode<T>::childExists(unsigned int i) const { assert(i < 8); if ((children != NULL) && (children[i] != NULL)) return true; else return false; } template <typename T> bool OcTreeDataNode<T>::hasChildren() const { if (children == NULL) return false; for (unsigned int i = 0; i<8; i++){ // fast check, we know children != NULL if (children[i] != NULL) return true; } return false; } // ============================================================ // = File IO ======================================= // ============================================================ template <typename T> std::istream& OcTreeDataNode<T>::readData(std::istream &s) { s.read((char*) &value, sizeof(value)); return s; } template <typename T> std::ostream& OcTreeDataNode<T>::writeData(std::ostream &s) const{ s.write((const char*) &value, sizeof(value)); return s; } // ============================================================ // = private methodes ======================================= // ============================================================ template <typename T> void OcTreeDataNode<T>::allocChildren() { children = new AbstractOcTreeNode*[8]; for (unsigned int i=0; i<8; i++) { children[i] = NULL; } } } // end namespace
4,485
30.815603
99
hxx
octomap
octomap-master/octomap/include/octomap/OcTreeIterator.hxx
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMAP_OCTREEITERATOR_HXX_ #define OCTOMAP_OCTREEITERATOR_HXX_ /** * Base class for OcTree iterators. So far, all iterator's are * const with respect to the tree. This file is included within * OcTreeBaseImpl.h, you should probably not include this directly. */ class iterator_base : public std::iterator<std::forward_iterator_tag, NodeType>{ public: struct StackElement; /// Default ctor, only used for the end-iterator iterator_base() : tree(NULL), maxDepth(0){} /** * Constructor of the iterator. Initializes the iterator with the default * constructor (= end() iterator) if tree is empty or NULL. * * @param ptree OcTreeBaseImpl on which the iterator is used on * @param depth Maximum depth to traverse the tree. 0 (default): unlimited */ iterator_base(OcTreeBaseImpl<NodeType,INTERFACE> const* ptree, uint8_t depth=0) : tree((ptree && ptree->root) ? ptree : NULL), maxDepth(depth) { if (ptree && maxDepth == 0) maxDepth = ptree->getTreeDepth(); if (tree && tree->root){ // tree is not empty StackElement s; s.node = tree->root; s.depth = 0; s.key[0] = s.key[1] = s.key[2] = tree->tree_max_val; stack.push(s); } else{ // construct the same as "end" tree = NULL; this->maxDepth = 0; } } /// Copy constructor of the iterator iterator_base(const iterator_base& other) : tree(other.tree), maxDepth(other.maxDepth), stack(other.stack) {} /// Comparison between iterators. First compares the tree, then stack size and top element of stack. bool operator==(const iterator_base& other) const { return (tree ==other.tree && stack.size() == other.stack.size() && (stack.size()==0 || (stack.size() > 0 && (stack.top().node == other.stack.top().node && stack.top().depth == other.stack.top().depth && stack.top().key == other.stack.top().key )))); } /// Comparison between iterators. First compares the tree, then stack size and top element of stack. bool operator!=(const iterator_base& other) const { return (tree !=other.tree || stack.size() != other.stack.size() || (stack.size() > 0 && ((stack.top().node != other.stack.top().node || stack.top().depth != other.stack.top().depth || stack.top().key != other.stack.top().key )))); } iterator_base& operator=(const iterator_base& other){ tree = other.tree; maxDepth = other.maxDepth; stack = other.stack; return *this; }; /// Ptr operator will return the current node in the octree which the /// iterator is referring to NodeType const* operator->() const { return stack.top().node;} /// Ptr operator will return the current node in the octree which the /// iterator is referring to NodeType* operator->() { return stack.top().node;} /// Return the current node in the octree which the /// iterator is referring to const NodeType& operator*() const { return *(stack.top().node);} /// Return the current node in the octree which the /// iterator is referring to NodeType& operator*() { return *(stack.top().node);} /// return the center coordinate of the current node point3d getCoordinate() const { return tree->keyToCoord(stack.top().key, stack.top().depth); } /// @return single coordinate of the current node double getX() const{ return tree->keyToCoord(stack.top().key[0], stack.top().depth); } /// @return single coordinate of the current node double getY() const{ return tree->keyToCoord(stack.top().key[1], stack.top().depth); } /// @return single coordinate of the current node double getZ() const{ return tree->keyToCoord(stack.top().key[2], stack.top().depth); } /// @return the side of the volume occupied by the current node double getSize() const {return tree->getNodeSize(stack.top().depth); } /// return depth of the current node unsigned getDepth() const {return unsigned(stack.top().depth); } /// @return the OcTreeKey of the current node const OcTreeKey& getKey() const {return stack.top().key;} /// @return the OcTreeKey of the current node, for nodes with depth != maxDepth OcTreeKey getIndexKey() const { return computeIndexKey(tree->getTreeDepth() - stack.top().depth, stack.top().key); } /// Element on the internal recursion stack of the iterator struct StackElement{ NodeType* node; OcTreeKey key; uint8_t depth; }; protected: OcTreeBaseImpl<NodeType,INTERFACE> const* tree; ///< Octree this iterator is working on uint8_t maxDepth; ///< Maximum depth for depth-limited queries /// Internal recursion stack. Apparently a stack of vector works fastest here. std::stack<StackElement,std::vector<StackElement> > stack; /// One step of depth-first tree traversal. /// How this is used depends on the actual iterator. void singleIncrement(){ StackElement top = stack.top(); stack.pop(); if (top.depth == maxDepth) return; StackElement s; s.depth = top.depth +1; key_type center_offset_key = tree->tree_max_val >> s.depth; // push on stack in reverse order for (int i=7; i>=0; --i) { if (tree->nodeChildExists(top.node,i)) { computeChildKey(i, center_offset_key, top.key, s.key); s.node = tree->getNodeChild(top.node, i); //OCTOMAP_DEBUG_STR("Current depth: " << int(top.depth) << " new: "<< int(s.depth) << " child#" << i <<" ptr: "<<s.node); stack.push(s); assert(s.depth <= maxDepth); } } } }; /** * Iterator over the complete tree (inner nodes and leafs). * See below for example usage. * Note that the non-trivial call to tree->end_tree() should be done only once * for efficiency! * * @code * for(OcTreeTYPE::tree_iterator it = tree->begin_tree(), * end=tree->end_tree(); it!= end; ++it) * { * //manipulate node, e.g.: * std::cout << "Node center: " << it.getCoordinate() << std::endl; * std::cout << "Node size: " << it.getSize() << std::endl; * std::cout << "Node value: " << it->getValue() << std::endl; * } * @endcode */ class tree_iterator : public iterator_base { public: tree_iterator() : iterator_base(){} /** * Constructor of the iterator. * * @param ptree OcTreeBaseImpl on which the iterator is used on * @param depth Maximum depth to traverse the tree. 0 (default): unlimited */ tree_iterator(OcTreeBaseImpl<NodeType,INTERFACE> const* ptree, uint8_t depth=0) : iterator_base(ptree, depth) {}; /// postfix increment operator of iterator (it++) tree_iterator operator++(int){ tree_iterator result = *this; ++(*this); return result; } /// Prefix increment operator to advance the iterator tree_iterator& operator++(){ if (!this->stack.empty()){ this->singleIncrement(); } if (this->stack.empty()){ this->tree = NULL; } return *this; } /// @return whether the current node is a leaf, i.e. has no children or is at max level bool isLeaf() const{ return (!this->tree->nodeHasChildren(this->stack.top().node) || this->stack.top().depth == this->maxDepth); } }; /** * Iterator to iterate over all leafs of the tree. * Inner nodes are skipped. See below for example usage. * Note that the non-trivial call to tree->end_leafs() should be done only once * for efficiency! * * @code * for(OcTreeTYPE::leaf_iterator it = tree->begin_leafs(), * end=tree->end_leafs(); it!= end; ++it) * { * //manipulate node, e.g.: * std::cout << "Node center: " << it.getCoordinate() << std::endl; * std::cout << "Node size: " << it.getSize() << std::endl; * std::cout << "Node value: " << it->getValue() << std::endl; * } * @endcode * */ class leaf_iterator : public iterator_base { public: leaf_iterator() : iterator_base(){} /** * Constructor of the iterator. * * @param ptree OcTreeBaseImpl on which the iterator is used on * @param depth Maximum depth to traverse the tree. 0 (default): unlimited */ leaf_iterator(OcTreeBaseImpl<NodeType, INTERFACE> const* ptree, uint8_t depth=0) : iterator_base(ptree, depth) { // tree could be empty (= no stack) if (this->stack.size() > 0){ // skip forward to next valid leaf node: // add root another time (one will be removed) and ++ this->stack.push(this->stack.top()); operator ++(); } } leaf_iterator(const leaf_iterator& other) : iterator_base(other) {}; /// postfix increment operator of iterator (it++) leaf_iterator operator++(int){ leaf_iterator result = *this; ++(*this); return result; } /// prefix increment operator of iterator (++it) leaf_iterator& operator++(){ if (this->stack.empty()){ this->tree = NULL; // TODO check? } else { this->stack.pop(); // skip forward to next leaf while(!this->stack.empty() && this->stack.top().depth < this->maxDepth && this->tree->nodeHasChildren(this->stack.top().node)) { this->singleIncrement(); } // done: either stack is empty (== end iterator) or a next leaf node is reached! if (this->stack.empty()) this->tree = NULL; } return *this; } }; /** * Bounding-box leaf iterator. This iterator will traverse all leaf nodes * within a given bounding box (axis-aligned). See below for example usage. * Note that the non-trivial call to tree->end_leafs_bbx() should be done only once * for efficiency! * * @code * for(OcTreeTYPE::leaf_bbx_iterator it = tree->begin_leafs_bbx(min,max), * end=tree->end_leafs_bbx(); it!= end; ++it) * { * //manipulate node, e.g.: * std::cout << "Node center: " << it.getCoordinate() << std::endl; * std::cout << "Node size: " << it.getSize() << std::endl; * std::cout << "Node value: " << it->getValue() << std::endl; * } * @endcode */ class leaf_bbx_iterator : public iterator_base { public: leaf_bbx_iterator() : iterator_base() {}; /** * Constructor of the iterator. The bounding box corners min and max are * converted into an OcTreeKey first. * * @note Due to rounding and discretization * effects, nodes may be traversed that have float coordinates appearing * outside of the (float) bounding box. However, the node's complete volume * will include the bounding box coordinate. For a more exact control, use * the constructor with OcTreeKeys instead. * * @param ptree OcTreeBaseImpl on which the iterator is used on * @param min Minimum point3d of the axis-aligned boundingbox * @param max Maximum point3d of the axis-aligned boundingbox * @param depth Maximum depth to traverse the tree. 0 (default): unlimited */ leaf_bbx_iterator(OcTreeBaseImpl<NodeType,INTERFACE> const* ptree, const point3d& min, const point3d& max, uint8_t depth=0) : iterator_base(ptree, depth) { if (this->stack.size() > 0){ assert(ptree); if (!this->tree->coordToKeyChecked(min, minKey) || !this->tree->coordToKeyChecked(max, maxKey)){ // coordinates invalid, set to end iterator this->tree = NULL; this->maxDepth = 0; } else{ // else: keys are generated and stored // advance from root to next valid leaf in bbx: this->stack.push(this->stack.top()); this->operator ++(); } } } /** * Constructor of the iterator. This version uses the exact keys as axis-aligned * bounding box (including min and max). * * @param ptree OcTreeBaseImpl on which the iterator is used on * @param min Minimum OcTreeKey to be included in the axis-aligned boundingbox * @param max Maximum OcTreeKey to be included in the axis-aligned boundingbox * @param depth Maximum depth to traverse the tree. 0 (default): unlimited */ leaf_bbx_iterator(OcTreeBaseImpl<NodeType,INTERFACE> const* ptree, const OcTreeKey& min, const OcTreeKey& max, uint8_t depth=0) : iterator_base(ptree, depth), minKey(min), maxKey(max) { // tree could be empty (= no stack) if (this->stack.size() > 0){ // advance from root to next valid leaf in bbx: this->stack.push(this->stack.top()); this->operator ++(); } } leaf_bbx_iterator(const leaf_bbx_iterator& other) : iterator_base(other) { minKey = other.minKey; maxKey = other.maxKey; } /// postfix increment operator of iterator (it++) leaf_bbx_iterator operator++(int){ leaf_bbx_iterator result = *this; ++(*this); return result; } /// prefix increment operator of iterator (++it) leaf_bbx_iterator& operator++(){ if (this->stack.empty()){ this->tree = NULL; // TODO check? } else { this->stack.pop(); // skip forward to next leaf while(!this->stack.empty() && this->stack.top().depth < this->maxDepth && this->tree->nodeHasChildren(this->stack.top().node)) { this->singleIncrement(); } // done: either stack is empty (== end iterator) or a next leaf node is reached! if (this->stack.empty()) this->tree = NULL; } return *this; }; protected: void singleIncrement(){ typename iterator_base::StackElement top = this->stack.top(); this->stack.pop(); typename iterator_base::StackElement s; s.depth = top.depth +1; key_type center_offset_key = this->tree->tree_max_val >> s.depth; // push on stack in reverse order for (int i=7; i>=0; --i) { if (this->tree->nodeChildExists(top.node, i)) { computeChildKey(i, center_offset_key, top.key, s.key); // overlap of query bbx and child bbx? if ((minKey[0] <= (s.key[0] + center_offset_key)) && (maxKey[0] >= (s.key[0] - center_offset_key)) && (minKey[1] <= (s.key[1] + center_offset_key)) && (maxKey[1] >= (s.key[1] - center_offset_key)) && (minKey[2] <= (s.key[2] + center_offset_key)) && (maxKey[2] >= (s.key[2] - center_offset_key))) { s.node = this->tree->getNodeChild(top.node, i); this->stack.push(s); assert(s.depth <= this->maxDepth); } } } } OcTreeKey minKey; OcTreeKey maxKey; }; #endif /* OCTREEITERATOR_HXX_ */
17,543
36.810345
133
hxx
octomap
octomap-master/octomap/include/octomap/OcTreeKey.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMAP_OCTREE_KEY_H #define OCTOMAP_OCTREE_KEY_H /* According to c++ standard including this header has no practical effect * but it can be used to determine the c++ standard library implementation. */ #include <ciso646> #include <assert.h> /* Libc++ does not implement the TR1 namespace, all c++11 related functionality * is instead implemented in the std namespace. */ #if defined(__GNUC__) && ! defined(_LIBCPP_VERSION) #include <tr1/unordered_set> #include <tr1/unordered_map> namespace octomap { namespace unordered_ns = std::tr1; } #else #include <unordered_set> #include <unordered_map> namespace octomap { namespace unordered_ns = std; } #endif namespace octomap { typedef uint16_t key_type; /** * OcTreeKey is a container class for internal key addressing. The keys count the * number of cells (voxels) from the origin as discrete address of a voxel. * @see OcTreeBaseImpl::coordToKey() and OcTreeBaseImpl::keyToCoord() for conversions. */ class OcTreeKey { public: OcTreeKey () {} OcTreeKey (key_type a, key_type b, key_type c){ k[0] = a; k[1] = b; k[2] = c; } OcTreeKey(const OcTreeKey& other){ k[0] = other.k[0]; k[1] = other.k[1]; k[2] = other.k[2]; } bool operator== (const OcTreeKey &other) const { return ((k[0] == other[0]) && (k[1] == other[1]) && (k[2] == other[2])); } bool operator!= (const OcTreeKey& other) const { return( (k[0] != other[0]) || (k[1] != other[1]) || (k[2] != other[2]) ); } OcTreeKey& operator=(const OcTreeKey& other){ k[0] = other.k[0]; k[1] = other.k[1]; k[2] = other.k[2]; return *this; } const key_type& operator[] (unsigned int i) const { return k[i]; } key_type& operator[] (unsigned int i) { return k[i]; } key_type k[3]; /// Provides a hash function on Keys struct KeyHash{ size_t operator()(const OcTreeKey& key) const{ // a simple hashing function // explicit casts to size_t to operate on the complete range // constanst will be promoted according to C++ standard return static_cast<size_t>(key.k[0]) + 1447*static_cast<size_t>(key.k[1]) + 345637*static_cast<size_t>(key.k[2]); } }; }; /** * Data structure to efficiently compute the nodes to update from a scan * insertion using a hash set. * @note you need to use boost::unordered_set instead if your compiler does not * yet support tr1! */ typedef unordered_ns::unordered_set<OcTreeKey, OcTreeKey::KeyHash> KeySet; /** * Data structrure to efficiently track changed nodes as a combination of * OcTreeKeys and a bool flag (to denote newly created nodes) * */ typedef unordered_ns::unordered_map<OcTreeKey, bool, OcTreeKey::KeyHash> KeyBoolMap; class KeyRay { public: KeyRay () { ray.resize(maxSize); reset(); } KeyRay(const KeyRay& other){ ray = other.ray; size_t dSize = other.end() - other.begin(); end_of_ray = ray.begin() + dSize; } void reset() { end_of_ray = begin(); } void addKey(const OcTreeKey& k) { assert(end_of_ray != ray.end()); *end_of_ray = k; ++end_of_ray; } size_t size() const { return end_of_ray - ray.begin(); } size_t sizeMax() const { return maxSize; } typedef std::vector<OcTreeKey>::iterator iterator; typedef std::vector<OcTreeKey>::const_iterator const_iterator; typedef std::vector<OcTreeKey>::reverse_iterator reverse_iterator; iterator begin() { return ray.begin(); } iterator end() { return end_of_ray; } const_iterator begin() const { return ray.begin(); } const_iterator end() const { return end_of_ray; } reverse_iterator rbegin() { return (reverse_iterator) end_of_ray; } reverse_iterator rend() { return ray.rend(); } private: std::vector<OcTreeKey> ray; std::vector<OcTreeKey>::iterator end_of_ray; const static size_t maxSize = 100000; }; /** * Computes the key of a child node while traversing the octree, given * child index and current key * * @param[in] pos index of child node (0..7) * @param[in] center_offset_key constant offset of octree keys * @param[in] parent_key current (parent) key * @param[out] child_key computed child key */ inline void computeChildKey (unsigned int pos, key_type center_offset_key, const OcTreeKey& parent_key, OcTreeKey& child_key) { // x-axis if (pos & 1) child_key[0] = parent_key[0] + center_offset_key; else child_key[0] = parent_key[0] - center_offset_key - (center_offset_key ? 0 : 1); // y-axis if (pos & 2) child_key[1] = parent_key[1] + center_offset_key; else child_key[1] = parent_key[1] - center_offset_key - (center_offset_key ? 0 : 1); // z-axis if (pos & 4) child_key[2] = parent_key[2] + center_offset_key; else child_key[2] = parent_key[2] - center_offset_key - (center_offset_key ? 0 : 1); } /// generate child index (between 0 and 7) from key at given tree depth inline uint8_t computeChildIdx(const OcTreeKey& key, int depth){ uint8_t pos = 0; if (key.k[0] & (1 << depth)) pos += 1; if (key.k[1] & (1 << depth)) pos += 2; if (key.k[2] & (1 << depth)) pos += 4; return pos; } /** * Generates a unique key for all keys on a certain level of the tree * * @param level from the bottom (= tree_depth - depth of key) * @param key input indexing key (at lowest resolution / level) * @return key corresponding to the input key at the given level */ inline OcTreeKey computeIndexKey(key_type level, const OcTreeKey& key) { if (level == 0) return key; else { key_type mask = 65535 << level; OcTreeKey result = key; result[0] &= mask; result[1] &= mask; result[2] &= mask; return result; } } } // namespace #endif
7,910
31.422131
96
h
octomap
octomap-master/octomap/include/octomap/OcTreeNode.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMAP_OCTREE_NODE_H #define OCTOMAP_OCTREE_NODE_H #include "octomap_types.h" #include "octomap_utils.h" #include "OcTreeDataNode.h" #include <limits> namespace octomap { /** * Nodes to be used in OcTree. They represent 3d occupancy grid cells. * "value" stores their log-odds occupancy. * * Note: If you derive a class (directly or indirectly) from OcTreeNode or * OcTreeDataNode, you have to implement (at least) the following functions: * createChild(), getChild(), getChild() const, expandNode() to avoid slicing * errors and memory-related bugs. * See ColorOcTreeNode in ColorOcTree.h for an example. * */ class OcTreeNode : public OcTreeDataNode<float> { public: OcTreeNode(); ~OcTreeNode(); // -- node occupancy ---------------------------- /// \return occupancy probability of node inline double getOccupancy() const { return probability(value); } /// \return log odds representation of occupancy probability of node inline float getLogOdds() const{ return value; } /// sets log odds occupancy of node inline void setLogOdds(float l) { value = l; } /** * @return mean of all children's occupancy probabilities, in log odds */ double getMeanChildLogOdds() const; /** * @return maximum of children's occupancy probabilities, in log odds */ float getMaxChildLogOdds() const; /// update this node's occupancy according to its children's maximum occupancy inline void updateOccupancyChildren() { this->setLogOdds(this->getMaxChildLogOdds()); // conservative } /// adds p to the node's logOdds value (with no boundary / threshold checking!) void addValue(const float& p); protected: // "value" stores log odds occupancy probability }; } // end namespace #endif
3,621
35.959184
83
h
octomap
octomap-master/octomap/include/octomap/OcTreeStamped.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMAP_OCTREE_STAMPED_H #define OCTOMAP_OCTREE_STAMPED_H #include <octomap/OcTreeNode.h> #include <octomap/OccupancyOcTreeBase.h> #include <ctime> namespace octomap { // node definition class OcTreeNodeStamped : public OcTreeNode { public: OcTreeNodeStamped() : OcTreeNode(), timestamp(0) {} OcTreeNodeStamped(const OcTreeNodeStamped& rhs) : OcTreeNode(rhs), timestamp(rhs.timestamp) {} bool operator==(const OcTreeNodeStamped& rhs) const{ return (rhs.value == value && rhs.timestamp == timestamp); } void copyData(const OcTreeNodeStamped& from){ OcTreeNode::copyData(from); timestamp = from.getTimestamp(); } // timestamp inline unsigned int getTimestamp() const { return timestamp; } inline void updateTimestamp() { timestamp = (unsigned int) time(NULL);} inline void setTimestamp(unsigned int t) {timestamp = t; } // update occupancy and timesteps of inner nodes inline void updateOccupancyChildren() { this->setLogOdds(this->getMaxChildLogOdds()); // conservative updateTimestamp(); } protected: unsigned int timestamp; }; // tree definition class OcTreeStamped : public OccupancyOcTreeBase <OcTreeNodeStamped> { public: /// Default constructor, sets resolution of leafs OcTreeStamped(double resolution); /// virtual constructor: creates a new object of same type /// (Covariant return type requires an up-to-date compiler) OcTreeStamped* create() const {return new OcTreeStamped(resolution); } std::string getTreeType() const {return "OcTreeStamped";} //! \return timestamp of last update unsigned int getLastUpdateTime(); void degradeOutdatedNodes(unsigned int time_thres); virtual void updateNodeLogOdds(OcTreeNodeStamped* node, const float& update) const; void integrateMissNoTime(OcTreeNodeStamped* node) const; protected: /** * Static member object which ensures that this OcTree's prototype * ends up in the classIDMapping only once. You need this as a * static member in any derived octree class in order to read .ot * files through the AbstractOcTree factory. You should also call * ensureLinking() once from the constructor. */ class StaticMemberInitializer{ public: StaticMemberInitializer() { OcTreeStamped* tree = new OcTreeStamped(0.1); tree->clearKeyRays(); AbstractOcTree::registerTreeType(tree); } /** * Dummy function to ensure that MSVC does not drop the * StaticMemberInitializer, causing this tree failing to register. * Needs to be called from the constructor of this octree. */ void ensureLinking() {}; }; /// to ensure static initialization (only once) static StaticMemberInitializer ocTreeStampedMemberInit; }; } // end namespace #endif
4,655
35.093023
98
h
octomap
octomap-master/octomap/include/octomap/OccupancyOcTreeBase.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMAP_OCCUPANCY_OCTREE_BASE_H #define OCTOMAP_OCCUPANCY_OCTREE_BASE_H #include <list> #include <stdlib.h> #include <vector> #include "octomap_types.h" #include "octomap_utils.h" #include "OcTreeBaseImpl.h" #include "AbstractOccupancyOcTree.h" namespace octomap { /** * Base implementation for Occupancy Octrees (e.g. for mapping). * AbstractOccupancyOcTree serves as a common * base interface for all these classes. * Each class used as NODE type needs to be derived from * OccupancyOcTreeNode. * * This tree implementation has a maximum depth of 16. * At a resolution of 1 cm, values have to be < +/- 327.68 meters (2^15) * * This limitation enables the use of an efficient key generation * method which uses the binary representation of the data. * * \note The tree does not save individual points. * * \tparam NODE Node class to be used in tree (usually derived from * OcTreeDataNode) */ template <class NODE> class OccupancyOcTreeBase : public OcTreeBaseImpl<NODE,AbstractOccupancyOcTree> { public: /// Default constructor, sets resolution of leafs OccupancyOcTreeBase(double resolution); virtual ~OccupancyOcTreeBase(); /// Copy constructor OccupancyOcTreeBase(const OccupancyOcTreeBase<NODE>& rhs); /** * Integrate a Pointcloud (in global reference frame), parallelized with OpenMP. * Special care is taken that each voxel * in the map is updated only once, and occupied nodes have a preference over free ones. * This avoids holes in the floor from mutual deletion and is more efficient than the plain * ray insertion in insertPointCloudRays(). * * @note replaces insertScan() * * @param scan Pointcloud (measurement endpoints), in global reference frame * @param sensor_origin measurement origin in global reference frame * @param maxrange maximum range for how long individual beams are inserted (default -1: complete beam) * @param lazy_eval whether update of inner nodes is omitted after the update (default: false). * This speeds up the insertion, but you need to call updateInnerOccupancy() when done. * @param discretize whether the scan is discretized first into octree key cells (default: false). * This reduces the number of raycasts using computeDiscreteUpdate(), resulting in a potential speedup.* */ virtual void insertPointCloud(const Pointcloud& scan, const octomap::point3d& sensor_origin, double maxrange=-1., bool lazy_eval = false, bool discretize = false); /** * Integrate a 3d scan (transform scan before tree update), parallelized with OpenMP. * Special care is taken that each voxel * in the map is updated only once, and occupied nodes have a preference over free ones. * This avoids holes in the floor from mutual deletion and is more efficient than the plain * ray insertion in insertPointCloudRays(). * * @note replaces insertScan() * * @param scan Pointcloud (measurement endpoints) relative to frame origin * @param sensor_origin origin of sensor relative to frame origin * @param frame_origin origin of reference frame, determines transform to be applied to cloud and sensor origin * @param maxrange maximum range for how long individual beams are inserted (default -1: complete beam) * @param lazy_eval whether update of inner nodes is omitted after the update (default: false). * This speeds up the insertion, but you need to call updateInnerOccupancy() when done. * @param discretize whether the scan is discretized first into octree key cells (default: false). * This reduces the number of raycasts using computeDiscreteUpdate(), resulting in a potential speedup.* */ virtual void insertPointCloud(const Pointcloud& scan, const point3d& sensor_origin, const pose6d& frame_origin, double maxrange=-1., bool lazy_eval = false, bool discretize = false); /** * Insert a 3d scan (given as a ScanNode) into the tree, parallelized with OpenMP. * * @note replaces insertScan * * @param scan ScanNode contains Pointcloud data and frame/sensor origin * @param maxrange maximum range for how long individual beams are inserted (default -1: complete beam) * @param lazy_eval whether the tree is left 'dirty' after the update (default: false). * This speeds up the insertion by not updating inner nodes, but you need to call updateInnerOccupancy() when done. * @param discretize whether the scan is discretized first into octree key cells (default: false). * This reduces the number of raycasts using computeDiscreteUpdate(), resulting in a potential speedup. */ virtual void insertPointCloud(const ScanNode& scan, double maxrange=-1., bool lazy_eval = false, bool discretize = false); /** * Integrate a Pointcloud (in global reference frame), parallelized with OpenMP. * This function simply inserts all rays of the point clouds as batch operation. * Discretization effects can lead to the deletion of occupied space, it is * usually recommended to use insertPointCloud() instead. * * @param scan Pointcloud (measurement endpoints), in global reference frame * @param sensor_origin measurement origin in global reference frame * @param maxrange maximum range for how long individual beams are inserted (default -1: complete beam) * @param lazy_eval whether update of inner nodes is omitted after the update (default: false). * This speeds up the insertion, but you need to call updateInnerOccupancy() when done. */ virtual void insertPointCloudRays(const Pointcloud& scan, const point3d& sensor_origin, double maxrange = -1., bool lazy_eval = false); /** * Set log_odds value of voxel to log_odds_value. This only works if key is at the lowest * octree level * * @param key OcTreeKey of the NODE that is to be updated * @param log_odds_value value to be set as the log_odds value of the node * @param lazy_eval whether update of inner nodes is omitted after the update (default: false). * This speeds up the insertion, but you need to call updateInnerOccupancy() when done. * @return pointer to the updated NODE */ virtual NODE* setNodeValue(const OcTreeKey& key, float log_odds_value, bool lazy_eval = false); /** * Set log_odds value of voxel to log_odds_value. * Looks up the OcTreeKey corresponding to the coordinate and then calls setNodeValue() with it. * * @param value 3d coordinate of the NODE that is to be updated * @param log_odds_value value to be set as the log_odds value of the node * @param lazy_eval whether update of inner nodes is omitted after the update (default: false). * This speeds up the insertion, but you need to call updateInnerOccupancy() when done. * @return pointer to the updated NODE */ virtual NODE* setNodeValue(const point3d& value, float log_odds_value, bool lazy_eval = false); /** * Set log_odds value of voxel to log_odds_value. * Looks up the OcTreeKey corresponding to the coordinate and then calls setNodeValue() with it. * * @param x * @param y * @param z * @param log_odds_value value to be set as the log_odds value of the node * @param lazy_eval whether update of inner nodes is omitted after the update (default: false). * This speeds up the insertion, but you need to call updateInnerOccupancy() when done. * @return pointer to the updated NODE */ virtual NODE* setNodeValue(double x, double y, double z, float log_odds_value, bool lazy_eval = false); /** * Manipulate log_odds value of a voxel by changing it by log_odds_update (relative). * This only works if key is at the lowest octree level * * @param key OcTreeKey of the NODE that is to be updated * @param log_odds_update value to be added (+) to log_odds value of node * @param lazy_eval whether update of inner nodes is omitted after the update (default: false). * This speeds up the insertion, but you need to call updateInnerOccupancy() when done. * @return pointer to the updated NODE */ virtual NODE* updateNode(const OcTreeKey& key, float log_odds_update, bool lazy_eval = false); /** * Manipulate log_odds value of a voxel by changing it by log_odds_update (relative). * Looks up the OcTreeKey corresponding to the coordinate and then calls updateNode() with it. * * @param value 3d coordinate of the NODE that is to be updated * @param log_odds_update value to be added (+) to log_odds value of node * @param lazy_eval whether update of inner nodes is omitted after the update (default: false). * This speeds up the insertion, but you need to call updateInnerOccupancy() when done. * @return pointer to the updated NODE */ virtual NODE* updateNode(const point3d& value, float log_odds_update, bool lazy_eval = false); /** * Manipulate log_odds value of a voxel by changing it by log_odds_update (relative). * Looks up the OcTreeKey corresponding to the coordinate and then calls updateNode() with it. * * @param x * @param y * @param z * @param log_odds_update value to be added (+) to log_odds value of node * @param lazy_eval whether update of inner nodes is omitted after the update (default: false). * This speeds up the insertion, but you need to call updateInnerOccupancy() when done. * @return pointer to the updated NODE */ virtual NODE* updateNode(double x, double y, double z, float log_odds_update, bool lazy_eval = false); /** * Integrate occupancy measurement. * * @param key OcTreeKey of the NODE that is to be updated * @param occupied true if the node was measured occupied, else false * @param lazy_eval whether update of inner nodes is omitted after the update (default: false). * This speeds up the insertion, but you need to call updateInnerOccupancy() when done. * @return pointer to the updated NODE */ virtual NODE* updateNode(const OcTreeKey& key, bool occupied, bool lazy_eval = false); /** * Integrate occupancy measurement. * Looks up the OcTreeKey corresponding to the coordinate and then calls udpateNode() with it. * * @param value 3d coordinate of the NODE that is to be updated * @param occupied true if the node was measured occupied, else false * @param lazy_eval whether update of inner nodes is omitted after the update (default: false). * This speeds up the insertion, but you need to call updateInnerOccupancy() when done. * @return pointer to the updated NODE */ virtual NODE* updateNode(const point3d& value, bool occupied, bool lazy_eval = false); /** * Integrate occupancy measurement. * Looks up the OcTreeKey corresponding to the coordinate and then calls udpateNode() with it. * * @param x * @param y * @param z * @param occupied true if the node was measured occupied, else false * @param lazy_eval whether update of inner nodes is omitted after the update (default: false). * This speeds up the insertion, but you need to call updateInnerOccupancy() when done. * @return pointer to the updated NODE */ virtual NODE* updateNode(double x, double y, double z, bool occupied, bool lazy_eval = false); /** * Creates the maximum likelihood map by calling toMaxLikelihood on all * tree nodes, setting their occupancy to the corresponding occupancy thresholds. * This enables a very efficient compression if you call prune() afterwards. */ virtual void toMaxLikelihood(); /** * Insert one ray between origin and end into the tree. * integrateMissOnRay() is called for the ray, the end point is updated as occupied. * It is usually more efficient to insert complete pointcloudsm with insertPointCloud() or * insertPointCloudRays(). * * @param origin origin of sensor in global coordinates * @param end endpoint of measurement in global coordinates * @param maxrange maximum range after which the raycast should be aborted * @param lazy_eval whether update of inner nodes is omitted after the update (default: false). * This speeds up the insertion, but you need to call updateInnerOccupancy() when done. * @return success of operation */ virtual bool insertRay(const point3d& origin, const point3d& end, double maxrange=-1.0, bool lazy_eval = false); /** * Performs raycasting in 3d, similar to computeRay(). Can be called in parallel e.g. with OpenMP * for a speedup. * * A ray is cast from 'origin' with a given direction, the first non-free * cell is returned in 'end' (as center coordinate). This could also be the * origin node if it is occupied or unknown. castRay() returns true if an occupied node * was hit by the raycast. If the raycast returns false you can search() the node at 'end' and * see whether it's unknown space. * * * @param[in] origin starting coordinate of ray * @param[in] direction A vector pointing in the direction of the raycast (NOT a point in space). Does not need to be normalized. * @param[out] end returns the center of the last cell on the ray. If the function returns true, it is occupied. * @param[in] ignoreUnknownCells whether unknown cells are ignored (= treated as free). If false (default), the raycast aborts when an unknown cell is hit and returns false. * @param[in] maxRange Maximum range after which the raycast is aborted (<= 0: no limit, default) * @return true if an occupied cell was hit, false if the maximum range or octree bounds are reached, or if an unknown node was hit. */ virtual bool castRay(const point3d& origin, const point3d& direction, point3d& end, bool ignoreUnknownCells=false, double maxRange=-1.0) const; /** * Retrieves the entry point of a ray into a voxel. This is the closest intersection point of the ray * originating from origin and a plane of the axis aligned cube. * * @param[in] origin Starting point of ray * @param[in] direction A vector pointing in the direction of the raycast. Does not need to be normalized. * @param[in] center The center of the voxel where the ray terminated. This is the output of castRay. * @param[out] intersection The entry point of the ray into the voxel, on the voxel surface. * @param[in] delta A small increment to avoid ambiguity of beeing exactly on a voxel surface. A positive value will get the point out of the hit voxel, while a negative valuewill get it inside. * @return Whether or not an intesection point has been found. Either, the ray never cross the voxel or the ray is exactly parallel to the only surface it intersect. */ virtual bool getRayIntersection(const point3d& origin, const point3d& direction, const point3d& center, point3d& intersection, double delta=0.0) const; /** * Performs a step of the marching cubes surface reconstruction algorithm * to retrieve the normal of the triangles that fall in the cube * formed by the voxels located at the vertex of a given voxel. * * @param[in] point voxel for which retrieve the normals * @param[out] normals normals of the triangles * @param[in] unknownStatus consider unknown cells as free (false) or occupied (default, true). * @return True if the input voxel is known in the occupancy grid, and false if it is unknown. */ bool getNormals(const point3d& point, std::vector<point3d>& normals, bool unknownStatus=true) const; //-- set BBX limit (limits tree updates to this bounding box) /// use or ignore BBX limit (default: ignore) void useBBXLimit(bool enable) { use_bbx_limit = enable; } bool bbxSet() const { return use_bbx_limit; } /// sets the minimum for a query bounding box to use void setBBXMin (const point3d& min); /// sets the maximum for a query bounding box to use void setBBXMax (const point3d& max); /// @return the currently set minimum for bounding box queries, if set point3d getBBXMin () const { return bbx_min; } /// @return the currently set maximum for bounding box queries, if set point3d getBBXMax () const { return bbx_max; } point3d getBBXBounds () const; point3d getBBXCenter () const; /// @return true if point is in the currently set bounding box bool inBBX(const point3d& p) const; /// @return true if key is in the currently set bounding box bool inBBX(const OcTreeKey& key) const; //-- change detection on occupancy: /// track or ignore changes while inserting scans (default: ignore) void enableChangeDetection(bool enable) { use_change_detection = enable; } bool isChangeDetectionEnabled() const { return use_change_detection; } /// Reset the set of changed keys. Call this after you obtained all changed nodes. void resetChangeDetection() { changed_keys.clear(); } /** * Iterator to traverse all keys of changed nodes. * you need to enableChangeDetection() first. Here, an OcTreeKey always * refers to a node at the lowest tree level (its size is the minimum tree resolution) */ KeyBoolMap::const_iterator changedKeysBegin() const {return changed_keys.begin();} /// Iterator to traverse all keys of changed nodes. KeyBoolMap::const_iterator changedKeysEnd() const {return changed_keys.end();} /// Number of changes since last reset. size_t numChangesDetected() const { return changed_keys.size(); } /** * Helper for insertPointCloud(). Computes all octree nodes affected by the point cloud * integration at once. Here, occupied nodes have a preference over free * ones. * * @param scan point cloud measurement to be integrated * @param origin origin of the sensor for ray casting * @param free_cells keys of nodes to be cleared * @param occupied_cells keys of nodes to be marked occupied * @param maxrange maximum range for raycasting (-1: unlimited) */ void computeUpdate(const Pointcloud& scan, const octomap::point3d& origin, KeySet& free_cells, KeySet& occupied_cells, double maxrange); /** * Helper for insertPointCloud(). Computes all octree nodes affected by the point cloud * integration at once. Here, occupied nodes have a preference over free * ones. This function first discretizes the scan with the octree grid, which results * in fewer raycasts (=speedup) but a slightly different result than computeUpdate(). * * @param scan point cloud measurement to be integrated * @param origin origin of the sensor for ray casting * @param free_cells keys of nodes to be cleared * @param occupied_cells keys of nodes to be marked occupied * @param maxrange maximum range for raycasting (-1: unlimited) */ void computeDiscreteUpdate(const Pointcloud& scan, const octomap::point3d& origin, KeySet& free_cells, KeySet& occupied_cells, double maxrange); // -- I/O ----------------------------------------- /** * Reads only the data (=complete tree structure) from the input stream. * The tree needs to be constructed with the proper header information * beforehand, see readBinary(). */ std::istream& readBinaryData(std::istream &s); /** * Read node from binary stream (max-likelihood value), recursively * continue with all children. * * This will set the log_odds_occupancy value of * all leaves to either free or occupied. */ std::istream& readBinaryNode(std::istream &s, NODE* node); /** * Write node to binary stream (max-likelihood value), * recursively continue with all children. * * This will discard the log_odds_occupancy value, writing * all leaves as either free or occupied. * * @param s * @param node OcTreeNode to write out, will recurse to all children * @return */ std::ostream& writeBinaryNode(std::ostream &s, const NODE* node) const; /** * Writes the data of the tree (without header) to the stream, recursively * calling writeBinaryNode (starting with root) */ std::ostream& writeBinaryData(std::ostream &s) const; /** * Updates the occupancy of all inner nodes to reflect their children's occupancy. * If you performed batch-updates with lazy evaluation enabled, you must call this * before any queries to ensure correct multi-resolution behavior. **/ void updateInnerOccupancy(); /// integrate a "hit" measurement according to the tree's sensor model virtual void integrateHit(NODE* occupancyNode) const; /// integrate a "miss" measurement according to the tree's sensor model virtual void integrateMiss(NODE* occupancyNode) const; /// update logodds value of node by adding to the current value. virtual void updateNodeLogOdds(NODE* occupancyNode, const float& update) const; /// converts the node to the maximum likelihood value according to the tree's parameter for "occupancy" virtual void nodeToMaxLikelihood(NODE* occupancyNode) const; /// converts the node to the maximum likelihood value according to the tree's parameter for "occupancy" virtual void nodeToMaxLikelihood(NODE& occupancyNode) const; protected: /// Constructor to enable derived classes to change tree constants. /// This usually requires a re-implementation of some core tree-traversal functions as well! OccupancyOcTreeBase(double resolution, unsigned int tree_depth, unsigned int tree_max_val); /** * Traces a ray from origin to end and updates all voxels on the * way as free. The volume containing "end" is not updated. */ inline bool integrateMissOnRay(const point3d& origin, const point3d& end, bool lazy_eval = false); // recursive calls ---------------------------- NODE* updateNodeRecurs(NODE* node, bool node_just_created, const OcTreeKey& key, unsigned int depth, const float& log_odds_update, bool lazy_eval = false); NODE* setNodeValueRecurs(NODE* node, bool node_just_created, const OcTreeKey& key, unsigned int depth, const float& log_odds_value, bool lazy_eval = false); void updateInnerOccupancyRecurs(NODE* node, unsigned int depth); void toMaxLikelihoodRecurs(NODE* node, unsigned int depth, unsigned int max_depth); protected: bool use_bbx_limit; ///< use bounding box for queries (needs to be set)? point3d bbx_min; point3d bbx_max; OcTreeKey bbx_min_key; OcTreeKey bbx_max_key; bool use_change_detection; /// Set of leaf keys (lowest level) which changed since last resetChangeDetection KeyBoolMap changed_keys; }; } // namespace #include "octomap/OccupancyOcTreeBase.hxx" #endif
25,146
48.404715
198
h
octomap
octomap-master/octomap/include/octomap/OccupancyOcTreeBase.hxx
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <bitset> #include <algorithm> #include <octomap/MCTables.h> namespace octomap { template <class NODE> OccupancyOcTreeBase<NODE>::OccupancyOcTreeBase(double in_resolution) : OcTreeBaseImpl<NODE,AbstractOccupancyOcTree>(in_resolution), use_bbx_limit(false), use_change_detection(false) { } template <class NODE> OccupancyOcTreeBase<NODE>::OccupancyOcTreeBase(double in_resolution, unsigned int in_tree_depth, unsigned int in_tree_max_val) : OcTreeBaseImpl<NODE,AbstractOccupancyOcTree>(in_resolution, in_tree_depth, in_tree_max_val), use_bbx_limit(false), use_change_detection(false) { } template <class NODE> OccupancyOcTreeBase<NODE>::~OccupancyOcTreeBase(){ } template <class NODE> OccupancyOcTreeBase<NODE>::OccupancyOcTreeBase(const OccupancyOcTreeBase<NODE>& rhs) : OcTreeBaseImpl<NODE,AbstractOccupancyOcTree>(rhs), use_bbx_limit(rhs.use_bbx_limit), bbx_min(rhs.bbx_min), bbx_max(rhs.bbx_max), bbx_min_key(rhs.bbx_min_key), bbx_max_key(rhs.bbx_max_key), use_change_detection(rhs.use_change_detection), changed_keys(rhs.changed_keys) { this->clamping_thres_min = rhs.clamping_thres_min; this->clamping_thres_max = rhs.clamping_thres_max; this->prob_hit_log = rhs.prob_hit_log; this->prob_miss_log = rhs.prob_miss_log; this->occ_prob_thres_log = rhs.occ_prob_thres_log; } template <class NODE> void OccupancyOcTreeBase<NODE>::insertPointCloud(const ScanNode& scan, double maxrange, bool lazy_eval, bool discretize) { // performs transformation to data and sensor origin first Pointcloud& cloud = *(scan.scan); pose6d frame_origin = scan.pose; point3d sensor_origin = frame_origin.inv().transform(scan.pose.trans()); insertPointCloud(cloud, sensor_origin, frame_origin, maxrange, lazy_eval, discretize); } template <class NODE> void OccupancyOcTreeBase<NODE>::insertPointCloud(const Pointcloud& scan, const octomap::point3d& sensor_origin, double maxrange, bool lazy_eval, bool discretize) { KeySet free_cells, occupied_cells; if (discretize) computeDiscreteUpdate(scan, sensor_origin, free_cells, occupied_cells, maxrange); else computeUpdate(scan, sensor_origin, free_cells, occupied_cells, maxrange); // insert data into tree ----------------------- for (KeySet::iterator it = free_cells.begin(); it != free_cells.end(); ++it) { updateNode(*it, false, lazy_eval); } for (KeySet::iterator it = occupied_cells.begin(); it != occupied_cells.end(); ++it) { updateNode(*it, true, lazy_eval); } } template <class NODE> void OccupancyOcTreeBase<NODE>::insertPointCloud(const Pointcloud& pc, const point3d& sensor_origin, const pose6d& frame_origin, double maxrange, bool lazy_eval, bool discretize) { // performs transformation to data and sensor origin first Pointcloud transformed_scan (pc); transformed_scan.transform(frame_origin); point3d transformed_sensor_origin = frame_origin.transform(sensor_origin); insertPointCloud(transformed_scan, transformed_sensor_origin, maxrange, lazy_eval, discretize); } template <class NODE> void OccupancyOcTreeBase<NODE>::insertPointCloudRays(const Pointcloud& pc, const point3d& origin, double /* maxrange */, bool lazy_eval) { if (pc.size() < 1) return; #ifdef _OPENMP omp_set_num_threads(this->keyrays.size()); #pragma omp parallel for #endif for (int i = 0; i < (int)pc.size(); ++i) { const point3d& p = pc[i]; unsigned threadIdx = 0; #ifdef _OPENMP threadIdx = omp_get_thread_num(); #endif KeyRay* keyray = &(this->keyrays.at(threadIdx)); if (this->computeRayKeys(origin, p, *keyray)){ #ifdef _OPENMP #pragma omp critical #endif { for(KeyRay::iterator it=keyray->begin(); it != keyray->end(); it++) { updateNode(*it, false, lazy_eval); // insert freespace measurement } updateNode(p, true, lazy_eval); // update endpoint to be occupied } } } } template <class NODE> void OccupancyOcTreeBase<NODE>::computeDiscreteUpdate(const Pointcloud& scan, const octomap::point3d& origin, KeySet& free_cells, KeySet& occupied_cells, double maxrange) { Pointcloud discretePC; discretePC.reserve(scan.size()); KeySet endpoints; for (int i = 0; i < (int)scan.size(); ++i) { OcTreeKey k = this->coordToKey(scan[i]); std::pair<KeySet::iterator,bool> ret = endpoints.insert(k); if (ret.second){ // insertion took place => k was not in set discretePC.push_back(this->keyToCoord(k)); } } computeUpdate(discretePC, origin, free_cells, occupied_cells, maxrange); } template <class NODE> void OccupancyOcTreeBase<NODE>::computeUpdate(const Pointcloud& scan, const octomap::point3d& origin, KeySet& free_cells, KeySet& occupied_cells, double maxrange) { #ifdef _OPENMP omp_set_num_threads(this->keyrays.size()); #pragma omp parallel for schedule(guided) #endif for (int i = 0; i < (int)scan.size(); ++i) { const point3d& p = scan[i]; unsigned threadIdx = 0; #ifdef _OPENMP threadIdx = omp_get_thread_num(); #endif KeyRay* keyray = &(this->keyrays.at(threadIdx)); if (!use_bbx_limit) { // no BBX specified if ((maxrange < 0.0) || ((p - origin).norm() <= maxrange) ) { // is not maxrange meas. // free cells if (this->computeRayKeys(origin, p, *keyray)){ #ifdef _OPENMP #pragma omp critical (free_insert) #endif { free_cells.insert(keyray->begin(), keyray->end()); } } // occupied endpoint OcTreeKey key; if (this->coordToKeyChecked(p, key)){ #ifdef _OPENMP #pragma omp critical (occupied_insert) #endif { occupied_cells.insert(key); } } } else { // user set a maxrange and length is above point3d direction = (p - origin).normalized (); point3d new_end = origin + direction * (float) maxrange; if (this->computeRayKeys(origin, new_end, *keyray)){ #ifdef _OPENMP #pragma omp critical (free_insert) #endif { free_cells.insert(keyray->begin(), keyray->end()); } } } // end if maxrange } else { // BBX was set // endpoint in bbx and not maxrange? if ( inBBX(p) && ((maxrange < 0.0) || ((p - origin).norm () <= maxrange) ) ) { // occupied endpoint OcTreeKey key; if (this->coordToKeyChecked(p, key)){ #ifdef _OPENMP #pragma omp critical (occupied_insert) #endif { occupied_cells.insert(key); } } } // end if in BBX and not maxrange // truncate the end point to the max range if the max range is exceeded point3d new_end = p; if ((maxrange >= 0.0) && ((p - origin).norm() > maxrange)) { const point3d direction = (p - origin).normalized(); new_end = origin + direction * (float) maxrange; } // update freespace, break as soon as bbx limit is reached if (this->computeRayKeys(origin, new_end, *keyray)){ for(KeyRay::iterator it=keyray->begin(); it != keyray->end(); it++) { if (inBBX(*it)) { #ifdef _OPENMP #pragma omp critical (free_insert) #endif { free_cells.insert(*it); } } else break; } } // end if compute ray } // end bbx case } // end for all points, end of parallel OMP loop // prefer occupied cells over free ones (and make sets disjunct) for(KeySet::iterator it = free_cells.begin(), end=free_cells.end(); it!= end; ){ if (occupied_cells.find(*it) != occupied_cells.end()){ it = free_cells.erase(it); } else { ++it; } } } template <class NODE> NODE* OccupancyOcTreeBase<NODE>::setNodeValue(const OcTreeKey& key, float log_odds_value, bool lazy_eval) { // clamp log odds within range: log_odds_value = std::min(std::max(log_odds_value, this->clamping_thres_min), this->clamping_thres_max); bool createdRoot = false; if (this->root == NULL){ this->root = new NODE(); this->tree_size++; createdRoot = true; } return setNodeValueRecurs(this->root, createdRoot, key, 0, log_odds_value, lazy_eval); } template <class NODE> NODE* OccupancyOcTreeBase<NODE>::setNodeValue(const point3d& value, float log_odds_value, bool lazy_eval) { OcTreeKey key; if (!this->coordToKeyChecked(value, key)) return NULL; return setNodeValue(key, log_odds_value, lazy_eval); } template <class NODE> NODE* OccupancyOcTreeBase<NODE>::setNodeValue(double x, double y, double z, float log_odds_value, bool lazy_eval) { OcTreeKey key; if (!this->coordToKeyChecked(x, y, z, key)) return NULL; return setNodeValue(key, log_odds_value, lazy_eval); } template <class NODE> NODE* OccupancyOcTreeBase<NODE>::updateNode(const OcTreeKey& key, float log_odds_update, bool lazy_eval) { // early abort (no change will happen). // may cause an overhead in some configuration, but more often helps NODE* leaf = this->search(key); // no change: node already at threshold if (leaf && ((log_odds_update >= 0 && leaf->getLogOdds() >= this->clamping_thres_max) || ( log_odds_update <= 0 && leaf->getLogOdds() <= this->clamping_thres_min))) { return leaf; } bool createdRoot = false; if (this->root == NULL){ this->root = new NODE(); this->tree_size++; createdRoot = true; } return updateNodeRecurs(this->root, createdRoot, key, 0, log_odds_update, lazy_eval); } template <class NODE> NODE* OccupancyOcTreeBase<NODE>::updateNode(const point3d& value, float log_odds_update, bool lazy_eval) { OcTreeKey key; if (!this->coordToKeyChecked(value, key)) return NULL; return updateNode(key, log_odds_update, lazy_eval); } template <class NODE> NODE* OccupancyOcTreeBase<NODE>::updateNode(double x, double y, double z, float log_odds_update, bool lazy_eval) { OcTreeKey key; if (!this->coordToKeyChecked(x, y, z, key)) return NULL; return updateNode(key, log_odds_update, lazy_eval); } template <class NODE> NODE* OccupancyOcTreeBase<NODE>::updateNode(const OcTreeKey& key, bool occupied, bool lazy_eval) { float logOdds = this->prob_miss_log; if (occupied) logOdds = this->prob_hit_log; return updateNode(key, logOdds, lazy_eval); } template <class NODE> NODE* OccupancyOcTreeBase<NODE>::updateNode(const point3d& value, bool occupied, bool lazy_eval) { OcTreeKey key; if (!this->coordToKeyChecked(value, key)) return NULL; return updateNode(key, occupied, lazy_eval); } template <class NODE> NODE* OccupancyOcTreeBase<NODE>::updateNode(double x, double y, double z, bool occupied, bool lazy_eval) { OcTreeKey key; if (!this->coordToKeyChecked(x, y, z, key)) return NULL; return updateNode(key, occupied, lazy_eval); } template <class NODE> NODE* OccupancyOcTreeBase<NODE>::updateNodeRecurs(NODE* node, bool node_just_created, const OcTreeKey& key, unsigned int depth, const float& log_odds_update, bool lazy_eval) { bool created_node = false; assert(node); // follow down to last level if (depth < this->tree_depth) { unsigned int pos = computeChildIdx(key, this->tree_depth -1 - depth); if (!this->nodeChildExists(node, pos)) { // child does not exist, but maybe it's a pruned node? if (!this->nodeHasChildren(node) && !node_just_created ) { // current node does not have children AND it is not a new node // -> expand pruned node this->expandNode(node); } else { // not a pruned node, create requested child this->createNodeChild(node, pos); created_node = true; } } if (lazy_eval) return updateNodeRecurs(this->getNodeChild(node, pos), created_node, key, depth+1, log_odds_update, lazy_eval); else { NODE* retval = updateNodeRecurs(this->getNodeChild(node, pos), created_node, key, depth+1, log_odds_update, lazy_eval); // prune node if possible, otherwise set own probability // note: combining both did not lead to a speedup! if (this->pruneNode(node)){ // return pointer to current parent (pruned), the just updated node no longer exists retval = node; } else{ node->updateOccupancyChildren(); } return retval; } } // at last level, update node, end of recursion else { if (use_change_detection) { bool occBefore = this->isNodeOccupied(node); updateNodeLogOdds(node, log_odds_update); if (node_just_created){ // new node changed_keys.insert(std::pair<OcTreeKey,bool>(key, true)); } else if (occBefore != this->isNodeOccupied(node)) { // occupancy changed, track it KeyBoolMap::iterator it = changed_keys.find(key); if (it == changed_keys.end()) changed_keys.insert(std::pair<OcTreeKey,bool>(key, false)); else if (it->second == false) changed_keys.erase(it); } } else { updateNodeLogOdds(node, log_odds_update); } return node; } } // TODO: mostly copy of updateNodeRecurs => merge code or general tree modifier / traversal template <class NODE> NODE* OccupancyOcTreeBase<NODE>::setNodeValueRecurs(NODE* node, bool node_just_created, const OcTreeKey& key, unsigned int depth, const float& log_odds_value, bool lazy_eval) { bool created_node = false; assert(node); // follow down to last level if (depth < this->tree_depth) { unsigned int pos = computeChildIdx(key, this->tree_depth -1 - depth); if (!this->nodeChildExists(node, pos)) { // child does not exist, but maybe it's a pruned node? if (!this->nodeHasChildren(node) && !node_just_created ) { // current node does not have children AND it is not a new node // -> expand pruned node this->expandNode(node); } else { // not a pruned node, create requested child this->createNodeChild(node, pos); created_node = true; } } if (lazy_eval) return setNodeValueRecurs(this->getNodeChild(node, pos), created_node, key, depth+1, log_odds_value, lazy_eval); else { NODE* retval = setNodeValueRecurs(this->getNodeChild(node, pos), created_node, key, depth+1, log_odds_value, lazy_eval); // prune node if possible, otherwise set own probability // note: combining both did not lead to a speedup! if (this->pruneNode(node)){ // return pointer to current parent (pruned), the just updated node no longer exists retval = node; } else{ node->updateOccupancyChildren(); } return retval; } } // at last level, update node, end of recursion else { if (use_change_detection) { bool occBefore = this->isNodeOccupied(node); node->setLogOdds(log_odds_value); if (node_just_created){ // new node changed_keys.insert(std::pair<OcTreeKey,bool>(key, true)); } else if (occBefore != this->isNodeOccupied(node)) { // occupancy changed, track it KeyBoolMap::iterator it = changed_keys.find(key); if (it == changed_keys.end()) changed_keys.insert(std::pair<OcTreeKey,bool>(key, false)); else if (it->second == false) changed_keys.erase(it); } } else { node->setLogOdds(log_odds_value); } return node; } } template <class NODE> void OccupancyOcTreeBase<NODE>::updateInnerOccupancy(){ if (this->root) this->updateInnerOccupancyRecurs(this->root, 0); } template <class NODE> void OccupancyOcTreeBase<NODE>::updateInnerOccupancyRecurs(NODE* node, unsigned int depth){ assert(node); // only recurse and update for inner nodes: if (this->nodeHasChildren(node)){ // return early for last level: if (depth < this->tree_depth){ for (unsigned int i=0; i<8; i++) { if (this->nodeChildExists(node, i)) { updateInnerOccupancyRecurs(this->getNodeChild(node, i), depth+1); } } } node->updateOccupancyChildren(); } } template <class NODE> void OccupancyOcTreeBase<NODE>::toMaxLikelihood() { if (this->root == NULL) return; // convert bottom up for (unsigned int depth=this->tree_depth; depth>0; depth--) { toMaxLikelihoodRecurs(this->root, 0, depth); } // convert root nodeToMaxLikelihood(this->root); } template <class NODE> void OccupancyOcTreeBase<NODE>::toMaxLikelihoodRecurs(NODE* node, unsigned int depth, unsigned int max_depth) { assert(node); if (depth < max_depth) { for (unsigned int i=0; i<8; i++) { if (this->nodeChildExists(node, i)) { toMaxLikelihoodRecurs(this->getNodeChild(node, i), depth+1, max_depth); } } } else { // max level reached nodeToMaxLikelihood(node); } } template <class NODE> bool OccupancyOcTreeBase<NODE>::getNormals(const point3d& point, std::vector<point3d>& normals, bool unknownStatus) const { normals.clear(); OcTreeKey init_key; if ( !OcTreeBaseImpl<NODE,AbstractOccupancyOcTree>::coordToKeyChecked(point, init_key) ) { OCTOMAP_WARNING_STR("Voxel out of bounds"); return false; } // OCTOMAP_WARNING("Normal for %f, %f, %f\n", point.x(), point.y(), point.z()); int vertex_values[8]; OcTreeKey current_key; NODE* current_node; // There is 8 neighbouring sets // The current cube can be at any of the 8 vertex int x_index[4][4] = {{1, 1, 0, 0}, {1, 1, 0, 0}, {0, 0 -1, -1}, {0, 0 -1, -1}}; int y_index[4][4] = {{1, 0, 0, 1}, {0, -1, -1, 0}, {0, -1, -1, 0}, {1, 0, 0, 1}}; int z_index[2][2] = {{0, 1}, {-1, 0}}; // Iterate over the 8 neighboring sets for(int m = 0; m < 2; ++m){ for(int l = 0; l < 4; ++l){ int k = 0; // Iterate over the cubes for(int j = 0; j < 2; ++j){ for(int i = 0; i < 4; ++i){ current_key[0] = init_key[0] + x_index[l][i]; current_key[1] = init_key[1] + y_index[l][i]; current_key[2] = init_key[2] + z_index[m][j]; current_node = this->search(current_key); if(current_node){ vertex_values[k] = this->isNodeOccupied(current_node); // point3d coord = this->keyToCoord(current_key); // OCTOMAP_WARNING_STR("vertex " << k << " at " << coord << "; value " << vertex_values[k]); }else{ // Occupancy of unknown cells vertex_values[k] = unknownStatus; } ++k; } } int cube_index = 0; if (vertex_values[0]) cube_index |= 1; if (vertex_values[1]) cube_index |= 2; if (vertex_values[2]) cube_index |= 4; if (vertex_values[3]) cube_index |= 8; if (vertex_values[4]) cube_index |= 16; if (vertex_values[5]) cube_index |= 32; if (vertex_values[6]) cube_index |= 64; if (vertex_values[7]) cube_index |= 128; // OCTOMAP_WARNING_STR("cubde_index: " << cube_index); // All vertices are occupied or free resulting in no normal if (edgeTable[cube_index] == 0) return true; // No interpolation is done yet, we use vertexList in <MCTables.h>. for(int i = 0; triTable[cube_index][i] != -1; i += 3){ point3d p1 = vertexList[triTable[cube_index][i ]]; point3d p2 = vertexList[triTable[cube_index][i+1]]; point3d p3 = vertexList[triTable[cube_index][i+2]]; point3d v1 = p2 - p1; point3d v2 = p3 - p1; // OCTOMAP_WARNING("Vertex p1 %f, %f, %f\n", p1.x(), p1.y(), p1.z()); // OCTOMAP_WARNING("Vertex p2 %f, %f, %f\n", p2.x(), p2.y(), p2.z()); // OCTOMAP_WARNING("Vertex p3 %f, %f, %f\n", p3.x(), p3.y(), p3.z()); // Right hand side cross product to retrieve the normal in the good // direction (pointing to the free nodes). normals.push_back(v1.cross(v2).normalize()); } } } return true; } template <class NODE> bool OccupancyOcTreeBase<NODE>::castRay(const point3d& origin, const point3d& directionP, point3d& end, bool ignoreUnknown, double maxRange) const { /// ---------- see OcTreeBase::computeRayKeys ----------- // Initialization phase ------------------------------------------------------- OcTreeKey current_key; if ( !OcTreeBaseImpl<NODE,AbstractOccupancyOcTree>::coordToKeyChecked(origin, current_key) ) { OCTOMAP_WARNING_STR("Coordinates out of bounds during ray casting"); return false; } NODE* startingNode = this->search(current_key); if (startingNode){ if (this->isNodeOccupied(startingNode)){ // Occupied node found at origin // (need to convert from key, since origin does not need to be a voxel center) end = this->keyToCoord(current_key); return true; } } else if(!ignoreUnknown){ end = this->keyToCoord(current_key); return false; } point3d direction = directionP.normalized(); bool max_range_set = (maxRange > 0.0); int step[3]; double tMax[3]; double tDelta[3]; for(unsigned int i=0; i < 3; ++i) { // compute step direction if (direction(i) > 0.0) step[i] = 1; else if (direction(i) < 0.0) step[i] = -1; else step[i] = 0; // compute tMax, tDelta if (step[i] != 0) { // corner point of voxel (in direction of ray) double voxelBorder = this->keyToCoord(current_key[i]); voxelBorder += double(step[i] * this->resolution * 0.5); tMax[i] = ( voxelBorder - origin(i) ) / direction(i); tDelta[i] = this->resolution / fabs( direction(i) ); } else { tMax[i] = std::numeric_limits<double>::max(); tDelta[i] = std::numeric_limits<double>::max(); } } if (step[0] == 0 && step[1] == 0 && step[2] == 0){ OCTOMAP_ERROR("Raycasting in direction (0,0,0) is not possible!"); return false; } // for speedup: double maxrange_sq = maxRange *maxRange; // Incremental phase --------------------------------------------------------- bool done = false; while (!done) { unsigned int dim; // find minimum tMax: if (tMax[0] < tMax[1]){ if (tMax[0] < tMax[2]) dim = 0; else dim = 2; } else { if (tMax[1] < tMax[2]) dim = 1; else dim = 2; } // check for overflow: if ((step[dim] < 0 && current_key[dim] == 0) || (step[dim] > 0 && current_key[dim] == 2* this->tree_max_val-1)) { OCTOMAP_WARNING("Coordinate hit bounds in dim %d, aborting raycast\n", dim); // return border point nevertheless: end = this->keyToCoord(current_key); return false; } // advance in direction "dim" current_key[dim] += step[dim]; tMax[dim] += tDelta[dim]; // generate world coords from key end = this->keyToCoord(current_key); // check for maxrange: if (max_range_set){ double dist_from_origin_sq(0.0); for (unsigned int j = 0; j < 3; j++) { dist_from_origin_sq += ((end(j) - origin(j)) * (end(j) - origin(j))); } if (dist_from_origin_sq > maxrange_sq) return false; } NODE* currentNode = this->search(current_key); if (currentNode){ if (this->isNodeOccupied(currentNode)) { done = true; break; } // otherwise: node is free and valid, raycasting continues } else if (!ignoreUnknown){ // no node found, this usually means we are in "unknown" areas return false; } } // end while return true; } template <class NODE> bool OccupancyOcTreeBase<NODE>::getRayIntersection (const point3d& origin, const point3d& direction, const point3d& center, point3d& intersection, double delta/*=0.0*/) const { // We only need three normals for the six planes octomap::point3d normalX(1, 0, 0); octomap::point3d normalY(0, 1, 0); octomap::point3d normalZ(0, 0, 1); // One point on each plane, let them be the center for simplicity octomap::point3d pointXNeg(center(0) - float(this->resolution / 2.0), center(1), center(2)); octomap::point3d pointXPos(center(0) + float(this->resolution / 2.0), center(1), center(2)); octomap::point3d pointYNeg(center(0), center(1) - float(this->resolution / 2.0), center(2)); octomap::point3d pointYPos(center(0), center(1) + float(this->resolution / 2.0), center(2)); octomap::point3d pointZNeg(center(0), center(1), center(2) - float(this->resolution / 2.0)); octomap::point3d pointZPos(center(0), center(1), center(2) + float(this->resolution / 2.0)); double lineDotNormal = 0.0; double d = 0.0; double outD = std::numeric_limits<double>::max(); octomap::point3d intersect; bool found = false; // Find the intersection (if any) with each place // Line dot normal will be zero if they are parallel, in which case no intersection can be the entry one // if there is an intersection does it occur in the bounded plane of the voxel // if yes keep only the closest (smallest distance to sensor origin). if((lineDotNormal = normalX.dot(direction)) != 0.0){ // Ensure lineDotNormal is non-zero (assign and test) d = (pointXNeg - origin).dot(normalX) / lineDotNormal; intersect = direction * float(d) + origin; if(!(intersect(1) < (pointYNeg(1) - 1e-6) || intersect(1) > (pointYPos(1) + 1e-6) || intersect(2) < (pointZNeg(2) - 1e-6) || intersect(2) > (pointZPos(2) + 1e-6))){ outD = std::min(outD, d); found = true; } d = (pointXPos - origin).dot(normalX) / lineDotNormal; intersect = direction * float(d) + origin; if(!(intersect(1) < (pointYNeg(1) - 1e-6) || intersect(1) > (pointYPos(1) + 1e-6) || intersect(2) < (pointZNeg(2) - 1e-6) || intersect(2) > (pointZPos(2) + 1e-6))){ outD = std::min(outD, d); found = true; } } if((lineDotNormal = normalY.dot(direction)) != 0.0){ // Ensure lineDotNormal is non-zero (assign and test) d = (pointYNeg - origin).dot(normalY) / lineDotNormal; intersect = direction * float(d) + origin; if(!(intersect(0) < (pointXNeg(0) - 1e-6) || intersect(0) > (pointXPos(0) + 1e-6) || intersect(2) < (pointZNeg(2) - 1e-6) || intersect(2) > (pointZPos(2) + 1e-6))){ outD = std::min(outD, d); found = true; } d = (pointYPos - origin).dot(normalY) / lineDotNormal; intersect = direction * float(d) + origin; if(!(intersect(0) < (pointXNeg(0) - 1e-6) || intersect(0) > (pointXPos(0) + 1e-6) || intersect(2) < (pointZNeg(2) - 1e-6) || intersect(2) > (pointZPos(2) + 1e-6))){ outD = std::min(outD, d); found = true; } } if((lineDotNormal = normalZ.dot(direction)) != 0.0){ // Ensure lineDotNormal is non-zero (assign and test) d = (pointZNeg - origin).dot(normalZ) / lineDotNormal; intersect = direction * float(d) + origin; if(!(intersect(0) < (pointXNeg(0) - 1e-6) || intersect(0) > (pointXPos(0) + 1e-6) || intersect(1) < (pointYNeg(1) - 1e-6) || intersect(1) > (pointYPos(1) + 1e-6))){ outD = std::min(outD, d); found = true; } d = (pointZPos - origin).dot(normalZ) / lineDotNormal; intersect = direction * float(d) + origin; if(!(intersect(0) < (pointXNeg(0) - 1e-6) || intersect(0) > (pointXPos(0) + 1e-6) || intersect(1) < (pointYNeg(1) - 1e-6) || intersect(1) > (pointYPos(1) + 1e-6))){ outD = std::min(outD, d); found = true; } } // Substract (add) a fraction to ensure no ambiguity on the starting voxel // Don't start on a boundary. if(found) intersection = direction * float(outD + delta) + origin; return found; } template <class NODE> inline bool OccupancyOcTreeBase<NODE>::integrateMissOnRay(const point3d& origin, const point3d& end, bool lazy_eval) { if (!this->computeRayKeys(origin, end, this->keyrays.at(0))) { return false; } for(KeyRay::iterator it=this->keyrays[0].begin(); it != this->keyrays[0].end(); it++) { updateNode(*it, false, lazy_eval); // insert freespace measurement } return true; } template <class NODE> bool OccupancyOcTreeBase<NODE>::insertRay(const point3d& origin, const point3d& end, double maxrange, bool lazy_eval) { // cut ray at maxrange if ((maxrange > 0) && ((end - origin).norm () > maxrange)) { point3d direction = (end - origin).normalized (); point3d new_end = origin + direction * (float) maxrange; return integrateMissOnRay(origin, new_end,lazy_eval); } // insert complete ray else { if (!integrateMissOnRay(origin, end,lazy_eval)) return false; updateNode(end, true, lazy_eval); // insert hit cell return true; } } template <class NODE> void OccupancyOcTreeBase<NODE>::setBBXMin (const point3d& min) { bbx_min = min; if (!this->coordToKeyChecked(bbx_min, bbx_min_key)) { OCTOMAP_ERROR("ERROR while generating bbx min key.\n"); } } template <class NODE> void OccupancyOcTreeBase<NODE>::setBBXMax (const point3d& max) { bbx_max = max; if (!this->coordToKeyChecked(bbx_max, bbx_max_key)) { OCTOMAP_ERROR("ERROR while generating bbx max key.\n"); } } template <class NODE> bool OccupancyOcTreeBase<NODE>::inBBX(const point3d& p) const { return ((p.x() >= bbx_min.x()) && (p.y() >= bbx_min.y()) && (p.z() >= bbx_min.z()) && (p.x() <= bbx_max.x()) && (p.y() <= bbx_max.y()) && (p.z() <= bbx_max.z()) ); } template <class NODE> bool OccupancyOcTreeBase<NODE>::inBBX(const OcTreeKey& key) const { return ((key[0] >= bbx_min_key[0]) && (key[1] >= bbx_min_key[1]) && (key[2] >= bbx_min_key[2]) && (key[0] <= bbx_max_key[0]) && (key[1] <= bbx_max_key[1]) && (key[2] <= bbx_max_key[2]) ); } template <class NODE> point3d OccupancyOcTreeBase<NODE>::getBBXBounds () const { octomap::point3d obj_bounds = (bbx_max - bbx_min); obj_bounds /= 2.; return obj_bounds; } template <class NODE> point3d OccupancyOcTreeBase<NODE>::getBBXCenter () const { octomap::point3d obj_bounds = (bbx_max - bbx_min); obj_bounds /= 2.; return bbx_min + obj_bounds; } // -- I/O ----------------------------------------- template <class NODE> std::istream& OccupancyOcTreeBase<NODE>::readBinaryData(std::istream &s){ // tree needs to be newly created or cleared externally if (this->root) { OCTOMAP_ERROR_STR("Trying to read into an existing tree."); return s; } this->root = new NODE(); this->readBinaryNode(s, this->root); this->size_changed = true; this->tree_size = OcTreeBaseImpl<NODE,AbstractOccupancyOcTree>::calcNumNodes(); // compute number of nodes return s; } template <class NODE> std::ostream& OccupancyOcTreeBase<NODE>::writeBinaryData(std::ostream &s) const{ OCTOMAP_DEBUG("Writing %zu nodes to output stream...", this->size()); if (this->root) this->writeBinaryNode(s, this->root); return s; } template <class NODE> std::istream& OccupancyOcTreeBase<NODE>::readBinaryNode(std::istream &s, NODE* node){ assert(node); char child1to4_char; char child5to8_char; s.read((char*)&child1to4_char, sizeof(char)); s.read((char*)&child5to8_char, sizeof(char)); std::bitset<8> child1to4 ((unsigned long long) child1to4_char); std::bitset<8> child5to8 ((unsigned long long) child5to8_char); // std::cout << "read: " // << child1to4.to_string<char,std::char_traits<char>,std::allocator<char> >() << " " // << child5to8.to_string<char,std::char_traits<char>,std::allocator<char> >() << std::endl; // inner nodes default to occupied node->setLogOdds(this->clamping_thres_max); for (unsigned int i=0; i<4; i++) { if ((child1to4[i*2] == 1) && (child1to4[i*2+1] == 0)) { // child is free leaf this->createNodeChild(node, i); this->getNodeChild(node, i)->setLogOdds(this->clamping_thres_min); } else if ((child1to4[i*2] == 0) && (child1to4[i*2+1] == 1)) { // child is occupied leaf this->createNodeChild(node, i); this->getNodeChild(node, i)->setLogOdds(this->clamping_thres_max); } else if ((child1to4[i*2] == 1) && (child1to4[i*2+1] == 1)) { // child has children this->createNodeChild(node, i); this->getNodeChild(node, i)->setLogOdds(-200.); // child is unkown, we leave it uninitialized } } for (unsigned int i=0; i<4; i++) { if ((child5to8[i*2] == 1) && (child5to8[i*2+1] == 0)) { // child is free leaf this->createNodeChild(node, i+4); this->getNodeChild(node, i+4)->setLogOdds(this->clamping_thres_min); } else if ((child5to8[i*2] == 0) && (child5to8[i*2+1] == 1)) { // child is occupied leaf this->createNodeChild(node, i+4); this->getNodeChild(node, i+4)->setLogOdds(this->clamping_thres_max); } else if ((child5to8[i*2] == 1) && (child5to8[i*2+1] == 1)) { // child has children this->createNodeChild(node, i+4); this->getNodeChild(node, i+4)->setLogOdds(-200.); // set occupancy when all children have been read } // child is unkown, we leave it uninitialized } // read children's children and set the label for (unsigned int i=0; i<8; i++) { if (this->nodeChildExists(node, i)) { NODE* child = this->getNodeChild(node, i); if (fabs(child->getLogOdds() + 200.)<1e-3) { readBinaryNode(s, child); child->setLogOdds(child->getMaxChildLogOdds()); } } // end if child exists } // end for children return s; } template <class NODE> std::ostream& OccupancyOcTreeBase<NODE>::writeBinaryNode(std::ostream &s, const NODE* node) const{ assert(node); // 2 bits for each children, 8 children per node -> 16 bits std::bitset<8> child1to4; std::bitset<8> child5to8; // 10 : child is free node // 01 : child is occupied node // 00 : child is unkown node // 11 : child has children // speedup: only set bits to 1, rest is init with 0 anyway, // can be one logic expression per bit for (unsigned int i=0; i<4; i++) { if (this->nodeChildExists(node, i)) { const NODE* child = this->getNodeChild(node, i); if (this->nodeHasChildren(child)) { child1to4[i*2] = 1; child1to4[i*2+1] = 1; } else if (this->isNodeOccupied(child)) { child1to4[i*2] = 0; child1to4[i*2+1] = 1; } else { child1to4[i*2] = 1; child1to4[i*2+1] = 0; } } else { child1to4[i*2] = 0; child1to4[i*2+1] = 0; } } for (unsigned int i=0; i<4; i++) { if (this->nodeChildExists(node, i+4)) { const NODE* child = this->getNodeChild(node, i+4); if (this->nodeHasChildren(child)) { child5to8[i*2] = 1; child5to8[i*2+1] = 1; } else if (this->isNodeOccupied(child)) { child5to8[i*2] = 0; child5to8[i*2+1] = 1; } else { child5to8[i*2] = 1; child5to8[i*2+1] = 0; } } else { child5to8[i*2] = 0; child5to8[i*2+1] = 0; } } // std::cout << "wrote: " // << child1to4.to_string<char,std::char_traits<char>,std::allocator<char> >() << " " // << child5to8.to_string<char,std::char_traits<char>,std::allocator<char> >() << std::endl; char child1to4_char = (char) child1to4.to_ulong(); char child5to8_char = (char) child5to8.to_ulong(); s.write((char*)&child1to4_char, sizeof(char)); s.write((char*)&child5to8_char, sizeof(char)); // write children's children for (unsigned int i=0; i<8; i++) { if (this->nodeChildExists(node, i)) { const NODE* child = this->getNodeChild(node, i); if (this->nodeHasChildren(child)) { writeBinaryNode(s, child); } } } return s; } //-- Occupancy queries on nodes: template <class NODE> void OccupancyOcTreeBase<NODE>::updateNodeLogOdds(NODE* occupancyNode, const float& update) const { occupancyNode->addValue(update); if (occupancyNode->getLogOdds() < this->clamping_thres_min) { occupancyNode->setLogOdds(this->clamping_thres_min); return; } if (occupancyNode->getLogOdds() > this->clamping_thres_max) { occupancyNode->setLogOdds(this->clamping_thres_max); } } template <class NODE> void OccupancyOcTreeBase<NODE>::integrateHit(NODE* occupancyNode) const { updateNodeLogOdds(occupancyNode, this->prob_hit_log); } template <class NODE> void OccupancyOcTreeBase<NODE>::integrateMiss(NODE* occupancyNode) const { updateNodeLogOdds(occupancyNode, this->prob_miss_log); } template <class NODE> void OccupancyOcTreeBase<NODE>::nodeToMaxLikelihood(NODE* occupancyNode) const{ if (this->isNodeOccupied(occupancyNode)) occupancyNode->setLogOdds(this->clamping_thres_max); else occupancyNode->setLogOdds(this->clamping_thres_min); } template <class NODE> void OccupancyOcTreeBase<NODE>::nodeToMaxLikelihood(NODE& occupancyNode) const{ if (this->isNodeOccupied(occupancyNode)) occupancyNode.setLogOdds(this->clamping_thres_max); else occupancyNode.setLogOdds(this->clamping_thres_min); } } // namespace
40,621
34.790308
148
hxx
octomap
octomap-master/octomap/include/octomap/Pointcloud.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMAP_POINTCLOUD_H #define OCTOMAP_POINTCLOUD_H #include <vector> #include <list> #include <octomap/octomap_types.h> namespace octomap { /** * A collection of 3D coordinates (point3d), which are regarded as endpoints of a * 3D laser scan. */ class Pointcloud { public: Pointcloud(); ~Pointcloud(); Pointcloud(const Pointcloud& other); Pointcloud(Pointcloud* other); size_t size() const { return points.size(); } void clear(); inline void reserve(size_t size) {points.reserve(size); } inline void push_back(float x, float y, float z) { points.push_back(point3d(x,y,z)); } inline void push_back(const point3d& p) { points.push_back(p); } inline void push_back(point3d* p) { points.push_back(*p); } /// Add points from other Pointcloud void push_back(const Pointcloud& other); /// Export the Pointcloud to a VRML file void writeVrml(std::string filename); /// Apply transform to each point void transform(pose6d transform); /// Rotate each point in pointcloud void rotate(double roll, double pitch, double yaw); /// Apply transform to each point, undo previous transforms void transformAbsolute(pose6d transform); /// Calculate bounding box of Pointcloud void calcBBX(point3d& lowerBound, point3d& upperBound) const; /// Crop Pointcloud to given bounding box void crop(point3d lowerBound, point3d upperBound); // removes any points closer than [thres] to (0,0,0) void minDist(double thres); void subSampleRandom(unsigned int num_samples, Pointcloud& sample_cloud); // iterators ------------------ typedef point3d_collection::iterator iterator; typedef point3d_collection::const_iterator const_iterator; iterator begin() { return points.begin(); } iterator end() { return points.end(); } const_iterator begin() const { return points.begin(); } const_iterator end() const { return points.end(); } point3d back() { return points.back(); } /// Returns a copy of the ith point in point cloud. /// Use operator[] for direct access to point reference. point3d getPoint(unsigned int i) const; // may return NULL inline const point3d& operator[] (size_t i) const { return points[i]; } inline point3d& operator[] (size_t i) { return points[i]; } // I/O methods std::istream& readBinary(std::istream &s); std::istream& read(std::istream &s); std::ostream& writeBinary(std::ostream &s) const; protected: pose6d current_inv_transform; point3d_collection points; }; } #endif
4,430
33.889764
83
h
octomap
octomap-master/octomap/include/octomap/ScanGraph.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMAP_SCANGRAPH_H #define OCTOMAP_SCANGRAPH_H #include <string> #include <math.h> #include "Pointcloud.h" #include "octomap_types.h" namespace octomap { class ScanGraph; /** * A 3D scan as Pointcloud, performed from a Pose6D. */ class ScanNode { public: ScanNode (Pointcloud* _scan, pose6d _pose, unsigned int _id) : scan(_scan), pose(_pose), id(_id) {} ScanNode () : scan(NULL) {} ~ScanNode(); bool operator == (const ScanNode& other) { return (id == other.id); } std::ostream& writeBinary(std::ostream &s) const; std::istream& readBinary(std::istream &s); std::ostream& writePoseASCII(std::ostream &s) const; std::istream& readPoseASCII(std::istream &s); Pointcloud* scan; pose6d pose; ///< 6D pose from which the scan was performed unsigned int id; }; /** * A connection between two \ref ScanNode "ScanNodes" */ class ScanEdge { public: ScanEdge(ScanNode* _first, ScanNode* _second, pose6d _constraint) : first(_first), second(_second), constraint(_constraint), weight(1.0) { } ScanEdge() {} bool operator == (const ScanEdge& other) { return ( (*first == *(other.first) ) && ( *second == *(other.second) ) ); } std::ostream& writeBinary(std::ostream &s) const; // a graph has to be given to recover ScanNode pointers std::istream& readBinary(std::istream &s, ScanGraph& graph); std::ostream& writeASCII(std::ostream &s) const; std::istream& readASCII(std::istream &s, ScanGraph& graph); ScanNode* first; ScanNode* second; pose6d constraint; double weight; }; /** * A ScanGraph is a collection of ScanNodes, connected by ScanEdges. * Each ScanNode contains a 3D scan performed from a pose. * */ class ScanGraph { public: ScanGraph() {}; ~ScanGraph(); /// Clears all nodes and edges, and will delete the corresponding objects void clear(); /** * Creates a new ScanNode in the graph from a Pointcloud. * * @param scan Pointer to a pointcloud to be added to the ScanGraph. * ScanGraph will delete the object when it's no longer needed, don't delete it yourself. * @param pose 6D pose of the origin of the Pointcloud * @return Pointer to the new node */ ScanNode* addNode(Pointcloud* scan, pose6d pose); /** * Creates an edge between two ScanNodes. * ScanGraph will delete the object when it's no longer needed, don't delete it yourself. * * @param first ScanNode * @param second ScanNode * @param constraint 6D transform between the two nodes * @return */ ScanEdge* addEdge(ScanNode* first, ScanNode* second, pose6d constraint); ScanEdge* addEdge(unsigned int first_id, unsigned int second_id); /// will return NULL if node was not found ScanNode* getNodeByID(unsigned int id); /// \return true when an edge between first_id and second_id exists bool edgeExists(unsigned int first_id, unsigned int second_id); /// Connect previously added ScanNode to the one before that void connectPrevious(); std::vector<unsigned int> getNeighborIDs(unsigned int id); std::vector<ScanEdge*> getOutEdges(ScanNode* node); // warning: constraints are reversed std::vector<ScanEdge*> getInEdges(ScanNode* node); void exportDot(std::string filename); /// Transform every scan according to its pose void transformScans(); /// Cut graph (all containing Pointclouds) to given BBX in global coords void crop(point3d lowerBound, point3d upperBound); /// Cut Pointclouds to given BBX in local coords void cropEachScan(point3d lowerBound, point3d upperBound); typedef std::vector<ScanNode*>::iterator iterator; typedef std::vector<ScanNode*>::const_iterator const_iterator; iterator begin() { return nodes.begin(); } iterator end() { return nodes.end(); } const_iterator begin() const { return nodes.begin(); } const_iterator end() const { return nodes.end(); } size_t size() const { return nodes.size(); } size_t getNumPoints(unsigned int max_id = -1) const; typedef std::vector<ScanEdge*>::iterator edge_iterator; typedef std::vector<ScanEdge*>::const_iterator const_edge_iterator; edge_iterator edges_begin() { return edges.begin(); } edge_iterator edges_end() { return edges.end(); } const_edge_iterator edges_begin() const { return edges.begin(); } const_edge_iterator edges_end() const { return edges.end(); } std::ostream& writeBinary(std::ostream &s) const; std::istream& readBinary(std::ifstream &s); bool writeBinary(const std::string& filename) const; bool readBinary(const std::string& filename); std::ostream& writeEdgesASCII(std::ostream &s) const; std::istream& readEdgesASCII(std::istream &s); std::ostream& writeNodePosesASCII(std::ostream &s) const; std::istream& readNodePosesASCII(std::istream &s); /** * Reads in a ScanGraph from a "plain" ASCII file of the form * NODE x y z R P Y * x y z * x y z * x y z * NODE x y z R P Y * x y z * * Lines starting with the NODE keyword contain the 6D pose of a scan node, * all 3D point following until the next NODE keyword (or end of file) are * inserted into that scan node as pointcloud in its local coordinate frame * * @param s input stream to read from * @return read stream */ std::istream& readPlainASCII(std::istream& s); void readPlainASCII(const std::string& filename); protected: std::vector<ScanNode*> nodes; std::vector<ScanEdge*> edges; }; } #endif
7,500
31.331897
100
h
octomap
octomap-master/octomap/include/octomap/octomap.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "octomap_types.h" #include "Pointcloud.h" #include "ScanGraph.h" #include "OcTree.h"
1,875
47.102564
78
h
octomap
octomap-master/octomap/include/octomap/octomap_deprecated.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMAP_DEPRECATED_H #define OCTOMAP_DEPRECATED_H // define multi-platform deprecation mechanism #ifndef OCTOMAP_DEPRECATED #ifdef __GNUC__ #define OCTOMAP_DEPRECATED(func) func __attribute__ ((deprecated)) #elif defined(_MSC_VER) #define OCTOMAP_DEPRECATED(func) __declspec(deprecated) func #else #pragma message("WARNING: You need to implement OCTOMAP_DEPRECATED for this compiler") #define OCTOMAP_DEPRECATED(func) func #endif #endif #endif
2,258
44.18
90
h
octomap
octomap-master/octomap/include/octomap/octomap_timing.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMAP_TIMING_H_ #define OCTOMAP_TIMING_H_ #ifdef _MSC_VER // MS compilers #include <sys/timeb.h> #include <sys/types.h> #include <winsock.h> void gettimeofday(struct timeval* t, void* timezone) { struct _timeb timebuffer; _ftime64_s( &timebuffer ); t->tv_sec= (long) timebuffer.time; t->tv_usec=1000*timebuffer.millitm; } #else // GCC and minGW #include <sys/time.h> #endif #endif
2,205
39.109091
78
h
octomap
octomap-master/octomap/include/octomap/octomap_types.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMAP_TYPES_H #define OCTOMAP_TYPES_H #include <stdio.h> #include <vector> #include <list> #include <inttypes.h> #include <octomap/math/Vector3.h> #include <octomap/math/Pose6D.h> #include <octomap/octomap_deprecated.h> namespace octomap { ///Use Vector3 (float precision) as a point3d in octomap typedef octomath::Vector3 point3d; /// Use our Pose6D (float precision) as pose6d in octomap typedef octomath::Pose6D pose6d; typedef std::vector<octomath::Vector3> point3d_collection; typedef std::list<octomath::Vector3> point3d_list; /// A voxel defined by its center point3d and its side length typedef std::pair<point3d, double> OcTreeVolume; } // no debug output if not in debug mode: #ifdef NDEBUG #ifndef OCTOMAP_NODEBUGOUT #define OCTOMAP_NODEBUGOUT #endif #endif #ifdef OCTOMAP_NODEBUGOUT #define OCTOMAP_DEBUG(...) (void)0 #define OCTOMAP_DEBUG_STR(...) (void)0 #else #define OCTOMAP_DEBUG(...) fprintf(stderr, __VA_ARGS__), fflush(stderr) #define OCTOMAP_DEBUG_STR(args) std::cerr << args << std::endl #endif #define OCTOMAP_WARNING(...) fprintf(stderr, "WARNING: "), fprintf(stderr, __VA_ARGS__), fflush(stderr) #define OCTOMAP_WARNING_STR(args) std::cerr << "WARNING: " << args << std::endl #define OCTOMAP_ERROR(...) fprintf(stderr, "ERROR: "), fprintf(stderr, __VA_ARGS__), fflush(stderr) #define OCTOMAP_ERROR_STR(args) std::cerr << "ERROR: " << args << std::endl #endif
3,315
39.439024
110
h
octomap
octomap-master/octomap/include/octomap/octomap_utils.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMAP_UTILS_H_ #define OCTOMAP_UTILS_H_ #include <math.h> namespace octomap{ /// compute log-odds from probability: inline float logodds(double probability){ return (float) log(probability/(1-probability)); } /// compute probability from logodds: inline double probability(double logodds){ return 1. - ( 1. / (1. + exp(logodds))); } } #endif /* OCTOMAP_UTILS_H_ */
2,183
38
78
h
octomap
octomap-master/octomap/include/octomap/math/Pose6D.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMATH_POSE6D_H #define OCTOMATH_POSE6D_H #include "Vector3.h" #include "Quaternion.h" namespace octomath { /*! * \brief This class represents a tree-dimensional pose of an object * * The tree-dimensional pose is represented by a three-dimensional * translation vector representing the position of the object and * a Quaternion representing the attitude of the object */ class Pose6D { public: Pose6D(); ~Pose6D(); /*! * \brief Constructor * * Constructs a pose from given translation and rotation. */ Pose6D(const Vector3& trans, const Quaternion& rot); /*! * \brief Constructor * * Constructs a pose from a translation represented by * its x, y, z-values and a rotation represented by its * Tait-Bryan angles roll, pitch, and yaw */ Pose6D(float x, float y, float z, double roll, double pitch, double yaw); Pose6D(const Pose6D& other); Pose6D& operator= (const Pose6D& other); bool operator==(const Pose6D& other) const; bool operator!=(const Pose6D& other) const; /*! * \brief Translational component * * @return the translational component of this pose */ inline Vector3& trans() { return translation; } /*! * \brief Rotational component * * @return the rotational component of this pose */ inline Quaternion& rot() { return rotation; } /*! * \brief Translational component * * @return the translational component of this pose */ const Vector3& trans() const { return translation; } /*! * \brief Rotational component * @return the rotational component of this pose */ const Quaternion& rot() const { return rotation; } inline float& x() { return translation(0); } inline float& y() { return translation(1); } inline float& z() { return translation(2); } inline const float& x() const { return translation(0); } inline const float& y() const { return translation(1); } inline const float& z() const { return translation(2); } inline double roll() const {return (rotation.toEuler())(0); } inline double pitch() const {return (rotation.toEuler())(1); } inline double yaw() const {return (rotation.toEuler())(2); } /*! * \brief Transformation of a vector * * Transforms the vector v by the transformation which is * specified by this. * @return the vector which is translated by the translation of * this and afterwards rotated by the rotation of this. */ Vector3 transform (const Vector3 &v) const; /*! * \brief Inversion * * Inverts the coordinate transformation represented by this pose * @return a copy of this pose inverted */ Pose6D inv() const; /*! * \brief Inversion * * Inverts the coordinate transformation represented by this pose * @return a reference to this pose */ Pose6D& inv_IP(); /*! * \brief Concatenation * * Concatenates the coordinate transformations represented * by this and p. * @return this * p (applies first this, then p) */ Pose6D operator* (const Pose6D &p) const; /*! * \brief In place concatenation * * Concatenates p to this Pose6D. * @return this which results from first moving by this and * afterwards by p */ const Pose6D& operator*= (const Pose6D &p); /*! * \brief Translational distance * * @return the translational (euclidian) distance to p */ double distance(const Pose6D &other) const; /*! * \brief Translational length * * @return the translational (euclidian) length of the translation * vector of this Pose6D */ double transLength() const; /*! * \brief Output operator * * Output to stream in a format which can be parsed using read(). */ std::ostream& write(std::ostream &s) const; /*! * \brief Input operator * * Parsing from stream which was written by write(). */ std::istream& read(std::istream &s); /*! * \brief Binary output operator * * Output to stream in a binary format which can be parsed using readBinary(). */ std::ostream& writeBinary(std::ostream &s) const; /*! * \brief Binary input operator * * Parsing from binary stream which was written by writeBinary(). */ std::istream& readBinary(std::istream &s); protected: Vector3 translation; Quaternion rotation; }; //! user friendly output in format (x y z, u x y z) which is (translation, rotation) std::ostream& operator<<(std::ostream& s, const Pose6D& p); } #endif
6,525
30.52657
86
h
octomap
octomap-master/octomap/include/octomap/math/Quaternion.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMATH_QUATERNION_H #define OCTOMATH_QUATERNION_H #include "Vector3.h" #include <iostream> #include <vector> namespace octomath { /*! * \brief This class represents a Quaternion. * * The Unit Quaternion is one possible representation of the * attitude of an object in tree-dimensional space. * * This Quaternion class is implemented according to Diebel, * James. Representing Attitude: Euler Angle, Unit Quaternions, and * Rotation Vectors. Stanford University. 2006. - Technical Report. */ class Quaternion { public: /*! * \brief Default constructor * * Constructs the (1,0,0,0) Unit Quaternion * representing the identity rotation. */ inline Quaternion() { u() = 1; x() = 0; y() = 0; z() = 0; } /*! * \brief Copy constructor */ Quaternion(const Quaternion& other); /*! * \brief Constructor * * Constructs a Quaternion from four single * values */ Quaternion(float u, float x, float y, float z); /*! * \brief Constructor * * @param other a vector containing euler angles */ Quaternion(const Vector3& other); /*! * \brief Constructor from Euler angles * * Constructs a Unit Quaternion from Euler angles / Tait Bryan * angles (in radians) according to the 1-2-3 convention. * @param roll phi/roll angle (rotation about x-axis) * @param pitch theta/pitch angle (rotation about y-axis) * @param yaw psi/yaw angle (rotation about z-axis) */ Quaternion(double roll, double pitch, double yaw); //! Constructs a Unit Quaternion from a rotation angle and axis. Quaternion(const Vector3& axis, double angle); /*! * \brief Conversion to Euler angles * * Converts the attitude represented by this to * Euler angles (roll, pitch, yaw). */ Vector3 toEuler() const; void toRotMatrix(std::vector <double>& rot_matrix_3_3) const; inline const float& operator() (unsigned int i) const { return data[i]; } inline float& operator() (unsigned int i) { return data[i]; } float norm () const; Quaternion normalized () const; Quaternion& normalize (); void operator/= (float x); Quaternion& operator= (const Quaternion& other); bool operator== (const Quaternion& other) const; /*! * \brief Quaternion multiplication * * Standard Quaternion multiplication which is not * commutative. * @return this * other */ Quaternion operator* (const Quaternion& other) const; /*! * \brief Quaternion multiplication with extended vector * * @return q * (0, v) */ Quaternion operator* (const Vector3 &v) const; /*! * \brief Quaternion multiplication with extended vector * * @return (0, v) * q */ friend Quaternion operator* (const Vector3 &v, const Quaternion &q); /*! * \brief Inversion * * @return A copy of this Quaterion inverted */ inline Quaternion inv() const { return Quaternion(u(), -x(), -y(), -z()); } /*! * \brief Inversion * * Inverts this Quaternion * @return a reference to this Quaternion */ Quaternion& inv_IP(); /*! * \brief Rotate a vector * * Rotates a vector to the body fixed coordinate * system according to the attitude represented by * this Quaternion. * @param v a vector represented in world coordinates * @return v represented in body-fixed coordinates */ Vector3 rotate(const Vector3 &v) const; inline float& u() { return data[0]; } inline float& x() { return data[1]; } inline float& y() { return data[2]; } inline float& z() { return data[3]; } inline const float& u() const { return data[0]; } inline const float& x() const { return data[1]; } inline const float& y() const { return data[2]; } inline const float& z() const { return data[3]; } std::istream& read(std::istream &s); std::ostream& write(std::ostream &s) const; std::istream& readBinary(std::istream &s); std::ostream& writeBinary(std::ostream &s) const; protected: float data[4]; }; //! user friendly output in format (u x y z) std::ostream& operator<<(std::ostream& s, const Quaternion& q); } #endif
6,132
29.063725
80
h
octomap
octomap-master/octomap/include/octomap/math/Utils.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMATH_UTILS_H #define OCTOMATH_UTILS_H #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifndef M_PI_2 #define M_PI_2 1.570796326794896619 #endif #ifndef DEG2RAD #define DEG2RAD(x) ((x) * 0.01745329251994329575) #endif #ifndef RAD2DEG #define RAD2DEG(x) ((x) * 57.29577951308232087721) #endif #endif
2,106
35.964912
78
h
octomap
octomap-master/octomap/include/octomap/math/Vector3.h
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef OCTOMATH_VECTOR3_H #define OCTOMATH_VECTOR3_H #include <iostream> #include <math.h> namespace octomath { /*! * \brief This class represents a three-dimensional vector * * The three-dimensional vector can be used to represent a * translation in three-dimensional space or to represent the * attitude of an object using Euler angle. */ class Vector3 { public: /*! * \brief Default constructor */ Vector3 () { data[0] = data[1] = data[2] = 0.0; } /*! * \brief Copy constructor * * @param other a vector of dimension 3 */ Vector3 (const Vector3& other) { data[0] = other(0); data[1] = other(1); data[2] = other(2); } /*! * \brief Constructor * * Constructs a three-dimensional vector from * three single values x, y, z or roll, pitch, yaw */ Vector3 (float x, float y, float z) { data[0] = x; data[1] = y; data[2] = z; } /* inline Eigen3::Vector3f getVector3f() const { return Eigen3::Vector3f(data[0], data[1], data[2]) ; } */ /* inline Eigen3::Vector4f& getVector4f() { return data; } */ /* inline Eigen3::Vector4f getVector4f() const { return data; } */ /*! * \brief Assignment operator * * @param other a vector of dimension 3 */ inline Vector3& operator= (const Vector3& other) { data[0] = other(0); data[1] = other(1); data[2] = other(2); return *this; } /*! * \brief Three-dimensional vector (cross) product * * Calculates the tree-dimensional cross product, which * represents the vector orthogonal to the plane defined * by this and other. * @return this x other */ inline Vector3 cross (const Vector3& other) const { //return (data.start<3> ().cross (other.data.start<3> ())); // \note should this be renamed? return Vector3(y()*other.z() - z()*other.y(), z()*other.x() - x()*other.z(), x()*other.y() - y()*other.x()); } /// dot product inline double dot (const Vector3& other) const { return x()*other.x() + y()*other.y() + z()*other.z(); } inline const float& operator() (unsigned int i) const { return data[i]; } inline float& operator() (unsigned int i) { return data[i]; } inline float& x() { return operator()(0); } inline float& y() { return operator()(1); } inline float& z() { return operator()(2); } inline const float& x() const { return operator()(0); } inline const float& y() const { return operator()(1); } inline const float& z() const { return operator()(2); } inline float& roll() { return operator()(0); } inline float& pitch() { return operator()(1); } inline float& yaw() { return operator()(2); } inline const float& roll() const { return operator()(0); } inline const float& pitch() const { return operator()(1); } inline const float& yaw() const { return operator()(2); } inline Vector3 operator- () const { Vector3 result; result(0) = -data[0]; result(1) = -data[1]; result(2) = -data[2]; return result; } inline Vector3 operator+ (const Vector3 &other) const { Vector3 result(*this); result(0) += other(0); result(1) += other(1); result(2) += other(2); return result; } inline Vector3 operator* (float x) const { Vector3 result(*this); result(0) *= x; result(1) *= x; result(2) *= x; return result; } inline Vector3 operator- (const Vector3 &other) const { Vector3 result(*this); result(0) -= other(0); result(1) -= other(1); result(2) -= other(2); return result; } inline void operator+= (const Vector3 &other) { data[0] += other(0); data[1] += other(1); data[2] += other(2); } inline void operator-= (const Vector3& other) { data[0] -= other(0); data[1] -= other(1); data[2] -= other(2); } inline void operator/= (float x) { data[0] /= x; data[1] /= x; data[2] /= x; } inline void operator*= (float x) { data[0] *= x; data[1] *= x; data[2] *= x; } inline bool operator== (const Vector3 &other) const { for (unsigned int i=0; i<3; i++) { if (operator()(i) != other(i)) return false; } return true; } /// @return length of the vector ("L2 norm") inline double norm () const { return sqrt(norm_sq()); } /// @return squared length ("L2 norm") of the vector inline double norm_sq() const { return (x()*x() + y()*y() + z()*z()); } /// normalizes this vector, so that it has norm=1.0 inline Vector3& normalize () { double len = norm(); if (len > 0) *this /= (float) len; return *this; } /// @return normalized vector, this one remains unchanged inline Vector3 normalized () const { Vector3 result(*this); result.normalize (); return result; } inline double angleTo(const Vector3& other) const { double dot_prod = this->dot(other); double len1 = this->norm(); double len2 = other.norm(); return acos(dot_prod / (len1*len2)); } inline double distance (const Vector3& other) const { double dist_x = x() - other.x(); double dist_y = y() - other.y(); double dist_z = z() - other.z(); return sqrt(dist_x*dist_x + dist_y*dist_y + dist_z*dist_z); } inline double distanceXY (const Vector3& other) const { double dist_x = x() - other.x(); double dist_y = y() - other.y(); return sqrt(dist_x*dist_x + dist_y*dist_y); } Vector3& rotate_IP (double roll, double pitch, double yaw); // void read (unsigned char * src, unsigned int size); std::istream& read(std::istream &s); std::ostream& write(std::ostream &s) const; std::istream& readBinary(std::istream &s); std::ostream& writeBinary(std::ostream &s) const; protected: float data[3]; }; //! user friendly output in format (x y z) std::ostream& operator<<(std::ostream& out, octomath::Vector3 const& v); } #endif
8,332
24.48318
110
h
octomap
octomap-master/octomap/src/AbstractOcTree.cpp
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <octomap/AbstractOcTree.h> #include <octomap/OcTree.h> #include <octomap/CountingOcTree.h> namespace octomap { AbstractOcTree::AbstractOcTree(){ } bool AbstractOcTree::write(const std::string& filename) const{ std::ofstream file(filename.c_str(), std::ios_base::out | std::ios_base::binary); if (!file.is_open()){ OCTOMAP_ERROR_STR("Filestream to "<< filename << " not open, nothing written."); return false; } else { // TODO: check is_good of finished stream, return write(file); file.close(); } return true; } bool AbstractOcTree::write(std::ostream &s) const{ s << fileHeader <<"\n# (feel free to add / change comments, but leave the first line as it is!)\n#\n"; s << "id " << getTreeType() << std::endl; s << "size "<< size() << std::endl; s << "res " << getResolution() << std::endl; s << "data" << std::endl; // write the actual data: writeData(s); // TODO: ret.val, checks stream? return true; } AbstractOcTree* AbstractOcTree::read(const std::string& filename){ std::ifstream file(filename.c_str(), std::ios_base::in |std::ios_base::binary); if (!file.is_open()){ OCTOMAP_ERROR_STR("Filestream to "<< filename << " not open, nothing read."); return NULL; } else { // TODO: check is_good of finished stream, warn? return read(file); } } AbstractOcTree* AbstractOcTree::read(std::istream &s){ // check if first line valid: std::string line; std::getline(s, line); if (line.compare(0,fileHeader.length(), fileHeader) !=0){ OCTOMAP_ERROR_STR("First line of OcTree file header does not start with \""<< fileHeader); return NULL; } std::string id; unsigned size; double res; if (!AbstractOcTree::readHeader(s, id, size, res)) return NULL; // otherwise: values are valid, stream is now at binary data! OCTOMAP_DEBUG_STR("Reading octree type "<< id); AbstractOcTree* tree = createTree(id, res); if (tree){ if (size > 0) tree->readData(s); OCTOMAP_DEBUG_STR("Done ("<< tree->size() << " nodes)"); } return tree; } bool AbstractOcTree::readHeader(std::istream& s, std::string& id, unsigned& size, double& res){ id = ""; size = 0; res = 0.0; std::string token; bool headerRead = false; while(s.good() && !headerRead) { s >> token; if (token == "data"){ headerRead = true; // skip forward until end of line: char c; do { c = s.get(); } while(s.good() && (c != '\n')); } else if (token.compare(0,1,"#") == 0){ // comment line, skip forward until end of line: char c; do { c = s.get(); } while(s.good() && (c != '\n')); } else if (token == "id") s >> id; else if (token == "res") s >> res; else if (token == "size") s >> size; else{ OCTOMAP_WARNING_STR("Unknown keyword in OcTree header, skipping: "<<token); char c; do { c = s.get(); } while(s.good() && (c != '\n')); } } if (!headerRead) { OCTOMAP_ERROR_STR("Error reading OcTree header"); return false; } if (id == "") { OCTOMAP_ERROR_STR("Error reading OcTree header, ID not set"); return false; } if (res <= 0.0) { OCTOMAP_ERROR_STR("Error reading OcTree header, res <= 0.0"); return false; } // fix deprecated id value: if (id == "1"){ OCTOMAP_WARNING("You are using a deprecated id \"%s\", changing to \"OcTree\" (you should update your file header)\n", id.c_str()); id = "OcTree"; } return true; } AbstractOcTree* AbstractOcTree::createTree(const std::string class_name, double res){ std::map<std::string, AbstractOcTree*>::iterator it = classIDMapping().find(class_name); if (it == classIDMapping().end()){ OCTOMAP_ERROR("Could not create octree of type %s, not in store in classIDMapping\n", class_name.c_str()); return NULL; } else { AbstractOcTree* tree = it->second->create(); tree->setResolution(res); return tree; } } std::map<std::string, AbstractOcTree*>& AbstractOcTree::classIDMapping(){ // we will "leak" the memory of the map and all trees until program exits, // but this ensures all static objects are there as long as needed // http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.15 static std::map<std::string, AbstractOcTree*>* map = new std::map<std::string, AbstractOcTree*>(); return *map; } void AbstractOcTree::registerTreeType(AbstractOcTree* tree){ classIDMapping()[tree->getTreeType()] = tree; } const std::string AbstractOcTree::fileHeader = "# Octomap OcTree file"; }
6,655
30.396226
137
cpp
octomap
octomap-master/octomap/src/AbstractOccupancyOcTree.cpp
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <octomap/AbstractOccupancyOcTree.h> #include <octomap/octomap_types.h> namespace octomap { AbstractOccupancyOcTree::AbstractOccupancyOcTree(){ // some sane default values: setOccupancyThres(0.5); // = 0.0 in logodds setProbHit(0.7); // = 0.85 in logodds setProbMiss(0.4); // = -0.4 in logodds setClampingThresMin(0.1192); // = -2 in log odds setClampingThresMax(0.971); // = 3.5 in log odds } bool AbstractOccupancyOcTree::writeBinary(const std::string& filename){ std::ofstream binary_outfile( filename.c_str(), std::ios_base::binary); if (!binary_outfile.is_open()){ OCTOMAP_ERROR_STR("Filestream to "<< filename << " not open, nothing written."); return false; } return writeBinary(binary_outfile); } bool AbstractOccupancyOcTree::writeBinaryConst(const std::string& filename) const{ std::ofstream binary_outfile( filename.c_str(), std::ios_base::binary); if (!binary_outfile.is_open()){ OCTOMAP_ERROR_STR("Filestream to "<< filename << " not open, nothing written."); return false; } writeBinaryConst(binary_outfile); binary_outfile.close(); return true; } bool AbstractOccupancyOcTree::writeBinary(std::ostream &s){ // convert to max likelihood first, this makes efficient pruning on binary data possible this->toMaxLikelihood(); this->prune(); return writeBinaryConst(s); } bool AbstractOccupancyOcTree::writeBinaryConst(std::ostream &s) const{ // write new header first: s << binaryFileHeader <<"\n# (feel free to add / change comments, but leave the first line as it is!)\n#\n"; s << "id " << this->getTreeType() << std::endl; s << "size "<< this->size() << std::endl; s << "res " << this->getResolution() << std::endl; s << "data" << std::endl; writeBinaryData(s); if (s.good()){ OCTOMAP_DEBUG(" done.\n"); return true; } else { OCTOMAP_WARNING_STR("Output stream not \"good\" after writing tree"); return false; } } bool AbstractOccupancyOcTree::readBinaryLegacyHeader(std::istream &s, unsigned int& size, double& res) { if (!s.good()){ OCTOMAP_WARNING_STR("Input filestream not \"good\" in OcTree::readBinary"); } int tree_type = -1; s.read((char*)&tree_type, sizeof(tree_type)); if (tree_type == 3){ this->clear(); s.read((char*)&res, sizeof(res)); if (res <= 0.0){ OCTOMAP_ERROR("Invalid tree resolution: %f", res); return false; } s.read((char*)&size, sizeof(size)); return true; } else { OCTOMAP_ERROR_STR("Binary file does not contain an OcTree!"); return false; } } bool AbstractOccupancyOcTree::readBinary(const std::string& filename){ std::ifstream binary_infile( filename.c_str(), std::ios_base::binary); if (!binary_infile.is_open()){ OCTOMAP_ERROR_STR("Filestream to "<< filename << " not open, nothing read."); return false; } return readBinary(binary_infile); } bool AbstractOccupancyOcTree::readBinary(std::istream &s) { if (!s.good()){ OCTOMAP_WARNING_STR("Input filestream not \"good\" in OcTree::readBinary"); } // check if first line valid: std::string line; std::istream::pos_type streampos = s.tellg(); std::getline(s, line); unsigned size; double res; if (line.compare(0,AbstractOccupancyOcTree::binaryFileHeader.length(), AbstractOccupancyOcTree::binaryFileHeader) ==0){ std::string id; if (!AbstractOcTree::readHeader(s, id, size, res)) return false; OCTOMAP_DEBUG_STR("Reading binary octree type "<< id); } else{ // try to read old binary format: s.clear(); // clear eofbit of istream s.seekg(streampos); if (readBinaryLegacyHeader(s, size, res)){ OCTOMAP_WARNING_STR("You are using an outdated binary tree file format."); OCTOMAP_WARNING_STR("Please convert your .bt files with convert_octree."); } else { OCTOMAP_ERROR_STR("First line of OcTree file header does not start with \""<< AbstractOccupancyOcTree::binaryFileHeader<<"\""); return false; } } // otherwise: values are valid, stream is now at binary data! this->clear(); this->setResolution(res); if (size > 0) this->readBinaryData(s); if (size != this->size()){ OCTOMAP_ERROR("Tree size mismatch: # read nodes (%zu) != # expected nodes (%d)\n",this->size(), size); return false; } return true; } const std::string AbstractOccupancyOcTree::binaryFileHeader = "# Octomap OcTree binary file"; }
6,509
34.769231
135
cpp
octomap
octomap-master/octomap/src/ColorOcTree.cpp
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <octomap/ColorOcTree.h> namespace octomap { // node implementation -------------------------------------- std::ostream& ColorOcTreeNode::writeData(std::ostream &s) const { s.write((const char*) &value, sizeof(value)); // occupancy s.write((const char*) &color, sizeof(Color)); // color return s; } std::istream& ColorOcTreeNode::readData(std::istream &s) { s.read((char*) &value, sizeof(value)); // occupancy s.read((char*) &color, sizeof(Color)); // color return s; } ColorOcTreeNode::Color ColorOcTreeNode::getAverageChildColor() const { int mr = 0; int mg = 0; int mb = 0; int c = 0; if (children != NULL){ for (int i=0; i<8; i++) { ColorOcTreeNode* child = static_cast<ColorOcTreeNode*>(children[i]); if (child != NULL && child->isColorSet()) { mr += child->getColor().r; mg += child->getColor().g; mb += child->getColor().b; ++c; } } } if (c > 0) { mr /= c; mg /= c; mb /= c; return Color((uint8_t) mr, (uint8_t) mg, (uint8_t) mb); } else { // no child had a color other than white return Color(255, 255, 255); } } void ColorOcTreeNode::updateColorChildren() { color = getAverageChildColor(); } // tree implementation -------------------------------------- ColorOcTree::ColorOcTree(double in_resolution) : OccupancyOcTreeBase<ColorOcTreeNode>(in_resolution) { colorOcTreeMemberInit.ensureLinking(); } ColorOcTreeNode* ColorOcTree::setNodeColor(const OcTreeKey& key, uint8_t r, uint8_t g, uint8_t b) { ColorOcTreeNode* n = search (key); if (n != 0) { n->setColor(r, g, b); } return n; } bool ColorOcTree::pruneNode(ColorOcTreeNode* node) { if (!isNodeCollapsible(node)) return false; // set value to children's values (all assumed equal) node->copyData(*(getNodeChild(node, 0))); if (node->isColorSet()) // TODO check node->setColor(node->getAverageChildColor()); // delete children for (unsigned int i=0;i<8;i++) { deleteNodeChild(node, i); } delete[] node->children; node->children = NULL; return true; } bool ColorOcTree::isNodeCollapsible(const ColorOcTreeNode* node) const{ // all children must exist, must not have children of // their own and have the same occupancy probability if (!nodeChildExists(node, 0)) return false; const ColorOcTreeNode* firstChild = getNodeChild(node, 0); if (nodeHasChildren(firstChild)) return false; for (unsigned int i = 1; i<8; i++) { // compare nodes only using their occupancy, ignoring color for pruning if (!nodeChildExists(node, i) || nodeHasChildren(getNodeChild(node, i)) || !(getNodeChild(node, i)->getValue() == firstChild->getValue())) return false; } return true; } ColorOcTreeNode* ColorOcTree::averageNodeColor(const OcTreeKey& key, uint8_t r, uint8_t g, uint8_t b) { ColorOcTreeNode* n = search(key); if (n != 0) { if (n->isColorSet()) { ColorOcTreeNode::Color prev_color = n->getColor(); n->setColor((prev_color.r + r)/2, (prev_color.g + g)/2, (prev_color.b + b)/2); } else { n->setColor(r, g, b); } } return n; } ColorOcTreeNode* ColorOcTree::integrateNodeColor(const OcTreeKey& key, uint8_t r, uint8_t g, uint8_t b) { ColorOcTreeNode* n = search (key); if (n != 0) { if (n->isColorSet()) { ColorOcTreeNode::Color prev_color = n->getColor(); double node_prob = n->getOccupancy(); uint8_t new_r = (uint8_t) ((double) prev_color.r * node_prob + (double) r * (0.99-node_prob)); uint8_t new_g = (uint8_t) ((double) prev_color.g * node_prob + (double) g * (0.99-node_prob)); uint8_t new_b = (uint8_t) ((double) prev_color.b * node_prob + (double) b * (0.99-node_prob)); n->setColor(new_r, new_g, new_b); } else { n->setColor(r, g, b); } } return n; } void ColorOcTree::updateInnerOccupancy() { this->updateInnerOccupancyRecurs(this->root, 0); } void ColorOcTree::updateInnerOccupancyRecurs(ColorOcTreeNode* node, unsigned int depth) { // only recurse and update for inner nodes: if (nodeHasChildren(node)){ // return early for last level: if (depth < this->tree_depth){ for (unsigned int i=0; i<8; i++) { if (nodeChildExists(node, i)) { updateInnerOccupancyRecurs(getNodeChild(node, i), depth+1); } } } node->updateOccupancyChildren(); node->updateColorChildren(); } } void ColorOcTree::writeColorHistogram(std::string filename) { #ifdef _MSC_VER fprintf(stderr, "The color histogram uses gnuplot, this is not supported under windows.\n"); #else // build RGB histogram std::vector<int> histogram_r (256,0); std::vector<int> histogram_g (256,0); std::vector<int> histogram_b (256,0); for(ColorOcTree::tree_iterator it = this->begin_tree(), end=this->end_tree(); it!= end; ++it) { if (!it.isLeaf() || !this->isNodeOccupied(*it)) continue; ColorOcTreeNode::Color& c = it->getColor(); ++histogram_r[c.r]; ++histogram_g[c.g]; ++histogram_b[c.b]; } // plot data FILE *gui = popen("gnuplot ", "w"); fprintf(gui, "set term postscript eps enhanced color\n"); fprintf(gui, "set output \"%s\"\n", filename.c_str()); fprintf(gui, "plot [-1:256] "); fprintf(gui,"'-' w filledcurve lt 1 lc 1 tit \"r\","); fprintf(gui, "'-' w filledcurve lt 1 lc 2 tit \"g\","); fprintf(gui, "'-' w filledcurve lt 1 lc 3 tit \"b\","); fprintf(gui, "'-' w l lt 1 lc 1 tit \"\","); fprintf(gui, "'-' w l lt 1 lc 2 tit \"\","); fprintf(gui, "'-' w l lt 1 lc 3 tit \"\"\n"); for (int i=0; i<256; ++i) fprintf(gui,"%d %d\n", i, histogram_r[i]); fprintf(gui,"0 0\n"); fprintf(gui, "e\n"); for (int i=0; i<256; ++i) fprintf(gui,"%d %d\n", i, histogram_g[i]); fprintf(gui,"0 0\n"); fprintf(gui, "e\n"); for (int i=0; i<256; ++i) fprintf(gui,"%d %d\n", i, histogram_b[i]); fprintf(gui,"0 0\n"); fprintf(gui, "e\n"); for (int i=0; i<256; ++i) fprintf(gui,"%d %d\n", i, histogram_r[i]); fprintf(gui, "e\n"); for (int i=0; i<256; ++i) fprintf(gui,"%d %d\n", i, histogram_g[i]); fprintf(gui, "e\n"); for (int i=0; i<256; ++i) fprintf(gui,"%d %d\n", i, histogram_b[i]); fprintf(gui, "e\n"); fflush(gui); #endif } std::ostream& operator<<(std::ostream& out, ColorOcTreeNode::Color const& c) { return out << '(' << (unsigned int)c.r << ' ' << (unsigned int)c.g << ' ' << (unsigned int)c.b << ')'; } ColorOcTree::StaticMemberInitializer ColorOcTree::colorOcTreeMemberInit; } // end namespace
9,212
34.298851
144
cpp
octomap
octomap-master/octomap/src/CountingOcTree.cpp
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <cassert> #include <octomap/CountingOcTree.h> namespace octomap { /// implementation of CountingOcTreeNode ---------------------------------- CountingOcTreeNode::CountingOcTreeNode() : OcTreeDataNode<unsigned int>(0) { } CountingOcTreeNode::~CountingOcTreeNode() { } /// implementation of CountingOcTree -------------------------------------- CountingOcTree::CountingOcTree(double in_resolution) : OcTreeBase<CountingOcTreeNode>(in_resolution) { countingOcTreeMemberInit.ensureLinking(); } CountingOcTreeNode* CountingOcTree::updateNode(const point3d& value) { OcTreeKey key; if (!coordToKeyChecked(value, key)) return NULL; return updateNode(key); } // Note: do not inline this method, will decrease speed (KMW) CountingOcTreeNode* CountingOcTree::updateNode(const OcTreeKey& k) { if (root == NULL) { root = new CountingOcTreeNode(); tree_size++; } CountingOcTreeNode* curNode (root); curNode->increaseCount(); // follow or construct nodes down to last level... for (int i=(tree_depth-1); i>=0; i--) { unsigned int pos = computeChildIdx(k, i); // requested node does not exist if (!nodeChildExists(curNode, pos)) { createNodeChild(curNode, pos); } // descent tree curNode = getNodeChild(curNode, pos); curNode->increaseCount(); // modify traversed nodes } return curNode; } void CountingOcTree::getCentersMinHits(point3d_list& node_centers, unsigned int min_hits) const { OcTreeKey root_key; root_key[0] = root_key[1] = root_key[2] = this->tree_max_val; getCentersMinHitsRecurs(node_centers, min_hits, this->tree_depth, this->root, 0, root_key); } void CountingOcTree::getCentersMinHitsRecurs( point3d_list& node_centers, unsigned int& min_hits, unsigned int max_depth, CountingOcTreeNode* node, unsigned int depth, const OcTreeKey& parent_key) const { if (depth < max_depth && nodeHasChildren(node)) { key_type center_offset_key = this->tree_max_val >> (depth + 1); OcTreeKey search_key; for (unsigned int i=0; i<8; ++i) { if (nodeChildExists(node,i)) { computeChildKey(i, center_offset_key, parent_key, search_key); getCentersMinHitsRecurs(node_centers, min_hits, max_depth, getNodeChild(node,i), depth+1, search_key); } } } else { // max level reached if (node->getCount() >= min_hits) { node_centers.push_back(this->keyToCoord(parent_key, depth)); } } } CountingOcTree::StaticMemberInitializer CountingOcTree::countingOcTreeMemberInit; } // namespace
4,635
33.857143
112
cpp
octomap
octomap-master/octomap/src/OcTree.cpp
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <octomap/OcTree.h> namespace octomap { OcTree::OcTree(double in_resolution) : OccupancyOcTreeBase<OcTreeNode>(in_resolution) { ocTreeMemberInit.ensureLinking(); } OcTree::OcTree(std::string _filename) : OccupancyOcTreeBase<OcTreeNode> (0.1) { // resolution will be set according to tree file readBinary(_filename); } OcTree::StaticMemberInitializer OcTree::ocTreeMemberInit; } // namespace
2,209
39.181818
95
cpp
octomap
octomap-master/octomap/src/OcTreeNode.cpp
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <bitset> #include <cassert> #include <math.h> #include <fstream> #include <stdlib.h> #include <inttypes.h> #include <octomap/OcTreeNode.h> namespace octomap { OcTreeNode::OcTreeNode() : OcTreeDataNode<float>(0.0) { } OcTreeNode::~OcTreeNode(){ } // ============================================================ // = occupancy probability ================================== // ============================================================ double OcTreeNode::getMeanChildLogOdds() const{ double mean = 0; uint8_t c = 0; if (children !=NULL){ for (unsigned int i=0; i<8; i++) { if (children[i] != NULL) { mean += static_cast<OcTreeNode*>(children[i])->getOccupancy(); // TODO check if works generally ++c; } } } if (c > 0) mean /= (double) c; return log(mean/(1-mean)); } float OcTreeNode::getMaxChildLogOdds() const{ float max = -std::numeric_limits<float>::max(); if (children !=NULL){ for (unsigned int i=0; i<8; i++) { if (children[i] != NULL) { float l = static_cast<OcTreeNode*>(children[i])->getLogOdds(); // TODO check if works generally if (l > max) max = l; } } } return max; } void OcTreeNode::addValue(const float& logOdds) { value += logOdds; } } // end namespace
3,180
31.459184
105
cpp
octomap
octomap-master/octomap/src/OcTreeStamped.cpp
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "octomap/OcTreeStamped.h" namespace octomap { OcTreeStamped::OcTreeStamped(double in_resolution) : OccupancyOcTreeBase<OcTreeNodeStamped>(in_resolution) { ocTreeStampedMemberInit.ensureLinking(); } unsigned int OcTreeStamped::getLastUpdateTime() { // this value is updated whenever inner nodes are // updated using updateOccupancyChildren() return root->getTimestamp(); } void OcTreeStamped::degradeOutdatedNodes(unsigned int time_thres) { unsigned int query_time = (unsigned int) time(NULL); for(leaf_iterator it = this->begin_leafs(), end=this->end_leafs(); it!= end; ++it) { if ( this->isNodeOccupied(*it) && ((query_time - it->getTimestamp()) > time_thres) ) { integrateMissNoTime(&*it); } } } void OcTreeStamped::updateNodeLogOdds(OcTreeNodeStamped* node, const float& update) const { OccupancyOcTreeBase<OcTreeNodeStamped>::updateNodeLogOdds(node, update); node->updateTimestamp(); } void OcTreeStamped::integrateMissNoTime(OcTreeNodeStamped* node) const{ OccupancyOcTreeBase<OcTreeNodeStamped>::updateNodeLogOdds(node, prob_miss_log); } OcTreeStamped::StaticMemberInitializer OcTreeStamped::ocTreeStampedMemberInit; } // end namespace
3,044
40.712329
93
cpp
octomap
octomap-master/octomap/src/Pointcloud.cpp
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* According to c++ standard including this header has no practical effect * but it can be used to determine the c++ standard library implementation. */ #include <ciso646> #if defined(_MSC_VER) || defined(_LIBCPP_VERSION) #include <algorithm> #if __cplusplus > 199711L #include <random> #endif #else #include <ext/algorithm> #endif #include <fstream> #include <math.h> #include <assert.h> #include <limits> #include <octomap/Pointcloud.h> namespace octomap { Pointcloud::Pointcloud() { } Pointcloud::~Pointcloud() { this->clear(); } void Pointcloud::clear() { // delete the points if (points.size()) { points.clear(); } } Pointcloud::Pointcloud(const Pointcloud& other) { for (Pointcloud::const_iterator it = other.begin(); it != other.end(); it++) { points.push_back(point3d(*it)); } } Pointcloud::Pointcloud(Pointcloud* other) { for (Pointcloud::const_iterator it = other->begin(); it != other->end(); it++) { points.push_back(point3d(*it)); } } void Pointcloud::push_back(const Pointcloud& other) { for (Pointcloud::const_iterator it = other.begin(); it != other.end(); it++) { points.push_back(point3d(*it)); } } point3d Pointcloud::getPoint(unsigned int i) const{ if (i < points.size()) return points[i]; else { OCTOMAP_WARNING("Pointcloud::getPoint index out of range!\n"); return points.back(); } } void Pointcloud::transform(octomath::Pose6D transform) { for (unsigned int i=0; i<points.size(); i++) { points[i] = transform.transform(points[i]); } // FIXME: not correct for multiple transforms current_inv_transform = transform.inv(); } void Pointcloud::transformAbsolute(pose6d transform) { // undo previous transform, then apply current transform pose6d transf = current_inv_transform * transform; for (unsigned int i=0; i<points.size(); i++) { points[i] = transf.transform(points[i]); } current_inv_transform = transform.inv(); } void Pointcloud::rotate(double roll, double pitch, double yaw) { for (unsigned int i=0; i<points.size(); i++) { points[i].rotate_IP(roll, pitch, yaw); } } void Pointcloud::calcBBX(point3d& lowerBound, point3d& upperBound) const { float min_x, min_y, min_z; float max_x, max_y, max_z; min_x = min_y = min_z = 1e6; max_x = max_y = max_z = -1e6; float x,y,z; for (Pointcloud::const_iterator it=begin(); it!=end(); it++) { x = (*it)(0); y = (*it)(1); z = (*it)(2); if (x < min_x) min_x = x; if (y < min_y) min_y = y; if (z < min_z) min_z = z; if (x > max_x) max_x = x; if (y > max_y) max_y = y; if (z > max_z) max_z = z; } lowerBound(0) = min_x; lowerBound(1) = min_y; lowerBound(2) = min_z; upperBound(0) = max_x; upperBound(1) = max_y; upperBound(2) = max_z; } void Pointcloud::crop(point3d lowerBound, point3d upperBound) { Pointcloud result; float min_x, min_y, min_z; float max_x, max_y, max_z; float x,y,z; min_x = lowerBound(0); min_y = lowerBound(1); min_z = lowerBound(2); max_x = upperBound(0); max_y = upperBound(1); max_z = upperBound(2); for (Pointcloud::const_iterator it=begin(); it!=end(); it++) { x = (*it)(0); y = (*it)(1); z = (*it)(2); if ( (x >= min_x) && (y >= min_y) && (z >= min_z) && (x <= max_x) && (y <= max_y) && (z <= max_z) ) { result.push_back (x,y,z); } } // end for points this->clear(); this->push_back(result); } void Pointcloud::minDist(double thres) { Pointcloud result; float x,y,z; for (Pointcloud::const_iterator it=begin(); it!=end(); it++) { x = (*it)(0); y = (*it)(1); z = (*it)(2); double dist = sqrt(x*x+y*y+z*z); if ( dist > thres ) result.push_back (x,y,z); } // end for points this->clear(); this->push_back(result); } void Pointcloud::subSampleRandom(unsigned int num_samples, Pointcloud& sample_cloud) { point3d_collection samples; // visual studio does not support random_sample_n and neither does libc++ #if defined(_MSC_VER) || defined(_LIBCPP_VERSION) samples.reserve(this->size()); samples.insert(samples.end(), this->begin(), this->end()); #if __cplusplus > 199711L std::random_device r; std::mt19937 urbg(r()); std::shuffle(samples.begin(), samples.end(), urbg); #else std::random_shuffle(samples.begin(), samples.end()); #endif samples.resize(num_samples); #else random_sample_n(begin(), end(), std::back_insert_iterator<point3d_collection>(samples), num_samples); for (unsigned int i=0; i<samples.size(); i++) { sample_cloud.push_back(samples[i]); } #endif } void Pointcloud::writeVrml(std::string filename){ std::ofstream outfile (filename.c_str()); outfile << "#VRML V2.0 utf8" << std::endl; outfile << "Transform {" << std::endl; outfile << "translation 0 0 0" << std::endl; outfile << "rotation 0 0 0 0" << std::endl; outfile << " children [" << std::endl; outfile << " Shape{" << std::endl; outfile << " geometry PointSet {" << std::endl; outfile << " coord Coordinate {" << std::endl; outfile << " point [" << std::endl; OCTOMAP_DEBUG_STR("PointCloud::writeVrml writing " << points.size() << " points to " << filename.c_str() << "."); for (unsigned int i = 0; i < (points.size()); i++){ outfile << "\t\t" << (points[i])(0) << " " << (points[i])(1) << " " << (points[i])(2) << "\n"; } outfile << " ]" << std::endl; outfile << " }" << std::endl; outfile << " color Color{" << std::endl; outfile << " color [" << std::endl; for (unsigned int i = 0; i < points.size(); i++){ outfile << "\t\t 1.0 1.0 1.0 \n"; } outfile << " ]" << std::endl; outfile << " }" << std::endl; outfile << " }" << std::endl; outfile << " }" << std::endl; outfile << " ]" << std::endl; outfile << "}" << std::endl; } std::istream& Pointcloud::read(std::istream &s){ while (!s.eof()){ point3d p; for (unsigned int i=0; i<3; i++){ s >> p(i); } if (!s.fail()){ this->push_back(p); } else { break; } } return s; } std::istream& Pointcloud::readBinary(std::istream &s) { uint32_t pc_size = 0; s.read((char*)&pc_size, sizeof(pc_size)); OCTOMAP_DEBUG("Reading %d points from binary file...", pc_size); if (pc_size > 0) { this->points.reserve(pc_size); point3d p; for (uint32_t i=0; i<pc_size; i++) { p.readBinary(s); if (!s.fail()) { this->push_back(p); } else { OCTOMAP_ERROR("Pointcloud::readBinary: ERROR.\n" ); break; } } } assert(pc_size == this->size()); OCTOMAP_DEBUG("done.\n"); return s; } std::ostream& Pointcloud::writeBinary(std::ostream &s) const { // check if written unsigned int can hold size size_t orig_size = this->size(); if (orig_size > std::numeric_limits<uint32_t>::max()){ OCTOMAP_ERROR("Pointcloud::writeBinary ERROR: Point cloud too large to be written"); return s; } uint32_t pc_size = static_cast<uint32_t>(this->size()); OCTOMAP_DEBUG("Writing %u points to binary file...", pc_size); s.write((char*)&pc_size, sizeof(pc_size)); for (Pointcloud::const_iterator it = this->begin(); it != this->end(); it++) { it->writeBinary(s); } OCTOMAP_DEBUG("done.\n"); return s; } } // end namespace
9,606
26.765896
105
cpp
octomap
octomap-master/octomap/src/ScanGraph.cpp
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <iomanip> #include <fstream> #include <sstream> #include <stdlib.h> #include <octomap/math/Pose6D.h> #include <octomap/ScanGraph.h> namespace octomap { ScanNode::~ScanNode(){ if (scan != NULL){ delete scan; scan = NULL; } } std::ostream& ScanNode::writeBinary(std::ostream &s) const { // file structure: pointcloud | pose | id scan->writeBinary(s); pose.writeBinary(s); uint32_t uintId = static_cast<uint32_t>(id); s.write((char*)&uintId, sizeof(uintId)); return s; } std::istream& ScanNode::readBinary(std::istream &s) { this->scan = new Pointcloud(); this->scan->readBinary(s); this->pose.readBinary(s); uint32_t uintId; s.read((char*)&uintId, sizeof(uintId)); this->id = uintId; return s; } std::ostream& ScanNode::writePoseASCII(std::ostream &s) const { s << " " << this->id; // export pose for human editor s << " "; this->pose.trans().write(s); s << " "; this->pose.rot().toEuler().write(s); s << std::endl; return s; } std::istream& ScanNode::readPoseASCII(std::istream &s) { unsigned int read_id; s >> read_id; if (read_id != this->id) OCTOMAP_ERROR("ERROR while reading ScanNode pose from ASCII. id %d does not match real id %d.\n", read_id, this->id); this->pose.trans().read(s); // read rotation from euler angles point3d rot; rot.read(s); this->pose.rot() = octomath::Quaternion(rot); return s; } std::ostream& ScanEdge::writeBinary(std::ostream &s) const { // file structure: first_id | second_id | constraint | weight s.write((char*)&first->id, sizeof(first->id)); s.write((char*)&second->id, sizeof(second->id)); constraint.writeBinary(s); s.write((char*)&weight, sizeof(weight)); return s; } std::istream& ScanEdge::readBinary(std::istream &s, ScanGraph& graph) { unsigned int first_id, second_id; s.read((char*)&first_id, sizeof(first_id)); s.read((char*)&second_id, sizeof(second_id)); this->first = graph.getNodeByID(first_id); if (this->first == NULL) OCTOMAP_ERROR("ERROR while reading ScanEdge. first node not found.\n"); this->second = graph.getNodeByID(second_id); if (this->second == NULL) OCTOMAP_ERROR("ERROR while reading ScanEdge. second node not found.\n"); this->constraint.readBinary(s); s.read((char*)&weight, sizeof(weight)); return s; } std::ostream& ScanEdge::writeASCII(std::ostream &s) const { // file structure: first_id | second_id | constraint | weight s << " " << first->id << " " << second->id; s << " "; constraint.write(s); s << " " << weight; s << std::endl; return s; } std::istream& ScanEdge::readASCII(std::istream &s, ScanGraph& graph) { unsigned int first_id, second_id; s >> first_id; s >> second_id; this->first = graph.getNodeByID(first_id); if (this->first == NULL) OCTOMAP_ERROR("ERROR while reading ScanEdge. first node %d not found.\n", first_id); this->second = graph.getNodeByID(second_id); if (this->second == NULL) OCTOMAP_ERROR("ERROR while reading ScanEdge. second node %d not found.\n", second_id); this->constraint.read(s); s >> weight; return s; } ScanGraph::~ScanGraph() { this->clear(); } void ScanGraph::clear() { for (unsigned int i=0; i<nodes.size(); i++) { delete nodes[i]; } nodes.clear(); for (unsigned int i=0; i<edges.size(); i++) { delete edges[i]; } edges.clear(); } ScanNode* ScanGraph::addNode(Pointcloud* scan, pose6d pose) { if (scan != 0) { nodes.push_back(new ScanNode(scan, pose, (unsigned int) nodes.size())); return nodes.back(); } else { OCTOMAP_ERROR("scan is invalid.\n"); return NULL; } } ScanEdge* ScanGraph::addEdge(ScanNode* first, ScanNode* second, pose6d constraint) { if ((first != 0) && (second != 0)) { edges.push_back(new ScanEdge(first, second, constraint)); // OCTOMAP_DEBUG("ScanGraph::AddEdge %d --> %d\n", first->id, second->id); return edges.back(); } else { OCTOMAP_ERROR("addEdge:: one or both nodes invalid.\n"); return NULL; } } ScanEdge* ScanGraph::addEdge(unsigned int first_id, unsigned int second_id) { if ( this->edgeExists(first_id, second_id)) { OCTOMAP_ERROR("addEdge:: Edge exists!\n"); return NULL; } ScanNode* first = getNodeByID(first_id); ScanNode* second = getNodeByID(second_id); if ((first != 0) && (second != 0)) { pose6d constr = first->pose.inv() * second->pose; return this->addEdge(first, second, constr); } else { OCTOMAP_ERROR("addEdge:: one or both scans invalid.\n"); return NULL; } } void ScanGraph::connectPrevious() { if (nodes.size() >= 2) { ScanNode* first = nodes[nodes.size()-2]; ScanNode* second = nodes[nodes.size()-1]; pose6d c = (first->pose).inv() * second->pose; this->addEdge(first, second, c); } } void ScanGraph::exportDot(std::string filename) { std::ofstream outfile (filename.c_str()); outfile << "graph ScanGraph" << std::endl; outfile << "{" << std::endl; for (unsigned int i=0; i<edges.size(); i++) { outfile << (edges[i]->first)->id << " -- " << (edges[i]->second)->id << " [label=" << std::fixed << std::setprecision(2) << edges[i]->constraint.transLength() << "]" << std::endl; } outfile << "}" << std::endl; outfile.close(); } ScanNode* ScanGraph::getNodeByID(unsigned int id) { for (unsigned int i = 0; i < nodes.size(); i++) { if (nodes[i]->id == id) return nodes[i]; } return NULL; } bool ScanGraph::edgeExists(unsigned int first_id, unsigned int second_id) { for (unsigned int i=0; i<edges.size(); i++) { if ( (((edges[i]->first)->id == first_id) && ((edges[i]->second)->id == second_id)) || (((edges[i]->first)->id == second_id) && ((edges[i]->second)->id == first_id))) { return true; } } return false; } std::vector<unsigned int> ScanGraph::getNeighborIDs(unsigned int id) { std::vector<unsigned int> res; ScanNode* node = getNodeByID(id); if (node) { // check all nodes for (unsigned int i = 0; i < nodes.size(); i++) { if (node->id == nodes[i]->id) continue; if (edgeExists(id, nodes[i]->id)) { res.push_back(nodes[i]->id); } } } return res; } std::vector<ScanEdge*> ScanGraph::getOutEdges(ScanNode* node) { std::vector<ScanEdge*> res; if (node) { for (std::vector<ScanEdge*>::iterator it = edges.begin(); it != edges.end(); it++) { if ((*it)->first == node) { res.push_back(*it); } } } return res; } std::vector<ScanEdge*> ScanGraph::getInEdges(ScanNode* node) { std::vector<ScanEdge*> res; if (node) { for (std::vector<ScanEdge*>::iterator it = edges.begin(); it != edges.end(); it++) { if ((*it)->second == node) { res.push_back(*it); } } } return res; } void ScanGraph::transformScans() { for(ScanGraph::iterator it=this->begin(); it != this->end(); it++) { ((*it)->scan)->transformAbsolute((*it)->pose); } } bool ScanGraph::writeBinary(const std::string& filename) const { std::ofstream binary_outfile( filename.c_str(), std::ios_base::binary); if (!binary_outfile.is_open()){ OCTOMAP_ERROR_STR("Filestream to "<< filename << " not open, nothing written."); return false; } writeBinary(binary_outfile); binary_outfile.close(); return true; } std::ostream& ScanGraph::writeBinary(std::ostream &s) const { // file structure: n | node_1 | ... | node_n | m | edge_1 | ... | edge_m // write nodes --------------------------------- // note: size is always an unsigned int! unsigned int graph_size = (unsigned int) this->size(); if (graph_size) OCTOMAP_DEBUG("writing %u nodes to binary file...\n", graph_size); s.write((char*)&graph_size, sizeof(graph_size)); for (ScanGraph::const_iterator it = this->begin(); it != this->end(); it++) { (*it)->writeBinary(s); } if (graph_size) OCTOMAP_DEBUG("done.\n"); // write edges --------------------------------- unsigned int num_edges = (unsigned int) this->edges.size(); if (num_edges) OCTOMAP_DEBUG("writing %u edges to binary file...\n", num_edges); s.write((char*)&num_edges, sizeof(num_edges)); for (ScanGraph::const_edge_iterator it = this->edges_begin(); it != this->edges_end(); it++) { (*it)->writeBinary(s); } if (num_edges) OCTOMAP_DEBUG(" done.\n"); return s; } bool ScanGraph::readBinary(const std::string& filename) { std::ifstream binary_infile(filename.c_str(), std::ios_base::binary); if (!binary_infile.is_open()){ OCTOMAP_ERROR_STR("Filestream to "<< filename << " not open, nothing read."); return false; } readBinary(binary_infile); binary_infile.close(); return true; } std::istream& ScanGraph::readBinary(std::ifstream &s) { if (!s.is_open()){ OCTOMAP_ERROR_STR("Could not read from input filestream in ScanGraph::readBinary"); return s; } else if (!s.good()){ OCTOMAP_WARNING_STR("Input filestream not \"good\" in ScanGraph::readBinary"); } this->clear(); // read nodes --------------------------------- unsigned int graph_size = 0; s.read((char*)&graph_size, sizeof(graph_size)); if (graph_size) OCTOMAP_DEBUG("reading %d nodes from binary file...\n", graph_size); if (graph_size > 0) { this->nodes.reserve(graph_size); for (unsigned int i=0; i<graph_size; i++) { ScanNode* node = new ScanNode(); node->readBinary(s); if (!s.fail()) { this->nodes.push_back(node); } else { OCTOMAP_ERROR("ScanGraph::readBinary: ERROR.\n" ); break; } } } if (graph_size) OCTOMAP_DEBUG("done.\n"); // read edges --------------------------------- unsigned int num_edges = 0; s.read((char*)&num_edges, sizeof(num_edges)); if (num_edges) OCTOMAP_DEBUG("reading %d edges from binary file...\n", num_edges); if (num_edges > 0) { this->edges.reserve(num_edges); for (unsigned int i=0; i<num_edges; i++) { ScanEdge* edge = new ScanEdge(); edge->readBinary(s, *this); if (!s.fail()) { this->edges.push_back(edge); } else { OCTOMAP_ERROR("ScanGraph::readBinary: ERROR.\n" ); break; } } } if (num_edges) OCTOMAP_DEBUG("done.\n"); return s; } void ScanGraph::readPlainASCII(const std::string& filename){ std::ifstream infile(filename.c_str()); if (!infile.is_open()){ OCTOMAP_ERROR_STR("Filestream to "<< filename << " not open, nothing read."); return; } readPlainASCII(infile); infile.close(); } std::istream& ScanGraph::readPlainASCII(std::istream& s){ std::string currentLine; ScanNode* currentNode = NULL; while (true){ getline(s, currentLine); if (s.good() && !s.eof()){ std::stringstream ss; ss << currentLine; // skip empty and comment lines: if (currentLine.size() == 0 || (currentLine.compare(0,1, "#") == 0) || (currentLine.compare(0,1, " ") == 0)){ continue; } else if(currentLine.compare(0,4,"NODE")==0){ if (currentNode){ this->nodes.push_back(currentNode); this->connectPrevious(); OCTOMAP_DEBUG_STR("ScanNode "<< currentNode->pose << " done, size: "<< currentNode->scan->size()); } currentNode = new ScanNode(); currentNode->scan = new Pointcloud(); float x, y, z, roll, pitch, yaw; std::string tmp; ss >> tmp >> x >> y >> z >> roll >> pitch >> yaw; pose6d pose(x, y, z, roll, pitch, yaw); //std::cout << "Pose "<< pose << " found.\n"; currentNode->pose = pose; } else{ if (currentNode == NULL){ // TODO: allow "simple" pc files by setting initial Scan Pose to (0,0,0) OCTOMAP_ERROR_STR("Error parsing log file, no Scan to add point to!"); break; } float x, y, z; ss >> x >> y >> z; //std::cout << "Point "<< x << "," <<y <<"," <<z << " found.\n"; currentNode->scan->push_back(x,y,z); } } else{ if (currentNode){ this->nodes.push_back(currentNode); this->connectPrevious(); OCTOMAP_DEBUG_STR("Final ScanNode "<< currentNode->pose << " done, size: "<< currentNode->scan->size()); } break; } } return s; } std::ostream& ScanGraph::writeEdgesASCII(std::ostream &s) const { // file structure: n | edge_1 | ... | edge_n OCTOMAP_DEBUG_STR("Writing " << this->edges.size() << " edges to ASCII file..."); s << " " << this->edges.size(); s << std::endl; for (ScanGraph::const_edge_iterator it = this->edges_begin(); it != this->edges_end(); it++) { (*it)->writeASCII(s); } s << std::endl; OCTOMAP_DEBUG_STR("Done."); return s; } std::istream& ScanGraph::readEdgesASCII(std::istream &s) { unsigned int num_edges = 0; s >> num_edges; OCTOMAP_DEBUG("Reading %d edges from ASCII file...\n", num_edges); if (num_edges > 0) { for (unsigned int i=0; i<this->edges.size(); i++) delete edges[i]; this->edges.clear(); this->edges.reserve(num_edges); for (unsigned int i=0; i<num_edges; i++) { ScanEdge* edge = new ScanEdge(); edge->readASCII(s, *this); if (!s.fail()) { this->edges.push_back(edge); } else { OCTOMAP_ERROR("ScanGraph::readBinary: ERROR.\n" ); break; } } } OCTOMAP_DEBUG("done.\n"); return s; } std::ostream& ScanGraph::writeNodePosesASCII(std::ostream &s) const { OCTOMAP_DEBUG("Writing %lu node poses to ASCII file...\n", (unsigned long) this->size()); for (ScanGraph::const_iterator it = this->begin(); it != this->end(); it++) { (*it)->writePoseASCII(s); } s << std::endl; OCTOMAP_DEBUG("done.\n"); return s; } std::istream& ScanGraph::readNodePosesASCII(std::istream &s) { for (ScanGraph::const_iterator it = this->begin(); it != this->end(); it++) { (*it)->readPoseASCII(s); } for (ScanGraph::edge_iterator it = this->edges_begin(); it != this->edges_end(); it++) { ScanNode* first = (*it)->first; ScanNode* second = (*it)->second; (*it)->constraint = (first->pose).inv() * second->pose; } // constraints and nodes are inconsistent, rewire graph // for (unsigned int i=0; i<this->edges.size(); i++) delete edges[i]; // this->edges.clear(); // ScanGraph::iterator first_it = this->begin(); // ScanGraph::iterator second_it = first_it+1; // for ( ; second_it != this->end(); first_it++, second_it++) { // ScanNode* first = (*first_it); // ScanNode* second = (*second_it); // octomath::Pose6D c = (first->pose).inv() * second->pose; // this->addEdge(first, second, c); // } return s; } void ScanGraph::cropEachScan(point3d lowerBound, point3d upperBound) { for (ScanGraph::iterator it = this->begin(); it != this->end(); it++) { ((*it)->scan)->crop(lowerBound, upperBound); } } void ScanGraph::crop(point3d lowerBound, point3d upperBound) { // for all node in graph... for (ScanGraph::iterator it = this->begin(); it != this->end(); it++) { pose6d scan_pose = (*it)->pose; Pointcloud* pc = new Pointcloud((*it)->scan); pc->transformAbsolute(scan_pose); pc->crop(lowerBound, upperBound); pc->transform(scan_pose.inv()); delete (*it)->scan; (*it)->scan = pc; } } size_t ScanGraph::getNumPoints(unsigned int max_id) const { size_t retval = 0; for (ScanGraph::const_iterator it = this->begin(); it != this->end(); it++) { retval += (*it)->scan->size(); if ((max_id > 0) && ((*it)->id == max_id)) break; } return retval; } } // end namespace
18,219
28.105431
123
cpp
octomap
octomap-master/octomap/src/binvox2bt.cpp
/* * OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees * https://octomap.github.io/ * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /*! * @file binvox2bt.cpp * Read files generated by Patrick Min's 3D mesh voxelizer * ("binvox", available at: http://www.cs.princeton.edu/~min/binvox/) * and convert the voxel meshes to a single bonsai tree file. * This file is based on code from http://www.cs.princeton.edu/~min/binvox/read_binvox.cc * * @author S. Osswald, University of Freiburg, Copyright (C) 2010. * License: New BSD License */ #ifndef M_PI_2 #define M_PI_2 1.5707963267948966192E0 #endif #include <string> #include <fstream> #include <iostream> #include <octomap/octomap.h> #include <cstdlib> #include <cstring> using namespace std; using namespace octomap; namespace octomap { typedef unsigned char byte; } int main(int argc, char **argv) { int version; // binvox file format version (should be 1) size_t depth, height, width; // dimensions of the voxel grid size_t size; // number of grid cells (height * width * depth) float tx, ty, tz; // Translation float scale; // Scaling factor bool mark_free = false; // Mark free cells (false = cells remain "unknown") bool rotate = false; // Fix orientation of webots-exported files bool show_help = false; string output_filename; double minX = 0.0; double minY = 0.0; double minZ = 0.0; double maxX = 0.0; double maxY = 0.0; double maxZ = 0.0; bool applyBBX = false; bool applyOffset = false; octomap::point3d offset(0.0, 0.0, 0.0); OcTree *tree = 0; if(argc == 1) show_help = true; for(int i = 1; i < argc && !show_help; i++) { if(strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-help") == 0 || strcmp(argv[i], "--usage") == 0 || strcmp(argv[i], "-usage") == 0 || strcmp(argv[i], "-h") == 0 ) show_help = true; } if(show_help) { cout << "Usage: "<<argv[0]<<" [OPTIONS] <binvox filenames>" << endl; cout << "\tOPTIONS:" << endl; cout << "\t -o <file> Output filename (default: first input filename + .bt)\n"; cout << "\t --mark-free Mark not occupied cells as 'free' (default: unknown)\n"; cout << "\t --rotate Rotate left by 90 deg. to fix the coordinate system when exported from Webots\n"; cout << "\t --bb <minx> <miny> <minz> <maxx> <maxy> <maxz>: force bounding box for OcTree\n"; cout << "\t --offset <x> <y> <z>: add an offset to the final coordinates\n"; cout << "If more than one binvox file is given, the models are composed to a single bonsai tree->\n"; cout << "All options apply to the subsequent input files.\n\n"; exit(0); } for(int i = 1; i < argc; i++) { // Parse command line arguments if(strcmp(argv[i], "--mark-free") == 0) { mark_free = true; continue; } else if(strcmp(argv[i], "--no-mark-free") == 0) { mark_free = false; continue; }else if(strcmp(argv[i], "--rotate") == 0) { rotate = true; continue; } else if(strcmp(argv[i], "-o") == 0 && i < argc - 1) { i++; output_filename = argv[i]; continue; } else if (strcmp(argv[i], "--bb") == 0 && i < argc - 7) { i++; minX = atof(argv[i]); i++; minY = atof(argv[i]); i++; minZ = atof(argv[i]); i++; maxX = atof(argv[i]); i++; maxY = atof(argv[i]); i++; maxZ = atof(argv[i]); applyBBX = true; continue; } else if (strcmp(argv[i], "--offset") == 0 && i < argc - 4) { i++; offset(0) = (float) atof(argv[i]); i++; offset(1) = (float) atof(argv[i]); i++; offset(2) = (float) atof(argv[i]); applyOffset = true; continue; } // Open input file ifstream *input = new ifstream(argv[i], ios::in | ios::binary); if(!input->good()) { cerr << "Error: Could not open input file " << argv[i] << "!" << endl; exit(1); } else { cout << "Reading binvox file " << argv[i] << "." << endl; if(output_filename.empty()) { output_filename = string(argv[i]).append(".bt"); } } // read header string line; *input >> line; // #binvox if (line.compare("#binvox") != 0) { cout << "Error: first line reads [" << line << "] instead of [#binvox]" << endl; delete input; return 0; } *input >> version; cout << "reading binvox version " << version << endl; depth = 0; int done = 0; while(input->good() && !done) { *input >> line; if (line.compare("data") == 0) done = 1; else if (line.compare("dim") == 0) { *input >> depth >> height >> width; } else if (line.compare("translate") == 0) { *input >> tx >> ty >> tz; } else if (line.compare("scale") == 0) { *input >> scale; } else { cout << " unrecognized keyword [" << line << "], skipping" << endl; char c; do { // skip until end of line c = input->get(); } while(input->good() && (c != '\n')); } } if (!done) { cout << " error reading header" << endl; return 0; } if (depth == 0) { cout << " missing dimensions in header" << endl; return 0; } size = width * height * depth; int maxSide = std::max(std::max(width, height), depth); double res = double(scale)/double(maxSide); if(!tree) { cout << "Generating octree with leaf size " << res << endl << endl; tree = new OcTree(res); } if (applyBBX){ cout << "Bounding box for Octree: [" << minX << ","<< minY << "," << minZ << " - " << maxX << ","<< maxY << "," << maxZ << "]\n"; } if (applyOffset){ std::cout << "Offset on final map: "<< offset << std::endl; } cout << "Read data: "; cout.flush(); // read voxel data octomap::byte value; octomap::byte count; size_t index = 0; size_t end_index = 0; size_t nr_voxels = 0; size_t nr_voxels_out = 0; input->unsetf(ios::skipws); // need to read every byte now (!) *input >> value; // read the linefeed char while((end_index < size) && input->good()) { *input >> value >> count; if (input->good()) { end_index = index + count; if (end_index > size) return 0; for(size_t j=index; j < end_index; j++) { // Output progress dots if(j % (size / 20) == 0) { cout << "."; cout.flush(); } // voxel index --> voxel coordinates size_t y = j % width; size_t z = (j / width) % height; size_t x = j / (width * height); // voxel coordinates --> world coordinates point3d endpoint((float) ((double) x*res + tx + 0.000001), (float) ((double) y*res + ty + 0.000001), (float) ((double) z*res + tz + 0.000001)); if(rotate) { endpoint.rotate_IP(M_PI_2, 0.0, 0.0); } if (applyOffset) endpoint += offset; if (!applyBBX || (endpoint(0) <= maxX && endpoint(0) >= minX && endpoint(1) <= maxY && endpoint(1) >= minY && endpoint(2) <= maxZ && endpoint(2) >= minZ)){ // mark cell in octree as free or occupied if(mark_free || value == 1) { tree->updateNode(endpoint, value == 1, true); } } else{ nr_voxels_out ++; } } if (value) nr_voxels += count; index = end_index; } // if file still ok } // while cout << endl << endl; input->close(); cout << " read " << nr_voxels << " voxels, skipped "<<nr_voxels_out << " (out of bounding box)\n\n"; } // prune octree cout << "Pruning octree" << endl << endl; tree->updateInnerOccupancy(); tree->prune(); // write octree to file if(output_filename.empty()) { cerr << "Error: No input files found." << endl << endl; exit(1); } cout << "Writing octree to " << output_filename << endl << endl; tree->writeBinary(output_filename.c_str()); cout << "done" << endl << endl; return 0; }
11,019
34.207668
118
cpp