Beispiel #1
0
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
Beispiel #2
0
def test_thermoml_mole_constraints():
    """A collection of tests to ensure that the Mole fraction constraint is
    implemented correctly alongside solvent constraints."""

    # Mole fraction
    data_set = ThermoMLDataSet.from_file(get_data_filename('test/properties/mole.xml'))

    assert data_set is not None
    assert len(data_set.properties) > 0

    # Mole fraction + Solvent: Mass fraction
    data_set = ThermoMLDataSet.from_file(get_data_filename('test/properties/mole_mass.xml'))

    assert data_set is not None
    assert len(data_set.properties) > 0

    # Mole fraction + Solvent: Mole fraction
    data_set = ThermoMLDataSet.from_file(get_data_filename('test/properties/mole_mole.xml'))

    assert data_set is not None
    assert len(data_set.properties) > 0

    # Mole fraction + Solvent: Molality
    data_set = ThermoMLDataSet.from_file(get_data_filename('test/properties/mole_molality.xml'))

    assert data_set is not None
    assert len(data_set.properties) > 0
def test_density_dielectric_merging():

    substance = Mixture()
    substance.add_component('C', 1.0)

    density = Density(thermodynamic_state=ThermodynamicState(
        temperature=298 * unit.kelvin, pressure=1 * unit.atmosphere),
                      phase=PropertyPhase.Liquid,
                      substance=substance,
                      value=10 * unit.gram / unit.mole,
                      uncertainty=1 * unit.gram / unit.mole)

    dielectric = DielectricConstant(thermodynamic_state=ThermodynamicState(
        temperature=298 * unit.kelvin, pressure=1 * unit.atmosphere),
                                    phase=PropertyPhase.Liquid,
                                    substance=substance,
                                    value=10 * unit.gram / unit.mole,
                                    uncertainty=1 * unit.gram / unit.mole)

    density_schema = density.get_default_workflow_schema(
        'SimulationLayer', PropertyWorkflowOptions())
    dielectric_schema = dielectric.get_default_workflow_schema(
        'SimulationLayer', PropertyWorkflowOptions())

    density_metadata = Workflow.generate_default_metadata(
        density, get_data_filename('forcefield/smirnoff99Frosst.offxml'),
        PropertyEstimatorOptions())

    dielectric_metadata = Workflow.generate_default_metadata(
        density, get_data_filename('forcefield/smirnoff99Frosst.offxml'),
        PropertyEstimatorOptions())

    density_workflow = Workflow(density, density_metadata)
    density_workflow.schema = density_schema

    dielectric_workflow = Workflow(dielectric, dielectric_metadata)
    dielectric_workflow.schema = dielectric_schema

    workflow_graph = WorkflowGraph('')

    workflow_graph.add_workflow(density_workflow)
    workflow_graph.add_workflow(dielectric_workflow)

    merge_order_a = graph.topological_sort(density_workflow.dependants_graph)
    merge_order_b = graph.topological_sort(
        dielectric_workflow.dependants_graph)

    for protocol_id_A, protocol_id_B in zip(merge_order_a, merge_order_b):

        if protocol_id_A.find('extract_traj') < 0 and protocol_id_A.find(
                'extract_stats') < 0:

            assert density_workflow.protocols[protocol_id_A].schema.json() == \
                   dielectric_workflow.protocols[protocol_id_B].schema.json()

        else:

            assert density_workflow.protocols[protocol_id_A].schema.json() != \
                   dielectric_workflow.protocols[protocol_id_B].schema.json()
def test_from_files():

    data_set = ThermoMLDataSet.from_file(get_data_filename('properties/j.jct.2004.09.014.xml'),
                                         get_data_filename('properties/j.jct.2004.09.022.xml'),
                                         get_data_filename('properties/j.jct.2007.09.004.xml'))
    assert data_set is not None

    assert len(data_set.properties) > 0

    data_set = ThermoMLDataSet.from_file('properties/j.jct.2004.09.014.xmld')
    assert data_set is None
