def normalized_formula_parts(assignments, ratios, counts): formula = {} alloccs = {} maxc = 0 for i in range(len(counts)): assignment = assignments[i] ratio = ratios[i] if not assignment in formula: formula[assignment] = FracVector.create(0) alloccs[assignment] = FracVector.create(0) occ = ratio formula[assignment] += occ * counts[i] alloccs[assignment] += FracVector.create(counts[i]) if alloccs[assignment] > maxc: maxc = alloccs[assignment] alloccs = FracVector.create(alloccs.values()) alloccs = (alloccs / maxc).simplify() for symbol in formula.keys(): formula[symbol] = (formula[symbol] * alloccs.denom / maxc).simplify() # if abs(value-int(value))<1e-6: # formula[symbol] = int(value) # elif int(100*(value-(int(value)))) > 1: # formula[symbol] = float("%d.%.2e" % (value, 100*(value-(int(value))))) # else: # formula[symbol] = float("%d" % (value,)) return formula
def __init__(self, niggli_matrix, orientation=1, basis=None): """ Private constructor, as per httk coding guidelines. Use Cell.create instead. """ self.niggli_matrix = niggli_matrix self.orientation = orientation if basis is None: basis = FracVector.use( niggli_to_basis(niggli_matrix, orientation=orientation)) c = basis maxele = max(c[0, 0], c[0, 1], c[0, 2], c[1, 0], c[1, 1], c[1, 2], c[2, 0], c[2, 1], c[2, 2]) maxeleneg = max(-c[0, 0], -c[0, 1], -c[0, 2], -c[1, 0], -c[1, 1], -c[1, 2], -c[2, 0], -c[2, 1], -c[2, 2]) if maxeleneg > maxele: scale = (-maxeleneg).simplify() else: scale = (maxele).simplify() basis = (basis * scale.inv()).simplify() self._basis = basis self.det = basis.det() self.inv = basis.inv() self.volume = abs(self.det) self.metric = niggli_to_metric(self.niggli_matrix) self.lengths, self.angles = niggli_to_lengths_angles( self.niggli_matrix) self.lengths = [FracVector.use(x).simplify() for x in self.lengths] self.angles = [FracVector.use(x).simplify() for x in self.angles] self.a, self.b, self.c = self.lengths self.alpha, self.beta, self.gamma = self.angles
def main(): cell = FracVector.create([[1, 1, 0], [1, 0, 1], [0, 1, 1]]) coordgroups = FracVector.create([[[2, 3, 5], [3, 5, 4]], [[4, 6, 7]]]) assignments = [2, 5] print(cell, coordgroups) cell, coordgroups = coordswap(0, 2, cell, coordgroups) print(cell, coordgroups) pass
def add_phase(self, symbols, counts, id, energy): """ Handles energy=None, for a phase we don't know the energy of. """ counts = FracVector.use(counts) phase = {} # In Python 3 symbols in an iterator, so we should convert it to # a list. symbols = list(symbols) for i in range(len(symbols)): symbol = symbols[i] if symbol in phase: phase[symbol] += counts[i] else: phase[symbol] = counts[i] self.seen_symbols[symbol] = True if energy is not None: self.phases += [phase] self.energies += [energy] self.ids += [id] else: self.other_phases += [phase] self.other_ids += [id] # Clear out so things get reevaluated self._reset()
def read_coords_occs(results, match): if results['in_input']: coordstr = 'sgcoords' occstr = 'sgoccupancies' seenstr = 'sgseen' idxstr = 'sgidx' elif results['in_output']: coordstr = 'coords' occstr = 'occupancies' seenstr = 'seen' idxstr = 'idx' else: return newcoord = (match.group(2), match.group(3), match.group(4)) #newcoord = FracVector.create([match.group(2),match.group(3),match.group(4)]).limit_denominator(5000000).simplify() species = match.group(1).split("/") occups = match.group(6).split("/") for j in range(len(species)): occup = {'atom': periodictable.atomic_number(species[j]), 'ratio': FracVector.create(occups[j]), } if newcoord in results[seenstr]: idx = results[seenstr][newcoord] #print("OLD",results[occstr],idx) results[occstr][idx].append(occup) else: results[seenstr][newcoord] = results[idxstr] results[coordstr].append(newcoord) results[occstr].append([occup]) results[idxstr] += 1
def read_coords(results, match): if not results['in_setting']: results['setting'].append({'coords': [], 'occupancies': [], 'wyckoff': [], 'multiplicities': []}) results['in_setting'] = True newcoord = FracVector.create([match.group(4), match.group(5), match.group(6)]).limit_denominator(5000000).simplify() #print("CHECK1",[match.group(4),match.group(5),match.group(6)]) #print("CHECK2:",newcoord) results['setting'][-1]['coords'].append([match.group(4), match.group(5), match.group(6)]) if based_on_struct is None: results['setting'][-1]['occupancies'].append(match.group(1)) else: abstract_symbol = match.group(1).strip() index = httk.basic.anonymous_symbol_to_int(abstract_symbol) results['setting'][-1]['occupancies'].append(based_on_struct.assignments[index]) wyckoff_string = match.group(3) wyckoff_symbol = wyckoff_string[wyckoff_string.index("(") + 1:wyckoff_string.rindex(")")] multiplicity = int(wyckoff_string[:wyckoff_string.index("(")]) results['setting'][-1]['wyckoff'].append(wyckoff_symbol) results['setting'][-1]['multiplicities'].append(multiplicity) results['in_setting'] = True
def niggli_vol_to_scale(niggli_matrix, vol): niggli_matrix = FracVector.use(niggli_matrix) metric = niggli_to_metric(niggli_matrix) volsqr = metric.det() if volsqr == 0: raise Exception("niggli_vol_to_scale: singular cell matrix.") det = sqrt(float(volsqr)) return (float(vol) / det)**(1.0 / 3.0)
def coordgroups_to_coords(coordgroups): coords = [] counts = [len(x) for x in coordgroups] for group in coordgroups: for i in range(len(group)): coords.append(group[i]) coords = FracVector.stack_vecs(coords) return coords, counts
def cubic_supercell_transformation(structure, tolerance=None, max_search_cells=1000): # Note: a better name for tolerance is max_extension or similar, it is not really a tolerance, it regulates the maximum number of repetitions of the primitive cell # in any directions to reach the soughts supercell if tolerance is None: prim_cell = structure.uc_cell.basis inv = prim_cell.inv().simplify() transformation = (inv * inv.denom).simplify() else: maxtol = max(int(FracVector.use(tolerance)), 2) bestlen = None bestortho = None besttrans = None #TODO: This loop may be possible to do with fewer iterations, since I suppose the only thing that #matter is the prime factors? for tol in range(1, maxtol): prim_cell = structure.uc_cell.basis prim_cell = structure.uc_cell.basis approxinv = prim_cell.inv().set_denominator(tol).simplify() if approxinv[0] == [0, 0, 0] or approxinv[1] == [ 0, 0, 0 ] or approxinv[2] == [0, 0, 0]: continue transformation = (approxinv * approxinv.denom).simplify() try: cell = Cell.create(basis=transformation * prim_cell) except Exception: continue ortho = (abs(cell.niggli_matrix[1][0]) + abs(cell.niggli_matrix[1][1]) + abs(cell.niggli_matrix[1][2])).simplify() equallen = abs(cell.niggli_matrix[0][0] - cell.niggli_matrix[0][1] ) + abs(cell.niggli_matrix[0][0] - cell.niggli_matrix[0][2]) if ortho == 0 and equallen == 0: # Already perfectly cubic, use this besttrans = transformation break elif bestlen is None or not (bestortho < ortho and bestlen < equallen): bestlen = equallen bestortho = ortho besttrans = transformation elif besttrans == None: bestlen = equallen bestortho = ortho besttrans = transformation transformation = besttrans if transformation == None: raise Exception( "Not possible to find a cubic supercell with this limitation of number of repeated cell (increase tolerance.)" ) return transformation
def niggli_scale_to_vol(niggli_matrix, scale): niggli_matrix = FracVector.use(niggli_matrix) metric = niggli_to_metric(niggli_matrix) volsqr = metric.det() if volsqr == 0: raise Exception("niggli_vol_to_scale: singular cell matrix.") det = sqrt(float(volsqr)) if abs(det) < 1e-12: raise Exception("niggli_scale_to_vol: singular cell matrix.") return (((scale)**3) * det)
def reduced_to_cartesian(cell, coordgroups): cell = FracVector.use(cell) newcoordgroups = [] for coordgroup in coordgroups: newcoordgroup = coordgroup * cell newcoordgroups.append(newcoordgroup) return newcoordgroups
def occupations_and_coords_to_assignments_and_coordgroups( occupationscoords, occupations): if len(occupationscoords) == 0: return [], FracVector((), 1) occupationscoords = FracVector.use(occupationscoords) new_coordgroups = [] new_assignments = [] for i in range(len(occupations)): for j in range(len(new_assignments)): if occupations[i] == new_assignments[j]: new_coordgroups[j].append(occupationscoords[i]) break else: new_coordgroups.append([occupationscoords[i]]) new_assignments.append(occupations[i]) new_coordgroups = FracVector.create(new_coordgroups) return new_assignments, new_coordgroups
def cartesian_to_reduced(cell, coordgroups): cell = FracVector.use(cell) cellinv = cell.inv() newcoordgroups = [] for coordgroup in coordgroups: newcoordgroup = coordgroup * cellinv newcoordgroups.append(newcoordgroup) return newcoordgroups
def coordgroups_cartesian_to_reduced(coordgroups, basis): basis = FracVector.use(basis) cellinv = basis.inv() newcoordgroups = [] for coordgroup in coordgroups: newcoordgroup = coordgroup * cellinv newcoordgroups.append(newcoordgroup) return newcoordgroups
def clean_coordgroups_and_assignments(coordgroups, assignments): if len(assignments) != len(coordgroups): raise Exception( "Occupations and coords needs to be of the same length.") if len(assignments) == 0: return [], FracVector((), 1) new_coordgroups = [] new_assignments = [] for i in range(len(assignments)): for j in range(len(new_assignments)): if assignments[i] == new_assignments[j]: idx = j new_coordgroups[idx] = FracVector.chain_vecs( [new_coordgroups[idx], coordgroups[i]]) break else: new_coordgroups.append(coordgroups[i]) new_assignments.append(assignments[i]) idx = len(coordgroups) - 1 return new_coordgroups, new_assignments
def read_coords(results, match): sys.stdout.write("\n>>|") #for i in range(1,14): # sys.stdout.write(match.group(i)+"|") species = periodictable.atomic_number(match.group(1)) ratio = FracVector.create(re.sub(r'\([^)]*\)', '', match.group(11))) a1 = re.sub(r'\([^)]*\)', '', match.group(2)) b1 = re.sub(r'\([^)]*\)', '', match.group(3)) c1 = re.sub(r'\([^)]*\)', '', match.group(4)) a = match.group(2).replace('(', '').replace(')', '') b = match.group(3).replace('(', '').replace(')', '') c = match.group(4).replace('(', '').replace(')', '') coord = FracVector.create([a1, b1, c1]).normalize() sys.stdout.write(str(species)+" "+str(coord.to_floats())) limcoord = FracVector.create([a1, b1, c1]).normalize() coordtuple = ((species, ratio.to_tuple()), limcoord.to_tuple()) if coordtuple in seen_coords: return results['occupancies'].append((species, float(ratio))) results['coords'].append(coord) seen_coords.add(coordtuple)
def basis_to_niggli(basis): basis = FracVector.use(basis) A = basis.noms det = basis.det() if det == 0: raise Exception("basis_to_niggli: singular cell matrix.") if det > 0: orientation = 1 else: orientation = -1 s11 = A[0][0] * A[0][0] + A[0][1] * A[0][1] + A[0][2] * A[0][2] s22 = A[1][0] * A[1][0] + A[1][1] * A[1][1] + A[1][2] * A[1][2] s33 = A[2][0] * A[2][0] + A[2][1] * A[2][1] + A[2][2] * A[2][2] s23 = A[1][0] * A[2][0] + A[1][1] * A[2][1] + A[1][2] * A[2][2] s13 = A[0][0] * A[2][0] + A[0][1] * A[2][1] + A[0][2] * A[2][2] s12 = A[0][0] * A[1][0] + A[0][1] * A[1][1] + A[0][2] * A[1][2] new = FracVector.create(((s11, s22, s33), (2 * s23, 2 * s13, 2 * s12)), denom=basis.denom**2).simplify() return new, orientation
def niggli_to_cell_old(niggli_matrix, orientation=1): cell = FracVector.use(niggli_matrix) niggli_matrix = niggli_matrix.to_floats() s11, s22, s33 = niggli_matrix[0][0], niggli_matrix[0][1], niggli_matrix[0][ 2] s23, s13, s12 = niggli_matrix[1][0] / 2.0, niggli_matrix[1][ 1] / 2.0, niggli_matrix[1][2] / 2.0 a, b, c = sqrt(s11), sqrt(s22), sqrt(s33) alpha_rad, beta_rad, gamma_rad = acos(s23 / (b * c)), acos( s13 / (c * a)), acos(s12 / (a * b)) iv = 1 - cos(alpha_rad)**2 - cos(beta_rad)**2 - cos( gamma_rad)**2 + 2 * cos(alpha_rad) * cos(beta_rad) * cos(gamma_rad) # Handle that iv may be very, very slightly < 0 by the floating point accuracy limit if iv > 0: v = sqrt(iv) else: v = 0.0 if c * v < 1e-14: raise Exception( "niggli_to_cell: Physically unreasonable cell, cell vectors degenerate or very close to degenerate." ) if orientation < 0: cell = [[-a, 0.0, 0.0], [-b * cos(gamma_rad), -b * sin(gamma_rad), 0.0], [ -c * cos(beta_rad), -c * (cos(alpha_rad) - cos(beta_rad) * cos(gamma_rad)) / sin(gamma_rad), -c * v / sin(gamma_rad) ]] else: cell = [[a, 0.0, 0.0], [b * cos(gamma_rad), b * sin(gamma_rad), 0.0], [ c * cos(beta_rad), c * (cos(alpha_rad) - cos(beta_rad) * cos(gamma_rad)) / sin(gamma_rad), c * v / sin(gamma_rad) ]] for i in range(3): for j in range(3): cell[i][j] = round(cell[i][j], 14) return cell
def coordswap(fromidx, toidx, cell, coordgroups): new_coordgroups = [] for group in coordgroups: coords = MutableFracVector.from_FracVector(group) rows = coords[:, toidx] coords[:, toidx] = coords[:, fromidx] coords[:, fromidx] = rows new_coordgroups.append(coords.to_FracVector()) coordgroups = FracVector.create(new_coordgroups) cell = MutableFracVector.from_FracVector(cell) row = cell[toidx] cell[toidx] = cell[fromidx] cell[fromidx] = row cell = cell.to_FracVector() return (cell, coordgroups)
def coords_and_occupancies_to_coordgroups_and_assignments(coords, occupancies): if len(occupancies) != len(coords): raise Exception( "Occupations and coords needs to be of the same length.") if len(occupancies) == 0: return [], FracVector((), 1) coordgroups = [] group_occupancies = [] for i in range(len(occupancies)): try: idx = group_occupancies.index(occupancies[i]) except ValueError: idx = len(group_occupancies) group_occupancies.append(occupancies[i]) coordgroups.append([]) coordgroups[idx].append(coords[i]) return coordgroups, group_occupancies
def normalized_formula_parts(assignments, ratios, counts): formula = {} alloccs = {} maxc = 0 for i in range(len(counts)): assignment = assignments[i] ratio = ratios[i] if is_sequence(assignment): if len(assignment) == 1: assignment = assignment[0] ratio = ratio[0] occ = ratio else: assignment = tuple([(x, FracVector.use(y)) for x, y in zip(assignment, ratio)]) occ = 1 else: occ = ratio if not assignment in formula: formula[assignment] = FracVector.create(0) alloccs[assignment] = FracVector.create(0) formula[assignment] += FracVector.create(occ * counts[i]) alloccs[assignment] += FracVector.create(counts[i]) if alloccs[assignment] > maxc: maxc = alloccs[assignment] alloccs = FracVector.create(alloccs.values()) alloccs = (alloccs / maxc).simplify() for symbol in formula.keys(): formula[symbol] = (formula[symbol] * alloccs.denom / maxc).simplify() # if abs(value-int(value))<1e-6: # formula[symbol] = int(value) # elif int(100*(value-(int(value)))) > 1: # formula[symbol] = float("%d.%.2e" % (value, 100*(value-(int(value))))) # else: # formula[symbol] = float("%d" % (value,)) return formula
def transform(structure, transformation, max_search_cells=20, max_atoms=1000): transformation = FracVector.use(transformation).simplify() #if transformation.denom != 1: # raise Exception("Structure.transform requires integer transformation matrix") old_cell = structure.uc_cell new_cell = Cell.create(basis=transformation * old_cell.basis) conversion_matrix = (old_cell.basis * new_cell.inv).simplify() volume_ratio = abs( (new_cell.basis.det() / abs(old_cell.basis.det()))).simplify() seek_counts = [ int((volume_ratio * x).simplify()) for x in structure.uc_counts ] #print("HMM",(new_cell.basis.det()/old_cell.basis.det()).simplify()) #print("SEEK_COUNTS",seek_counts, volume_ratio, structure.uc_counts, transformation) total_seek_counts = sum(seek_counts) if total_seek_counts > max_atoms: raise Exception("Structure.transform: more than " + str(max_atoms) + " needed. Change limit with max_atoms parameter.") #if max_search_cells != None and maxvec[0]*maxvec[1]*maxvec[2] > max_search_cells: # raise Exception("Very obtuse angles in cell, to search over all possible lattice vectors will take a very long time. To force, set max_search_cells = None when calling find_prototypeid()") ### Collect coordinate list of all sites inside the new cell coordgroups = structure.uc_reduced_coordgroups extendedcoordgroups = [[] for x in range(len(coordgroups))] if max_search_cells is not None: max_search = [max_search_cells, max_search_cells, max_search_cells] else: max_search = None for offset in breath_first_idxs(dim=3, end=max_search, negative=True): #print("X",offset, seek_counts) for idx in range(len(coordgroups)): coordgroup = coordgroups[idx] newcoordgroup = coordgroup + FracVector([offset] * len(coordgroup)) new_reduced = newcoordgroup * conversion_matrix #print("NEW:",FracVector.use(new_reduced).to_floats(),) new_reduced = [ x for x in new_reduced if x[0] >= 0 and x[1] >= 0 and x[2] >= 0 and x[0] < 1 and x[1] < 1 and x[2] < 1 ] extendedcoordgroups[idx] += new_reduced c = len(new_reduced) seek_counts[idx] -= c total_seek_counts -= c #print("ADD",str(c)) if seek_counts[idx] < 0: #print("X",offset, seek_counts) raise Exception( "Structure.transform safety check error, internal error: too many atoms in supercell." ) if total_seek_counts == 0: break else: raise Exception( "Very obtuse angles in cell, to search over all possible lattice vectors will take a very long time. To force, set max_search_cells = None when calling find_prototypeid()" ) return structure.create(uc_reduced_coordgroups=extendedcoordgroups, uc_basis=new_cell.basis, assignments=structure.assignments)
def out_to_struct(ioa): """ Example input:: OUTPUT CELL INFORMATION Symmetry information: Trigonal crystal system. Space group number : 165 Hall symbol : -P 3 2"c Hermann-Mauguin symbol : P-3c1 Bravais lattice vectors : 0.8660254 -0.5000000 0.0000000 0.0000000 1.0000000 0.0000000 0.0000000 0.0000000 1.0231037 All sites, (lattice coordinates): Atom a1 a2 a3 La 0.6609000 0.0000000 0.2500000 La 0.3391000 0.0000000 0.7500000 ... F 0.0000000 0.0000000 0.2500000 F 0.0000000 0.0000000 0.7500000 Unit cell volume : 328.6477016 A^3 Unit cell density : 3.5764559 u/A^3 = 5.9388437 g/cm^3 """ results = {} results['output_cell'] = [] results['input_cell'] = [] results['coords'] = [] results['sgcoords'] = [] results['occupancies'] = [] results['sgoccupancies'] = [] results['in_output'] = False results['in_input'] = False results['in_input_coords'] = False results['in_coords'] = False results['in_cell'] = False results['in_input_cell'] = False results['in_bib'] = False results['bib'] = "" results['seen'] = {} results['sgseen'] = {} results['idx'] = 0 results['sgidx'] = 0 def read_cell(results, match): if results['in_input']: results['input_cell'].append([(match.group(1)), (match.group(2)), (match.group(3))]) elif results['in_output']: results['output_cell'].append([(match.group(1)), (match.group(2)), (match.group(3))]) def read_coords_occs(results, match): if results['in_input']: coordstr = 'sgcoords' occstr = 'sgoccupancies' seenstr = 'sgseen' idxstr = 'sgidx' elif results['in_output']: coordstr = 'coords' occstr = 'occupancies' seenstr = 'seen' idxstr = 'idx' else: return newcoord = (match.group(2), match.group(3), match.group(4)) #newcoord = FracVector.create([match.group(2),match.group(3),match.group(4)]).limit_denominator(5000000).simplify() species = match.group(1).split("/") occups = match.group(6).split("/") for j in range(len(species)): occup = {'atom': periodictable.atomic_number(species[j]), 'ratio': FracVector.create(occups[j]), } if newcoord in results[seenstr]: idx = results[seenstr][newcoord] #print("OLD",results[occstr],idx) results[occstr][idx].append(occup) else: results[seenstr][newcoord] = results[idxstr] results[coordstr].append(newcoord) results[occstr].append([occup]) results[idxstr] += 1 #print("NEW",results[occstr],results[idxstr]) def read_coords(results, match): if results['in_input']: coordstr = 'sgcoords' occstr = 'sgoccupancies' seenstr = 'sgseen' idxstr = 'sgidx' elif results['in_output']: coordstr = 'coords' occstr = 'occupancies' seenstr = 'seen' idxstr = 'idx' else: return newcoord = (match.group(2), match.group(3), match.group(4)) #newcoord = FracVector.create([match.group(2),match.group(3),match.group(4)]).limit_denominator(5000000).simplify() species = match.group(1) occup = {'atom': periodictable.atomic_number(species)} if newcoord in results[seenstr]: idx = results[seenstr][newcoord] #print("XOLD",results[occstr],idx) results[occstr][idx].append(occup) else: results[seenstr][newcoord] = results[idxstr] results[coordstr].append(newcoord) results[occstr].append([occup]) results[idxstr] += 1 #print("XNEW",results[occstr],results['idx']) #if results['in_input']: # results['sgcoords'].append(newcoord) # results['sgoccupancies'].append(periodictable.atomic_symbol(match.group(1))) #elif results['in_output']: # results['coords'].append(newcoord) # results['occupancies'].append(periodictable.atomic_symbol(match.group(1))) def read_volume(results, match): results['volume'] = match.group(1) def read_hall(results, match): if results['in_input']: results['sghall'] = match.group(1) elif results['in_output']: results['hall'] = match.group(1) def read_id(results, match): results['id'] = match.group(1) def coords_stop(results, match): results['in_coords'] = False def coords_start(results, match): if results['in_input']: results['in_input_coords'] = True elif results['in_output']: results['in_coords'] = True def cell_stop(results, match): results['in_cell'] = False def input_cell_stop(results, match): results['in_input_cell'] = False def cell_start(results, match): results['in_cell'] = True def input_cell_start(results, match): results['in_input_cell'] = True def output_start(results, match): results['in_output'] = True results['in_input'] = False def read_version(results, match): results['version'] = match.group(1) def read_name(results, match): expr = httk.basic.parse_parexpr(match.group(1)) # Grab the last, nested, parenthesed expression p = "" for x in expr: if x[0] == 0: p = x[1] results['name'] = p def read_bib(results, match): if match.group(1).strip() != 'Failed to get author information, No journal information': results['bib'] += match.group(1).strip() def bib_start(results, match): results['in_bib'] = True def bib_stop_input_start(results, match): results['in_bib'] = False results['in_input'] = True def read_source(results, match): results['source'] = match.group(1).rstrip('.') out = httk.basic.micro_pyawk(ioa, [ ['^ *INPUT CELL INFORMATION *$', None, bib_stop_input_start], ['^ *CIF2CELL ([0-9.]*)', None, read_version], ['^ *Output for (.*\)) *$', None, read_name], ['^ *Database reference code: *([0-9]+)', None, read_id], ['^ *All sites, (lattice coordinates): *$', lambda results, match: results['in_cell'], cell_stop], ['^ *Representative sites *: *$', lambda results, match: results['in_input_cell'], input_cell_stop], ['^ *$', lambda results, match: results['in_coords'], coords_stop], ['^ *([-0-9.]+) +([-0-9.]+) +([-0-9.]+) *$', lambda results, match: results['in_cell'] or results['in_input_cell'], read_cell], ['^ *([a-zA-Z]+) +([-0-9.]+) +([-0-9.]+) +([-0-9.]+) *$', lambda results, match: results['in_coords'] or results['in_input_coords'], read_coords], ['^ *([a-zA-Z/]+) +([-0-9.]+) +([-0-9.]+) +([-0-9.]+)( +([-0-9./]+)) *$', lambda results, match: results['in_coords'] or results['in_input_coords'], read_coords_occs], # ['^ *Hermann-Mauguin symbol *: *(.*)$',lambda results,match: results['in_output'],read_spacegroup], ['^ *Hall symbol *: *(.*)$', lambda results, match: results['in_output'] or results['in_input'], read_hall], ['^ *Unit cell volume *: *([-0-9.]+) +A\^3 *$', lambda results, match: results['in_output'], read_volume], ['^ *Bravais lattice vectors : *$', lambda results, match: results['in_output'], cell_start], ['^ *Lattice parameters: *$', lambda results, match: results['in_input'], input_cell_start], ['^ *Atom +a1 +a2 +a3', lambda results, match: results['in_output'] or results['in_input'], coords_start], ['^ *OUTPUT CELL INFORMATION *$', None, output_start], ['^([^\n]*)$', lambda results, match: results['in_bib'], read_bib], ['^ *BIBLIOGRAPHIC INFORMATION *$', None, bib_start], ['CIF file exported from +(.*) *$', None, read_source] ], debug=False, results=results) out['bib'] = out['bib'].strip() rc_a, rc_b, rc_c = [float(x) for x in out['input_cell'][0]] rc_alpha, rc_beta, rc_gamma = [float(x) for x in out['input_cell'][1]] uc_a, uc_b, uc_c = [float(x) for x in out['output_cell'][0]] uc_alpha, uc_beta, uc_gamma = [float(x) for x in out['output_cell'][1]] rc_cell = FracVector.create(out['input_cell']) uc_cell = FracVector.create(out['output_cell']) coords = FracVector.create(out['coords']).limit_denominator(5000000).simplify() sgcoords = FracVector.create(out['sgcoords']).limit_denominator(5000000).simplify() hall_symbol = out['hall'] sghall_symbol = out['sghall'] tags = {} if 'source' in out: tags['source'] = out['source']+":"+out['id'] if 'bib' in out and out['bib'] != '': refs = [out['bib']] else: refs = None if 'name' in out: tags['name'] = filter(lambda x: x in string.printable, out['name']) # This is to handle a weird corner case, where atoms in a disordered structure # are placed on equivalent but different sites in the representative representation; then # they will be mapped to the same sites in the filled cell. Our solution in that case is # to throw away the rc_cell, since it is incorrect - it has equivalent sites that appear # different even though they are the same. remaining_filled_sites = list(out['occupancies']) for i in range(len(out['sgoccupancies'])): if out['sgoccupancies'][i] in remaining_filled_sites: remaining_filled_sites = filter(lambda a: a != out['sgoccupancies'][i], remaining_filled_sites) if len(remaining_filled_sites) > 0: rc_cell_broken = True else: rc_cell_broken = False if not rc_cell_broken: struct = Structure.create(rc_lengths=rc_cell[0], rc_angles=rc_cell[1], rc_reduced_occupationscoords=sgcoords, uc_cell=uc_cell, uc_reduced_occupationscoords=coords, uc_volume=out['volume'], rc_occupancies=out['sgoccupancies'], uc_occupancies=out['occupancies'], spacegroup=sghall_symbol, tags=tags, refs=refs, periodicity=0) else: struct = Structure.create(uc_cell=uc_cell, uc_reduced_occupationscoords=coords, uc_volume=out['volume'], uc_occupancies=out['occupancies'], spacegroup=sghall_symbol, tags=tags, refs=refs, periodicity=0) # A bit of santiy check to trigger on possible bugs from cif2cell if len(struct.uc_sites.counts) != len(struct.rc_sites.counts): print(struct.uc_sites.counts, struct.rc_sites.counts) raise Exception("cif2cell_if.out_to_struct: non-sensible parsing of cif2cell output.") #if 'volume' in out: # vol = FracVector.create(out['volume']) #else: # volstruct = httk.Structure.create(a=a,b=b,c=c,alpha=alpha,beta=beta,gamma=gamma, occupancies=out['sgoccupancies'], coords=sgcoords, hall_symbol=sghall_symbol, refs=refs) # vol = volstruct.volume #struct = httk.Structure.create(cell,occupancies=out['occupancies'],coords=coords,volume=vol,tags=tags,hall_symbol=hall_symbol, refs=refs) #struct._sgstructure = httk.SgStructure.create(a=a,b=b,c=c,alpha=alpha,beta=beta,gamma=gamma, occupancies=out['sgoccupancies'], coords=sgcoords, hall_symbol=sghall_symbol) #print("HERE WE ARE:",out['sgoccupancies'],sgcoords,sghall_symbol) #print("HERE WE ARE:",out['occupancies'],coords) #struct = httk.Structure.create(cell, volume=vol, unique_occupations=out['sgoccupancies'], uc_occupations=out['occupancies'], unique_reduced_occupationscoords=sgcoords, uc_reduced_occupationscoords=coords, spacegroup=sghall_symbol, tags=tags, refs=refs, periodicity=0) #print("HERE",sgcoords, coords) #counts = [len(x) for x in out['occupancies']] #p1structure = httk.Structure.create(cell,occupancies=out['occupancies'],coords=coords,volume=vol,tags=tags, refs=refs, periodicity=0) #struct.set_p1structure(p1structure) return struct
def coords_reduced_to_cartesian(cell, coords): cell = FracVector.use(cell) newcoords = coords * cell return newcoords
def get_primitive_basis_transform(hall_symbol): """ Transform to be applied to conventional unit cell to give the primitive unit cell """ half = Fraction(1, 2) lattice_symbol = hall_symbol.lstrip("-")[0][0] crystal_system = crystal_system_from_hall(hall_symbol) lattrans = None unit = FracVector.create([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) if lattice_symbol == 'P': lattrans = unit elif crystal_system == 'cubic': if lattice_symbol == 'F': lattrans = FracVector.create([[half, half, 0], [half, 0, half], [0, half, half]]) elif lattice_symbol == 'I': lattrans = FracVector.create([[half, half, half], [-half, half, half], [-half, -half, half]]) elif crystal_system == 'hexagonal' or crystal_system == 'trigonal': if lattice_symbol == 'R': lattrans = unit elif crystal_system == 'tetragonal': if lattice_symbol == 'I': lattrans = FracVector.create([[half, -half, half], [half, half, half], [-half, -half, half]]) elif crystal_system == 'orthorhombic': if lattice_symbol == 'A': lattrans = FracVector.create([[1, 0, 0], [0, half, half], [0, -half, half]]) elif lattice_symbol == 'B': lattrans = FracVector.create([[half, 0, half], [0, 1, 0], [-half, 0, half]]) elif lattice_symbol == 'C': lattrans = FracVector.create([[half, half, 0], [-half, half, 0], [0, 0, 1]]) elif lattice_symbol == 'F': # or lattice_symbol == 'A' or lattice_symbol == 'B' or lattice_symbol == 'C': lattrans = FracVector.create([[half, 0, half], [half, half, 0], [0, half, half]]) elif lattice_symbol == 'I': lattrans = FracVector.create([[half, half, half], [-half, half, half], [-half, -half, half]]) elif crystal_system == 'monoclinic': if lattice_symbol == 'A': lattrans = FracVector.create([[1, 0, 0], [0, half, -half], [0, half, half]]) if lattice_symbol == 'B': lattrans = FracVector.create([[half, 0, -half], [0, 1, 0], [half, 0, half]]) if lattice_symbol == 'C': lattrans = FracVector.create([[half, -half, 0], [half, half, 0], [0, 0, 1]]) elif crystal_system == 'triclinic': lattrans = unit else: raise Exception( "structureutils.get_primitive_basis_transform: unknown crystal system, " + str(crystal_system)) if lattrans is None: raise Exception( "structureutils.get_primitive_basis_transform: no match for lattice transform." ) return lattrans
def build_supercell_old(structure, transformation, max_search_cells=1000): ### New basis matrix, note: works in units of old_cell.scale to avoid floating point errors #print("BUILD SUPERCELL",structure.uc_sites.cell.basis.to_floats(), repetitions) transformation = FracVector.use(transformation).simplify() if transformation.denom != 1: raise Exception( "Structure.build_supercell requires integer transformation matrix") old_cell = structure.uc_sites.cell.get_normalized_longestvec() new_cell = Cell.create(basis=transformation * old_cell.basis) #conversion_matrix = (new_cell.inv*old_cell.basis).T().simplify() conversion_matrix = (old_cell.basis * new_cell.inv).T().simplify() volume_ratio = (new_cell.basis.det() / abs(old_cell.basis.det())).simplify() # Generate the reduced (old cell) coordinates of each corner in the new cell # This determines how far we must loop the old cell to cover all these corners nb = new_cell.basis corners = FracVector.create([(0, 0, 0), nb[0], nb[1], nb[2], nb[0] + nb[1], nb[0] + nb[2], nb[1] + nb[2], nb[0] + nb[1] + nb[2]]) reduced_corners = corners * (old_cell.basis.inv().T()) maxvec = [ int(reduced_corners[:, 0].max()) + 2, int(reduced_corners[:, 1].max()) + 2, int(reduced_corners[:, 2].max()) + 2 ] minvec = [ int(reduced_corners[:, 0].min()) - 2, int(reduced_corners[:, 1].min()) - 2, int(reduced_corners[:, 2].min()) - 2 ] if max_search_cells is not None and maxvec[0] * maxvec[1] * maxvec[ 2] > max_search_cells: raise Exception( "Very obtuse angles in cell, to search over all possible lattice vectors will take a very long time. To force, set max_search_cells = None when calling find_prototypeid()" ) ### Collect coordinate list of all sites inside the new cell coordgroups = structure.uc_reduced_coordgroups extendedcoordgroups = [[] for x in range(len(coordgroups))] for idx in range(len(coordgroups)): coordgroup = coordgroups[idx] for i in range(minvec[0], maxvec[0]): for j in range(minvec[1], maxvec[1]): for k in range(minvec[2], maxvec[2]): newcoordgroup = coordgroup + FracVector( ((i, j, k), ) * len(coordgroup)) new_reduced = newcoordgroup * conversion_matrix new_reduced = [ x for x in new_reduced if x[0] >= 0 and x[1] >= 0 and x[2] >= 0 and x[0] < 1 and x[1] < 1 and x[2] < 1 ] extendedcoordgroups[idx] += new_reduced # Safety check for avoiding bugs that change the ratio of atoms new_counts = [len(x) for x in extendedcoordgroups] for i in range(len(structure.uc_counts)): if volume_ratio * structure.uc_counts[i] != new_counts[i]: print("Volume ratio:", float(volume_ratio), volume_ratio) print("Extended coord groups:", FracVector.create(extendedcoordgroups).to_floats()) print("Old counts:", structure.uc_counts, structure.assignments.symbols) print("New counts:", new_counts, structure.assignments.symbols) #raise Exception("Structure.build_supercell safety check failure. Volume changed by factor "+str(float(volume_ratio))+", but atoms in group "+str(i)+" changed by "+str(float(new_counts[i])/float(structure.uc_counts[i]))) return structure.create(uc_reduced_coordgroups=extendedcoordgroups, basis=new_cell.basis, assignments=structure.assignments, cell=structure.uc_cell)
def metric_to_niggli(cell): m = cell.noms return FracVector( ((m[0][0], m[1][1], m[2][2]), (2 * m[1][2], 2 * m[0][2], 2 * m[0][1])), cell.denom).simplify()
def niggli_to_metric(niggli): m = niggli.noms # Since the niggli matrix contains 2*the product of the off diagonal elements, we increase the denominator by cell.denom*2 return FracVector( ((2 * m[0][0], m[1][2], m[1][1]), (m[1][2], 2 * m[0][1], m[1][0]), (m[1][1], m[1][0], 2 * m[0][2])), niggli.denom * 2).simplify()
def orthogonal_supercell_transformation(structure, tolerance=None, ortho=[True, True, True]): # TODO: How to solve for exact orthogonal cell? if tolerance is None: prim_cell = structure.uc_cell.basis print("Starting cell:", prim_cell) inv = prim_cell.inv().simplify() if ortho[0]: row0 = (inv[0] / max(inv[0])).simplify() else: row0 = [1, 0, 0] if ortho[1]: row1 = (inv[1] / max(inv[1])).simplify() else: row1 = [0, 1, 0] if ortho[2]: row2 = (inv[2] / max(inv[2])).simplify() else: row2 = [0, 0, 1] transformation = FracVector.create( [row0 * row0.denom, row1 * row1.denom, row2 * row2.denom]) else: maxtol = max(int(FracVector.use(tolerance)), 2) bestval = None besttrans = None for tol in range(1, maxtol): prim_cell = structure.uc_cell.basis inv = prim_cell.inv().set_denominator(tol).simplify() if inv[0] == [0, 0, 0] or inv[1] == [0, 0, 0 ] or inv[2] == [0, 0, 0]: continue absinv = abs(inv) if ortho[0]: row0 = (inv[0] / max(absinv[0])).simplify() else: row0 = [1, 0, 0] if ortho[1]: row1 = (inv[1] / max(absinv[1])).simplify() else: row1 = [0, 1, 0] if ortho[2]: row2 = (inv[2] / max(absinv[2])).simplify() else: row2 = [0, 0, 1] transformation = FracVector.create( [row0 * row0.denom, row1 * row1.denom, row2 * row2.denom]) try: cell = Cell.create(basis=transformation * prim_cell) except Exception: continue maxval = (abs(cell.niggli_matrix[1][0]) + abs(cell.niggli_matrix[1][1]) + abs(cell.niggli_matrix[1][2])).simplify() if maxval == 0: besttrans = transformation break if bestval is None or maxval < bestval: bestval = maxval besttrans = transformation transformation = besttrans if transformation == None: raise Exception( "Not possible to find a othogonal supercell with this limitation of number of repeated cell (increase tolerance.)" ) return transformation
def create(cls, cellshape=None, basis=None, metric=None, niggli_matrix=None, a=None, b=None, c=None, alpha=None, beta=None, gamma=None, lengths=None, angles=None, scale=None, scaling=None, volume=None, periodicity=None, nonperiodic_vecs=None, orientation=1): """ Create a new cell object, cell: any one of the following: - a 3x3 array with (in rows) the three basis vectors of the cell (a non-periodic system should conventionally use an identity matrix) - a dict with a single key 'niggli_matrix' with a 3x2 array with the Niggli Matrix representation of the cell - a dict with 6 keys, 'a', 'b', 'c', 'alpha', 'beta', 'gamma' giving the cell parameters as floats scaling: free form input parsed for a scale. positive value = multiply basis vectors by this value negative value = rescale basis vectors so that cell volume becomes abs(value). scale: set to non-None to multiply all cell vectors with this factor volume: set to non-None if the basis vectors only give directions, and the volume of the cell should be this value (overrides scale) periodicity: free form input parsed for periodicity sequence: True/False for each basis vector being periodic integer: number of non-periodic basis vectors """ if isinstance(cellshape, CellShape): basis = cellshape.basis elif cellshape is not None: basis = cell_to_basis(cellshape) if basis is not None: basis = FracVector.use(basis) if niggli_matrix is not None: niggli_matrix = FracVector.use(niggli_matrix) basis = FracVector.use( niggli_to_basis(niggli_matrix, orientation=orientation)) if niggli_matrix is None and basis is not None: niggli_matrix, orientation = basis_to_niggli(basis) if niggli_matrix is None and lengths is not None and angles is not None: niggli_matrix = lengths_angles_to_niggli(lengths, angles) niggli_matrix = FracVector.use(niggli_matrix) if basis is None: basis = FracVector.use( niggli_to_basis(niggli_matrix, orientation=1)) if niggli_matrix is None and not (a is None or b is None or c is None or alpha is None or beta is None or gamma is None): niggli_matrix = lengths_angles_to_niggli([a, b, c], [alpha, beta, gamma]) niggli_matrix = FracVector.use(niggli_matrix) if basis is None: basis = FracVector.use( niggli_to_basis(niggli_matrix, orientation=1)) if niggli_matrix is None: raise Exception( "CellShape.create: Not enough information to specify a cell given." ) if scaling is None and scale is not None: scaling = scale if scaling is not None and volume is not None: raise Exception( "CellShape.create: cannot specify both scaling and volume!") if volume is not None: scaling = vol_to_scale(basis, volume) if scaling is not None: scaling = FracVector.use(scaling) niggli_matrix = (basis * scaling * scaling).simplify() if basis is not None: basis = (basis * scaling).simplify() # For the basis we use a somewhat unusual normalization where the largest one element # in the cell = 1, this way we avoid floating point operations for prototypes created # from cell vector (prototypes created from lengths and angles is another matter) if basis is not None: c = basis maxele = max(c[0, 0], c[0, 1], c[0, 2], c[1, 0], c[1, 1], c[1, 2], c[2, 0], c[2, 1], c[2, 2]) maxeleneg = max(-c[0, 0], -c[0, 1], -c[0, 2], -c[1, 0], -c[1, 1], -c[1, 2], -c[2, 0], -c[2, 1], -c[2, 2]) if maxeleneg > maxele: scale = (-maxeleneg).simplify() else: scale = (maxele).simplify() basis = (basis * scale.inv()).simplify() c = niggli_matrix maxele = max(c[0, 0], c[0, 1], c[0, 2]) niggli_matrix = (niggli_matrix * maxele.inv()).simplify() return cls(niggli_matrix, orientation, basis)