def randn_c_RS(RS: np.random.RandomState, *args: int) -> np.ndarray: # pragma: no cover """ Generates a random circularly complex gaussian matrix. This is essentially the same as the the randn_c function. The only difference is that the randn_c function uses the global RandomState object in numpy, while randn_c_RS use the provided RandomState object. This allow us greater control. Parameters ---------- RS : np.random.RandomState The RandomState object used to generate the random values. *args : any Variable number of arguments specifying the dimensions of the returned array. This is directly passed to the numpy.random.randn function. Returns ------- result : np.ndarray A random N-dimensional numpy array (complex dtype) where the `N` is equal to the number of parameters passed to `randn_c`. """ if RS is None: # noinspection PyArgumentList return randn_c(*args) # noinspection PyArgumentList return (1.0 / math.sqrt(2.0)) * (RS.randn(*args) + (1j * RS.randn(*args)))
def step(self, rng: np.random.RandomState): self.v = self.v - self.dt * self.freq**2 * self.x + self.v_noise * rng.randn( ) self.x = self.x + self.v * self.dt + self.x_noise * rng.randn() current_energy = self.energy(self.x, self.v) self.x = self.x * self.initial_energy / current_energy self.v = self.v * self.initial_energy / current_energy m = self.x + self.measurement_noise * rng.randn() + 2 return m
def random_unitary(n: int, np_random: np.random.RandomState): """Return an n x n Haar distributed unitary matrix. Return numpy array. """ X = (1.0 / math.sqrt(2.0)) * (np_random.randn(n, n) + 1j * np_random.randn(n, n)) Q, R = qr(X) R = np.diag(np.diag(R) / np.abs(np.diag(R))) U = np.dot(Q, R) return U
def step(self, rng: np.random.RandomState): ''' 1 transition step, that changes the state [x, v] of the model ''' self.v = self.v - self.dt * self.freq**2 * self.x + self.v_noise * rng.randn( ) self.x = self.x + self.v * self.dt + self.x_noise * rng.randn() current_energy = self.energy(self.x, self.v) self.x = self.x * self.initial_energy / current_energy self.v = self.v * self.initial_energy / current_energy m = self.x + self.measurement_noise * rng.randn() + 2 return m
def data(rng: np.random.RandomState): n: int = 100 t: int = 20 d: int = 2 x = rng.randn(n, d) xs = rng.randn(t, d) # test points c = np.array([[-1.4], [0.5]]) y = np.sin(x @ c + 0.5 * rng.randn(n, 1)) z = rng.randn(10, 2) return (tdf(x), tdf(y)), tdf(z), tdf(xs)
def __init__(self, N: int, # specify the length of each minhash vector random: np.random.RandomState, sparsity: int, din: int, quantization_step: int = 1, ): self.N = N self.sparsity = min(sparsity, din) self.quantization_step = quantization_step self.planes = random.randn(N, self.sparsity) self.biases = random.randn(self.N) self.indices_for_planes = random.randint(low=0, high=din, size=(N, self.sparsity))
def generate_one(self, rnd: np.random.RandomState) -> Chem.rdchem.Mol: node_logits = rnd.randn(self.n_nodes, self.n_node_types) node_probs = softmax(node_logits, axis=1) edge_logits = rnd.randn(self._n_adj_flat) weight_logits = rnd.randn(self._n_adj_flat, self.n_edge_types) num_edges = self._n_adj_flat # set to maximum sampled_nodes, sampled_edges = sample_molecule_graph( num_edges=num_edges, feature_probs=node_probs, weight_logits=weight_logits, edge_logits=edge_logits) mol = to_mol(sampled_nodes, sampled_edges) return mol
def random_date_img_tuple( dataset: Dict[str, torch.Tensor], writer: Union[int, None] = None, rand: np.random.RandomState = np.random.RandomState(seed=1234), **kwargs ) -> Tuple[Tuple[torch.Tensor, int], Tuple[torch.Tensor, int], Tuple[ torch.Tensor, int]]: """Compose a tuple of images of a valid date written by one person.""" # choose a consistent writer if writer is None: max_writer = min([d.shape[0] for d in dataset.values()]) - 1 writer = rand.randint(low=0, high=max_writer, size=1).item() # choose whether the writer prepends zeros to day and month leading_zero = rand.randn(1) > 0.6 return (random_day_img(dataset=dataset, writer=writer, rand=rand, leading_zero=leading_zero, **kwargs), random_month_img(dataset=dataset, writer=writer, rand=rand, leading_zero=leading_zero, **kwargs), random_year_img(dataset=dataset, writer=writer, rand=rand, **kwargs))
def generate_relative_risk_from_distribution( random_state: np.random.RandomState, parameters: dict) -> Union[float, pd.Series, np.ndarray]: first = pd.Series(list(parameters.values())[0]) length = len(first) index = first.index for v in parameters.values(): if length != len(pd.Series(v)) or not index.equals(pd.Series(v).index): raise ValueError( 'If specifying vectorized parameters, all parameters ' 'must be the same length and have the same index.') if 'mean' in parameters: # normal distribution rr_value = random_state.normal(parameters['mean'], parameters['se']) elif 'log_mean' in parameters: # log distribution log_value = parameters[ 'log_mean'] + parameters['log_se'] * random_state.randn() if parameters['tau_squared']: log_value += random_state.normal(0, parameters['tau_squared']) rr_value = np.exp(log_value) else: raise NotImplementedError( f'Only normal distributions (supplying mean and se) and log distributions ' f'(supplying log_mean, log_se, and tau_squared) are currently supported.' ) rr_value = np.maximum(1, rr_value) return rr_value
def random_lunarlander(random: np.random.RandomState=None, env=None): env = LunarLanderEnv() if env is None else env feature_size = len(LunarLanderEnv.params) feature_min = np.asarray([10., 0.5]) feature_max = np.asarray([16., 0.7]) feature_min_abs = np.asarray([10., 0.5]) if isinstance(random, np.random.RandomState): features = random.randn(feature_size) elif isinstance(random, np.ndarray): features = random elif isinstance(random, (int, float)): random = np.random.RandomState(random) features = random.rand(feature_size) features = np.clip(features, feature_min, feature_max) features = np.where(np.abs(features) < feature_min_abs, np.sign(features) * feature_min_abs, features) params = {k:v for k, v in zip(env.params, features)} env.set_parameters(**params) return env
def random_cartpole(random: np.random.RandomState = None, env=None): env = CartPoleEnv() if env is None else env feature_size = len(CartPoleEnv.params) feature_min = np.asarray([0.75, 0.075, 0.75, 7.5]) feature_max = np.asarray([1.25, 0.125, 1.25, 12.5]) feature_min_abs = np.asarray([0.1, 0.01, 0.1, 1.]) if isinstance(random, np.random.RandomState): features = random.randn(feature_size) elif isinstance(random, np.ndarray): features = random elif isinstance(random, (int, float)): random = np.random.RandomState(random) features = random.rand(feature_size) features = np.clip(features, feature_min, feature_max) features = np.where( np.abs(features) < feature_min_abs, np.sign(features) * feature_min_abs, features) params = {k: v for k, v in zip(env.params, features)} env.set_parameters(**params) return env
def fake_executor(circuit: cirq.Circuit, random_state: np.random.RandomState): """A fake executor which just samples from a normal distribution.""" return random_state.randn()
def junkify( img: torch.Tensor, resize: bool = False, cut_bottom: bool = False, speckle: bool = False, gaussian: bool = False, underlines: bool = False, fg_value: int = 0, bkg_value: int = 255, rand: np.random.RandomState = np.random.RandomState(seed=1234) ) -> torch.Tensor: """Add noise to an image. Args: img: The input image resize: True to resize the image cut_bottom: True to cut a few pixels off the bottom speckle: True to add speckle noise (blobs) gaussian: True to add Gaussian noise underlines: True to add spotty underlines fg_value: Foreground value bkg_value: Background value rand: For reproducibility, pass a seeded numpy random number generator object. Returns: img: The noisy image, possibly of a different size. """ out = img if resize: height = rand.randint(low=img.shape[-2], high=2 * img.shape[-2], size=1).item() width = rand.randint(low=img.shape[-1], high=3 * img.shape[-1], size=1).item() out = torch.ones([height, width ]) * bkg_value # blank canvas with bkg_value x = rand.randint(low=0, high=width - img.shape[-1] + 1) y = rand.randint(low=0, high=height - 28 + 1) out[y:y + img.shape[-2], x:x + img.shape[-1]] = img # paste image somewhere if cut_bottom: out = out[:-10, :] if speckle: # create spots noise = torch.zeros(out.shape) n = rand.randint(low=1, high=5, size=1).item() for _ in range(n): x = rand.randint(low=0, high=out.shape[-1] - 1, size=1).item() y = rand.randint(low=0, high=out.shape[-2] - 1, size=1).item() noise[..., y:y + 2, x:x + 2] = 1. # smooth the spots if len(noise.shape) == 2: noise = noise.unsqueeze(0).unsqueeze( 0) # add "batch" and "channel" dims elif len(noise.shape) == 3: noise = noise.unsqueeze(1) # add "channel" dim smoothed_noise = torch.nn.functional.conv2d( noise, weight=torch.ones([1, 1, 2, 2]) * 0.25, padding=(0, 0)) # convert to this foreground / background scheme smoothed_noise = smoothed_noise * (fg_value - bkg_value) + bkg_value # add to image if bkg_value > fg_value: out[..., 1:, 1:] = torch.where(smoothed_noise.squeeze() < out[..., 1:, 1:], smoothed_noise.squeeze(), out[..., 1:, 1:]) else: out[..., 1:, 1:] = torch.where(smoothed_noise.squeeze() > out[..., 1:, 1:], smoothed_noise.squeeze(), out[..., 1:, 1:]) if gaussian: out = (out + rand.randn(out.shape[-2], out.shape[-1]) * np.abs(bkg_value - fg_value).item() / 10.) if underlines: # create an underline y = rand.randint(low=out.shape[-2] - 10, high=out.shape[-2] - 1, size=1).item() xstart = rand.randint(low=0, high=out.shape[-1] - 1, size=1).item() xend = rand.randint(low=xstart, high=out.shape[-1] - 1, size=1).item() # add to image out[..., y, xstart:xend] = fg_value return torch.clamp(out, min=min(bkg_value, fg_value), max=max(bkg_value, fg_value))
def synthetic_data(num: int, rng: np.random.RandomState): X = rng.rand(num, 1) Y = np.sin(12 * X) + 0.66 * np.cos(25 * X) + rng.randn(num, 1) * 0.1 + 3 return X, Y
def gen_random_direction(dimension: int, random_state: np.random.RandomState) -> np.ndarray: random_direction = random_state.randn(dimension) random_direction *= 1.0 / np.linalg.norm(random_direction) return random_direction