def to_element(x): if isinstance(x, (list, tuple)): assert len(x) == 1 x = x[0] if '.' in x: # orbital-hybridizations in SYBL return x.split('.')[0] try: # check if we can convert the whole str to an Element, # if not, we only pass the first letter. from mdtraj.core.element import Element Element.getBySymbol(x) except KeyError: return to_element(x[0]) return x
def convert_Traj_RDF(): """Convert the trajectory and structure files into the rdf""" ## add parameters to function calls - maybe add other functions ## other potential functions: ## - check_file_overwrite() ## - check_g_r_dropoff() - integrate with plot function ## - manage_filetypes() - read in files (maybe for mdtraj flexibility) traj_filename = os.path.join(os.getcwd(), 'data/traj_unwrapped.dcd') struct_filename = os.path.join(os.getcwd(), 'data/start_aa.hoomdxml') search_mapping_filename = os.path.join(os.getcwd(), 'data/propane_search_mapping.xml') user_mapping_filename = os.path.join(os.getcwd(), 'data/propane_user_mapping.xml') t = md.load(traj_filename, top=struct_filename) print("Loaded struct & traj files") molecules = t.top.find_molecules() first_mol_indices = [atom.index for atom in list(molecules[0])] first_molecule = t.top.subset( first_mol_indices) # topology for first molecule for atom in first_molecule.atoms: #possible other function atom.element = Element.getBySymbol(atom.name) topology = first_molecule.to_openmm( traj=None) # openmm topology accepted by foyer # import pdb; pdb.set_trace() read_search_mapping(search_mapping_filename, user_mapping_filename, topology)
def create_system_mapping(element_names, n_beads_TOTAL, t): """Create a system mapping Parameters ---------- element_names : (???) (???) n_beads_TOTAL : int Number of beads in the system t : mdTraj.Trajectory Initial trajectory object generated from structure and trajectory files """ # SLOWEST PART OF CODE IS THIS FUNCTION # Initialize atoms with elements ## for loop to traverse element_names array for elements ## need to expand from just carbon to more/different elements ## maybe use elements from periodic package for atom in t.top.atoms: #possible other function atom.element = Element.getBySymbol(atom.name) # check element #need for the xml file to have element symbol as type # Map the beads accordingly cg_idx = 0 start_idx = 0 propane_map = {0: [0, 1, 2]} ## mapping definition needs to be created # from search and user files ## TEST CODE ###################################################################### ###################################################################### ## TEST CODE system_mapping = {} for n in range(n_beads_TOTAL ): # what does sections mean in this particular context for bead, atoms in propane_map.items(): system_mapping[cg_idx] = [x + start_idx for x in atoms] start_idx += len(atoms) # understand this part cg_idx += 1 # Apply mapping for XYZ coordinates cg_xyz = np.empty((t.n_frames, len(system_mapping), 3)) for cg_bead, aa_indices in system_mapping.items(): cg_xyz[:, cg_bead, :] = md.compute_center_of_mass( t.atom_slice(aa_indices)) # Apply mapping for Topology object cg_top = md.Topology() for cg_bead in system_mapping.keys(): #i got the keys keys keys cg_top.add_atom('carbon', element.virtual_site, cg_top.add_residue('A', cg_top.add_chain())) ## Check element and name for items 'A' ## Possible interface with mbuild for better UI and aesthetics return cg_xyz, cg_top
def get_form_factor(element_name=None, water=None): if water: return get_form_factor_water(element_name=element_name) if element_name is not None: elem = Element.getBySymbol(element_name) warnings.warn('Estimating atomic form factor as atomic number') form_factor = elem.atomic_number return form_factor
def get_form_factor(element_name=None, water=None): if water: return get_form_factor_water(element_name=element_name) if element_name is not None: elem = Element.getBySymbol(element_name) warnings.warn('Estimating atomic form factor as atomic number') form_factor = elem.atomic_number return form_factor if form_factor > 0 else 1
def get_form_factor_water(element_name=None): if element_name is not None: elem = Element.getBySymbol(element_name) else: raise ValueError('Need an element') if elem.atomic_number not in [1, 8]: raise ValueError('') if elem.atomic_number == 1: form_factor = float(1/3) elif elem.atomic_number == 8: form_factor = float(9 + 1/3) else: raise ValueError('Found an element not in water') form_factor = None return form_factor
def get_form_factor_water(element_name=None): if element_name is not None: elem = Element.getBySymbol(element_name) else: raise ValueError('Need an element') if elem.atomic_number not in [1, 8]: raise ValueError('') if elem.atomic_number == 1: form_factor = float(1 / 3) elif elem.atomic_number == 8: form_factor = float(9 + 1 / 3) else: raise ValueError('Found an element not in water') form_factor = None return form_factor
def get_form_factor(element_name=None, q=None, method="atomic", water=None): """Get form factor for elements""" if method == "cromer-mann" and q is None: raise ValueError( "q must be a non-null value when method='cromer-mann'") if water: return get_form_factor_water(element_name=element_name) if element_name is not None: elem = Element.getBySymbol(element_name) if method == "atomic": warnings.warn('Estimating atomic form factor as atomic number') form_factor = elem.atomic_number elif method == "cromer-mann": form_factor = cromermann.fxrayatq(elem.symbol, q) else: raise ValueError( f"Invalid method {method}. Use `atomic` or `cromer-mann`.") return form_factor if form_factor > 0 else 1
def _traj_from_xyza(xyz, atomic_numbers, units='nm'): """ Parameters ---------- xyz : np.array, float, shape( num_atom, 3) array of x,y,z,a atomic_numbers : np.array, int, shape( num_atom, 1 ) the atomic numbers of each of the atoms. Optional Parameters ------------------- units : str if units == 'nm' then nothing happens. if units == 'ang' then we convert them to nm. Returns ------- structure : mdtraj.trajectory A meta-data minimal mdtraj instance """ if units == 'ang': xyz /= 10. top = Topology() chain = top.add_chain() residue = top.add_residue('XXX', chain) for i in range(xyz.shape[0]): element_symb = periodic_table[atomic_numbers[i]][1] # should give symbol element = Element.getBySymbol(element_symb) name = '%s' % element_symb top.add_atom(name, element, residue) structure = Trajectory(xyz=xyz, topology=top) return structure
def _read(self): "Read a single frame" from mdtraj.core.topology import Topology from mdtraj.core.element import Element, virtual # Read in the number of atoms. line = self._fh.readline() if line == '': raise _EOF() self._n_atoms = int(line.split()[0]) self._line_counter += 1 coords = np.empty((self._n_atoms, 3), dtype=np.float32) bond_partners = [[] for i in xrange(self._n_atoms)] atom_names = ['' for i in xrange(self._n_atoms)] line = self._fh.readline() s = line.split() self._line_counter += 1 # See if we have box info on this line or not cell_lengths = cell_angles = None if len(s) == 6: try: cell_lengths = np.asarray( [float(s[0]), float(s[1]), float(s[2])] ) cell_angles = np.asarray( [float(s[3]), float(s[4]), float(s[5])] ) line = self._fh.readline() self._line_counter += 1 except ValueError: pass i = 0 while i < self._n_atoms - 1: atom_names[i] = s[1] bond_partners[i] = [int(x) for x in s[6:]] coords[i,:] = [float(s[pos]) for pos in [2, 3, 4]] i += 1 line = self._fh.readline() s = line.split() self._line_counter += 1 # Now do the last atom atom_names[i] = s[1] bond_partners[i] = [int(x) for x in s[6:]] coords[i,:] = [float(s[pos]) for pos in [2, 3, 4]] # Now see if we have to build a topology if self.topology is None: self.topology = top = Topology() chain = top.add_chain() # only 1 chain res = top.add_residue('RES', chain, 1) # only 1 residue for at in atom_names: # First get the element. Try for common 2-letter elements, then # use the first letter only (default to None if I can't find it) if at[:2].upper() in ('NA', 'CL', 'MG'): elem = Element.getBySymbol(at[:2]) else: try: elem = Element.getBySymbol(at[0]) except KeyError: elem = virtual top.add_atom(at, elem, res) # Now add the bonds atoms = list(top.atoms) for i, bonds in enumerate(bond_partners): me = atoms[i] for b in bonds: b -= 1 if b < i: continue it = atoms[b] top.add_bond(me, it) self._frame_index += 1 return coords, cell_lengths, cell_angles
def _read(self): "Read a single frame" from mdtraj.core.topology import Topology from mdtraj.core.element import Element, virtual # Read in the number of atoms. line = self._fh.readline() if line == '': raise _EOF() self._n_atoms = int(line.split()[0]) self._line_counter += 1 coords = np.empty((self._n_atoms, 3), dtype=np.float32) bond_partners = [[] for i in xrange(self._n_atoms)] atom_names = ['' for i in xrange(self._n_atoms)] line = self._fh.readline() s = line.split() self._line_counter += 1 # See if we have box info on this line or not cell_lengths = cell_angles = None if len(s) == 6: try: cell_lengths = np.asarray( [float(s[0]), float(s[1]), float(s[2])]) cell_angles = np.asarray( [float(s[3]), float(s[4]), float(s[5])]) line = self._fh.readline() self._line_counter += 1 except ValueError: pass i = 0 while i < self._n_atoms - 1: atom_names[i] = s[1] bond_partners[i] = [int(x) for x in s[6:]] coords[i, :] = [float(s[pos]) for pos in [2, 3, 4]] i += 1 line = self._fh.readline() s = line.split() self._line_counter += 1 # Now do the last atom atom_names[i] = s[1] bond_partners[i] = [int(x) for x in s[6:]] coords[i, :] = [float(s[pos]) for pos in [2, 3, 4]] # Now see if we have to build a topology if self.topology is None: self.topology = top = Topology() chain = top.add_chain() # only 1 chain res = top.add_residue('RES', chain, 1) # only 1 residue for at in atom_names: # First get the element. Try for common 2-letter elements, then # use the first letter only (default to None if I can't find it) if at[:2].upper() in ('NA', 'CL', 'MG'): elem = Element.getBySymbol(at[:2]) else: try: elem = Element.getBySymbol(at[0]) except KeyError: elem = virtual top.add_atom(at, elem, res) # Now add the bonds atoms = list(top.atoms) for i, bonds in enumerate(bond_partners): me = atoms[i] for b in bonds: b -= 1 if b < i: continue it = atoms[b] top.add_bond(me, it) self._frame_index += 1 return coords, cell_lengths, cell_angles
molecule_types = molecule_types, mapping_function = 'center') cg_trj.save(output_dir + output_traj_native) cg_trj[0].save(output_dir + output_top_native) ############################### run null mass ############################ ### pull in trajectories trj = md.load(input_dir + input_traj,top=input_dir + input_top) #the types of each molecule in the trajectory. molecule_types = [lipid_types.index(r.name) for r in trj.top.residues] #preprocess trajectory content by adding new parts for a in trj.top.atoms: a.element = Element.getBySymbol('H') #actual map command cg_trj = cg.map_molecules( trj = trj, selection_list = [ name_lists ], bead_label_list = [ label_lists ], molecule_types = molecule_types, mapping_function = 'com') cg_trj.save(output_dir + output_traj_null_mass) cg_trj[0].save(output_dir + output_top_null_mass) ############################### check results ############################### # reloading results from disk. cg_traj_null_mass = cg_trj.load(output_dir + output_traj_null_mass,