Beispiel #5
0
def test_thermoml_from_files():
    """A test to ensure that ThermoML archive files can be loaded from local sources."""

    data_set = ThermoMLDataSet.from_file(get_data_filename('properties/single_density.xml'),
                                         get_data_filename('properties/single_dielectric.xml'),
                                         get_data_filename('properties/single_enthalpy_mixing.xml'))

    assert data_set is not None
    assert len(data_set.properties) == 3

    data_set = ThermoMLDataSet.from_file('dummy_filename')
    assert data_set is None
def compute_estimate_async():
    """Submit calculations to a running server instance"""
    from openforcefield.typing.engines import smirnoff

    setup_timestamp_logging()

    # Load in the data set of interest.
    data_set = ThermoMLDataSet.from_file(get_data_filename('properties/single_dielectric.xml'))
    # Load in the force field to use.
    force_field = smirnoff.ForceField(get_data_filename('forcefield/smirnoff99Frosst.offxml'))

    # new_property_0 = copy.deepcopy(data_set.properties['COCCO{1.0}'][0])
    # new_property_0.thermodynamic_state.temperature -= 2.0 * unit.kelvin
    # new_property_0.id = str(uuid4())
    #
    # data_set.properties['COCCO{1.0}'].append(new_property_0)
    #
    # new_property_1 = copy.deepcopy(data_set.properties['COCCO{1.0}'][0])
    # new_property_1.thermodynamic_state.temperature += 2.0 * unit.kelvin
    # new_property_1.id = str(uuid4())
    #
    # data_set.properties['COCCO{1.0}'].append(new_property_1)

    # Modify the submission options
    submission_options = PropertyEstimatorOptions()

    workflow_options = PropertyWorkflowOptions(PropertyWorkflowOptions.ConvergenceMode.RelativeUncertainty,
                                               relative_uncertainty_fraction=100000)

    submission_options.workflow_options = {
        'Density': workflow_options,
        'Dielectric': workflow_options,
        'EnthalpyOfMixing': workflow_options
    }
    # submission_options.allowed_calculation_layers = ['SimulationLayer']
    submission_options.allowed_calculation_layers = ['ReweightingLayer']

    # Create the client object.
    property_estimator = client.PropertyEstimatorClient()
    # Submit the request to a running server.
    request = property_estimator.request_estimate(data_set, force_field, submission_options)

    logging.info('Request info: {}'.format(str(request)))

    # Wait for the results.
    result = request.results(synchronous=True)

    logging.info('The server has returned a response: {}'.format(result.json()))
def test_statistics_object():

    statistics_object = StatisticsArray.from_openmm_csv(
        get_data_filename('test/statistics/stats_openmm.csv'),
        1 * unit.atmosphere)

    statistics_object.to_pandas_csv('stats_pandas.csv')

    statistics_object = StatisticsArray.from_pandas_csv('stats_pandas.csv')
    assert statistics_object is not None

    subsampled_array = StatisticsArray.from_existing(statistics_object,
                                                     [1, 2, 3])
    assert subsampled_array is not None and len(subsampled_array) == 3

    if os.path.isfile('stats_pandas.csv'):
        os.unlink('stats_pandas.csv')

    reduced_potential = np.array([0.1] * (len(statistics_object) - 1))

    with pytest.raises(ValueError):
        statistics_object[ObservableType.ReducedPotential] = reduced_potential

    reduced_potential = np.array([0.1] * len(statistics_object))

    with pytest.raises(ValueError):
        statistics_object[ObservableType.ReducedPotential] = reduced_potential

    statistics_object[
        ObservableType.
        ReducedPotential] = reduced_potential * unit.dimensionless

    assert ObservableType.ReducedPotential in statistics_object
def compute_estimate_sync():
    """Submit calculations to a running server instance"""
    from openforcefield.typing.engines import smirnoff

    setup_timestamp_logging()

    # Load in the data set of interest.
    data_set = ThermoMLDataSet.from_file(get_data_filename('properties/single_density.xml'))
    # Load in the force field to use.
    force_field = smirnoff.ForceField(get_data_filename('forcefield/smirnoff99Frosst.offxml'))

    # Create the client object.
    property_estimator = client.PropertyEstimatorClient()
    # Submit the request to a running server, and wait for the results.
    result = property_estimator.request_estimate(data_set, force_field)

    logging.info('The server has returned a response: {}'.format(result))
