def setup(self):
        if os.path.isfile(data_filename(self.fname)):
            os.remove(data_filename(self.fname))

        setup_storage = paths.Storage(data_filename("tps_setup.nc"), "r")
        network = setup_storage.networks[0]
        tps_ensemble = network.sampling_ensembles[0]
        initial_sample = paths.Sample(
            replica=0, 
            trajectory=common.initial_tps_sample.trajectory,
            ensemble=tps_ensemble
        )
        template = initial_sample.trajectory[0]
        setup_storage.close()

        shoot = oink.ShootingStub(tps_ensemble)
        self.storage = paths.Storage(data_filename(self.fname), "w",
                                     template)

        self.pseudosim = oink.ShootingPseudoSimulator(
            storage=self.storage,
            initial_conditions=paths.SampleSet([initial_sample]),
            mover=shoot,
            network=network
        )

        nojoin = oink.ShootingStub(tps_ensemble, pre_joined=False)
        self.nojoin_pseudosim = oink.ShootingPseudoSimulator(
            storage=self.storage,
            initial_conditions=paths.SampleSet([initial_sample]),
            mover=nojoin,
            network=network
        )
 def setup(self):
     super(TestINIT_CONDS, self).setup()
     self.traj = make_1d_traj([-0.1, 1.0, 4.4, 7.7, 10.01])
     ensemble = self.scheme.network.sampling_ensembles[0]
     self.sample_set = paths.SampleSet(
         [paths.Sample(trajectory=self.traj, replica=0, ensemble=ensemble)])
     self.other_traj = make_1d_traj([-1.0, 1.0, 100.0])
     self.other_sample_set = paths.SampleSet([
         paths.Sample(trajectory=self.other_traj,
                      replica=0,
                      ensemble=ensemble)
     ])
    def test_nan_rejected(self):
        stateA = paths.EmptyVolume()  # will run indefinitely
        stateB = paths.EmptyVolume()
        tps = A2BEnsemble(stateA, stateB)
        self.engine.n_frames_max = 10

        init_traj = paths.Trajectory([nan_causing_template] * 5)
        init_samp = paths.SampleSet([paths.Sample(
            trajectory=init_traj,
            replica=0,
            ensemble=tps
        )])

        mover = paths.BackwardShootMover(
            ensemble=tps,
            selector=paths.UniformSelector(),
            engine=self.engine
        )
        change = mover.move(init_samp)

        assert (isinstance(change, paths.RejectedNaNSampleMoveChange))
        assert_equal(change.details.rejection_reason, 'nan')
        # since we shoot, we start with a shorter trajectory
        assert(len(change.samples[0].trajectory) < len(init_traj))

        newsamp = init_samp.apply_samples(change)
        assert_equal(len(newsamp), 1)

        # make sure there is no change!
        assert_equal(init_samp[0].trajectory, init_traj)
    def test_in_shooting_move(self):
        for testfile in glob.glob("test*out") + glob.glob("test*inp"):
            os.remove(testfile)
        ens10 = paths.LengthEnsemble(10)
        init_traj = self.fast_engine.generate(self.template,
                                              [ens10.can_append])
        assert_equal(ens10(init_traj), True)
        init_conds = paths.SampleSet(
            [paths.Sample(replica=0, ensemble=ens10, trajectory=init_traj)])
        shooter = paths.OneWayShootingMover(ensemble=ens10,
                                            selector=paths.UniformSelector(),
                                            engine=self.fast_engine)
        prev_sample_set = init_conds
        default_traj = [[[0.0]], [[1.0]], [[2.0]], [[3.0]], [[4.0]], [[5.0]],
                        [[6.0]], [[7.0]], [[8.0]], [[9.0]]]
        assert_items_equal(init_conds[0].trajectory.xyz, default_traj)
        for step in range(10):
            assert_equal(len(prev_sample_set), 1)
            change = shooter.move(prev_sample_set)
            new_sample_set = prev_sample_set.apply_samples(change.results)
            assert_items_equal(new_sample_set[0].trajectory.xyz, default_traj)
            prev_traj = prev_sample_set[0].trajectory
            new_traj = new_sample_set[0].trajectory
            shared = prev_traj.shared_configurations(new_traj)
            assert_true(0 < len(list(shared)) < len(new_traj))
            prev_sample_set = new_sample_set

        for testfile in glob.glob("test*out") + glob.glob("test*inp"):
            os.remove(testfile)
 def _make_active(self, seq):
     traj = make_1d_traj(seq)
     sample = paths.Sample(replica=0,
                           trajectory=traj,
                           ensemble=self.ensemble)
     sample_set = paths.SampleSet(sample)
     return sample_set
    def collapsed_samples(self):
        """
        Return a collapsed set of samples with non used samples removed

        This is the minimum required set of samples to keep the `MoveChange`
        correct and allow to target sampleset to be correctly created.
        These are the samples used by `.closed`

        Examples
        --------
        Assume that you run 3 shooting moves for replica #1. Then only the
        last of the three really matters for the target sample_set since #1
        will be replaced by #2 which will be replaced by #3. So this function
        will return only the last sample.

        """
        if self._collapsed is None:
            s = paths.SampleSet([]).apply_samples(self.results)

            # keep order just for being thorough
            self._collapsed = [
                samp for samp in self.results
                if samp in s
            ]

        return self._collapsed
