Exemplo n.º 1
0
def _load_structures(inp, sys_params,):
	'''load protein/ligand structures needed for calculation'''
	parser = pdb.Big_PDBParser()
	print("now loading structures")

	# Read and/or create pickle files for the structures to save I/O time
	ligand_pkl_filename = os.path.join(inp['rootdir'], "ligand.pkl")
	receptor_pkl_filename = os.path.join(inp['rootdir'], "receptor.pkl")
	receptor_pkl_dry_filename = os.path.join(inp['rootdir'], "receptor_dry.pkl")
	receptor_pkl_dry_pqr_filename = os.path.join(inp['rootdir'], "receptor_dry_pqr.pkl")

	ligand=pickle_or_load(sys_params['lig_pqr_filename'], ligand_pkl_filename, struc_name="ligand", pqr=True)
	#receptor=pickle_or_load(sys_params['rec_pdb_filename'], receptor_pkl_filename, struc_name="receptor", pqr=False)
	receptor_dry=pickle_or_load(sys_params['rec_dry_pdb_filename'], receptor_pkl_dry_filename, struc_name="receptor_dry", pqr=False)
	receptor_dry_pqr=pickle_or_load(sys_params['rec_dry_pqr_filename'], receptor_pkl_dry_pqr_filename, struc_name="receptor_dry_pqr", pqr=True)

	struct={ # all parameters pertaining to structure
		'ligand':ligand,
		#'receptor':receptor,
		'receptor_dry':receptor_dry, # or create a function that will remove all waters, complicated by ions
		'receptor_dry_pqr':receptor_dry_pqr,
		'rec_com':pdb.center_of_mass(receptor_dry), # have to take into account the center of mass of the receptor itself
		'lig_com':pdb.center_of_mass(ligand), # have to take into account the center of mass of the ligand itself
	}

	return struct
Exemplo n.º 2
0
def structures_clash_MDanalysis(structure1, MDatoms):
    '''determines whether two structures have any clashing atoms
    the smallest structure should be the first argument to allow
    this function to run quickly as possible'''
    if verbose:
        print "using MDAnalysis to find clash between structures", structure1.struct_id, "and", structure2.struct_id
    struct1_com = pdb.center_of_mass(
        structure1)  # find center of mass of structure1
    struct1_rad = pdb.molecular_radius(structure1)  # find molecular radius
    clashing = False
    for atom2 in MDatoms:  # for every atom in structure2
        atom2_radius = radii[pdb.find_element(atom2.name)]
        if numpy.linalg.norm(
                numpy.array(struct1_com) -
                numpy.array(atom2.pos)) < struct1_rad + atom2_radius:
            # then we have to check this atom against every struct1 atom
            for atom1 in structure1.get_atoms(
            ):  # for every atom in structure1
                atom1_radius = radii[
                    atom1.element]  # radii[atom2.resname][atom2.name]
                atom_dist = atom2_radius + atom1_radius
                if numpy.linalg.norm(
                        numpy.array(atom1.coords) -
                        numpy.array(atom2.pos)) < atom_dist:
                    return True
    return clashing
Exemplo n.º 3
0
def orient_to_principal_axes(structure):
  ''' finds the principle axes of the structure, and aligns the structure
  to the those axes'''
  evals, p_axes = pdb.principal_axes(structure) # calc principal axes
  vec_minor = p_axes[0] / numpy.linalg.norm(p_axes[0]) # the minor axis
  vec_z = numpy.array([0,0,1]) # the axis to which we will align, in this case the z
  structure, m1 = orient_to_axis(structure, vec_minor, vec_z) # orient to z
  if structure.atoms[0].coords[2] > pdb.center_of_mass(structure)[2]: # if atom0 coordinate is positive
    structure = generate_orientation(structure, one_eighty_matrix(0))
  evals, p_axes = pdb.principal_axes(structure) # recalc principal axes
  vec_inter = p_axes[1] / numpy.linalg.norm(p_axes[1]) # the intermediate axis
  vec_y = numpy.array([0,1,0]) # the axis to which we will align, in this case the y
  structure, m2 = orient_to_axis(structure, vec_inter, vec_y) # orient to y
  if structure.atoms[0].coords[1] > pdb.center_of_mass(structure)[1]: # if atom0 coordinate is positive
    structure = generate_orientation(structure, one_eighty_matrix(2))
  evals, p_axes = pdb.principal_axes(structure) # recalc principal axes
  m = m2 * m1
  #print "evals:", evals
  return m #structure, m
Exemplo n.º 4
0
def orient_to_axis(structure, struct_vec, ref_vec):
  '''orients the structure so that struct_vec is aligned to ref_vec'''
  #global x
  com = pdb.center_of_mass(structure)
  structure.moveby(-com)
  matrix = get_orient_matrix(struct_vec, ref_vec)
  #print "matrix:", matrix
  #x = matrix * x
  structure = generate_orientation(structure, matrix) # rotate the structure
  structure.moveby(com)
  return structure, matrix