Beispiel #9
0
def test_serialization():
    """A test to ensure that data sets are JSON serializable."""

    data_set = ThermoMLDataSet.from_file(get_data_filename('properties/single_density.xml'))
    data_set_json = data_set.json()

    parsed_data_set = ThermoMLDataSet.parse_json(data_set_json)
    assert data_set.number_of_properties == parsed_data_set.number_of_properties

    parsed_data_set_json = parsed_data_set.json()
    assert parsed_data_set_json == data_set_json
Beispiel #10
0
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
Beispiel #11
0
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
Beispiel #12
0
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 test_force_field_serialization():

    from openforcefield.typing.engines import smirnoff

    force_field = smirnoff.ForceField(get_data_filename('forcefield/smirnoff99Frosst.offxml'))

    serialized_force_field = serialize_force_field(force_field)
    deserialized_force_field = deserialize_force_field(serialized_force_field)

    original_generators = force_field.getGenerators()
    deserialized_generators = deserialized_force_field.getGenerators()

    assert len(original_generators) == len(deserialized_generators)
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_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)
Beispiel #16
0
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_statistics_object():

    statistics_object = StatisticsArray.from_openmm_csv(
        get_data_filename('properties/stats_openmm.csv'), 1 * unit.atmosphere)
    statistics_object.save_as_pandas_csv('stats_pandas.csv')

    statistics_object = StatisticsArray.from_pandas_csv('stats_pandas.csv')
    subsampled_array = StatisticsArray.from_statistics_array(
        statistics_object, [1, 2, 3])

    if os.path.isfile('stats_pandas.csv'):
        os.unlink('stats_pandas.csv')

    assert statistics_object is not None
    assert subsampled_array is not None and len(subsampled_array) == 3
Beispiel #18
0
def create_dummy_metadata(dummy_property, calculation_layer):

    global_metadata = Workflow.generate_default_metadata(
        dummy_property,
        get_data_filename('forcefield/smirnoff99Frosst.offxml'),
        PropertyEstimatorOptions())

    if calculation_layer == 'ReweightingLayer':

        global_metadata['full_system_data'] = [('data_path_0', 'ff_path_0'),
                                               ('data_path_1', 'ff_path_0'),
                                               ('data_path_2', 'ff_path_1')]

        global_metadata['component_data'] = [[('data_path_3', 'ff_path_3'),
                                              ('data_path_4', 'ff_path_4')],
                                             [('data_path_5', 'ff_path_5'),
                                              ('data_path_6', 'ff_path_6')]]

    return global_metadata
def parse_all_jct_files():

    logging.basicConfig(filename='data_sets.log', filemode='w', level=logging.INFO)

    data_path = get_data_filename('properties/JCT')

    thermoml_files = []

    for file_path in listdir(data_path):

        full_path = join(data_path, file_path)

        if not isfile(full_path):
            continue

        thermoml_files.append(full_path)

    data_set = ThermoMLDataSet.from_file(*thermoml_files)

    from propertyestimator.properties.density import Density
    from propertyestimator.properties.dielectric import DielectricConstant
    from propertyestimator.properties.enthalpy import EnthalpyOfMixing

    properties_by_type = {Density.__name__: [], DielectricConstant.__name__: [],
                          EnthalpyOfMixing.__name__: []}

    for substance_key in data_set.properties:

        for data_property in data_set.properties[substance_key]:

            if type(data_property).__name__ not in properties_by_type:
                continue

            properties_by_type[type(data_property).__name__].append(data_property.source.reference)

    for type_key in properties_by_type:

        with open('{}.dat'.format(type_key), 'w') as file:

            for doi in properties_by_type[type_key]:
                file.write('{}\n'.format(doi))
Beispiel #20
0
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
Beispiel #21
0
def build_tip3p_smirnoff_force_field():
    """Combines the smirnoff99Frosst and tip3p offxml files
    into a single one which can be consumed by the property
    estimator.

    Returns
    -------
    SmirnoffForceFieldSource
        The force field containing both smirnoff99Frosst-1.1.0
        and TIP3P parameters
    """
    from openforcefield.typing.engines.smirnoff import ForceField

    smirnoff_force_field_path = 'smirnoff99Frosst-1.1.0.offxml'
    tip3p_force_field_path = get_data_filename('forcefield/tip3p.offxml')

    smirnoff_force_field_with_tip3p = ForceField(smirnoff_force_field_path,
                                                 tip3p_force_field_path)

    return SmirnoffForceFieldSource.from_object(
        smirnoff_force_field_with_tip3p)