Example #7
0
    def __init__(
            self,
            storage,
            move_scheme=None,
            sample_set=None,
            initialize=True
    ):
        """
        Parameters
        ----------
        storage : :class:`openpathsampling.storage.Storage`
            the storage where all results should be stored in
        move_scheme : :class:`openpathsampling.MoveScheme`
            the move scheme used for the pathsampling cycle
        sample_set : :class:`openpathsampling.SampleSet`
            the initial SampleSet for the Simulator
        initialize : bool
            if `False` the new PathSimulator will continue at the step and
            not create a new SampleSet object to cut the connection to previous
            steps
        """
        super(PathSampling, self).__init__(storage)
        self.move_scheme = move_scheme
        if move_scheme is not None:
            self.root_mover = move_scheme.move_decision_tree()
            self._mover = paths.PathSimulatorMover(self.root_mover, self)
        else:
            self.root_mover = None
            self._mover = None

        initialization_logging(init_log, self,
                               ['move_scheme', 'sample_set'])
        self.live_visualizer = None
        self.status_update_frequency = 1

        if initialize:
            samples = []
            if sample_set is not None:
                for sample in sample_set:
                    samples.append(sample.copy_reset())

            self.sample_set = paths.SampleSet(samples)

            mcstep = MCStep(
                simulation=self,
                mccycle=self.step,
                active=self.sample_set,
                change=paths.AcceptedSampleMoveChange(self.sample_set.samples)
            )

            self._current_step = mcstep

        else:
            self.sample_set = sample_set
            self._current_step = None

        self.root = self.sample_set

        if self.storage is not None:
            self.save_current_step()
    def test_max_length_rejected(self):
        stateA = paths.EmptyVolume()  # will run indefinitely
        stateB = paths.EmptyVolume()
        tps = A2BEnsemble(stateA, stateB)
        self.engine.options['n_frames_max'] = 10
        self.engine.on_max_length = 'fail'

        init_traj = paths.Trajectory([template] * 5)
        init_samp = paths.SampleSet([paths.Sample(
            trajectory=init_traj,
            replica=0,
            ensemble=tps
        )])

        mover = paths.BackwardShootMover(
            ensemble=tps,
            selector=paths.UniformSelector(),
            engine=self.engine
        )
        change = mover.move(init_samp)

        assert(isinstance(change, paths.RejectedMaxLengthSampleMoveChange))
        assert_equal(change.details.rejection_reason, 'max_length')
        assert_equal(
            len(change.samples[0].trajectory), self.engine.n_frames_max)

        newsamp = init_samp.apply_samples(change)
        assert_equal(len(newsamp), 1)

        # make sure there is no change!
        assert_equal(init_samp[0].trajectory, init_traj)
Example #9
0
    def run(self, n_per_snapshot, as_chain=False):
        """Run the simulation.

        Parameters
        ----------
        n_per_snapshot : int
            number of shots per snapshot
        as_chain : bool
            if as_chain is False (default), then the input to the modifier
            is always the original snapshot. If as_chain is True, then the
            input to the modifier is the previous (modified) snapshot.
            Useful for modifications that can't cover the whole range from a
            given snapshot.
        """
        self.step = 0
        snap_num = 0
        for snapshot in self.initial_snapshots:
            start_snap = snapshot
            # do what we need to get the snapshot set up
            for step in range(n_per_snapshot):
                paths.tools.refresh_output(
                    "Working on snapshot %d / %d; shot %d / %d" % (
                        snap_num+1, len(self.initial_snapshots),
                        step+1, n_per_snapshot
                    ),
                    output_stream=self.output_stream,
                    refresh=self.allow_refresh
                )

                if as_chain:
                    start_snap = self.randomizer(start_snap)
                else:
                    start_snap = self.randomizer(snapshot)

                sample_set = paths.SampleSet([
                    paths.Sample(replica=0,
                                 trajectory=paths.Trajectory([start_snap]),
                                 ensemble=self.starting_ensemble)
                ])
                sample_set.sanity_check()
                new_pmc = self.mover.move(sample_set)
                samples = new_pmc.results
                new_sample_set = sample_set.apply_samples(samples)

                mcstep = MCStep(
                    simulation=self,
                    mccycle=self.step,
                    previous=sample_set,
                    active=new_sample_set,
                    change=new_pmc
                )

                if self.storage is not None:
                    self.storage.steps.save(mcstep)
                    if self.step % self.save_frequency == 0:
                        self.sync_storage()

                self.step += 1
            snap_num += 1
