Ejemplo n.º 1
0
 def initialize(self):
     self.pcoord_ndim = 1
     self.pcoord_dtype = np.float32
     self.pcoord_len = 5
     self.bin_mapper = RectilinearBinMapper([ list(np.arange(0.0, 10.1, 0.1)) ] )
     self.bin_target_counts = np.empty((self.bin_mapper.nbins,), np.int_)
     self.bin_target_counts[...] = 10
     self.test_variable_2 = "And I'm the second one"
Ejemplo n.º 2
0
 def setup(self):
     system = WESTSystem()
     system.bin_mapper = RectilinearBinMapper([[0.0, 1.0, 2.0]])
     system.bin_target_counts = np.array([4, 4])
     system.pcoord_len = 2
     self.we_driver = WEDriver(system=system)
     self.system = system
     self._seg_id = 0
Ejemplo n.º 3
0
def bins_from_yaml_dict(bin_dict):
    kwargs = deepcopy(bin_dict)
    typename = kwargs.pop('type')

    try:
        mapper_type = getattr(sys.modules['westpa.core.binning'], typename)
    except AttributeError:
        try:
            mapper_type = get_object(typename)
        except AttributeError:
            raise KeyError('unknown bin mapper type {!r}'.format(typename))

    if not issubclass(mapper_type, BinMapper):
        raise ValueError('{} is not a BinMapper'.format(mapper_type.__name__))

    if mapper_type is RectilinearBinMapper:
        boundary_lists = kwargs.pop('boundaries', None)
        if boundary_lists is None:
            raise KeyError('RectilinearBinMapper: missing boundaries')
        parsed_lists = boundary_lists[:]
        for iboundary, boundary in enumerate(boundary_lists):
            if boundary.__class__ == str:
                parsed_lists[iboundary] = parsePCV(boundary)[0]
            else:
                parsed_lists[iboundary] = list(map((lambda x: float(x) if isinstance(x, str) else x), boundary))
        return RectilinearBinMapper(parsed_lists)
    elif mapper_type is RecursiveBinMapper:
        base_mapper_config = kwargs.pop('base', None)
        base_mapper_config = kwargs.pop('base_mapper', base_mapper_config)
        if base_mapper_config is None:
            raise KeyError('RecursiveBinMapper: missing base_mapper')

        base_mapper = bins_from_yaml_dict(base_mapper_config)
        start_index = kwargs.pop('start_index', 0)

        rec_mapper = RecursiveBinMapper(base_mapper, start_index)
        mapper_configs = kwargs.pop('mappers')
        mappers = []
        if mapper_configs is not None:
            for config in mapper_configs:
                replaced_bin = config.pop('replaces_bin_at', None)
                replaced_bin = config.pop('at', replaced_bin)
                if replaced_bin is None:
                    raise KeyError('RecursiveBinMapper: missing replaces_bin_at for ' 'at least one of the child mappers')
                mapper = bins_from_yaml_dict(config)
                mappers.append((mapper, replaced_bin))

        for mapper, replaced_bin in mappers:
            rec_mapper.add_mapper(mapper, replaced_bin)

        return rec_mapper
    else:
        try:
            return mapper_type(**kwargs)
        except Exception:
            log.exception('exception instantiating mapper')
            raise
Ejemplo n.º 4
0
    def initialize(self):
        self.pcoord_ndim = 1
        self.pcoord_dtype = pcoord_dtype
        self.pcoord_len = pcoord_len

        #self.bin_mapper = RectilinearBinMapper([[0,1.3] + list(np.arange(1.4, 10.1, 0.1)) + [float('inf')]])
        self.bin_mapper = RectilinearBinMapper(
            [list(np.arange(0.0, 10.1, 0.1))])
        self.bin_target_counts = np.empty((self.bin_mapper.nbins, ), np.int_)
        self.bin_target_counts[...] = 10
Ejemplo n.º 5
0
def mapper_from_expr(expr):
    namespace = {'numpy': np, 'np': np, 'inf': float('inf')}
    try:
        mapper = RectilinearBinMapper(eval(expr, namespace))
    except TypeError as e:
        if 'has no len' in str(e):
            raise ValueError('invalid bin boundary specification (a list of lists is required)')
        else:
            raise
    else:
        log.debug('loaded {!r} from expression {!r}'.format(mapper, expr))
        return mapper
