示例#1
0
def find_bin(line):
	truth_cases = []
	for i in range(len(pent_polygons)):
		plane0 = Plane(Point3D(pent_polygons[i][0]), Point3D(pent_polygons[i][1]), Point3D(pent_polygons[i][2]))
		search_line = Line3D(Point3D(line), Point3D(0,0,0))
		plane_search_intersection = plane0.intersection(search_line)[0].evalf()

		point_plane_dist = plane0.distance(Point3D(line)).evalf()
		intersectionX = plane_search_intersection.x
		intersectionY = plane_search_intersection.y
		intersectionZ = plane_search_intersection.z
		intersection_line = (intersectionX, intersectionY, intersectionZ)

		print i
		true_or_false = check_projections(pent_polygons[i], intersection_line)
		print i

		for j in range(3):
			temp_string = 'xyz'
			if true_or_false[j] == 1:
				truth_cases.append((i,temp_string[j],point_plane_dist,'pent'))


	for i in range(len(hex_polygons)):
		plane0 = Plane(Point3D(hex_polygons[i][0]), Point3D(hex_polygons[i][1]), Point3D(hex_polygons[i][2]))
		search_line = Line3D(Point3D(line), Point3D(0,0,0))
		plane_search_intersection = plane0.intersection(search_line)[0].evalf()

		point_plane_dist = plane0.distance(Point3D(line)).evalf()
		intersectionX = plane_search_intersection.x
		intersectionY = plane_search_intersection.y
		intersectionZ = plane_search_intersection.z
		intersection_line = (intersectionX, intersectionY, intersectionZ)

		print i		
		true_or_false = check_projections(hex_polygons[i], intersection_line)
		print i

		for j in range(3):
			temp_string = 'xyz'
			if true_or_false[j] == 1:
				truth_cases.append((i,temp_string[j],point_plane_dist,'hex'))

	print truth_cases
    def ransac(self, triangulated_points):
        """ Feature rejection function
        :param triangulated_points: np array, (num_features, 3) all triangulated points
        :return bestinliers: (N, ), indices of the inliers, where N is the total number of inliers
        """
        # we only expect to have the 5-10% outliers, so we'll set the minimum inliers
        # to be 92% of the total number of features.
        num_features = triangulated_points.shape[0]

        # tunable parameters
        mininliers = .92 * num_features
        alpha = 0.042

        maxinliers = 0
        sympy_points = np.ndarray((num_features, 3))
        for j in range(num_features):
            sympy_points[j] = Point3D(triangulated_points[j, 0],
                                      triangulated_points[j, 1],
                                      triangulated_points[j, 2])

        # make an array of possible indices that we will randomly draw from
        for i in range(1000):
            # select 3 random points from triangulated points to compute a plane
            rand_pts = np.random.choice(triangulated_points.shape[0], 3)
            normal, d = self.compute_plane(triangulated_points[rand_pts, :])

            # make the points into a plane object
            plane = Plane(Point3D(triangulated_points[rand_pts[0], :]),
                          normal_vector=normal)

            # compute the reprojection error for all the points
            reproj = np.ndarray((num_features, ))
            for j in range(num_features):
                reproj[j] = plane.distance(Point3D(sympy_points[j, :]))
            # print(reproj)
            inliers = reproj < alpha
            ninliers = np.sum(inliers)

            # update the max values if applicable
            if ninliers > maxinliers:
                maxinliers = ninliers
                bestinliers = inliers
                # check exit condition
                if maxinliers > mininliers:
                    print('required', i + 1,
                          'RANSAC attempts to remove outliers.')
                    break

        print('number of inliers: ' + str(maxinliers))

        # returns the inlier indices, not the actual values
        return bestinliers
示例#3
0
    return float(ag)


toArray = lambda x: np.array(x).astype(float)


def degreeOfVictor(p1, p2):
    p1, p2 = map(toArray, (p1, p2))
    dotProduct = (p1 * p2).sum()
    norm = lambda p: (p**2).sum()**0.5
    angle = dotProduct / (norm(p1) * norm(p2))
    arccosDegree = lambda x: np.degrees(np.arccos(x))
    degree = arccosDegree(angle)
    return degree


#%%
if __name__ == '__main__':
    po = Point3D(0, 0, 0)
    #    print fitPointsToPlane(points)
    a.distance(po)

    l = Line3D((0, 0, 0), (1, 0, 0))
    l2 = Line3D((0, 1, 0), (0, 1, 1))

    a = Plane(Point3D(1, 1, 1), normal_vector=(1, 1, 1))
    b = a.perpendicular_line(Point3D(0, 0, 0))
    points = (1, 0, 0), (0, 1, 0), (0, 0, 1), (0.1, 0.1, 0.1)

    a.distance(Point3D(0, 0, 0))
    pass
