def __init__( self, width=320, height=240, x_arc=73.0, y_arc=73.0, focal_distance=2.2, depth=5000.0, ): self.w, self.h = width, height self.xarc, self.yarc = x_arc, y_arc self.FD = focal_distance self.depth = depth self.T = Vector() self.RM = rotx(0) * roty(0) * rotz(0) # Create a list of eight "blank" new Vectors. These will be the # corners of the frustum, used to determine the planes beyond # which a given point is outside the viewable space. self._frustum = [Vector() for _ in range(8)] self._reset() self._getFrustumPlanes()
def load(self, of): self.base_format = of curdir = self.base_format.param('System.CurrrentDirectory')[0] or "./" assert curdir == "./", "Cannot work with changed current dir" self.data_path = self.base_format.param( 'DATA.PATH')[0] or "../DFT_DATA13" self.system_name = self.base_format.param('System.Name')[0] self.stdout_level = int(self.base_format.param('level.of.stdout')[0]) self.fileout_level = int(self.base_format.param('level.of.fileout')[0]) spe_num = int(self.base_format.param('Species.Number')[0]) assert spe_num == len( self.base_format.multiparam( 'Definition.of.Atomic.Species')), "Incorrect species number!" self.species = {} for ls in self.base_format.multiparam('Definition.of.Atomic.Species'): s = openmx_species(ls, self.data_path) self.species[s.name] = s atom_num = int(self.base_format.param('Atoms.Number')[0]) assert atom_num == len( self.base_format.multiparam( 'Atoms.SpeciesAndCoordinates')), "Incorrect atom number!" atom_unit = self.get_unit( self.base_format.param('Atoms.SpeciesAndCoordinates.Unit')[0]) atoms = [] for ls in self.base_format.multiparam('Atoms.SpeciesAndCoordinates'): v = Vector( float(ls[2]) * atom_unit, float(ls[3]) * atom_unit, float(ls[4]) * atom_unit) name = self.species[ls[1]].name a = AtomVector(name, v) a.data()[AtomKeys.ORBITAL_COUNT] = self.species[a.name()].orbnum() a.data()[AtomKeys.ORBITAL_ARRAY] = self.species[ a.name()].orbarray() a.data()[AtomKeys.CUTOFF] = self.species[a.name()].real_r() if self.species[a.name()].basis: a.data()[AtomKeys.FULL_VALENCE] = self.species[ a.name()].basis.eval atoms.append(a) vectors = [] if self.base_format.multiparam('Atoms.UnitVectors'): cell_unit = self.get_unit( self.base_format.param('Atoms.UnitVectors.Unit')[0]) for ls in self.base_format.multiparam('Atoms.UnitVectors'): v = Vector( float(ls[0]) * cell_unit, float(ls[1]) * cell_unit, float(ls[2]) * cell_unit) vectors.append(v) assert len(vectors) == 3, "Wrong vector count!" self.cell = Cell(atoms, vectors)
def __parse_lines(lines): verts = [] norms = [] tris = [] for line in lines: attributes = line.split(" ") if attributes[0] == "#" or len(attributes) < 2: continue if attributes[0] == "v": verts.append( Vector(float(attributes[1]), float(attributes[2]), float(attributes[3]))) elif attributes[0] == "vn": norms.append( Vector(float(attributes[1]), float(attributes[2]), float(attributes[3]))) elif attributes[0] == "f": i = 3 while i < len(attributes): for j in xrange(3): values = attributes[i - 2 + j].split("/") value = Vector(-1, -1, -1) value[0] = int(values[0]) - 1 if len(values) == 3: if values[1] != "": value[1] = int(values[1]) - 1 if values[2] != "": value[2] = int(values[2]) - 1 tris.append(value) i += 1 if len(tris) == 0: return vertices = [] normals = [] triangles = [] index = 0 for triangle in tris: vertices.append(verts[int(triangle[0])]) normals.append(norms[int(triangle[2])]) triangles.append(index) index += 1 mesh = Mesh() mesh.vertices = tuple(vertices) mesh.normals = tuple(normals) mesh.triangles = tuple(triangles) return mesh
def __init__( self, scale=1.0, translation=None, rotation=None, ): self.things = [] self.subframes = [] if not isinstance(scale, scalar_types): #raise TypeError, scale raise TypeError self.s = scale # Translation. if isinstance(translation, Vector): self.T = translation elif translation is not None: translation = tuple(translation) if not (len(translation) == 3 and all(isinstance(t, scalar_types) for t in translation)): #raise TypeError, translation raise TypeError self.T = Vector(*translation) else: self.T = Vector() # Rotation. if isinstance(rotation, Matrix): self.RM = rotation elif rotation is not None: rotation = tuple(rotation) if not (len(rotation) == 3 and all(isinstance(a, scalar_types) for a in rotation)): #raise TypeError, rotation raise TypeError ax, ay, az = rotation self.RM = rotx(ax) * roty(ay) * rotz(az) else: self.RM = rotx(0) * roty(0) * rotz(0)
def __init__(self, atoms, vectors, cryst_mat, symops, assym_n): self.vectors = vectors self.cryst_mat = cryst_mat self.symops = symops self.assym_n = assym_n self.atoms = atoms self.coord_param_mat = None self.vector_param_mat = None self.cell = self.shift([0, 0, 0]) if self.vectors: self.bordered_cell = [a.real_atom() for a in self.shift([0, 0, 0])] start = Vector(0, 0, 0) for i in range(2): for j in range(2): for k in range(2): self.bordered_cell.append( AtomVector( 'x', start + self.vectors[0] * i + self.vectors[1] * j + self.vectors[2] * k, {})) if self.vectors: self.supercell = self.extended_cell(1) else: self.supercell = self.cell self.neighbours = NeighbourCache(self)
def get_magnetism(self, data): try: x, y, z = data[MAGNETOMETER]["values"] except KeyError: log("Warning: No magnetometer data") return None return Vector(x, y, z)
def cartesian_atom(self, atom, cryst_cell=False): vector_basis = np.array([v._data for v in self.vectors]) if (cryst_cell): crysmat = np.array(self.cryst_mat) vector_basis = np.transpose(crysmat).dot(vector_basis) unrel = np.transpose(vector_basis).dot(atom.position()._data) return AtomVector(atom.name(), Vector(unrel), {})
def apply_symop_to_vector(self, point, symop): vector_basis = np.array([v._data for v in self.vectors]) n, inv, rot_mat, translator = symop rel_data = np.linalg.inv(np.transpose(vector_basis)).dot(point._data) new_rel_data = np.array(rot_mat).dot(rel_data) new_data = np.transpose(vector_basis).dot(new_rel_data) return Vector(new_data)
def __init__(self): self.atoms = [] self.origin = Vector(0, 0, 0) self.vectors = [] self.size = [] self.data = None self.celltype = self.TYPE_CLUSTER
def from_file(name): logging.info(u'') logging.info(u'*********************************************') logging.info(u' Reading cube from %s' % name) logging.info(u'*********************************************') logging.info(u'') with open(name) as f: gc = GaussianCube() n = 0 i = 0 nat = 9999999999 lines = f.xreadlines() for line in lines: if n == 2: ls = line.split() nat = int(ls[0]) logging.debug(u' atoms count: %d' % nat) gc.origin = Vector([float(x) for x in ls[1:4]]) elif 3 <= n < 6: ls = line.split() nv = int(ls[0]) vv = Vector([float(x) for x in ls[1:]]) gc.vectors.append(vv) gc.size.append(nv) elif 6 <= n < 6 + nat: ls = line.split() num = int(ls[0]) name = ELEMENTS[num].symbol if num != 0 else 'Q' val = float(ls[1]) v = Vector([float(x) for x in ls[2:]]) a = AtomVector(name, v) a.data()[AtomKeys.FULL_VALENCE] = val gc.atoms.append(a) if n == 5 + nat: gc.data = np.empty([gc.size[x] for x in [0, 1, 2]]) elif 6 + nat <= n: ls = [float(k) for k in line.split()] for f in ls: x = i / gc.size[2] / gc.size[1] y = i / gc.size[2] % gc.size[1] z = i % gc.size[2] % gc.size[1] gc.data[x, y, z] = f i += 1 if i % (gc.data.size / 10) == 0: logging.debug(u' %d of %d' % (i, gc.data.size)) n += 1 return gc
def modify_by_coords(self, x, atoms): x, bx = list(self.cut_by_coords(x, atoms)) b2x = self.coord_basis_matrix(atoms) b2a = self.coord_basis_matrix(self.atoms) ax = b2a.dot(bx) for i, atom in enumerate(self.atoms): v = Vector(np.array(ax[i * 3:i * 3 + 3]) + atom.position()._data) atom.set_position(v)
def true_relative_atom(self, atom, cryst_cell=False): vector_basis = np.array([v._data for v in self.vectors]) if (cryst_cell): crysmat = np.array(self.cryst_mat) vector_basis = np.transpose(crysmat).dot(vector_basis) rel = np.linalg.inv(np.transpose(vector_basis)).dot( atom.position()._data) return AtomVector(atom.name(), Vector(rel), {})
def load_target_direction(self): if RESUME: try: with open(TARGET_DIRECTION_PATH, encoding="utf8") as f: direction = Vector(*map(float, f.read().split(","))) self.target_direction = direction return except FileNotFoundError: pass self.change_target_direction()
def apply_symop_to_point(self, point, symop, validate=False): vector_basis = np.array([v._data for v in self.vectors]) n, inv, rot_mat, translator = symop rel_data = np.linalg.inv(np.transpose(vector_basis)).dot(point._data) new_rel_data = np.array(rot_mat).dot(rel_data) new_rel_data += np.array(translator) if validate: new_rel_data = self.validate_rel(new_rel_data) new_data = np.transpose(vector_basis).dot(new_rel_data) return Vector(new_data)
def modify_by_vectors(self, x, atoms): x, bx = list(self.cut_by_vectors(x, atoms)) b2a = self.vector_basis_matrix( self.atoms) # maybe make cell_atoms relative?? ax = b2a.dot(bx) for i, atom in enumerate(self.atoms): v = Vector(np.array(ax[i * 3:i * 3 + 3]) + atom.position()._data) atom.set_position(v) for i in range(3): for j in range(3): self.vectors[j]._data[i] += bx[i * 3 + j]
def get_gravity(self, data): try: x, y, z = data[GRAVITY]["values"] except KeyError: log("Warning: No gravity data") return None result = Vector(x, y, z) if result.length == 0: log("Warning: Zero-length gravity vector") return None return result
def read_atoms(filename): with open(filename) as inp: atoms = [] lines = inp.read().splitlines() assert lines[0] == "$coord" assert lines[-1] == "$end" for line in lines[1:-1]: ls = line.strip().split() name = ls[3] if len(ls) == 4 else 'zz' vector = Vector( [float(i) * Units.BOHR / Units.UNIT for i in ls[0:3]]) atoms.append(AtomVector(name, vector)) return atoms
def __init__(self, canvas, x=0.0, y=0.0, z=0.0, **settings): self.vector = Vector(x, y, z) self.canvas = canvas # Width in pixels of canvas dot. self._width = settings.pop('width', None) or 3 self.settings = settings self.settings.setdefault('fill', 'green') # Canvas item id for our vector/dot. self.item = None
def read_xyz(name): nat = -1 with open(name, 'r') as f: lines = f.read().splitlines() n = 0 atoms = [] if re.match('^[0-9]+$', lines[0].strip()): nat = int(lines[0].strip()) n = 2 while n < len(lines): ls = lines[n].split() if len(ls) != 4 or nat == 0: break name = ls[0] if re.match('^[0-9]+$', name): num = int(name) name = ELEMENTS[num].symbol v = Vector([(float(x) * Units.ANGSTROM / Units.UNIT) for x in ls[1:]]) a = AtomVector(name, v) atoms.append(a) n += 1 nat -= 1 cell = Cell(atoms, [], None, None, None) return cell
def change_target_direction(self): angle = random.uniform(0, math.pi * 2) self.target_direction = Vector(math.cos(angle), math.sin(angle)) log("Target direction: {}".format(self.target_direction)) with open(TARGET_DIRECTION_PATH, "w", encoding="utf8") as f: print(",".join(map(str, self.target_direction)), file=f)
def __init__(self, cell, num, shifts): self.num = num self.cell = cell self.shifts = Vector(shifts) self.pos = None
def apply_symop(self, atom, symop): n, inv, rot_mat, translator = symop new_vec = np.array(rot_mat).dot(atom.position()._data) new_vec += np.array(translator) new_vec = self.validate_rel(new_vec) return AtomVector(atom.name(), Vector(new_vec), {})
def load(self, of): self.base_format = of bp = self.base_format.param('basis') assert bp.lineparam.strip() == 'file=basis' self.bases = TurboBasis.read_basis('basis') smap = self.species_map() cp = self.base_format.param('coord') assert cp.lineparam.strip() == 'file=coord' coordf = TurboTemplate.from_file('coord') cp = coordf.param('coord') atoms = [] for n, l in enumerate(cp.multiparam): ls = l.split() v = Vector(float(ls[0]), float(ls[1]), float(ls[2])) name = ls[3] a = AtomVector(name, v) atoms.append(a) a.data()[AtomKeys.ORBITAL_COUNT] = self.bases[smap[n + 1]].orbnum() a.data()[AtomKeys.ORBITAL_ARRAY] = self.bases[smap[n + 1]].orbarray() self.cell = Cell(atoms, []) twecp = self.base_format.param('twocomp-ecp') if twecp: ts = self.base_format.param('twocomp') ls = re.split("[\s\-]+", ts.multiparam[0].strip()) nocc = len(range(int(ls[1]), int(ls[2]) + 1)) rm = self.base_format.param('uhfmo_real') im = self.base_format.param('uhfmo_imag') assert rm.lineparam.strip() == 'file=realmos' assert im.lineparam.strip() == 'file=imagmos' rmat = MosReader.from_file('realmos').matrix imat = MosReader.from_file('imagmos').matrix basis_mat = [] N = len(rmat) / 2 for i in range(N * 2): tm = [] for j in range(N): e = rmat[i][j] + imat[i][j] * 1j tm.append(e) e = rmat[i][j + N] + imat[i][j + N] * 1j tm.append(e) basis_mat.append(tm) bm = numpy.matrix(basis_mat) # occ_m = self.dft_matrix(N * 2, nalpha, nbeta) occ_m = block_diag(numpy.identity(nocc), numpy.zeros((N * 2 - nocc, N * 2 - nocc))) self.dm = bm.getH().dot(occ_m).dot(bm) else: assert False #TODO nalpha = int( re.split( "[\s\-]+", self.base_format.param('alpha').multiparam[0].strip())[2]) nbeta = int( re.split( "[\s\-]+", self.base_format.param('beta').multiparam[0].strip())[2]) no = self.base_format.param('natural') assert no.lineparam.split()[-1] == 'file=natorb' mat = MosReader.from_file('natorb').matrix basis_mat = [] N = len(mat) for i in range(N * 2): tm = [] for j in range(N * 2): e = 0 if (i - j) % 2 == 0: e = mat[i / 2][j / 2] tm.append(e) basis_mat.append(tm) bm = numpy.matrix(basis_mat) occ_m = self.dft_matrix(N * 2, nalpha, nbeta) self.dm = bm.getH().dot(occ_m).dot(bm)
from qcldm.crystal_format.crystal_meta import CrystalMeta init_log(sys.argv) c = CrystalMeta() c.load('.') co = CrystalOut.from_file(c.out_file) write_xyz(co.cell.cell, 'cell.xyz') write_xyz(co.cell.supercell, 'supercell.xyz') cube = GaussianCube.from_file('crystal.cube') cube.celltype = GaussianCube.TYPE_PERIODIC_WITH_BORDER a1 = Vector([0.00000000, 1.29001007, -1.29858367]) a2 = Vector([0.00000000, -1.29001007, -3.89575101]) a1 = co.cell.validate_point(a1) a2 = co.cell.validate_point(a2) symop_to_use = None for symop in co.cell.symops: na1 = co.cell.apply_symop_to_point(a1, symop, True) if na1 == a2: symop_to_use = symop print symop break trans = transformed_copy(cube, co.cell, symop_to_use)
def validate_point(self, point): vector_basis = np.array([v._data for v in self.vectors]) rel_data = np.linalg.inv(np.transpose(vector_basis)).dot(point._data) rel_data = self.validate_rel(rel_data) new_data = np.transpose(vector_basis).dot(rel_data) return Vector(new_data)
import math import random import os import sys import time SCRIPT_DIR = os.path.dirname(__file__) CACHE_DIR = os.path.join(SCRIPT_DIR, "..", ".cache") TARGET_DIRECTION_PATH = os.path.join(CACHE_DIR, "directions.vec") DEBUG = bool(os.environ.get("DEBUG")) RESUME = not bool(os.environ.get("NORESUME")) TIME_SPEEDUP = 1 HOST = "0.0.0.0" REFERENCE_GRAVITY = Vector(0, 0, 1) _log_file = sys.stderr def set_log_file(file): global _log_file _log_file = file or sys.stderr def log(*args, **kwargs): kwargs.setdefault("flush", True) print(*args, **kwargs, file=_log_file) if DEBUG: print(*args, **kwargs, file=sys.stderr)
def get_cell_new(lines, vm, basis): start = CrystalOut.get_first_geom(lines) if ASSYM in lines[start + 2]: atoms = [] logging.debug(u'NON-PERIODIC SYSTEM') for n in xrange(start + 5, len(lines)): m = re.match(atom1_regex, lines[n]) if m: v = Vector([ (float(x) * Units.ANGSTROM / Units.UNIT) for x in [m.group( 2), m.group(3), m.group(4)] ]) name = CrystalOut.get_normal_name(m.group(1)) a = AtomVector(name, v) numorb = 0 for l in basis[a.name()].keys(): for cg in basis[a.name()][l]: numorb += cg.fs[0][1].l * 2 + 1 a.data()[AtomKeys.ORBITAL_COUNT] = numorb a.data()[AtomKeys.FULL_VALENCE] = vm[a.name()] atoms.append(a) return Cell(atoms, [], None, [], range(len(atoms))) elif LATTICE_DEG in lines[start + 2]: atoms = [] vectors = [] assym_n = [] trans_mat = [[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]] logging.debug(u'PERIODIC SYSTEM') m = re.match( '\s*ATOMS IN THE ASYMMETRIC UNIT\s+([0-9]+)\s+- ATOMS IN THE UNIT CELL:\s+([0-9]+)', lines[start + 7]) ass, tot = [int(x) for x in m.groups()] for n in range(tot): if ' T ' in lines[start + 10 + n]: assym_n.append(n) symstart = 0 if TRANS_MATRIX in lines[start + tot + 11]: logging.debug( u'PRIMITIVE CELL IS DIFFERENT FROM CRYSTALLOGRAPHIC') mat_raw = [float(i) for i in lines[start + tot + 12].split()] trans_mat = map(lambda x: mat_raw[3 * x:(x + 1) * 3], range(3)) symstart = start + 2 * tot + 25 else: logging.debug(u'PRIMITIVE CELL IS EQUAL TO CRYSTALLOGRAPHIC') symstart = start + tot + 13 m = re.match( '\s+\*+\s+([0-9]+)\s+SYMMOPS - TRANSLATORS IN FRACTIONAL UNITS', lines[symstart]) nops = int(m.group(1)) symops = [] for i in range(nops): ls = lines[symstart + 3 + i].split() n, inv = int(ls[0]), int(ls[1]) rot_raw = [float(i) for i in ls[2:11]] rot_mat = map(lambda x: rot_raw[3 * x:(x + 1) * 3], range(3)) translator = [float(i) for i in ls[11:14]] symop = [n, inv, rot_mat, translator] symops.append(symop) for n in range(symstart + nops + 6, symstart + nops + 9): ls = lines[n].split() assert len(ls) == 3 v = Vector([(float(x) * Units.ANGSTROM / Units.UNIT) for x in ls]) vectors.append(v) coordstart = symstart + nops + 15 for n in range(coordstart, coordstart + tot): m = re.match(atom_regex, lines[n]) if m: v = Vector([ (float(x) * Units.ANGSTROM / Units.UNIT) for x in [m.group( 2), m.group(3), m.group(4)] ]) name = CrystalOut.get_normal_name(m.group(1)) a = AtomVector(name, v) numorb = 0 for l in basis[a.name()].keys(): for cg in basis[a.name()][l]: numorb += cg.fs[0][1].l * 2 + 1 a.data()[AtomKeys.ORBITAL_COUNT] = numorb a.data()[AtomKeys.FULL_VALENCE] = vm[a.name()] atoms.append(a) return Cell(atoms, vectors, trans_mat, symops, assym_n)
def apply_delta(self, dx): for i, a in enumerate(self.atoms): v = Vector(np.array(dx[i * 3:i * 3 + 3]) + a.position()._data) a.set_position(v)
def read_basis(lines): numorbmap = {} basismap = {} basis = {} atoms = [] first_n = -1 last_n = -1 l = 0 l1 = -1 for n in xrange(len(lines)): if BASIS in lines[n]: break gs = [] gs1 = [] for line in lines[n + 4:]: m = re.match(basis_atom_regex, line) m1 = re.match(basis_orb_regex, line) m2 = re.match(basis_gauss_regex, line) if not line: if gs: cg = GaussFunctionContracted() cg.fs = gs if gs[0][1].l not in basis.keys(): basis[gs[0][1].l] = [] basis[gs[0][1].l].append(cg) if gs1: cg = GaussFunctionContracted() cg.fs = gs1 if gs1[0][1].l not in basis.keys(): basis[gs1[0][1].l] = [] basis[gs1[0][1].l].append(cg) gs = [] gs1 = [] if atoms: al = atoms[-1] if last_n != -1 and first_n != -1: numorb = last_n - first_n + 1 numorbmap[al.name()] = numorb if basis: basismap[al.name()] = basis basis = {} break elif m: if gs: cg = GaussFunctionContracted() cg.fs = gs if gs[0][1].l not in basis.keys(): basis[gs[0][1].l] = [] basis[gs[0][1].l].append(cg) if gs1: cg = GaussFunctionContracted() cg.fs = gs1 if gs1[0][1].l not in basis.keys(): basis[gs1[0][1].l] = [] basis[gs1[0][1].l].append(cg) gs = [] gs1 = [] if atoms: al = atoms[-1] if last_n != -1 and first_n != -1: numorb = last_n - first_n + 1 numorbmap[al.name()] = numorb if basis: basismap[al.name()] = basis basis = {} v = Vector([ (float(x) * Units.BOHR / Units.UNIT) for x in [m.group(3), m.group(4), m.group(5)] ]) name = CrystalOut.get_normal_name(m.group(2)) a = AtomVector(name, v) atoms.append(a) first_n = -1 last_n = -1 elif m1: if first_n == -1: if m1.group(1): first_n = int(m1.group(2)) else: first_n = int(m1.group(3)) last_n = int(m1.group(3)) lname = m1.group(4) if lname == 'SP': l = 0 l1 = 1 elif len(lname) == 1: l = Shells.SHELLS.index(lname) l1 = -1 else: assert False if gs: cg = GaussFunctionContracted() cg.fs = gs if gs[0][1].l not in basis.keys(): basis[gs[0][1].l] = [] basis[gs[0][1].l].append(cg) if gs1: cg = GaussFunctionContracted() cg.fs = gs1 if gs1[0][1].l not in basis.keys(): basis[gs1[0][1].l] = [] basis[gs1[0][1].l].append(cg) gs = [] gs1 = [] elif m2: ls = line.split() a = float(m2.group(1)) ln = min(l + 1, 3) k = float(m2.group(ln + 1)) g = GaussFunctionNormed(a, l) gs.append([k, g]) if l1 != -1: ln = min(l1 + 1, 3) k = float(m2.group(ln + 1)) g = GaussFunctionNormed(a, l1) gs1.append([k, g]) assert k # for k in basismap.keys(): # s = 0 # for cg in basismap[k]: # s += cg.fs[0][1].l * 2 + 1 # print k, s, numorbmap[k] return basismap
def __stand_perpendicular(self, plane): # TODO: rework this method without moving robot # point = self.ROBOT.getl() vector = Vector(plane[:3]) self.set_tool_orientation(orient_from_vector(vector))