Exemplo n.º 5
0
def generate_orientation(structure,matrix):
  '''given a ligand pdb object, will rearrange the atoms in the ligand according
  to the given rotation matrix'''

  struct_center = numpy.array([pdb.center_of_mass(structure)]) # find the center of mass of a ligand
  #print struct_center
  for atom in structure.get_atoms():
    coord = get_rot_vec(atom.get_coords())
    new_coord = matrix * coord
    atom.set_coords(new_coord.T) # assign atom object to have given coordinates
  return structure
Exemplo n.º 6
0
def structures_clash(structure1, structure2, tolerance=0.0):
    '''determines whether two structures have any clashing atoms
    the smallest structure should be the first argument to allow
    this function to run quickly as possible
    Input:
     - structure1: a Structure() object, probably representing the receptor
     - structure2: a Structure() object, probably representing the ligand
     - tolerance: float, The distance, in Angstroms, to subtract from the addition of 
         the radii before a clash is rejected.
    Output:
     - clashing: a boolean representing whether the structures are clashing or 
         not.
  '''
    if verbose:
        print "searching for clashes between structures", structure1.struct_id, "and", structure2.struct_id
    struct1_com = pdb.center_of_mass(
        structure1)  # find center of mass of structure1
    struct1_rad = pdb.molecular_radius(structure1)  # find molecular radius
    clashing = False

    for atom2 in structure2.atoms:  # for every atom in structure2
        if atom2.radius == '0.0':
            atom2_radius = pdb.radii[
                atom2.
                element]  # if not included, then retrieve a standard radius for this atom
            if verbose:
                print "using dictionary on atom2. atom2.radius:", atom2.radius
        else:
            atom2_radius = float(atom2.radius)

        # the statement below saves some computation time by being a semi-divide and conquer method. Could be better but I'm sure it will work just fine
        if np.linalg.norm(np.array(struct1_com) -
                          np.array(atom2.coords)) < struct1_rad + atom2_radius:
            # then we have to check this atom against every struct1 atom
            for atom1 in structure1.get_atoms(
            ):  # for every atom in structure1
                if atom1.radius == '0.0':
                    atom1_radius = pdb.radii[
                        atom1.
                        element]  # if not included, then retrieve a standard radius for this atom
                    if verbose:
                        print "using dictionary on atom1. atom1.radius:", atom1.radius
                else:
                    atom1_radius = float(atom1.radius)
                atom_dist = atom2_radius + atom1_radius
                if np.linalg.norm(
                        np.array(atom1.coords) -
                        np.array(atom2.coords)) < atom_dist - tolerance:
                    return True
    return clashing
Exemplo n.º 7
0
def structures_clash(structure1, structure2, tolerance=0.0):
    '''determines whether two structures have any clashing atoms
    the smallest structure should be the first argument to allow
    this function to run quickly as possible'''
    if verbose:
        print "searching for clashes between structures", structure1.struct_id, "and", structure2.struct_id
    struct1_com = pdb.center_of_mass(
        structure1)  # find center of mass of structure1
    struct1_rad = pdb.molecular_radius(structure1)  # find molecular radius
    clashing = False

    for atom2 in structure2.atoms:  # for every atom in structure2
        #try:
        #atom2_radius = float(radii[atom2.resname][atom2.name])
        #except KeyError:
        # look in the pdb for the radius itself
        if atom2.radius == '0.0':
            atom2_radius = radii[
                atom2.
                element]  # if not included, then retrieve a standard radius for this atom
            print "using dictionary on atom2. atom2.radius:", atom2.radius
        else:
            atom2_radius = float(atom2.radius)

        # the statement below saves some computation time by being a semi-divide and conquer method. Could be better but I'm sure it will work just fine
        if numpy.linalg.norm(
                numpy.array(struct1_com) -
                numpy.array(atom2.coords)) < struct1_rad + atom2_radius:
            # then we have to check this atom against every struct1 atom
            for atom1 in structure1.get_atoms(
            ):  # for every atom in structure1
                if atom1.radius == '0.0':
                    atom1_radius = radii[
                        atom1.
                        element]  # if not included, then retrieve a standard radius for this atom
                    print "using dictionary on atom1. atom1.radius:", atom1.radius
                else:
                    atom1_radius = float(atom1.radius)
                #print atom1_radius
                atom_dist = atom2_radius + atom1_radius
                if numpy.linalg.norm(
                        numpy.array(atom1.coords) -
                        numpy.array(atom2.coords)) < atom_dist - tolerance:
                    #print numpy.linalg.norm(numpy.array(atom1.coords) - numpy.array(atom2.coords))
                    # then we have a clash
                    return True
    return clashing
