def generate_voronoi(self): # make the 2D list of points points = [] for a in self.atoms: points.append([a.coords().x(), a.coords().y()]) numpad = self.generate_padding_atoms() for p in self.padding_atoms: points.append([p.x(), p.y()]) points = numpy.array(points) self.voronoi = Voronoi(points) # read in all of the ridges for r in self.voronoi.ridge_vertices: self.edges.append(Edge(r[0], r[1])) # now build the regions # the scipy voronoi object has an array point_region, which # maps the index of the input point to its associated Voronoi region v = [] for vert in self.voronoi.vertices: c = loos.GCoord(vert[0], vert[1], 0.0) v.append(c) for i in range(self.num_atoms()): index = self.voronoi.point_region[i] if index == -1: raise ValueError, "point %d (atomId = %d) from voronoi decomposition isn't associated with a voronoi region; you may need to increase the padding value" % i, self.atoms[ i].id() r = self.voronoi.regions[index] self.regions.append(Region(v, r, self.atoms[i])) self.atoms_to_regions[self.atoms[i].id()] = self.regions[i]
def readVals(self, velocities = False): """ Read the binary format. Determine endian-ness by verifying the number of atoms (the first thing read) matches the supplied AtomicGroup. """ if self.atomicGroup is None: raise ValueError, "Must supply an atomic group first" with open(self.filename, 'rb') as f: atoms_bytes = f.read(4) # check the number of atoms to figure out endian-ness num_atoms_big = struct.unpack('>i', atoms_bytes)[0] num_atoms_little = struct.unpack('<i', atoms_bytes)[0] num_atoms_model = len(self.atomicGroup) if num_atoms_big == num_atoms_model: self.endian_signal = ">" elif num_atoms_little == num_atoms_model: self.endian_signal = "<" else: raise ValueError, "Number of atoms doesn't match supplied model" for i in xrange(num_atoms_model): x,y,z = struct.unpack(self.endian_signal + 'ddd', f.read(24) ) c = loos.GCoord(x,y,z) if velocities: c *= self.PDBVELFACTOR self.atomicGroup[i].velocities(c) else: self.atomicGroup[i].coords(c)
def generate_padding_atoms(self): """ Build the list of atoms in the periodic images surrounding the central image. This is necessary because QHull doesn't know anything about periodicity, so we need to do fake it; otherwise, you'd have bizarre or infinite areas for atoms near the edge of the box """ if not self.isPeriodic(): raise VoronoiError("Periodic boundaries are required") box = self.atoms.periodicBox() half_box = 0.5 * box xbox = loos.GCoord(box.x(), 0.0, 0.0) ybox = loos.GCoord(0.0, box.y(), 0.0) for a in self.atoms: c = a.coords() # generate the square neighbors if (c.x() < -half_box.x() + self.pad): self.padding_atoms.append(c + xbox) if (c.x() > half_box.x() - self.pad): self.padding_atoms.append(c - xbox) if (c.y() < -half_box.y() + self.pad): self.padding_atoms.append(c + ybox) if (c.y() > half_box.y() - self.pad): self.padding_atoms.append(c - ybox) # generate the diagonal neighbors if ((c.x() < -half_box.x() + self.pad) and (c.y() < -half_box.y() + self.pad)): self.padding_atoms.append(c + xbox + ybox) if ((c.x() > half_box.x() - self.pad) and (c.y() > half_box.y() - self.pad)): self.padding_atoms.append(c - xbox - ybox) if ((c.x() < -half_box.x() + self.pad) and (c.y() > half_box.y() - self.pad)): self.padding_atoms.append(c + xbox - ybox) if ((c.x() > half_box.x() - self.pad) and (c.y() < -half_box.y() + self.pad)): self.padding_atoms.append(c - xbox + ybox) return len(self.padding_atoms)
def buildBox(self): """ Use the template structure to build the full structure by replicating it each dimension until it's bigger than the target box size, then deleting waters with centroid that fall outside the target box. The resulting AtomicGroup is self.full_system """ # figure out how many replicas we need in each direction num_x = int(self.box.x() / self.template_box.x()) + 1 num_y = int(self.box.y() / self.template_box.y()) + 1 num_z = int(self.box.z() / self.template_box.z()) + 1 # build up the new system by replicating the target box # and systematically translating it self.full_system = loos.AtomicGroup() for x in range(num_x): for y in range(num_y): for z in range(num_z): new = self.template.copy() trans = loos.GCoord() trans.x(self.template_box.x() * x) trans.y(self.template_box.y() * y) trans.z(self.template_box.z() * z) new.translate(trans) self.full_system.append(new) self.full_system.centerAtOrigin() # trim the waters outside the target box size residues = self.full_system.splitByResidue() print len(residues), len(self.full_system) half_box = 0.5 * self.box to_remove = loos.AtomicGroup() for res in residues: centroid = res.centroid() print centroid, half_box if ((abs(centroid.x()) > half_box.x()) or (abs(centroid.y()) > half_box.y()) or (abs(centroid.z()) > half_box.z())): to_remove.append(res) print "Need to remove: ", len(to_remove) print "before: ", self.full_system.boundingBox(), len(self.full_system) self.full_system.remove(to_remove) print "after: ", self.full_system.boundingBox(), len(self.full_system) self.full_system.periodicBox(self.box) # renumber atom ids and resids self.full_system.renumber() for i in range(len(self.full_system)): self.full_system[i].resid(i / 3 + 1)
def averageStructure(traj): """Returns the average structure for a trajectory. >>> avg = loos.pyloos.averageStructure(traj) """ avg = numpy.zeros((len(traj.frame()), 3)) for frame in traj: coords = frame.getCoords() avg += coords avg /= len(traj) structure = traj.frame().copy() for i in range(len(structure)): structure[i].coords(loos.GCoord(avg[i][0], avg[i][1], avg[i][2])) return (structure)
def svd(traj): """ Returns a tuple containing SVD results along with the average structure for a trajectory >>> (L,S,V,avg) = loos.pyloos.svd(traj) """ A = extractCoords(traj) avg = numpy.average(A, 1) avg = avg[:, numpy.newaxis] A -= avg (U, s, V) = numpy.linalg.svd(A) structure = traj.frame().copy() for i in range(len(structure)): structure[i].coords( loos.GCoord(avg[i * 3], avg[i * 3 + 1], avg[i * 3 + 2])) return (U, s, V, structure)
molecules = system.splitByMolecule() segments = [] for segment in config.segments: s = loos.selectAtoms(system, 'segname == "' + segment.segname + '"') if (len(s) == 0): sys.stderr.write( "Selection failed assembling system: segment %s doesn't exist\n" % (segment.segname)) sys.stderr.write("Exiting...\n") sys.exit(0) segments.append(s) x_axis = loos.GCoord(1, 0, 0) z_axis = loos.GCoord(0, 0, 1) for j in range(len(segments)): seg_ag = segments[j] seg_ag_arr = seg_ag.splitByMolecule() seg_conf = config.segments[j] i = 0 while i < seg_conf.numres: lipid = seg_conf.library.pick_structure() phos = loos.selectAtoms(lipid, 'name == "' + seg_conf.phos_atom + '"') if (len(phos) == 0): sys.stderr.write( "Selection failed: \"phos\" atom %s doesn't exist in lipid %s\n"
# create AtomicGroup containing all protein segments in case # we want to rotate it to_rot = loos.AtomicGroup() for s in config.protein.segments: current_seg = s[0].segid() # Don't need to trap failed selection here, because we # already know this segment exists seg = loos.selectAtoms(system, 'segname == "' + current_seg + '"') seg.copyMappedCoordinatesFrom(s) to_rot.append(seg) # if we asked for rotation, rotate all segments together # about a random axis if config.protrot: axis = loos.GCoord() axis.random() rot = random.uniform(0., 360.) to_rot.rotate(axis, rot) sys.stderr.write("Beginning water box construction\n") # now add water and salt water_template = loos.GCoord(1.0, 1.0, 1.0) water_template *= config.water.box_size water_target = loos.GCoord(config.box.x(), config.box.y(), config.box.z()) water = WaterBox.WaterBox(config.water.coords_filename, water_template, water_target, config.water.segname)
# test the closing line segment side = test_side(p, self.coords(self.vertices[-1]), self.coords(self.vertices[0])) match = (((side >= 0) and (prev_side >= 0)) or ((side <= 0) and (prev_side <= 0))) return match if __name__ == '__main__': ag = loos.createSystem("rhod_only.pdb") slicer = ZSliceSelector(-3.0, 3.0) ag = loos.selectAtoms(ag, 'name == "CA"') ag_slice = slicer(ag) hull = ConvexHull(ag_slice) hull.generate_hull() hull.generate_vertices() i = 0 for v in hull.vertices: c = hull.coords(v) print(i, v, c.x(), c.y(), c.z()) i += 1 print(hull.is_inside(loos.GCoord(0.0, 0.0, 0.0))) print(hull.is_inside(loos.GCoord(20.0, 0.0, 0.0))) print(hull.is_inside(loos.GCoord(0.0, 20.0, 0.0)))
system_filename = sys.argv[1] traj_filename = sys.argv[2] selections = sys.argv[3:] system = loos.createSystem(system_filename) traj = loos.pyloos.Trajectory(traj_filename, system) helices = [] for s in selections: helices.append(loos.selectAtoms(system, s)) print "#Frame\tAngle\tCosine" for frame in traj: vec = loos.GCoord(0., 0., 0.) for h in helices: pca = h.principalAxes() v = pca[0] if v.z() < 0: v *= -1. vec += v cosine = vec.z() / vec.length() cosine = max(-1.0, cosine) cosine = min(1.0, cosine) ang = math.acos(cosine) * 180. / math.pi print traj.index(), ang, cosine
outputenergies 50 timestep 2.0 langevin on langevinTemp 500 langevinDamping 2 langevinHydrogen off """ # @endcond if __name__ == '__main__': import loos box = loos.GCoord(377, 377, 1000) n = NAMD("generated.psf", "t.pdb", "end", "toppar/par_build.inp", box) print n.construct_header() print n.construct_box() box[0] = 60 n.update_box(box) print n.construct_box() box[0] = 377 n.update_box(box) print n.construct_mini() #print n.construct_mini(1000) n.write_inputfile("n.inp", 50)
print '# ', args.num_means," \t",distortion print "# -------------------------------" print "# Trajectory list:" for i in range(len(args.traj)): print '# %5d = "%s"' % (i, args.traj[i]) print '#\n# %8s %16s %8s %8s' % ('Index', 'Trajectory', 'Frame', 'Cluster') print '# %8s %16s %8s %8s' % ('--------', '----------------', '--------', '--------') for i in range(len(idx)): loc = allTrajs.frameLocation(i) print '%10d %16d %8d %8d' % (i, loc[1], loc[3], idx[i]) # Output centroids cen_list = centroids.tolist() subset = allTrajs.frame() for j in range(len(cen_list)): troid = cen_list[j] centroid_structure = subset.copy() for i in range(0, len(troid), 3): centroid_structure[i/3].coords(loos.GCoord(troid[i], troid[i+1], troid[i+2])) pdb = loos.PDB.fromAtomicGroup(centroid_structure) pdb.remarks().add(cmd_string) pdb.remarks().add(">>> Means = %s, Distortion = %f" % (args.num_means, distortion)) filename = "%s-centroid-%d.pdb" % (args.prefix, j) file = open(filename, 'w') file.write(str(pdb)) file.close()
residues[i][j].resid(i + 1) residues[i][j].segid(self.segname) def pdb(self): """ Return a string containing a PDB version of the full_system, convenient for writing out the coordinates in PDB format. """ p = loos.PDB.fromAtomicGroup(self.full_system) return str(p) # @endcond if __name__ == '__main__': import sys coordfile = 'water_small.crd' box_size = loos.GCoord(15.5516, 15.5516, 15.5516) big_box = loos.GCoord(74.1, 74.1, 95.0) w = WaterBox(coordfile, box_size, big_box, "BULK") f = open("big_water.pdb", "w") f.write(w.pdb()) f.close() print w.full_system.periodicBox() print w.full_system.boundingBox()
def __init__(self, filename): self.segments = [] self.water = None self.salt = [] self.protein = None self.topology = [] self.parameters = [] self.psfname = None self.directory = "./out/" self.box = None self.namd_binary = None self.psfgen_binary = None file = open(filename) for line in file.readlines(): # skip blanks and comments if line.startswith("#") or line.isspace() or len(line) == 0: continue if line.upper().startswith("TOPOLOGY"): (top, filename) = line.split() self.topology.append(os.path.abspath(filename)) elif line.upper().startswith("PARAMETERS"): (par, filename) = line.split() self.parameters.append(os.path.abspath(filename)) elif line.upper().startswith("PSFGEN"): (n, psfgen) = line.split() self.psfgen_binary = psfgen elif line.upper().startswith("PSF"): (p, psfname) = line.split() self.psfname = psfname elif line.upper().startswith("SEGMENT"): s = Segment(line) self.segments.append(s) elif line.upper().startswith("WATER"): self.water = WaterSeg(line) elif line.upper().startswith("SALT"): s = SaltSeg(line) self.salt.append(s) elif line.upper().startswith("PROTEIN"): self.protein = Protein(line) elif line.upper().startswith("BOX"): (b,x,y,z) = line.split() x = float(x) y = float(y) z = float(z) self.box = loos.GCoord(x,y,z) #elif line.upper().startswith("DIRECTORY"): # (d, directory) = line.split() # self.directory = directory elif line.upper().startswith("NAMD"): (n, namd) = line.split() self.namd_binary = namd else: sys.stderr.write("Unrecognized line type: %s" % line) if len(self.topology) == 0: sys.stderr.write("No topology file specified... exiting\n") sys.exit(1) if len(self.parameters) == 0: sys.stderr.write("No parameter file specified... exiting\n") sys.exit(1) if self.psfname is None: sys.stderr.write("No output psf file specified... exiting\n") sys.exit(1) # Warn but don't exit if there are no lipids if len(self.segments) == 0: sys.stderr.write("No segments specified... your system has no lipids\n")
""" import loos import sys filename = sys.argv[1] system = loos.createSystem(filename) system.centerAtOrigin() # loop over atoms and reverse the sign of the x coordinate for i in range(system.size()): # 2 different ways to assign to coordinates # SWIG won't let us do: coords.x() = new_x # so we can do this: #system[i].coords().x(-system[i].coords().x()) # or this: system[i].coords()[0] *= -1.0 system.centerAtOrigin() # convert to PDB and print out pdb = loos.PDB_fromAtomicGroup(system) # now rotate 180 degrees around the z axis z_axis = loos.GCoord(0, 0, 1) pdb.rotate(z_axis, 180) # print the pdb out print pdb
'--protein', help= "File containing coordinates of the protein to be surrounded by small molecules" ) parser.add_argument('--no_center', help="If set, do not center the protein at the origin", action="store_true") parser.add_argument('--zbox', help="Z dimension of system, if not cubic", type=float) parser.add_argument('--z_exclude', help="Don't let molecules be placed in +/- z_exclude", type=float) args = parser.parse_args() box = loos.GCoord(args.box_size, args.box_size, args.box_size) half_box = 0.5 * args.box_size half_z = half_box if args.zbox: box.z(args.zbox) half_z = 0.5 * args.zbox if args.z_exclude: args.z_exclude = abs(args.z_exclude) if args.protein: protein = loos.createSystem(args.protein) else: protein = loos.AtomicGroup()
minima[idx[i]] = dists[i] minima_indices[idx[i]] = i print('%10d %16d %8d %8d %8f' % (i, loc[1], loc[3], idx[i], dists[i])) print("\n# Closest structure to each centroid") print('# %8s %10s %8s' % ("Cluster", "Index", "Distance")) print('# %8s %10s %8s' % ("-------", "-----", "--------")) for i in range(args.num_means): print("# %8d %10d %8f" % (i, minima_indices[i], minima[i])) # Output centroids, unless we're doing tsne, in which case the # structures of the centroids aren't meaninful if not args.tsne: cen_list = centroids.tolist() subset = allTrajs.frame() for j in range(len(cen_list)): troid = cen_list[j] centroid_structure = subset.copy() for i in range(0, len(troid), 3): centroid_structure[i // 3].coords( loos.GCoord(troid[i], troid[i + 1], troid[i + 2])) pdb = loos.PDB.fromAtomicGroup(centroid_structure) pdb.remarks().add(cmd_string) pdb.remarks().add(">>> Means = %s, Distortion = %f" % (args.num_means, distortion)) filename = "%s-centroid-%d.pdb" % (args.prefix, j) file = open(filename, 'w') file.write(str(pdb)) file.close()
# make the directory to hold the library try: os.mkdir(library_dir) except FileExistsError: print("Library directory %s exists" % (library_dir)) pass # set up the virtual trajectory first = loos.pyloos.Trajectory(traj_files[0], system, stride=stride) vtraj = loos.pyloos.VirtualTrajectory(first) for t in traj_files[1:]: traj = loos.pyloos.Trajectory(t, system, stride=stride) vtraj.append(traj) x_axis = loos.GCoord(1.0, 0., 0.) index = 0 for frame in vtraj: for i in range(len(lipids)): # rotate the lower leafet "right side up" c = lipids[i].centroid() if c.z() < 0: lipids[i].rotate(x_axis, 180.) # put the centering atom at the origin center = centers[i].coords() lipids[i].translate(-center) # covert to a PDB and write it out pdb = loos.PDB.fromAtomicGroup(lipids[i])