Пример #1
0
 def setup(self):
     self.tmpdir = tempfile.mkdtemp()
     self.storage_filename = os.path.join(self.tmpdir, "test.nc")
     self.storage = paths.Storage(self.storage_filename, mode='w')
     snap = make_1d_traj([1])[0]
     self.storage.save(snap)
     self.cv_x = paths.CoordinateFunctionCV("x", lambda s: s.xyz[0][0])
     self.cv_y = paths.CoordinateFunctionCV("y", lambda s: s.xyz[0][1])
     self.storage.save([self.cv_x, self.cv_y])
Пример #2
0
    def test_safemode(self):
        fname = data_filename("cv_storage_safemode_test.nc")
        if os.path.isfile(fname):
            os.remove(fname)

        cv = paths.CoordinateFunctionCV('cv', lambda x: x)

        traj = paths.Trajectory(list(self.traj))
        template = traj[0]

        storage_w = paths.Storage(fname, "w")
        storage_w.snapshots.save(template)
        storage_w.cvs.save(cv)
        storage_w.close()

        storage_r = paths.Storage(fname, 'r')
        # default safemode = False
        assert (storage_r.simplifier.safemode is False)
        cv_r = storage_r.cvs[0]
        assert (cv_r == cv)
        assert (cv.cv_callable is not None)
        storage_r.close()

        storage_r = paths.Storage(fname, 'r')
        storage_r.simplifier.safemode = True
        cv_r = storage_r.cvs[0]
        assert (cv_r == cv)
        assert (cv_r.cv_callable is None)
        storage_r.close()
Пример #3
0
    def setup(self):
        # set up the trajectory that we'll annotate in the tests
        self.traj = make_1d_traj(
            [-1, 1, 4, 3, 6, 11, 22, 33, 23, 101, 205, 35, 45])
        # set up some states to test later
        # this system is designed under the assumption that the "states" are
        # defined by how many digits are in the x-coordinate (and I'll
        # intentionally fail to identify some of them)
        self.cv = paths.CoordinateFunctionCV("x", lambda s: s.xyz[0][0])
        self.state_1 = paths.CVDefinedVolume(self.cv, 0, 9)
        self.state_2 = paths.CVDefinedVolume(self.cv, 10, 99)
        self.state_3 = paths.CVDefinedVolume(self.cv, 100, 999)
        # create the annotations
        self.annotation_1 = Annotation(state="1-digit", begin=1, end=4)
        self.annotation_2 = Annotation(state="2-digit", begin=6, end=8)
        self.annotation_3 = Annotation(state="3-digit", begin=10, end=10)
        self.annotation_4 = Annotation(state="2-digit", begin=11, end=12)

        self.states = {
            "1-digit": self.state_1,
            "2-digit": self.state_2,
            "3-digit": self.state_3
        }

        self.annotated = AnnotatedTrajectory(self.traj)
        self.annotations = [
            self.annotation_1, self.annotation_2, self.annotation_3,
            self.annotation_4
        ]
Пример #4
0
 def setup(self):
     cv = paths.CoordinateFunctionCV('x', lambda x: x.xyz[0][0])
     vol_A = paths.CVDefinedVolume(cv, float("-inf"), 0.0)
     vol_B = paths.CVDefinedVolume(cv, 1.0, float("inf"))
     ensembles = [
         paths.LengthEnsemble(1).named("len1"),
         paths.LengthEnsemble(3).named("len3"),
         paths.SequentialEnsemble([
             paths.LengthEnsemble(1) & paths.AllInXEnsemble(vol_A),
             paths.AllOutXEnsemble(vol_A | vol_B),
             paths.LengthEnsemble(1) & paths.AllInXEnsemble(vol_A)
         ]).named('return'),
         paths.SequentialEnsemble([
             paths.LengthEnsemble(1) & paths.AllInXEnsemble(vol_A),
             paths.AllOutXEnsemble(vol_A | vol_B),
             paths.LengthEnsemble(1) & paths.AllInXEnsemble(vol_B)
         ]).named('transition'),
     ]
     self.ensembles = {ens.name: ens for ens in ensembles}
     self.traj_vals = [-0.1, 1.1, 0.5, -0.2, 0.1, -0.3, 0.4, 1.4, -1.0]
     self.trajectory = make_1d_traj(self.traj_vals)
     self.engine = CalvinistDynamics(self.traj_vals)
     self.satisfied_when_traj_len = {
         "len1": 1,
         "len3": 3,
         "return": 6,
         "transition": 8,
     }
     self.conditions = EnsembleSatisfiedContinueConditions(ensembles)