Exemplo n.º 8
0
def main(settings):

    rec_struct = settings['rec_struct']
    lig_struct = settings['lig_struct']
    lig_center = pdb.center_of_mass(lig_struct)
    browndye_bin = settings['browndye_bin_dir']
    empty_pqrxml = os.path.abspath(settings['empty_pqrxml_path'])

    #b surface for FHPD preparation
    pqrs = [copy.deepcopy(rec_struct), copy.deepcopy(lig_struct)]
    pqrs[1].struct_id = 'bd_ligand'
    b_surface_path = settings['b_surface_path']
    if not os.path.exists(b_surface_path): os.mkdir(b_surface_path)
    b_surface_criteria = []
    b_surface_criteria.append({
        'centerx': settings['bd_centerx'],
        'centery': settings['bd_centery'],
        'centerz': settings['bd_centerz'],
        'ligx': lig_center[0],
        'ligy': lig_center[1],
        'ligz': lig_center[2],
        'radius': settings['b_surf_distance'],
        'index': settings['bd_index']
    })  # add every site to the criteria list
    print("bsurface_criteria:", b_surface_criteria)
    b_surface_pqrxmls = _write_browndye_input(
        pqrs,
        settings,
        b_surface_criteria,
        work_dir=b_surface_path,
        browndye_bin=browndye_bin,
        start_at_site='false',
    )  # write input for this part

    #generate BD milestone files
    pqrs = [copy.deepcopy(rec_struct), copy.deepcopy(lig_struct)]
    pqrs[1].struct_id = 'bd_ligand'
    bd_file_path = settings['bd_milestone_path']
    if not os.path.exists(bd_file_path): os.mkdir(bd_file_path)
    criteria = []
    criteria.append({
        'centerx': settings['bd_centerx'],
        'centery': settings['bd_centery'],
        'centerz': settings['bd_centerz'],
        'ligx': lig_center[0],
        'ligy': lig_center[1],
        'ligz': lig_center[2],
        'radius': settings['bd_lower_bound'],
        'index': settings['bd_lower_bound_index']
    })  # add every site to the criteria list

    # make BD preparation scripts extract_bd_frames.py and bd_fhpd.pyp
    #print "settings['starting_surfaces'][i]:", settings['starting_surfaces'][i]
    # Write the script to extract all frames from the successful b_surface bd trajectories

    extract_bd_frames_dict = {
        'TRAJDIR': "../b_surface",
        'WORKDIR': "./trajs",
        'PQRXML0': os.path.basename(b_surface_pqrxmls[0]),
        'PQRXML1': os.path.basename(b_surface_pqrxmls[1]),
        'EMPTY': empty_pqrxml,
        'SITENAME': 'milestone_%s' % (settings['bd_index']),
        'NUMBER_OF_TRAJS': settings['threads']
    }
    extract_bd_frames = Adv_template(extract_bd_frames_template,
                                     extract_bd_frames_dict)
    extract_file = open(os.path.join(bd_file_path, "extract_bd_frames.py"),
                        'w')
    extract_file.write(extract_bd_frames.get_output()
                       )  # write an xml file for the input to bd
    extract_file.close()
    # construct the FHPD distribution prep scripts
    make_fhpd_dict = {
        'INPUT_TEMPLATE_FILENAME': 'input.xml',
        'RECEPTOR_PQRXML': os.path.basename(b_surface_pqrxmls[0]),
        'RXNS': 'rxns.xml',
        'NTRAJ': settings['fhpd_numtraj'],
        'ARGS': "glob.glob(os.path.join('./trajs','lig*.pqr'))"
    }  # NOTE: should change NTRAJ to be consistent with the number of reaction events in the b_surface phase
    make_fhpd = Adv_template(make_fhpd_template, make_fhpd_dict)
    make_fhpd_file = open(os.path.join(bd_file_path, "make_fhpd.py"), 'w')
    make_fhpd_file.write(
        make_fhpd.get_output())  # write an xml file for the input to bd
    make_fhpd_file.close()
    # Consolidate all result files from the FHPD simulations into one large results.xml file
    fhpd_consolidate_dict = {
        'FHPD_DIR': "fhpd",
        'LIG_DIR_GLOB': "lig*/",
        'RESULTS_NAME': 'results.xml'
    }
    fhpd_consolidate = Adv_template(fhpd_consolidate_template,
                                    fhpd_consolidate_dict)
    fhpd_consolidate_file = open(
        os.path.join(bd_file_path, "fhpd_consolidate.py"), 'w')
    fhpd_consolidate_file.write(
        fhpd_consolidate.get_output())  # write an xml file for the input to bd
    fhpd_consolidate_file.close()

    #counter += 1

    bd_pqrxmls = _write_browndye_input(pqrs,
                                       settings,
                                       criteria,
                                       work_dir=bd_file_path,
                                       browndye_bin=browndye_bin,
                                       fhpd_mode=True)

    return
