Esempio n. 1
0
def task_fail(walker):

    n = walker.state['num']
    if n == 1:
        raise ValueError("No soup for you!!")
    else:
        return Walker(WalkerState(**{'num' : n+1}), walker.weight)
Esempio n. 2
0
    def _runtest(self, num_walkers, num_cycles, dimension, debug_prints=False):
        print("Random walk simulation with: ")
        print("Dimension =", dimension)
        print("Probability =", self.probability)
        print("Number of Walkers", num_walkers)
        print("Number of Cycles", num_cycles)

        # set up initial state for walkers
        positions = np.zeros((1, dimension))

        init_state = WalkerState(positions=positions, time=0.0)

        # create list of init_walkers
        initial_weight = 1 / num_walkers
        init_walkers = []

        # init_walkers, n_cycles = get_final_state(path, num_walkers)
        init_walkers = [
            Walker(init_state, initial_weight) for i in range(num_walkers)
        ]

        # set up raunner for system
        runner = RandomWalkRunner(dimension=dimension,
                                  probability=self.probability)

        units = dict(UNIT_NAMES)
        # instantiate a revo unbindingboudaryconditiobs
        segment_length = 10

        # set up the reporter
        randomwalk_system_top_json = self.generate_topology()

        hdf5_reporter = WepyHDF5Reporter(self.hdf5_reporter_path,
                                         mode='w',
                                         save_fields=SAVE_FIELDS,
                                         topology=randomwalk_system_top_json,
                                         resampler=self.resampler,
                                         units=dict(UNITS),
                                         n_dims=dimension)
        # running the simulation
        sim_manager = Manager(init_walkers,
                              runner=runner,
                              resampler=self.resampler,
                              work_mapper=Mapper(),
                              reporters=[hdf5_reporter])

        # run a simulation with the manager for n_steps cycles of length 1000 each
        steps = [segment_length for i in range(num_cycles)]
        print("Start simulation")

        sim_manager.run_simulation(num_cycles,
                                   steps,
                                   debug_prints=debug_prints)

        print("Finished Simulation")
Esempio n. 3
0
    def run_segment(self, walker, segment_length):
        # documented in superclass

        # Gets the current posiotion of RandomWalk Walker
        positions = walker.state['positions']
        # Make movements for the segment_length steps
        for _ in range(segment_length):
            # calls walk function for one step movement
            new_positions = self._walk(positions)
            positions = new_positions
        # makes new state form new positions
        new_state = WalkerState(positions=new_positions, time=0.0)
        # creates new_walker from new state and current weight
        new_walker = Walker(new_state, walker.weight)
        return new_walker
Esempio n. 4
0
    def run_segment(self, walker, segment_length, **kwargs):
        """Runs a random walk simulation for the given number of steps.

        Parameters
        ----------
        walker : object implementing the Walker interface
            The walker for which dynamics will be propagated.


        segment_length : int
            The numerical value that specifies how much dynamical steps
            are to be run.

        Returns
        -------
        new_walker : object implementing the Walker interface
            Walker after dynamics was run, only the state should be modified.

        """

        # Gets the current posiotion of RandomWalk Walker
        positions = walker.state['positions']

        # Make movements for the segment_length steps
        for _ in range(segment_length):
            # calls walk function for one step movement
            new_positions = self._walk(positions)
            positions = new_positions

        # makes new state form new positions
        new_state = WalkerState(positions=new_positions, time=0.0)

        # creates new_walker from new state and current weight
        new_walker = Walker(new_state, walker.weight)

        return new_walker
Esempio n. 5
0
    def __init__(self, native_state=None,
                 cutoff_rmsd=0.2,
                 initial_states=None,
                 initial_weights=None,
                 ligand_idxs=None,
                 binding_site_idxs=None,
                 **kwargs):
        """Constructor for RebindingBC.

        Arguments
        ---------

        native_state : object implementing the State interface
            The reference bound state. Will be automatically centered.

        cutoff_rmsd : float
            The cutoff RMSD for considering a walker bound.

        initial_states : list of objects implementing the State interface
            The list of possible states that warped walkers will assume.

        initial_weights : list of float, optional
            List of normalized probabilities of the initial_states
            provided. If not given, uniform probabilities will be
            used.

        ligand_idxs : arraylike of int
            The indices of the atom positions in the state considered
            the ligand.

        binding_site_idxs : arraylike of int
            The indices of the atom positions in the state considered
            the binding site.

        Raises
        ------
        AssertionError
            If any of the following kwargs are not given:
            native_state, initial_states, ligand_idxs, receptor_idxs.


        """

        super().__init__(initial_states=initial_states,
                         initial_weights=initial_weights,
                         ligand_idxs=ligand_idxs,
                         receptor_idxs=binding_site_idxs
                         **kwargs)

        # test inputs
        assert native_state is not None, "Must give a native state"
        assert type(cutoff_rmsd) is float

        native_state_d = native_state.dict()

        # save the native state and center it around it's binding site
        native_state_d['positions'] = center_around(native_state['positions'], binding_site_idxs)

        native_state = WalkerState(**native_state_d)

        # save attributes
        self._native_state = native_state
        self._cutoff_rmsd = cutoff_rmsd