Пример #5
0
    def test_analysis(self):
        # check wrong analyze_single_step() argument
        empty_dict = self.analysis.analyze_single_step(3.1415)
        assert empty_dict == {}

        # dictionary with three entries returned
        assert len(self.analysis) == 3

        # run C_AB() in advance, this triggers calculate_averages()
        cab = self.analysis.C_AB()
        assert len(cab) == self.l + 1
        assert cab.sum() > 0

        # get total and per-snapshot results
        M, Ns, I_Bt, Ns_Bt, hAhB_Bt, sres = self.analysis.calculate_averages()

        # check total number of generated subtrajectories
        assert M == 3 * (self.l + 1)
        # since we did not use a bias Ns_Bt should be 1.0
        np.testing.assert_almost_equal(Ns_Bt, 1.0)
        # now do the same tests on a per-snapshot basis
        snaps = sres.keys()
        for snap in snaps:
            assert sres[snap]["M"] == self.l + 1
            np.testing.assert_almost_equal(sres[snap]["Ns_Bt"], 1.0)
            # check whether time correlation is only filled for case (2), for
            # case (1) and (3) the array should be empty.
            if snap.xyz[0][0] == 0.0:
                np.testing.assert_almost_equal(
                    np.array(sres[snap]["hAhB_Bt"]).sum(), 0)
            elif snap.xyz[0][0] == 0.1:
                assert np.array(sres[snap]["hAhB_Bt"]).sum() > 0
            elif snap.xyz[0][0] == -0.2:
                np.testing.assert_almost_equal(
                    np.array(sres[snap]["hAhB_Bt"]).sum(), 0)

        # run C_AB() afterwards, this triggers another if clause
        cab = self.analysis.C_AB()
        assert len(cab) == self.l + 1
        assert cab.sum() > 0

        # try another analysis with different arguments for complete coverage
        def dummy_bias(x):
            return 1.0

        cv_b = paths.CoordinateFunctionCV(name="cv_b", f=dummy_bias)
        rc = paths.FunctionCV("Id", lambda snap: snap.coordinates[0][0])
        self.state_S2 = paths.CVDefinedVolume(rc, -0.55, 0.05)
        self.analysis2 = SShootingAnalysis(
            steps=self.storage.steps,
            states=[self.state_A, self.state_B, self.state_S2],
            bias=cv_b)

        with pytest.raises(NotImplementedError):
            self.analysis.committor()
        with pytest.raises(NotImplementedError):
            self.analysis.committor_histogram()
 def setup(self):
     xval = paths.CoordinateFunctionCV(name="xA", f=lambda s: s.xyz[0][0])
     self.stateA = paths.CVDefinedVolume(xval, -1.0, -0.5).named("A")
     self.stateB = paths.CVDefinedVolume(xval, 0.5, float("inf")).named("B")
     self.ifacesA = paths.VolumeInterfaceSet(xval, -1.0,
                                             [-0.5, -0.4, -0.3, -0.2])
     self.ifacesB = paths.VolumeInterfaceSet(xval, [0.5, 0.4, 0.3, 0.2],
                                             1.0)
     self.tcp_A = paths.numerics.LookupFunction(
         ordinate=[-0.5, -0.4, -0.3, -0.2, -0.1],
         abscissa=[1.0, 0.5, 0.25, 0.125, 0.0625])
     self.tcp_B = paths.numerics.LookupFunction(
         ordinate=[0.5, 0.4, 0.3, 0.2, 0.1],
         abscissa=[1.0, 0.2, 0.04, 0.008, 0.0016])