Ejemplo n.º 6
0
    def test_merge_by_weight(self):
        selected_counts = {0: 0, 1: 0}
        alpha = 0.01
        nrounds = 1000
        from scipy.stats import binom

        # lower and upper bounds of 95% CI for selecting the segment with weight 1/3
        lb = binom.ppf(alpha / 2.0, nrounds, 1.0 / 3.0)
        ub = binom.ppf(1.0 - alpha / 2.0, nrounds, 1.0 / 3.0)

        system = WESTSystem()
        system.bin_mapper = RectilinearBinMapper([[0.0, 1.0]])
        system.bin_target_counts = np.array([1])
        system.pcoord_len = 2
        self.we_driver = WEDriver(system=system)
        self.system = system
        self._seg_id = 0

        segments = [
            Segment(n_iter=1,
                    seg_id=0,
                    pcoord=np.array([[0], [0.25]], dtype=np.float32),
                    weight=1.0 / 3.0),
            Segment(n_iter=1,
                    seg_id=1,
                    pcoord=np.array([[0], [0.75]], dtype=np.float32),
                    weight=2.0 / 3.0),
        ]

        for _iround in range(nrounds):
            for segment in segments:
                segment.endpoint_type = Segment.SEG_ENDPOINT_UNSET

            self.we_driver.new_iteration()
            self.we_driver.assign(segments)
            self.we_driver.construct_next()

            assert len(self.we_driver.next_iter_binning[0]) == 1
            newseg = self.we_driver.next_iter_binning[0].pop()

            assert segments[
                newseg.
                parent_id].endpoint_type == Segment.SEG_ENDPOINT_CONTINUES
            assert segments[
                ~newseg.parent_id].endpoint_type == Segment.SEG_ENDPOINT_MERGED

            selected_counts[newseg.parent_id] += 1

        print(selected_counts)
        assert (
            lb <= selected_counts[0] <= ub
        ), 'Incorrect proportion of histories selected.' 'this is expected about {:%} of the time; retry test.'.format(
            alpha)
Ejemplo n.º 7
0
    def mapper_from_expr(self, expr):
        from westpa.core.binning import RectilinearBinMapper

        namespace = {'numpy': np, 'np': np, 'inf': float('inf')}

        try:
            return RectilinearBinMapper(eval(expr, namespace))
        except TypeError as e:
            if 'has no len' in str(e):
                raise ValueError(
                    'invalid bin boundary specification; you probably forgot to make a list of lists'
                )
Ejemplo n.º 8
0
    def initialize(self):

        #   pcoord dimensionality and length. This should match your outside bin
        self.pcoord_ndim = 2
        self.pcoord_len = pcoordlength
        self.pcoord_dtype = pcoord_dtype

        #   These are your "outer" bins in both dimensions
        outer_mapper = RectilinearBinMapper([[0.00, numpy.inf],
                                             [0.00, 8.00, numpy.inf]])
        #   These define the "inner" adaptive bins. Each one indicates an independent
        #   adaptive binning scheme. Copy for more. Respects the parameters at the start.
        adaptive_mapper0 = FuncBinMapper(function_map,
                                         prod(binsperdim) + numberofdim *
                                         (2 + 2 * splitIsolated) +
                                         activetarget,
                                         kwargs={"multi_idx": 0})  # Bottom bin
        adaptive_mapper1 = FuncBinMapper(function_map,
                                         prod(binsperdim) + numberofdim *
                                         (2 + 2 * splitIsolated) +
                                         activetarget,
                                         kwargs={"multi_idx": 1})  # Top bin

        #   These are the bins where you'll place each adaptive scheme.
        self.bin_mapper = RecursiveBinMapper(outer_mapper)
        self.bin_mapper.add_mapper(adaptive_mapper0, [5, 1])  #Bottom mapper
        self.bin_mapper.add_mapper(adaptive_mapper1, [5, 10])  #Top mapper

        ######################### JL ##########################################
        #    This is the what the example looks like.
        #
        #   inf --------------------------------------------------------
        #      |                                                        |
        #      |                    adaptive_mapper1                    |
        #      |                                                        |
        #     8 --------------------------------------------------------
        #  D2  |        |                                               |
        #      | TARGET |           adaptive_mapper0                    |
        #      | STATE  |                                               |
        #     0 --------------------------------------------------------
        #              3.5 (soft bound via mincap)                     inf
        #                        Dimension 1 of pcoord
        #
        #######################################################################

        self.bin_target_counts = numpy.empty((self.bin_mapper.nbins, ),
                                             dtype=numpy.int)

        #   Number of walkers per bin
        self.bin_target_counts[...] = bintargetcount