Python random.getstate() Examples

The following are code examples for showing how to use random.getstate(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: ptm   Author: GrivIN   File: factory.py    (MIT License) View Source Project 6 votes vote down vote up
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)) 
Example 2
Project: deeppavlov   Author: deepmipt   File: agents.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 3
Project: deeppavlov   Author: deepmipt   File: agents.py    (license) View Source Project 6 votes vote down vote up
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 = [] 
Example 4
Project: CodingDojo   Author: ComputerSocietyUNB   File: crypto.py    (license) View Source Project 6 votes vote down vote up
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)) 
Example 5
Project: FrankWolfe   Author: neu-spiral   File: modularDistFW.py    (license) View Source Project 6 votes vote down vote up
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 
Example 6
Project: BioQueue   Author: liyao001   File: install.py    (license) View Source Project 6 votes vote down vote up
def get_random_secret_key():
    import random
    import hashlib
    import time
    try:
        random = random.SystemRandom()
        using_sysrandom = True
    except NotImplementedError:
        import warnings
        warnings.warn('A secure pseudo-random number generator is not available '
                      'on your system. Falling back to Mersenne Twister.')
        using_sysrandom = False

    chars = '[email protected]#$%^&*(-_=+)'
    if not using_sysrandom:
        random.seed(
            hashlib.sha256(
                ("%s%s%s" % (
                    random.getstate(),
                    time.time(),
                    'BioQueue')).encode('utf-8')
            ).digest())
    return ''.join(random.choice(chars) for i in range(50)) 
Example 7
Project: coralillo   Author: getfleety   File: hashing.py    (license) View Source Project 6 votes vote down vote up
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)) 
Example 8
Project: xgovctf   Author: alphagov   File: autogen.py    (license) View Source Project 6 votes vote down vote up
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 
Example 9
Project: cupy   Author: cupy   File: random.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 10
Project: python-sepadd   Author: raphaelm   File: utils.py    (license) View Source Project 6 votes vote down vote up
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)]) 
Example 11
Project: lifesoundtrack   Author: MTG   File: crypto.py    (license) View Source Project 6 votes vote down vote up
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)) 
Example 12
Project: lang2program   Author: kelvinguu   File: utils.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 13
Project: lang2program   Author: kelvinguu   File: utils.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 14
Project: coordinates   Author: markovmodel   File: contexts.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 15
Project: bloomfilter-py   Author: seomoz   File: util.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 16
Project: liberator   Author: libscie   File: crypto.py    (license) View Source Project 6 votes vote down vote up
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)) 
Example 17
Project: djanoDoc   Author: JustinChavez   File: crypto.py    (license) View Source Project 6 votes vote down vote up
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)) 
Example 18
Project: pytest-randomly   Author: pytest-dev   File: test_it.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 19
Project: pytest-randomly   Author: pytest-dev   File: test_it.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 20
Project: pytest-randomly   Author: pytest-dev   File: pytest_randomly.py    (license) View Source Project 6 votes vote down vote up
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]) 
Example 21
Project: django-next-train   Author: bitpixdigital   File: crypto.py    (license) View Source Project 6 votes vote down vote up
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)) 
Example 22
Project: django-wechat-api   Author: crazy-canux   File: crypto.py    (license) View Source Project 6 votes vote down vote up
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)) 
Example 23
Project: deeppavlov   Author: deepmipt   File: agents.py    (license) View Source Project 5 votes vote down vote up
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 
Example 24
Project: deeppavlov   Author: deepmipt   File: agents.py    (license) View Source Project 5 votes vote down vote up
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 
Example 25
Project: deeppavlov   Author: deepmipt   File: agents.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 26
Project: deeppavlov   Author: deepmipt   File: agents.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 27
Project: text   Author: pytorch   File: iterator.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, random_state=None):
        self._random_state = random_state
        if self._random_state is None:
            self._random_state = random.getstate() 
Example 28
Project: text   Author: pytorch   File: iterator.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 29
Project: third_person_im   Author: bstadie   File: trainer.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 30
Project: plone.server   Author: plone   File: utils.py    (license) View Source Project 5 votes vote down vote up
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)]) 
Example 31
Project: django-sspanel   Author: Ehco1996   File: tools.py    (license) View Source Project 5 votes vote down vote up
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)) 
Example 32
Project: guillotina   Author: plone   File: utils.py    (license) View Source Project 5 votes vote down vote up
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)]) 
Example 33
Project: CrowdMaster   Author: johnroper100   File: cm_noiseChannels.py    (license) View Source Project 5 votes vote down vote up
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 
Example 34
Project: PonyGE2   Author: PonyGE   File: state.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 35
Project: neural_wfst   Author: se4u   File: util_lstm_seqlabel.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 36
Project: tfdnn-kaldi   Author: dreaming-dog   File: utils.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 37
Project: gps   Author: cbfinn   File: algorithm.py    (license) View Source Project 5 votes vote down vote up
def __getstate__(self):
        state = self.__dict__.copy()
        state['_random_state'] = random.getstate()
        state['_np_random_state'] = np.random.get_state()
        return state

    # For unpickling. 
Example 38
Project: Sentiment-Analysis   Author: AliceDudu   File: c6_sgd.py    (license) View Source Project 5 votes vote down vote up
def save_params(iter, params):
	with open("saved_params_%d.npy" % iter, "w") as f:
		pickle.dump(params, f)
		pickle.dumpy(random.getstate(), f) 
Example 39
Project: Sentiment-Analysis   Author: AliceDudu   File: c2_gradcheck.py    (license) View Source Project 5 votes vote down vote up
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" 
Example 40
Project: GAKeras   Author: PetraVidnerova   File: alg.py    (license) View Source Project 5 votes vote down vote up
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 
Example 41
Project: stargateRL   Author: thee-engineer   File: genesis.py    (license) View Source Project 5 votes vote down vote up
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() 
Example 42
Project: dl4nlp-stanford   Author: cioionut   File: q2_gradcheck.py    (license) View Source Project 5 votes vote down vote up
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!" 
Example 43
Project: dl4nlp-stanford   Author: cioionut   File: q3_sgd.py    (license) View Source Project 5 votes vote down vote up
def save_params(iter, params):
    with open("saved_params_%d.npy" % iter, "w") as f:
        pickle.dump(params, f)
        pickle.dump(random.getstate(), f) 
Example 44
Project: bloomfilter-py   Author: seomoz   File: util_test.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 45
Project: PACE-python   Author: mit-ll   File: coin.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, seed):
        random.seed(seed)
        self.state = random.getstate() 
Example 46
Project: PACE-python   Author: mit-ll   File: coin.py    (license) View Source Project 5 votes vote down vote up
def flip(self, *args):
        random.setstate(self.state)
        bit = super(SeededCoin, self).flip()
        self.state = random.getstate()
        return bit 
Example 47
Project: PACE-python   Author: mit-ll   File: coin.py    (license) View Source Project 5 votes vote down vote up
def reseed(self, seed):
        random.seed(seed)
        self.state = random.getstate() 
Example 48
Project: hanabi   Author: chikinn   File: general_encoding_player.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 49
Project: pytest-randomly   Author: pytest-dev   File: test_it.py    (license) View Source Project 5 votes vote down vote up
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) 
Example 50
Project: POTCO-PS   Author: ksmit799   File: DistributedGameTable.py    (license) View Source Project 5 votes vote down vote up
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