def make_mstis_network():
    opA = paths.CoordinateFunctionCV(name="opA", f=circle, center=[-0.5, -0.5])
    opB = paths.CoordinateFunctionCV(name="opB", f=circle, center=[0.5, -0.5])
    opC = paths.CoordinateFunctionCV(name="opC", f=circle, center=[0.0, 0.4])
    stateA = paths.CVDefinedVolume(opA, 0.0, 0.2).named("A")
    stateB = paths.CVDefinedVolume(opB, 0.0, 0.2).named("B")
    stateC = paths.CVDefinedVolume(opC, 0.0, 0.2).named("C")

    interfacesA = paths.VolumeInterfaceSet(opA, 0.0, [0.2, 0.3, 0.4])
    interfacesB = paths.VolumeInterfaceSet(opB, 0.0, [0.2, 0.3, 0.4])
    interfacesC = paths.VolumeInterfaceSet(opC, 0.0, [0.2, 0.3, 0.4])

    ms_outers = paths.MSOuterTISInterface.from_lambdas(
        {ifaces: 0.5
         for ifaces in [interfacesA, interfacesB, interfacesC]}
    )

    mstis = paths.MSTISNetwork(
        [(stateA, interfacesA),
         (stateB, interfacesB),
         (stateC, interfacesC)],
        ms_outers=ms_outers
    )
    return mstis
    def __init__(self, steps, states, bias=None):
        # SShootingAnalysis is inherited from ShootinPointAnalysis but
        # overrides the __init__ function. Thus, the call to the
        # SnapshotByCoordinateDict __init__ function has to be repeated
        # here (ugly)!
        SnapshotByCoordinateDict.__init__(self)
        #super(ShootingPointAnalysis, self).__init__()

        # Definition of states A, B and S.
        self.state_A = states[0]
        self.state_B = states[1]
        self.state_S = states[2]

        # If called without bias create a dummy one.
        if bias is None:

            def dummy_bias(x):
                return 1.0

            cv_b = paths.CoordinateFunctionCV(name="cv_b", f=dummy_bias)
            self.bias = cv_b
        else:
            self.bias = bias

        # Initialize inconsistency counter.
        self.count_inconsistent_S = 0

        # Set one-direction shot length l.
        self.l = steps[0].simulation.trajectory_length

        # Prepare array for time correlation function.
        self._CABxhA_hS = None

        # Analyze each trajectory.
        if steps is not None:
            self.analyze(steps)

        # Issue a warning if some trajectories were harvested with a different
        # settings for the S region.
        if self.count_inconsistent_S > 0:
            logging.warning("Some trajectories (" +
                            str(self.count_inconsistent_S) +
                            " cases) were harvested with a different S region "
                            "definition than the one provided for the "
                            "analysis. Trajectories with starting snapshots "
                            "out of the given S region were ignored.")
    def test_iter_generate_clear_cache(self):
        # when running with iter_generate, only the most recently generated
        # snapshot should contain data -- the others should have their cache
        # cleared
        if not has_gmx:
            pytest.skip("Gromacs (gmx) not found. Skipping test.")
        if not HAS_MDTRAJ:
            pytest.skip("MDTraj not found. Skipping test.")

        def continue_condition(trajectory, trusted=False):
            if len(trajectory) == 5:
                return False
            for snap in trajectory[1:-1]:
                # the initial snapshot does not get cleared
                # the final snapshot has not yet been cleared
                assert snap._xyz is None
                assert snap._velocities is None
                assert snap._box_vectors is None
            # the final snapshot should have been loaded, and not yet
            # cleared
            assert trajectory[-1]._xyz is not None
            assert trajectory[-1]._velocities is not None
            assert trajectory[-1]._box_vectors is not None
            return True

        cv_x0 = paths.CoordinateFunctionCV('x0', lambda snap: snap.xyz[0][0])
        in_all_space = paths.AllInXEnsemble(
            paths.CVDefinedVolume(cv_x0, float("-inf"), float("inf")))

        traj_0 = self.engine.trajectory_filename(0)
        snap = self.engine.read_frame_from_file(traj_0, 0)
        self.engine.filename_setter.reset(0)
        traj = self.engine.generate(
            snap, running=[in_all_space.can_append, continue_condition])
        assert len(traj) == 5
        ttraj = md.load(self.engine.trajectory_filename(1),
                        top=self.engine.gro)
        assert len(ttraj) < 100
Пример #10
0
def tps_network():
    cv = paths.CoordinateFunctionCV('x', lambda s: s.xyz[0][0])
    state_A = paths.CVDefinedVolume(cv, float("-inf"), 0).named("A")
    state_B = paths.CVDefinedVolume(cv, 0, float("inf")).named("B")
    network = paths.TPSNetwork(state_A, state_B).named('tps-network')
    return network