Beispiel #22
0
def test_local_force_field_storage():
    """A simple test to that force fields can be stored and
    retrieved using the local storage backend."""

    from openforcefield.typing.engines import smirnoff
    force_field = smirnoff.ForceField(
        get_data_filename('forcefield/smirnoff99Frosst.offxml'))

    with tempfile.TemporaryDirectory() as temporary_directory:

        local_storage = LocalFileStorage(temporary_directory)
        local_storage.store_force_field('tmp_id', force_field)

        retrieved_force_field = local_storage.retrieve_force_field('tmp_id')

        serialized_force_field = serialize_force_field(force_field)
        serialized_retrieved_force_field = serialize_force_field(
            retrieved_force_field)

        assert json.dumps(serialized_force_field) == json.dumps(
            serialized_retrieved_force_field)

        local_storage_new = LocalFileStorage(temporary_directory)
        assert local_storage_new.has_force_field(force_field)
Beispiel #23
0
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_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_base_simulation_protocols():
    """Tests that the commonly chain build coordinates, assigned topology,
    energy minimise and perform simulation are able to work together without
    raising an exception."""

    mixed_system = Mixture()
    mixed_system.add_component(smiles='O', mole_fraction=1.0)

    thermodynamic_state = ThermodynamicState(298 * unit.kelvin,
                                             1 * unit.atmosphere)

    with tempfile.TemporaryDirectory() as temporary_directory:

        build_coordinates = BuildCoordinatesPackmol('')

        # Set the maximum number of molecules in the system.
        build_coordinates.max_molecules = 10
        # and the target density (the default 1.0 g/ml is normally fine)
        build_coordinates.mass_density = 0.05 * 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
        result = build_coordinates.execute(temporary_directory, None)
        assert not isinstance(result, PropertyEstimatorException)

        # 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 = path.join(
            temporary_directory, 'output.pdb')
        assign_force_field_parameters.substance = mixed_system

        result = assign_force_field_parameters.execute(temporary_directory,
                                                       None)
        assert not isinstance(result, PropertyEstimatorException)

        # Do a simple energy minimisation
        print('Performing energy minimisation.')
        energy_minimisation = RunEnergyMinimisation('')

        energy_minimisation.input_coordinate_file = path.join(
            temporary_directory, 'output.pdb')
        energy_minimisation.system_path = assign_force_field_parameters.system_path

        result = energy_minimisation.execute(temporary_directory,
                                             ComputeResources())
        assert not isinstance(result, PropertyEstimatorException)

        npt_equilibration = RunOpenMMSimulation('npt_equilibration')

        npt_equilibration.ensemble = Ensemble.NPT

        npt_equilibration.steps = 20  # Debug settings.
        npt_equilibration.output_frequency = 2  # Debug settings.

        npt_equilibration.thermodynamic_state = thermodynamic_state

        npt_equilibration.input_coordinate_file = path.join(
            temporary_directory, 'minimised.pdb')
        npt_equilibration.system_path = assign_force_field_parameters.system_path

        result = npt_equilibration.execute(temporary_directory,
                                           ComputeResources())
        assert not isinstance(result, PropertyEstimatorException)

        extract_density = ExtractAverageStatistic('extract_density')

        extract_density.statistics_type = ObservableType.Density
        extract_density.statistics_path = path.join(temporary_directory,
                                                    'statistics.csv')

        result = extract_density.execute(temporary_directory,
                                         ComputeResources())
        assert not isinstance(result, PropertyEstimatorException)

        extract_dielectric = ExtractAverageDielectric('extract_dielectric')

        extract_dielectric.thermodynamic_state = thermodynamic_state

        extract_dielectric.input_coordinate_file = path.join(
            temporary_directory, 'input.pdb')
        extract_dielectric.trajectory_path = path.join(temporary_directory,
                                                       'trajectory.dcd')
        extract_dielectric.system_path = assign_force_field_parameters.system_path

        result = extract_dielectric.execute(temporary_directory,
                                            ComputeResources())
        assert not isinstance(result, PropertyEstimatorException)

        extract_uncorrelated_trajectory = ExtractUncorrelatedTrajectoryData(
            'extract_traj')

        extract_uncorrelated_trajectory.statistical_inefficiency = extract_density.statistical_inefficiency
        extract_uncorrelated_trajectory.equilibration_index = extract_density.equilibration_index
        extract_uncorrelated_trajectory.input_coordinate_file = path.join(
            temporary_directory, 'input.pdb')
        extract_uncorrelated_trajectory.input_trajectory_path = path.join(
            temporary_directory, 'trajectory.dcd')

        result = extract_uncorrelated_trajectory.execute(
            temporary_directory, ComputeResources())
        assert not isinstance(result, PropertyEstimatorException)

        extract_uncorrelated_statistics = ExtractUncorrelatedStatisticsData(
            'extract_stats')

        extract_uncorrelated_statistics.statistical_inefficiency = extract_density.statistical_inefficiency
        extract_uncorrelated_statistics.equilibration_index = extract_density.equilibration_index
        extract_uncorrelated_statistics.input_statistics_path = path.join(
            temporary_directory, 'statistics.csv')

        result = extract_uncorrelated_statistics.execute(
            temporary_directory, ComputeResources())
        assert not isinstance(result, PropertyEstimatorException)
