def test_mpi_cpptraj_style(): comm = MPI.COMM_WORLD # end. you are free to update anything below here # split remd.x.000 to N cores and do calc_surf in parallel root_dir = "data/" traj_name = root_dir + "tz2.ortho.nc" parm_name = root_dir + "tz2.ortho.parm7" # load to TrajectoryIterator traj = pt.iterload(traj_name, parm_name) # save `total_arr` to rank=0 # others: total_arr = None total_arr = pt.pmap_mpi( ['autoimage', 'center :2', 'distance :3 :7', 'angle :3 :7 :8'], traj) if comm.rank != 0: assert total_arr is None if comm.rank == 0: # assert to serial from pytraj.utils.tools import dict_to_ndarray arr = dict_to_ndarray(total_arr) t0 = pt.center(traj[:].autoimage(), ':2') aa_eq(pt.distance(t0, ':3 :7'), arr[0]) aa_eq(pt.angle(t0, ':3 :7 :8'), arr[1])
def test_different_cores(self): # use different frame_slice with different n_cores to test REF_0 = pt.iterload(fn('tz2.nc'), fn('tz2.parm7'))[0] for frame_slice in [ (0, 100), (10, 100, 3), (50, 80, 2), (51, 80, 3), ]: traj = pt.iterload( fn('tz2.nc'), fn('tz2.parm7'), frame_slice=frame_slice) saved_angle = pt.angle(traj, ':3 :7 :9') saved_dist = pt.distance(traj, ':2 :10') saved_rmsd = pt.rmsd(traj, ref=REF_0, mask='@CA') lines = ['angle :3 :7 :9', 'distance :2 :10'] for n_cores in [1, 2]: data_list = [ worker_by_state(rank, n_cores, traj, lines) for rank in range(n_cores) ] final_data = concat_dict([x[1] for x in data_list]) aa_eq(final_data['Ang_00002'], saved_angle) aa_eq(final_data['Dis_00003'], saved_dist)
def test_multiple_cores(self): from multiprocessing import Pool traj = pt.iterload('data/tz2.nc', 'data/tz2.parm7') for _ in range(10): traj._load(traj.filelist) saved_angle = pt.angle(traj, ':3 :10 :11') saved_dist = pt.distance(traj, ':3 :10') for n_cores in [2, 3]: lines = ['angle :3 :10 :11', 'distance :3 :10'] pfuncs = partial(worker_state, n_cores=n_cores, traj=traj, dtype='dict', lines=lines) p = Pool(n_cores) data_list = p.map(pfuncs, [rank for rank in range(n_cores)]) p.close() p.join() data_list_sorted_rank = (data[1] for data in sorted(data_list, key=lambda x: x[0])) final_data = concat_dict(data_list_sorted_rank) aa_eq(final_data['Ang_00002'], saved_angle) aa_eq(final_data['Dis_00003'], saved_dist)
def test_0(self): import numpy as np traj = mdio.iterload(fn('Tc5b.x'), fn('Tc5b.top')) fa = traj[:] mask = ':1@CA :14@CB :15CA' d0 = pt.calc_angle(traj, mask, dtype='dataset').to_ndarray() d1 = pt.angle(traj, mask) d2 = pt.angle(fa, mask) aa_eq(d0, d1) aa_eq(d0, d2) Nsize = 10 arr = np.random.randint(0, 300, size=Nsize * 3).reshape(Nsize, 3) d3 = pt.angle(fa, arr) d4 = pt.angle(traj, arr) d5 = pt.calc_angle(traj, arr) d6 = pt.calc_angle(fa, arr) d7 = pt.calc_angle([fa, traj], arr, n_frames=2 * fa.n_frames) aa_eq(d3, d4) aa_eq(d3, d5) aa_eq(d3, d6) aa_eq(d3.T, d7.T[:fa.n_frames]) aa_eq(d3.T, d7.T[fa.n_frames:]) d8 = pt.angle(traj, mask, dtype='dataset') d9 = pt.tools.dict_to_ndarray(pt.angle(traj, mask, dtype='dict')) aa_eq(d0, d8.values) aa_eq([d0], d9)
def test_0(self): import numpy as np traj = mdio.iterload("./data/Tc5b.x", "./data/Tc5b.top") fa = traj[:] mask = ':1@CA :14@CB :15CA' d0 = pt.calc_angle(traj, mask, dtype='dataset').to_ndarray() d1 = pt.angle(traj, mask) d2 = pt.angle(fa, mask) aa_eq(d0, d1) aa_eq(d0, d2) Nsize = 10 arr = np.random.randint(0, 300, size=Nsize * 3).reshape(Nsize, 3) d3 = pt.angle(fa, arr) d4 = pt.angle(traj, arr) d5 = pt.calc_angle(traj, arr) d6 = pt.calc_angle(fa, arr) d7 = pt.calc_angle([fa, traj], arr, n_frames=2 * fa.n_frames) aa_eq(d3, d4) aa_eq(d3, d5) aa_eq(d3, d6) aa_eq(d3.T, d7.T[:fa.n_frames]) aa_eq(d3.T, d7.T[fa.n_frames:]) d8 = pt.angle(traj, mask, dtype='dataset') d9 = pt.tools.dict_to_ndarray(pt.angle(traj, mask, dtype='dict')) aa_eq(d0, d8.values) aa_eq(d0, d9)
def test_c_command_style(self): traj = pt.iterload(fn('tz2.nc'), fn('tz2.parm7')) angle_ = pt.angle(traj, ':3 :4 :5') distance_ = pt.distance(traj, '@10 @20') data = pt.pmap(['angle :3 :4 :5', 'distance @10 @20'], traj, n_cores=2) assert isinstance(data, OrderedDict), 'must be OrderDict' arr = pt.tools.dict_to_ndarray(data) aa_eq(angle_, arr[0]) aa_eq(distance_, arr[1]) # as whole text, case 1 data = pt.pmap( '''angle :3 :4 :5 distance @10 @20''', traj, n_cores=2) assert isinstance(data, OrderedDict), 'must be OrderDict' arr = pt.tools.dict_to_ndarray(data) aa_eq(angle_, arr[0]) aa_eq(distance_, arr[1])
def test_c_command_style(self): traj = pt.iterload("data/tz2.nc", "data/tz2.parm7") angle_ = pt.angle(traj, ':3 :4 :5') distance_ = pt.distance(traj, '@10 @20') data = pt.pmap(['angle :3 :4 :5', 'distance @10 @20'], traj, n_cores=2) assert isinstance(data, OrderedDict), 'must be OrderDict' arr = pt.tools.dict_to_ndarray(data) aa_eq(angle_, arr[0]) aa_eq(distance_, arr[1]) # as whole text, case 1 data = pt.pmap('''angle :3 :4 :5 distance @10 @20''', traj, n_cores=2) assert isinstance(data, OrderedDict), 'must be OrderDict' arr = pt.tools.dict_to_ndarray(data) aa_eq(angle_, arr[0]) aa_eq(distance_, arr[1])
def test_multiple_cores(self): from multiprocessing import Pool traj = pt.iterload(fn('tz2.nc'), fn('tz2.parm7')) saved_angle = pt.angle(traj, ':3 :10 :11') saved_dist = pt.distance(traj, ':3 :10') for n_cores in [1, 2]: lines = ['angle :3 :10 :11', 'distance :3 :10'] pfuncs = partial(worker_by_state, n_cores=n_cores, traj=traj, dtype='dict', lines=lines) p = Pool(n_cores) data_list = p.map(pfuncs, [rank for rank in range(n_cores)]) p.close() p.join() data_list_sorted_rank = ( data[1] for data in sorted(data_list, key=lambda x: x[0])) final_data = concat_dict(data_list_sorted_rank) aa_eq(final_data['Ang_00002'], saved_angle) aa_eq(final_data['Dis_00003'], saved_dist)
def test_different_cores(self): # use different frame_slice with different n_cores to test REF_0 = pt.iterload("./data/tz2.nc", "./data/tz2.parm7")[0] for frame_slice in [(0, 100), (10, 100, 3), (50, 80, 2), (51, 80, 3), ]: traj = pt.iterload("./data/tz2.nc", "./data/tz2.parm7", frame_slice=frame_slice) saved_angle = pt.angle(traj, ':3 :7 :9') saved_dist = pt.distance(traj, ':2 :10') saved_rmsd = pt.rmsd(traj, ref=REF_0, mask='@CA') lines = ['angle :3 :7 :9', 'distance :2 :10'] for n_cores in [2, 3]: data_list = [worker_state(rank, n_cores, traj, lines) for rank in range(n_cores)] final_data = concat_dict([x[1] for x in data_list]) aa_eq(final_data['Ang_00002'], saved_angle) aa_eq(final_data['Dis_00003'], saved_dist)
def static_DAT_restraint( restraint_mask_list, num_window_list, ref_structure, force_constant, continuous_apr=True, amber_index=False, ): """ Create a static restraint """ # Setup reference structure if isinstance(ref_structure, str): ref_structure = utils.return_parmed_structure(ref_structure) elif isinstance(ref_structure, pmd.structure.Structure): pass else: raise Exception( "static_DAT_restraint does not support the type associated with ref_structure:" + type(ref_structure)) ref_traj = pt.load_parmed(ref_structure, traj=True) # Check num_window_list if len(num_window_list) != 3: raise Exception( "The num_window_list needs to contain three integers corresponding to the number of windows in the attach, pull, and release phase, respectively" ) # Setup restraint rest = DAT_restraint() rest.continuous_apr = continuous_apr rest.amber_index = amber_index rest.topology = ref_structure rest.mask1 = restraint_mask_list[0] rest.mask2 = restraint_mask_list[1] if len(restraint_mask_list) >= 3: rest.mask3 = restraint_mask_list[2] if len(restraint_mask_list) == 4: rest.mask4 = restraint_mask_list[3] # Target value mask_string = " ".join(restraint_mask_list) if len(restraint_mask_list) == 2: # Distance restraint target = pt.distance(ref_traj, mask_string)[0] elif len(restraint_mask_list) == 3: # Angle restraint target = pt.angle(ref_traj, mask_string)[0] elif len(restraint_mask_list) == 4: # Dihedral restraint target = pt.dihedral(ref_traj, mask_string)[0] else: raise Exception( "The number of masks (" + str(len(restraint_mask_list)) + ") in restraint_mask_list is not 2, 3, or 4 and thus is not one of the supported types: distance, angle, dihedral" ) # Attach phase if num_window_list[0] is not None and num_window_list[0] != 0: rest.attach["target"] = target rest.attach["fc_initial"] = force_constant rest.attach["fc_final"] = force_constant rest.attach["num_windows"] = num_window_list[0] # Pull phase if num_window_list[1] is not None and num_window_list[1] != 0: rest.pull["fc"] = force_constant rest.pull["target_initial"] = target rest.pull["target_final"] = target rest.pull["num_windows"] = num_window_list[1] # Release phase if num_window_list[2] is not None and num_window_list[2] != 0: rest.release["target"] = target rest.release["fc_initial"] = force_constant rest.release["fc_final"] = force_constant rest.release["num_windows"] = num_window_list[2] rest.initialize() return rest
def static_DAT_restraint( restraint_mask_list, num_window_list, ref_structure, force_constant, continuous_apr=True, amber_index=False, ): """ Create a restraint whose value does not change during a calculation. Parameters ---------- restraint_mask_list: list A list of masks for which this restraint applies. num_window_list: list A list of windows during which this restraint will be applied, which should be in the form: [attach windows, pull windows, release windows]. ref_structure: Path-like or parmed Amber object The reference structure that is used to determine the initial, **static** value for this restraint. force_constant: float The force constant for this restraint. continuous_apr: bool Whether this restraint uses ``continuous_apr``. This must be consistent with existing restraints. amber_index: bool Whether the atom indices for the restraint should be AMBER-style (+1) or not. Returns ------- rest: ``DAT_restraint`` A static restraint. """ # Check num_window_list if len(num_window_list) != 3: raise ValueError( "The num_window_list needs to contain three integers corresponding to the number of windows in the " "attach, pull, and release phase, respectively ") rest = DAT_restraint() rest.continuous_apr = continuous_apr rest.amber_index = amber_index if isinstance(ref_structure, pmd.amber._amberparm.AmberParm): reference_trajectory = pt.load_parmed(ref_structure, traj=True) rest.topology = ref_structure elif isinstance(ref_structure, str): reference_trajectory = pt.iterload(ref_structure, traj=True) rest.topology = pmd.load_file(ref_structure, structure=True) else: raise TypeError( "static_DAT_restraint does not support the type associated with ref_structure:" + type(ref_structure)) rest.mask1 = restraint_mask_list[0] rest.mask2 = restraint_mask_list[1] if len(restraint_mask_list) >= 3: rest.mask3 = restraint_mask_list[2] if len(restraint_mask_list) == 4: rest.mask4 = restraint_mask_list[3] # Target value mask_string = " ".join(restraint_mask_list) if len(restraint_mask_list) == 2: # Distance restraint if reference_trajectory.top.has_box(): target = pt.distance(reference_trajectory, mask_string, image=True)[0] logger.debug("Calculating distance with 'image = True' ...") else: target = pt.distance(reference_trajectory, mask_string, image=False)[0] logger.debug("Calculating distance with 'image = False' ...") elif len(restraint_mask_list) == 3: # Angle restraint target = pt.angle(reference_trajectory, mask_string)[0] elif len(restraint_mask_list) == 4: # Dihedral restraint target = pt.dihedral(reference_trajectory, mask_string)[0] else: raise IndexError( f"The number of masks -- {len(restraint_mask_list)} -- is not 2, 3, or 4 and thus is not one of the " f"supported types: distance, angle, or dihedral.") # Attach phase if num_window_list[0] is not None and num_window_list[0] != 0: rest.attach["target"] = target rest.attach["fc_initial"] = force_constant rest.attach["fc_final"] = force_constant rest.attach["num_windows"] = num_window_list[0] # Pull phase if num_window_list[1] is not None and num_window_list[1] != 0: rest.pull["fc"] = force_constant rest.pull["target_initial"] = target rest.pull["target_final"] = target rest.pull["num_windows"] = num_window_list[1] # Release phase if num_window_list[2] is not None and num_window_list[2] != 0: rest.release["target"] = target rest.release["fc_initial"] = force_constant rest.release["fc_final"] = force_constant rest.release["num_windows"] = num_window_list[2] rest.initialize() return rest
def main(traj): ''' 氢键分析与数据导出 Paramters ---------- traj: MD轨迹 pytraj对象 ''' print('\nStart H-Bond Analysis...') # hbond 分析 hb = pt.hbond( traj, mask=':*', distance=4, options='avgout ./pynalysis/hbond/avg-hbd.dat printatomnum nointramol') ''' options可填参数与cpptraj一致 输出氢键平均信息文件 打印原子序号 仅计算分子间氢键 distance: 识别氢键cutoff值 默认值3埃 ''' distance_mask = hb.get_amber_mask()[0] print('Hbond Distance Mask: {} \n '.format(distance_mask)) angle_mask = hb.get_amber_mask()[1] print('Hbond Hngle Mask: {} \n'.format(angle_mask)) print("\nHbond Data") print(hb.data) # 1: have hbond; 0: does not have hbond # 创建excel工作表 hbondxlsx = xlsxwriter.Workbook('./pynalysis/hbond/hbond.xlsx') distance_sheet = hbondxlsx.add_worksheet('Distance') angle_sheet = hbondxlsx.add_worksheet('Angle') # 写入header col = 0 row = 0 for hbond_mask in distance_mask: distance_sheet.write(row, col, hbond_mask) col += 1 col = 0 row = 0 for hbond_mask in angle_mask: angle_sheet.write(row, col, hbond_mask) col += 1 # 计算氢键距离 dist = pt.distance(traj, distance_mask) print('\nAll Hbond Distance: \n', dist, end='\n') # 计算氢键角度 angle = pt.angle(traj, angle_mask) print('\nAll Hbond Angle: \n', angle, end='\n') print('\nSaving Data...', end='\n') # 写入氢键长度角度数据 row = 1 col = 0 for i in dist[:]: for j in i[:]: distance_sheet.write(row, col, j) row += 1 col += 1 row = 1 row = 1 col = 0 for l in angle[:]: for k in l[:]: angle_sheet.write(row, col, k) row += 1 col += 1 row = 1 hbondxlsx.close() print('\nDistance and Angle Raw Data(hbond.xlsx) saved.', end='\n') print('\nH Bond Analysis Complete\n') print(''.center(80, '*'))
def test_openmm_cb6but_sim(num_rests=0, guest_pos='guest_inside'): path = './cb6-but_test/' + guest_pos + '/' topology = 'cb6-but-dum.prmtop' coordinates = 'cb6-but-dum.rst7' if num_rests > 0: md_out = 'cb6_but_openmm_rest_{:02d}.csv'.format(num_rests) traj_out = 'cb6_but_openmm_rest_{:02d}.nc'.format(num_rests) else: md_out = 'cb6_but_openmm.csv' traj_out = 'cb6_but_openmm.nc' structure = pmd.load_file(path + topology, path + coordinates, structure=True) traj = pt.load(path + coordinates, path + topology) host = ":CB6" guest = ":BUT" H = [host + "@C7", host + "@C31", host + "@C19"] G = [guest + "@C", guest + "@C3"] D = [":DM1", ":DM2", ":DM3"] H_i = [0, 0, 0] G_i = [0, 0] D_i = [0, 0, 0] # Get indices for atom masks for i, mask in enumerate(H): H_i[i] = utils.index_from_mask(structure, mask, amber_index=False)[0] for i, mask in enumerate(G): G_i[i] = utils.index_from_mask(structure, mask, amber_index=False)[0] for i, mask in enumerate(D): D_i[i] = utils.index_from_mask(structure, mask, amber_index=False)[0] # Set mass of Dummy atoms to 0 so they are non-interacting for i, atom in enumerate(structure.atoms): if atom.name == 'DUM': atom.mass = 0.0 topology_0m = 'cb6-but-dum-0m.prmtop' coordinates_0m = 'cb6-but-dum-0m.rst7' structure.save(path + topology_0m, overwrite=True) structure.save(path + coordinates_0m, overwrite=True) prmtop = app.AmberPrmtopFile(path + topology_0m) inpcrd = app.AmberInpcrdFile(path + coordinates_0m) settings = { 'nonbonded_method': app.NoCutoff, 'temperature': 298.15 * unit.kelvin, 'friction': 1 / unit.picosecond, 'timestep': 0.002 * unit.picosecond, 'implicit_solvent': app.HCT, 'dist_fc': 5.0, 'angle_fc': 100.0, 'numsteps': 500000, } system = prmtop.createSystem( nonbondedMethod=settings['nonbonded_method'], implicitSolvent=settings['implicit_solvent'], removeCMMotion=False, ) integrator = LangevinIntegrator(settings['temperature'], settings['friction'], settings['timestep']) # Create Positional Restraints for Dummy atoms pos_restraint = mm.CustomExternalForce('k*((x-x0)^2+(y-y0)^2+(z-z0)^2)') pos_restraint.addGlobalParameter( 'k', 50.0 * unit.kilocalories_per_mole / unit.angstroms**2) pos_restraint.addPerParticleParameter('x0') pos_restraint.addPerParticleParameter('y0') pos_restraint.addPerParticleParameter('z0') for i, atom in enumerate(structure.positions): if structure.atoms[i].name == 'DUM': pos_restraint.addParticle(i, atom.value_in_unit(unit.nanometers)) static_restraints = [] # Create Distance Restraint static_distance_rest = [D[0], H[0]] static_init_dist = pt.distance(traj, D[0] + ' ' + H[0])[0] dist_restraint = mm.CustomBondForce('k*(r-r0)^2') dist_restraint.addPerBondParameter('k') dist_restraint.addPerBondParameter('r0') r0 = static_init_dist * unit.angstroms k = settings['dist_fc'] * unit.kilocalories_per_mole / unit.angstroms**2 dist_restraint.addBond(D_i[0], H_i[0], [k, r0]) static_restraints.append(dist_restraint) # Create Angle Restraint 1 static_angle_rest_1 = [D[1], D[0], H[0]] static_init_angle_1 = pt.angle(traj, D[1] + ' ' + D[0] + ' ' + H[0])[0] angle_restraint_1 = mm.CustomAngleForce('0.5*k*(theta-theta0)^2') angle_restraint_1.addPerAngleParameter('k') angle_restraint_1.addPerAngleParameter('theta0') theta0 = static_init_angle_1 * unit.degrees k = settings['angle_fc'] * unit.kilocalories_per_mole / unit.radians**2 angle_restraint_1.addAngle(D_i[1], D_i[0], H_i[0], [k, theta0]) static_restraints.append(angle_restraint_1) # Create Dihedral Restraint 1 static_dihedral_rest_1 = [D[2], D[1], D[0], H[0]] static_init_dihedral_1 = pt.dihedral( traj, D[2] + ' ' + D[1] + ' ' + D[0] + ' ' + H[0])[0] dihedral_restraint_1 = mm.CustomTorsionForce('0.5*k*(theta-theta0)^2') dihedral_restraint_1.addPerTorsionParameter('k') dihedral_restraint_1.addPerTorsionParameter('theta0') theta0 = static_init_dihedral_1 * unit.degrees k = settings['angle_fc'] * unit.kilocalories_per_mole / unit.radians**2 dihedral_restraint_1.addTorsion(D_i[2], D_i[1], D_i[0], H_i[0], [k, theta0]) static_restraints.append(dihedral_restraint_1) # Create Angle Restraint 2 static_angle_rest_2 = [D[0], H[0], H[1]] static_init_angle_2 = pt.angle(traj, D[0] + ' ' + H[0] + ' ' + H[1])[0] angle_restraint_2 = mm.CustomAngleForce('0.5*k*(theta-theta0)^2') angle_restraint_2.addPerAngleParameter('k') angle_restraint_2.addPerAngleParameter('theta0') theta0 = static_init_angle_2 * unit.degrees k = settings['angle_fc'] * unit.kilocalories_per_mole / unit.radians**2 angle_restraint_2.addAngle(D_i[0], H_i[0], H_i[1], [k, theta0]) static_restraints.append(angle_restraint_2) # Create Dihedral Restraint 2 static_dihedral_rest_2 = [D[1], D[0], H[0], H[1]] static_init_dihedral_2 = pt.dihedral( traj, D[1] + ' ' + D[0] + ' ' + H[0] + ' ' + H[1])[0] dihedral_restraint_2 = mm.CustomTorsionForce('0.5*k*(theta-theta0)^2') dihedral_restraint_2.addPerTorsionParameter('k') dihedral_restraint_2.addPerTorsionParameter('theta0') theta0 = static_init_dihedral_2 * unit.degrees k = settings['angle_fc'] * unit.kilocalories_per_mole / unit.radians**2 dihedral_restraint_2.addTorsion(D_i[1], D_i[0], H_i[0], H_i[1], [k, theta0]) static_restraints.append(dihedral_restraint_2) # Create Dihedral Restraint 3 static_dihedral_rest_3 = [D[0], H[0], H[1], H[2]] static_init_dihedral_3 = pt.dihedral( traj, D[0] + ' ' + H[0] + ' ' + H[1] + ' ' + H[2])[0] dihedral_restraint_3 = mm.CustomTorsionForce('0.5*k*(theta-theta0)^2') dihedral_restraint_3.addPerTorsionParameter('k') dihedral_restraint_3.addPerTorsionParameter('theta0') theta0 = static_init_dihedral_3 * unit.degrees k = settings['angle_fc'] * unit.kilocalories_per_mole / unit.radians**2 dihedral_restraint_3.addTorsion(D_i[0], H_i[0], H_i[1], H_i[2], [k, theta0]) static_restraints.append(dihedral_restraint_3) #system.addForce(pos_restraint) if num_rests > 0: for rest in static_restraints[0:num_rests]: system.addForce(rest) simulation = app.Simulation(prmtop.topology, system, integrator, mm.Platform.getPlatformByName('CPU')) simulation.context.setPositions(inpcrd.positions) simulation.reporters.append(NetCDFReporter(path + traj_out, 250)) simulation.reporters.append( app.StateDataReporter(path + md_out, 250, step=True, time=True, potentialEnergy=True, kineticEnergy=True, totalEnergy=True, temperature=True, volume=True, density=True)) simulation.step(settings['numsteps'])
import pytraj as pt from pytraj.testing import aa_eq comm = MPI.COMM_WORLD # end. you are free to update anything below here # split remd.x.000 to N cores and do calc_surf in parallel root_dir = "data/" traj_name = root_dir + "tz2.ortho.nc" parm_name = root_dir + "tz2.ortho.parm7" # load to TrajectoryIterator traj = pt.iterload(traj_name, parm_name) # save `total_arr` to rank=0 # others: total_arr = None total_arr = pt.pmap_mpi( ['autoimage', 'center :2', 'distance :3 :7', 'angle :3 :7 :8'], traj) if comm.rank != 0: assert total_arr is None if comm.rank == 0: # assert to serial from pytraj.tools import dict_to_ndarray arr = dict_to_ndarray(total_arr) t0 = pt.center(traj[:].autoimage(), ':2') aa_eq(pt.distance(t0, ':3 :7'), arr[0]) aa_eq(pt.angle(t0, ':3 :7 :8'), arr[1])
struct_dir + '/' + old_topology) static_distance_rest = [D[0], H[0]] static_init_dist = pt.distance(traj, D[0] + ' ' + H[0])[0] dist_restraint = mm.CustomBondForce('k * (r - r_0)^2') dist_restraint.addPerBondParameter('k') dist_restraint.addPerBondParameter('r_0') r_0 = static_init_dist * angstroms k = 5 * kilojoules_per_mole / angstroms**2 dist_restraint.addBond(D_i[0], H_i[0], [k, r_0]) # Angle restraint 1 static_angle_rest1 = [D[1], D[0], H[0]] static_init_angle1 = pt.angle(traj, D[1] + ' ' + D[0] + ' ' + H[0])[0] angle_restraint1 = mm.CustomAngleForce('0.5*k*(theta-theta_0)^2') angle_restraint1.addPerAngleParameter('k') angle_restraint1.addPerAngleParameter('theta_0') theta_0 = static_init_angle1 * degrees k = 100 * kilojoules_per_mole / angstroms**2 angle_restraint1.addAngle(D_i[1], D_i[0], H_i[0], [k, theta_0]) # Dihedral restraint 1 static_dihedral_rest1 = [D[2], D[1], D[0], H[0]] static_init_dihedral1 = pt.dihedral( traj, D[2] + ' ' + D[1] + ' ' + D[0] + ' ' + H[0])[0]
def candidatevalues_rc_eval(coord_file, index, settings): """ Evaluate the index'th candidate OP values from the coordinates given by the coord_file This code is copied from the atesa.py function of the same name, and modified to accept a single coordinate file rather than a thread as its argument, as well as to return only the index'th OP as a float rather than every OP as a space-separated string. This function may appear "unused"; this is because it is only actually called indirectly within eval() calls. It is necessary! This function is only capable of returning order parameter rate of change values when the literal_ops Boolean is True. This will change in future versions. Parameters ---------- coord_file : str The name of the coordinate file from which the candidate OP should be read. index : int The zero-indexed index corresponding to the desired OP. Returns ------- float The evaluation of the desired candidate OP. """ def increment_coords(coord_file): # Modified from revvels() to increment coordinate values by velocities, rather than reversing velocities. # Returns the name of the newly-created coordinate file byline = open(coord_file).readlines() pattern = re.compile( '[-0-9.]+' ) # regex to match numbers including decimals and negatives pattern2 = re.compile( '\s[-0-9.]+' ) # regex to match numbers including decimals and negatives, with one space in front n_atoms = pattern.findall(byline[1])[ 0] # number of atoms indicated on second line of .rst file shutil.copyfile(coord_file, 'temp' + settings.committor_suffix + '.rst') for i, line in enumerate( fileinput.input('temp' + settings.committor_suffix + '.rst', inplace=1)): if int(n_atoms) / 2 + 2 > i >= 2: newline = line coords = pattern2.findall(newline) # line of coordinates vels = pattern2.findall( byline[i + int(math.ceil(int(n_atoms) / 2))]) # corresponding velocities for index in range(len(coords)): length = len( coords[index] ) # length of string representing this coordinate replace_string = ' ' + str( float(coords[index]) + float(vels[index]))[0:length - 1] while len(replace_string) < length: replace_string += '0' newline = newline.replace(coords[index], replace_string) sys.stdout.write(newline) else: sys.stdout.write(line) return 'temp' + settings.committor_suffix + '.rst' try: null = settings.committor_suffix except AttributeError: settings.committor_suffix = '' try: traj = pytraj.iterload(coord_file, settings.topology) except ValueError: sys.exit('Error: coordinate file name ' + coord_file + ' is invalid.') if settings.literal_ops: try: # assuming this is not a rate of change OP... output = float(eval(settings.candidateops[index])) except IndexError: # this is a rate of change OP after all, so... v_0 = float( eval(settings.candidateops[int(index - len(settings.candidateops))]) ) # value of relevant OP at t = 0 traj = pytraj.iterload( increment_coords(coord_file), settings.topology) # new traj for evaluation of OPs v_1 = float( eval(settings.candidateops[int(index - len(settings.candidateops))]) ) # value of OP at t = 1/20.455 ps output = float( v_1 - v_0) # subtract value of op from value 1/20.455 ps earlier else: if len(settings.candidateops ) == 4: # settings.candidateops contains dihedrals if settings.candidateops[3][index]: # if this OP is a dihedral value = pytraj.dihedral(traj, mask=settings.candidateops[0][index] + ' ' + settings.candidateops[1][index] + ' ' + settings.candidateops[2][index] + ' ' + settings.candidateops[3][index]) elif settings.candidateops[2][index]: # if this OP is an angle value = pytraj.angle(traj, mask=settings.candidateops[0][index] + ' ' + settings.candidateops[1][index] + ' ' + settings.candidateops[2][index]) else: # if this OP is a distance value = pytraj.distance(traj, mask=settings.candidateops[0][index] + ' ' + settings.candidateops[1][index]) output = float(value) elif len( settings.candidateops ) == 3: # settings.candidateops contains angles but not dihedrals if settings.candidateops[2][index]: # if this OP is an angle value = pytraj.angle(traj, mask=settings.candidateops[0][index] + ' ' + settings.candidateops[1][index] + ' ' + settings.candidateops[2][index]) else: # if this OP is a distance value = pytraj.distance(traj, mask=settings.candidateops[0][index] + ' ' + settings.candidateops[1][index]) output = float(value) else: # settings.candidateops contains only distances value = pytraj.distance(traj, mask=settings.candidateops[0][index] + ' ' + settings.candidateops[1][index]) output = float(value) # Before returning the result, we want to convert to a reduced variable z = (r-rmin)/(rmax-rmin) if settings.rc_minmax: try: if not settings.rc_minmax[0][index] or not settings.rc_minmax[1][ index]: # if there's a blank entry in rc_minmax sys.exit('\nError: rc_definition contains reference to CV' + str(index + 1) + ' without a corresponding entry in rc_minmax') except IndexError: # if there's no entry at all sys.exit('\nError: rc_definition contains reference to CV' + str(index + 1) + ' without a corresponding entry in rc_minmax') raw_output = output output = (output - settings.rc_minmax[0][index]) / ( settings.rc_minmax[1][index] - settings.rc_minmax[0][index]) if not -0.01 <= output <= 1.01: # For debugging # print(raw_output) # print(v_0) # print(v_1) if settings.minmax_error_behavior == 'exit': sys.exit( '\nError: reduced variable at index ' + str(index) + ' (zero-indexed) in coordinate file ' + coord_file + ' is not between 0 and 1 (value is ' + str(output) + '). ' 'minmax_error_behavior = exit, so exiting. Check that rc_minmax is correct.' ) elif settings.minmax_error_behavior == 'skip': print( '\nWarning: reduced variable at index ' + str(index) + ' (zero-indexed) in coordinate file ' + coord_file + ' is not between 0 and 1 (value is ' + str(output) + '). minmax_error_behavior' ' = skip, so this file is being skipped and will not appear in rc_eval' + settings.committor_suffix + '.out') return 'SKIP' elif settings.minmax_error_behavior == 'accept': print( '\nWarning: reduced variable at index ' + str(index) + ' (zero-indexed) in coordinate file ' + coord_file + ' is not between 0 and 1 (value is ' + str(output) + '). minmax_error_behavior' ' = accept, so this file is NOT being skipped and will appear in rc_eval' + settings.committor_suffix + '.out') return output
def main(traj, top): ''' 用户选择计算模式 调用pytraj计算 调用xlsxwriter保存数据文件 Paramters ---------- traj: MD轨迹 Pytraj对象 top: MD拓扑文件PATH ''' print(''' 请输入计算模式: 1.计算原子间距离(键长)变化 2.计算键角变化 3.计算二面角变化 0.退出 ''') while True: flag = input().strip() if re.match('[0123]', flag): flag = int(flag) break else: print('输入代号无效,请重新输入\n') if flag == 0: sys.exit() lis = get_mask(flag) topfile = pt.load_topology(top) masks = '' for i in lis: masks += i + ' ' judge(i, topfile) print('\nProcessing and Saving Data...') disangxlsx = xlsxwriter.Workbook( './pynalysis/dis_ang/distance_angle_data.xlsx') def save(sheet, mask, data): # 保存数据 sheet.write(0, 0, mask) col = 0 row = 1 for i in data: sheet.write(row, col, i) row += 1 if flag == 1: dis = pt.distance(traj, masks) print('\nDistance Data:\n', dis) distance_sheet = disangxlsx.add_worksheet('Distance') save(distance_sheet, masks, dis) if flag == 2: angle = pt.angle(traj, masks) print('Angel Data:\n', angle) angel_sheet = disangxlsx.add_worksheet('Angel') save(angel_sheet, masks, angle) if flag == 3: dihedral = pt.dihedral(traj, masks) print('Dihedral Data:\n', dihedral) dihedral_sheet = disangxlsx.add_worksheet('Dihedral') save(dihedral_sheet, masks, dihedral) disangxlsx.close() print('\ndistance_angle_data.xlsx Data Saved.', end='\n')