def Move( gaze=None, newGaze=None ): position = mouse.position() if( gaze is None ): mouse.move( position[0] + mouseMoveData[0], position[1] + mouseMoveData[1] ) position = mouse.position() if( position[0] <= 0 or position[1] <= 0 or position[0] >= mouseMoveData[2] or position[1] >= mouseMoveData[3] ): mouseMoveData = None else: screenSize = mouse.screen_size() shifts = vector( gaze ) - vector( newGaze ) + 0.0 # x and y shifts as floats shifts[1] = -shifts[1] # Due to coordinate style, both x and y must be inverse; x is already corrected by mirror image xDistance = abs( float(position[0] - (0 if shifts[0] < 0 else screenSize[0])) ) yDistance = abs( float(position[1] - (0 if shifts[1] < 0 else screenSize[1])) ) TICKS_TO_EDGE = 10.0 # It will take 10 cycles of the event loop to hit the screen edge, or 1 second (10.0 * 0.1s) xMultiplier = ( xDistance / abs(shifts[0]) ) / TICKS_TO_EDGE yMultiplier = ( yDistance / abs(shifts[1]) ) / TICKS_TO_EDGE # Multiplier used is the smaller one, because it corresponds with the edge that will be hit first shifts = shifts * (xMultiplier if xMultiplier < yMultiplier else yMultiplier) # Sets array with data needed to begin and continue mouse movement mouseMoveData = [ shifts[0], shifts[1], screenSize[0] - 1, screenSize[1] - 1 ] Move()
def bounce(self, d=50): if d > self.position[0]: self.steer(vector((self.maxspeed, self.velocity[1]))) if self.position[0] > WIDTH - d: self.steer(vector((-self.maxspeed, self.velocity[1]))) if d > self.position[1]: self.steer(vector((self.velocity[1], self.maxspeed))) if self.position[1] > HEIGHT - d: self.steer(vector((self.velocity[1], -self.maxspeed)))
def __init__(self, pos, size=5, speed=5): super().__init__(pos) self.size = size self.maxspeed = speed self.maxforce = self.maxspeed / 10 self.desired = vector((0, 0)) self.theta = 0 self.velocity = vector([ uniform(-self.maxspeed / 2, self.maxspeed / 2), uniform(-self.maxspeed / 2, self.maxspeed / 2) ])
def step(self): # apply physics to update velocities for n in self.graph.node: if self.graph.node[n]['actor'] is self.pin: continue force = vector([0., 0.]) for m in self.graph.node: if m == n: continue ### CRITICAL SPEED SECTION ### direction = self.graph.node[n]['position'] - self.graph.node[m]['position'] dist = norm(direction) if dist < self.mindist: if dist == 0.: direction = vector([uniform(-0.5, 0.5), uniform(-0.5, 0.5)]) dist = self.mindist newdist = norm(direction) direction *= dist/newdist force += direction * self.graph.node[n]['charge'] * self.graph.node[m]['charge'] / dist ** 3. if m in self.graph[n]: force = force - direction * self.spring * (1. - self.naturallength / dist) massy = self.stepsize / self.graph.node[n]['mass'] dampdv = - self.damping * self.graph.node[n]['velocity'] * norm(self.graph.node[n]['velocity']) * massy if norm(dampdv) > norm(self.graph.node[n]['velocity']): self.graph.node[n]['velocity'] = vector([0., 0.]) self.graph.node[n]['actor'].props.fill_color_rgba = 0xcc333380 else: self.graph.node[n]['velocity'] += dampdv self.graph.node[n]['actor'].props.fill_color_rgba = 0x33333380 self.graph.node[n]['velocity'] += force * massy # update positions for n in self.graph.node: if self.graph.node[n]['actor'] is not self.pin: self.graph.node[n]['position'] += self.graph.node[n]['velocity'] * self.stepsize if not self.pin: self.align() bs = self.scale * self.blobsize / 2. for n in self.graph.node: self.graph.node[n]['actor'].props.x = self.scale * self.graph.node[n]['position'][0] - self.left - bs self.graph.node[n]['actor'].props.y = self.scale * self.graph.node[n]['position'][1] - self.top - bs for m in self.graph[n]: if m > n: continue # overwriting the 'data' property directly leaks memory (bgo 669661) self.graph[n][m]['actor'].set_property('data', " ".join([ "M", str(self.graph.node[n]['actor'].props.x + bs), str(self.graph.node[n]['actor'].props.y + bs), "L", str(self.graph.node[m]['actor'].props.x + bs), str(self.graph.node[m]['actor'].props.y + bs)])) # reset every five hundred un-pinned frames self.frame += 1 if not self.pin: self.unpinnedframe += 1 if self.unpinnedframe == 500: elapsed = datetime.now() - self.last print self.frame / elapsed.total_seconds() self.create() return True
def __init__(self, fitness_function, convex_boundaries: list, spawn_position: vector = None): # Randomly spawning the particle according to the problem's convex boundaries. if spawn_position is None: self._position: vector = vector([ uniform(convex_boundaries[vector_space_dimension][0], convex_boundaries[vector_space_dimension][1]) for vector_space_dimension in range(len(convex_boundaries)) ]) if isinstance(spawn_position, ndarray): self._position: vector = spawn_position # The particle's first personal best _position is the _position where it is spawned. self._personal_best_position: vector = self._position # TODO # 1)Verify whether the velocities will have boundaries or not. # Will depend on algorithm used, e.g. Last-Eliminated Principle PSO. # 2) At which speeds is it a good idea to start the algorithm? With small initial speeds, the particles # will have a larger velocity, tending at the global optimum # self.__velocity: vector = vector([particle_position_and_velocity_initializer(0, 1) # for vector_space_dimension in range(len(spawn_boundaries))]) self.__velocity: vector = zeros( len(convex_boundaries)) # Initialize the particles as being still. Particle.fitness_function = fitness_function
def nearest(self, pos, radius=40): col = floor(pos[0] / self.resolution) row = floor(pos[1] / self.resolution) n = ceil(radius / self.resolution) + 1 arr = vector(range(2 * n + 1)) - n res = [] for i in arr: for j in arr: try: app = self.grid[col + i][row + j] res += app except IndexError: pass # print(len(res)) res1 = [] for other in res: if 0 < dist(pos, other.position) < radius: res1.append(other) # print(len(res1)) # print() return res1
def wander(self, d=50, r=25, change=0.5): center = normalize(self.velocity) * d + self.position self.theta += random() * 2 * change - change randrad = vector((sin(self.theta), cos(self.theta))) * r desired = center + randrad self.steer(desired - self.position)
def __init__(self, path, resolution=None): resolution = resolution or path.raduis / 1.5 super().__init__(resolution=resolution) for i in range(self.cols): for j in range(self.rows): center = vector((int((i + 0.5) * self.resolution), int((j + 0.5) * self.resolution))) self.field[i][j] = normalize(path.get_normal(center) - center) # * 0.2
def draw(self, scr): for i in range(self.cols): for j in range(self.rows): center = vector((int((i + 0.5) * self.resolution), int((j + 0.5) * self.resolution))) pygame.draw.circle(scr, (230, 230, 0), center, ceil(self.resolution / 5), 2) pygame.draw.line(scr, (230, 230, 0), center, center + self.field[i][j] * 20, 2)
def __init__(self, resolution=50): self.field = [] self.resolution = resolution self.cols = int(WIDTH / self.resolution) self.rows = int(HEIGHT / self.resolution) for i in range(self.cols): row = [] for j in range(self.rows): row.append(vector((10, 0))) self.field.append(row)
def cohese(self, vehicles): radius = self.size * 2 # sum_vel = vector((0.0, 0.0)) n = 0 for other in vehicles: sum_vel += other.position n += 1 if n > 0: sum_vel /= n # sum_vel = normalize(sum_vel) * self.maxspeed # self.steer(sum_vel) self.seek(sum_vel)
def align(self, vehicles): sum_vel = vector((0.0, 0.0)) n = 0 for other in vehicles: if other is not self: sum_vel += other.velocity n += 1 if n > 0: sum_vel /= n sum_vel = normalize(sum_vel) * self.maxspeed # print(self.velocity, sum_vel) self.steer(sum_vel)
def __init__(self, pos): spread = 1.0 self.position = pos self.velocity = np.array([random.uniform(-spread, spread), random.uniform(-spread, spread)]) self.acceleration = np.array([0.0, 0.0]) self.mover = None self.mass = 1.0 # self.mass = random.uniform(0.5, 2.0) self.radius = 5 * self.mass self.lifespan = 75 self.size = vector([random.random() * 10 + 10, random.random() * 5 + 5])
def separate(self, vehicles): radius = self.size * 2 sum_vel = vector((0.0, 0.0)) n = 0 for other in vehicles: d = dist(self.position, other.position) if 0 < d < radius: n += 1 diff = normalize(self.position - other.position) / d sum_vel += diff if n > 0: sum_vel /= n sum_vel = normalize(sum_vel) * self.maxspeed self.steer(sum_vel)
def select_vector_mode(vec,mode): """ Change given vector into given mode (default or global) If mode is the same as vector, do nothing. """ from numpy import array as vector from numpy import mod listvec=( type(vec)==type([]) ) if listvec and mode=='default': return vec elif not listvec and mode=='global': return vec elif listvec and mode=='global': x=list(vec[0]) for vec in vec[1:]: x=x+list(vec) return vector(x) elif not listvec and mode=='default': if mod(len(vec),3)!=0: raise AssertionError N=len(vec)/3 x=[] for i in range(N): x.append( vector(vec[i*3:i*3+3]) ) return x
def select_vector_mode(vec, mode): """ Change given vector into given mode (default or global) If mode is the same as vector, do nothing. """ from numpy import array as vector from numpy import mod listvec = (type(vec) == type([])) if listvec and mode == 'default': return vec elif not listvec and mode == 'global': return vec elif listvec and mode == 'global': x = list(vec[0]) for vec in vec[1:]: x = x + list(vec) return vector(x) elif not listvec and mode == 'default': if mod(len(vec), 3) != 0: raise AssertionError N = len(vec) / 3 x = [] for i in range(N): x.append(vector(vec[i * 3:i * 3 + 3])) return x
def rhs(xx, uu): """ Right hand side of the vectorfield defining the system dynamics :param xx: state :param uu: input :param uuref: reference input (not used) :param t: time (not used) :param pp: additionial free parameters (not used) :return: xdot """ if isinstance(xx, np.ndarray): # Function should be evaluated numerically from numpy import sin, cos from numpy import array as vector else: # Evaluate function symbolically from sympy import sin, cos from sympy import Matrix as vector x1, x2, x3, x4 = xx u1, = uu m = 1.0 # masses of the rods [m1 = m2 = m] l = 0.5 # lengths of the rods [l1 = l2 = l] I = 1 / 3.0 * m * l**2 # moments of inertia [I1 = I2 = I] g = 9.81 # gravitational acceleration lc = l / 2.0 d11 = m * lc**2 + m * (l**2 + lc**2 + 2 * l * lc * cos(x1)) + 2 * I h1 = -m * l * lc * sin(x1) * (x2 * (x2 + 2 * x4)) d12 = m * (lc**2 + l * lc * cos(x1)) + I phi1 = (m * lc + m * l) * g * cos(x3) + m * lc * g * cos(x1 + x3) ff = vector([x2, u1, x4, -1 / d11 * (h1 + phi1 + d12 * u1)]) return ff
def estimate_x_and_u(F, N, m, E, d, v, u, z, y, x, spk_ids): """ F - matrix of first order statistics (not centered). The rows correspond to training segments. Number of columns is given by the supervector dimensionality. The first n collums correspond to the n dimensions of the first Gaussian component, the second n collums to second· component, and so on. N - matrix of zero order statistics (occupation counts of Gaussian components). The rows correspond to training segments. The collums correspond to Gaussian components. S - NOT USED by this function; reserved for second order statistics m - speaker and channel independent mean supervector (e.g. concatenated UBM mean vectors) E - speaker and channel independent variance supervector (e.g. concatenated UBM variance vectors) d - Row vector that is the diagonal from the diagonal matrix describing the remaining speaker variability (not described by eigenvoices). Number of columns is given by the supervector dimensionality. v - The rows of matrix v are 'eigenvoices'. (The number of rows must be the same as the number of columns of matrix y). Number of columns is given by the supervector dimensionality. u - The rows of matrix u are 'eigenchannels'. (The number of rows must be the same as the number of columns of matrix x) Number of columns is given by the supervector dimensionality. y - matrix of speaker factors corresponding to eigenvoices. The rows correspond to speakers (values in vector spk_ids are the indices of the rows, therfore the number of the rows must be (at least) the highest value in spk_ids). The columns correspond to eigenvoices (The number of columns must the same as the number of rows of matrix v). z - matrix of speaker factors corresponding to matrix d. The rows correspond to speakers (values in vector spk_ids are the indices of the rows, therfore the number of the rows must be (at least) the highest value in spk_ids). Number of columns is given by the supervector· dimensionality. x - NOT USED by this function; used by other JFA function as matrix of channel factors. The rows correspond to training segments. The columns correspond to eigenchannels (The number of columns must be the same as the number of rows of matrix u) spk_ids - column vector with rows corresponding to training segments and integer values identifying a speaker. Rows having same values identifies segments spoken by same speakers. The values are indices of rows in y and z matrices containing corresponding speaker factors. """ T, C = N.shape T, CD = F.shape assert CD % C == 0 assert N.shape[0] == F.shape[0] == spk_ids.shape[0] == x.shape[0] assert m.shape[0] == F.shape[1] == E.shape[0] == d.shape[0] == v.shape[1] == u.shape[1] == z.shape[1] D = CD / C ru, _ = v.shape rv, _ = u.shape assert y.shape[1] == rv and x.shape[1] == ru assert y.shape[0] == z.shape[0] Nspk, _ = z.shape uEut = np.empty((C, ru, rv)) # blitz::firstIndex i; # blitz::secondIndex j; tmp1 = np.empty((ru, D)) # for(int c=0; c<C; ++c) for c in range(C): # blitz::Array<double,2> uEuT_c = uEuT(c, blitz::Range::all(), blitz::Range::all()); uEut_c = uEut[c] # blitz::Array<double,2> u_elements = u(blitz::Range::all(), blitz::Range(c*D, (c+1)*D-1)); u_elements = u[:, c*D: (c+1)*D-1 ] # blitz::Array<double,1> e_elements = E(blitz::Range(c*D, (c+1)*D-1)); e_elements = E[c*D: (c+1)*D-1] # tmp1 = u_elements(i,j) / e_elements(j); for i in range(C): for j in range(ru): tmp1 = u_elements[i, j] / e_elements[j] # blitz::Array<double,2> u_transposed = u_elements.transpose(1,0); u_transposed = u_elements.transpose(1, 0) # math::prod(tmp1, u_transposed, uEuT_c); np.prod(tmp1, u_transposed, uEut_c) #} # // 3/ Determine the vector of speaker ids # // Assume that samples from the same speaker are consecutive # std::vector<uint32_t> ids; ids = np.vector(type=np.uint32_t) last_elem = 0 for ind in range(T): if ids.empty(): ids.push_back(spk_ids(ind)) last_elem = spk_ids(ind) elif last_elem != spk_ids(ind): ids.push_back(spk_ids(ind)) last_elem = spk_ids(ind) # // 4/ Main computation # // Allocate working arrays spk_shift = np.empty(CD, dtype='double') tmp2 = np.empty(CD, dtype='double') tmp3 = np.empty(ru, dtype='double') Fh = np.empty(CD, dtype='double') L = np.empty((ru, ru), dtype='double') Linv = np.empty((ru, ru), dtype='double') # std::vector<uint32_t>::iterator it; it = iter cur_start_ind = 0 # int cur_end_ind; pass # for(it=ids.begin(); it<ids.end(); ++it) for id in enumerate(ids): # // a/ Determine speaker sessions # uint32_t cur_elem=*it; cur_elem = id(iter) cur_start_ind = 0 while spk_ids(cur_start_ind) != cur_elem: cur_start_ind += 1 cur_end_ind = cur_start_ind for ind in range(cur_start_ind+1, T): cur_end_ind = ind if spk_ids(ind) != cur_elem: cur_end_ind = ind - 1 break # // b/ Compute speaker shift spk_shift = m y_ii = y[cur_elem] math.prod(y_ii, v, tmp2) spk_shift += tmp2 z_ii = z[cur_elem] spk_shift += z_ii * d # // c/ Loop over speaker session # for(int jj=cur_start_ind; jj<=cur_end_ind; ++jj) for jj in range(cur_start_ind, cur_end_ind): # blitz::Array<double,1> Nhint = N(jj, blitz::Range::all()); Nhint = N[jj] core.repelem(Nhint, tmp2) Fh = F[jj] - tmp2 * spk_shift # // L=Identity L.set_everything_to(0.) for k in range(ru): L[k, k] = 1. for c in range(C): uEuT_c = uEut[c] L += uEuT_c * N[jj, c] # // inverse L np.invert(L, Linv) # // update x x_jj = x[jj] Fh /= E print ("WTF IS the next line") uu = u[:, :] for i in range(10): print ("WTF happened") raise Exception("WTFFF") u_t = uu.transpose(1, 0) tmp3 = Fh * u_t x_jj = tmp3 * Linv return x, u
def f(t, x): S, E, I, R = x return vector([ -beta * S * I, beta * S * I - a * E, a * E - gamma * I, gamma * I ])
def Main(): global FACE_CASCADE, EYE_CASCADE, MOUTH_CASCADE, NOSE_CASCADE, camera, blobMaker, mouse, facePresent, mouthWidth, nosePosition, distanceMouthNose, gaze, mouseMoveData, actionTriggered, clickRegistered # Event loop while True: time.sleep( 0.1 ) image = camera.getImage() try: face = image.findHaarFeatures( FACE_CASCADE )[0] except: facePresent = False continue try: # N.B. The enemy's gate is down (greater Y implies lower position on image) eye = image.findHaarFeatures( EYE_CASCADE )[0] mouth = image.findHaarFeatures( MOUTH_CASCADE )[0] nose = image.findHaarFeatures( NOSE_CASCADE )[0] pupil = Pupil( image ) print pupil newMouthWidth = mouth.width() newNosePosition = nose.y newDistanceMouthNose = mouth.maxY() - nose.minY() newGaze = vector( eye.coordinates() ) - vector( pupil.coordinates()[0] ) except: facePresent = False continue if( facePresent is True ): print 'face.width: ' + str(face.width()) print 'mouth.width: ' + str(mouth.width()) print 'nose.y: ' + str(nose.y) print 'newMouthWidth: ' + str(newMouthWidth) print 'newNosePosition: ' + str(newNosePosition) print 'newDistanceMouthNose: ' + str(newDistanceMouthNose) # Enters mouse action decision tree if and only if mouth is puckered if( GreaterThan(mouthWidth, newMouthWidth, .01) is False ): mouseMoveData = None actionTriggered = False clickRegistered = False continue elif( actionTriggered is False ): # Secondary calibration each time mouth puckers actionTriggered = True nosePosition = newNosePosition distanceMouthNose = newDistanceMouthNose gaze = newGaze continue print 'pucker' if( mouseMoveData is not None ): Move() clickRegistered = False elif( GreaterThan(nosePosition, newNosePosition, .10, image.height) is True ): ScrollDown() clickRegistered = False elif( GreaterThan(newNosePosition, nosePosition, .10, image.height) is True ): ScrollUp() clickRegistered = False elif( GreaterThan(distanceMouthNose, newDistanceMouthNose, .05) is True and clickRegistered is False ): LeftClick() clickRegistered = True elif( GreaterThan(newDistanceMouthNose, distanceMouthNose, .05) is True and clickRegistered is False ): RightClick() clickRegistered = True else: Move( gaze, newGaze ) clickRegistered = False else: # Primary calibration each time face (re)appears facePresent = True mouthWidth = newMouthWidth mouseMoveData = None actionTriggered = False clickRegistered = False
self.particles.remove(particle) def run(self, c): self.update() self.draw(c) def apply(self, force): for particle in self.particles: particle.apply(force) screen = pygame.display.set_mode((WIDTH, HEIGHT)) done = False clock = pygame.time.Clock() ps = ParticleSystem(vector([WIDTH / 2, 50])) def main(): global ps screen.fill(WHITE) ps.run(screen) for system in pss: system.run(screen) gravity = np.array([0, 0.1]) ps.apply(gravity) for system in pss: system.apply(gravity)
def SEIR_simulation(beta, gamma, a, E0, I0, days, step=0.1): x0 = vector([1.0 - E0 - I0, E0, I0, 0.0]) return euler_method(SEIR_model(beta, gamma, a), 0, x0, days, step)
def read_from_csv_file(self, filename): print("Parse data from CSV file " + filename + " ...") with open(filename, encoding='utf-8-sig') as csv_file: csv_reader = csv.reader(csv_file, delimiter=";") nr_of_given_tracing_data = 0 for row in csv_reader: if row[0] == "N_total": N_total = int(float(row[1].replace(",", "."))) assert (N_total > 0) elif row[0] == "K": K = int(float(row[1].replace(",", "."))) assert (K > 0) elif row[0] == "N": N = vector(self._to_float(row[1:1 + K])) assert (sum(N) == N_total) assert (len(N) == K) elif row[0] == "beta_asym": beta_asym = matrix(vector(self._to_float( row[1:1 + K * K]))).reshape((K, K)) elif row[0] == "beta_sym": beta_sym = matrix(vector(self._to_float( row[1:1 + K * K]))).reshape((K, K)) elif row[0] == "beta_sev": beta_sev = matrix(vector(self._to_float( row[1:1 + K * K]))).reshape((K, K)) elif row[0] == "epsilon": epsilon = vector(self._to_float(row[1:1 + K])) assert (len(epsilon) == K) elif row[0] == "eta": eta = vector(self._to_float(row[1:1 + K])) assert (len(eta) == K) elif row[0] == "nu": nu = vector(self._to_float(row[1:1 + K])) assert (len(nu) == K) elif row[0] == "sigma": sigma = vector(self._to_float(row[1:1 + K])) assert (len(sigma) == K) elif row[0] == "gamma_asym": gamma_asym = float(row[1].replace(",", ".")) elif row[0] == "gamma_sym": gamma_sym = vector(self._to_float(row[1:1 + K])) assert (len(gamma_sym) == K) elif row[0] == "gamma_sev_d_hat": gamma_sev_d_hat = vector(self._to_float(row[1:1 + K])) assert (len(gamma_sev_d_hat) == K) elif row[0] == "gamma_sev_r_hat": gamma_sev_r_hat = vector(self._to_float(row[1:1 + K])) assert (len(gamma_sev_r_hat) == K) elif row[0] == "psi": psi = vector(self._to_float(row[1:1 + K])) assert (len(psi) == K) nr_of_given_tracing_data += 1 elif row[0] == "beds": beds = float(row[1].replace(",", ".")) assert (beds > 0) elif row[0] == "S": S = vector(self._to_float(row[1:1 + K])) assert (len(S) == K) elif row[0] == "E": E = vector(self._to_float(row[1:1 + K])) assert (len(E) == K) elif row[0] == "E_T": E_tracked = vector(self._to_float(row[1:1 + K])) assert (len(E_tracked) == K) nr_of_given_tracing_data += 1 elif row[0] == "I_asym": I_asym = vector(self._to_float(row[1:1 + K])) assert (len(I_asym) == K) elif row[0] == "I_sym": I_sym = vector(self._to_float(row[1:1 + K])) assert (len(I_sym) == K) elif row[0] == "I_sev": I_sev = vector(self._to_float(row[1:1 + K])) assert (len(I_sev) == K) elif row[0] == "Q_asym": Q_asym = vector(self._to_float(row[1:1 + K])) assert (len(Q_asym) == K) nr_of_given_tracing_data += 1 elif row[0] == "Q_sym": Q_sym = vector(self._to_float(row[1:1 + K])) assert (len(Q_sym) == K) nr_of_given_tracing_data += 1 elif row[0] == "Q_sev": Q_sev = vector(self._to_float(row[1:1 + K])) assert (len(Q_sev) == K) nr_of_given_tracing_data += 1 elif row[0] == "R": R = vector(self._to_float(row[1:1 + K])) assert (len(R) == K) elif row[0] == "D": D = vector(self._to_float(row[1:1 + K])) assert (len(D) == K) else: print("Unknown data field: " + str(row[0])) assert (False) tracing_data_given = (nr_of_given_tracing_data >= 1) if tracing_data_given: assert (nr_of_given_tracing_data == 5) x0_total = np.concatenate((S, E, E_tracked, I_asym, I_sym, I_sev, Q_asym, Q_sym, Q_sev, R, D)) assert (sum(S) + sum(E) + sum(E_tracked) + sum(I_asym) + sum(I_sym) + sum(I_sev) + sum(Q_asym) + sum(Q_sym) + sum(Q_sev) + sum(R) + sum(D) == N_total) x0_share = vector([x / N_total for x in x0_total]) assert (x0_total.shape[0] == 11 * K) assert (x0_share.shape[0] == 11 * K) packed_data = [ tracing_data_given, K, N, beta_asym, beta_sym, beta_sev, epsilon, eta, nu, sigma, gamma_asym, gamma_sym, gamma_sev_d_hat, gamma_sev_r_hat, psi, beds, x0_total ] else: assert (nr_of_given_tracing_data == 0) x0_total = np.concatenate((S, E, I_asym, I_sym, I_sev, R, D)) assert (sum(S) + sum(E) + sum(I_asym) + sum(I_sym) + sum(I_sev) + sum(R) + sum(D) == N_total) x0_share = vector([x / N_total for x in x0_total]) assert (x0_total.shape[0] == 7 * K) assert (x0_share.shape[0] == 7 * K) packed_data = [ tracing_data_given, K, N, beta_asym, beta_sym, beta_sev, epsilon, eta, nu, sigma, gamma_asym, gamma_sym, gamma_sev_d_hat, gamma_sev_r_hat, beds, x0_total ] return packed_data
def coordinates_n_angstroms_away_from(atom: Atom, n: float) -> Optional[Tuple[float, float, float]]: if atom.coordinates is None: return None else: random_vector = uniform(-1, 1, 3) return tuple((vector(atom.coordinates) + random_vector / norm(random_vector) * n).tolist())
def createVector(x, y): ''' Return a new vector ''' return vector([x, y], dtype=np.float64)
def __init__(self, x, y): self.pos = vector([x, y]) self.vel = vector([1, -1])
def createVector(x, y): ''' Return a new vector ''' return vector([x, y])
def centre(self): for n in self.graph.node: self.graph.node[n]['position'] = vector([0., 0.]) self.graph.node[n]['velocity'] = vector([0., 0.])
def read_from_csv_file(self, filename, print_data=False): print("Parse data from CSV file " + filename + " ...") with open(filename) as csv_file: csv_reader = csv.reader(csv_file, delimiter=";") nr_of_given_tracing_data = 0 beta_asym_rows = [] beta_sym_rows = [] beta_sev_rows = [] for row in csv_reader: if row[0] == "\ufeffN_total": # todo What the heck?! N_total = int(float(row[1].replace(",", "."))) assert (N_total > 0) elif row[0] == "K": K = int(float(row[1].replace(",", "."))) assert (K > 0) elif row[0] == "Group_labels": pass # todo maybe use later for plots elif row[0] == "N": N = vector(self._to_float(row[1:1 + K])) assert (sum(N) == N_total) assert (len(N) == K) elif row[0] == "beta_asym": beta_asym_rows.append(vector(self._to_float(row[1:1 + K]))) elif row[0] == "beta_sym": beta_sym_rows.append(vector(self._to_float(row[1:1 + K]))) elif row[0] == "beta_sev": beta_sev_rows.append(vector(self._to_float(row[1:1 + K]))) elif row[0] == "epsilon": epsilon = vector(self._to_float(row[1:1 + K])) assert (len(epsilon) == K) elif row[0] == "eta": eta = vector(self._to_float(row[1:1 + K])) assert (len(eta) == K) elif row[0] == "nu": nu = vector(self._to_float(row[1:1 + K])) assert (len(nu) == K) elif row[0] == "sigma": sigma = vector(self._to_float(row[1:1 + K])) assert (len(sigma) == K) elif row[0] == "psi": psi = vector(self._to_float(row[1:1 + K])) assert (len(psi) == K) nr_of_given_tracing_data += 1 elif row[0] == "gamma_asym": gamma_asym = float(row[1].replace(",", ".")) elif row[0] == "gamma_sym": gamma_sym = vector(self._to_float(row[1:1 + K])) assert (len(gamma_sym) == K) elif row[0] == "gamma_sev_d_hat": gamma_sev_d_hat = vector(self._to_float(row[1:1 + K])) assert (len(gamma_sev_d_hat) == K) elif row[0] == "gamma_sev_r_hat": gamma_sev_r_hat = vector(self._to_float(row[1:1 + K])) assert (len(gamma_sev_r_hat) == K) elif row[0] == "beds": beds = float(row[1].replace(",", ".")) assert (beds > 0) elif row[0] == "S": S = vector(self._to_float(row[1:1 + K])) assert (len(S) == K) elif row[0] == "E": E = vector(self._to_float(row[1:1 + K])) assert (len(E) == K) elif row[0] == "E_T": E_tracked = vector(self._to_float(row[1:1 + K])) assert (len(E_tracked) == K) nr_of_given_tracing_data += 1 elif row[0] == "I_asym": I_asym = vector(self._to_float(row[1:1 + K])) assert (len(I_asym) == K) elif row[0] == "I_sym": I_sym = vector(self._to_float(row[1:1 + K])) assert (len(I_sym) == K) elif row[0] == "I_sev": I_sev = vector(self._to_float(row[1:1 + K])) assert (len(I_sev) == K) elif row[0] == "Q_asym": Q_asym = vector(self._to_float(row[1:1 + K])) assert (len(Q_asym) == K) nr_of_given_tracing_data += 1 elif row[0] == "Q_sym": Q_sym = vector(self._to_float(row[1:1 + K])) assert (len(Q_sym) == K) nr_of_given_tracing_data += 1 elif row[0] == "Q_sev": Q_sev = vector(self._to_float(row[1:1 + K])) assert (len(Q_sev) == K) nr_of_given_tracing_data += 1 elif row[0] == "R": R = vector(self._to_float(row[1:1 + K])) assert (len(R) == K) elif row[0] == "D": D = vector(self._to_float(row[1:1 + K])) assert (len(D) == K) else: print("Unknown data field: " + str(row[0])) assert (False) beta_asym = self._parse_symmetric_matrix(beta_asym_rows, K) beta_sym = self._parse_symmetric_matrix(beta_sym_rows, K) beta_sev = self._parse_symmetric_matrix(beta_sev_rows, K) numerical_tolerance = 1e-12 tracing_data_given = (nr_of_given_tracing_data >= 1) if tracing_data_given: assert (nr_of_given_tracing_data == 5) x0_total = np.concatenate((S, E, E_tracked, I_asym, I_sym, I_sev, Q_asym, Q_sym, Q_sev, R, D)) assert (abs(sum(x0_total) - N_total) < numerical_tolerance) x0_share = vector([x / N_total for x in x0_total]) assert (x0_total.shape[0] == 11 * K) assert (x0_share.shape[0] == 11 * K) if print_data: self._print_all_data(tracing_data_given, N_total, K, N, beta_asym, beta_sym, beta_sev, epsilon, eta, nu, sigma, gamma_asym, gamma_sym, gamma_sev_d_hat, gamma_sev_r_hat, psi, beds, x0_total) packed_data = [ tracing_data_given, K, N, beta_asym, beta_sym, beta_sev, epsilon, eta, nu, sigma, gamma_asym, gamma_sym, gamma_sev_d_hat, gamma_sev_r_hat, psi, beds, x0_total ] else: assert (nr_of_given_tracing_data == 0) x0_total = np.concatenate((S, E, I_asym, I_sym, I_sev, R, D)) x0_share = vector([x / N_total for x in x0_total]) assert (abs(sum(x0_total) - N_total) < numerical_tolerance) assert (x0_total.shape[0] == 7 * K) assert (x0_share.shape[0] == 7 * K) packed_data = [ tracing_data_given, K, N, beta_asym, beta_sym, beta_sev, epsilon, eta, nu, sigma, gamma_asym, gamma_sym, gamma_sev_d_hat, gamma_sev_r_hat, beds, x0_total ] return packed_data
def add_point(self, x, y): self.points.append(vector((int(x), int(y))))
''' Walker program to draw a path that moves in random directions using vectors ''' import random import pyglet from pyglet.shapes import Rectangle from numpy import array as vector window = pyglet.window.Window(1080, 768) main_batch = pyglet.graphics.Batch() pos = vector([window.width // 2, window.height // 2]) def update(dt): global pos pos[0] += (random.randrange(3) - 1) # range -1 through 1 pos[1] += (random.randrange(3) - 1) # range -1 through 1 @window.event def on_draw(): global pos #window.clear() #main_batch.draw() rec = Rectangle(pos[0], pos[1], 1, 1) rec.draw()