def iter_random_dSS(number, stable=True, n=(5, 10), p=(1, 5), q=(1, 5), pRepeat=0.01, pReal=0.5, pBCmask=0.90, pDmask=0.8, pDzero=0.5): """ Generate some n-th order random (stable or not) state-spaces, with q inputs and p outputs copy/Adapted from control-python library (thanks guys): https://sourceforge.net/projects/python-control/ possibly already adpated from Mathworks or Octave Parameters: - number: number of state-space to generate - stable: indicate if the state-spaces are stable or not - n: tuple (mini,maxi) number of states (default: random between 5 and 10) - p: 1 or a tuple (mini,maxi) number of outputs (default: 1) - q: 1 or a tuple (mini,maxi) number of inputs (default: 1) - pRepeat: Probability of repeating a previous root (default: 0.01) - pReal: Probability of choosing a real root (default: 0.5). Note that when choosing a complex root, the conjugate gets chosen as well. So the expected proportion of real roots is pReal / (pReal + 2 * (1 - pReal)) - pBCmask: Probability that an element in B or C will not be masked out (default: 0.9) - pDmask: Probability that an element in D will not be masked out (default: 0.8) - pDzero: Probability that D = 0 (default: 0.5) Returns: - returns a generator of dSS objects (to use in a for loop for example) ..Example:: >>> sys = list( iter_random_dSS( 12, True, (10,20)) ) >>> for S in iter_random_dSS( 12, True, (10,20)): >>> print( S ) """ for i in range(number): if stable: yield random_dSS(randint(*n), randint(*p), randint(*q), pRepeat, pReal, pBCmask, pDmask, pDzero) else: nn = randint(*n) if p == 1 and q == 1: pp = 1 qq = 1 else: pp = randint(*p) qq = randint(*q) A = mat(rand(nn, nn)) B = mat(rand(nn, qq)) C = mat(rand(pp, nn)) D = mat(rand(pp, qq)) yield dSS(A, B, C, D)
def random_augmentation(imageBatch): imageBatch = imageBatch.clone() if (rand() >= 0.1): imageBatch = random_rotate(imageBatch) if (rand() >= 0.1): imageBatch = random_shift(imageBatch) if (rand() >= 0.1): imageBatch = gaussian_noise(imageBatch) return imageBatch
def random_augmentation(imageBatch): if (rand() >= 0.0): imageBatch = random_rotate(imageBatch) if (rand() >= 0.0): imageBatch = random_shift(imageBatch) if (rand() >= 0.0): imageBatch = gaussian_noise(imageBatch) # if(rand()>=0.5): # imageBatch = invert_colors(imageBatch) return imageBatch
def random_dTFmp(order=(5, 10)): """ Generate a n-th order random transfer function (not necessary stable) Parameters: - order: tuple (mini,maxi) order of the filter (default: random between 5 and 10) """ if order[0] == order[1]: n = order[0] else: n = randint(*order) num = numpy.matrix(rand(1, n)) den = numpy.matrix(rand(1, n)) return dTFmp(num, den)
def test_source(source_encoder, source_decoder, size): from numpy.random import mtrand import scipy from scipy import misc import time test_picture = mtrand.rand(size, size) * 255 encode_start = time.clock() enc = source_encoder(test_picture) encoded_picture, aux = enc.encode(False) encode_end = time.clock() decode_start = time.clock() dec = source_decoder(encoded_picture, aux) decoded_picture = dec.decode() decode_end = time.clock() if not PseudorandomnessSourceTestSuite.compare( scipy.misc.imresize(test_picture, numpy.array( [aux[PseudorandomnessSourceConfig.AUX_SQUARE_MATRIX_SHAPE][0], aux[PseudorandomnessSourceConfig.AUX_SQUARE_MATRIX_SHAPE][1]]), interp='bicubic'), decoded_picture): return 'Test failed' return '\n --- \nTest passed' + '\nEncode time: ' + repr(encode_end - encode_start) + '\nDecode time: ' + repr( decode_end - decode_start) + '\n --- \n'
def generate_global_variable_consensus_ilp(params): nb_agents = params['nb_agents'] nb_vars = params['nb_vars'] seed = params['seed'] if seed is not None: np.random.seed(seed) random.seed(seed) cs = [] As = [] bs = [] c_cent = np.zeros((nb_vars * nb_agents, 1)) A_cent = np.zeros((nb_agents, nb_vars * nb_agents)) b_cent = np.ones((nb_agents, 1)) for i in range(nb_agents): c = rand(nb_vars, 1) + 0.5 # np.random.randint(1, 10000, size=(nb_vars, 1)) # + rand(nb_vars, 1) * 1e-2 A = np.ones((1, nb_vars)) b = np.ones((1, 1)) cs.append(c) As.append(A) bs.append(b) A_cent[i, range(i * nb_vars, (i + 1) * nb_vars)] = A c_cent[range(i * nb_vars, (i + 1) * nb_vars), :] = c for j in range(nb_vars): for (i, k) in itertools.combinations(range(nb_agents), r=2): if i != k: line = np.zeros((1, nb_vars * nb_agents)) line[0, i * nb_vars + j] = 1 line[0, k * nb_vars + j] = -1 A_cent = np.concatenate([A_cent, line]) b_cent = np.concatenate([b_cent, np.zeros((1, 1))]) return cs, As, bs, c_cent, A_cent, b_cent
def nSidedDie(p): N = 1000 n = np.size(p) s = np.zeros((N, 1)) # print(s) for x in range(0, N): r = rand() s[x] = nDieSingleRoll(r, p) print("Die outcomes for", N, "rolls", "\n", s) # Plotting b = range(1, n + 2) sb = np.size(b) h1, bin_edges = np.histogram(s, bins=b) b1 = bin_edges[0:sb - 1] plt.close('all') prob = h1 / N plt.stem(b1, prob) # Graph labels plt.title('PMF for n-sided die') plt.xlabel('Number on the face of the die') plt.ylabel('Probability') plt.xticks(b1) plt.show()
def create_C_W_X_d(bias=True): C_train, C_val, X_train, X_val = data_factory( 'GMMData') # options: 'swiss','PeaksData','GMMData' W = randn(X_val.shape[0], C_val.shape[0]) d_w = rand(*W.shape) d_x = randn(*X_val.shape) return C_val, W, X_val, d_w, d_x
def terrain(res, lin, exp): print "Creating noise" realnoise = rand(res, res) imagnoise = rand(res, res) print "Normalizing noise" realnoise = [[2*_-1 for _ in __] for __ in realnoise] imagnoise = [[2*_-1 for _ in __] for __ in imagnoise] complexnoise = [[complex(0) for _ in range(res)] for __ in range(res)] for i in range(res): for j in range(res): complexnoise[i][j] = complex(realnoise[i][j], imagnoise[i][j]) x = (i+0.5)/res-0.5 y = (j+0.5)/res-0.5 dist = x*x+y*y nf = (lin*dist+0.1)**(-exp) complexnoise[i][j] = complex(realnoise[i][j]*nf, imagnoise[i][j]*nf) print "Performing backwards FFT2" fourier = ifft2(complexnoise) fourier = absolute(fourier) fourier -= fourier.min() fourier /= fourier.max() return fourier.tolist()
def generate_general_form_consensus_ilp(params): nb_agents = params['nb_agents'] nb_vars_per_agent = params['nb_vars_per_agent'] nb_shared_vars = params['nb_shared_vars'] seed = params['seed'] if seed is not None: np.random.seed(seed) random.seed(seed) cs = [] As = [] bs = [] c_cent = np.zeros((nb_vars_per_agent * nb_agents, 1)) A_cent = np.zeros((nb_agents, nb_vars_per_agent * nb_agents)) b_cent = np.ones((nb_agents, 1)) mapping = {i: [] for i in range(0, nb_shared_vars)} for i in range(nb_agents): c = rand(nb_vars_per_agent, 1) + 0.5 # np.random.randint(1, 10000, size=(nb_vars, 1)) # + rand(nb_vars, 1) * 1e-2 A = np.ones((1, nb_vars_per_agent)) b = np.ones((1, 1)) cs.append(c) As.append(A) bs.append(b) A_cent[i, range(i * nb_vars_per_agent, (i + 1) * nb_vars_per_agent)] = A c_cent[range(i * nb_vars_per_agent, (i + 1) * nb_vars_per_agent), :] = c indexes = list(range(nb_vars_per_agent)) random.shuffle(indexes) for v, j in zip(range(nb_shared_vars), indexes[0:nb_shared_vars]): mapping[v].append((i, j)) for g in mapping: for (xi, xj) in itertools.combinations(mapping[g], r=2): if xi != xj: line = np.zeros((1, nb_vars_per_agent * nb_agents)) line[0, xi[0] * nb_vars_per_agent + xi[1]] = 1 line[0, xj[0] * nb_vars_per_agent + xj[1]] = -1 A_cent = np.concatenate([A_cent, line]) b_cent = np.concatenate([b_cent, np.zeros((1, 1))]) return cs, As, bs, c_cent, A_cent, b_cent, mapping
def generate_global_variable_consensus_lp(params): nb_agents = params['nb_agents'] nb_vars = params['nb_vars'] nb_constraints_per_agent = params['nb_constraints_per_agent'] seed = params['seed'] if seed is not None: np.random.seed(seed) random.seed(seed) cs = [] As = [] bs = [] c_cent = np.zeros((nb_vars * nb_agents, 1)) A_cent = np.zeros((nb_agents * nb_constraints_per_agent, nb_vars * nb_agents)) b_cent = np.ones((nb_agents * nb_constraints_per_agent, 1)) n = nb_vars m = nb_constraints_per_agent for i in range(nb_agents): c = rand(n, 1) + 0.5 x0 = abs(randn(n, 1)) A = abs(randn(m, n)) b = A @ x0 cs.append(c) As.append(A) bs.append(b) A_cent[i * nb_constraints_per_agent:(i + 1) * nb_constraints_per_agent, i * nb_vars:(i + 1) * nb_vars] = A c_cent[i * nb_vars:(i + 1) * nb_vars, :] = c b_cent[i * nb_vars:(i + 1) * nb_vars, :] = b # consensus constraints for j in range(nb_vars): for (i, k) in itertools.combinations(range(nb_agents), r=2): if i != k: line = np.zeros((1, nb_vars * nb_agents)) line[0, i * nb_vars + j] = 1 line[0, k * nb_vars + j] = -1 A_cent = np.concatenate([A_cent, line]) b_cent = np.concatenate([b_cent, np.zeros((1, 1))]) return cs, As, bs, c_cent, A_cent, b_cent
from numpy import ndarray, array import numpy from scipy.spatial.distance import cdist from numpy.random.mtrand import rand from scipy.spatial.qhull import ConvexHull import matplotlib.pyplot as plt __author__ = 'basir' points = rand(10, 2) print type(points) print points.shape hull = ConvexHull(points) plt.plot(points[:, 0], points[:, 1], 'o') # for simplex in hull.simplices: # plt.plot(points[simplex, 0], points[simplex, 1], 'k-') plt.plot(points[hull.vertices, 0], points[hull.vertices, 1], 'r--', lw=2) # plt.plot(points[hull.vertices[0], 0], points[hull.vertices[0], 1], 'ro') boundary = array(points[hull.vertices, :]) print boundary print numpy.max(cdist(boundary, boundary)) print numpy.max(cdist(points, points)) plt.show()
from matplotlib.pyplot import contour, show, contourf, pcolor from numpy.fft.fftpack import ifft2 from numpy.ma.core import absolute from numpy.random.mtrand import rand res = 128 print "Creating noise" realnoise = rand(res, res) imagnoise = rand(res, res) print "Normalizing noise" realnoise = [[2*_-1 for _ in __] for __ in realnoise] imagnoise = [[2*_-1 for _ in __] for __ in imagnoise] complexnoise = [[complex(0) for _ in range(res)] for __ in range(res)] for i in range(res): for j in range(res): complexnoise[i][j] = complex(realnoise[i][j], imagnoise[i][j]) for i in range(res): for j in range(res): x = (i+0.5)/res-0.5 y = (j+0.5)/res-0.5 dist = x*x+y*y nf = (10000*dist+0.1)**(-1.2) complexnoise[i][j] = complex(realnoise[i][j]*nf, imagnoise[i][j]*nf) print "Performing backwards FFT2" fourier = ifft2(complexnoise) pcolor(absolute(fourier)) show()
def random_merged(values1: ndarray, values2: ndarray, values1_share: float = .5): return np.where(rand(len(values1)) < values1_share, values1, values2)
vertex_array, index_array = divide_all(vertex_array, index_array) return vertex_array, index_array def vertex_array_only_unit_sphere(recursion_level=2): vertex_array, index_array = create_unit_sphere(recursion_level) if recursion_level > 1: return vertex_array.reshape((-1)) else: return vertex_array[index_array].reshape((-1)) # http://en.wikipedia.org/wiki/Spherical_coordinate_system # def main(): n = 1000 r = 1+0 * rand(n) theta_0 = 0 theta = np.pi # theta_0 = np.pi/20 # theta = 9*np.pi/10 phi_0 = 0 phi = np.pi # thetas = np.linspace(0, np.pi, n) thetas = theta * rand(n) + theta_0 # phis = list(np.linspace(0, 2 * np.pi, np.sqrt(n))) * int(np.sqrt(n)) phis = phi * rand(n) + phi_0 print np.mean(phis) print np.std(phis) plt.plot(phis) plt.show()
def random_ABCD(n, p, q, pRepeat=0.01, pReal=0.5, pBCmask=0.90, pDmask=0.8, pDzero=0.5): """ Generate ONE n-th order random stable state-spaces, with q inputs and p outputs copy/adapted from control-python library (Richard Murray): https://sourceforge.net/projects/python-control/ (thanks guys!) possibly already adpated/copied from Mathworks or Octave Parameters: - n: number of states (default: random between 5 and 10) - p: number of outputs (default: 1) - q: number of inputs (default: 1) - pRepeat: Probability of repeating a previous root (default: 0.01) - pReal: Probability of choosing a real root (default: 0.5). Note that when choosing a complex root, the conjugate gets chosen as well. So the expected proportion of real roots is pReal / (pReal + 2 * (1 - pReal)) - pBCmask: Probability that an element in B or C will not be masked out (default: 0.90) - pDmask: Probability that an element in D will not be masked out (default: 0.8) - pDzero: Probability that D = 0 (default: 0.5) Returns a four numpy matrices A,B,C,D """ # Make some poles for A. Preallocate a complex array. poles = zeros(n) + zeros(n) * 0.j i = 0 while i < n: if rand() < pRepeat and i != 0 and i != n - 1: # Small chance of copying poles, if we're not at the first or last element. if poles[i - 1].imag == 0: poles[i] = poles[i - 1] # Copy previous real pole. i += 1 else: poles[i:i + 2] = poles[ i - 2:i] # Copy previous complex conjugate pair of poles. i += 2 elif rand() < pReal or i == n - 1: poles[i] = 2. * rand() - 1. # No-oscillation pole. i += 1 else: mag = rand() # Complex conjugate pair of oscillating poles. phase = 2. * pi * rand() poles[i] = complex(mag * cos(phase), mag * sin(phase)) poles[i + 1] = complex(poles[i].real, -poles[i].imag) i += 2 # Now put the poles in A as real blocks on the diagonal. A = zeros((n, n)) i = 0 while i < n: if poles[i].imag == 0: A[i, i] = poles[i].real i += 1 else: A[i, i] = A[i + 1, i + 1] = poles[i].real A[i, i + 1] = poles[i].imag A[i + 1, i] = -poles[i].imag i += 2 while True: # Finally, apply a transformation so that A is not block-diagonal. T = randn(n, n) try: A = dot(solve(T, A), T) # A = T \ A * T break except LinAlgError: # In the unlikely event that T is rank-deficient, iterate again. pass # Make the remaining matrices. B = randn(n, q) C = randn(p, n) D = randn(p, q) # Make masks to zero out some of the elements. while True: Bmask = rand(n, q) < pBCmask if not Bmask.all(): # Retry if we get all zeros. break while True: Cmask = rand(p, n) < pBCmask if not Cmask.all(): # Retry if we get all zeros. break if rand() < pDzero: Dmask = zeros((p, q)) else: while True: Dmask = rand(p, q) < pDmask if not Dmask.all(): # Retry if we get all zeros. break # Apply masks. B *= Bmask C *= Cmask # D *= Dmask return A, B, C, D
def rand(): return r.rand()
def bernoulli(p): return rand() < p