def test_solvate_existing_structure_protocol(): """Tests solvating a single methanol molecule in water.""" methanol_substance = Substance() methanol_substance.add_component(Substance.Component('CO'), Substance.ExactAmount(1)) water_substance = Substance() water_substance.add_component(Substance.Component('O'), Substance.MoleFraction(1.0)) with tempfile.TemporaryDirectory() as temporary_directory: build_methanol_coordinates = BuildCoordinatesPackmol('build_methanol') build_methanol_coordinates.max_molecules = 1 build_methanol_coordinates.substance = methanol_substance build_methanol_coordinates.execute(temporary_directory, ComputeResources()) solvate_coordinates = SolvateExistingStructure('solvate_methanol') solvate_coordinates.max_molecules = 9 solvate_coordinates.substance = water_substance solvate_coordinates.solute_coordinate_file = build_methanol_coordinates.coordinate_file_path solvate_coordinates.execute(temporary_directory, ComputeResources()) solvated_pdb = PDBFile(solvate_coordinates.coordinate_file_path) assert solvated_pdb.topology.getNumResidues() == 10
def test_addition_subtract_protocols(): with tempfile.TemporaryDirectory() as temporary_directory: quantity_a = EstimatedQuantity(1 * unit.kelvin, 0.1 * unit.kelvin, 'dummy_source_1') quantity_b = EstimatedQuantity(2 * unit.kelvin, 0.2 * unit.kelvin, 'dummy_source_2') add_quantities = AddQuantities('add') add_quantities.values = [quantity_a, quantity_b] result = add_quantities.execute(temporary_directory, ComputeResources()) assert not isinstance(result, PropertyEstimatorException) assert add_quantities.result.value == 3 * unit.kelvin sub_quantities = SubtractQuantities('sub') sub_quantities.value_b = quantity_b sub_quantities.value_a = quantity_a result = sub_quantities.execute(temporary_directory, ComputeResources()) assert not isinstance(result, PropertyEstimatorException) assert sub_quantities.result.value == 1 * unit.kelvin
def test_run_openmm_simulation_checkpoints(): import mdtraj thermodynamic_state = ThermodynamicState(298 * unit.kelvin, 1.0 * unit.atmosphere) with tempfile.TemporaryDirectory() as directory: coordinate_path, system_path = _setup_dummy_system(directory) # Check that executing twice doesn't run the simulation twice npt_equilibration = RunOpenMMSimulation('npt_equilibration') npt_equilibration.total_number_of_iterations = 1 npt_equilibration.steps_per_iteration = 4 npt_equilibration.output_frequency = 1 npt_equilibration.thermodynamic_state = thermodynamic_state npt_equilibration.input_coordinate_file = coordinate_path npt_equilibration.system_path = system_path npt_equilibration.execute(directory, ComputeResources()) assert os.path.isfile(npt_equilibration._checkpoint_path) npt_equilibration.execute(directory, ComputeResources()) assert len( StatisticsArray.from_pandas_csv( npt_equilibration.statistics_file_path)) == 4 assert len( mdtraj.load(npt_equilibration.trajectory_file_path, top=coordinate_path)) == 4 # Make sure that the output files are correctly truncating if more frames # than expected are written with open(npt_equilibration._checkpoint_path, 'r') as file: checkpoint = json.load(file, cls=TypedJSONDecoder) # Fake having saved more frames than expected npt_equilibration.steps_per_iteration = 8 checkpoint.steps_per_iteration = 8 npt_equilibration.output_frequency = 2 checkpoint.output_frequency = 2 with open(npt_equilibration._checkpoint_path, 'w') as file: json.dump(checkpoint, file, cls=TypedJSONEncoder) npt_equilibration.execute(directory, ComputeResources()) assert len( StatisticsArray.from_pandas_csv( npt_equilibration.statistics_file_path)) == 4 assert len( mdtraj.load(npt_equilibration.trajectory_file_path, top=coordinate_path)) == 4
def main(n_workers, cpus_per_worker, gpus_per_worker): if n_workers <= 0: raise ValueError('The number of workers must be greater than 0') if cpus_per_worker <= 0: raise ValueError('The number of CPU\'s per worker must be greater than 0') if gpus_per_worker < 0: raise ValueError('The number of GPU\'s per worker must be greater than or equal to 0') if 0 < gpus_per_worker != cpus_per_worker: raise ValueError('The number of GPU\'s per worker must match the number of ' 'CPU\'s per worker.') # Set up logging for the propertyestimator. setup_timestamp_logging() logger = logging.getLogger() # Set up the directory structure. working_directory = 'working_directory' storage_directory = 'storage_directory' # Remove any existing data. if path.isdir(working_directory): shutil.rmtree(working_directory) # Set up a backend to run the calculations on with the requested resources. if gpus_per_worker <= 0: worker_resources = ComputeResources(number_of_threads=cpus_per_worker) else: worker_resources = ComputeResources(number_of_threads=cpus_per_worker, number_of_gpus=gpus_per_worker, preferred_gpu_toolkit=QueueWorkerResources.GPUToolkit.CUDA) calculation_backend = DaskLocalCluster(number_of_workers=n_workers, resources_per_worker=worker_resources) # Create a backend to cache simulation files. storage_backend = LocalFileStorage(storage_directory) # Create an estimation server which will run the calculations. logger.info(f'Starting the server with {n_workers} workers, each with ' f'{cpus_per_worker} CPUs and {gpus_per_worker} GPUs.') server = PropertyEstimatorServer(calculation_backend=calculation_backend, storage_backend=storage_backend, working_directory=working_directory, port=8000) # Tell the server to start listening for estimation requests. server.start_listening_loop()
def test_substance_filtering_protocol(filter_role): """Tests that the protocol to filter substances by role correctly works.""" def create_substance(): test_substance = Substance() test_substance.add_component(Substance.Component('C', role=Substance.ComponentRole.Solute), Substance.ExactAmount(1)) test_substance.add_component(Substance.Component('CC', role=Substance.ComponentRole.Ligand), Substance.ExactAmount(1)) test_substance.add_component(Substance.Component('CCC', role=Substance.ComponentRole.Receptor), Substance.ExactAmount(1)) test_substance.add_component(Substance.Component('O', role=Substance.ComponentRole.Solvent), Substance.MoleFraction(1.0)) return test_substance filter_protocol = FilterSubstanceByRole('filter_protocol') filter_protocol.input_substance = create_substance() filter_protocol.component_role = filter_role filter_protocol.execute('', ComputeResources()) assert len(filter_protocol.filtered_substance.components) == 1 assert filter_protocol.filtered_substance.components[0].role == filter_role
def test_reweight_statistics(): number_of_frames = 10 reduced_potentials = np.ones(number_of_frames) * random.random() * unit.dimensionless potentials = np.ones(number_of_frames) * random.random() * unit.kilojoule / unit.mole with tempfile.TemporaryDirectory() as directory: statistics_path = path.join(directory, 'stats.csv') statistics_array = StatisticsArray() statistics_array[ObservableType.ReducedPotential] = reduced_potentials statistics_array[ObservableType.PotentialEnergy] = potentials statistics_array.to_pandas_csv(statistics_path) reweight_protocol = ReweightStatistics(f'reduced_potentials') reweight_protocol.statistics_type = ObservableType.PotentialEnergy reweight_protocol.statistics_paths = [statistics_path] reweight_protocol.reference_reduced_potentials = [statistics_path] reweight_protocol.target_reduced_potentials = [statistics_path] reweight_protocol.bootstrap_uncertainties = True reweight_protocol.required_effective_samples = 0 result = reweight_protocol.execute(directory, ComputeResources()) assert not isinstance(result, PropertyEstimatorException)
def test_central_difference_gradient(): with tempfile.TemporaryDirectory() as directory: gradient_key = ParameterGradientKey('vdW', '[#1]-[#8X2H2+0:1]-[#1]', 'epsilon') reverse_parameter = -random.random() * unit.kelvin reverse_observable = -random.random() * unit.kelvin forward_parameter = random.random() * unit.kelvin forward_observable = random.random() * unit.kelvin central_difference = CentralDifferenceGradient('central_difference') central_difference.parameter_key = gradient_key central_difference.reverse_observable_value = reverse_observable central_difference.reverse_parameter_value = reverse_parameter central_difference.forward_observable_value = forward_observable central_difference.forward_parameter_value = forward_parameter result = central_difference.execute(directory, ComputeResources()) assert not isinstance(result, PropertyEstimatorException) assert central_difference.gradient.value == ( (forward_observable - reverse_observable) / (forward_parameter - reverse_parameter))
def test_extract_uncorrelated_trajectory_data(): import mdtraj coordinate_path = get_data_filename('test/trajectories/water.pdb') trajectory_path = get_data_filename('test/trajectories/water.dcd') original_trajectory = mdtraj.load(trajectory_path, top=coordinate_path) with tempfile.TemporaryDirectory() as temporary_directory: extract_protocol = ExtractUncorrelatedTrajectoryData( 'extract_protocol') extract_protocol.input_coordinate_file = coordinate_path extract_protocol.input_trajectory_path = trajectory_path extract_protocol.equilibration_index = 2 extract_protocol.statistical_inefficiency = 2.0 result = extract_protocol.execute(temporary_directory, ComputeResources()) assert not isinstance(result, PropertyEstimatorException) final_trajectory = mdtraj.load(extract_protocol.output_trajectory_path, top=coordinate_path) assert len(final_trajectory) == (len(original_trajectory) - 2) / 2 assert extract_protocol.number_of_uncorrelated_samples == ( len(original_trajectory) - 2) / 2
def _get_options_dictionary(self, available_resources): """Returns a dictionary of options which will be serialized to a yaml file and passed to YANK. Parameters ---------- available_resources: ComputeResources The resources available to execute on. Returns ------- dict of str and Any A yaml compatible dictionary of YANK options. """ from openforcefield.utils import quantity_to_string platform_name = 'CPU' if available_resources.number_of_gpus > 0: # A platform which runs on GPUs has been requested. from propertyestimator.backends import ComputeResources toolkit_enum = ComputeResources.GPUToolkit( available_resources.preferred_gpu_toolkit) # A platform which runs on GPUs has been requested. platform_name = 'CUDA' if toolkit_enum == ComputeResources.GPUToolkit.CUDA else \ ComputeResources.GPUToolkit.OpenCL return { 'verbose': self.verbose, 'output_dir': '.', 'temperature': quantity_to_string( pint_quantity_to_openmm(self.thermodynamic_state.temperature)), 'pressure': quantity_to_string( pint_quantity_to_openmm(self.thermodynamic_state.pressure)), 'minimize': True, 'number_of_equilibration_iterations': self.number_of_equilibration_iterations, 'default_number_of_iterations': self.number_of_iterations, 'default_nsteps_per_iteration': self.steps_per_iteration, 'checkpoint_interval': self.checkpoint_interval, 'default_timestep': quantity_to_string(pint_quantity_to_openmm(self.timestep)), 'annihilate_electrostatics': True, 'annihilate_sterics': False, 'platform': platform_name }
def test_nested_input(): dummy_schema = WorkflowSchema() dict_protocol = DummyInputOutputProtocol('dict_protocol') dict_protocol.input_value = {'a': ThermodynamicState(temperature=1*unit.kelvin)} dummy_schema.protocols[dict_protocol.id] = dict_protocol.schema quantity_protocol = DummyInputOutputProtocol('quantity_protocol') quantity_protocol.input_value = ProtocolPath('output_value[a].temperature', dict_protocol.id) dummy_schema.protocols[quantity_protocol.id] = quantity_protocol.schema dummy_schema.validate_interfaces() dummy_property = create_dummy_property(Density) dummy_workflow = Workflow(dummy_property, {}) dummy_workflow.schema = dummy_schema with tempfile.TemporaryDirectory() as temporary_directory: workflow_graph = WorkflowGraph(temporary_directory) workflow_graph.add_workflow(dummy_workflow) dask_local_backend = DaskLocalCluster(1, ComputeResources(1)) dask_local_backend.start() results_futures = workflow_graph.submit(dask_local_backend) assert len(results_futures) == 1 result = results_futures[0].result() assert isinstance(result, CalculationLayerResult)
def test_add_values_protocol(values): with tempfile.TemporaryDirectory() as temporary_directory: add_quantities = AddValues('add') add_quantities.values = values result = add_quantities.execute(temporary_directory, ComputeResources()) assert not isinstance(result, PropertyEstimatorException) assert add_quantities.result == reduce(operator.add, values)
def test_subtract_values_protocol(values): with tempfile.TemporaryDirectory() as temporary_directory: sub_quantities = SubtractValues('sub') sub_quantities.value_b = values[1] sub_quantities.value_a = values[0] result = sub_quantities.execute(temporary_directory, ComputeResources()) assert not isinstance(result, PropertyEstimatorException) assert sub_quantities.result == values[1] - values[0]
def test_simple_workflow_graph_with_groups(): dummy_schema = WorkflowSchema() dummy_protocol_a = DummyEstimatedQuantityProtocol('protocol_a') dummy_protocol_a.input_value = EstimatedQuantity(1 * unit.kelvin, 0.1 * unit.kelvin, 'dummy_source') dummy_protocol_b = DummyEstimatedQuantityProtocol('protocol_b') dummy_protocol_b.input_value = ProtocolPath('output_value', dummy_protocol_a.id) conditional_group = ConditionalGroup('conditional_group') conditional_group.add_protocols(dummy_protocol_a, dummy_protocol_b) condition = ConditionalGroup.Condition() condition.right_hand_value = 2 * unit.kelvin condition.type = ConditionalGroup.ConditionType.LessThan condition.left_hand_value = ProtocolPath('output_value.value', conditional_group.id, dummy_protocol_b.id) conditional_group.add_condition(condition) dummy_schema.protocols[conditional_group.id] = conditional_group.schema dummy_schema.final_value_source = ProtocolPath('output_value', conditional_group.id, dummy_protocol_b.id) dummy_schema.validate_interfaces() dummy_property = create_dummy_property(Density) dummy_workflow = Workflow(dummy_property, {}) dummy_workflow.schema = dummy_schema with tempfile.TemporaryDirectory() as temporary_directory: workflow_graph = WorkflowGraph(temporary_directory) workflow_graph.add_workflow(dummy_workflow) dask_local_backend = DaskLocalClusterBackend(1, ComputeResources(1)) dask_local_backend.start() results_futures = workflow_graph.submit(dask_local_backend) assert len(results_futures) == 1 result = results_futures[0].result() assert isinstance(result, CalculationLayerResult) assert result.calculated_property.value == 1 * unit.kelvin
def test_multiply_values_protocol(value, multiplier): with tempfile.TemporaryDirectory() as temporary_directory: multiply_quantities = MultiplyValue('multiply') multiply_quantities.value = value multiply_quantities.multiplier = multiplier result = multiply_quantities.execute(temporary_directory, ComputeResources()) assert not isinstance(result, PropertyEstimatorException) assert multiply_quantities.result == value * multiplier
def test_divide_values_protocol(value, divisor): with tempfile.TemporaryDirectory() as temporary_directory: divide_quantities = DivideValue('divide') divide_quantities.value = value divide_quantities.divisor = divisor result = divide_quantities.execute(temporary_directory, ComputeResources()) assert not isinstance(result, PropertyEstimatorException) assert divide_quantities.result == value / divisor
def test_extract_average_statistic(): statistics_path = get_data_filename('test/statistics/stats_pandas.csv') with tempfile.TemporaryDirectory() as temporary_directory: extract_protocol = ExtractAverageStatistic('extract_protocol') extract_protocol.statistics_path = statistics_path extract_protocol.statistics_type = ObservableType.PotentialEnergy result = extract_protocol.execute(temporary_directory, ComputeResources()) assert not isinstance(result, PropertyEstimatorException)
def build_solvated_system(): """An example of how to build a solvated system using the built in utilities and protocol classes. """ # Define the system that you wish to create coordinates for. mixed_system = Mixture() # Here we simply define a 1:1 mix of water and octanol. mixed_system.add_component(smiles='O', mole_fraction=0.5) mixed_system.add_component(smiles='CCCCCCCCO', mole_fraction=0.5) # Add any 'impurities' such as single solute molecules. # In this case we add a molecule of paracetamol. mixed_system.add_component(smiles='CC(=O)NC1=CC=C(C=C1)O', mole_fraction=0.0, impurity=True) # Create an object which under the hood calls the packmol utility # in a friendlier way: print('Building the coordinates (this may take a while...)') build_coordinates = BuildCoordinatesPackmol('') # Set the maximum number of molecules in the system. build_coordinates.max_molecules = 1500 # and the target density (the default 1.0 g/ml is normally fine) build_coordinates.mass_density = 1.0 * unit.grams / unit.milliliters # and finally the system which coordinates should be generated for. build_coordinates.substance = mixed_system # Build the coordinates, creating a file called output.pdb build_coordinates.execute('', None) # Assign some smirnoff force field parameters to the # coordinates print('Assigning some parameters.') assign_force_field_parameters = BuildSmirnoffSystem('') assign_force_field_parameters.force_field_path = get_data_filename('forcefield/smirnoff99Frosst.offxml') assign_force_field_parameters.coordinate_file_path = 'output.pdb' assign_force_field_parameters.substance = mixed_system assign_force_field_parameters.execute('', None) # Do a simple energy minimisation print('Performing energy minimisation.') energy_minimisation = RunEnergyMinimisation('') energy_minimisation.input_coordinate_file = 'output.pdb' energy_minimisation.system_path = assign_force_field_parameters.system_path energy_minimisation.execute('', ComputeResources())
def test_run_energy_minimisation(): with tempfile.TemporaryDirectory() as directory: coordinate_path, system_path = _setup_dummy_system(directory) energy_minimisation = RunEnergyMinimisation('energy_minimisation') energy_minimisation.input_coordinate_file = coordinate_path energy_minimisation.system_path = system_path result = energy_minimisation.execute(directory, ComputeResources()) assert not isinstance(result, PropertyEstimatorException) assert path.isfile(energy_minimisation.output_coordinate_file)
def test_concatenate_statistics(): statistics_path = get_data_filename('test/statistics/stats_pandas.csv') original_array = StatisticsArray.from_pandas_csv(statistics_path) with tempfile.TemporaryDirectory() as temporary_directory: concatenate_protocol = ConcatenateStatistics('concatenate_protocol') concatenate_protocol.input_statistics_paths = [statistics_path, statistics_path] result = concatenate_protocol.execute(temporary_directory, ComputeResources()) assert not isinstance(result, PropertyEstimatorException) final_array = StatisticsArray.from_pandas_csv(concatenate_protocol.output_statistics_path) assert len(final_array) == len(original_array) * 2
def test_weight_by_mole_fraction_protocol(component_smiles, value): full_substance = Substance.from_components('C', 'CC', 'CCC') component = Substance.from_components(component_smiles) mole_fraction = next(iter(full_substance.get_amounts(component_smiles))).value with tempfile.TemporaryDirectory() as temporary_directory: weight_protocol = WeightByMoleFraction('weight') weight_protocol.value = value weight_protocol.full_substance = full_substance weight_protocol.component = component result = weight_protocol.execute(temporary_directory, ComputeResources()) assert not isinstance(result, PropertyEstimatorException) assert weight_protocol.weighted_value == value * mole_fraction
def test_concatenate_trajectories(): import mdtraj coordinate_path = get_data_filename('test/trajectories/water.pdb') trajectory_path = get_data_filename('test/trajectories/water.dcd') original_trajectory = mdtraj.load(trajectory_path, top=coordinate_path) with tempfile.TemporaryDirectory() as temporary_directory: concatenate_protocol = ConcatenateTrajectories('concatenate_protocol') concatenate_protocol.input_coordinate_paths = [coordinate_path, coordinate_path] concatenate_protocol.input_trajectory_paths = [trajectory_path, trajectory_path] result = concatenate_protocol.execute(temporary_directory, ComputeResources()) assert not isinstance(result, PropertyEstimatorException) final_trajectory = mdtraj.load(concatenate_protocol.output_trajectory_path, top=coordinate_path) assert len(final_trajectory) == len(original_trajectory) * 2
def test_calculate_reduced_potential_openmm(): substance = Substance.from_components('O') thermodynamic_state = ThermodynamicState(298 * unit.kelvin, 1.0 * unit.atmosphere) with tempfile.TemporaryDirectory() as directory: force_field_path = path.join(directory, 'ff.json') with open(force_field_path, 'w') as file: file.write(build_tip3p_smirnoff_force_field().json()) build_coordinates = BuildCoordinatesPackmol('build_coordinates') build_coordinates.max_molecules = 10 build_coordinates.mass_density = 0.05 * unit.grams / unit.milliliters build_coordinates.substance = substance build_coordinates.execute(directory, None) assign_parameters = BuildSmirnoffSystem(f'assign_parameters') assign_parameters.force_field_path = force_field_path assign_parameters.coordinate_file_path = build_coordinates.coordinate_file_path assign_parameters.substance = substance assign_parameters.execute(directory, None) reduced_potentials = CalculateReducedPotentialOpenMM(f'reduced_potentials') reduced_potentials.substance = substance reduced_potentials.thermodynamic_state = thermodynamic_state reduced_potentials.reference_force_field_paths = [force_field_path] reduced_potentials.system_path = assign_parameters.system_path reduced_potentials.trajectory_file_path = get_data_filename('test/trajectories/water.dcd') reduced_potentials.coordinate_file_path = get_data_filename('test/trajectories/water.pdb') reduced_potentials.kinetic_energies_path = get_data_filename('test/statistics/stats_pandas.csv') reduced_potentials.high_precision = False result = reduced_potentials.execute(directory, ComputeResources()) assert not isinstance(result, PropertyEstimatorException) assert path.isfile(reduced_potentials.statistics_file_path) final_array = StatisticsArray.from_pandas_csv(reduced_potentials.statistics_file_path) assert ObservableType.ReducedPotential in final_array
def test_extract_uncorrelated_statistics_data(): statistics_path = get_data_filename('test/statistics/stats_pandas.csv') original_array = StatisticsArray.from_pandas_csv(statistics_path) with tempfile.TemporaryDirectory() as temporary_directory: extract_protocol = ExtractUncorrelatedStatisticsData( 'extract_protocol') extract_protocol.input_statistics_path = statistics_path extract_protocol.equilibration_index = 2 extract_protocol.statistical_inefficiency = 2.0 result = extract_protocol.execute(temporary_directory, ComputeResources()) assert not isinstance(result, PropertyEstimatorException) final_array = StatisticsArray.from_pandas_csv( extract_protocol.output_statistics_path) assert len(final_array) == (len(original_array) - 2) / 2 assert extract_protocol.number_of_uncorrelated_samples == ( len(original_array) - 2) / 2
def test_run_openmm_simulation(): thermodynamic_state = ThermodynamicState(298 * unit.kelvin, 1.0 * unit.atmosphere) with tempfile.TemporaryDirectory() as directory: coordinate_path, system_path = _setup_dummy_system(directory) npt_equilibration = RunOpenMMSimulation('npt_equilibration') npt_equilibration.steps_per_iteration = 2 npt_equilibration.output_frequency = 1 npt_equilibration.thermodynamic_state = thermodynamic_state npt_equilibration.input_coordinate_file = coordinate_path npt_equilibration.system_path = system_path result = npt_equilibration.execute(directory, ComputeResources()) assert not isinstance(result, PropertyEstimatorException) assert path.isfile(npt_equilibration.output_coordinate_file) assert path.isfile(npt_equilibration.trajectory_file_path) assert path.isfile(npt_equilibration.statistics_file_path)
def test_simple_workflow_graph(): dummy_schema = WorkflowSchema() dummy_protocol_a = DummyInputOutputProtocol('protocol_a') dummy_protocol_a.input_value = EstimatedQuantity(1 * unit.kelvin, 0.1 * unit.kelvin, 'dummy_source') dummy_schema.protocols[dummy_protocol_a.id] = dummy_protocol_a.schema dummy_protocol_b = DummyInputOutputProtocol('protocol_b') dummy_protocol_b.input_value = ProtocolPath('output_value', dummy_protocol_a.id) dummy_schema.protocols[dummy_protocol_b.id] = dummy_protocol_b.schema dummy_schema.final_value_source = ProtocolPath('output_value', dummy_protocol_b.id) dummy_schema.validate_interfaces() dummy_property = create_dummy_property(Density) dummy_workflow = Workflow(dummy_property, {}) dummy_workflow.schema = dummy_schema with tempfile.TemporaryDirectory() as temporary_directory: workflow_graph = WorkflowGraph(temporary_directory) workflow_graph.add_workflow(dummy_workflow) dask_local_backend = DaskLocalCluster(1, ComputeResources(1)) dask_local_backend.start() results_futures = workflow_graph.submit(dask_local_backend) assert len(results_futures) == 1 result = results_futures[0].result() assert isinstance(result, CalculationLayerResult) assert result.calculated_property.value == 1 * unit.kelvin
def test_gradient_reduced_potentials(use_subset): substance = Substance.from_components('O') thermodynamic_state = ThermodynamicState(298 * unit.kelvin, 1.0 * unit.atmosphere) with tempfile.TemporaryDirectory() as directory: force_field_path = path.join(directory, 'ff.json') with open(force_field_path, 'w') as file: file.write(build_tip3p_smirnoff_force_field().json()) reduced_potentials = GradientReducedPotentials(f'reduced_potentials') reduced_potentials.substance = substance reduced_potentials.thermodynamic_state = thermodynamic_state reduced_potentials.reference_force_field_paths = [force_field_path] reduced_potentials.reference_statistics_path = get_data_filename( 'test/statistics/stats_pandas.csv') reduced_potentials.force_field_path = force_field_path reduced_potentials.trajectory_file_path = get_data_filename( 'test/trajectories/water.dcd') reduced_potentials.coordinate_file_path = get_data_filename( 'test/trajectories/water.pdb') reduced_potentials.use_subset_of_force_field = use_subset reduced_potentials.enable_pbc = True reduced_potentials.parameter_key = ParameterGradientKey( 'vdW', '[#1]-[#8X2H2+0:1]-[#1]', 'epsilon') result = reduced_potentials.execute(directory, ComputeResources()) assert not isinstance(result, PropertyEstimatorException) assert path.isfile(reduced_potentials.forward_potentials_path) assert path.isfile(reduced_potentials.reverse_potentials_path) for reference_path in reduced_potentials.reference_force_field_paths: assert path.isfile(reference_path)
def generate_trajectories(): """Generates trajectories to subsample. """ setup_timestamp_logging() logger = logging.getLogger() substance = Substance.from_components('C(C(C(C(C(F)(F)Br)(F)F)(F)F)(F)F)(C(C(C(F)(F)F)(F)F)(F)F)(F)F') logger.info('Building system.') build_system = BuildSmirnoffSystem('build_system') build_system.coordinate_file_path = 'coords.pdb' build_system.substance = substance build_system.force_field_path = 'smirnoff99Frosst-1.1.0.offxml' build_system.execute('', None) logger.info('System built.') production_simulation = RunOpenMMSimulation(f'production_simulation') production_simulation.steps_per_iteration = 500 production_simulation.output_frequency = 1 production_simulation.timestep = 2.0 * unit.femtosecond production_simulation.thermodynamic_state = ThermodynamicState(temperature=298.15*unit.kelvin, pressure=1.0*unit.atmosphere) production_simulation.input_coordinate_file = 'coords.pdb' production_simulation.system_path = 'system.xml' compute_resources = ComputeResources(number_of_threads=4) logger.info(f'Simulation started.') production_simulation_schema = production_simulation.schema production_simulation.execute('', compute_resources) production_simulation.schema = production_simulation_schema logger.info(f'Simulation finished.')
def test_estimate_request(): """Test sending an estimator request to a server.""" from openforcefield.typing.engines import smirnoff with tempfile.TemporaryDirectory() as temporary_directory: storage_directory = path.join(temporary_directory, 'storage') working_directory = path.join(temporary_directory, 'working') dummy_property = create_dummy_property(Density) dummy_data_set = PhysicalPropertyDataSet() dummy_data_set.properties[dummy_property.substance.identifier] = [ dummy_property ] force_field = smirnoff.ForceField( get_data_filename('forcefield/smirnoff99Frosst.offxml')) calculation_backend = DaskLocalClusterBackend(1, ComputeResources()) storage_backend = LocalFileStorage(storage_directory) PropertyEstimatorServer(calculation_backend, storage_backend, working_directory=working_directory) property_estimator = PropertyEstimatorClient() options = PropertyEstimatorOptions( allowed_calculation_layers=[TestCalculationLayer]) request = property_estimator.request_estimate(dummy_data_set, force_field, options) result = request.results(synchronous=True, polling_interval=0) assert not isinstance(result, PropertyEstimatorException)
def test_build_docked_coordinates_protocol(): """Tests docking a methanol molecule into alpha-Cyclodextrin.""" ligand_substance = Substance() ligand_substance.add_component( Substance.Component('CO', role=Substance.ComponentRole.Ligand), Substance.ExactAmount(1)) # TODO: This test could likely be made substantially faster # by storing the binary prepared receptor. Would this # be in breach of any oe license terms? with tempfile.TemporaryDirectory() as temporary_directory: build_docked_coordinates = BuildDockedCoordinates('build_methanol') build_docked_coordinates.ligand_substance = ligand_substance build_docked_coordinates.number_of_ligand_conformers = 5 build_docked_coordinates.receptor_coordinate_file = get_data_filename( 'test/molecules/acd.mol2') build_docked_coordinates.execute(temporary_directory, ComputeResources()) docked_pdb = PDBFile( build_docked_coordinates.docked_complex_coordinate_path) assert docked_pdb.topology.getNumResidues() == 2
def test_ligand_receptor_yank_protocol(): full_substance = Substance() full_substance.add_component( Substance.Component(smiles='c1ccccc1', role=Substance.ComponentRole.Receptor), Substance.ExactAmount(1)) full_substance.add_component( Substance.Component(smiles='C', role=Substance.ComponentRole.Ligand), Substance.ExactAmount(1)) full_substance.add_component( Substance.Component(smiles='O', role=Substance.ComponentRole.Solvent), Substance.MoleFraction(1.0)) solute_substance = Substance() solute_substance.add_component( Substance.Component(smiles='C', role=Substance.ComponentRole.Ligand), Substance.ExactAmount(1)) solute_substance.add_component( Substance.Component(smiles='O', role=Substance.ComponentRole.Solvent), Substance.MoleFraction(1.0)) thermodynamic_state = ThermodynamicState(temperature=298.15 * unit.kelvin, pressure=1.0 * unit.atmosphere) with tempfile.TemporaryDirectory() as directory: with temporarily_change_directory(directory): force_field_path = 'ff.json' with open(force_field_path, 'w') as file: file.write(build_tip3p_smirnoff_force_field().json()) complex_coordinate_path, complex_system_path = _setup_dummy_system( 'full', full_substance, 3, force_field_path) ligand_coordinate_path, ligand_system_path = _setup_dummy_system( 'ligand', solute_substance, 2, force_field_path) run_yank = LigandReceptorYankProtocol('yank') run_yank.substance = full_substance run_yank.thermodynamic_state = thermodynamic_state run_yank.number_of_iterations = 1 run_yank.steps_per_iteration = 1 run_yank.checkpoint_interval = 1 run_yank.verbose = True run_yank.setup_only = True run_yank.ligand_residue_name = 'TMP' run_yank.receptor_residue_name = 'TMP' run_yank.solvated_ligand_coordinates = ligand_coordinate_path run_yank.solvated_ligand_system = ligand_system_path run_yank.solvated_complex_coordinates = complex_coordinate_path run_yank.solvated_complex_system = complex_system_path run_yank.force_field_path = force_field_path result = run_yank.execute('', ComputeResources()) assert not isinstance(result, PropertyEstimatorException)