Пример #11
0
    def test_storage_sync(self):
        import os

        # test all combinations of (1) with and without UUIDs,
        # (2) using partial yes; all of these must work

        allow_incomplete = True

        # print
        # print

        for use_uuid in [True]:

            # print '=========================================================='
            # print 'UUID', use_uuid
            # print '=========================================================='

            fname = data_filename("cv_storage_test.nc")
            if os.path.isfile(fname):
                os.remove(fname)

            traj = paths.Trajectory(list(self.traj_simple))
            template = traj[0]

            storage_w = paths.Storage(fname, "w")
            storage_w.snapshots.save(template)

            cv1 = paths.CoordinateFunctionCV(
                'f1', lambda snapshot: snapshot.coordinates[0]).with_diskcache(
                    allow_incomplete=allow_incomplete)

            # let's mess up the order in which we save and
            # include reversed ones as well
            assert (len(storage_w.snapshots) == 2)
            storage_w.trajectories.save(traj[6:])
            assert (len(storage_w.snapshots) == 10)
            storage_w.snapshots.save(traj[1].reversed)
            assert (len(storage_w.snapshots) == 12)

            storage_w.save(cv1)

            store = storage_w.cvs.cache_store(cv1)
            assert (len(store.vars['value']) == 0)
            storage_w.snapshots.sync_cv(cv1)

            # nothing added to the cache so no changes
            assert (len(store.vars['value']) == 1)

            # fill the cache
            _ = cv1(traj)

            storage_w.snapshots.sync_cv(cv1)

            # should match the number of stored snapshots
            assert (len(store.vars['value']) == 6)

            # save the rest
            storage_w.trajectories.save(traj.reversed)
            assert (len(storage_w.snapshots) == 20)

            # should still be unchanged
            assert (len(store.vars['value']) == 6)

            # this should store the remaining CV values

            storage_w.snapshots.sync_cv(cv1)
            assert (len(store.vars['value']) == 10)

            # check if the values match
            for idx, value in zip(store.variables['index'][:],
                                  store.vars['value']):
                snap = storage_w.snapshots[storage_w.snapshots.vars['uuid']
                                           [idx]]

                assert_close_unit(cv1(snap), value)

            storage_w.close()

            if os.path.isfile(fname):
                os.remove(fname)
Пример #12
0
    def test_storage_sync_and_complete(self):
        import os

        # test all combinations of (1) with and without UUIDs,
        # (2) using partial yes, no all of these must work

        allow_incomplete = True

        # print
        # print

        for use_uuid in [True]:

            # print '=========================================================='
            # print 'UUID', use_uuid
            # print '=========================================================='

            fname = data_filename("cv_storage_test.nc")
            if os.path.isfile(fname):
                os.remove(fname)

            traj = paths.Trajectory(list(self.traj_simple))
            template = traj[0]

            storage_w = paths.Storage(fname, "w")
            storage_w.snapshots.save(template)

            cv1 = paths.CoordinateFunctionCV(
                'f1', lambda snapshot: snapshot.coordinates[0]).with_diskcache(
                    allow_incomplete=allow_incomplete)

            # let's mess up the order in which we save and include
            # reversed ones as well
            assert (len(storage_w.snapshots) == 2)
            storage_w.trajectories.save(traj[3:])
            assert (len(storage_w.snapshots) == 16)
            storage_w.snapshots.save(traj[1].reversed)
            assert (len(storage_w.snapshots) == 18)
            storage_w.trajectories.save(traj.reversed)
            assert (len(storage_w.snapshots) == 20)

            storage_w.save(cv1)

            store = storage_w.cvs.cache_store(cv1)
            assert (len(store.vars['value']) == 0)

            storage_w.snapshots.complete_cv(cv1)
            assert (len(store.vars['value']) == 10)

            # check if stored values match computed ones
            for idx, value in zip(store.variables['index'][:],
                                  store.vars['value']):
                snap = storage_w.snapshots[storage_w.snapshots.vars['uuid']
                                           [idx]]

                # print(snap, snap.__uuid__, value)
                assert_close_unit(cv1(snap), value)

            storage_w.close()

            if os.path.isfile(fname):
                os.remove(fname)