def _make_null_mover_step(mccycle, path_sim_mover, null_mover):
    empty_sample_set = paths.SampleSet([])
    change = paths.PathSimulatorMoveChange(
        mover=path_sim_mover, subchange=null_mover.move(empty_sample_set))
    step = paths.MCStep(mccycle=mccycle,
                        active=empty_sample_set,
                        change=change)
    return step
 def setup(self):
     self.mytraj = make_1d_traj(coordinates=[-0.5, 0.1, 0.2, 0.3, 0.5],
                                velocities=[1.0, 1.0, 1.0, 1.0, 1.0])
     self.dyn = CalvinistDynamics(
         [-0.5, -0.4, -0.3, -0.2, -0.1, 0.1, 0.2, 0.3, 0.4, 0.5])
     self.dyn.initialized = True
     self.initial_guess = 3
     self.ens = paths.LengthEnsemble(5)
     self.ges = paths.SampleSet(
         paths.Sample(replica=0, trajectory=self.mytraj, ensemble=self.ens))
Example #12
0
 def test_integration(self):
     simulation = paths.PathSampling(storage=None,
                                     sample_set=paths.SampleSet([]),
                                     move_scheme=MagicMock())
     simulation.live_visualizer = MagicMock()
     simulation.run_hooks('before_simulation', sim=simulation)  # prep
     simulation.run_hooks('after_step',
                          sim=simulation,
                          step_number=1,
                          step_info=(1, 100),
                          state=simulation.sample_set,
                          results=MagicMock(),
                          hook_state={})
     simulation.live_visualizer.draw_ipynb.assert_called_once()
Example #13
0
    def __init__(
            self,
            storage,
            engine=None,
            movers=None,
            trajectory=None,
            ensembles=None
    ):
        """
        Parameters
        ----------
        storage : openpathsampling.storage.Storage
            the storage all results should be stored in
        engine : openpathsampling.DynamicsEngine
            the dynamics engine to be used
        movers : list of openpathsampling.PathMover
            list of shooters to be used in the BootstrapPromotionMove
        trajectory : openpathsampling.Trajectory
            an initial trajectory to be started from
        ensembles : nested list of openpathsampling.Ensemble
            the ensembles this move should act on
        """
        # TODO: Change input from trajectory to sample
        super(Bootstrapping, self).__init__(storage)
        self.engine = engine
        paths.EngineMover.default_engine = engine  # set the default
        self.ensembles = ensembles
        self.trajectory = trajectory

        sample = paths.Sample(
            replica=0,
            trajectory=trajectory,
            ensemble=self.ensembles[0]
        )

        self.sample_set = paths.SampleSet([sample])

        if movers is None:
            pass # TODO: implement defaults: one per ensemble, uniform sel
        else:
            self.movers = movers
        initialization_logging(init_log, self,
                               ['movers', 'ensembles'])
        init_log.info("Parameter: %s : %s", 'trajectory', str(trajectory))

        self._bootstrapmove = BootstrapPromotionMove(
            bias=None,
            shooters=self.movers,
            ensembles=self.ensembles
        )
