Python random 模块,getstate() 实例源码

我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用random.getstate()

项目:ptm    作者:GrivIN    | 项目源码 | 文件源码
def get_random_string(length=12,
                      allowed_chars='abcdefghijklmnopqrstuvwxyz'
                                    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    """
    Returns a securely generated random string.

    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
    """
    if not using_sysrandom:
        # This is ugly, and a hack, but it makes things better than
        # the alternative of predictability. This re-seeds the PRNG
        # using a value that is hard for an attacker to predict, every
        # time a random string is required. This may change the
        # properties of the chosen random sequence slightly, but this
        # is better than absolute predictability.
        random.seed(
            hashlib.sha256(
                ("%s%s" % (random.getstate(), time.time())).encode('utf-8')
            ).digest())
    return ''.join(random.choice(allowed_chars) for i in range(length))
项目:deeppavlov    作者:deepmipt    | 项目源码 | 文件源码
def __init__(self, opt, shared=None):
        """Initialize the parameters of the DefaultTeacher"""
        assert opt['train_part'] + opt['test_part'] + opt['valid_part'] == 1
        self.parts = [opt['train_part'], opt['valid_part'], opt['test_part']]
        # store datatype
        self.dt = opt['datatype'].split(':')[0]
        self.opt = opt
        opt['datafile'] = _path(opt)

        # store identifier for the teacher in the dialog
        self.id = 'ner_teacher'

        random_state = random.getstate()
        random.seed(opt.get('teacher_seed'))
        self.random_state = random.getstate()
        random.setstate(random_state)

        if shared and shared.get('metrics'):
            self.metrics = shared['metrics']
        else:
            self.metrics = CoNLLClassificationMetrics(opt['model_file'])

        # define standard question, since it doesn't change for this task
        super().__init__(opt, shared)
项目:deeppavlov    作者:deepmipt    | 项目源码 | 文件源码
def __init__(self, opt, shared=None):
        """Initialize the class accordint to given parameters in opt."""
        # store datatype
        self.datatype_strict = opt['datatype'].split(':')[0]

        opt['datafile'] = _path(opt)

        # store identifier for the teacher in the dialog
        self.id = 'insults_teacher'

        self.answer_candidates = ['Non-insult', "Insult"]

        random_state = random.getstate()
        random.seed(opt.get('teacher_random_seed'))
        self.random_state = random.getstate()
        random.setstate(random_state)

        super().__init__(opt, shared)

        if shared:
            self.observations = shared['observations']
            self.labels = shared['labels']
        else:
            self.observations = []
            self.labels = []
项目:CodingDojo    作者:ComputerSocietyUNB    | 项目源码 | 文件源码
def get_random_string(length=12,
                      allowed_chars='abcdefghijklmnopqrstuvwxyz'
                                    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    """
    Returns a securely generated random string.

    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
    """
    if not using_sysrandom:
        # This is ugly, and a hack, but it makes things better than
        # the alternative of predictability. This re-seeds the PRNG
        # using a value that is hard for an attacker to predict, every
        # time a random string is required. This may change the
        # properties of the chosen random sequence slightly, but this
        # is better than absolute predictability.
        random.seed(
            hashlib.sha256(
                ("%s%s%s" % (
                    random.getstate(),
                    time.time(),
                    settings.SECRET_KEY)).encode('utf-8')
            ).digest())
    return ''.join(random.choice(allowed_chars) for i in range(length))
项目:FrankWolfe    作者:neu-spiral    | 项目源码 | 文件源码
def adapt_z_state(self,main_rdd, cinfo,beta):
        ainv = cinfo
        def Updatez(tpl):
            tt=[]
            for ((tx,lam,state,z),index) in tpl:
                random.setstate(state)
                p = random.random()
                state = random.getstate()
                if p<self.ptr:
                    znew=float(-np.matrix(tx)*ainv*np.matrix(tx).T)
                else:
                    znew=0.0
                z=(1-beta)*z+beta*znew
                tt.append(((tx,lam,state,z),index))
            return tt
        main_rdd = main_rdd.mapValues(Updatez).cache()
        return main_rdd
项目:coralillo    作者:getfleety    | 项目源码 | 文件源码
def get_random_string(length=12,
                      allowed_chars='abcdefghijklmnopqrstuvwxyz'
                                    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    """
    Return a securely generated random string.
    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
    """
    if not using_sysrandom:
        # This is ugly, and a hack, but it makes things better than
        # the alternative of predictability. This re-seeds the PRNG
        # using a value that is hard for an attacker to predict, every
        # time a random string is required. This may change the
        # properties of the chosen random sequence slightly, but this
        # is better than absolute predictability.
        random.seed(
            hashlib.sha256(
                ('%s%s%s' % (random.getstate(), time.time(), settings.SECRET_KEY)).encode()
            ).digest()
        )
        return ''.join(random.choice(allowed_chars) for i in range(length))
项目:xgovctf    作者:alphagov    | 项目源码 | 文件源码
def seed_generator(pid, tid):
    """
    Sets python's random number generator.

    Args:
        pid: the problem id
        tid: the team id
    Returns:
        The previous state of the random generator
    """

    previous_state = random.getstate()

    random.seed(get_seed(pid, tid))

    return previous_state
项目:cupy    作者:cupy    | 项目源码 | 文件源码
def do_setup(deterministic=True):
    global _old_python_random_state
    global _old_numpy_random_state
    global _old_cupy_random_states
    _old_python_random_state = random.getstate()
    _old_numpy_random_state = numpy.random.get_state()
    _old_cupy_random_states = cupy.random.generator._random_states
    cupy.random.reset_states()
    # Check that _random_state has been recreated in
    # cupy.random.reset_states(). Otherwise the contents of
    # _old_cupy_random_states would be overwritten.
    assert (cupy.random.generator._random_states is not
            _old_cupy_random_states)

    if not deterministic:
        random.seed()
        numpy.random.seed()
        cupy.random.seed()
    else:
        random.seed(99)
        numpy.random.seed(100)
        cupy.random.seed(101)
项目:python-sepadd    作者:raphaelm    | 项目源码 | 文件源码
def get_rand_string(length=12, allowed_chars='0123456789abcdef'):
    """
    Returns a securely generated random string. Taken from the Django project

    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
    """
    if not using_sysrandom:
        # This is ugly, and a hack, but it makes things better than
        # the alternative of predictability. This re-seeds the PRNG
        # using a value that is hard for an attacker to predict, every
        # time a random string is required. This may change the
        # properties of the chosen random sequence slightly, but this
        # is better than absolute predictability.
        random.seed(
            hashlib.sha256(
                ("%s%s" % (
                    random.getstate(),
                    time.time())).encode('utf-8')
            ).digest())
    return ''.join([random.choice(allowed_chars) for i in range(length)])
项目:lifesoundtrack    作者:MTG    | 项目源码 | 文件源码
def get_random_string(length=12,
                      allowed_chars='abcdefghijklmnopqrstuvwxyz'
                                    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    """
    Returns a securely generated random string.

    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
    """
    if not using_sysrandom:
        # This is ugly, and a hack, but it makes things better than
        # the alternative of predictability. This re-seeds the PRNG
        # using a value that is hard for an attacker to predict, every
        # time a random string is required. This may change the
        # properties of the chosen random sequence slightly, but this
        # is better than absolute predictability.
        random.seed(
            hashlib.sha256(
                ("%s%s%s" % (
                    random.getstate(),
                    time.time(),
                    settings.SECRET_KEY)).encode('utf-8')
            ).digest())
    return ''.join(random.choice(allowed_chars) for i in range(length))
项目:lang2program    作者:kelvinguu    | 项目源码 | 文件源码
def random_seed(seed=None):
    """Execute code inside this with-block using the specified seed.

    If no seed is specified, nothing happens.

    Does not affect the state of the random number generator outside this block.
    Not thread-safe.

    Args:
        seed (int): random seed
    """
    if seed is None:
        yield
    else:
        py_state = random.getstate()  # save state
        np_state = np.random.get_state()

        random.seed(seed)  # alter state
        np.random.seed(seed)
        yield

        random.setstate(py_state)  # restore state
        np.random.set_state(np_state)
项目:lang2program    作者:kelvinguu    | 项目源码 | 文件源码
def random_seed(seed=None):
    """Execute code inside this with-block using the specified seed.

    If no seed is specified, nothing happens.

    Does not affect the state of the random number generator outside this block.
    Not thread-safe.

    Args:
        seed (int): random seed
    """
    if seed is None:
        yield
    else:
        py_state = random.getstate()  # save state
        np_state = np.random.get_state()

        random.seed(seed)  # alter state
        np.random.seed(seed)
        yield

        random.setstate(py_state)  # restore state
        np.random.set_state(np_state)
项目:coordinates    作者:markovmodel    | 项目源码 | 文件源码
def random_seed(seed=42):
    """ sets the random seed of Python within the context.

    Example
    -------
    >>> import random
    >>> with random_seed(seed=0):
    ...    random.randint(0, 1000) # doctest: +SKIP
    864
    """
    old_state = random.getstate()
    random.seed(seed)
    try:
        yield
    finally:
        random.setstate(old_state)
项目:bloomfilter-py    作者:seomoz    | 项目源码 | 文件源码
def derandomize(seed=123):
    '''
    Disable randomization for a block

    Since bloomfilter generates hash seeds randomly, it is inherently instable object.
    It considerably complicates testing. This helper addresses the issue:

        with bloomfilter.util.derandomize():
            bloom_filter_1 = BloomFilter(100, 0.1)

        with bloomfilter.util.derandomize():
            bloom_filter_2 = BloomFilter(100, 0.1)

    The resulting bloom_filters are stable between runs.
    '''
    state = random.getstate()
    try:
        random.seed(seed)
        yield
    finally:
        random.setstate(state)
项目:liberator    作者:libscie    | 项目源码 | 文件源码
def get_random_string(length=12,
                      allowed_chars='abcdefghijklmnopqrstuvwxyz'
                                    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    """
    Returns a securely generated random string.

    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
    """
    if not using_sysrandom:
        # This is ugly, and a hack, but it makes things better than
        # the alternative of predictability. This re-seeds the PRNG
        # using a value that is hard for an attacker to predict, every
        # time a random string is required. This may change the
        # properties of the chosen random sequence slightly, but this
        # is better than absolute predictability.
        random.seed(
            hashlib.sha256(
                ("%s%s%s" % (
                    random.getstate(),
                    time.time(),
                    settings.SECRET_KEY)).encode('utf-8')
            ).digest())
    return ''.join(random.choice(allowed_chars) for i in range(length))
项目:djanoDoc    作者:JustinChavez    | 项目源码 | 文件源码
def get_random_string(length=12,
                      allowed_chars='abcdefghijklmnopqrstuvwxyz'
                                    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    """
    Returns a securely generated random string.

    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
    """
    if not using_sysrandom:
        # This is ugly, and a hack, but it makes things better than
        # the alternative of predictability. This re-seeds the PRNG
        # using a value that is hard for an attacker to predict, every
        # time a random string is required. This may change the
        # properties of the chosen random sequence slightly, but this
        # is better than absolute predictability.
        random.seed(
            hashlib.sha256(
                ("%s%s%s" % (
                    random.getstate(),
                    time.time(),
                    settings.SECRET_KEY)).encode('utf-8')
            ).digest())
    return ''.join(random.choice(allowed_chars) for i in range(length))
项目:pytest-randomly    作者:pytest-dev    | 项目源码 | 文件源码
def test_the_same_random_seed_per_test_can_be_turned_off(ourtestdir):
    ourtestdir.makepyfile(
        test_one="""
        import random

        def test_a():
            test_a.state1 = random.getstate()
            assert test_a.state1 == random.getstate()  # sanity check
            assert random.random() >= 0  # mutate state
            test_a.state2 = random.getstate()

        def test_b():
            test_b.state = random.getstate()
            assert test_b.state == random.getstate()  # sanity check
            assert test_a.state1 != test_b.state
            assert test_a.state2 == test_b.state
        """
    )
    out = ourtestdir.runpytest(
        '--randomly-dont-reset-seed', '--randomly-dont-reorganize',
    )
    out.assert_outcomes(passed=2, failed=0)
项目:pytest-randomly    作者:pytest-dev    | 项目源码 | 文件源码
def test_fixtures_get_different_random_state_to_tests(ourtestdir):
    ourtestdir.makepyfile(
        test_one="""
        import random

        import pytest


        @pytest.fixture()
        def myfixture():
            return random.getstate()


        def test_one(myfixture):
            assert myfixture != random.getstate()
        """
    )
    out = ourtestdir.runpytest()
    out.assert_outcomes(passed=1)
项目:pytest-randomly    作者:pytest-dev    | 项目源码 | 文件源码
def _reseed(config, offset=0):
    seed = config.getoption('randomly_seed') + offset
    if seed not in random_states:
        random.seed(seed)
        random_states[seed] = random.getstate()
    else:
        random.setstate(random_states[seed])

    if have_factory_boy:
        factory_set_random_state(random_states[seed])

    if have_faker:
        faker_random.setstate(random_states[seed])

    if have_numpy:
        if seed not in np_random_states:
            np_random.seed(seed)
            np_random_states[seed] = np_random.get_state()
        else:
            np_random.set_state(np_random_states[seed])
项目:django-next-train    作者:bitpixdigital    | 项目源码 | 文件源码
def get_random_string(length=12,
                      allowed_chars='abcdefghijklmnopqrstuvwxyz'
                                    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    """
    Returns a securely generated random string.

    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
    """
    if not using_sysrandom:
        # This is ugly, and a hack, but it makes things better than
        # the alternative of predictability. This re-seeds the PRNG
        # using a value that is hard for an attacker to predict, every
        # time a random string is required. This may change the
        # properties of the chosen random sequence slightly, but this
        # is better than absolute predictability.
        random.seed(
            hashlib.sha256(
                ("%s%s%s" % (
                    random.getstate(),
                    time.time(),
                    settings.SECRET_KEY)).encode('utf-8')
            ).digest())
    return ''.join(random.choice(allowed_chars) for i in range(length))
项目:django-wechat-api    作者:crazy-canux    | 项目源码 | 文件源码
def get_random_string(length=12,
                      allowed_chars='abcdefghijklmnopqrstuvwxyz'
                                    'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    """
    Returns a securely generated random string.

    The default length of 12 with the a-z, A-Z, 0-9 character set returns
    a 71-bit value. log_2((26+26+10)^12) =~ 71 bits
    """
    if not using_sysrandom:
        # This is ugly, and a hack, but it makes things better than
        # the alternative of predictability. This re-seeds the PRNG
        # using a value that is hard for an attacker to predict, every
        # time a random string is required. This may change the
        # properties of the chosen random sequence slightly, but this
        # is better than absolute predictability.
        random.seed(
            hashlib.sha256(
                ("%s%s%s" % (
                    random.getstate(),
                    time.time(),
                    settings.SECRET_KEY)).encode('utf-8')
            ).digest())
    return ''.join(random.choice(allowed_chars) for i in range(length))
项目:deeppavlov    作者:deepmipt    | 项目源码 | 文件源码
def reset(self):
        """Reset Teacher random states"""
        random_state = random.getstate()
        random.setstate(self.random_state)
        random.shuffle(self.data.data)
        self.random_state = random.getstate()
        random.setstate(random_state)

        self.lastY = None
        self.episode_idx = self.data_offset - self.step_size
        self.episode_done = True
        self.epochDone = False
        if not self.random and self.data_offset >= self.data.num_episodes():
            # could have bigger batchsize then episodes... so nothing to do
            self.epochDone = True
项目:deeppavlov    作者:deepmipt    | 项目源码 | 文件源码
def setup_data(self, path):
        """Read and iteratively yield data to agent"""
        print('loading: ' + path)

        questions = []
        y = []

        # open data file with labels
        # (path will be provided to setup_data from opt['datafile'] defined above)
        with open(path) as labels_file:
            context = csv.reader(labels_file)
            next(context)

            for item in context:
                label, text = item
                questions.append(text)
                y.append([self.answer_candidates[int(label)]])

        episode_done = True

        indexes = range(len(questions))
        if self.datatype_strict != 'test':
            random_state = random.getstate()
            random.setstate(self.random_state)
            kf_seed = random.randrange(500000)
            kf = KFold(self.opt.get('bagging_folds_number'), shuffle=True,
                       random_state=kf_seed)
            i = 0
            for train_index, test_index in kf.split(questions):
                indexes = train_index if self.datatype_strict == 'train' else test_index
                if i >= self.opt.get('bagging_fold_index', 0):
                    break
            self.random_state = random.getstate()
            random.setstate(random_state)

        # define iterator over all queries
        for i in indexes:
            # get current label, both as a digit and as a text
            # yield tuple with information and episode_done? flag
            yield (questions[i], y[i]), episode_done
项目:deeppavlov    作者:deepmipt    | 项目源码 | 文件源码
def reset(self):
        """Reset class, random state"""
        super().reset()

        random_state = random.getstate()
        random.setstate(self.random_state)
        random.shuffle(self.data.data)
        self.random_state = random.getstate()
        random.setstate(random_state)
项目:deeppavlov    作者:deepmipt    | 项目源码 | 文件源码
def reset(self):
        """Reset class and random state."""

        super().reset()

        random_state = random.getstate()
        random.setstate(self.random_state)
        random.shuffle(self.data.data)
        self.random_state = random.getstate()
        random.setstate(random_state)
项目:text    作者:pytorch    | 项目源码 | 文件源码
def __init__(self, random_state=None):
        self._random_state = random_state
        if self._random_state is None:
            self._random_state = random.getstate()
项目:text    作者:pytorch    | 项目源码 | 文件源码
def use_internal_state(self):
        """Use a specific RNG state."""
        old_state = random.getstate()
        random.setstate(self._random_state)
        yield
        self._random_state = random.getstate()
        random.setstate(old_state)
项目:third_person_im    作者:bstadie    | 项目源码 | 文件源码
def set_seed_tmp(seed=None):
    if seed is None:
        yield
    else:
        state = random.getstate()
        np_state = np.random.get_state()
        random.seed(seed)
        np.random.seed(seed)
        yield
        np.random.set_state(np_state)
        random.setstate(state)
项目:plone.server    作者:plone    | 项目源码 | 文件源码
def get_random_string(length=30, allowed_chars=string.ascii_letters + string.digits):
    """
    Heavily inspired by Plone/Django
    Returns a securely generated random string.
    """
    if not using_sys_random:
        # do our best to get secure random without sysrandom
        seed_value = "%s%s%s" % (random.getstate(), time.time(), RANDOM_SECRET)
        random.seed(sha(seed_value).digest())
    return ''.join([random.choice(allowed_chars) for i in range(length)])
项目:django-sspanel    作者:Ehco1996    | 项目源码 | 文件源码
def get_random_string(length=12,
                      allowed_chars='abcdefghijklmnopqrstuvwxyz'
                      'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
    '''
    ?????????????????
    '''
    random.seed(
        hashlib.sha256(
            ("%s%s%s" % (
                random.getstate(),
                time.time(),
                'SCRWEWYOURBITCHES')).encode('utf-8')
        ).digest())
    return ''.join(random.choice(allowed_chars) for i in range(length))
项目:guillotina    作者:plone    | 项目源码 | 文件源码
def get_random_string(length: int=30,
                      allowed_chars: str=string.ascii_letters + string.digits) -> str:
    """
    Heavily inspired by Plone/Django
    Returns a securely generated random string.
    """
    if not using_sys_random:
        # do our best to get secure random without sysrandom
        seed_value = "%s%s%s" % (random.getstate(), time.time(), RANDOM_SECRET)
        random.seed(sha(seed_value).digest())
    return ''.join([random.choice(allowed_chars) for i in range(length)])
项目:CrowdMaster    作者:johnroper100    | 项目源码 | 文件源码
def agentRandom(self, offset=0):
        """Return a random number that is consistent between frames but can
        be offset by an integer"""
        state = random.getstate()
        random.seed(hash(self.userid) - 1 + offset)
        # -1 so that this number is different to the first random number
        # generated on frame 0 (if used) of the simulation
        result = random.random()
        random.setstate(state)
        return result
项目:PonyGE2    作者:PonyGE    | 项目源码 | 文件源码
def create_state(individuals):
    """
    Create a dictionary representing the current state of an evolutionary
    run. The state includes the current population, the current random state,
    the parameters dictionary, the stats dictionary, and all lists in the
    utilities.stats.trackers module.

    :param individuals: A population of individuals to be saved.
    :return: The complete state of a run.
    """

    from algorithm.parameters import params
    from stats.stats import stats
    from utilities.stats import trackers
    from time import time

    # Get time.
    state_time = time()

    # Get random state.
    random_state = random.getstate()

    # Create a picklable version of the params dictionary. Since the params
    # dictionary contains functions and class instances, we need to replace
    # these with the names of their respective modules, since module
    # instances are not picklable.
    pickle_params = {param: (check_name(params[param]) if callable(
        params[param]) else params[param]) for param in params}

    # Create a picklable version of the trackers module.
    pickle_trackers = {i: getattr(trackers, i) for i in dir(trackers)
                       if not i.startswith("__")}

    # Create state dictionary
    state = {"trackers": pickle_trackers, "params": pickle_params,
             "stats": stats, "individuals": individuals,
             "random_state": random_state, "time": state_time}

    save_state(state)
项目:neural_wfst    作者:se4u    | 项目源码 | 文件源码
def shuffle(lol):
    '''
    shuffle inplace each list in the same order by ensuring that we
    use the same state for every run of shuffle.

    lol :: list of list as input
    '''
    state = random.getstate()
    for l in lol:
        random.setstate(state)
        random.shuffle(l)
项目:tfdnn-kaldi    作者:dreaming-dog    | 项目源码 | 文件源码
def shuffle_together(self, mats):
        """

        :param mats: shuffles the given matrices and maintains the same 'shuffled order' in all matrices
        """
        rng = random.getstate()
        for mat in mats:
            random.setstate(rng) # reset random state to the saved state to get the same 'shuffled order' as previous shuffling
            random.shuffle(mat)
项目:gps    作者:cbfinn    | 项目源码 | 文件源码
def __getstate__(self):
        state = self.__dict__.copy()
        state['_random_state'] = random.getstate()
        state['_np_random_state'] = np.random.get_state()
        return state

    # For unpickling.
项目:Sentiment-Analysis    作者:AliceDudu    | 项目源码 | 文件源码
def save_params(iter, params):
    with open("saved_params_%d.npy" % iter, "w") as f:
        pickle.dump(params, f)
        pickle.dumpy(random.getstate(), f)
项目:Sentiment-Analysis    作者:AliceDudu    | 项目源码 | 文件源码
def gradcheck_naive(f, x):

    #Return an object capturing the current internal state of the generator
    rndstate = random.getstate()            #why use state??????
    random.setstate(rndstate)
    fx, grad = f(x)                         #fx=np.sum(x ** 2), grad=x * 2 
    h = 1e-4

    #Efficient multi-dimensional iterator object to iterate over arrays
    # Iterate over all indexes in x
    it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])    

    while not it.finished:
        ix = it.multi_index                 #starts from (0, 0) then (0, 1)

        x[ix] += h                          #To calculate [f(xi+h)-f(xi-h)] / 2h
        random.setstate(rndstate)
        fxh, _ = f(x)
        x[ix] -= 2*h
        random.setstate(rndstate)
        fxnh, _ = f(x)
        x[ix] += h
        numgrad = (fxh - fxnh) / 2 / h
                                            #To compare gradient calculated by formular and calculus
        reldiff = abs(numgrad - grad[ix]) / max(1, abs(numgrad), abs(grad[ix]))
        if reldiff > 1e-5:
            print "Gradient check failed."
            print "First gradient error found at index %s" % str(ix)
            print "Your gradient: %f \t Numerical gradient: %f" % (grad[ix], numgrad)
            return

        it.iternext()

    print "Gradient check passed"
项目:GAKeras    作者:PetraVidnerova    | 项目源码 | 文件源码
def myEASimple(population, start_gen, toolbox, cxpb, mutpb, ngen, 
               stats, halloffame, logbook, verbose, id=None):

    total_time = datetime.timedelta(seconds=0) 
    for gen in range(start_gen, ngen):
        start_time = datetime.datetime.now()
        population = algorithms.varAnd(population, toolbox, cxpb=cxpb, mutpb=mutpb)

        # Evaluate the individuals with an invalid fitness
        invalid_ind = [ind for ind in population if not ind.fitness.valid]
        fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)
        for ind, fit in zip(invalid_ind, fitnesses):
            ind.fitness.values = fit

        halloffame.update(population)
        record = stats.compile(population)
        logbook.record(gen=gen, evals=len(invalid_ind), **record)
        if verbose:
            print(logbook.stream)


        population = toolbox.select(population, k=len(population))

        if gen % 1 == 0:
            # Fill the dictionary using the dict(key=value[, ...]) constructor
            cp = dict(population=population, generation=gen, halloffame=halloffame,
                      logbook=logbook, rndstate=random.getstate())
            if id is None:
                cp_name = "checkpoint_ea.pkl"
            else:
                cp_name = "checkpoint_ea_{}.pkl".format(id)
            pickle.dump(cp, open(cp_name, "wb"))

        gen_time = datetime.datetime.now() - start_time
        total_time = total_time + gen_time
        #print("Time ", total_time)
        if total_time > datetime.timedelta(hours=4*24):
            print("Time limit exceeded.")
            break 

    return population, logbook
项目:stargateRL    作者:thee-engineer    | 项目源码 | 文件源码
def __init__(self, settings=None):
        """Construct the biomes using elevation and moisture."""
        if settings['homeworld']:
            self.width = settings['homeworld']['width']
            self.height = settings['homeworld']['height']
        else:
            self.width = random.randint(settings['min_size'],
                                        settings['max_size'])
            self.height = self.width

        logger.info(
            'Created PlanetGenerator %dx%d', self.width, self.height)

        if settings['homeworld']:
            elv_profile = read_profile(settings['homeworld']['elevation'],
                                       'elv')
            mst_profile = read_profile(settings['homeworld']['moisture'],
                                       'mst')
        else:
            elv_profile = read_profile('random', 'elv')
            mst_profile = read_profile('random', 'mst')

        # Generate map data using noise
        logger.debug('Creating elevation')
        self._generator_elevation = NoiseGenerator(self.width, self.height,
                                                   elv_profile)
        logger.debug('Creating moisture')
        self._generator_moisture = NoiseGenerator(self.width, self.height,
                                                  mst_profile)
        logger.debug('Creating biomes')
        self._data_biomes = self.generate_biomes()

        logger.debug('Computing hash of random state')
        self._hash = hashlib.sha256(str(random.getstate())).hexdigest()
项目:dl4nlp-stanford    作者:cioionut    | 项目源码 | 文件源码
def gradcheck_naive(f, x):
    """
    Gradient check for a function f
    - f should be a function that takes a single argument and outputs the cost and its gradients
    - x is the point (numpy array) to check the gradient at
    """

    rndstate = random.getstate()
    random.setstate(rndstate)
    fx, grad = f(x) # Evaluate function value at original point
    h = 1e-6

    # Iterate over all indexes in x
    it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])
    while not it.finished:
        ix = it.multi_index

        ### try modifying x[ix] with h defined above to compute numerical gradients
        ### make sure you call random.setstate(rndstate) before calling f(x) each time, this will make it
        ### possible to test cost functions with built in randomness later
        old_ix = x[ix]
        x[ix] += h
        random.setstate(rndstate)
        fxh, _ = f(x)
        numgrad = (fxh - fx) / (x[ix] - (x[ix] - h))
        x[ix] = old_ix
        # Compare gradients
        reldiff = abs(numgrad - grad[ix]) / max(1, abs(numgrad), abs(grad[ix]))
        if reldiff > 1e-5:
            print "Gradient check failed."
            print "First gradient error found at index %s" % str(ix)
            print "Your gradient: %f \t Numerical gradient: %f" % (grad[ix], numgrad)
            return

        it.iternext() # Step to next dimension

    print "Gradient check passed!"
项目:dl4nlp-stanford    作者:cioionut    | 项目源码 | 文件源码
def save_params(iter, params):
    with open("saved_params_%d.npy" % iter, "w") as f:
        pickle.dump(params, f)
        pickle.dump(random.getstate(), f)
项目:bloomfilter-py    作者:seomoz    | 项目源码 | 文件源码
def test_derandomize_allows_exceptions(self):
        '''derandomize propagates exception, but restores random state'''
        state = random.getstate()
        with self.assertRaises(ValueError):
            with bloomfilter.util.derandomize(234):
                raise ValueError('boom!')
        self.assertEqual(random.getstate(), state)
项目:PACE-python    作者:mit-ll    | 项目源码 | 文件源码
def __init__(self, seed):
        random.seed(seed)
        self.state = random.getstate()
项目:PACE-python    作者:mit-ll    | 项目源码 | 文件源码
def flip(self, *args):
        random.setstate(self.state)
        bit = super(SeededCoin, self).flip()
        self.state = random.getstate()
        return bit
项目:PACE-python    作者:mit-ll    | 项目源码 | 文件源码
def reseed(self, seed):
        random.seed(seed)
        self.state = random.getstate()
项目:hanabi    作者:chikinn    | 项目源码 | 文件源码
def StartRandom(self,seed):
        # This function initializes the fixed seed random method used by
        # players. There is a concern that the use of this method, particularly
        # the setting of a fixed seed, may bias other functions which wish to 
        # call random. For this reason, the RNG state is recorded at the start 
        # of the player call; the RNG state will then be set back to this state
        # before the player concludes it's turn. This will prevent the fixed
        # seed method from interacting with other random calls outside of the
        # AI program.
        self.RNG_State = random.getstate()
        random.seed(seed)
项目:pytest-randomly    作者:pytest-dev    | 项目源码 | 文件源码
def test_fixtures_dont_interfere_with_tests_getting_same_random_state(ourtestdir):
    ourtestdir.makepyfile(
        test_one="""
        import random

        import pytest


        random.seed(2)
        state_at_seed_two = random.getstate()


        @pytest.fixture(scope='module')
        def myfixture():
            return random.random()


        @pytest.mark.one()
        def test_one(myfixture):
            assert random.getstate() == state_at_seed_two


        @pytest.mark.two()
        def test_two(myfixture):
            assert random.getstate() == state_at_seed_two
        """
    )
    args = ['--randomly-seed=2']

    out = ourtestdir.runpytest(*args)
    out.assert_outcomes(passed=2)

    out = ourtestdir.runpytest('-m', 'one', *args)
    out.assert_outcomes(passed=1)
    out = ourtestdir.runpytest('-m', 'two', *args)
    out.assert_outcomes(passed=1)
项目:POTCO-PS    作者:ksmit799    | 项目源码 | 文件源码
def createAiPlayerName(self, female, seed):
        state = random.getstate()
        random.seed(seed)
        if female:
            first_name_array = PLocalizer.PirateNames_FirstNamesFemale
        else:
            first_name_array = PLocalizer.PirateNames_FirstNamesMale
        last_name_prefix_array = PLocalizer.PirateNames_LastNamePrefixesGeneric
        last_name_suffix_array = PLocalizer.PirateNames_LastNameSuffixesGeneric
        string = ''
        string = string + self.randomArraySelection(first_name_array) + ' '
        string = string + self.randomArraySelection(last_name_prefix_array)
        string = string + self.randomArraySelection(last_name_suffix_array)
        random.setstate(state)
        return string