Exemplo n.º 9
0
def generate_configs(structure, locations, sites, quaternions, fullnames, traj=None,traj_matrices=None, traj_coms=None, monomer=None, random_quat=False):
  '''given a list of coordinates and a list of orientations (in the form of
    quaternions) all possible orientations at all possible locations will be
    generated'''
  if verbose: print "Generating structural configurations..."
  configs = []
  starttime = time.time()
  counter = 0
  struct_center = pdb.center_of_mass(structure)
  #for q in quaternions: # for every quaternion, generate a rotation matrix
  #  matrix = numpy.matrix(transformations.quaternion_matrix(q))
  #  matrices.append(matrix) # take the entire 4x4 matrix

  totalconfigs = len(locations) # # the total number of configs to be generated
  if verbose: print "Total number of configurations to test/generate:", totalconfigs
  #location_counter = 0
  for location in locations: # for every anchor
    q = quaternions[counter] # find the quaternion for this milestone
    if random_quat==True: # calculate a random quat
      matrix = numpy.matrix(transformations.quaternion_matrix(random_quaternion())) # generate a random quaternion inside this function
    else: # then generate a rotation matrix from the quat
      matrix = numpy.matrix(transformations.quaternion_matrix(q))
    #print "struct_center", struct_center, "location:", location
    #delta = location - struct_center
    #print "delta:",delta
    #for matrix in matrices: # for every rotation matrix

    #print "matrix:", matrix
    new_structure = deepcopy(structure)
    new_structure.moveby(-struct_center) # move the center of mass over 0,0,0
    new_structure = generate_orientation(new_structure, matrix) # rotate the structure
    #print pdb.center_of_mass(new_structure)
    new_structure.moveby(location) # move the center of mass over the specified location
    #quat_index =
    #location_index = counter
    new_structure.struct_id = fullnames[counter] #"%d_%s_%.1f_%.1f_%.1f_%d" % (counter, sites[counter], location[0],location[1],location[2], counter%len(matrices)) # give the structure a new id based on: counter, xyz-location, rotation number
    # before saving the structure, have to make sure its not clashing
    if traj: # FLAGGED FOR IMPROVEMENT
      #clashes = structures_clash_MDanalysis(new_structure, clash_structure)
      # look to see if any frame of the trajectory will allow this pose to exist
      good_frame = fit_random_snapshots(new_structure, traj, traj_range=range(5))

      if good_frame == None: # then waste no more time on this one
        print "No frame found to fit location:", location, counter
        continue
      else: # then a frame was found that will work for our purposes
        #print location, good_frame
        if verbose: print "Location", location, "fits into frame", good_frame

      new_structure.moveby(traj_coms[good_frame])
      new_structure.matrix_operation(traj_matrices[good_frame])

      #break
      if monomer == None:
        ligstring = ""
      else:
        ligstring = "%d_" % monomer
      new_structure.save('/tmp/ligand%s%0*i_frame%d.pdb' % (ligstring, int(log10(totalconfigs))+1, counter, good_frame), standard = False)
    else:
      #print "center of mass", pdb.center_of_mass(new_structure)
      #new_structure.save('/tmp/ligand%i.pdb' % counter , standard = False)
      configs.append(new_structure)
    counter += 1
    #location_counter += 1

  #print "counter: ", counter
  endtime = time.time()
  if verbose: print "Generate_configs complete. Total number %d. Elapsed time: %d" % (len(configs), endtime-starttime,)

  return configs
