def bodyDef(fpath): """ Used with input files ProblemX-BodyY.txt to return a PointCloud with the marker positions and another with the tip position. :param fpath: path to fine containing definition of rigid body :type fpath: str :return: The number of LED markers on the rigid body :return: PointCloud with the positions of the LEDs :return: PointCloud with position of the tip :rtype: int :rtype: pc.PointCloud :rtype: pc.PointCloud """ f = open(fpath, 'r') nMarkers = int(f.readline().split()[0]) pcArray = np.zeros([3, nMarkers]) for i in range(nMarkers): led = f.readline().split() for j in range(0, 3): pcArray[j][i] = np.float64(led[j]) tip = np.zeros([3, 1]) tipPos = f.readline().split() for j in range(0, 3): tip[j] = np.float64(tipPos[j]) ledPC = pc.PointCloud(pcArray) tip = pc.PointCloud(tip) return nMarkers, ledPC, tip
def classifyPointCloud(radius, threshold, method): """ :param radius: search radius :param threshold: max slope between points :param method: the data structure the user would like to use :type radius: float :type threshold: deg :type method: string :return: wrapper method - choose a way of searching and get results """ cloud = PointCloud() cloud.initializeData() if method == 'KDTree': kdtree = KDTree() kdtree.initializeKDTree(cloud.pts, cloud.pts.shape[1] - 1) return KDTreeSearch(radius, threshold, cloud.pts, kdtree) elif method == 'Naive': return naiveSearch(radius, threshold, cloud.pts) elif method == 'EqualCells': g = GeoEqualCells() g.initializeGeoEqualCells(cloud.pts, 10, [1, 1]) # terrain, objects, rtime = g.classifyPoints(radius, threshold) return g.classifyPoints(radius, threshold) else: return print( 'method needs to be of the following: Naive, EqualCells or KDTree')
def c_expected(calbody_file, calreadings_file): """ Computes expected EM marker positions on calibration object, given measured positions of markers on the object and data from each tracker. :param calbody_file: File name/path for the calibration object data file :param calreadings_file: File name/path for the readings from the trackers :type calbody_file: str :type calreadings_file: str :return: C_expected, a list of the expected positions of EM tracking markers on the calibration object for each frame of data :rtype: [PointCloud.PointCloud] """ tracker_frames = pc.fromfile(calreadings_file) object_frame = pc.fromfile(calbody_file) c_exp = [] for frame in tracker_frames: f_d = object_frame[0][0].register(frame[0]) f_a = object_frame[0][1].register(frame[1]) c_exp.append(object_frame[0][2].transform(f_d.inv.compose(f_a))) return c_exp
def testMatlabPointcloud(): filename = '/Users/naheed/PycharmProjects/PersistenceHomology/data/eight.mat' p = pc.MatlabPointCloud(filename, 'point_cloud') print p.dimension, p.size # p.compute_distancematrix() # print p.distmat filename = '/Users/naheed/PycharmProjects/PersistenceHomology/data/pointsRange.mat' p = pc.MatlabPointCloud(filename, 'pointsRange') print p.dimension, p.size
def load_and_plot(filename, boxsize): points = np.loadtxt(filename, skiprows=2) pc.impose_pbc(points, boxsize) rcut = boxsize[0]/4 npar = len(points) rho = pc.rho(npar, boxsize) pairs = pc.get_pair(points, boxsize, rcut) rvec = pc.get_rvec(points, boxsize, rcut, pairs) r, rdf = pc.gen_rdf(rvec, npar, pc.rho( npar, boxsize), rcut=rcut, nbins=200) # min q = 2*pi/boxsize[0] # max q = 500*(min q) q = np.array([(2*np.pi/boxsize[0])*(j+1) for j in range(500)]) Sq = np.zeros(q.shape) if len(boxsize) == 3: for j in range(len(q)): Sq[j] = (pc.Sint3D(q[j], r, rdf, rho)) else: for j in range(len(q)): Sq[j] = (pc.Sint2D(q[j], r, rdf, rho)) plt.clf() plt.figure(figsize=(8, 4)) ax1 = plt.subplot(121) ax2 = plt.subplot(122) ax1.plot(r, rdf) ax1.set_xlabel('$r$') ax1.set_ylabel('$g(r)$') ax2.plot(q, Sq) ax2.set_xlabel(r'$q/ \frac{2\pi k}{L}$') ax2.set_ylabel('$S(q)$') plt.tight_layout() name = os.path.splitext(os.path.basename(filename))[0] plt.savefig(name+'.png', dpi=300)
def testFindTipB(tolerance=1e-4): """ Tests finding the tip position of body B from the tip position of the A body. If the generated and calculated positions are within tolerance of one another, the test passes. :param tolerance: The minimum error between created and computed values for the test to pass. :type tolerance: float :return: None """ print('Testing registration of pointer tip wrt body B...') print('Generate random A_tip, and A_i, B_i points') angles1 = np.random.uniform(0, 2 * np.pi, (3, )) angles2 = np.random.uniform(0, 2 * np.pi, (3, )) a_tip = np.random.uniform(0, 10, (3, 1)) a_led = np.random.uniform(0, 10, (3, 10)) b_led = np.random.uniform(0, 10, (3, 10)) r1 = _rotation(angles1) r2 = _rotation(angles2) p1 = np.random.uniform(0, 10, (3, 1)) p2 = np.random.uniform(0, 10, (3, 1)) a_frames = r1.dot(a_led) + p1 b_frames = r2.dot(b_led) + p2 print( 'Generate random transformations to a_i,k and b_i,k, and generate d_k for one frame' ) print('\nd_k =') d_k = np.linalg.inv(r2).dot(r1).dot(a_tip) + np.linalg.inv(r2).dot(p1 - p2) print(d_k) print('\nCalculate d_k using function:\ntest_d_k =') test_d_k = icpm.findTipB([pc.PointCloud(a_frames)], [pc.PointCloud(b_frames)], pc.PointCloud(a_led), pc.PointCloud(a_tip), pc.PointCloud(b_led)) print(test_d_k) print( '\nAssert difference between created and calculated d_k is less than tolerance = {}' .format(tolerance)) print('\nIs calculated d_k within tolerance?') assert np.all(np.abs(d_k - test_d_k.data) <= tolerance) print(np.all(np.abs(d_k - test_d_k.data) <= tolerance)) print('Find d_k test passed!')
def test_reg(tolerance=1e-4): """ Tests registration of a random point cloud using a random rotation and translation. If the difference between the transformation components and the originals are withing tolerance, the registration is considered accurate and the tests pass. :param tolerance: The amount of allowed error between the generated and calculated transformation components :type tolerance: float :return: None """ print('Testing registration...') angles = np.random.uniform(0, 2 * np.pi, (3, )) a = np.random.uniform(0, 10, (3, 10)) print('\na =') print(a) r = _rotation(angles) print('\nR =') print(r) p = np.random.uniform(0, 10, (3, 1)) print('\np =') print(p) print('\ntolerance = ' + str(tolerance)) b = r.dot(a) + p print('\nb =') print(b) print('\nCalculating F_AB...') f = pc.PointCloud(a).register(pc.PointCloud(b)) print('Done!') print('\nR_AB =') print(f.r) print('\np_AB =') print(f.p) print('\nIs calculated R within tolerance?') assert np.all(np.abs(r - f.r) <= tolerance) print(np.all(np.abs(r - f.r) <= tolerance)) print('\nIs it a rotation (det = 1)?') assert np.abs(scialg.det(f.r) - scialg.det(r)) <= tolerance print(np.abs(scialg.det(f.r) - scialg.det(r)) <= tolerance) print('\nIs calculated p within tolerance?') assert np.all(np.abs(p - f.p) <= tolerance) print(np.all(np.abs(p - f.p) <= tolerance)) print('\nRegistration tests passed!')
def testgraphrips(): # path = '/Users/naheed/Google Drive/tda-sna/' # filename = 'core-blah.txt' # path = '/Users/naheed/Google Drive/tda-sna/animal/' # filename = 'dolphin.txt' # g = nx.read_edgelist(path + filename, nodetype=int, data=(('weight', float),)) path = '/Users/naheed/Google Drive/tda-sna/ppi/' filename = 'rat-inact-ppi.txt' g = nx.read_edgelist(path + filename, nodetype=str, data=(('weight', float), )) maxdim = 1 # we want to compute upto maxdim-th homology. For that need to construct maxdim and maxdim+1 simplices. maxfilter = 0.3 print 'graph size ', len(g.nodes) print 'number of edges = ', len(g.edges) p = Pc.GraphPointcloud(nxgraph=g) p.compute_distancematrix() # Compute all pair shortest path (normalized) print "max distance: ", p.maxdist rf = IncrementalRips(p, 10, maxdim, maxfilter) rf.construct() print 'filtration size ', len(rf) # print rf ci = IntervalComputation(rf, maxk=maxdim, max_filtration_val=maxfilter) ci.compute_intervals() ci.print_BettiNumbers()
def testWitnessStream(): from WitnessFiltration import WitnessStream from WeakWitnessFiltration import WeakWitnessStream # mean = [0, 0] # cov = [[1, 0], [0, 1]] # matrixofpoints_inR2 = np.random.multivariate_normal(mean, cov, 100) # p = pc.PointCloud(matrixofpoints_inR2) filename = '/Users/naheed/PycharmProjects/PersistenceHomology/data/eight.mat' p = pc.MatlabPointCloud(filename, 'point_cloud') p.compute_distancematrix() # Create Selector pointcloud_sel = sel.PointCloudSelector(p, 100, "RandomSelector") R = float(pointcloud_sel.get_maxdistance_landmarktoPointcloud()) / 2 # R = 0 print 'R = ', R numdivision = 5 maxdim = 3 # ws = WitnessStream(landmarkselector=pointcloud_sel, maxdistance=R, numdivision=numdivision, maxdimension=maxdim) ws = WeakWitnessStream(mu=2, landmarkselector=pointcloud_sel, maxdistance=R, numdivision=numdivision, maxdimension=maxdim) ws.construct print ws print "Total number of Simplices in the Filtration: ", len(ws)
def runmaxmin(self): """ construct max min landmarks set """ import random random.seed(self.seed) mindist_ptolandmarkset = np.full(self.pointcloud.size, np.inf) self.subsetindices = [] for i in xrange(self.subsetsize): if i == 0: selected_index = random.randint(0, self.pointcloud.size - 1) # update min for all the rest indices # update min for this index to 0. for z in xrange(self.pointcloud.size): # if z == selected_index: # mindist_ptolandmarkset[z] = 0.0 # else: mindist_ptolandmarkset[z] = self.pointcloud.distmat[selected_index][z] else: selected_index = np.argmax(mindist_ptolandmarkset) # update minimum distance for all points for z in xrange(self.pointcloud.size): mindist_ptolandmarkset[z] = min(mindist_ptolandmarkset[z], self.pointcloud.distmat[selected_index][z]) self.subsetindices.append(selected_index) self.subsetpointcloud = pc.PointCloud(self.pointcloud.points[self.subsetindices])
def main(): FreeCAD.Console.PrintMessage("\n\n============== START ==============") p = cloud.PointCloud() """Sampler overlate(r) med gitt avstand i mm """ p.get_subObjects(10.0, 10.0) """Setter sammen alle samples i en punktsky""" p.generate_point_cloud() """Uncomment to display sampling""" # p.display_sampling() """Test for Path. Uncomment the desired path""" path = pathgen.Path(p.point_cloud) """GREEDY""" # path.greedy_algorithm(path.point_cloud[0]) """GREEDY WEIGHTED. Uncomment desired weighting. U-weighting is default.""" path.greedy_weighted(path.point_cloud[0], "u") # path.greedy_weighted(path.point_cloud[0], "y") """TSP""" # path.TSP_path() """Display path""" path.display_path()
def findTipB(aFrames, bFrames, ledA, tipA, ledB): """ Finds the positions of the tip of pointer A with respect to the B rigid body for each sample frame. :param aFrames: Sample frames of A pointer :param bFrames: Sample frames of B rigid body :param ledA: Position of LEDs on A pointer in calibration frame :param tipA: Position of tip with respect to A pointer :param ledB: Position of LEDs on B rigid body in calibration frame :param tipB: Position of attachment of B to bone in B coordinate system :type aFrames: [pc.PointCloud] :type bFrames: [pc.PointCloud] :type ledA: pc.PointCloud :type tipA: pc.PointCloud :type ledB: pc.PointCloud :type tipB: pc.PointCloud :return: d_ks: Tip positions with respect to B rigid body in each data frame :rtype: pc.PointCloud """ d_ks = np.zeros([3, len(aFrames)]) for i in range(len(aFrames)): regA = ledA.register(aFrames[i]) regB = ledB.register(bFrames[i]) reg = regB.inv.compose(regA) d_k = reg.r.dot(tipA.data) + reg.p for j in range(0, 3): d_ks[j][i] = d_k[j] return pc.PointCloud(d_ks)
def testRipsstream(): # maxdim = 2 # filename = '/Users/naheed/PycharmProjects/PersistenceHomology/data/pointcloud.txt' # p = pc.TextPointCloud(filename, ' ') maxdim = 2 filename = '/Users/naheed/PycharmProjects/PersistenceHomology/data/eight.mat' p = pc.MatlabPointCloud(filename, 'point_cloud') print p.dimension, p.size p.compute_distancematrix() print p.getdistance(0, 1) from src.RipsFiltration import BruteForceRips rf = BruteForceRips(p, 100, maxdim, 0.02) rf.construct() print rf.write_boundarylists_to( '/Users/naheed/PycharmProjects/PersistenceHomology/data/eight_mat.fil') print len(rf) from src.ComputeInterval import IntervalComputation ci = IntervalComputation(rf) ci.compute_intervals(maxdim) npar = ci.get_intervals_asnumpyarray() print npar[:10] print npar.shape import numpy as np with open("test.csv", 'wb') as f: f.write("Dimension,Birth,Death\n") np.savetxt(f, npar, delimiter=",", fmt='%d,%.4f,%.4f') ci.print_BettiNumbers() from src.Intervalviz import PersistenceViz pv = PersistenceViz(ci.betti_intervals, replace_Inf=rf.maxfiltration_val) pv.draw_barcodes()
def distcal(calbody_file, calreadings_file, empivot_file): """ Calculates the coefficient matrix of the distortion correction file and applies it to a set of EM pivot calibration frames to return the corrected pivot calibration. :param calbody_file: File name/path for the calibration object data file :param calreadings_file: File name/path for the readings from the trackers :param empivot_file: File name/path for EM pivot poses :type calbody_file: str :type emfiducialss: str :type empivot_file: str :return: pivotanswer: the corrected pivot calibration :return: coeff_mat: matrix of the coefficients for dewarping a data set :return: q_min: vector of minimum value for each coordinate in experimental data set :return: q_max: vector of maximum value for each coordinate in experimental data set :return: q_star_min: vector of minimim value for each coordinate in expected data set :return: q_star_max: vector of maximum value for each coordinate in expected data set :rtype coeffs: numpy.array([numpy.float64][]) degree**3 x 3 :rtype q_min: numpy.array(numpy.float64) shape (3,) or (, 3) :rtype q_max: numpy.array(numpy.float64) shape (3,) or (, 3) :rtype q_star_min: numpy.array(numpy.float64) shape (3,) or (, 3) :rtype q_star_max: numpy.array(numpy.float64) shape (3,) or (, 3) """ tracker_frames = pc.fromfile(calreadings_file) c = [] for k in range(len(tracker_frames)): c.append(tracker_frames[k][2]) c_exp = p1.c_expected(calbody_file, calreadings_file) pPerFrame = np.shape(c[0].data)[1] #points per frame nFrames = np.shape(c)[0] concatc = c[0].data concatc_exp = c_exp[0].data for i in range(1, nFrames): concatc = np.concatenate((concatc, c[i].data), axis=1) concatc_exp = np.concatenate((concatc_exp, c_exp[i].data), axis=1) q_min, q_max, q_star_min, q_star_max = calc_q(concatc, concatc_exp) u_s_star = normalize(pPerFrame * nFrames, concatc_exp, q_star_min, q_star_max) u_s = normalize(pPerFrame * nFrames, concatc, q_min, q_max) F_mat = f_matrix(u_s, 5) coeff_mat = solve_fcu(F_mat, u_s_star) EMcorrect = correct(empivot_file, coeff_mat, q_min, q_max, q_star_min, q_star_max) pivotanswer = piv.pivot(EMcorrect, 0) return pivotanswer, coeff_mat, q_min, q_max, q_star_min, q_star_max
def testpointcloud(): matrixofpoints_inR2 = [] mean = [0, 0] cov = [[1, 0], [0, 1]] matrixofpoints_inR2 = np.random.multivariate_normal(mean, cov, 100) p = pc.PointCloud(matrixofpoints_inR2) print p.size, p.dimension p.compute_distancematrix() print p.distmat
def readSample(fpath, nA, nB): """ Reads frames of positions of led markers on bodies A and B and creates 2 lists of pointClouds. :param fpath: Filepath containing sample readings :param nA: number of LED markers on A :param nB: number of LED markers on B :type fpath: str :type nA: int :type nB: int :return: PointClouds representing positions of LEDs on A in each frame :return: PointClouds representing positions of LEDs on B in each frame :rtype: [pc.PointCloud] :rtype: [pc.PointCloud] """ f = open(fpath, 'r') line1 = f.readline() nMarkers = int(line1.split()[0].replace(',', '')) nSamples = int(line1.split()[1].replace(',', '')) aFrames = [] bFrames = [] for i in range(nSamples): aCloud = np.zeros([3, nA]) bCloud = np.zeros([3, nB]) for j in range(nA): point = f.readline().split() for k in range(0, 3): aCloud[k][j] = np.float64(point[k].replace(',', '')) for j in range(nB): point = f.readline().split() for k in range(0, 3): bCloud[k][j] = np.float64(point[k].replace(',', '')) for j in range(nMarkers - nA - nB): f.readline() aFrames.append(pc.PointCloud(aCloud)) bFrames.append(pc.PointCloud(bCloud)) return aFrames, bFrames
def tip_in_EM(empivot, emfiducialss, ptip, coeffs, q_min, q_max, q_star_min, q_star_max): """ Returns the position of the pointer tip in EM coordinates for tracker data frames when the tip is on a fiducial pin. :param empivot: The file name/path containing EM tracking data during calibration :param emfiducialss: The file name/path of the file with marker positions when the pointer is on the fiducials, relative to the EM tracker. :param ptip: The coordinates of the tip of the pointer relative to the pointer coordinate system (Output of pivot_cal.pivot) :param coeffs: Coefficient matrix for dewarping (Output of distortion.distcal) :param q_min: Vector of input minima for the initial correction matrix creation (Output of distortion.distcal) :param q_max: Vector of input maxima for the initial correction matrix creation (Output of distortion.distcal) :param q_star_min: Vector of output minima for the initial correction matrix creation (Output of distortion.distcal) :param q_star_max: Vector of output maxima for the initial correction matrix creation (Output of distortion.distcal) :type empivot: str :type emfiducialss: str :type ptip: numpy.array(numpy.float64) shape (3,) or (, 3) :type coeffs: numpy.array([numpy.float64][]) degree**3 x 3 :type q_min: numpy.array(numpy.float64) shape (3,) or (, 3) :type q_max: numpy.array(numpy.float64) shape (3,) or (, 3) :type q_star_min: numpy.array(numpy.float64) shape (3,) or (, 3) :type q_star_max: numpy.array(numpy.float64) shape (3,) or (, 3) :return: A PointCloud representing the location of the pointer tip in EM tracker coordinates at each set of observations G :rtype: PointCloud.PointCloud """ G = d.correct(emfiducialss, coeffs, q_min, q_max, q_star_min, q_star_max) G_orig = d.correct(empivot, coeffs, q_min, q_max, q_star_min, q_star_max) G_0 = np.mean(G_orig[0][0].data, axis=1, keepdims=True) G_j = G_orig[0][0].data - G_0 Cs = pc.PointCloud() for frame in G: F = pc.PointCloud(G_j).register(frame[0]) C = pc.PointCloud(ptip.reshape((3, 1))).transform(F) Cs = Cs.add(C) return Cs
def test_pivot_cal(empivot, tolerance=1e-2): """ Tests whether pivot calibration is correct by using the fact that all frame transformations F_G[k] from pointer to EM coordinates will map p_tip to p_dimple. :param empivot: The name/path of an empivot.txt file, containing frames of EM tracker data during pivot calibration :param tolerance: Error tolerance between calculated and predicted values. Default is 1e-2. :type empivot: str :type tolerance: float :return: None """ print('\nTesting pivot calibration...') print('\nExtracting marker points:') G = pc.fromfile(empivot) for i in range(len(G)): print('\n') print(G[i][0].data) p_ans = piv.pivot(G, 0, True) print('\np_tip:') print(p_ans[0]) print('\np_dimple:') print(p_ans[1]) print( '\nIf calibration is correct, all frame transformations F_G[k] from pointer to EM coordinates will map' ) print('p_tip to p_dimple. Assert that this is true:') print('\ntolerance = {}'.format(tolerance)) for i in range(len(G)): passes = np.all( np.abs(p_ans[1].reshape((3, 1)) - pc.PointCloud(p_ans[0].reshape( (3, 1))).transform(p_ans[2][i]).data) <= tolerance) assert passes print('\nFrame: {} of {}: {}'.format(i + 1, len(G), True)) print('\nCalibration tests passed!')
def tip_in_CT(empivot, emnav, ptip, F_reg, coeffs, q_min, q_max, q_star_min, q_star_max): """ Returns the position of the pointer tip in CT coordinates for tracker data frames. :param empivot: The file name/path containing EM tracking data during calibration :param emnav: The file name/path of the file with marker positions when the pointer is in an arbitrary position, relative to the EM tracker. :param ptip: The coordinates of the tip of the pointer relative to the pointer coordinate system (Output of pivot_cal.pivot) :param coeffs: Coefficient matrix for dewarping (Output of distortion.distcal) :param q_min: Vector of input minima for the initial correction matrix creation (Output of distortion.distcal) :param q_max: Vector of input maxima for the initial correction matrix creation (Output of distortion.distcal) :param q_star_min: Vector of output minima for the initial correction matrix creation (Output of distortion.distcal) :param q_star_max: Vector of output maxima for the initial correction matrix creation (Output of distortion.distcal) :type empivot: str :type emnav: str :type ptip: numpy.array(numpy.float64) shape (3,) or (, 3) :type coeffs: numpy.array([numpy.float64][]) degree**3 x 3 :type q_min: numpy.array(numpy.float64) shape (3,) or (, 3) :type q_max: numpy.array(numpy.float64) shape (3,) or (, 3) :type q_star_min: numpy.array(numpy.float64) shape (3,) or (, 3) :type q_star_max: numpy.array(numpy.float64) shape (3,) or (, 3) :return: A list of arrays, where each array is the position of the pointer tip in EM tracker coordinates for each frame """ G = d.correct(emnav, coeffs, q_min, q_max, q_star_min, q_star_max) G_orig = d.correct(empivot, coeffs, q_min, q_max, q_star_min, q_star_max) G_0 = np.mean(G_orig[0][0].data, axis=1, keepdims=True) G_j = G_orig[0][0].data - G_0 CTs = pc.PointCloud() for frame in G: F = pc.PointCloud(G_j).register(frame[0]) C = pc.PointCloud(ptip.reshape((3, 1))).transform(F).transform(F_reg) CTs = CTs.add(C) return CTs
def __init__(self, window): super().setupUi(window) self.look_timer = QTimer() self.look_timer.timeout.connect(self.user_look_timer_timeout_handler) self.look_timer.setTimerType(0) self.look_timer.start(20) # self.btn_save_image.clicked.connect(self.user_btn_save_image_click_handler) self.cameraSystem = None self.tt = 0 pg.setConfigOptions(antialias=True) self.graphicsWidget = pg.GraphicsLayoutWidget() p1 = self.graphicsWidget.addPlot(title="image") # Item for displaying image data self.image = pg.ImageItem() p1.addItem(self.image) # Contrast/color control self.hist = pg.HistogramLUTItem() self.hist.setImageItem(self.image) self.graphicsWidget.addItem(self.hist) self.hist.setHistogramRange(0, 100) # Generate image data # data = np.random.random(size=(480, 640)) # for i in range(0, 480): # for j in range(0, 640): # data[i][j] = 200 # self.image.setImage(data) self.grid_graph.addWidget(self.graphicsWidget) # camera init self.cameraSystem = PointCloud.CameraSystem() self.devices = self.cameraSystem.scan() if len(self.devices) == 1: print(" Find one device.") self.user_camera_window = ShowDepthNoGUI.MainWindow( self.cameraSystem, self.devices) # key = input("Input enter key to quit.") # print(" Quit now.") # window.stop() else: print(" No device found.") print(" before del cameraSystem.") del self.cameraSystem print(" after del cameraSystem.") cameraSystem = None
def vxltocsv(filename): print(" on vxl to csv ") """Converts VXL file to csv file""" camsys = PointCloud.CameraSystem() r = PointCloud.FrameStreamReader(filename, camsys) bool1, cols = r.getStreamParamu("frameWidth") bool2, rows = r.getStreamParamu("frameHeight") if not bool1 or not bool2: print("Cannot read the stream") if not r.isStreamGood(): print("Stream is not good: " + filename) numFrames = r.size() print(" numFrames:",numFrames) mAmplitudes = np.zeros(( rows, cols), dtype='float') mPhase = np.zeros(( rows, cols), dtype='float') pointX = 118 pointY = 142 outFileName = os.path.splitext(filename)[0] + '.csv' if outFileName: print("outFileName: ",outFileName) with open(outFileName, 'w') as f: for i in (range(numFrames)): if not r.readNext(): print("Failed to read frame %d" %i) break # Extract depth information depthFrame = PointCloud.DepthFrame.typeCast(r.frames[PointCloud.DepthCamera.FRAME_DEPTH_FRAME]) mDepths = np.array(depthFrame.depth, copy=True).reshape((rows, cols)) depth = mDepths[pointX][pointY] # Extract amplitude and phase information tofFrame = PointCloud.ToF1608Frame.typeCast(r.frames[PointCloud.DepthCamera.FRAME_RAW_FRAME_PROCESSED]) mAmplitudes = np.array(tofFrame._amplitude, copy=True).reshape((rows, cols)) mPhase = np.array(tofFrame._phase, copy=True).reshape((rows, cols)) amp = mAmplitudes[pointX][pointY] phase = mPhase[pointX][pointY] # print print("tofFrame.id is %s amp : %s phase : %s depth : %.4f" %(tofFrame.id,amp,phase,depth) ) content = "%5d,%5d,%.4f"%(amp,phase,depth) f.write(content+"\n") r.close() f.close()
def runrandom(self): rnd = np.random.RandomState(seed=self.seed) self.subsetindices = [] if self.subsetsize > self.pointcloud.size: raise Exception("Subset size can not be more than the size of the Pointcloud") elif self.subsetsize == self.pointcloud.size: self.subsetindices = range(0, self.pointcloud.size, 1) else: self.subsetindices = rnd.choice(self.pointcloud.size, self.subsetsize, replace=False) self.subsetpointcloud = pc.PointCloud(self.pointcloud.points[self.subsetindices])
def testRandomSelector(): # Create PointCloud matrixofpoints_inR2 = [] mean = [0, 0] cov = [[1, 0], [0, 1]] matrixofpoints_inR2 = np.random.multivariate_normal(mean, cov, 100) p = pc.PointCloud(matrixofpoints_inR2) # Create Selector s = sel.PointCloudSelector(p, 5, "RandomSelector") print s.getLandmarkPoints().points print s.getdistance_subsetstoPointcloud()
def ICPmatch(s_i, vCoords, vInd, spheres=None, tree=None, oldpts=None, linear=False, usetree=True): """ Finds the closest point on a given surface for each point in a given PointCloud :param s_i: PointCloud of points to find closest point :param vCoords: Coordinates of each vertex on surface :param vInd: Indices of vertices for each triangle on surface :param spheres: List of bounding spheres around triangles on surface. :param tree: tree data strucutre to search from (optional) :param oldpts: old closest points (optional) :param linear: true if linear search should be performed :param usetree: true if tree search should be used :type s_i: PointCloud.PointCloud :type vCoords: np.array([np.float64]) 3 x N :type vInd: np.array([np.float64]) 3 x M :type spheres: [bs.BoundingSphere] :type tree: tree.CovTreeNode :type oldpts: pc.PointCloud :type linear: bool :type usetree: bool :return: closest point on surface to each point in s_i :rtype: pc.PointCloud """ c_ij = np.zeros([3, np.shape(s_i.data)[1]]) old = None closest_pts = None if usetree: old = oldpts closest_pts = old for i in range(np.shape(s_i.data)[1]): if linear: c = findClosestPointLinear(s_i.data[:, i], vCoords, vInd) c_ij[:, i] = c[:] elif usetree: old_i = closest_pts.data[:, i] dist = np.linalg.norm(old_i - s_i.data[:, i]) closest = [old_i] bound = [dist] tree.FindClosestPoint(s_i.data[:, i], bound, closest) c_ij[:, i] = closest[0][:] else: c = findClosestPoint(s_i.data[:, i], vCoords, vInd, spheres) c_ij[:, i] = c[:] return pc.PointCloud(c_ij)
def drawClassification(terrain, objects, rtime, flag, runNumber=1): """ :param terrain: terrain cloud of points :param objects: objects cloud of points :param rtime: run time of the search in seconds :param flag: what does the user want to be drawn - 'terrain', 'objects' or 'all' :type terrain: array nX3 :type objects: array nX3 :type rtime: float :type flag: string :return: void """ c = PointCloud() print('Classification took ', rtime, 'seconds') print('terrain points: ', len(terrain), ' %: ', len(terrain) / (len(terrain) + len(objects))) print('object points: ', len(objects), ' %: ', len(objects) / (len(terrain) + len(objects))) c.drawFilteredPointCloud(objects, terrain, flag, runNumber=runNumber)
def __init__(self, nails, connects, scaleFactor, origin): self.pc = None self.connects = None self.origin = None self.scale = None self.safeZ = 15.0 self.feedRate = 2500 self.drillFeed = 1000 self.mposX = 0 self.mposY = 0 self.mposZ = 0 self.feed = 0 self.startZ = 0.6 self.threadThickness = 0.25 self.maxZ = 7.0 self.ramp_angle = 15 # degrees self.z_hop = 3 self.nailThreadHeights = None self.ramp_A_p = None self.ramp_A_z = 0 self.ramp_B_p = None self.ramp_B_z = 0 self.epsilon = 0.1 # moves smaller than this will be omitted (currently only z) self.pc = PointCloud(100, 100) self.pc.addFromList(nails) self.connects = connects self.connectHeight = [0.0] * len(connects) self.pc.translate(-origin.x, -origin.y) self.pc.scale(scaleFactor.x, scaleFactor.y) self.program = None self.resetProgram()
def comparebars(): maxdim = 2 filename = '/Users/naheed/PycharmProjects/PersistenceHomology/data/eight.mat' p = pc.MatlabPointCloud(filename, 'point_cloud') print p.dimension, p.size p.compute_distancematrix() print p.getdistance(0, 1) from src.RipsFiltration import BruteForceRips rf = BruteForceRips(p, 100, maxdim, 0.01) rf.construct() from src.ComputeInterval import IntervalComputation ci = IntervalComputation(rf) ci.compute_intervals(maxdim) print ci.betti_intervals from src.WeakWitnessFiltration import WeakWitnessStream filename = '/Users/naheed/PycharmProjects/PersistenceHomology/data/eight.mat' p2 = pc.MatlabPointCloud(filename, 'point_cloud') print p2.dimension, p2.size p2.compute_distancematrix() pointcloud_sel = sel.PointCloudSelector(p2, 200, "MaxminSelector") pointcloud_sel.select() R = 0.01 print "R= ", R ws = WeakWitnessStream(mu=1, landmarkselector=pointcloud_sel, maxdistance=R, numdivision=100, maxdimension=maxdim) ws.construct() ci2 = IntervalComputation(ws) ci2.compute_intervals(maxdim) # print len(ci2.betti_intervals), len(ci.betti_intervals) from src.Intervalviz import PersistenceViz pv = PersistenceViz(ci.betti_intervals, replace_Inf=rf.maxfiltration_val) pv.qual_compare_barcodes(ci2.betti_intervals, R)
def __init__(self, pc): self.pc = pc self.kmeans = KMeans(n_clusters=pc.numMols, # using scipy implementation of kmeans random_state=0).fit(pc.cartesianCoords) self.target = pc.generateTarget(pc.cartesianCoords) # generate targets self.classifications = self.kmeans.predict(pc.cartesianCoords) # predict clusters # Run performance metrics self.contingencyTable = self.generateContingencyTable(self.target, self.classifications) self.accuracy = self.calcAccuracy(self.contingencyTable) self.precision = self.calcPrecision(self.contingencyTable) self.recall = self.calcRecall(self.contingencyTable) self.falsePositiveRate = self.calcFPRate(self.contingencyTable) self.fMeasure = self.calcFMeasure(self.contingencyTable)
def p_dimple(optpivot_file, calbody_file): """ Computes expected EM marker positions on calibration object, given measured positions of markers on the object and data from each tracker. :param optpivot_file: File name/path for the calibration object data file :type optpivot_file: str :return: C_expected, a list of the expected positions of EM tracking markers on the calibration object for each frame of data :rtype: [PointCloud.PointCloud] """ opt_frames = pc.fromfile(optpivot_file) object_frame = pc.fromfile(calbody_file) f_d = opt_frames[0][0].register(object_frame[0][0]) for i in range(len(opt_frames)): opt_frames[i][1] = opt_frames[i][1].transform(f_d) p_cal, p_piv = piv.pivot(opt_frames, 1) return p_piv
def _FindBoundingBox(self, n): """ Finds the upper and lower bounds of a bounding box around this covariance tree. :param n: Number of triangles in the covariance tree. :type n: integer :return: upper and lower bounds of bounding box around this covariance tree :rtype: [] """ LB = pc.PointCloud(self.triangle_list[0].SortPoint()).transform( self.frame.inv).data bounds = [LB, LB] for k in range(n): bounds = self.triangle_list[k].EnlargeBounds(self.frame, bounds) self.bounds = bounds return bounds