Пример #13
0
    def test_storage_cv_function(self):
        import os

        # test all combinations of (1) with and without UUIDs,
        # (2) using partial yes, no all of these must work
        for allow_incomplete in (True, False):

            # print '=========================================================='
            # print 'PARTIAL', allow_incomplete
            # print '=========================================================='

            fname = data_filename("cv_storage_test.nc")
            if os.path.isfile(fname):
                os.remove(fname)

            traj = paths.Trajectory(list(self.traj_simple))
            template = traj[0]

            storage_w = paths.Storage(fname, "w")
            storage_w.snapshots.save(template)

            cv1 = paths.CoordinateFunctionCV(
                'f1', lambda x: x.coordinates[0]).with_diskcache(
                    allow_incomplete=allow_incomplete)

            storage_w.save(cv1)

            # let's mess up the order in which we save and
            # include reversed ones as well
            assert (len(storage_w.snapshots) == 2)
            storage_w.trajectories.save(traj[3:])
            assert (len(storage_w.snapshots) == 16)
            storage_w.snapshots.save(traj[1].reversed)
            assert (len(storage_w.snapshots) == 18)
            storage_w.trajectories.save(traj.reversed)
            assert (len(storage_w.snapshots) == 20)

            # this should be ignored for all is saved already
            storage_w.trajectories.save(traj)
            storage_w.close()

            storage_r = paths.AnalysisStorage(fname)
            rcv1 = storage_r.cvs['f1']

            assert (rcv1._store_dict)

            cv_cache = rcv1._store_dict.value_store

            assert (cv_cache.allow_incomplete == allow_incomplete)

            for idx, snap in enumerate(storage_r.trajectories[1]):
                # print idx, snap
                # if hasattr(snap, '_idx'):
                #     print 'Proxy IDX', snap._idx

                # print 'ITEMS', storage_r.snapshots.index.items()
                # print snap, type(snap), snap.__dict__

                # print snap.__uuid__
                # print snap.reversed.__uuid__
                # print snap.create_reversed().__uuid__
                #
                # print 'POS', cv_cache.object_pos(snap),
                # print 'POS', storage_r.snapshots.pos(snap),
                # print 'POS', storage_r.snapshots.index[snap]
                #
                # print 'POS', cv_cache.object_pos(snap.reversed),
                # print 'POS', storage_r.snapshots.pos(snap.reversed),
                # print 'POS', storage_r.snapshots.index[snap.reversed]

                # if len(cv_cache.cache._chunkdict) > 0:
                #
                #     if allow_incomplete:
                #         print cv_cache.index
                #         print cv_cache.vars['value'][:]
                #
                #     for n, v in enumerate(cv_cache.cache._chunkdict[0]):
                #         print n, v
                #
                # print cv1(snap)
                # print cv1(snap.reversed)
                # print cv_cache[snap]
                #
                # print cv_cache[snap.reversed]

                if not allow_incomplete or cv_cache[snap] is not None:
                    assert_close_unit(cv_cache[snap], cv1(snap))
                    assert_close_unit(cv_cache[snap.reversed],
                                      cv1(snap.reversed))

            storage_r.close()

            if os.path.isfile(fname):
                os.remove(fname)
def cv_and_states():
    cv = paths.CoordinateFunctionCV("x", lambda s: s.xyz[0][0])
    state_A = paths.CVDefinedVolume(cv, float("-inf"), 0).named("A")
    state_B = paths.CVDefinedVolume(cv, 1, float("inf")).named("B")
    return cv, state_A, state_B
Пример #15
0
    f=md.compute_contacts,
    topology=template.topology,
    scheme='closest-heavy',
    ignore_nonprotein=False,
    periodic=False).with_diskcache()


def distance(snapshot, receptor_atoms, ligand_atoms):
    import numpy as np
    receptor_com = snapshot.xyz[receptor_atoms, :].mean(0)
    ligand_com = snapshot.xyz[ligand_atoms, :].mean(0)
    return np.sqrt(((receptor_com - ligand_com)**2).sum())


cv = paths.CoordinateFunctionCV(name="distance",
                                f=distance,
                                receptor_atoms=receptor_atoms,
                                ligand_atoms=ligand_atoms).with_diskcache()
storage.save([cv])

# State definitions
states = ['bound  ', 'unbound']

max_bound = 0.05  # nanometers, maximum bound state separation distance
min_unbound = 0.90  # nanometers, minimum unbound state separation distance

print('Creating interfaces...')
ninterfaces = 100
bound = paths.CVDefinedVolume(cv, lambda_min=0.0, lambda_max=max_bound)
unbound = paths.CVDefinedVolume(cv,
                                lambda_min=min_unbound,
                                lambda_max=float("inf"))