示例#4
0
    def site_descriptors(self, COsites=[]):
        '''
        Calculate site specific descriptors
        '''

        # when the site indices are not provided
        if COsites == []:
            self.get_COsites()

        else:
            self.COsites = COsites

        # Numbef of sites
        self.Nsites = len(self.COsites)
        if self.Nsites == 3: self.sitetype = 'hollow'
        if self.Nsites == 2: self.sitetype = 'bridge'
        if self.Nsites == 1: self.sitetype = 'top'

        #indices of Pd atom at CO binding sites
        COsites_Pdi = []
        for s in range(len(self.COsites)):
            COsites_Pdi.append('Pd' + str(self.COsites[s]))

        # Get CO site position - the mean of Pd pos at the site
        COsites_Pdpos = []
        for i in self.COsites:
            COsites_Pdpos.append(self.atoms[i].position)
        self.site_pos = np.mean(COsites_Pdpos, axis=0)

        # Add a facticious C to the end
        atoms_C = self.atoms.copy()
        atoms_C.append(Atom('C', position=self.site_pos))
        # all Pd-site bond length
        Pd_site = atoms_C.get_distances(-1, self.Pdi, mic=True)
        # sorted Pd-site bond length
        Pd_site, _ = sort_i_and_d(Pd_site, self.Pdi)
        # Site distance to neighboring Pd atoms
        Pd_site_CO = np.array(Pd_site[:len(self.COsites)])

        #NN dataframe at CO binding site only
        PdNN_CO = self.PdNN.loc[:, COsites_Pdi]

        # Aprroximate Bond lengths by site-Pd length
        if not COsites == []:

            PdC3 = np.zeros(3)
            PdC3[:len(self.COsites)] = Pd_site_CO
            # Bond lengths
            self.PdC1 = PdC3[0]
            self.PdC2 = PdC3[1]
            self.PdC3 = PdC3[2]
        '''
        Weighted average for NN1, NN2, GCN
        '''
        #weights based on 1 over CO-Pd distance
        if self.Nsites == 1:  # for top site
            norm_weights = np.ones(1)  #avoid zero division problem
        else:
            norm_weights = (1 / Pd_site_CO) / np.sum(1 / Pd_site_CO)

        # CN1 and CN2
        self.CN1 = np.dot(norm_weights, PdNN_CO.loc['NN1'].values)
        self.CN2 = np.dot(norm_weights, PdNN_CO.loc['NN2'].values)

        # GCNs
        cn_max = [12, 18, 22]
        NN1_site = []
        #Iterate through each atom at the site
        for i in self.COsites:
            for j in self.Pd1NN['Pd' + str(i)]:
                NN1_site += list(self.Pd1NN['Pd' + str(j)])
        #Find non-repeating NN1 atoms for the site
        NN1_site = list(set(NN1_site))
        # Take out the atoms at the site
        NN1_site = [ni for ni in NN1_site if ni not in list(self.COsites)]
        #Add up CN numbers for those NN1 atoms
        gcn_sum = 0
        for ni in NN1_site:
            gcn_sum += self.PdNN.loc['NN1']['Pd' + str(ni)]
        #Normalize by the max GCNs
        self.GCN = gcn_sum / cn_max[self.Nsites - 1]
        '''
        '''
        #Weighted average for OCN and CeCN
        '''
        PdONN_CO = []
        PdCeNN_CO = []
        for si in COsites_Pdi:
            PdONN_CO.append(self.PdONN[si])
            PdCeNN_CO.append(self.PdCeNN[si])

        self.OCN1  = np.dot(np.array(PdONN_CO), norm_weights)
        self.CeCN1 = np.dot(np.array(PdCeNN_CO), norm_weights)
        '''
        '''
        Calculate distance to the support
        '''
        #take the  distance of CO to Ce plane (determined by 3 Ce points)
        # as the distance to support
        Ce_plane = Plane(Point3D(self.atoms[self.Cei[0]].position),
                         Point3D(self.atoms[self.Cei[1]].position),
                         Point3D(self.atoms[self.Cei[2]].position))
        self.Dsupport = float(Ce_plane.distance(Point3D(self.site_pos)))