Esempio n. 6
0
def task_pass(walker):

    # simulate it actually taking some time
    n = walker.state['num']
    return Walker(WalkerState(**{'num' : n+1}), walker.weight)
Esempio n. 7
0
def gen_walkers():

    return [Walker(WalkerState(**{'num' : arg}), 1/len(ARGS))
            for arg in ARGS]
Esempio n. 8
0
def gen_walkers(n_args):

    args = range(n_args)

    return [Walker(WalkerState(**{'num': arg}), 1 / len(args)) for arg in args]
Esempio n. 9
0
    def init(self, continue_run=None, init_walkers=None, **kwargs):

        # do the inherited stuff
        super().init(**kwargs)

        # open and initialize the HDF5 file
        logging.info("Initializing HDF5 file at {}".format(self.file_path))

        self.wepy_h5 = WepyHDF5(self.file_path,
                                mode=self.mode,
                                topology=self._tmp_topology,
                                units=self.units,
                                sparse_fields=list(self._sparse_fields.keys()),
                                feature_shapes=self._feature_shapes,
                                feature_dtypes=self._feature_dtypes,
                                n_dims=self._n_dims,
                                main_rep_idxs=self.main_rep_idxs,
                                alt_reps=self.alt_reps_idxs)

        # if we specify save fields only save these for the initial walkers
        if self.save_fields is not None:

            state_fields = list(init_walkers[0].state.dict().keys())

            # make sure all the save_fields are present in the state
            assert all([True if save_field in state_fields else False
                        for save_field in self.save_fields]), \
                            "Not all specified save_fields present in walker states"

            filtered_init_walkers = []
            for walker in init_walkers:
                # make a new state by filtering the attributes of the old ones
                state_d = {
                    k: v
                    for k, v in walker.state.dict().items()
                    if k in self.save_fields
                }

                # and saving alternate representations as we would
                # expect them

                # if there are any alternate representations set them
                for alt_rep_name, alt_rep_idxs in self.alt_reps_idxs.items():

                    alt_rep_path = 'alt_reps/{}'.format(alt_rep_name)

                    # if the idxs are None we want all of the atoms
                    if alt_rep_idxs is None:
                        state_d[alt_rep_path] = state_d['positions'][:]
                    # otherwise get only the atoms we want
                    else:
                        state_d[alt_rep_path] = state_d['positions'][
                            alt_rep_idxs]

                # if the main rep is different then the full state
                # positions set that
                if self.main_rep_idxs is not None:
                    state_d['positions'] = state_d['positions'][
                        self.main_rep_idxs]

                # then making the new state
                new_state = WalkerState(**state_d)

                filtered_init_walkers.append(Walker(new_state, walker.weight))
        # otherwise save the full state
        else:
            filtered_init_walkers = init_walkers

        self.wepy_h5.set_mode(mode='r+')
        with self.wepy_h5:

            # if this is a continuation run of another run we want to
            # initialize it as such

            # initialize a new run
            run_grp = self.wepy_h5.new_run(filtered_init_walkers,
                                           continue_run=continue_run)
            self.wepy_run_idx = run_grp.attrs['run_idx']

            # initialize the run record groups using their fields
            self.wepy_h5.init_run_fields_resampling(self.wepy_run_idx,
                                                    self.resampling_fields)
            # the enumeration for the values of resampling
            self.wepy_h5.init_run_fields_resampling_decision(
                self.wepy_run_idx, self.decision_enum)
            self.wepy_h5.init_run_fields_resampler(self.wepy_run_idx,
                                                   self.resampler_fields)
            # set the fields that are records for tables etc. unless
            # they are already set
            if 'resampling' not in self.wepy_h5.record_fields:
                self.wepy_h5.init_record_fields('resampling',
                                                self.resampling_records)
            if 'resampler' not in self.wepy_h5.record_fields:
                self.wepy_h5.init_record_fields('resampler',
                                                self.resampler_records)

            # if there were no warping fields set there is no boundary
            # conditions and we don't initialize them
            if self.warping_fields is not None:
                self.wepy_h5.init_run_fields_warping(self.wepy_run_idx,
                                                     self.warping_fields)
                self.wepy_h5.init_run_fields_progress(self.wepy_run_idx,
                                                      self.progress_fields)
                self.wepy_h5.init_run_fields_bc(self.wepy_run_idx,
                                                self.bc_fields)
                # table records
                if 'warping' not in self.wepy_h5.record_fields:
                    self.wepy_h5.init_record_fields('warping',
                                                    self.warping_records)
                if 'boundary_conditions' not in self.wepy_h5.record_fields:
                    self.wepy_h5.init_record_fields('boundary_conditions',
                                                    self.bc_records)
                if 'progress' not in self.wepy_h5.record_fields:
                    self.wepy_h5.init_record_fields('progress',
                                                    self.progress_records)

        # if this was opened in a truncation mode, we don't want to
        # overwrite old runs with future calls to init(). so we
        # change the mode to read/write 'r+'
        if self.mode == 'w':
            self.set_mode(0, 'r+')
