def dice_coefficient_np(y_true, y_pred, smooth=1): y_true_f = np.flatten(y_true) y_pred_f = np.flatten(y_pred) intersection = np.sum(y_true_f * y_pred_f) dice = (2 * intersection + smooth) / (np.sum(y_true_f) + np.sum(y_pred_f) + smooth) return dice
def ss_rotate(self, shape, x_ang, y_ang, z_ang): Rx = np.matrix([[1,0,0], [0, np.cos(x_ang), -np.sin(x_ang)], [0,np.sin(x_ang), np.cos(x_ang)]]) Ry = np.matrix([[np.cos(y_ang), 0, np.sin(y_ang)], [0,1,0], [-np.sin(y_ang), 0, np.cos(y_ang)]]) Rz = np.matrix([[np.cos(z_ang), -np.sin(z_ang), 0], [np.sin(z_ang),np.cos(z_ang), 0], [0,0,1]]) Rtotal = Rx*Ry*Rz test = np.matrix([[a.x], [a.y],[a.z]]) New = Rtotal*test New= np.flatten(New) shape.x = New[0] shape.y = New[1] shape.z = New[2] #For Theta Phi Rotations if shape == ori_cylinder: x = 1 z = 1/(np.tan(a.theta)) y = np.tan(a.phi) temp = np.matrix([[x],[y],[a.z]]) New = Rtotal*temp New = np.flatten(New) shape.theta = np.arctan(New[0]/New[2]) shape.phi = np.arctan(New[1]/New[0]) #For x_ang, y_ang, z_ang Rotations if shape == paralellpiped: shape.x_ang = shape.x_ang + x_ang shape.y_ang = shape.y_ang + y_ang shape.z_ang = shape.z_ang + z_ang
def constrain2(self, del_phi1, del_phi2): # Revert positions and forces to time prior to BXD inversion self.currentPos = self.oldPos self.currentVel = self.oldVel self.forces = self.oldForces # Temporarily flatten 3 by n matrices into vectors to get dot products. a = ((np.tile(self.masses, (3, 1))).transpose()).flatten() b = np.flatten(del_phi1) c = np.flatten(del_phi2) d = np.flatten(self.currentVel) # In the two constraint case the simulataneous equations can be solved analytically. This should be gneralised in the future # Here we save the various coefficients from the various permuations of dot products containing the two constraints c1 = np.vdot(b, (b * (1 / a))) c2 = np.vdot(b, (c * (1 / a))) c3 = np.vdot(c, (b * (1 / a))) c4 = np.vdot(c, (c * (1 / a))) c5 = np.vdot(b, d) c6 = np.vdot(c, d) lamb2 = ((c3 * c4) - (c1 * c6)) / ((c2 * c3) - (c1 * c4)) lamb1 = (c3 - lamb2 * c2) / c1 # Update velocities self.currentVel = self.currentVel + (lamb1 * del_phi1 * (1 / self.masses[:, None])) + ( lamb2 * del_phi2 * (1 / self.masses[:, None])) self.constrained = True
def treepars_to_array(treepars): """ Flattens cut_vals and tree_ids for optimizer """ cuts = np.flatten(treepars.cut_vals) ids = np.flatten(treepars.tree_ids) arr = np.concatenate((cuts, ids)) return(arr)
def dice_coeff_hard_np(y_true, y_pred): smooth = 1. y_true_f = np.flatten(y_true) y_pred_f = np.round(np.flatten(y_pred)) intersection = np.sum(y_true_f * y_pred_f) score = (2. * intersection + smooth) / (np.sum(y_true_f) + np.sum(y_pred_f) + smooth) return score
def d(x, y, dist="ones", mask_ratio=0.04, same_mask=False, func="mse"): x = np.flatten(x) y = np.flatten(y) x_shape = x.shape[0] y_shape = y.shape[0] resizing = False if x_shape < y_shape: big_shape = y_shape size = x_shape resizing = "y" if y_shape < x_shape: big_shape = x_shape size = y_shape resizing = "x" y = np.expand_dims(y, 1) x = np.expand_dims(x, 1) # we resize the bigger array to the smaller size if resizing is not False: if dist == "uniform": resize = np.random.uniform(shape=(size, big_shape)) if dist == "normal": resize = np.random.normal(shape=(size, big_shape)) if dist == "ones": resize = np.ones(shape=(size, big_shape)) if resizing == "y": y = np.dot(resize, y) if resizing == "x": x = np.dot(resize, x) # we mask x and y (dropout) if mask_ratio != 0: x_mask = np.random.choice([0, 1], x.shape[0], p=[mask_ratio, 1 - mask_ratio]) if not same_mask: y_mask = np.random.choice([0, 1], y.shape[0], p=[mask_ratio, 1 - mask_ratio]) if same_mask: y_mask = x_mask x = np.multiply(x, x_mask) y = np.multiply(y, y_mask) if func == "mpse": distance = tf.losses.mean_pairwise_squared_error(x, y) if func == "mse": distance = tf.losses.mean_squared_error(x, y) if func == "abs": distance = tf.losses.absolute_distance(x, y) return distance
def act(self, thrust): self._update_state(thrust) state_matrix = np.flatten([self.state["position"], self.state["motion"], self.state["planet_size"]]) reward = self._get_reward() game_over = self._game_over() return state_matrix, reward, game_over
def mul(x, y, pub): """ return the result of x * s (sematic of "*" explained in numpy) x: numpy array of PaillierEncryptedNumber y: numpy array of FixedPointNumber """ x_shape = x.shape y_shape = y.shape if x_shape == y_shape: x_flatten = np.flatten(x) y_flatten = np.flatten(y) res = paillier_gpu.mul_impl(x_flatten, y_flatten) return np.reshape(res, x_shape) else: brd_x, brd_y = brdcst(x, y) return mul(brd_x, brd_y, pub)
def int_array_factory(I): if I is None: return None I = np.asarray(I) if I.ndim > 1: I = np.flatten(I) return np.require(I, dtype=np.int32, requirements=['A', 'O', 'C'])
def observe(self): if self.absolute: raise NotImplementedError() else: # Add nearby traffic self.grid.fill(0) df = pandas.DataFrame.from_records([ v.to_dict(self.env.vehicle) for v in self.env.road.vehicles if v is not self.env.vehicle ]) # Normalize df = self.normalize(df) # Fill-in features for layer, feature in enumerate(self.features): for _, vehicle in df.iterrows(): cell = (int((vehicle["x"] - self.grid_size[0, 0]) / self.grid_step[0]), int((vehicle["y"] - self.grid_size[1, 0]) / self.grid_step[1])) if 0 <= cell[1] < self.grid.shape[-2] and 0 <= cell[ 0] < self.grid.shape[-1]: self.grid[layer, cell[1], cell[0]] = vehicle[feature] # Flatten obs = np.stack( np.flatten(self.grid), np.array(self.env.vehicle.velocity / MDPVehicle.SPEED_MAX)) # Clip obs = np.clip(obs, -1, 1) return obs
def flatten(A): """ Flatten a shapeable quantity Parameters ---------- A : Poly, frac, array_like Shapeable input quantity Returns ------- Q : Poly, frac, array_like Same type as `A` with `len(Q.shape)==1` Examples -------- >>> P = cp.reshape(cp.prange(4), (2,2)) >>> print P [[1, q0], [q0^2, q0^3]] >>> print cp.flatten(P) [1, q0, q0^2, q0^3] """ if isinstance(A, (np.ndarray, float, int, long)): return np.flatten(A) elif isinstance(A, f.frac): return f.flatten(A) elif isinstance(A, p.Poly): return p.flatten(A) raise NotImplementedError
def _execute(self, x): # Sortie y = np.array([]) # Vérifie les données if x.shape[1] != 1: raise InvalidDigitNumber("Nombre de digits en entrée invalide") if x.shape[0] % self.entrySize != 0: raise InvalidTimeserie("Séries temporelles en entrées invalide, taille multiple de {} attendue".format(self.entrySize)) # Pour chaque partie des séries correspondante à un digit for i in np.arange(0, x.shape[0], self.entrySize): # Le début et la fin de la partie à examiner start = i + int(self.imagesSize * self.digitImageRatio) end = i + self.entrySize + int(self.interImagesRatio * self.interImagesSpace) # Résultat average = int(round(np.average(np.flatten(x[start:end])))) # Inscrit le vainqueur y = np.append(y, average) # Renvoi le résultat return (y, x[0:self.analyzeSampling*self.entrySize,:])
def shot_frame_clustering(diff_values): """ diff_values here is for the entire sequence of frames. has shape (N-1, ) where N is total number of frames """ delta = 5 d = 1 i = 1 clusters = [] clusters.append([diff_values[0]]) i += 1 cont_val = frame_continuity_value(diff_values) while i < len(diff_values): if diff_values[i] < 5: clusters[d] = np.append(clusters[d], i) elif len(clusters[d]) == 1: clusters[d - 1] = np.append(clusters[d - 1], i) elif len(clusters[d]) > 1 and len(clusters[d]) < 5: l = clusters[d - i][len(clusters[d - 1]) - 1] f = clusters[d][0] s = clusters[d][1] if (diff_values[f] - diff_values[l]) - (diff_values[f] - diff_values[s]) < 0.5*delta: clusters[d - 1] = np.append(clusters[d], clusters[d - 1]) clusters[d - 1] = np.flatten(clusters[d - 1]) clusters[d] = np.delete(clusters, d) else: d += 1 i += 1 return clusters
def test_mddd(): from diagram.diagram import MTxDD mtqdd = MTxDD(3) # mat1 = np.array([[1, 7, 0]], dtype=float) # mat1 = np.array([[1, 7, 0], [0, -1, 0], [2, 8, 1], [1, 5, 0], [1, 5, 0], [1, 5, 0], [1, 15, 0]], dtype=float) # mat1 = np.random.random((3, 4)) np.random.seed(0) a = (729, 243) mat1 = np.flatten(np.random.random(a)) # mat2 = np.random.random(a) # x3gf1 = np.array([[1, 0, 0], [0, 2, 1], [2, 2, 2]]) # x3gfn = kronecker_expansion(x3gf1, target_mat=mat2) # mat1 = np.dot(mat2, x3gfn) print 'Reference:' print 'Complexity: ' + str(np.prod(mat1.shape)) # print mat1 print 'Result:' diagram1 = mtqdd.create(mat1, 0, False) # print diagram1.to_matrix(7, True) print 'Complexity: ' + str(diagram1.complexity()) print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' print 'Reduced:' mtqdd.reduce(diagram1) # import code; code.interact(local=dict(locals().items() + globals().items())) # print diagram1.to_matrix(7, True) print 'Complexity: ' + str(diagram1.complexity()) print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' print 'Reduced and lossy:' diagram2 = mtqdd.create(mat1, 0, True, dec_digits=2) # print diagram2.to_matrix(7, True) print 'Complexity: ' + str(diagram2.complexity())
def _p(self, K, c): """ The reduced dimensionless fourier-transform of the profile This function should not need to be called by the user in general. Parameters ---------- K : float or array_like The unit-less wavenumber k*r_s c : float or array_like The concentration .. note :: This should be replaced by an analytic function if possible """ c = np.atleast_1d(c) if K.ndim < 2: if len(K) != len(c): K = np.atleast_2d(K).T # should be len(rs) x len(k) else: K = np.atleast_2d(K) minsteps = 100 # if len(c)>50: # C = np.linspace(c.min(),c.max(),50) # else: # C = c # if K.size > 100: kk = np.logspace(np.log10(K.min()), np.log10(K.max()), 100) else: kk = np.sort(np.flatten(K)) res = np.zeros_like(K) intermediate_res = np.zeros((len(kk), len(c))) for ik, kappa in enumerate(kk): smallest_period = np.pi / kappa dx = smallest_period / 5 nsteps = max(int(np.ceil(c.max() / dx)), minsteps) x, dx = np.linspace(0, c.max(), nsteps, retstep=True) spl = spline(x, x * self._f(x) * np.sin(kappa * x) / kappa) intg = spl.antiderivative() intermediate_res[ik, :] = intg(c) - intg(0) for ic, cc in enumerate(c): #print intermediate_res.shape, kk.shape, res.shape # For high K, intermediate_res can be negative, so we mask that. mask = intermediate_res[:, ic] > 0 spl = spline(np.log(kk[mask]), np.log(intermediate_res[mask, ic]), k=1) res[:, ic] = np.exp(spl(np.log(K[:, ic]))) return res
def sensitivity_profile(self,observable,parameter): position = self.overall_index[2].index(observable) position_param = self.overall_index[1].index(parameter) sens = self.sensitivities[:,position_param,position] independentVar = np.asarray(self.overall_index[0]) sens = np.flatten(sens) return np.vstack((independentVar,sens))
def flatten(A): """ Flatten a shapeable quantity. Args: A (Poly, frac, array_like) : Shapeable input quantity. Returns: (Poly, frac, array_like) : Same type as `A` with `len(Q.shape)==1`. Examples: >>> P = cp.reshape(cp.prange(4), (2,2)) >>> print(P) [[1, q0], [q0^2, q0^3]] >>> print(cp.flatten(P)) [1, q0, q0^2, q0^3] """ if isinstance(A, (np.ndarray, float, int)): return np.flatten(A) elif isinstance(A, f.frac): return f.flatten(A) elif isinstance(A, p.Poly): return p.flatten(A) raise NotImplementedError
def solve_for_prior_normalization(self, inv_Cyy, inv_Cf, A, inv_A, R_real, datamap, print_alpha): N = R_real.shape[1] #from numpy.linalg import inv alpha = N / (np.trace(np.dot(inv_A, inv_Cf)) + np.dot( datamap.T, np.dot( inv_Cyy, np.dot( R_real, np.dot( inv_A, np.dot( inv_Cf, np.dot(inv_A, np.dot(R_real.T, np.dot(inv_Cyy, datamap))))))))) if print_alpha is 1: alpha_towrite = np.flatten(alpha)[0] outfile = 'alpha_lmax' + str( Multiverse.truncated_lmax) + 'lmin' + str( Multiverse.truncated_lmin) + 'nmax' + str( Multiverse.truncated_nmax) + 'nmin' + str( Multiverse.truncated_nmin) + '.txt' f = open('RobustnessAnalysis/' + outfile, 'a') towrite = str(alpha_towrite) + "\n" f.write(towrite) f.close() return alpha * inv_Cf
def fit_constrained(self, Y): # NOTE: this method fails because of a memory error in forming P n_samples = Y.shape[1] C, s, V = la.svd(Y, full_matrices=False) Z = s*V.T num_conditions = 0 P = matrix(np.kron(np.eye(self.n_dim_obs),Y[:,0:-1].dot(Y[:,0:-1].T))) q = matrix(np.flatten(Y[:,0:-1].dot(Y[:,1:].T))) sol = solvers.qp(P,q) A = np.reshape(sol['x'], (self.n_dim_state,self.n_dim_state)) rho = np.max(la.eigvals(A)) while rho > 1: num_conditions += 1 U,s,V = la.svd(A, full_matrices=False) Gold = G G = np.zeros(num_conditions, self.n_dim_state**2) G[0:-1,:] = Gold G[-1,:] = np.dot(U[:,0], V[:,0].T) h = matrix(np.ones(num_conditions)) sol = solvers.qp(P,q,matrix(G),h) A = np.reshape(sol['x'], (self.n_dim_state,self.n_dim_state)) rho = np.max(la.eigvals(A))
def __init__(self, u): s = u.shape if len(s) == 3 and s[0] == s[1] and s[1] == s[2]: self.m = int(s[0]) self.u = np.flatten(u, order='C') else: self.m = int(np.cbrt(s[0])) self.u = u
def _p(self, K, c): """ The reduced dimensionless fourier-transform of the profile This function should not need to be called by the user in general. Parameters ---------- K : float or array_like The unit-less wavenumber k*r_s c : float or array_like The concentration .. note :: This should be replaced by an analytic function if possible """ c = np.atleast_1d(c) if K.ndim < 2: if len(K)!=len(c): K = np.atleast_2d(K).T # should be len(rs) x len(k) else: K = np.atleast_2d(K) minsteps = 100 # if len(c)>50: # C = np.linspace(c.min(),c.max(),50) # else: # C = c # if K.size > 100: kk = np.logspace(np.log10(K.min()),np.log10(K.max()),100) else: kk = np.sort(np.flatten(K)) res = np.zeros_like(K) intermediate_res = np.zeros((len(kk),len(c))) for ik, kappa in enumerate(kk): smallest_period = np.pi / kappa dx = smallest_period / 5 nsteps = max(int(np.ceil(c.max() / dx)),minsteps) x, dx = np.linspace(0, c.max(), nsteps, retstep=True) spl = spline(x, x*self._f(x)*np.sin(kappa*x)/kappa) intg = spl.antiderivative() intermediate_res[ik,:] = intg(c) - intg(0) for ic, cc in enumerate(c): #print intermediate_res.shape, kk.shape, res.shape # For high K, intermediate_res can be negative, so we mask that. mask = intermediate_res[:,ic]>0 spl = spline(np.log(kk[mask]),np.log(intermediate_res[mask,ic]),k=1) res[:,ic] = np.exp(spl(np.log(K[:,ic]))) return res
def get_neighbors(self, puzzle_list): grid_row = self.row / 3 grid_col = self.col / 3 np.reshape(puzzle_list, (9, 9)) return np.flatten(puzzle_list[grid_row * 3:(grid_row + 1) * 3, grid_col * 3:(grid_col * 3) + 1])
def hist(self, q_img): if np.max(q_img) > 0: levels = len(set(np.flatten(q_img))) hist, _ = np.histogram(q_img.reshape(-1), bins=np.arange(levels + 1), density=True) else: hist = np.zeros(self.levels) return hist
def pack(arr): try: arr = np.vstack(arr) if arr.shape[0] == 1: return np.flatten(arr) else: return arr except: return np.hstack(arr)
def __writesum__(self, predictions, targets): p_np = predictions[0].cpu().data.numpy() t_np = targets[0].cpu().data.numpy() if self.one_hot: p_np = np.flatten(p_np) t_np = np.flatten(t_np) prediction = None target = None if self.data.mode == 'SMI': prediction_ = torch.tensor(np.absolute(p_np.round(0))) prediction = smiles_decoder(prediction_, one_hot=self.one_hot) target_ = torch.tensor(np.absolute(t_np.round(0))) target = smiles_decoder(target_, one_hot=self.one_hot) if self.data.mode == 'SEQ': prediction_ = torch.tensor(np.absolute(p_np.round(0))) prediction = seq_decoder(prediction_, one_hot=self.one_hot) target_ = torch.tensor(np.absolute(t_np.round(0))) target = seq_decoder(target_, one_hot=self.one_hot) return prediction, target
def isSolvable(puzzle): puzz = puzzle[:] invCount = getInvCount(flatten(puzz)) if N % 2: return not invCount % 2 # return even else: pos = blankTilePosition(puzzle)[0] if pos % 2: # X on odd row from last return not invCount % 2 # invCount is even else: return bool(invCount % 2) # invCount is odd
def __eq__(self, other): # Comparisons to make """ amplitude_ratio: Type::ndarray, Len: 4642 track_length: Type::ndarray, Len: 4642 skeleton: Type::skeleton, Len: 2 eigen_projection: Type::ndarray, Len: 4642 kinks: Type::ndarray, Len: 4642 primary_wavelength: Type::Dataset, Len: 4642 directions: Type::Directions, Len: 1 bend: Type::Bends, Len: 1 eccentricity: Type::ndarray, Len: 4642 secondary_wavelength: Type::Dataset, Len: 4642 amplitude_max: Type::ndarray, Len: 4642 """ return \ fc.corr_value_high(self.eccentricity, other.eccentricity, 'posture.eccentricity',high_corr_value=0.99) and \ fc.corr_value_high(self.amplitude_ratio, other.amplitude_ratio, 'posture.amplitude_ratio') and \ fc.corr_value_high(self.track_length, other.track_length, 'posture.track_length') and \ fc.corr_value_high(self.kinks, other.kinks, 'posture.kinks') and \ fc.corr_value_high(self.secondary_wavelength, other.secondary_wavelength, 'posture.secondary_wavelength') and \ fc.corr_value_high(self.amplitude_max, other.amplitude_max, 'posture.amplitude_max') and \ fc.corr_value_high(np.flatten(self.skeleton.x), np.flatten(other.skeleton.x), 'posture.skeleton.x') and \ fc.corr_value_high(np.flatten(self.skeleton.y), np.flatten(other.skeleton.y), 'posture.skeleton.y') and \ fc.corr_value_high(np.flatten(self.eigen_projection), np.flatten( other.eigen_projection), 'posture.eigen_projection')
def get_element_list(space, element): types = [ gym.spaces.box.Box, gym.spaces.multi_binary.MultiBinary, gym.spaces.discrete.Discrete, gym.spaces.multi_discrete.MultiDiscrete, gym.spaces.dict.Dict, gym.spaces.tuple.Tuple, ] if type(space) is gym.spaces.box.Box: return list(element) if type(space) is gym.spaces.multi_binary.MultiBinary: return list(np.flatten(element)) if type(space) is gym.spaces.discrete.Discrete: return [element] if type(space) is gym.spaces.multi_discrete.MultiDiscrete: return list(np.flatten(element)) if type(space) is gym.spaces.dict.Dict: element_list = [] for element_component in element.values(): element_list += get_element_list(element_component) return element_list if type(space) is gym.spaces.tuple.Tuple: element_list = [] for element_component in element: element_list += get_element_list(element_component) return element_list
def Easyinterp(Input): if ~ len(np.shape(Input)) == 1: Input = np.flatten(Input) X = np.arange(0,np.size(Input),1) Xinterp = np.arange(0,np.size(Input),0.1) f2 = interp1d(X, abs(Input), kind='slinear', fill_value="extrapolate") raw_interp = f2(Xinterp) output = np.reshape(raw_interp, (1, np.size(raw_interp)) ) return output
def flatten(self, order='C'): ''' Return a copy of the array collapsed(坍塌) into one dimension. @order: {'C', 'F', 'A', 'K'}, optional 'C' means to flatten in row-major (C-style) order. 'F' means to flatten in column-major (Fortran- style) order. 'A' means to flatten in column-major order if `a` is Fortran *contiguous* in memory, row-major order otherwise. 'K' means to flatten `a` in the order the elements occur in memory. The default is 'C'. ''' return np.flatten(order)
def scalar_mul(x, s, pub): """ scala multiplication of x(vector) and s(scala) x: numpy array of PaillierEncryptedNumber y: FixedPointNumber """ x_shape = x.shape x_flatten = np.flatten(x) s_array = np.array([s for _ in range(len(x_flatten))]) res = paillier_gpu.mul_impl(x_flatten, s_array) return np.reshape(res, x_shape)
def set_distribution(self, grid): print(np.shape(grid)) print(self.cell_ns) #if np.shape(grid) != self.cell_ns: # except ValueError: # print( # 'Shape of grid () does not match shape of distribution ()'.format(np.shape(grid), self.cell_ns) # ) # raise self.wgt_array = np.flatten(grid)
def Select(self, ndarray): """Return a bit mask for array elements falling within the range.""" shape = ndarray.shape if len(shape) != 1: ndarray = numpy.flatten(ndarray) mask = (numpy.in1d(ndarray, self._numerics) | numpy.in1d(ndarray, self._nonnumerics)) if len(shape) != 1: mask = mask.reshape(shape) return mask
def solve_for_prior_normalization(self, inv_Cyy, inv_Cf, A, inv_A, R_real, datamap, print_alpha): N = R_real.shape[1] #from numpy.linalg import inv alpha = N / ( np.trace( np.dot(inv_A, inv_Cf) ) + np.dot( datamap.T , np.dot( inv_Cyy, np.dot(R_real, np.dot( inv_A , np.dot(inv_Cf , np.dot( inv_A , np.dot( R_real.T ,np.dot(inv_Cyy, datamap)))))))) ) if print_alpha is 1: alpha_towrite=np.flatten(alpha)[0] outfile = 'alpha_lmax' + str(Multiverse.truncated_lmax) + 'lmin' + str(Multiverse.truncated_lmin) + 'nmax' + str(Multiverse.truncated_nmax) + 'nmin' + str(Multiverse.truncated_nmin) + '.txt' f = open('RobustnessAnalysis/' + outfile, 'a') towrite = str(alpha_towrite) + "\n" f.write(towrite) f.close() return alpha*inv_Cf
def __call__(self, thing): return np.flatten(thing)