Example #14
0
    def check_ensembles(self, ensembles):
        """
        Check for missing or extra ensembles in the sampleset

        This is primary used programmatically as a reusable function for
        several use cases where we need this information. See functions
        under "see also" for examples of such cases.

        Parameters
        ----------
        ensembles : list of :class:`Ensemble` or list of :class:`Ensemble`
            the list of ensembles to be generated. If an element is itself a
            list then one sample for one of the ensembles in that list if
            generated

        Returns
        -------
        missing : list of list of :class:`.Ensemble`
            ensembles needed by the move scheme and missing in the sample
            set, in the format used by `list_initial_ensembles`
        extra : list of :class:`.Ensemble`
            ensembles in the sampleset that are not used by the

        See Also
        --------
        MoveScheme.list_initial_ensembles
        MoveScheme.assert_initial_conditions
        MoveScheme.initial_conditions_report
        """
        samples = paths.SampleSet(self)  # to make a copy
        missing = []
        for ens_list in ensembles:
            if type(ens_list) is not list:
                ens_list = [ens_list]
            sample = None
            for ens in ens_list:
                if ens in samples.ensemble_list():
                    sample = samples[ens]
                    break
            if sample is not None:
                del samples[sample]
            else:
                missing.append(ens_list)

        # missing, extra
        return missing, samples.ensemble_list()
 def setup(self):
     # create the network
     paths.InterfaceSet._reset()
     xval = paths.FunctionCV(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")
     ifacesA = paths.VolumeInterfaceSet(xval, float(-1.0),
                                        [-0.5, -0.4, -0.3, -0.2])
     self.network = paths.MISTISNetwork([(self.stateA, ifacesA, self.stateB)
                                         ])
     transition = self.network.transitions[(self.stateA, self.stateB)]
     ensembles = transition.ensembles
     self.xval = xval
     self.ifacesA = ifacesA
     # create the biases
     bias_table = {}
     bias_table[ensembles[0]] = 1.0
     bias_table[ensembles[1]] = 0.5
     bias_table[ensembles[2]] = 0.2
     self.bias = BiasEnsembleTable.ratios_from_dictionary(bias_table)
     # samples, moves, changes
     traj = make_1d_traj(
         [-0.55, -0.45, -0.35, -0.25, -0.15, -0.26, -0.36, -0.46, -0.56])
     s0 = paths.Sample(replica=0, ensemble=ensembles[0], trajectory=traj)
     s1 = paths.Sample(replica=1, ensemble=ensembles[1], trajectory=traj)
     s2 = paths.Sample(replica=2, ensemble=ensembles[2], trajectory=traj)
     self.sample_set = paths.SampleSet([s0, s1, s2])
     self.sample_set.sanity_check()
     move_01 = paths.EnsembleHopMover(ensembles[0], ensembles[1])
     move_02 = paths.EnsembleHopMover(ensembles[0], ensembles[2])
     move_12 = paths.EnsembleHopMover(ensembles[1], ensembles[2])
     move_21 = paths.EnsembleHopMover(ensembles[2], ensembles[1])
     move_20 = paths.EnsembleHopMover(ensembles[2], ensembles[0])
     move_10 = paths.EnsembleHopMover(ensembles[1], ensembles[0])
     # NOTE: all changes here are accepted
     self.change_01 = move_01.move(self.sample_set)
     self.change_02 = move_02.move(self.sample_set)
     self.change_12 = move_12.move(self.sample_set)
     self.change_21 = move_21.move(self.sample_set)
     self.change_20 = move_20.move(self.sample_set)
     self.change_10 = move_10.move(self.sample_set)
     # convenience lists for changes going outward vs. inward
     self.out_changes = [self.change_01, self.change_02, self.change_12]
     self.in_changes = [self.change_10, self.change_20, self.change_21]
Example #16
0
    def test_missing_ctp(self):
        ensembles_AB = self.sampling_ensembles_for_transition(
            self.mistis, self.state_A, self.state_B
        )
        ensembles_BA = self.sampling_ensembles_for_transition(
            self.mistis, self.state_B, self.state_A
        )

        all_ensembles = ensembles_AB + ensembles_BA
        replicas = range(len(all_ensembles))
        set_trajectories = [self.trajs_AB[2]]*3 + [self.trajs_BA[2]]*3
        zipped = list(zip(set_trajectories, all_ensembles, replicas))
        mover_stub_mistis = MoverWithSignature(self.mistis.all_ensembles,
                                               self.mistis.all_ensembles)
        sample_sets = []
        n_steps = 3
        for step in range(n_steps):
            sample_set = paths.SampleSet([
                paths.Sample(trajectory=traj,
                             ensemble=ens,
                             replica=rep)
                for (traj, ens, rep) in zipped
            ])
            sample_set.sanity_check()
            sample_sets.append(sample_set)

        steps = self._make_fake_steps(sample_sets, mover_stub_mistis)
        for transition in self.mistis.transitions.values():
            max_lambda_calc = FullHistogramMaxLambdas(
                transition=transition,
                hist_parameters={'bin_width': 0.1, 'bin_range': (-0.1, 1.1)}
            )
            std_tp = StandardTransitionProbability(
                transition=transition,
                tcp_method=TotalCrossingProbability(max_lambda_calc),
                ctp_method=ConditionalTransitionProbability(
                    ensembles=[transition.ensembles[-1]],
                    states=[self.state_A, self.state_B]
                )
            )
            results = std_tp.calculate(steps)
            assert_almost_equal(results, 0.0)
Example #17
0
    def _make_fake_minus_steps(self, scheme, descriptions):
        network = scheme.network
        state_adjustment = {
            self.state_A: lambda x: x,
            self.state_B: lambda x: 1.0 - x
        }

        minus_ensemble_to_mover = {m.minus_ensemble: m
                                   for m in scheme.movers['minus']}

        assert_equal(set(minus_ensemble_to_mover.keys()),
                     set(network.minus_ensembles))
        steps = []
        mccycle = 0
        for minus_traj in descriptions:
            for i, minus_ensemble in enumerate(network.minus_ensembles):
                replica = -1 - i
                adjustment = state_adjustment[minus_ensemble.state_vol]
                traj = make_1d_traj([adjustment(s) for s in minus_traj])
                assert_equal(minus_ensemble(traj), True)
                samp = paths.Sample(trajectory=traj,
                                    ensemble=minus_ensemble,
                                    replica=replica)
                sample_set = paths.SampleSet([samp])
                change = paths.AcceptedSampleMoveChange(
                    samples=[samp],
                    mover=minus_ensemble_to_mover[samp.ensemble],
                    details=paths.Details()
                )
                # NOTE: this makes it so that only one ensemble is
                # represented in the same set at any time, which isn't quite
                # how it actually works. However, this is doesn't matter for
                # the current implementation
                steps.append(paths.MCStep(mccycle=mccycle,
                                          active=sample_set,
                                          change=change))

                mccycle += 1
        assert_equal(len(steps), 4)
        return steps
def _make_acceptance_mock_step(mccycle,
                               accepted,
                               path_sim_mover,
                               move_type,
                               mover_sig,
                               submover_num=None):
    root_mover = path_sim_mover.mover
    chooser_names = {m.name[:-7].lower(): m for m in root_mover.movers}
    chooser = chooser_names[move_type]
    sig_to_mover = {
        frozenset(m.ensemble_signature[0]): m
        for m in chooser.movers
    }
    # group_mover = chooser.movers[mover_num]
    group_mover = sig_to_mover[frozenset(mover_sig)]
    Change = {
        True: paths.AcceptedSampleMoveChange,
        False: paths.RejectedSampleMoveChange
    }[accepted]
    # foo here is because we need non-empty samples to show that we're
    # actually accepted or not (WHY?!?!?)
    if submover_num is not None:
        submover = group_mover.movers[submover_num]
        submover_change = Change(samples=['foo'], mover=submover)
        group_mover_change = paths.RandomChoiceMoveChange(
            subchange=submover_change, mover=group_mover)
    else:
        submover_change = None
        group_mover_change = Change(samples=['foo'], mover=group_mover)

    chooser_change = paths.RandomChoiceMoveChange(subchange=group_mover_change,
                                                  mover=chooser)
    root_mover_change = paths.RandomChoiceMoveChange(subchange=chooser_change,
                                                     mover=root_mover)
    path_sim_change = paths.PathSimulatorMoveChange(
        subchange=root_mover_change, mover=path_sim_mover)
    step = paths.MCStep(mccycle=mccycle,
                        active=paths.SampleSet([]),
                        change=path_sim_change)
    return step
Example #19
0
    def __init__(
            self,
            storage,
            engine=None,
            move_scheme=None,
            globalstate=None
    ):
        """
        Parameters
        ----------
        storage : openpathsampling.storage.Storage
            the storage where all results should be stored in
        engine : openpathsampling.DynamicsEngine
            the engine to be used with shooting moves
        move_scheme : openpathsampling.MoveScheme
            the move scheme used for the pathsampling cycle
        globalstate : openpathsampling.SampleSet
            the initial SampleSet for the Simulator
        """
        super(PathSampling, self).__init__(storage, engine)
        self.move_scheme = move_scheme
        self.root_mover = move_scheme.move_decision_tree()
#        self.move_scheme.name = "PathSamplingRoot"

        samples = []
        if globalstate is not None:
            for sample in globalstate:
                samples.append(sample.copy_reset())

        self.globalstate = paths.SampleSet(samples)
        self.root = self.globalstate

        initialization_logging(init_log, self, 
                               ['move_scheme', 'globalstate'])
        self.live_visualization = None
        self.visualize_frequency = 1
        self._mover = paths.PathSimulatorMover(self.root_mover, self)
Example #20
0
    def _make_fake_sampling_sets(self, network):
        ensembles_AB = self.sampling_ensembles_for_transition(
            network, self.state_A, self.state_B
        )
        ensembles_BA = self.sampling_ensembles_for_transition(
            network, self.state_B, self.state_A
        )

        all_ensembles = ensembles_AB + ensembles_BA
        replicas = range(len(all_ensembles))

        # This encodes how the SampleSets are at each time step. This is the
        # trajectory number (from trajs_AB/trajs_BA) for each ensemble
        # (index order of sampling_AB.ensembles + sampling_BA.ensembles)
        descriptions = [
            [2, 3, 3, 2, 3, 3],
            [1, 2, 3, 1, 2, 3],
            [0, 1, 2, 0, 1, 2],
            [0, 1, 2, 0, 1, 2]
        ]

        # here's the fancy fake data
        sample_sets = []
        for descr in descriptions:
            set_trajectories = ([self.trajs_AB[d] for d in descr[:3]]
                                + [self.trajs_BA[d] for d in descr[3:]])
            zipped = zip(set_trajectories, all_ensembles, replicas)
            sample_set = paths.SampleSet([
                paths.Sample(trajectory=traj,
                             ensemble=ens,
                             replica=rep)
                for (traj, ens, rep) in zip(set_trajectories, all_ensembles,
                                            range(len(all_ensembles)))
            ])
            sample_sets.append(sample_set)
        return sample_sets
    def __init__(self,
                 storage,
                 initial_file,
                 mover,
                 network,
                 options=None,
                 options_rejected=None):
        # TODO: mke the initial file into an initial trajectory
        if options is None:
            options = TPSConverterOptions()
        if options_rejected is None:
            options_rejected = options
        self.options = options
        self.options_rejected = options_rejected

        self.initial_file = initial_file  # needed for restore
        traj = self.load_trajectory(initial_file)
        # assume we're TPS here
        ensemble = network.sampling_ensembles[0]
        initial_trajectories = ensemble.split(traj)
        if len(initial_trajectories) == 0:  # pragma: no cover
            raise RuntimeError("Initial trajectory in " + str(initial_file) +
                               " has no subtrajectory satisfying the " +
                               "TPS ensemble.")
        elif len(initial_trajectories) > 1:  # pragma: no cover
            raise RuntimeWarning("More than one potential initial " +
                                 "subtrajectory. We use the first.")

        initial_trajectory = initial_trajectories[0]

        initial_conditions = paths.SampleSet([
            paths.Sample(replica=0,
                         trajectory=initial_trajectory,
                         ensemble=ensemble)
        ])

        self.extra_bw_frames = traj.index(initial_trajectory[0])
        final_frame_index = traj.index(initial_trajectory[-1])
        self.extra_fw_frames = len(traj) - final_frame_index - 1
        # extra -1 bc frame index counts from 0; len counts from 1

        self.summary_root_dir = None
        self.report_progress = None
        super(OneWayTPSConverter,
              self).__init__(storage=storage,
                             initial_conditions=initial_conditions,
                             mover=mover,
                             network=network)

        # initial_states = self.network.initial_states
        # final_states = self.network.final_states
        # TODO: prefer the above, but the below work until fix for network
        # storage
        initial_states = [self.network.sampling_transitions[0].stateA]
        final_states = [self.network.sampling_transitions[0].stateB]

        all_states = paths.join_volumes(initial_states + final_states)

        self.fw_ensemble = paths.SequentialEnsemble([
            paths.AllOutXEnsemble(all_states),
            paths.AllInXEnsemble(all_states) & paths.LengthEnsemble(1)
        ])
        self.bw_ensemble = paths.SequentialEnsemble([
            paths.AllInXEnsemble(all_states) & paths.LengthEnsemble(1),
            paths.AllOutXEnsemble(all_states)
        ])
        self.full_ensemble = paths.SequentialEnsemble([
            paths.AllInXEnsemble(all_states) & paths.LengthEnsemble(1),
            paths.AllOutXEnsemble(all_states),
            paths.AllInXEnsemble(all_states) & paths.LengthEnsemble(1)
        ])
        self.all_states = all_states
Example #22
0
 def set_replicas(self, samples):
     self.globalstate = paths.SampleSet(samples)
Example #23
0
    def full(self, ensembles, clear=True):

        storage = self.storage

        if clear:
            self.renderer.clear()
        level_y = dict()

        old_sset = paths.SampleSet([])

        self.t_count = 1

        self.ens_x = [None] * len(ensembles)
        self.repl_x = [None] * len(ensembles)

        for sset in storage.samplesets[0:2]:
            path = sset.movepath
            # level_y = dict()

            for level, sub in path.depth_post_order(lambda this: tuple(
                    [this, old_sset.apply_samples(this.samples)])):
                self.t_count += 1

                sub_mp, sub_set = sub

                if sub_mp.__class__ is paths.SamplePathMoveChange:
                    self.renderer.add(
                        self.renderer.block(-8.0 + level, self.t_count, 'blue'))
                    self.renderer.add(
                        self.renderer.label(
                            -8.0 + level, self.t_count, 3,
                            sub_mp.mover.__class__.__name__[:-5],
                            align='start', color='black')
                    )
                else:
                    self.renderer.add(
                        self.renderer.block(-8.0 + level, self.t_count,
                                            'green'))
                    self.renderer.add(
                        self.renderer.label(-8.0 + level, self.t_count, 3,
                                            sub_mp.__class__.__name__[:-8],
                                            align='start', color='black')
                    )

                if level + 1 in level_y \
                        and level_y[level + 1] == self.t_count - 1:
                    self.renderer.add(
                        self.renderer.v_connection(-7.0 + level, self.t_count,
                                                   self.t_count - 1, 'black')
                    )
                    del level_y[level + 1]

                if level in level_y and level_y[level]:
                    self.renderer.add(
                        self.renderer.v_connection(-8.0 + level, self.t_count,
                                                   level_y[level], 'black')
                    )

                level_y[level] = self.t_count

                self.render_ensemble_line(ensembles, sub_set, color='gray')
                self.render_replica_line(len(ensembles), sub_set, color='gray')

            self.t_count += 1

            self.render_ensemble_line(ensembles, sset)
            self.render_replica_line(len(ensembles), sset)

            self.renderer.add(self.renderer.block(-8.0, self.t_count, 'black'))
            self.renderer.add(
                self.renderer.label(-8.0, self.t_count, 3,
                                    'storage.sampleset[%d]' % sset.idx[storage.samplesets],
                                    align='start', color='black')
            )

            old_sset = sset
            self.t_count += 1

        self.renderer.shift_x = - 9.0
        self.renderer.shift_y = -0.5
        self.renderer.height = 1.0 * self.t_count + 1.0
        self.renderer.width = 1.0 * len(ensembles) + 20.5
    def initial_conditions_from_trajectories(self, trajectories,
                                             sample_set=None,
                                             strategies=None,
                                             preconditions=None,
                                             reuse_strategy='avoid-symmetric',
                                             engine=None):
        """
        Create a SampleSet with as many initial samples as possible.

        The goal of this is to give the initial SampleSet that would be
        desired. 

        Parameters
        ----------
        trajectories : list of :class:`.Trajectory` or :class:`.Trajectory`
            the input trajectories to use
        sample_set : :class:`.SampleSet`, optional
            if given, add samples to this sampleset. Default is None, which
            means that this will start a new sampleset.
        strategies : dict
            a dict that specifies the options used when ensemble functions
            are used to create a new sample.
        preconditions : list of str
            a list of possible steps to modify the initial list of trajectories.
            possible choices are

                1.  `sort-shortest` - sorting by shortest first,
                2.  `sort_median` - sorting by the middle one first and then in
                    move away from the median length
                3.  `sort-longest` - sorting by the longest first
                4.  `reverse` - reverse the order and
                5.  `mirror` which will add the reversed trajectories to the
                    list in the same order

            Default is `None` which means to do nothing.
        reuse_strategy : str
            if `avoid` then reusing the same same trajectory twice is avoided.
            `avoid-symmetric` will also remove reversed copies
            if possible. `all` will not attempt to avoid already existing ones.
            `once` will strictly not reuse a trajectory and `once-symmetric`
            will also not use reversed copies.
        engine : :class:`openpathsampling.engines.DyanmicsEngine`
            the engine used for extending moves

        Returns
        -------
        :class:`.SampleSet`
            sampleset with samples for every initial ensemble for this
            scheme that could be satisfied by the given trajectories

        See Also
        --------
        list_initial_ensembles
        check_initial_conditions
        assert_initial_conditions
        """

        if sample_set is None:
            sample_set = paths.SampleSet([])

        ensembles = self.list_initial_ensembles()

        sample_set = sample_set.generate_from_trajectories(
            ensembles,
            trajectories,
            preconditions,
            strategies,
            reuse_strategy,
            engine
        )
        refresh_output(self.initial_conditions_report(sample_set),
                       ipynb_display_only=True, print_anyway=False)
        return sample_set
Example #25
0
    def test_with_minus_move_flux(self):
        network = self.mstis
        scheme = paths.DefaultScheme(network, engine=RandomMDEngine())
        scheme.build_move_decision_tree()

        # create the minus move steps
        # `center` is the edge of the state/innermost interface
        center = {self.state_A: 0.0, self.state_B: 1.0}
        replica = {self.state_A: -1, self.state_B: -2}
        minus_ensemble_to_mover = {m.minus_ensemble: m
                                   for m in scheme.movers['minus']}
        state_to_minus_ensemble = {ens.state_vol: ens
                                   for ens in network.minus_ensembles}
        minus_changes = []
        # `delta` is the change on either side for in vs. out
        for (state, delta) in [(self.state_A, 0.1), (self.state_B, -0.1)]:
            minus_ens = state_to_minus_ensemble[state]
            minus_mover = minus_ensemble_to_mover[minus_ens]
            a_in = center[state] - delta
            a_out = center[state] + delta
            # note that these trajs are equivalent to minus move
            # descriptions in TestMinusMoveFlux
            seq_1 = [a_in] + [a_out]*2 + [a_in]*5 + [a_out]*5 + [a_in]
            seq_2 = [a_in] + [a_out]*3 + [a_in]*3 + [a_out]*3 + [a_in]

            for seq in [seq_1, seq_2]:
                traj = make_1d_traj(seq)
                assert_equal(minus_ens(traj), True)
                samp = paths.Sample(trajectory=traj,
                                    ensemble=minus_ens,
                                    replica=replica[state])
                sample_set = paths.SampleSet([samp])
                change = paths.AcceptedSampleMoveChange(
                    samples=[samp],
                    mover=minus_mover,
                    details=paths.Details()
                )
                minus_changes.append(change)

        active = self.mstis_steps[0].active
        steps = []
        cycle = -1
        for m_change in minus_changes:
            cycle += 1
            active = active.apply_samples(m_change.samples)
            step = paths.MCStep(mccycle=cycle,
                                active=active,
                                change=m_change)
            steps.append(step)
            for old_step in self.mstis_steps[1:]:
                cycle += 1
                active = active.apply_samples(old_step.change.samples)
                step = paths.MCStep(mccycle=cycle,
                                    active=active,
                                    change=old_step.change)
                steps.append(step)

        analysis = StandardTISAnalysis(
            network=self.mstis,
            scheme=scheme,
            max_lambda_calcs={t: {'bin_width': 0.1,
                                  'bin_range': (-0.1, 1.1)}
                              for t in network.sampling_transitions},
            steps=steps
        )

        # now we actually verify correctness
        avg_t_in = (5.0 + 3.0) / 2
        avg_t_out = (2.0 + 5.0 + 3.0 + 3.0) / 4
        expected_flux = 1.0 / (avg_t_in + avg_t_out)

        # NOTE: Apparently this approach screws up the TCP calculation. I
        # think this is a problem in the fake data, not the simulation.
        for flux in analysis.flux_matrix.values():
            assert_almost_equal(flux, expected_flux)

### INITIAL SNAPSHOT #######################################################
print("Getting energy-minimized initial snapshot")
engine.simulation.context.setPositions(testsystem.positions)
engine.simulation.minimizeEnergy()
initial_snapshot = engine.current_snapshot


### SETUP INITIAL CONDITIONS ###############################################
print("Setting up initial conditions")
initial_trajectory = engine.generate(initial_snapshot, ensemble.can_append)
sample = paths.Sample(replica=0,
                      ensemble=ensemble,
                      trajectory=initial_trajectory)
initial_conditions = paths.SampleSet([sample])

ref_frame = initial_trajectory.to_mdtraj()[0]
ref_frame.save("ref.pdb")

### RUN PATH SAMPLING ######################################################
storage = Storage('test_data.db', mode='w')
# add CVs
phi = MDTrajFunctionCV(md.compute_dihedrals,
                       topology=engine.topology,
                       indices=[[4, 6, 8, 14]]).named("phi")

psi = MDTrajFunctionCV(md.compute_dihedrals,
                       topology=engine.topology,
                       indices=[[6, 8, 14, 16]]).named("psi")