Esempio n. 10
0
if __name__=="__main__":
    if sys.argv[1] == "--help" or sys.argv[1] == '-h':
        print("arguments: n_cycles, n_walkers, dimension")
    else:

        num_cycles = int(sys.argv[1])
        num_walkers = int(sys.argv[2])
        dimension =  int(sys.argv[3])
        h5_path = str(sys.argv[4])
        # set up  the distance function
        rw_distance = RandomWalkDistance();

        # set up initial state for walkers
        positions = np.zeros((1, dimension))

        init_state = WalkerState(positions=positions, time=0.0)

        #set up the Wexplore Resampler with the parameters
        resampler = WExploreResampler(distance=rw_distance,
                                                 init_state=init_state,
                                                 max_n_regions=MAX_N_REGIONS,
                                                 max_region_sizes=MAX_REGION_SIZES,
                                                 pmin=PMIN, pmax=PMAX,
                                      debug_mode=True)

        # set up a RandomWalkProfilier
        rw_profiler = RandomwalkProfiler(resampler,
                                         hdf5_reporter_path=h5_path)

        rw_profiler.run_test(num_walkers=num_walkers,
                             num_cycles=num_cycles,
Esempio n. 11
0
def get_char_distance(dimension, num_walkers):
    """Calculate the characteristic value.
    Runs one cycle simulation and calculates the characteristic
    distance value.

    Parameters
    ----------
    dimension: int
        The dimension of the random walk space.


    num_walkers: int
        The number of walkers.

    Returns
    -------
    characteristic distance : float
        The characteristic distance value.

    """
    # set up initial state for walkers
    positions = np.zeros((1, dimension))

    init_state = WalkerState(positions=positions, time=0.0)

    # set up  the distance function
    rw_distance = RandomWalkDistance()

    # set up the  REVO Resampler with the parameters
    resampler = REVOResampler(distance=rw_distance,
                              pmin=PMIN,
                              pmax=PMAX,
                              init_state=init_state,
                              char_dist=1,
                              merge_dist=MERGE_DIST)

    # create list of init_walkers
    initial_weight = 1 / num_walkers

    init_walkers = [
        Walker(init_state, initial_weight) for i in range(num_walkers)
    ]

    # set up raunner for system
    runner = RandomWalkRunner(probability=PROBABILITY)

    n_steps = 10
    mapper = Mapper()
    # running the simulation
    sim_manager = Manager(init_walkers,
                          runner=runner,
                          resampler=resampler,
                          work_mapper=mapper)

    print("Running simulation")
    #runs for one cycle
    sim_manager.init(num_walkers)

    new_walkers = sim_manager.run_segment(init_walkers, n_steps, 0)

    dist_matrix, _ = resampler._all_to_all_distance(new_walkers)

    return np.average(dist_matrix)
Esempio n. 12
0
    def _run(self, num_runs, num_cycles, num_walkers):
        """Runs a random walk simulation.

        Parameters
        ----------
        num_runs: int
            The number independet simulations.

        num_cycles: int

            The number of cycles that will be run in the simulation.

        num_walkers: int
            The number of walkers.

        """

        print("Random walk simulation with: ")
        print("Dimension = {}".format(self.dimension))
        print("Probability = {}".format(self.probability))
        print("Number of Walkers = {}".format(num_walkers))
        print("Number of Cycles ={}".format(num_cycles))

        # set up initial state for walkers
        positions = np.zeros((1, self.dimension))

        init_state = WalkerState(positions=positions, time=0.0)

        # create list of init_walkers
        initial_weight = 1 / num_walkers
        init_walkers = []

        init_walkers = [
            Walker(init_state, initial_weight) for i in range(num_walkers)
        ]

        # set up raunner for system
        runner = RandomWalkRunner(probability=self.probability)

        units = dict(UNIT_NAMES)
        # instantiate a revo unbindingboudaryconditiobs
        segment_length = 10

        # set up the reporter
        randomwalk_system_top_json = self.generate_topology()

        hdf5_reporter = WepyHDF5Reporter(file_path=self.hdf5_filename,
                                         mode='w',
                                         save_fields=SAVE_FIELDS,
                                         topology=randomwalk_system_top_json,
                                         resampler=self.resampler,
                                         units=dict(UNITS),
                                         n_dims=self.dimension)
        # running the simulation
        sim_manager = Manager(init_walkers,
                              runner=runner,
                              resampler=self.resampler,
                              work_mapper=Mapper(),
                              reporters=[hdf5_reporter])

        # run a simulation with the manager for n_steps cycles of length 1000 each
        steps = [segment_length for i in range(num_cycles)]
        ### RUN the simulation
        for run_idx in range(num_runs):
            print("Starting run: {}".format(run_idx))
            sim_manager.run_simulation(num_cycles, steps)
            print("Finished run: {}".format(run_idx))

        print("Finished Simulation")