示例#5
0
def alignMono(entry,
              prec=1E-4,
              seed_index=0,
              supercell=2,
              c_mag=50,
              dist_from_plane=0):
    """
    Align a 2D material such that the 'c' vector is perpendicular to the
    in-plane lattice vectors
    
    inputs
    --------
       entry (list): A set of components necessary for the TSA.
                      Makes it easier to parallelize with this as
                      the input
                      --structure (Structure): pymatgen Structure object
                      --tol (float): The scaling for the atomic bonds
                      --mp_id (str): The label for the entry, commonly
                                     the MaterialsProject ID

        
        prec (float):       The precision to compare magnitude of vectors
                            representing the bonds in the system     
                        
        seed_index (int):   The site to use as the starting point for the
                            TSA. Typically does not impact the results, but
                            will if the structure is a bipartide or has
                            mixed dimensionality    
                            
        supercell (int):    The supercell size to generate for 
                            periodic networks
                            
        c_mag (float):      The magnitude to make the non-periodic vectors
        
        dist_from_plane (float): Maximum distance an atom can be from the
                                 plane parallel to the monolayer. Is relevant 
                                 when the atoms in the monolayer are spread 
                                 across periodic boundary conditions in the 
                                 unit cell
                                 
        
        
    returns
    --------
        list1 (list): -fractional coordinates in new lattice
                     -new lattice (a,b,c)
                     -species associated with each site
        list1 (list): -fractional coordinates in new lattice
                     -new lattice (b,a,c)
                     -species associated with each site
    
    """

    # Keep original copy of structure
    s = copy.deepcopy(entry[0])

    new_latt = getNewLattice(entry,
                             dim=2,
                             prec=prec,
                             seed_index=seed_index,
                             supercell=supercell,
                             c_mag=c_mag)

    # Identify plane to translate atoms towards
    plane = Plane(Point3D(s.sites[seed_index].coords),
                  normal_vector=new_latt[2])

    # Create list of translationss
    trans = list(itertools.product([1, -1, 0], repeat=3))

    lat = s.lattice.as_dict()['matrix']
    final_sites = []
    i = 0

    # Ensure that the atoms are nearby each other
    for site in s.sites:
        point = Point3D(site.coords)
        if plane.distance(point) < dist_from_plane:
            final_sites.append(site.coords)
        else:
            news = []

            # translate atomic sites to see which position is closest to plane
            for t in trans:
                point = Point3D(site.coords + np.dot(np.transpose(lat), t))
                news.append([float(plane.distance(point)), t])
            news.sort(key=lambda x: x[0])
            final_sites.append(site.coords +
                               np.dot(np.transpose(lat), news[0][1]))
        i += 1

    # Create new lattice matricies
    lat1 = np.array([new_latt[0], new_latt[1], new_latt[2]])
    lat2 = np.array([new_latt[1], new_latt[0], new_latt[2]])

    # Generate atomic fractions
    new_fracs1 = np.linalg.solve(lat1.T, np.array(final_sites).T).T
    new_fracs2 = np.linalg.solve(lat2.T, np.array(final_sites).T).T
    species = s.species
    return ([species, new_fracs1, lat1], [species, new_fracs2, lat2])
 zLP1 = Lparam[_sage_const_2].subs(t=tt)
 # запишем наши объекты через sympy
 from sympy import Plane, Point, Point3D, Line3D
 Psp = Plane(Point3D(pointP), normal_vector=n)
 M1sp = Point3D(M1)
 prtemp = Psp.projection(M1sp)
 # проекция M1 на P
 prM1P = vector([prtemp.x._sage_(), prtemp.y._sage_(), prtemp.z._sage_()])
 # наша L через sympy
 Lsp = Line3D(pointL, point2L)
 prtemp = Lsp.projection(M1sp)
 # проекция M1 на L
 prM1L = vector([prtemp.x._sage_(), prtemp.y._sage_(), prtemp.z._sage_()])
 # расстояние от M2 до P2
 P2sp = Plane(Point3D(M1), normal_vector=n2)
 dM2P2 = P2sp.distance(Point3D(M2))
 # плоскость через M1 и L
 P6 = Simp_Plane(Make_Plane(M1, pointL - M1, sL))
 # проекция L1 на P
 # уравнение L1 в параметрическом виде
 pointL1 = vector([
     M2[_sage_const_0] + a[_sage_const_0],
     M2[_sage_const_1] + a[_sage_const_1],
     M2[_sage_const_2] + a[_sage_const_2]
 ])
 M2sp = Point3D(M2)
 pointL1sp = Point3D(pointL1)
 # проекция M2 на P
 prtemp = Psp.projection(M2sp)
 prM2P = vector([prtemp.x._sage_(), prtemp.y._sage_(), prtemp.z._sage_()])
 # проекция pointL1 на P