Exemplo n.º 10
0
def main(settings):
  '''
  main function for bd.py

  takes a list of pqr filenames, reaction coordinate pairs/distances
  '''

  if verbose: print '\n', '#'*40, "\n Now creating BD files using bd.py\n", '#'*40

  rec_struct = settings['rec_struct']
  #milestones = settings['milestones']
  milestone_pos_rot_list = settings['milestone_pos_rot_list'] # NOTE: may want to clean up code referring to this variable

  if settings['starting_conditions'] == 'configs':
    lig_configs = settings['lig_configs']
  elif settings['starting_conditions'] == 'spheres':
    # then generate the anchors from random positions/orientations in a sphere
    # NOTE: there is a random orientation function in positions_orient.py
    pass
  else:
    raise Exception, "option not allowed: %s" % settings['starting_conditions']

  bd_file_paths = settings['bd_file_paths']
  browndye_bin = settings['browndye_bin_dir']
  empty_pqrxml = os.path.abspath(settings['empty_pqrxml_path'])
  bd_configs = []

  # fill the b_surface folder
  lig_config = lig_configs[0] # get the first config of the ligand
  lig_center = pdb.center_of_mass(lig_config)
  pqrs = [copy.deepcopy(rec_struct), copy.deepcopy(lig_config)]
  #print "PQR1 ID", pqrs[1].struct_id
  pqrs[1].struct_id='bd_ligand'
  #print "PQR1 ID", pqrs[1].struct_id
  b_surface_path = settings['b_surface_path']
  if not os.path.exists(b_surface_path): os.mkdir(b_surface_path)
  b_surface_criteria = []

  for site in settings['b_surface_ending_surfaces']:
    b_surface_criteria.append({'centerx':site['x'], 'centery':site['y'], 'centerz':site['z'], 'ligx':lig_center[0], 'ligy':lig_center[1], 'ligz':lig_center[2], 'radius':site['radius'], 'index':site['index'], 'siteid':site['siteid']}) # add every site to the criteria list
  print "bsurface_criteria:", b_surface_criteria
  b_surface_pqrxmls = write_browndye_input(pqrs, settings, b_surface_criteria, work_dir=b_surface_path, browndye_bin=browndye_bin, start_at_site='false', fhpd_mode = False) # write input for this part

  for bd_file_path in bd_file_paths:
    if not bd_file_path:
      pass
      #bd_configs.append(None)
      #continue # then don't do BD for this portion
    #print "bd_file_path:", bd_file_path
    anchor_folder_name = bd_file_path.split('/')[-2] # reading the file tree to get the index of every existing folder
    #print "anchor_folder_name:", anchor_folder_name
    folder_index = anchor_folder_name.split('_')[1] # getting the index out of the folder name
    bd_configs.append(int(folder_index))

  counter = 0 # the index of the loop itself
  print "bd_file_paths:", bd_file_paths
  print "bd_configs:", bd_configs
  for i in bd_configs: #len(milestones) should equal len(lig_configs); the index of the milestone/lig_config
    #lig_config = lig_configs[i]

    bd_file_path = bd_file_paths[counter]
    print "bd_file_path:", bd_file_path

    pqrs = [copy.deepcopy(rec_struct), copy.deepcopy(lig_config)]
    pqrs[1].struct_id='bd_ligand'
    #lig_center = pdb.center_of_mass(lig_config)
    bd_needed = True

    m=0
    for m in range(len(milestone_pos_rot_list)): # m will represent the proper milestone index
      if milestone_pos_rot_list[m][0].index == i:
        break

    criteria = [] #[[(31.121, 37.153, 35.253), (38.742, 51.710, 68.137), 9.0],] # a list of all reaction criteria
    for site in settings['starting_surfaces']:
      #site_center = [site['x'], site['y'],site['z']]
      #radius = site['radius'] # NOTE: at this time, only spherical reaction criteria are allowed in BrownDye
      if milestone_pos_rot_list[m][0].siteid == site['siteid']: # then its the same site, we need to go one shell in
        proper_radius = site['inner_radius'] # the radius in the same site
        proper_index = site['inner_index']
      else: # this is a different site, choose the same radius as starting
        proper_radius = site['outer_radius']
        proper_index = site['outer_index']
      criteria.append({'centerx':site['x'], 'centery':site['y'], 'centerz':site['z'], 'ligx':lig_center[0], 'ligy':lig_center[1], 'ligz':lig_center[2], 'radius':proper_radius, 'index':proper_index, 'siteid':site['siteid']}) # add every site to the criteria list

    #print "pqrs:", pqrs, 'criteria:', criteria

    site_pqrxmls = write_browndye_input(pqrs, settings, criteria, work_dir=bd_file_path, browndye_bin=browndye_bin,fhpd_mode=True)
    # make BD preparation scripts extract_bd_frames.py and bd_fhpd.pyp
    #print "settings['starting_surfaces'][i]:", settings['starting_surfaces'][i]
    # Write the script to extract all frames from the successful b_surface bd trajectories

    extract_bd_frames_dict = {'TRAJDIR':"../../b_surface", 'WORKDIR':"./trajs", 'PQRXML0':os.path.basename(b_surface_pqrxmls[0]), 'PQRXML1':os.path.basename(b_surface_pqrxmls[1]), 'EMPTY':empty_pqrxml, 'SITENAME':'%s_%s' % (milestone_pos_rot_list[m][0].siteid,milestone_pos_rot_list[m][0].index), 'NUMBER_OF_TRAJS':settings['threads']}
    extract_bd_frames = Adv_template(extract_bd_frames_template,extract_bd_frames_dict)
    extract_file = open(os.path.join(bd_file_path,"extract_bd_frames.py"), 'w')
    extract_file.write(extract_bd_frames.get_output()) # write an xml file for the input to bd
    extract_file.close()
    # construct the FHPD distribution prep scripts
    make_fhpd_dict = {'INPUT_TEMPLATE_FILENAME':'input.xml', 'RECEPTOR_PQRXML':os.path.basename(b_surface_pqrxmls[0]), 'RXNS':'rxns.xml', 'NTRAJ':settings['fhpd_numtraj'], 'ARGS':"glob.glob(os.path.join('./trajs','lig*.pqr'))"} # NOTE: should change NTRAJ to be consistent with the number of reaction events in the b_surface phase
    make_fhpd = Adv_template(make_fhpd_template,make_fhpd_dict)
    make_fhpd_file = open(os.path.join(bd_file_path,"make_fhpd.py"), 'w')
    make_fhpd_file.write(make_fhpd.get_output()) # write an xml file for the input to bd
    make_fhpd_file.close()
    # Consolidate all result files from the FHPD simulations into one large results.xml file
    fhpd_consolidate_dict = {'FHPD_DIR':"fhpd", 'LIG_DIR_GLOB':"lig*/", 'RESULTS_NAME':'results.xml'}
    fhpd_consolidate = Adv_template(fhpd_consolidate_template,fhpd_consolidate_dict)
    fhpd_consolidate_file = open(os.path.join(bd_file_path,"fhpd_consolidate.py"), 'w')
    fhpd_consolidate_file.write(fhpd_consolidate.get_output()) # write an xml file for the input to bd
    fhpd_consolidate_file.close()

    counter += 1
