def __init__(self, seed): self.random = random.Random() if seed is None: self.np_random = Generator(PCG64()) else: self.random.seed(seed) self.np_random = Generator(PCG64(seed))
def policy_evaluation(policy, bandit, anchor, anchor_context, true_ids, arms, arms_context, n_rounds): seq_error = np.zeros(shape=(n_rounds, 1)) actions_id = [a for a in arms.iterids()] if bandit in ['LinUCB', 'LinThompSamp']: for t in range(n_rounds): full_context = {} for action_id in actions_id: #full_context[action_id] = anchor_context full_context[action_id] = arms_context[ actions_id.index(action_id), :] history_id, action = policy.get_action(full_context, n_actions=1) if action[0].action.id not in true_ids: policy.reward(history_id, {action[0].action.id: 0.0}) if t == 0: seq_error[t] = 1.0 else: seq_error[t] = seq_error[t - 1] + 1.0 else: policy.reward(history_id, {action[0].action.id: 1.0}) if t > 0: seq_error[t] = seq_error[t - 1] elif bandit == 'Random': rg = Generator(PCG64(12345)) for t in range(n_rounds): action = actions_id[rg.integers(low=0, high=len(actions_id) - 1)] if action not in true_ids: if t == 0: seq_error[t] = 1.0 else: seq_error[t] = seq_error[t - 1] + 1.0 else: if t > 0: seq_error[t] = seq_error[t - 1] elif bandit == 'Similar': rg = Generator(PCG64(12345)) for t in range(n_rounds): #anchor_contextselect one of the 5 most similar arm cos_sim = cosine_similarity(anchor_context.reshape(1, -1), arms_context) ind = np.argpartition(cos_sim.ravel(), -10)[-10:] action = actions_id[rg.choice(ind)] if action not in true_ids: if t == 0: seq_error[t] = 1.0 else: seq_error[t] = seq_error[t - 1] + 1.0 else: if t > 0: seq_error[t] = seq_error[t - 1] return seq_error
def __init__(self, Lx, Ly, mu_ha, mu_a, J, init_mat, K, pK, sq=None): self.J = J self.Lx = Lx self.Ly = Ly self.K = K self.pK = pK self.mu_ha = mu_ha self.mu_a = mu_a #Define interaction parameters, H and M matrices #H are the site energies ,corresponding to state: (HA, Vac, A-) self.H = np.array([-self.mu_ha, 0, -self.mu_a]) #HA, Vac, A- #M is the nearest neighbor 3x3 interaction matrix depending upon the #the two spin states #J,K are positive, the repulsion is taken into account by the -ve sign in M definition self.M = np.array([[0, 0, -J], [0, 0, 0], [-J, 0, K]]) if sq == None: sq = np.random.SeedSequence() self.seed = sq.entropy bg = PCG64(sq) self.rgen = Generator(bg) #If init mat is not provided generate a random initial condition if init_mat is None: init_mat = random_3state_ic(self.rgen, self.Lx, self.Ly) self.even_mask = self.create_mask(0) self.odd_mask = self.create_mask(1) self.Spin = init_mat
def points_on_torus(num_points, param_c=0.5, param_a=0.375, random_seed=42, verbose=False): """Generates a pointcloud on a torus Parameters: num_points (int): Number of points to be generated param_c (float): Distance from center of torus to center of tube param_a (float): Radius of torus tube random_seed (int): Seed for the random number generator verbose (bool): Print information on screen Returns: np.array : The pointcloud generated with shape (3,num_points) """ if verbose: print(f"No. of points sampled = {num_points}") rg = Generator(PCG64(random_seed)) us = rg.random(num_points) * np.pi * 2 vs = rg.random(num_points) * np.pi * 2 pointcloud = np.zeros((num_points, 3)) pointcloud[:, 0] = (param_c + param_a * np.cos(vs)) * np.cos(us) pointcloud[:, 1] = (param_c + param_a * np.cos(vs)) * np.sin(us) pointcloud[:, 2] = param_a * np.sin(vs) return pointcloud
def __init__(self, seed=None, jump_index=0): # pylint: disable=no-member if seed is None: seed = random.getrandbits(128) self.seed = seed self.rng = PCG64(seed) self.jump_index = jump_index
def positive_param(): base = Generator(PCG64()) return [ base.chisquare(10), base.chisquare(10, (5, 1, 3)), base.chisquare(10, (6, 5, 4, 3)), ]
def __init__(self, demand_rate: float, demand_type: str, init_service_stock: int, seed: int): """Initialise Depot class.""" self.seed = seed self.generator = Generator(PCG64(seed)) # Inventory levels self.service_stock = init_service_stock self.service_stock_order = 0 self.service_back_orders = 0 self.repair_stock_level = 0 self.repair_stock = 0 # Demand rate self.demand_rate = demand_rate self.demand_type = demand_type self.log_data = pd.DataFrame(columns=[ "time", "service_stock", "service_orders", "service_back_orders", "service_stock_position", "repair_stock", ])
def test_primal_infeasible_problem(self): # Set random seed for reproducibility rg = Generator(PCG64(1)) self.n = 50 self.m = 500 # Generate random Matrices Pt = sparse.random(self.n, self.n, random_state=rg) self.P = sparse.triu(Pt.T.dot(Pt), format='csc') self.q = rg.standard_normal(self.n) self.A = sparse.random(self.m, self.n, random_state=rg).tolil() # Lil for efficiency self.u = 3 + rg.standard_normal(self.m) self.l = -3 + rg.standard_normal(self.m) # Make random problem primal infeasible self.A[int(self.n/2), :] = self.A[int(self.n/2)+1, :] self.l[int(self.n/2)] = self.u[int(self.n/2)+1] + 10 * rg.random() self.u[int(self.n/2)] = self.l[int(self.n/2)] + 0.5 # Convert A to csc self.A = self.A.tocsc() self.model = osqp.OSQP() self.model.setup(self.P, self.q, self.A, self.l, self.u, **self.opts) # Solve problem with OSQP res = self.model.solve() # Assert close self.assertEqual(res.info.status_val, constant('OSQP_PRIMAL_INFEASIBLE'))
def test_cython(tmp_path): srcdir = os.path.join(os.path.dirname(__file__), '..') shutil.copytree(srcdir, tmp_path / 'random') # build the examples and "install" them into a temporary directory env = os.environ.copy() subprocess.check_call([sys.executable, 'setup.py', 'build', 'install', '--prefix', str(tmp_path / 'installdir'), '--single-version-externally-managed', '--record', str(tmp_path/ 'tmp_install_log.txt'), ], cwd=str(tmp_path / 'random' / '_examples' / 'cython'), env=env) # get the path to the so's so1 = so2 = None with open(tmp_path /'tmp_install_log.txt') as fid: for line in fid: if 'extending.' in line: so1 = line.strip() if 'extending_distributions' in line: so2 = line.strip() assert so1 is not None assert so2 is not None # import the so's without adding the directory to sys.path from importlib.machinery import ExtensionFileLoader extending = ExtensionFileLoader('extending', so1).load_module() extending_distributions = ExtensionFileLoader('extending_distributions', so2).load_module() # actually test the cython c-extension from numpy.random import PCG64 values = extending_distributions.uniforms_ex(PCG64(0), 10, 'd') assert values.shape == (10,) assert values.dtype == np.float64
def prob(): base = Generator(PCG64()) return ([0.5], [0.5, (6, 5, 4, 3)], [0.3], [base.random((20, 2, 2))], [base.random(3)])
def int_prob(): base = Generator(PCG64()) return ([100, 0.5], [100, 0.5, (6, 5, 4, 3)], [base.integers(10, 100, size=(10, 2)), 0.3], [10, base.random((20, 2, 2))], [base.integers(10, 100, size=(5, 4, 3)), base.random(3)])
def __init__(self,Lx,Ly,mu_1,mu_2,J,init_mat,K=0,pK=7, seed = 1234567): super(LatticeModelVectorized,self).__init__(Lx,Ly,mu_1,mu_2, J,init_mat,K,pK) self.Spin_flip = self.Spin.copy() bg = PCG64(seed) self.rgen = Generator(bg)
def __init__(self, *args, **kwargs): super(NumpyPCG64, self).__init__(*args, **kwargs) self.name = "Numpy_PCG64" self.seed = 0 self.min = 0 self.max = 999999 self.random = Generator(PCG64(self.seed))
def __init__(self, seed=None, cls=None, cls_kw=None): super().__init__() seedx = int.from_bytes(bytes=seed, byteorder='big') if seed else None self.rand = PCG64(seedx) if cls is None else cls(seedx, **(cls_kw or {})) self.gen = Generator(self.rand) self.warned_high_inv = False self.warned_high_uni = False
def mlmc_eig_calc_innerloop(args): y, theta, M, seed, is_level_0 = args random_state_inner = RandomState(PCG64(seed)) theta = theta[np.newaxis, :] if use_importance_sampling: if use_laplace: q = mlmc_eig_laplace_approximation( theta, y - g(theta, xi).squeeze(axis=0), xi) else: q = qY(y, xi) theta_inner = q.rvs(size=M, random_state=random_state_inner) if M <= 1: theta_inner = theta_inner[np.newaxis, :] p = (dist_epsilon.pdf(y - g(theta_inner, xi)) * dist_theta.pdf(theta_inner) / q.pdf(theta_inner)) else: q = np.nan theta_inner = dist_theta.rvs(size=M, random_state=random_state_inner) if M <= 1: theta_inner = theta_inner[np.newaxis, :] p = dist_epsilon.pdf(y - g(theta_inner, xi)) if (is_level_0 and p.mean() > 0 or not is_level_0 and p[:int(M / 2)].mean() > 0 and p[int(M / 2):].mean() > 0): log_p_overline = np.log(p.mean()) log_p_overline_a = (np.log(p[:int(M / 2)].mean()) if not is_level_0 else np.nan) log_p_overline_b = (np.log(p[int(M / 2):].mean()) if not is_level_0 else np.nan) else: e_det = np.linalg.det(dist_epsilon.cov) y_dim = len(y) expornents = (-np.sum( (y - g(theta_inner, xi)) * ((y - g(theta_inner, xi)) @ Sigma_epsilon_I), axis=1, ) / 2) if use_importance_sampling: expornents += (-np.sum( (theta_inner - dist_theta.mean) * ((theta_inner - dist_theta.mean) @ np.linalg.inv( dist_theta.cov)), axis=1, ) / 2) expornents -= (-np.sum( (theta_inner - q.mean) * ((theta_inner - q.mean) @ np.linalg.inv(q.cov)), axis=1, ) / 2) log_p_overline = logsumexp(expornents, use_importance_sampling, q) log_p_overline_a = (logsumexp(expornents[:int(M / 2)], use_importance_sampling, q) if not is_level_0 else np.nan) log_p_overline_b = (logsumexp(expornents[int(M / 2):], use_importance_sampling, q) if not is_level_0 else np.nan) return (log_p_overline, log_p_overline_a, log_p_overline_b)
def test_unrelated_columns(N=60, random_seed=12345): """ Test to see if 'unrelated' columns jam up the analysis. See Github Issue 43. https://github.com/ACCLAB/DABEST-python/issues/44. Added in v0.2.5. """ # rng = RandomState(MT19937(random_seed)) rng = RandomState(PCG64(12345)) # rng = np.random.default_rng(seed=random_seed) df = pd.DataFrame({ 'groups': rng.choice(['Group 1', 'Group 2', 'Group 3'], size=(N, )), 'color': rng.choice(['green', 'red', 'purple'], size=(N, )), 'value': rng.random(size=(N, )) }) df['unrelated'] = np.nan test = load(data=df, x='groups', y='value', idx=['Group 1', 'Group 2']) md = test.mean_diff.results assert md.difference[0] == pytest.approx(-0.0322, abs=1e-4) assert md.bca_low[0] == pytest.approx(-0.2279, abs=1e-4) assert md.bca_high[0] == pytest.approx(0.1613, abs=1e-4)
def generate_random_radii_inverse_power(params, seed_radii, foldpath, subfoldname=SUB_FOLD_NAME): """ Generates radii for inverse potential and saves accordingly Args: foldname folder name seed seed Returns: Points """ n_part_by_2 = params.n_part.value // 2 # default generator passed with the seed rng = Generator(PCG64(seed_radii)) # first generate N samples with mean 0 and std 1 samples = rng.standard_normal(params.n_part.value) samples_1 = samples[:n_part_by_2] samples_2 = samples[n_part_by_2:] print(samples_2) radii_1 = list(params.r1.value + params.rstd1.value * samples_1) radii_2 = list(params.r2.value + params.rstd2.value * samples_2) radii = np.array(radii_1 + radii_2) os.makedirs(foldpath + "/" + subfoldname, exist_ok=True) np.savetxt(foldpath + "/" + subfoldname + "/radii.txt", radii) return radii
def test_polish_unconstrained(self): # Set random seed for reproducibility rg = Generator(PCG64(1)) self.n = 30 self.m = 0 P = sparse.diags(rg.random(self.n)) + 0.2*sparse.eye(self.n) self.P = P.tocsc() self.q = rg.standard_normal(self.n) self.A = sparse.csc_matrix((self.m, self.n)) self.l = np.array([]) self.u = np.array([]) self.model = osqp.OSQP() self.model.setup(self.P, self.q, self.A, self.l, self.u, **self.opts) # Solve problem res = self.model.solve() # Assert close nptest.assert_allclose( res.x, np.array([ 0.17221215, -1.84085666, 3.23111929, 0.32873825, -3.99110215, -1.0375029 , -0.64518994, 0.84374114, 2.19862467, -0.73591755, -0.11432888, 1.66275577, 1.28975978, 0.07288708, 1.87750662, 0.15037534, -0.28584164, -0.05900426, 1.25488928, -1.28429794, -0.93771052, -0.66786523, 1.19416376, -0.61965718, 0.4316592 , -0.9506598 , 1.44596409, -1.91755938, 0.05563106, 1.06737479]), rtol=1e-6, atol=1e-6) nptest.assert_allclose(res.y, np.array([])) nptest.assert_allclose(res.info.obj_val, -17.69727194, rtol=1e-6, atol=1e-6)
def __init__(self, n_particles: int, n_dimensions: int, verbose: bool = False, n_jobs: int = 1, random_state: Optional[int] = None) -> None: # Define attributes self.n_particles: int = n_particles self.n_dimensions: int = n_dimensions self.verbose: bool = verbose self.rg = Generator(PCG64(seed=random_state)) # Calculate number of jobs for parallel processing max_cpus: int = cpu_count() if n_jobs == 0: n_jobs = 1 elif abs(n_jobs) > max_cpus: n_jobs = max_cpus else: if n_jobs < 0: n_jobs = list(range(1, cpu_count() + 1))[n_jobs] self.n_jobs: int = n_jobs # Define function mapper map_func: Any = Pool(self.n_jobs).map if self.n_jobs > 1 else \ lambda func, x: list(map(func, x)) # type: ignore self._mapper: Any = lambda f, x: np.array(map_func(f, x)) # Hold history of swarm results self.history: List[Any] = []
def test_optimization_exact_input(self): """ Test the optimization step accuracy. This test creates the exact input power-spectrum and tri-spectrum and then performs the optimization step of the algorithm. Since the optimizer is not perfect, the error is at most 5e-7, instead of the expected perfect-fit score 0. This test is performed for both real data and complex data. """ seed: int = 1995 optimization_error_upper_bound: float = 5e-7 signal_length: int = 5 approximation_rank: int = 2 rng = Generator(PCG64(seed)) for data_type in [np.complex128, np.float64]: exact_cov: Matrix = generate_covariance(signal_length, approximation_rank, data_type, rng)[0] exact_cov_fourier_basis: Matrix = change_to_fourier_basis( exact_cov) exact_power_spectrum: Vector = np.ascontiguousarray( np.real(np.diag(exact_cov_fourier_basis))) exact_tri_spectrum: ThreeDMatrix = calc_exact_tri_spectrum( exact_cov_fourier_basis, data_type) g, min_fit_score = perform_optimization(exact_tri_spectrum, exact_power_spectrum, signal_length, data_type) min_fit_score = abs(min_fit_score) self.assertLess(min_fit_score, optimization_error_upper_bound) print( f'Optimization error for exact data of type {data_type} is smaller than ' f'{optimization_error_upper_bound}')
def integers(): dtypes = [ np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16, np.uint32, np.uint64, ] base = Generator(PCG64()) shape = tuple(base.integers(5, 10, size=2)) configs = [] for dt in dtypes: s1 = np.ones(shape, dtype=dt) s2 = np.ones((1, ) + shape, dtype=dt) lo = np.iinfo(dt).min hi = np.iinfo(dt).max configs.extend([ (0, np.iinfo(dt).max, None, dt), (lo, hi // 2, None, dt), (lo, hi, (10, 2), dt), (lo // 2 * s1, hi // 2 * s2, None, dt), ]) return configs
def divide_in_partitions(l: List[T], k: int, seed: int) -> List[FrozenSet[T]]: """ Divide the given list into k random partitions """ rng = Generator(PCG64(SeedSequence(seed))) rng.shuffle(l) return [frozenset(l[j::k]) for j in range(k)]
def main(): # API_key = "AIzaSyASm62A_u5U4Kcp4ohOA9lLLXy6PyceT4U" cd = os.path.join( os.path.dirname(os.path.abspath(__file__)), "..", "data" ) # direct to data folder sample_data_csv = os.path.join(cd, "Toll_CHC_November_Sample_Data.csv") CHC_data_csv = os.path.join(cd, "christchurch_street.csv") sample_df, sample_sub_dict, CHC_df, CHC_df_grouped, CHC_sub_dict = read_data( sample_data_csv, CHC_data_csv ) seed = 123456789 rg = Generator(PCG64(seed)) latitude, longitude = get_sample( 100, rg, cd, sample_df, sample_sub_dict, CHC_df_grouped, CHC_sub_dict, save=False, ) coord_filename = os.path.join(cd, "random_subset.csv") # get_coordinates(API_key, cd, address_filename, coord_filename) # coord_filename = None dm, tm = osrm_get_dist( cd, coord_filename, latitude, longitude, host="localhost:5000", save=True )
def EuropeanOptionPriceHurst(sigma, S0, K, r, delta, T, H=0.5, N=300, M=1000000): """ Create the function to price European Call options using Monte Carlo scheme for different Hurst parameters """ # pre-compute constants dt = T / N nudt = (r - delta - 0.5 * sigma ** 2) * dt sighdt = sigma * dt ** H # generate a matrix of standard normal random numbers of size MxN rg = Generator(PCG64()) Z = rg.standard_normal(size=[M, N]) # Generate stock value paths lnSt = np.log(S0) for i in range(N): lnSt = lnSt + nudt + sighdt * Z[:, i] ST = np.exp(lnSt) # Calculate the discounted value of the option disc_VT = np.maximum(0, ST - K) * np.exp(-r * T) return np.mean(disc_VT)
def points_on_ellipsoid(num_points, radius_x = 1.0, radius_y = 1.0, radius_z = 1.0, random_seed = 42, verbose = False): """Generates a pointcloud on an ellipsoid surface Parameters: num_points (int): Number of points to be generated radius_x (float): The radius along the X-axis radius_y (float): The radius along the Y-axis radius_z (float): The radius along the Z-axis random_seed (int): Seed for the random number generator verbose (bool): Print information on screen Returns: np.array : The pointcloud generated with shape (3,num_points) """ if verbose: print(f"No. of points sampled = {num_points}") rg = Generator(PCG64(random_seed)) thetas = rg.random(num_points) * np.pi phis = rg.random(num_points) * np.pi * 2 pointcloud = np.zeros((num_points, 3)) pointcloud[:, 0] = radius_x*np.sin(thetas)*np.cos(phis) pointcloud[:, 1] = radius_y*np.sin(thetas)*np.sin(phis) pointcloud[:, 2] = radius_z*np.cos(thetas) return pointcloud
def setUp(self): """ Setup equality constrained feasibility problem min 0 st A x = l = u """ # Set random seed for reproducibility rg = Generator(PCG64(1)) self.n = 30 self.m = 30 self.P = sparse.csc_matrix((self.n, self.n)) self.q = np.zeros(self.n) self.A = sparse.random(self.m, self.n, density=1.0, format='csc', random_state=rg) self.u = rg.random(self.m) self.l = self.u self.opts = {'verbose': False, 'eps_abs': 5e-05, 'eps_rel': 5e-05, 'scaling': True, 'adaptive_rho': 0, 'rho': 10, 'max_iter': 5000, 'polish': False} self.model = osqp.OSQP() self.model.setup(self.P, self.q, self.A, self.l, self.u, **self.opts)
def setUp(self): # Set random seed for reproducibility rg = Generator(PCG64(1)) self.n = 5 self.m = 8 p = 0.7 Pt = sparse.random(self.n, self.n, density=p, random_state=rg) Pt_new = Pt.copy() Pt_new.data += 0.1 * rg.standard_normal(Pt.nnz) self.P = sparse.triu(Pt.T.dot(Pt) + sparse.eye(self.n), format='csc') self.P_new = sparse.triu(Pt_new.T.dot(Pt_new) + sparse.eye(self.n), format='csc') self.q = rg.standard_normal(self.n) self.A = sparse.random(self.m, self.n, density=p, format='csc', random_state=rg) self.A_new = self.A.copy() self.A_new.data += rg.standard_normal(self.A_new.nnz) self.l = np.zeros(self.m) self.u = 30 + rg.standard_normal(self.m) self.opts = {'eps_abs': 1e-06, 'eps_rel': 1e-06, 'verbose': False} self.model = osqp.OSQP() self.model.setup(self.P, self.q, self.A, self.l, self.u, **self.opts)
def add_salt_and_pepper_noise(image,noise_percent): ''' Add noise with type "salt and pepper" Parameters ---------- image : numpy.ndarray Input image noise_percent : int Percentage of noise added to image Returns ------- image : numpy.ndarray Image with noise ''' noise_points = int((image.shape[0] * image.shape[1] * image.shape[2] * noise_percent) / 100) rand_gen = Generator(PCG64(seed = 1)) rand_widths = rand_gen.integers(low = 0,high = image.shape[0] - 1,size = noise_points) rand_heights = rand_gen.integers(low = 0,high = image.shape[1] - 1,size = noise_points) rand_ch = rand_gen.integers(low = 0,high = image.shape[2] - 1,size = noise_points) rand_pix = np.hstack((rand_widths[:,np.newaxis],rand_heights[:,np.newaxis],rand_ch[:,np.newaxis])) noise = np.zeros(noise_points,dtype = np.uint8) rand_floats = rand_gen.random(size = noise_points) mask = rand_floats > 0.5 noise[mask] = 255 image[rand_widths[:,np.newaxis],rand_heights[:,np.newaxis],rand_ch[:,np.newaxis]] = noise[:,np.newaxis] return image
def __init__(self, sampleFraction=0, seed=85792359, image_mask=None, phase=False, corr=False): """Setup for scan of images if sampleFraction is >0 (and it should be <=1) then that fraction of the image voxels will be retained. In that case, seed is used to set the random number generator. If phase is true, accumulate statistics on the phase as well as the modulus. If corr is true, accumulate statistics on the phase and its covariance with the modulus. Covariance is on a cell by cell basis. """ self.sampleFraction = sampleFraction self._modulus = RunningMean() if phase or corr: self._getPhase = True self._phase = RunningMean() if corr: self._getcorr = True self._xy = RunningMean(sd=False) if sampleFraction > 0: self._voxels = [] self._rg = Generator(PCG64(seed)) self.masking = (image_mask is not None) if self.masking: self.image_mask = image_mask self.image_keep = np.logical_not(image_mask) self._benchmarkHdr = None # checks for consistent headers self._mismatch = set() # holds keys that had a mismatch self._bifs = BIFS()
def test_feed_reward(self): greedy = EpsilonGreedy(num_arms=2, epsilon=0.0, rng=Generator(PCG64(42))) assert greedy.choice(0) == 1 with pytest.raises( ValueError, match=r"Expected the reward for arm 1, but got for 0" ): greedy.feed_reward(t=0, arm=0, reward=0.0) greedy.feed_reward(t=0, arm=1, reward=0.0)