def test_nested_replicators():

    dummy_schema = WorkflowSchema()

    dummy_protocol = DummyReplicableProtocol('dummy_$(rep_a)_$(rep_b)')

    dummy_protocol.replicated_value_a = ReplicatorValue('rep_a')
    dummy_protocol.replicated_value_b = ReplicatorValue('rep_b')

    dummy_schema.protocols[dummy_protocol.id] = dummy_protocol.schema

    dummy_schema.final_value_source = ProtocolPath('final_value',
                                                   dummy_protocol.id)

    replicator_a = ProtocolReplicator(replicator_id='rep_a')

    replicator_a.template_values = ['a', 'b']
    replicator_a.protocols_to_replicate = [ProtocolPath('', dummy_protocol.id)]

    replicator_b = ProtocolReplicator(replicator_id='rep_b')

    replicator_b.template_values = [1, 2]
    replicator_b.protocols_to_replicate = [ProtocolPath('', dummy_protocol.id)]

    dummy_schema.replicators = [replicator_a, replicator_b]

    dummy_schema.validate_interfaces()

    dummy_property = create_dummy_property(Density)

    dummy_metadata = Workflow.generate_default_metadata(
        dummy_property,
        get_data_filename('forcefield/smirnoff99Frosst.offxml'),
        PropertyEstimatorOptions())

    dummy_workflow = Workflow(dummy_property, dummy_metadata)
    dummy_workflow.schema = dummy_schema

    assert len(dummy_workflow.protocols) == 4

    assert dummy_workflow.protocols[dummy_workflow.uuid +
                                    '|dummy_0_0'].replicated_value_a == 'a'
    assert dummy_workflow.protocols[dummy_workflow.uuid +
                                    '|dummy_0_1'].replicated_value_a == 'a'

    assert dummy_workflow.protocols[dummy_workflow.uuid +
                                    '|dummy_1_0'].replicated_value_a == 'b'
    assert dummy_workflow.protocols[dummy_workflow.uuid +
                                    '|dummy_1_1'].replicated_value_a == 'b'

    assert dummy_workflow.protocols[dummy_workflow.uuid +
                                    '|dummy_0_0'].replicated_value_b == 1
    assert dummy_workflow.protocols[dummy_workflow.uuid +
                                    '|dummy_0_1'].replicated_value_b == 2

    assert dummy_workflow.protocols[dummy_workflow.uuid +
                                    '|dummy_1_0'].replicated_value_b == 1
    assert dummy_workflow.protocols[dummy_workflow.uuid +
                                    '|dummy_1_1'].replicated_value_b == 2

    print(dummy_workflow.schema)