def add_indicator_to_universe(u, ind_type="IND", ind_name="IND", frame=0, natoms=1): """ Add another atom and return the current universe Parameters ---------- u: MDAnalysis.Universe Universe to add indicator to natoms: int The number of atoms to append to the universe. Returns ------- all_u: MDAnalysis.Universe The new universe """ all_atoms = u.select_atoms("all") ind_sel = u.select_atoms("bynum %d" % 1) all_u = mda.Merge(all_atoms, ind_sel) for i in range(1, natoms): all_atoms = all_u.select_atoms("all") ind_sel = u.select_atoms("bynum %d" % 1) all_u = mda.Merge(all_atoms, ind_sel) all_u.dimensions = u.dimensions return all_u
def __init__(self, zdock_output_file, zdock_static_file_path='', zdock_mobile_file_path=''): self.zdock_output_file = zdock_output_file self.zdock_static_file_path = zdock_static_file_path self.zdock_mobile_file_path = zdock_mobile_file_path self.grid_size = None self.grid_spacing = None self.switch = None self.recep_init_rot = None self.lig_init_rot = None self.recep_init_trans = None self.lig_init_trans = None self.num_poses = None self.zdock_output_data = None self.temp_static_selection_str = '' self.temp_mobile_selection_str = '' self.parse_zdock_output(self.zdock_output_file) self.static_uni = self.load_pdb_structures( self.process_ZDOCK_marked_file(self.zdock_static_file_path)) self.mobile_uni = self.load_pdb_structures( self.process_ZDOCK_marked_file(self.zdock_mobile_file_path)) if self.switch: self.reverse_init_lig_rot_mat = euler_to_rot_mat( -self.lig_init_rot[::-1]) self.init_trans = self.lig_init_trans else: self.reverse_init_recep_rot_mat = euler_to_rot_mat( -self.recep_init_rot[::-1]) self.init_trans = self.recep_init_trans self.static_mobile_uni = MDAnalysis.Merge(self.static_uni.atoms, self.mobile_uni.atoms) self.static_mobile_copy_uni = MDAnalysis.Merge(self.static_uni.atoms, self.mobile_uni.atoms) self.static_mobile_copy_uni.trajectory.zdock_inst = self self.static_mobile_copy_uni.trajectory.n_frames = self.num_poses self.static_mobile_copy_uni.trajectory._read_next_timestep = types.MethodType( _read_next_timestep, self.static_mobile_copy_uni.trajectory) self.initial_mobile_coord = self.mobile_uni.atoms.positions self.initial_static_coord = self.static_uni.atoms.positions self.mobile_origin_coord = self.get_mobile_origin_coord( self.initial_mobile_coord) self.static_num_atoms = self.static_uni.atoms.n_atoms
def generate_topology_data(topology_data_list, list_restrained_residue_names, output_universe, ordered_residue_names, dictionary_residues_to_restrain, dictionary_residues_not_restrained): residue_names_accounted_for = [] for residue_name in ordered_residue_names: if residue_name in residue_names_accounted_for: continue else: residue_names_accounted_for.append(residue_name) if residue_name in dictionary_residues_to_restrain.keys(): new_restrained_residue_name = 'R' + residue_name[ 1:] #create a unique residue name for the restrained version of the residue (so that separate .itp may be used, etc.) if new_restrained_residue_name in list_restrained_residue_names: #in special cases like DOPC and POPC new_restrained_residue_name = 'Z' + new_restrained_residue_name[ 1:] list_restrained_residue_names.append(new_restrained_residue_name) list_restrained_residue_atomgroups = dictionary_residues_to_restrain[ residue_name] for ag in list_restrained_residue_atomgroups: ag.set_resnames(new_restrained_residue_name) if output_universe.select_atoms('all').n_atoms == 0: output_universe = MDAnalysis.Merge( *list_restrained_residue_atomgroups) else: output_universe = MDAnalysis.Merge( output_universe.atoms, *list_restrained_residue_atomgroups) output_universe = MDAnalysis.Merge( output_universe.atoms, *dictionary_residues_not_restrained[residue_name]) topology_data_list.append( (new_restrained_residue_name, len(list_restrained_residue_atomgroups))) topology_data_list.append( (residue_name, len(dictionary_residues_not_restrained[residue_name]))) else: #just merge in the unrestrained residues if there are no restrained targets for this residue type if output_universe.select_atoms('all').n_atoms == 0: output_universe = MDAnalysis.Merge( *dictionary_residues_not_restrained[residue_name]) else: output_universe = MDAnalysis.Merge( output_universe.atoms, *dictionary_residues_not_restrained[residue_name]) topology_data_list.append( (residue_name, len(dictionary_residues_not_restrained[residue_name]))) return topology_data_list, output_universe
def test_merge(self): u1, u2, u3 = self.universes ids_before = [a.index for u in [u1, u2, u3] for a in u.atoms] # Do the merge u0 = MDAnalysis.Merge(u1.atoms, u2.atoms, u3.atoms) # Check that the output Universe has the same number of atoms as the # starting AtomGroups assert_equal(len(u0.atoms), (len(u1.atoms) + len(u2.atoms) + len(u3.atoms))) # Make sure that all the atoms in the new universe are assigned to only # one, new Universe set0 = {a.universe for a in u0.atoms} assert_equal(len(set0), 1) u = list(set0)[0] assert_equal(u, u0) # Make sure that the atom ids of the original universes are unchanged, # ie we didn't make the original Universes 'dirty' ids_after = [a.index for u in [u1, u2, u3] for a in u.atoms] assert_equal(len(ids_after), (len(u1.atoms) + len(u2.atoms) + len(u3.atoms))) assert_equal(ids_before, ids_after) # Test that we have a same number of atoms in a different way ids_new = [a.index for a in u0.atoms] assert_equal(len(ids_new), len(ids_before)) u0.atoms.write(self.outfile) u = MDAnalysis.Universe(self.outfile) ids_new2 = [a.index for a in u.atoms] assert_equal(ids_new, ids_new2)
def test_merge_same_universe(self): u1, _, _ = self.universes u0 = MDAnalysis.Merge(u1.atoms, u1.atoms, u1.atoms) assert_equal(len(u0.atoms), 3*len(u1.atoms)) assert_equal(len(u0.residues), 3*len(u1.residues)) assert_equal(len(u0.segments), 3*len(u1.segments))
def RMSFcalculation(topology, trajectory, threshold): u = mda.Universe("%s" % trajectory, in_memory=True) # Initialization in MDAnalysis ref = mda.Universe("%s" % topology) # The backbone file has 3 atoms per residue prealigner = align.AlignTraj( u, ref, select="protein and name CA", in_memory=True).run( ) # Fit to the best frame to get a better average structure protein = u.select_atoms("protein") reference_coordinates = u.trajectory.timeseries(asel=protein).mean(axis=1) #print ("The atomic coordinates are\n%s" % reference_coordinates) reference = mda.Merge(protein).load_new(reference_coordinates[:, None, :], order="afc") aligner = align.AlignTraj(u, reference, select="protein and name CA", in_memory=True).run() calphas = protein.select_atoms("name CA") rmsfer = RMSF(calphas, verbose=True).run() # rmsf_data = numpy.zeros(rmsfer.rmsf.size) resnums = calphas.resnums rmsf_data = rmsfer.rmsf plot(resnums, rmsf_data, threshold) selection_residue = [] index = 1 for rmsf_pointer in rmsf_data: if rmsf_pointer >= threshold: selection_residue.append(index) index += 1 return selection_residue, rmsf_data
def concat(u1, u2): """Concatenate two MDAnalysis universes Parameters ---------- u1 : MDAnalysis universe First universe to be put together u2 : MDAnalysis universe Second universe to be put together Returns ------- u_comb : MDAnalysis universe Combined universes """ u_comb = MDAnalysis.Merge(u1, u2) p1 = u_comb.select_atoms("bynum 1:%s" % str(len(u1))) p2 = u_comb.select_atoms("bynum %s:%s" % (str(len(u1) + 1), str(len(u1) + len(u2)))) p1.segments.segids = "A" p2.segments.segids = "B" #p2.residues.set_resid(p2.residues.resids + p1.residues.resids[-1]) p2.residues.resids = (p2.residues.resids + p1.residues.resids[-1]) return u_comb
def merge_structures(self): """ This function takes the original protein structure and the newly created linker and merges them into one MDAnalysis universe. """ prot1 = mda.Universe(self.protein_pdb) ; pl = len(prot1.atoms.residues) prot2 = mda.Universe(self.protein_pdb2) link = mda.Universe(self.linker_pdb) ; ll = len(link.atoms.residues) # protein 1 sel1 = 'resid ' for i in range(pl): sel1+=str(i)+' ' # linker sel2 = 'resid ' for i in range(ll): link.atoms.residues[i].resid += (pl+1) sel2+=str(link.atoms.residues[i].resid)+' ' # protein 2 sel3 = 'resid ' for i in range(pl): prot2.atoms.residues[i].resid += (pl+ll) sel3+=str(prot2.atoms.residues[i].resid)+' ' u = mda.Merge(prot1.atoms,link.atoms,prot2.atoms) sel = [sel1, sel2, sel3] return [u, sel]
def __init__(self, top, traj, ncut=25): self.top = top self.traj = traj univ1 = mda.Universe(self.top, self.traj, verbose=True) protein = univ1.select_atoms("protein") coords_protein = AnalysisFromFunction(lambda ag: ag.positions.copy(), protein).run().results univ2 = mda.Merge(protein) # create the protein-only Universe univ2.load_new(coords_protein, format=MemoryReader) cut = [] for i in np.arange(0, len(coords_protein[:, 0, 0]), ncut): cut.append(coords_protein[i, :, :]) coord_cut = np.zeros((len(cut), 304, 3), dtype=np.float64) coord_cut[:, :, :] = [cut[i] for i in np.arange(0, len(cut))] univ_cut = mda.Universe("folded.pdb", coord_cut) self.univ_cut = univ_cut self.coords_protein = coords_protein self.coord_cut = coord_cut self.univ2 = univ2 self.ncut = ncut
def write(self, path, coordinates, name="generated", formats=("pdb", "xtc"), only_central=False, align_reference=None, align_select="all"): """ Writes a trajectory for the given coordinates. :param path: directory where to save the trajectory :param coordinates: numpy array of xyz coordinates (frames, atoms, xyz) :param name: filename (without extension) :param formats: specify which formats schould be used to write structure and trajectory. default: ("pdb", "xtc") :param only_central: if True only central atom coordinates are expected (N-Ca-C...) :param align_reference: Allows to allign the generated conformations according to some reference. The reference should be given as MDAnalysis atomgroup :param align_select: Allows to select which atoms should be used for the alignment. e.g. "resid 5:60" default is "all". Have a look at the MDAnalysis selection syntax for more details. :return: """ coordinates = np.array(coordinates) if coordinates.ndim == 2: coordinates = np.expand_dims(coordinates, 0) if only_central: output_universe = md.Merge(self.central_atoms) self.sorted_atoms[self.central_atom_indices].write( os.path.join(path, "{}.{}".format(name, formats[0]))) else: output_universe = md.Merge(self.sorted_atoms) self.sorted_atoms.write( os.path.join(path, "{}.{}".format(name, formats[0]))) output_universe.load_new(coordinates, format=MemoryReader) if align_reference is not None: align_traj = AlignTraj(output_universe, align_reference, align_select, in_memory=True) align_traj.run() with md.Writer(os.path.join(path, "{}.{}".format(name, formats[1]))) as w: for step in output_universe.trajectory: w.write(output_universe.atoms)
def affinity_propagation(self, preference=-6.0): '''Performing Affinity Propagation clustering of AMOEBA-run Trp-Cage folding trajectory:- Default parameter values from MDAnalysis - damping=0.9, max_iter=500, convergence_iter=50 Preference reduced to -10 from -1 to reflect local homogenity within the trajectory''' print("Performing Affinity Propagation with input preference = %f" % preference) clust = encore.cluster(self.univ_cut, method=encore.AffinityPropagation( preference=preference, verbose=True)) centroids = [cluster.centroid * self.ncut for cluster in clust] ids = [cluster.id for cluster in clust] print( "Clustering complete! - %d clusters formed with average size = %d frames" % (len(ids), np.average([cluster.size for cluster in clust]))) coords_centroids = np.zeros((len(centroids), 304, 3), dtype=np.float64) coords_centroids[:, :, :] = [ self.coords_protein[centroids[i], :, :] for i in np.arange(0, len(centroids)) ] protein = self.univ2.select_atoms("protein") univ_centroids = mda.Merge(protein) univ_centroids.load_new(coords_centroids, format=MemoryReader) ref = mda.Universe("folded.pdb") nframes = len(univ_centroids.trajectory) alignment = align.AlignTraj(univ_centroids, ref, select='protein and name CA', in_memory=True, verbose=True) alignment.run() idvscenter = { 'Cluster ID': [ids[i] for i in range(0, len(ids))], 'Centroid Time (ps)': [centroids[i] * 10 for i in range(0, len(centroids))], 'Cluster Size': [cluster.size for cluster in clust] } idtable = pd.DataFrame(data=idvscenter) #Visualisation representation set for Trp-Cage - will expand to general proteins later view = nglview.show_mdanalysis(univ_centroids) view.add_cartoon(selection="protein") view.add_licorice('TRP') view.add_licorice('PRO') view.center(selection='protein', duration=nframes) view.player.parameters = dict(frame=True) return view, idtable, univ_centroids
def test_merge_without_topology(self, u): # This shouldn't have topology as we merged single atoms u_merge = MDAnalysis.Merge(u.atoms[0:1], u.atoms[10:11]) assert (len(u_merge.atoms) == 2) assert (len(u_merge.atoms.bonds) == 0) assert (len(u_merge.atoms.angles) == 0) assert (len(u_merge.atoms.dihedrals) == 0) assert (len(u_merge.atoms.impropers) == 0)
def _conclude(self): # concatenate coordinate lists into arrays Up_arr = np.concatenate(self.upper_coords_list, axis=0) Um_arr = np.concatenate(self.lower_coords_list, axis=0) # compute histograms (perhaps for filtering out low occupancy grid points or other QC) self.Up_hist, _ = np.histogramdd(Up_arr[:, 0:2], [self.xedges, self.yedges]) self.Um_hist, _ = np.histogramdd(Um_arr[:, 0:2], [self.xedges, self.yedges]) # finalize surfaces if self.stype == 'interp': # if there are unprocessed coords, process those first if self.frame_count % self.interp_freq != 0: upp = np.concatenate(self.tmp_upper_coords_list, axis=0) low = np.concatenate(self.tmp_lower_coords_list, axis=0) # interpolate a surface for the frame and save it tUp_surf = scin.griddata((upp[:, 0], upp[:, 1]), upp[:, 2], (self.X, self.Y), method='cubic') tUm_surf = scin.griddata((low[:, 0], low[:, 1]), low[:, 2], (self.X, self.Y), method='cubic') # save a boolean array indicating defined surface values tUp_ct = ~np.isnan(tUp_surf) tUm_ct = ~np.isnan(tUm_surf) # turn nan into zero so that the surface averages cleanly tUp_surf[np.isnan(tUp_surf)] = 0.0 tUm_surf[np.isnan(tUm_surf)] = 0.0 # save surface and counts self.upper_surf_list.append((tUp_surf, tUp_ct)) self.lower_surf_list.append((tUm_surf, tUm_ct)) # average interpolated surfaces from each timestep Up_surf = np.sum([i[0] for i in self.upper_surf_list], axis=0) / np.sum( [i[1] for i in self.upper_surf_list], axis=0) Um_surf = np.sum([i[0] for i in self.lower_surf_list], axis=0) / np.sum( [i[1] for i in self.lower_surf_list], axis=0) # remove areas where there was never a count based on histogram # NOTE: this is problematic - it eliminates parts of the surface that I can clearly # see should have counts by watching the trajectory; for now leave it disabled # Up_surf[self.Up_hist==0] = np.nan # Um_surf[self.Um_hist==0] = np.nan elif self.stype == 'bin': # sort coordinates into bins and then cacluate the average value # NOTE: this is slow and the surfaces are a lot rougher than when using interpolation Up_surf = bin_surf(self.grid_dim, self.xedges, self.yedges, Up_arr) Um_surf = bin_surf(self.grid_dim, self.xedges, self.yedges, Um_arr) # save surfaces for access self.Up = Up_surf self.Um = Um_surf # this doesn't quite work as advertised in the MDA documentation (see Merge and MemoryReader for details) self.u.trajectory.rewind() self.u2 = mda.Merge(self.write_group) self.u2.transfer_to_memory() self.u2.load_new(np.stack(self.write_coords_list, axis=0))
def create_dummy_universe(self, reload = None): if reload: #reload specified pickle file of vectors with open(reload,'rb') as stream: self.m_vectors = pkl.load(stream) n_atoms = self.u_water.residues.n_residues # 1 m per moleculethe number of residues # may need to account for different numbers for general usage n_residues = n_atoms resindices = np.arange(0, n_atoms) segindices = [0]*n_residues atom_resindex = resindices n_segments = 1 # create a mda.Universe to merge with the input one and then the trajectory can be written self._M_universe = mda.Universe.empty(n_atoms, n_residues=n_residues, atom_resindex=resindices, residue_segindex=segindices, trajectory=True) # adding various required attributes to the system so that merge occurs properly # need dummy atom properties defined in init self._M_universe.add_TopologyAttr('resid', list(range(1, n_residues+1))) self._M_universe.add_TopologyAttr('type',[self.dummy_type]*n_residues) self._M_universe.add_TopologyAttr('name',[self.dummy_type]*n_residues) self._M_universe.add_TopologyAttr('segid', ['SYSTEM']) self._M_universe.add_TopologyAttr('charge', [self.dummy_charge]*n_residues) self._M_universe.add_TopologyAttr('masses', [self.dummy_mass]*n_residues) self._M_universe.dimensions=self.u_water.dimensions #extra depending on the type # set positions of the dummy atoms to the first frame self._M_universe.atoms.positions = self.m_vectors[0] # merged system u_water_to_merge = self.u_water.atoms #M_universe.atoms self.merged = mda.Merge(u_water_to_merge,self._M_universe.atoms) self.merged.add_TopologyAttr('name') #take dimensions from original box self.merged.dimensions = self.u_water.dimensions # set charges of oxygen in merged system to 0 # and set names to 'O self.merged.select_atoms(self._select_Os).charges=[0]*n_residues self.merged.select_atoms(self._select_Os).names=['O']*n_residues self.merged.select_atoms(self._select_hs).names=['H']*n_residues*2
def test_merge_without_topology(self): # This shouldn't have topology as we merged single atoms ag1 = AtomGroup([self.u.atoms[1]]) ag2 = AtomGroup([self.u.atoms[10]]) u2 = MDAnalysis.Merge(ag1, ag2) assert_(len(u2.atoms) == 2) assert_(len(u2.bonds) == 0) assert_(len(u2.angles) == 0) assert_(len(u2.dihedrals) == 0) assert_(len(u2.impropers) == 0)
def test_merge_with_topology_from_different_universes(self, u, u_ligand): u_merge = MDAnalysis.Merge(u.atoms[:110], u_ligand.atoms) # merge_protein doesn't contain bond topology, so merged universe # shouldn't have one either print(u_merge.atoms.bonds) # PDB reader yields empty Bonds group, which means bonds from # PSF/DCD survive the merge # assert(not hasattr(u_merge.atoms, 'bonds') or len(u_merge.atoms.bonds) == 0) assert(not hasattr(u_merge.atoms, 'angles') or len(u_merge.atoms.bonds) == 0) assert(not hasattr(u_merge.atoms, 'dihedrals') or len(u_merge.atoms.bonds) == 0) assert(not hasattr(u_merge.atoms, 'impropers') or len(u_merge.atoms.bonds) == 0)
def Merge(*args): """Combine multiple coarse-grain systems into one. Parameters ---------- args : iterable of either :class:`~MDAnalysis.Universe` or :class:`~MDAnalysis.AtomGroup` Returns ------- :class:`~MDAnalysis.Universe` A merged universe. """ from MDAnalysis.coordinates.memory import MemoryReader logger.warning("This might take a while depending upon the number of " "trajectory frames.") if not all([ u.universe.trajectory.n_frames == args[0].universe.trajectory.n_frames for u in args ]): logger.error("The trajectories are not the same length.") raise ValueError("The trajectories are not the same length.") ag = [_.atoms for _ in args] unit_cell = np.mean([_._unitcell for _ in args[0].trajectory], axis=0) universe = mda.Merge(*ag) if args[0].universe.trajectory.n_frames > 1: traj = (_.trajectory for _ in args) coordinates = [ np.concatenate([_.positions for _ in ts], axis=0) for ts in zip(*traj) ] coordinates = np.array(coordinates) if universe.atoms.n_atoms != coordinates.shape[1]: logger.error( "The number of sites does not match the number of coordinates." ) raise RuntimeError( "The number of sites does not match the number of coordinates." ) logger.info("The new universe has {1} beads in {0} frames.".format( *coordinates.shape)) universe.load_new(coordinates, format=MemoryReader) logger.warning( "The new trajectory will is assigned an average unit cell " "for the entire trajectory. This is currently a limitation " "implemented by MDAnalysis.") universe.trajectory.ts._unitcell = unit_cell return universe
def test_average_structure_ref_frame(self, universe): ref_frame = 3 u = mda.Merge(universe.atoms) # change to ref_frame universe.trajectory[ref_frame] u.load_new(universe.atoms.positions) # back to start universe.trajectory[0] ref, rmsd = _get_aligned_average_positions(self.ref_files, u) avg = align.AverageStructure(universe, ref_frame=ref_frame).run() assert_almost_equal(avg.universe.atoms.positions, ref, decimal=4) assert_almost_equal(avg.rmsd, rmsd)
def get_rmsf(t, label=None): sel = 'protein and not name H*' prot = t.select_atoms(sel) average_coordinates = t.trajectory.timeseries(asel=prot).mean(axis=1) # make a reference structure (need to reshape into a 1-frame "trajectory") reference = MDAnalysis.Merge(prot).load_new(average_coordinates[:, None, :], order="afc") aligner = align.AlignTraj(t, reference, select=sel, in_memory=True).run() print('\tDone Aligning... calculating RMSF') rmsfer = RMSF(prot).run() ret = pd.DataFrame(zip(prot.resids, prot.resnames, rmsfer.rmsf), columns=('resid', 'resname', 'rmsf')) if label != None: ret['label'] = label return ret
def test_merge_with_topology(self, u): ag1 = u.atoms[:20] ag2 = u.atoms[100:110] u_merge = MDAnalysis.Merge(ag1, ag2) assert (len(u_merge.atoms) == 30) assert (len(u_merge.atoms.bonds) == 28) assert (len(u_merge.atoms.angles) == 47) assert (len(u_merge.atoms.dihedrals) == 53) assert (len(u_merge.atoms.impropers) == 1) # All these bonds are in the merged Universe assert (len(ag1[0].bonds) == len(u_merge.atoms[0].bonds)) # One of these bonds isn't in the merged Universe assert (len(ag2[0].bonds) - 1 == len(u_merge.atoms[20].bonds))
def test_merge(self, u_protein, u_ligand, u_water, tmpdir): ids_before = [ a.index for u in [u_protein, u_ligand, u_water] for a in u.atoms ] # Do the merge u0 = MDAnalysis.Merge(u_protein.atoms, u_ligand.atoms, u_water.atoms) # Check that the output Universe has the same number of atoms as the # starting AtomGroups assert_equal( len(u0.atoms), (len(u_protein.atoms) + len(u_ligand.atoms) + len(u_water.atoms))) # Check that the output Universe has the same number of residues and # segments as the starting AtomGroups assert_equal(len(u0.residues), (len(u_protein.residues) + len(u_ligand.residues) + len(u_water.residues))) assert_equal(len(u0.segments), (len(u_protein.segments) + len(u_ligand.segments) + len(u_water.segments))) # Make sure that all the atoms in the new universe are assigned to only # one, new Universe set0 = {a.universe for a in u0.atoms} assert_equal(len(set0), 1) u = list(set0)[0] assert_equal(u, u0) # Make sure that the atom ids of the original universes are unchanged, # ie we didn't make the original Universes 'dirty' ids_after = [ a.index for u in [u_protein, u_ligand, u_water] for a in u.atoms ] assert_equal( len(ids_after), (len(u_protein.atoms) + len(u_ligand.atoms) + len(u_water.atoms))) assert_equal(ids_before, ids_after) # Test that we have a same number of atoms in a different way ids_new = [a.index for a in u0.atoms] assert_equal(len(ids_new), len(ids_before)) outfile = str(tmpdir.join('test.pdb')) u0.atoms.write(outfile) u = MDAnalysis.Universe(outfile) ids_new2 = [a.index for a in u.atoms] assert_equal(ids_new, ids_new2)
def ready_new(self, x=0., y=0., z=0.): """Add a new molecule to x, y, z """ # merge old box with new surfactant # Delete intersecting solvent # Try to re-add intersecting solvent to random positions inside solvent slab # write new structure u_box = mda.Universe(self.gro) u_surf = mda.Universe(self.surf_pdb) print('z: {:f}'.format(z)) print('surf COM: {}'.format(u_surf.atoms.center_of_mass())) u_new = mda.Merge(u_surf.atoms, u_box.atoms) u_new.dimensions = u_box.dimensions print('u dimensions: {}'.format(u_new.dimensions)) new_molecule = u_new.select_atoms(self.surf_sel_str).residues[0] COM = new_molecule.center_of_mass() xyz = np.array((x, y, z)) new_molecule.positions += (xyz - COM) print('new_molecule z: {:f}'.format(new_molecule.center_of_mass()[2])) u_new.atoms.pack_into_box() COM = u_new.atoms.center_of_mass() Lx, Ly, Lz, _, _, _ = u_new.dimensions xyz = np.array((Lx / 2., Ly / 2., Lz / 2.)) u_new.atoms.positions += (xyz - COM) print('new_molecule z: {:f}'.format(new_molecule.center_of_mass()[2])) with mda.Writer('new.pdb') as W: W.write(u_new.atoms) self.count += 1 # pre-process simulation AppendToTopFromPDB(self.template_top, '%s.top' % self.deffnm, 'new.pdb') gmx.grompp('-f %s -c %s -p %s -o %s.tpr' % (self.mdp, 'new.pdb', self.top, self.deffnm)) # set self state self.mdrun_args = ['-deffnm', self.deffnm, '-plumed', 'plumed.dat'] self.state = 'start'
def main(): parser = argparse.ArgumentParser(description='Project trajectory along PC') parser.add_argument('-s', '--tpr', help='Path to tpr file') parser.add_argument('-f', '--xtc', help='Path to xtc file') parser.add_argument('-c', '--cov', help='Path to displacement cov file') parser.add_argument('-v', '--vecs', help='Path to principle vectors file') parser.add_argument('-p', '--proj', help='Path to projected pc file') parser.add_argument('-o', '--out_pdb', help='Path to output pdbs file') args = parser.parse_args() univ = md.Universe(args.tpr, args.xtc) protein = univ.select_atoms('protein') with h5py.File(args.vecs, 'r') as fptr: pcs = fptr['vecs'][:] with h5py.File(args.cov, 'r') as fptr: mean_pos = fptr['mean_pos'][:] with h5py.File(args.proj, 'r') as fptr: pc_proj = fptr['pca'][:] # Projected coordinate of first principal component pc1 = pcs[:, 0] trans1 = pc_proj[:, 0] coordinates = (np.outer(trans1, pc1) + mean_pos.ravel()).reshape( len(trans1), -1, 3) # Create new universe to visualise the movement over the first principal component proj1 = md.Merge(protein) proj1_new = proj1.load_new(coordinates, order="fac") # Save the trajectory as PDB format with md.Writer(args.out_pdb, protein.n_atoms) as writer: for _ in proj1_new.trajectory: writer.write(proj1_new)
def reference_small(reference): return mda.Merge(reference.select_atoms( "not name H* and not atom 4AKE 1 CA"))
def insert_molecule(molecule, system, memb_sel, dist, rand_pos, leaflet="upper", rand=True): ''' Inserts a molecule above or below a membrane :param molecule: mdanalysis inverse object for molecule to be added :param system: mdanalysis universe object :param memb_sel: mdanalysis style selection string for membrane :param dist: distance in nm to insert above membrane :param rand_pos: points in the xy plane to insert molecule :param leaflet: the leaflet to insert the molecule with respect to :param rand: If true molecule is inserted in the xy plane using 'rand_pos' otherwise the center of the simulation box is used :return: A new mdanalysis object containing the inserted molecule ''' membrane = system.select_atoms(memb_sel) num = molecule.atoms.n_atoms # center protein to membrane# cog1 = membrane.center_of_geometry(pbc=False) cog2 = molecule.atoms.center_of_geometry(pbc=False) move = cog1 - cog2 molecule.atoms.translate(move) # move to random xy position if rand: cog2 = molecule.atoms.center_of_geometry(pbc=False)[:2] move = rand_pos - cog2 molecule.atoms.translate(np.append(move, 0.)) new_system = mda.Merge(molecule.atoms, system.atoms) new_system.dimensions = system.dimensions molecule = new_system.atoms[:num] membrane = new_system.select_atoms(memb_sel) if leaflet == "upper": #insert molecule above membrane min_ind = np.argmin(molecule.positions[:, 2]) min_atom = molecule.atoms[min_ind] min_z = min_atom.position[2] membrane = system.select_atoms("{0}".format(memb_sel)) max_z = np.max(membrane.positions[:, 2]) diffz = min_z - max_z movez = dist * 10. - diffz else: #insert molecule below membrane molecule.atoms.rotateby(180., [1, 0, 0]) max_ind = np.argmax(molecule.positions[:, 2]) max_atom = molecule.atoms[max_ind] max_z = max_atom.position[2] membrane = system.select_atoms("{0}".format(memb_sel)) min_z = np.min(membrane.positions[:, 2]) diffz = max_z - min_z movez = -dist * 10. - diffz molecule.translate([0, 0, movez]) #set size of new box in the z dimension protein_maxz = np.max(molecule.positions[:, 2]) if protein_maxz > new_system.dimensions[2]: new_system.dimensions[2] = protein_maxz + 10. return new_system
def iterative_align_average_2_site(coord, selGroup1, selGroup2, frameStart=0, frameStop=-1, deltaFrame=1, maxSteps=25, thresh=1.0E-10): selGroup3 = md.Merge(selGroup1.atoms, selGroup2.atoms) if frameStop < 0: frameStop = coord.trajectory.n_frames + frameStop + 1 nFrames = int((frameStop - frameStart) // deltaFrame) # create numpy array of aligned positions alignedPos = np.empty( (nFrames, (selGroup1.n_residues + selGroup2.n_residues), 3), dtype=np.float64) #generate an initial average by aligning to first frame avg = np.zeros(((selGroup1.n_residues + selGroup2.n_residues), 3), dtype=np.float64) comPos = np.empty(((selGroup1.n_residues + selGroup2.n_residues), 3), dtype=np.float64) frameCount = 0 for ts in coord.trajectory[frameStart:frameStop:deltaFrame]: selGroup1.translate(-selGroup3.atoms.center_of_mass()) selGroup2.translate(-selGroup3.atoms.center_of_mass()) count = 0 for i, resid in enumerate(np.unique(selGroup1.resids)): residSel = "resid " + str(resid) comPos[count, :] = selGroup1.select_atoms( residSel).center_of_mass() count += 1 for j, resid2 in enumerate(np.unique(selGroup2.resids)): if resid2 == resid: residSel = "resid " + str(resid2) comPos[count, :] = selGroup2.select_atoms( residSel).center_of_mass() count += 1 if frameCount == 0: ref = np.copy(comPos) else: R = align.rotation_matrix(comPos, ref)[0] comPos = np.dot(comPos, R.T) avg += comPos alignedPos[frameCount, :, :] = comPos frameCount += 1 # finish average avg /= nFrames # perform iterative alignment and average to converge average newAvg = np.zeros(((selGroup1.n_residues + selGroup2.n_residues), 3), dtype=np.float64) avgRmsd = 2 * thresh step = 0 while step < maxSteps and avgRmsd > thresh: newAvg = 0.0 frameCount = 0 for ts in coord.trajectory[frameStart:frameStop:deltaFrame]: alignedPos[frameCount, :, :] -= np.mean( alignedPos[frameCount, :, :], axis=0) R = align.rotation_matrix(alignedPos[frameCount, :, :], avg)[0] alignedPos[frameCount, :, :] = np.dot(alignedPos[frameCount, :, :], R.T) newAvg += alignedPos[frameCount, :, :] frameCount += 1 # finish average newAvg /= nFrames avgRmsd = rmsd(avg, newAvg, center=False, superposition=False) avg = np.copy(newAvg) step += 1 print(step, avgRmsd) return avg, alignedPos
def load(): u = mda.Universe(GRO) prot = u.select_atoms('protein') u2 = mda.Merge(prot) u2.load_new([[prot.positions]], format=mda.coordinates.memory.MemoryReader)
def test_load_new_memory_reader_success(self): u = mda.Universe(GRO) prot = u.select_atoms('protein') u2 = mda.Merge(prot) assert u2.load_new([prot.positions], format=mda.coordinates.memory.MemoryReader) is u2
def test_merge_same_universe(self, u_protein): u0 = MDAnalysis.Merge(u_protein.atoms, u_protein.atoms, u_protein.atoms) assert_equal(len(u0.atoms), 3 * len(u_protein.atoms)) assert_equal(len(u0.residues), 3 * len(u_protein.residues)) assert_equal(len(u0.segments), 3 * len(u_protein.segments))
ind_end = (rank + 1) * local_n else: ind_end = N if rank == 0: inds = np.arange(N) else: inds = None local_inds = np.empty(local_n, dtype=np.int) comm.Scatter(inds, local_inds, root=0) #print(chains) for i in local_inds: filename = folder + 'chain_{}.xtc'.format(i + 1) print(filename) sys.stdout.flush() protein = chains[i] if not os.path.exists(filename): u2 = md.Merge(protein).load_new(AnalysisFromFunction( lambda ag: ag.positions.copy(), protein).run().results, format=MemoryReader) with md.Writer(filename, protein.n_atoms) as W: for ts in u2.trajectory: W.write(u2) if rank == 0: chains[0].write(folder + 'chain.gro') chains[0].write(folder + 'chain.pdb')