From 2606be9a5f2cb0d31ed78e187759988fa2592d41 Mon Sep 17 00:00:00 2001 From: Katharina Eggensperger Date: Fri, 24 Feb 2017 10:52:45 +0100 Subject: [PATCH] ADD helper methods to get/create RandomState - work on #2 --- hpolib/util/rng_helper.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 hpolib/util/rng_helper.py diff --git a/hpolib/util/rng_helper.py b/hpolib/util/rng_helper.py new file mode 100644 index 0000000..294454b --- /dev/null +++ b/hpolib/util/rng_helper.py @@ -0,0 +1,36 @@ +import numpy as np + + +def get_rng(rng=None, self_rng=None): + """ helper function to obtain RandomState. + returns RandomState created from rng + if rng is None returns self_rng if RandomState + if self_rng is None initializes RandomState at random + + :param rng: int or RandomState + :param self_rng: RandomState + :return: RandomState + """ + + if rng is not None: + return create_rng(rng) + elif rng is None and self_rng is not None: + return create_rng(self_rng) + else: + return np.random.RandomState() + + +def create_rng(rng): + """ helper to create rng from RandomState or int + :param rng: int or RandomState + :return: RandomState + """ + if rng is None: + return np.random.RandomState() + elif type(rng) == np.random.RandomState: + return rng + elif int(rng) == rng: + return np.random.RandomState(rng) + else: + raise ValueError("%s is neither a number nor a RandomState. " + "Initializing RandomState failed") \ No newline at end of file