Exemplo n.º 11
0
                              receptor_pkl_dry_filename,
                              struc_name="receptor_dry",
                              pqr=False)
receptor_dry_pqr = pickle_or_load(sys_params['rec_dry_pqr_filename'],
                                  receptor_pkl_dry_pqr_filename,
                                  struc_name="receptor_dry_pqr",
                                  pqr=True)

struct = {  # all parameters pertaining to structure
    'ligand': ligand,
    'receptor': receptor,
    'receptor_dry':
    receptor_dry,  # or create a function that will remove all waters, complicated by ions
    'receptor_dry_pqr': receptor_dry_pqr,
    'rec_com': pdb.center_of_mass(
        receptor_dry
    ),  # have to take into account the center of mass of the receptor itself
    'lig_com': pdb.center_of_mass(
        ligand
    ),  # have to take into account the center of mass of the ligand itself
}
print "rec_com:", struct['rec_com'], ", lig_com:", struct['lig_com']
print "ligand index", ligand.atoms[-1].index
######## Positions/Orientations ###################################################
pos_settings = {  # position/orientation settings
    'quaternion_method':
    inp['hedron'],  # Options: single, random, simplex, tesseract, ... more to come someday
    'quaternion_random_count': int(
        inp['quaternion_random_count']
    ),  # if quaternion_method is set to 'random', must include number of random rotations to generate per position
    'align_lig_to_pa': boolean(
Exemplo n.º 12
0
def build_bd(seekrcalc):
  '''
  build all structures and necessary files for BD calculations

  takes a list of pqr filenames, reaction coordinate pairs/distances
  '''

  if verbose: print '\n', '#'*40, "\n Now creating BD files using bd.py\n", '#'*40

  parser = pdb.Big_PDBParser()
  rec_struct = parser.get_structure('bd_receptor_dry_pqr', seekrcalc.browndye.rec_dry_pqr_filename, pqr=True)

  #milestone_pos_rot_list = settings['milestone_pos_rot_list'] # NOTE: may want to clean up code referring to this variable
  
  ''' # TODO: marked for removal because feature probably not needed
  if settings['starting_conditions'] == 'configs':
    lig_configs = settings['lig_configs']
  elif settings['starting_conditions'] == 'spheres':
    # then generate the anchors from random positions/orientations in a sphere
    # NOTE: there is a random orientation function in positions_orient.py
    pass
  else:
    raise Exception, "option not allowed: %s" % settings['starting_conditions']
  '''
  
  #bd_file_paths = settings['bd_file_paths']
  #browndye_bin = settings['browndye_bin_dir']
  #if not os.path.exists(empty_pqrxml)
  
  bd_configs = []

  # fill the b_surface folder
  lig_config = seekrcalc.browndye.starting_lig_config # get the first config of the ligand
  lig_center = pdb.center_of_mass(lig_config)
  pqrs = [copy.deepcopy(rec_struct), copy.deepcopy(lig_config)]
  pqrs[1].struct_id='bd_ligand'
  

  #for site in settings['b_surface_ending_surfaces']:
  b_surface_criteria = []
  starting_surfaces = []
  for milestone in seekrcalc.milestones:
    if milestone.end:
      b_surface_criteria.append({'centerx':milestone.center_vec[0], 'centery':milestone.center_vec[1], 'centerz':milestone.center_vec[2], 'ligx':lig_center[0], 'ligy':lig_center[1], 'ligz':lig_center[2], 'radius':milestone.radius, 'index':milestone.index, 'siteid':milestone.siteid}) # add every site to the criteria list
    if milestone.bd:
      starting_surfaces.append({'site':milestone.siteid, 'radius':milestone.radius, 'index':milestone.index})
  
  print "bsurface_criteria:", b_surface_criteria
  b_surface_pqrxmls = write_browndye_input(pqrs, seekrcalc, b_surface_criteria, work_dir=seekrcalc.browndye.b_surface_path, browndye_bin=seekrcalc.browndye.browndye_bin, start_at_site='false', fhpd_mode = False) # write input for this part
  
  '''
  for bd_file_path in bd_file_paths:
    if not bd_file_path:
      pass
      #bd_configs.append(None)
      #continue # then don't do BD for this portion
    #print "bd_file_path:", bd_file_path
    anchor_folder_name = bd_file_path.split('/')[-2] # reading the file tree to get the index of every existing folder
    #print "anchor_folder_name:", anchor_folder_name
    folder_index = anchor_folder_name.split('_')[1] # getting the index out of the folder name
    bd_configs.append(int(folder_index))
  '''
  counter = 0 # the index of the loop itself
  
    
  for milestone in seekrcalc.milestones:
    if milestone.bd:
      lig_config = milestone.config
      bd_file_path = os.path.join(seekrcalc.project.rootdir, milestone.directory, 'bd')
      print "bd_file_path:", bd_file_path
      pqrs = [copy.deepcopy(rec_struct), copy.deepcopy(lig_config)]
      pqrs[1].struct_id='bd_ligand'
      bd_needed = True
      
      '''
      m=0
      for m in range(len(milestone_pos_rot_list)): # m will represent the proper milestone index
        if milestone_pos_rot_list[m][0].index == i:
          break
      '''
      criteria = []
      for surface in starting_surfaces:
        if surface['site'] == milestone.siteid:
          proper_radius = milestone.bd_adjacent.radius
          proper_index = milestone.bd_adjacent.index
        else:
          proper_radius = surface['radius']
          proper_index = surface['index']
        criteria.append({'centerx':milestone.center_vec[0], 'centery':milestone.center_vec[1], 'centerz':milestone.center_vec[2], 'ligx':lig_center[0], 'ligy':lig_center[1], 'ligz':lig_center[2], 'radius':proper_radius, 'index':proper_index, 'siteid':milestone.siteid})
      '''
      criteria = [] #[[(31.121, 37.153, 35.253), (38.742, 51.710, 68.137), 9.0],] # a list of all reaction criteria
      for site in settings['starting_surfaces']:
        #site_center = [site['x'], site['y'],site['z']]
        #radius = site['radius'] # NOTE: at this time, only spherical reaction criteria are allowed in BrownDye
        if milestone_pos_rot_list[m][0].siteid == site['siteid']: # then its the same site, we need to go one shell in
          proper_radius = site['inner_radius'] # the radius in the same site
          proper_index = site['inner_index']
        else: # this is a different site, choose the same radius as starting
          proper_radius = site['outer_radius']
          proper_index = site['outer_index']
        criteria.append({'centerx':site['x'], 'centery':site['y'], 'centerz':site['z'], 'ligx':lig_center[0], 'ligy':lig_center[1], 'ligz':lig_center[2], 'radius':proper_radius, 'index':proper_index, 'siteid':site['siteid']}) # add every site to the criteria list
      '''
      #print "pqrs:", pqrs, 'criteria:', criteria
    
    
      site_pqrxmls = write_browndye_input(pqrs, seekrcalc, criteria, work_dir=bd_file_path, browndye_bin=seekrcalc.browndye.browndye_bin,fhpd_mode=True)
      # make BD preparation scripts extract_bd_frames.py and bd_fhpd.pyp
      # Write the script to extract all frames from the successful b_surface bd trajectories
    
      extract_bd_frames_dict = {'TRAJDIR':"../../b_surface", 'WORKDIR':"./trajs", 'PQRXML0':os.path.basename(b_surface_pqrxmls[0]), 'PQRXML1':os.path.basename(b_surface_pqrxmls[1]), 'EMPTY':empty_pqrxml, 'SITENAME':'%s_%s' % (milestone.siteid, milestone.index), 'NUMBER_OF_TRAJS':seekrcalc.browndye.num_threads}
      extract_bd_frames = Adv_template(extract_bd_frames_template, extract_bd_frames_dict)
      extract_file = open(os.path.join(bd_file_path,"extract_bd_frames.py"), 'w')
      extract_file.write(extract_bd_frames.get_output()) # write an xml file for the input to bd
      extract_file.close()
      # construct the FHPD distribution prep scripts
      make_fhpd_dict = {'INPUT_TEMPLATE_FILENAME':'input.xml', 'RECEPTOR_PQRXML':os.path.basename(b_surface_pqrxmls[0]), 'RXNS':'rxns.xml', 'NTRAJ':seekrcalc.browndye.fhpd_numtraj, 'ARGS':"glob.glob(os.path.join('./trajs','lig*.pqr'))"} # NOTE: should change NTRAJ to be consistent with the number of reaction events in the b_surface phase
      make_fhpd = Adv_template(make_fhpd_template,make_fhpd_dict)
      make_fhpd_file = open(os.path.join(bd_file_path,"make_fhpd.py"), 'w')
      make_fhpd_file.write(make_fhpd.get_output()) # write an xml file for the input to bd
      make_fhpd_file.close()
      # Consolidate all result files from the FHPD simulations into one large results.xml file
      fhpd_consolidate_dict = {'FHPD_DIR':"fhpd", 'LIG_DIR_GLOB':"lig*/", 'RESULTS_NAME':'results.xml'}
      fhpd_consolidate = Adv_template(fhpd_consolidate_template,fhpd_consolidate_dict)
      fhpd_consolidate_file = open(os.path.join(bd_file_path,"fhpd_consolidate.py"), 'w')
      fhpd_consolidate_file.write(fhpd_consolidate.get_output()) # write an xml file for the input to bd
      fhpd_consolidate_file.close()
      make_empty_pqrxml(os.path.join(bd_file_path, 'empty.pqrxml'))

    counter += 1
Exemplo n.º 13
0
def generate_configs(seekrcalc):
    '''Generates the apo and holo configurations of the receptors and ligands.
  Input:
   - seekrcalc: a SeekrCalculation() object that contains all the settings for
       the SEEKR calculation
  Output:
   - None
  '''
    if verbose: print "Generating structural configurations..."
    parser = pdb.Big_PDBParser()
    if verbose: print "now loading structures"

    # Read and/or create pickle files for the structures to save I/O time
    ligand_pkl_filename = os.path.join(seekrcalc.project.rootdir, "ligand.pkl")
    receptor_pkl_wet_filename = os.path.join(seekrcalc.project.rootdir,
                                             "receptor.pkl")
    #receptor_pkl_dry_filename = os.path.join(seekrcalc.project.rootdir, "receptor_dry.pkl")
    receptor_pkl_dry_pqr_filename = os.path.join(seekrcalc.project.rootdir,
                                                 "receptor_dry_pqr.pkl")

    ligand = pickle_or_load(seekrcalc.building.lig_dry_pqr_filename,
                            ligand_pkl_filename,
                            parser,
                            struc_name="ligand",
                            pqr=True)
    receptor_wet = pickle_or_load(seekrcalc.building.rec_wet_pdb_filename,
                                  receptor_pkl_wet_filename,
                                  parser,
                                  struc_name="receptor_wet",
                                  pqr=False)
    receptor_dry = pickle_or_load(seekrcalc.building.rec_dry_pqr_filename,
                                  receptor_pkl_dry_pqr_filename,
                                  parser,
                                  struc_name="receptor_dry_pqr",
                                  pqr=True)

    seekrcalc.building.ligand = ligand
    seekrcalc.building.rec_wet_pdb_filename = receptor_wet
    seekrcalc.building.rec_dry_pqr_filename = receptor_dry
    milestones = seekrcalc.milestones
    configs = []
    starttime = time.time()
    struct_center = pdb.center_of_mass(ligand)
    if verbose: print "Generating", len(milestones), "ligand configurations"
    for milestone in milestones:
        new_ligand = deepcopy(ligand)  # copy the entire structure
        new_ligand.moveby(
            -struct_center)  # reposition ligand structure over the origin
        new_ligand.moveby(
            milestone.anchor)  # move ligand to the anchor location
        new_ligand.struct_id = milestone.fullname
        configs.append(new_ligand)
    endtime = time.time()
    if verbose:
        "Generate_configs complete. Total number: %d. Elapsed time: %d s" % (
            len(configs),
            endtime - starttime,
        )
        print "Now running through all configurations to combine ligand with receptor."
        if seekrcalc.building.reject_clashes:
            print "Rejecting steric clashes..."
        else:
            print "Ignoring steric clashes..."

    if seekrcalc.project.bd:
        seekrcalc.browndye.starting_lig_config = configs[0]

    for i, milestone in enumerate(
            milestones):  # run thru all the configurations of ligands
        lig_config = configs[i]
        milestone.config = deepcopy(lig_config)
        if seekrcalc.building.reject_clashes:
            if structures_clash(lig_config, receptor_dry, tolerance=0.2):
                continue  # if there's a clash
        if milestone.md:
            #pdb.TER_resnames.append(seekrcalc.building.lig_resname) # TODO: marked for removal
            holo_config_wet, insert_index, last_ligand_index = pdb.ligmerge(
                lig_config, receptor_wet, verbose=False)
            holo_config_wet.struct_id = lig_config.struct_id  # set the structure description to the same as the ligand
            holo_config_wet.renumber_indeces(
            )  # to number the indeces consecutively
            wet_holo_filename = milestone.openmm.wet_holo_pdb_filename
            if verbose: print "writing file:", wet_holo_filename
            holo_config_wet.save(
                wet_holo_filename, amber=True, standard=False
            )  # write the holo structure into the md directory
            last_insert_index = insert_index
            last_last_ligand_index = last_ligand_index
        if milestone.bd:
            holo_config_dry, insert_index, last_ligand_index = pdb.ligmerge(
                lig_config, receptor_dry, verbose=False)
            holo_config_dry.struct_id = lig_config.struct_id  # set the structure description to the same as the ligand
            holo_config_dry.renumber_indeces(
            )  # to number the indeces consecutively
            dry_holo_filename = milestone.openmm.dry_holo_pdb_filename
            if verbose: print "writing file:", dry_holo_filename
            holo_config_dry.save(
                dry_holo_filename, amber=True, standard=False
            )  # write the holo structure into the md directory
    return holo_config_wet, last_insert_index, last_last_ligand_index