def thunk(): in_shape = inputs[0][0].shape full_batch_size, num_channels_rolled, height, width = in_shape assert height == width # else convroll doesn't make sense assert full_batch_size % 4 == 0 assert num_channels_rolled % 4 == 0 num_channels = num_channels_rolled // 4 batch_size = full_batch_size // 4 out_shape = (full_batch_size, num_channels, height, width) example_size = num_channels * height * width map_size = height out = outputs[0] # only allocate if there is no previous allocation of the right size. if out[0] is None or out[0].shape != out_shape: out[0] = cuda.CudaNdarray.zeros(out_shape) x_block = 16 y_block = 16 block = (x_block, y_block, 1) x_grid = int(np.ceil(float(example_size) / x_block)) y_grid = int(np.ceil(float(full_batch_size) / y_block)) grid = (x_grid, y_grid, 1) kernel(inputs[0][0], out[0], np.intc(batch_size), np.intc(num_channels), np.intc(map_size), block=block, grid=grid)
def __init__(self, fc4, supercell, primitive, mesh, band_indices=None, frequency_factor_to_THz=VaspToTHz, is_nosym=False, symprec=1e-3, cutoff_frequency=1e-4, log_level=False, lapack_zheev_uplo='L'): self._fc4 = fc4 self._supercell = supercell self._primitive = primitive self._mesh = np.intc(mesh) if band_indices is None: self._band_indices = [ np.arange(primitive.get_number_of_atoms() * 3)] else: self._band_indices = band_indices self._frequency_factor_to_THz = frequency_factor_to_THz self._is_nosym = is_nosym self._symprec = symprec self._cutoff_frequency = cutoff_frequency self._log_level = log_level self._lapack_zheev_uplo = lapack_zheev_uplo self._band_indices_flatten = np.intc( [x for bi in self._band_indices for x in bi]) self._frequency_shifts = None
def _run_c(self, g_skip=None): import anharmonic._phono3py as phono3c if g_skip is None: g_skip = np.zeros_like(self._interaction_strength_reduced, dtype="bool") assert g_skip.shape == self._interaction_strength_reduced.shape self._set_phonon_c() masses = np.double(self._primitive.get_masses()) p2s = np.intc(self._primitive.get_primitive_to_supercell_map()) s2p = np.intc(self._primitive.get_supercell_to_primitive_map()) atc=np.intc(self._triplet_cut_super) # int type atc_prim = np.intc(self._triplet_cut_prim) # int type phono3c.interaction(self._interaction_strength_reduced, self._frequencies, self._eigenvectors, self._triplets_at_q_reduced.copy(), self._grid_address, self._mesh, self._fc3, atc, atc_prim, g_skip, self._svecs, self._multiplicity, np.double(masses), p2s, s2p, self._band_indices, self._symmetrize_fc3_q, self._cutoff_frequency, self._cutoff_hfrequency, self._cutoff_delta) phono3c.interaction_degeneracy_grid(self._interaction_strength_reduced, self._degenerates, self._triplets_at_q_reduced.astype('intc').copy(), self._band_indices.astype('intc'))
def get_reduced_pairs_permute_sym(pairs, mesh, first_mapping, first_rotation, second_mapping): mesh = np.array(mesh) pair_numbers = np.array([len(pair) for pair in pairs], dtype="intc") grid_points = np.array([pair[0][0] for pair in pairs], dtype="intc") pairs_all = np.vstack(pairs) pairs_mapping = np.arange(len(pairs_all)).astype("intc") sequences = np.array([[0,1]] * len(pairs_all), dtype="byte") num_irred_pairs = spg.reduce_pairs_permute_sym(pairs_mapping, sequences, pairs_all.astype("intc"), np.intc(grid_points).copy(), np.intc(pair_numbers).copy(), mesh.astype("intc"), np.intc(first_mapping).copy(), np.intc(first_rotation).copy(), np.intc(second_mapping).copy()) assert len(np.unique(pairs_mapping)) == num_irred_pairs unique_pairs, indices = np.unique(pairs_mapping, return_inverse=True) pairs_map = [] pair_sequence = [] num_pairs = 0 for i, pairs_at_q in enumerate(pairs): pairs_map.append(indices[num_pairs:num_pairs+len(pairs_at_q)]) pair_sequence.append(sequences[num_pairs:num_pairs+len(pairs_at_q)]) num_pairs += len(pairs_at_q) return unique_pairs,pairs_map, pair_sequence
def route_flow(self, receiver, dem='topographic__elevation'): #main self._dem = self._grid['node'][dem] """ if receiver==None: self._flow_receiver = self._flow_dirs_d8(self._dem) else: self._flow_receiver = receiver """ self._flow_receiver = receiver #(self._flow_receiver, ss) = grid_flow_directions(self._grid, self._dem) method = 'python' if method=='cython': from flow_direction_over_flat_cython import adjust_flow_direction self._flow_receiver = adjust_flow_direction(self._dem, np.intc(self._flow_receiver), np.intc(self._boundary), np.intc(self._close_boundary), np.intc(self._open_boundary), np.intc(self._neighbors)) else: flat_mask, labels = self._resolve_flats() self._flow_receiver = self._flow_dirs_over_flat_d8(flat_mask, labels) #a, q, s = flow_accum_bw.flow_accumulation(self._flow_receiver, self._open_boundary, node_cell_area=self._grid.forced_cell_areas) #self._grid['node']['flow_receiver'] = self._flow_receiver return self._flow_receiver
def setNeighborPair(self, s1, s2, w): """Create an edge (s1, s2) with weight w. w should be of type int or float (python primitive type). s1 should be smaller than s2.""" if not (0 <= s1 < s2 < self.numSites): raise IndexOutOfBoundError() _cgco.gcoSetNeighborPair(self.handle, np.intc(s1), np.intc(s2), self._convertPairwiseTerm(w))
def set_kappa_at_s_c(self, s): import anharmonic._phono3py as phono3c kappa = np.zeros_like(self._kappa[s]) rec_lat = np.linalg.inv(self._primitive.get_cell()) for t, temp in enumerate(self._temperatures): gouterm_temp = np.zeros((self._frequencies.shape[0], self._frequencies.shape[1], 6), dtype="double") phono3c.phonon_gb33_multiply_dvector_gb3_dvector_gb3(gouterm_temp, self._b[:,t].copy(), self._F[s,:,t].copy(), np.intc(self._irr_index_mapping).copy(), np.intc(self._kpoint_operations[self._rot_mappings]).copy(), rec_lat.copy()) kappa[:,t] = gouterm_temp * temp ** 2 self._F[s, np.where((np.abs(self._qpoints) > self._pp._criteria).any(axis=1)), t] = 0. kappa[np.where((np.abs(self._qpoints) > self._pp._criteria).any(axis=1)), t] = 0. # l = len(np.where((np.abs(self._qpoints) > self._pp._criteria).any(axis=1))[0]) # kappa *= np.prod(self._mesh) / np.double(np.prod(self._mesh) - l) kappa *= self._kappa_factor / np.prod(self._mesh) #modified for my own interest kappa_max = kappa.sum(axis=(0,2)).max(axis=-1) rkappa = np.sum(np.abs(kappa - self._kappa[s]), axis=(0, 2)) # over qpoints and nbands for i in range(6): self._rkappa[s, :, i] = rkappa[:, i] / kappa_max self._kappa[s] = kappa
def get_reduced_triplets_permute_sym(triplets, mesh, first_mapping, first_rotation, second_mapping): mesh = np.array(mesh) triplet_numbers = np.array([len(tri) for tri in triplets], dtype="intc") grid_points = np.array([triplet[0][0] for triplet in triplets], dtype="intc") triplets_all = np.vstack(triplets) triplets_mapping = np.arange(len(triplets_all)).astype("intc") sequences = np.array([[0,1,2]] * len(triplets_all), dtype="byte") num_irred_triplets = spg.reduce_triplets_permute_sym(triplets_mapping, sequences, triplets_all.astype("intc"), np.intc(grid_points).copy(), np.intc(triplet_numbers).copy(), mesh.astype("intc"), np.intc(first_mapping).copy(), np.intc(first_rotation).copy(), np.intc(second_mapping).copy()) assert len(np.unique(triplets_mapping)) == num_irred_triplets unique_triplets, indices = np.unique(triplets_mapping, return_inverse=True) triplets_map = [] triplet_sequence = [] num_triplets = 0 for i, triplets_at_q in enumerate(triplets): triplets_map.append(indices[num_triplets:num_triplets+len(triplets_at_q)]) triplet_sequence.append(sequences[num_triplets:num_triplets+len(triplets_at_q)]) num_triplets += len(triplets_at_q) return unique_triplets,triplets_map, triplet_sequence
def thunk(): # inputs A = inputs[0][0] B = inputs[1][0] # dimensions m = A.shape[0] n = A.shape[1] k = B.shape[1] assert n == B.shape[0] # Otherwise GEMM is impossible assert n%16 == 0 # Block size # output output_shape = (m, k) C = outputs[0] # only allocate if there is no previous allocation of the right size. if C[0] is None or C[0].shape != output_shape: C[0] = cuda.CudaNdarray.zeros(output_shape) # Launching GEMM GPU kernel block_size = 16 block = (block_size,block_size,1) grid = (k / block_size+1, m / block_size+1) # better too many blocks than too little gemm_kernel(A,B,C[0], np.intc(m), np.intc(n), np.intc(k), block= block, grid=grid)
def get_mappings(mesh, rotations, is_shift=np.zeros(3, dtype='intc'), is_time_reversal=True, qpoints=np.double([])): """ Return k-point map to the irreducible k-points and k-point grid points . The symmetry is searched from the input rotation matrices in real space. is_shift=[0, 0, 0] gives Gamma center mesh and the values 1 give half mesh distance shifts. """ mapping = np.zeros(np.prod(mesh), dtype='intc') rot_mapping = np.zeros(np.prod(mesh), dtype="intc") mesh_points = np.zeros((np.prod(mesh), 3), dtype='intc') qpoints = np.double(qpoints).copy() if qpoints.shape == (3,): qpoints = np.double([qpoints]) spg.stabilized_reciprocal_mesh(mesh_points, mapping, rot_mapping, np.intc(mesh).copy(), np.intc(is_shift), is_time_reversal * 1, np.intc(rotations).copy(), np.double(qpoints)) return mapping, rot_mapping
def thunk(): in_shape = inputs[0][0].shape rows, cols = in_shape assert rows % 4 == 0 out_shape = (rows, 4 * cols) batch_size = rows // 4 num_features = cols out = outputs[0] # only allocate if there is no previous allocation of the right size. if out[0] is None or out[0].shape != out_shape: out[0] = cuda.CudaNdarray.zeros(out_shape) x_block = 16 y_block = 16 block = (x_block, y_block, 1) x_grid = int(np.ceil(float(in_shape[1]) / x_block)) y_grid = int(np.ceil(float(in_shape[0]) / y_block)) grid = (x_grid, y_grid, 1) kernel(inputs[0][0], out[0], np.intc(batch_size), np.intc(num_features), block=block, grid=grid)
def X_router_Y_add_O(self, alpha, X, Y, beta, O, result = None): ''' xi, yi is vector X, Y is matrix X=[x1, x2, x3] Y=[y1, y2, y3] X_router_Y_add_O = a * (x1 outer y1 + x2 outer y2 + x3 outer y3) + b * O X_router_Y_add_O(float alpha, float* X, float* Y, float beta, float* O, float* result, uint r_col, uint r_row, uint XY_col) ''' if result is None: O_col = O.shape[0] O_row = O.shape[1] XY_col = X.shape[0] self.X_router_Y_add_O_kernel(np.float32(alpha), X.gpudata, Y.gpudata, \ np.float32(beta), O.gpudata, \ O.gpudata, np.intc(O_col), np.intc(O_row), np.intc(XY_col), \ block = (32, 32, 1), \ grid = (int(O_row / 32) + 1, int(O_col / 32) + 1) \ ) else: O_col = O.shape[0] O_row = O.shape[1] XY_col = X.shape[0] self.X_router_Y_add_O_kernel(np.float32(alpha), X.gpudata, Y.gpudata, \ np.float32(beta), O.gpudata, \ result.gpudata, np.intc(O_col), np.intc(O_row), np.intc(XY_col), \ block = (32, 32, 1), \ grid = (int(O_row / 32) + 1, int(O_col / 32) + 1) \ )
def x_cadd_Y_as_Y(self, alpha, x, beta, Y, result = None): ''' result[i,j] = alpha*x[j] + beta*Y[i,j] x_radd_Y_as_Y(float alpha, float* x, float beta, float* Y, float* result, uint Y_col, uint Y_row) ''' if result is None: Y_col = Y.shape[0] Y_row = Y.shape[1] self.x_cadd_Y_as_Y_kernel(np.float32(alpha), x.gpudata, \ np.float32(beta), Y.gpudata, \ Y.gpudata, np.intc(Y_col), np.intc(Y_row), \ block = (32, 32, 1), \ grid = (int(Y_row / 32) + 1, int(Y_col / 32) + 1) \ ) else: Y_col = Y.shape[0] Y_row = Y.shape[1] self.x_cadd_Y_as_Y_kernel(np.float32(alpha), x.gpudata, \ np.float32(beta), Y.gpudata, \ result.gpudata, np.intc(Y_col), np.intc(Y_row), \ block = (32, 32, 1), \ grid = (int(Y_row / 32) + 1, int(Y_col / 32) + 1) \ )
def get_triplets_reciprocal_mesh_at_q(fixed_grid_number, mesh, rotations, is_time_reversal=True, is_return_map=False, is_return_rot_map=False): weights = np.zeros(np.prod(mesh), dtype='intc') third_q = np.zeros(np.prod(mesh), dtype='intc') mesh_points = np.zeros((np.prod(mesh), 3), dtype='intc') mapping = np.zeros(np.prod(mesh), dtype='intc') rot_mapping = np.zeros(np.prod(mesh), dtype='intc') spg.triplets_reciprocal_mesh_at_q(weights, mesh_points, third_q, mapping, rot_mapping, fixed_grid_number, np.intc(mesh).copy(), is_time_reversal * 1, np.intc(rotations).copy()) assert len(mapping[np.unique(mapping)]) == len(weights[np.nonzero(weights)]), \ "At grid %d, number of irreducible mapping: %d is not equal to the number of irreducible triplets%d"%\ (fixed_grid_number, len(mapping[np.unique(mapping)]), len(weights[np.nonzero(weights)])) if not is_return_map and not is_return_rot_map: return weights, third_q, mesh_points elif not is_return_rot_map: return weights, third_q,mesh_points, mapping else: return weights, third_q,mesh_points, mapping, rot_mapping
def _calculate_fc4_normal_c(self): import anharmonic._phono4py as phono4c svecs, multiplicity = get_smallest_vectors(self._supercell, self._primitive, self._symprec) p2s = np.intc(self._primitive.get_primitive_to_supercell_map()) s2p = np.intc(self._primitive.get_supercell_to_primitive_map()) gp = self._grid_point self._set_phonon_c([gp]) self._set_phonon_c(self._quartets_at_q) phono4c.fc4_normal_for_frequency_shift( self._fc4_normal, self._frequencies, self._eigenvectors, gp, self._quartets_at_q, self._grid_address, self._mesh, np.double(self._fc4), svecs, multiplicity, self._masses, p2s, s2p, self._band_indices, self._cutoff_frequency)
def get_csr_matrix(A): '''get csr matrix from dolfin without copying data cf. http://code.google.com/p/pyamg/source/browse/branches/2.0.x/Examples/DolfinFormulation/demo.py ''' (row,col,data) = A.data() return csr_matrix( (data,intc(col),intc(row)), shape=(A.size(0),A.size(1)) )
def x_cmul_Y_as_Y(self, alpha, x, x0, Y, y0, beta, result = None): ''' result[i,j] = alpha*(x[i] + x0) * (Y[i,j] + y0) + beta x_cmul_Y_as_Y(float alpha, float* x, float x0, float* Y, float y0, float beta, float* result, uint Y_col, uint Y_row) ''' if result is None: Y_col = Y.shape[0] Y_row = Y.shape[1] self.x_cmul_Y_as_Y_kernel(np.float32(alpha), x.gpudata, np.float32(x0), \ Y.gpudata, np.float32(y0), np.float32(beta), \ Y.gpudata, np.intc(Y_col), np.intc(Y_row), \ block = self._2d_block, \ grid = self._2d_grid(Y_col, Y_row) \ ) else: Y_col = Y.shape[0] Y_row = Y.shape[1] self.x_cmul_Y_as_Y_kernel(np.float32(alpha), x.gpudata, np.float32(x0), \ Y.gpudata, np.float32(y0), np.float32(beta), \ result.gpudata, np.intc(Y_col), np.intc(Y_row), \ block = self._2d_block, \ grid = self._2d_grid(Y_col, Y_row) \ )
def calculate_gh_at_sigma_and_temp(self): import anharmonic._phono3py as phono3c if self._is_precondition: out = self._collision_out[self._isigma, :, self._itemp] out_reverse = np.where(self._frequencies>self._cutoff_frequency, 1 / out, 0) self._z[self._isigma, :, self._itemp] = self._r[self._isigma, :, self._itemp] * out_reverse[..., np.newaxis] else: self._z[self._isigma, :, self._itemp] = self._r[self._isigma, :, self._itemp] self._z[:, np.where(np.any(np.abs(self._qpoints) > self._pp._criteria, axis=1))] = 0 zr0 = np.zeros(3, dtype="double") phono3c.phonon_3_multiply_dvector_gb3_dvector_gb3(zr0, self._z_prev[self._isigma,:,self._itemp].copy(), self._r_prev[self._isigma,:,self._itemp].copy(), np.intc(self._irr_index_mapping).copy(), np.intc(self._kpoint_operations[self._rot_mappings]), np.double(np.linalg.inv(self._primitive.get_cell())).copy()) #Flexibly preconditioned CG: r(i+1)-r(i) instead of r(i+1) r = self._r[self._isigma,:,self._itemp] - self._r_prev[self._isigma,:,self._itemp] # r = self._r[self._isigma,:,self._itemp] zr1 = np.zeros(3, dtype="double") phono3c.phonon_3_multiply_dvector_gb3_dvector_gb3(zr1, self._z[self._isigma,:,self._itemp].copy(), r.copy(), np.intc(self._irr_index_mapping).copy(), np.intc(self._kpoint_operations[self._rot_mappings]), np.double(np.linalg.inv(self._primitive.get_cell())).copy()) zr1_over_zr0 = np.where(np.abs(zr0>0), zr1/zr0, 0) self._p[self._isigma,:,self._itemp] = self._z[self._isigma,:,self._itemp] +\ zr1_over_zr0 * self._p_prev[self._isigma,:,self._itemp] self._p[:, np.where(np.any(np.abs(self._qpoints) > self._pp._criteria, axis=1))] = 0
def __init__(self, fc4, supercell, primitive, mesh, temperatures=None, band_indices=None, frequency_factor_to_THz=VaspToTHz, is_nosym=False, symprec=1e-3, cutoff_frequency=1e-4, log_level=False, lapack_zheev_uplo='L'): self._fc4 = fc4 self._supercell = supercell self._primitive = primitive self._masses = np.double(self._primitive.get_masses()) self._mesh = np.intc(mesh) if temperatures is None: self._temperatures = np.double([0]) else: self._temperatures = np.double(temperatures) num_band = primitive.get_number_of_atoms() * 3 if band_indices is None: self._band_indices = np.arange(num_band, dtype='intc') else: self._band_indices = np.intc(band_indices) self._frequency_factor_to_THz = frequency_factor_to_THz self._is_nosym = is_nosym self._symprec = symprec self._cutoff_frequency = cutoff_frequency self._log_level = log_level self._lapack_zheev_uplo = lapack_zheev_uplo symmetry = Symmetry(primitive, symprec=symprec) self._point_group_operations = symmetry.get_pointgroup_operations() self._grid_address = None self._bz_map = None self._set_grid_address() self._grid_point = None self._quartets_at_q = None self._weights_at_q = None self._phonon_done = None self._frequencies = None self._eigenvectors = None self._dm = None self._nac_q_direction = None self._frequency_shifts = None # Unit to THz of Delta self._unit_conversion = (EV / Angstrom ** 4 / AMU ** 2 / (2 * np.pi * THz) ** 2 * Hbar * EV / (2 * np.pi * THz) / 8 / np.prod(self._mesh)) self._allocate_phonon()
def get_kpoint_group(mesh, point_group_operations, qpoints=[[0.,0.,0.]], is_time_reversal=True): reverse_kpt_group = np.zeros((len(point_group_operations) * 2, 3, 3), dtype="intc") num_kpt_rots = spg.kpointgroup(reverse_kpt_group, np.intc(point_group_operations).copy(), np.intc(mesh).copy(), np.double(qpoints).copy(), is_time_reversal) return reverse_kpt_group[:num_kpt_rots]
def to_scipy_csr(mat, dtype=None, imagify=False): (row,col,data) = mat.data() # get sparse data col = intc(col) row = intc(row) n = mat.size(0) if imagify: data = data*1j Asp = csr_matrix( (data,col,row), shape=(n,n), dtype=dtype) return Asp
def concatenation_cols(concatenate_cols_kernel,A,A_conc,A_rows,A_cols): assert A_rows%32 == 0 # concatenation step block_size = 64 block = (block_size,1,1) grid = (A_cols/block_size+1,1) concatenate_cols_kernel(A,A_conc, np.intc(A_rows), np.intc(A_cols), block= block, grid=grid)
def thunk(): n = inputs[1][0].shape[1] # Number of bit pairs m = n / inputs[0][0].size # Gene length t = 512 # Number of threads z = outputs[0] z[0] = cuda.CudaNdarray.zeros(inputs[1][0].shape) grid = (int(np.ceil(n / 512.)), 1) choose_cuda(z[0], inputs[0][0], inputs[1][0], np.intc(n), np.intc(m), block=(512,1,1), grid=grid)
def gemm(gemm_kernel,A,B,C,A_rows,A_cols,B_cols): # dimensions assert A_cols%16 == 0 # Block size # Launching GEMM GPU kernel block_size = 16 block = (block_size,block_size,1) grid = (B_cols / block_size+1, A_rows / block_size+1) # better too many blocks than too little gemm_kernel(A,B,C, np.intc(A_rows), np.intc(A_cols), np.intc(B_cols), block= block, grid=grid)
def get_symmetry_dataset(cell, tolerance=1e-5): """Return crystal symmetry information by analyzing Cell object. number: International space group number international: International symbol hall: Hall symbol transformation_matrix: Transformation matrix from lattice of input cell to Bravais lattice L^bravais = L^original * Tmat origin shift: Origin shift in the setting of 'Bravais lattice' rotations, translations: Rotation matrices and translation vectors Space group operations are obtained by [(r,t) for r, t in zip(rotations, translations)] wyckoffs: Wyckoff letters """ points = np.array(cell.get_points(), dtype='double', order='C') lattice = np.array(cell.get_lattice(), dtype='double', order='C') numbers = np.array(cell.get_numbers(), dtype='intc') keys = ('number', 'international', 'hall_number', 'hall', 'transformation_matrix', 'origin_shift', 'rotations', 'translations', 'wyckoffs', 'equivalent_atoms') dataset = {} for key, data in zip(keys, spg.get_dataset(lattice, points, numbers, tolerance)): dataset[key] = data dataset['international'] = dataset['international'].strip() dataset['hall'] = dataset['hall'].strip() dataset['transformation_matrix'] = np.double( dataset['transformation_matrix']) dataset['origin_shift'] = np.double(dataset['origin_shift']) dataset['rotations'] = np.intc(dataset['rotations']) dataset['translations'] = np.double(dataset['translations']) letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" dataset['wyckoffs'] = [letters[x] for x in dataset['wyckoffs']] dataset['equivalent_atoms'] = np.intc(dataset['equivalent_atoms']) dataset['international_standard'] = standard_HM_symbols[dataset['number']] return dataset
def get_kappa_residual_at_s_t(self, s, t): import anharmonic._phono3py as phono3c rec_lat = np.linalg.inv(self._primitive.get_cell()) dkappa = np.zeros((self._frequencies.shape[0], self._frequencies.shape[1], 6), dtype="double") phono3c.phonon_gb33_multiply_dvector_gb3_dvector_gb3(dkappa, self._b[:,t].copy(), self._R[s,:,t].copy(), np.intc(self._irr_index_mapping).copy(), np.intc(self._kpoint_operations[self._rot_mappings]).copy(), rec_lat.copy()) dkappa = np.sum(self._grid_weights[:, np.newaxis, np.newaxis] * np.abs(dkappa), axis=(0,1)) return dkappa * self._temperatures[t] ** 2 * self._kappa_factor / np.prod(self._mesh)
def uncompress(data, uncompressed_size): _0 = numpy.intc(0) _1 = numpy.intc(1) _2 = numpy.intc(2) _128 = numpy.intc(128) _255 = numpy.intc(255) n, r, s, p = _0, _0, _0, _0 i, d = _1, _1 f = _255 & data[_0] ptrs = numpy.zeros(256, dtype = numpy.intc) uncompressed = numpy.zeros(uncompressed_size, dtype = numpy.uint8) idx = numpy.arange(uncompressed_size, dtype = numpy.intc) while s < uncompressed_size: pp = p + _1 if f & i: r = ptrs[data[d]] n = _2 + data[d + _1] uncompressed[idx[s:s + n]] = uncompressed[r:r + n] ptrs[(uncompressed[p]) ^ (uncompressed[pp])] = p if s == pp: ptrs[(uncompressed[pp]) ^ (uncompressed[pp + _1])] = pp d += _2 r += _2 s = s + n p = s else: uncompressed[s] = data[d] if pp == s: ptrs[(uncompressed[p]) ^ (uncompressed[pp])] = p p = pp s += _1 d += _1 if i == _128: if s < uncompressed_size: f = _255 & data[d] d += _1 i = _1 else: i += i return uncompressed
def createGeneralGraph(self, numSites, numLabels, energyIsFloat=False): """Create a general graph with specified number of sites and labels. If energyIsFloat is set to True, then automatic scaling and rounding will be applied to convert all energies to integers when running graph cuts. Then the final energy will be converted back to floats after the computation.""" self.tempArray = np.empty(1, dtype=np.intc) self.energyTempArray = np.empty(1, dtype=np.longlong) _cgco.gcoCreateGeneralGraph(np.intc(numSites), np.intc(numLabels), self.tempArray) self.handle = self.tempArray[0] self.numSites = np.intc(numSites) self.numLabels = np.intc(numLabels) self.energyIsFloat = energyIsFloat
def set_kappa_at_s_c(self, s): import anharmonic._phono3py as phono3c kappa = np.zeros_like(self._kappa[s]) rec_lat = np.linalg.inv(self._primitive.get_cell()) for t, temp in enumerate(self._temperatures): gouterm_temp = np.zeros((self._frequencies.shape[0], self._frequencies.shape[1], 6), dtype="double") phono3c.phonon_gb33_multiply_dvector_gb3_dvector_gb3(gouterm_temp, self._b[:,t].copy(), self._F[s,:,t].copy(), np.intc(self._irr_index_mapping).copy(), np.intc(self._kpoint_operations[self._rot_mappings]).copy(), rec_lat.copy()) kappa[:,t] = gouterm_temp * temp ** 2 self._kappa[s] = kappa * self._kappa_factor
def get_symmetry_dataset(bulk, symprec=1e-5, angle_tolerance=-1.0): """ number: International space group number international: International symbol hall: Hall symbol transformation_matrix: Transformation matrix from lattice of input cell to Bravais lattice L^bravais = L^original * Tmat origin shift: Origin shift in the setting of 'Bravais lattice' rotations, translations: Rotation matrices and translation vectors Space group operations are obtained by [(r,t) for r, t in zip(rotations, translations)] wyckoffs: Wyckoff letters """ positions = bulk.get_scaled_positions().copy() lattice = bulk.get_cell().T.copy() numbers = np.intc(bulk.get_atomic_numbers()).copy() keys = ('number', 'international', 'hall', 'transformation_matrix', 'origin_shift', 'rotations', 'translations', 'wyckoffs', 'equivalent_atoms') dataset = {} for key, data in zip(keys, spg.dataset(lattice, positions, numbers, symprec, angle_tolerance)): dataset[key] = data dataset['international'] = dataset['international'].strip() dataset['hall'] = dataset['hall'].strip() dataset['transformation_matrix'] = np.double( dataset['transformation_matrix']) dataset['origin_shift'] = np.double(dataset['origin_shift']) dataset['rotations'] = np.intc(dataset['rotations']) dataset['translations'] = np.double(dataset['translations']) letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" dataset['wyckoffs'] = [letters[x] for x in dataset['wyckoffs']] dataset['equivalent_atoms'] = np.intc(dataset['equivalent_atoms']) return dataset
def _dgamma(x): res = 1.0 if x <= 0.0: if x == np.floor(x): return np.nan if x <= -20.0: return _π / (_dgamma(-x) * _dsinpi(x) * x) while x < 0: res /= x x += 1 if x <= 10 and x == np.floor(x): res *= FACTORIALS[np.intc(x) - 1] elif x < _root_ε: res *= 1.0 / x - _γ else: res *= _lanczos_sum(x) xgh = x + _lanczos_g - 0.5 log_xgh = np.log(xgh) xlog_xgh = x * log_xgh if xlog_xgh > _MAXEXP: if 0.5 * xlog_xgh > _MAXEXP: return np.copysign(np.inf, res) hp = xgh**(0.5 * x - 0.25) res *= hp / np.exp(xgh) res *= hp else: res *= xgh**(x - 0.5) / np.exp(xgh) return res
def set_srid(geometry, srid, **kwargs): """Returns a geometry with its SRID set. Parameters ---------- geometry : Geometry or array_like srid : int **kwargs For other keyword-only arguments, see the `NumPy ufunc docs <https://numpy.org/doc/stable/reference/ufuncs.html#ufuncs-kwargs>`_. See also -------- get_srid Examples -------- >>> point = Geometry("POINT (0 0)") >>> with_srid = set_srid(point, 4326) >>> get_srid(point) 0 >>> get_srid(with_srid) 4326 """ return lib.set_srid(geometry, np.intc(srid), **kwargs)
def get_point(geometry, index, **kwargs): """Returns the nth point of a linestring or linearring. Parameters ---------- geometry : Geometry or array_like index : int or array_like Negative values count from the end of the linestring backwards. **kwargs For other keyword-only arguments, see the `NumPy ufunc docs <https://numpy.org/doc/stable/reference/ufuncs.html#ufuncs-kwargs>`_. See also -------- get_num_points Examples -------- >>> line = Geometry("LINESTRING (0 0, 1 1, 2 2, 3 3)") >>> get_point(line, 1) <pygeos.Geometry POINT (1 1)> >>> get_point(line, -2) <pygeos.Geometry POINT (2 2)> >>> get_point(line, [0, 3]).tolist() [<pygeos.Geometry POINT (0 0)>, <pygeos.Geometry POINT (3 3)>] >>> get_point(Geometry("LINEARRING (0 0, 1 1, 2 2, 0 0)"), 1) <pygeos.Geometry POINT (1 1)> >>> get_point(Geometry("MULTIPOINT (0 0, 1 1, 2 2, 3 3)"), 1) is None True >>> get_point(Geometry("POINT (1 1)"), 0) is None True """ return lib.get_point(geometry, np.intc(index), **kwargs)
def get_triplets_reciprocal_mesh_at_q(fixed_grid_number, mesh, rotations, is_time_reversal=True): weights = np.zeros(np.prod(mesh), dtype='intc') third_q = np.zeros(np.prod(mesh), dtype='intc') mesh_points = np.zeros((np.prod(mesh), 3), dtype='intc') spg.triplets_reciprocal_mesh_at_q(weights, mesh_points, third_q, fixed_grid_number, np.intc(mesh).copy(), is_time_reversal * 1, np.intc(rotations).copy()) return weights, third_q, mesh_points
def sc(self): """Simple-cubic crystal. This cell is characterized by having an atom in each of its vertices. Returns ------- dict A `dict` with the keys `natoms`, `box`, `x`, `y`, `z`, the number of atoms, the box size and the xyz of the atoms, respectively. Raises ------ ValueError If the number of atoms does not correspond with the number of sites that a sc crystal structure has. """ nside = np.cbrt(self.natoms, dtype=np.float32) tmp = np.intc(nside) if nside % tmp != 0: raise ValueError("Number of atoms must be a power of three") s_range = range(int(nside)) positions = list(it.product(s_range, repeat=3)) positions = np.array(positions, dtype=np.float32) positions = np.transpose(positions) * (self.box_size / nside) return { "natoms": self.natoms, "box": np.full(3, self.box_size, dtype=np.float32), "x": positions[0], "y": positions[1], "z": positions[2], }
def __init__(self): #id vars self.id_list = [ np.intc(random.randrange(0, 2147483647)) for i in range(50) ] self.id_list.sort(reverse=True) #rand_string vars self.alphabet = string.ascii_lowercase #cursos vars (deve ter alguma maneira de fazer isso mais bonito) self.curso_list = list() for _i in range(5): temp_str = '' for _j in range(19): temp_str = temp_str + (random.choice(self.alphabet)) self.curso_list.append(temp_str) #cpf vars self.cpf_list = [ random.randrange(10000000000, 99999999999) for i in range(30) ] self.cpf_list.sort(reverse=True) #date vars self.start_date = datetime.date(1970, 1, 1) self.end_date = datetime.date(2020, 10, 26) self.time_between = self.end_date - self.start_date self.days_between = self.time_between.days
def thunk(): z = outputs[0] if z[0] is None or z[0].shape!=inputs[0][0].shape: z[0] = cuda.CudaNdarray.zeros(inputs[0][0].shape) grid = (int(numpy.ceil(inputs[0][0].size / 512.)),1) pycuda_fct(inputs[0][0], z[0], numpy.intc(inputs[0][0].size), block=(512,1,1), grid=grid)
def add_g4_function(self, eta, zeta, lambd): """ Add a new symmetric function of type G4 """ NNcpp.AddSymG4(self._SymFunc, np.double(eta), np.double(zeta), np.intc(lambd))
def step(self, action): action_array = np.array([0, 0, 0, 0, 0, 0, 0], dtype=np.intc) if self.continuous: assert isinstance(action, np.float), "{}_{}".format(type(action), action) assert action >= -5.1 and action <= 5.1 action = np.intc(action * 100) action_array[3] = 1 # move forward action_array[0] = action # control direction else: assert isinstance(action, np.int), "{}_{}".format(type(action), action) assert action >= 0 and action < 3 if action == 0: # turn left action_array[0] = -64 elif action == 1: # turn right action_array[0] = 64 else: # move forward action_array[3] = 1 reward = self.lab.step(action_array) done = not self.lab.is_running() if done: obs = self.old_obs else: obs = self.get_obs() self.old_obs = obs info = {'dm_lab_events': self.lab.events()} return obs, reward, done, info
def what_is_int(): ''' - Python's "int" type is of arbitrary precision - However, when "int" is used as an arg/kwarg for the "dtype" parameter, it is equivalent to "np.int_". Confusing! - "np.int_" and "np.intc" are aliases for real underlying NumPy scalar types - The values of those aliases depend on the operating system - On my system, "np.int_" creates an object whose class is "numpy.int64" - "np.int_" has the same precision as a C long - On my system, "np.intc" creates an object whose class is "numpy.int32" - "np.intc" has the same precision as a C int - If I want some size other than those specified by the aliases, I'll have to use a class with an explicit size, e.g. np.int32 ''' print(np.int_ is np.int64) # True print(np.intc is np.int32) # True # No error because 1 certainly fits within the size of a C long ary = np.array(1, dtype=int) print(type(ary.dtype)) print(ary.dtype) # int64 #print(int(10**50)) # 100000000000000000000000000000000000000000000000000 #np.array(10**50, dtype=int) # OverflowError: Python int too large to convert to C long print(type(np.int_)) # <class 'type'> scalar = np.int_(10) print(type(scalar)) # <class 'numpy.int64'> scalar = np.int32(10) print(type(scalar)) # <class 'numpy.int32'> scalar = np.intc(10) print(type(scalar)) # <class 'numpy.int32'>
def __new__(cls, x=0): if isinstance(x, afnumpy.ndarray): return x.astype(cls) elif isinstance(x, numbers.Number): return numpy.intc(x) else: return afnumpy.array(x).astype(cls)
def key_points_tap(self, yellow): yellow_heights = [] yellow_points = [] yellow_widths = [] yellow_cp = yellow.copy() # 按结构树模式找所有轮廓 cnts, _ = cv2.findContours(yellow_cp, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # print("count:",len(cnts)) # 按区域大小排序,将所有轮廓存储下来 flag = 0 if len(cnts) == 0: flag = -1 #未检测到黄色区域 else: if len(cnts) >= 3: length = 3 else: length = len(cnts) for i in range(length): cnt_one = sorted(cnts, key=cv2.contourArea, reverse=True)[i] box = cv2.minAreaRect(cnt_one) width = box[1][0] height = box[1][1] yellow_points.append(np.intc(cv2.boxPoints(box))) yellow_widths.append(width) yellow_heights.append(height) flag = 1 if flag == -1: return -1, 0, 0, flag else: return yellow_points, yellow_widths, yellow_heights, flag
def expansion(self, niters=-1): """Do alpha-expansion for specified number of iterations. Return total energy after the expansion moves. If niters is set to -1, the algorithm will run until convergence.""" _cgco.gcoExpansion(self.handle, np.intc(niters), self.energy_temp_array) return self._convert_energy_back(self.energy_temp_array[0])
def read_edge_params_hco(fname_params, NUM_EDGES, MODEL_LIST): #define a dictionary to store params: params_dict = OrderedDict() #open params file: fh_mpr = open(fname_params, 'r') #skip header line: next(fh_mpr) for line in fh_mpr: if not line.strip(): continue #split the line: fields = line.strip().split() if (int(float(fields[0])) not in MODEL_LIST): continue # initialize the lists for all parameter types: PARAM_arr = np.zeros(NUM_EDGES, dtype=np.intc) for i in range(1, len(fields)): PARAM_arr[i - 1] = np.intc(float(fields[i])) # insert the params in the dictionary: params_dict[int(fields[0])] = PARAM_arr fh_mpr.close() return params_dict
def FFTdist(NoteSeqS,NoteDurS,Hz,det): FFT_seq=[] for a in range (0,len(NoteSeqS)):#helps that 64 IS a valid multiple...not sure how to construct for b in range (0,NoteDurS[a]): if (NoteSeqS[a]==-1): FFT_seq.append(ScaleRoot) else: FFT_seq.append(NoteSeqS[a]) #FFT_seq.append(NoteSeqS[a]) FFT_seq = FFT_seq#*64 # streatches length...so no trend if det==True: FFT_det=scipy.signal.detrend(FFT_seq) else: FFT_det = FFT_seq U_fft = scipy.fftpack.rfft(FFT_det) U_psd = U_fft * U_fft.conjugate() N = len(FFT_det) fs = Hz#Hz df = fs/float(N) freq = numpy.arange(0,fs,df) Nfi = numpy.intc(numpy.floor(N/2)) testfreq = freq[1:Nfi+1] xU_psd = U_psd/df/N**2 sU_psd = numpy.real(xU_psd[1:Nfi+1]) Log_testfreq = numpy.log10(testfreq) Log_sU_psd = numpy.log10(sU_psd) m1,b1 = numpy.polyfit(Log_testfreq,Log_sU_psd,1) return m1*-1
def get_symmetry(bulk, symprec=1e-5, angle_tolerance=-1.0): """ Return symmetry operations as hash. Hash key 'rotations' gives the numpy integer array of the rotation matrices for scaled positions Hash key 'translations' gives the numpy double array of the translation vectors in scaled positions """ # Atomic positions have to be specified by scaled positions for spglib. positions = bulk.get_scaled_positions().copy() lattice = bulk.get_cell().T.copy() numbers = np.intc(bulk.get_atomic_numbers()).copy() # Get number of symmetry operations and allocate symmetry operations # multi = spg.multiplicity(cell, positions, numbers, symprec) multi = 48 * bulk.get_number_of_atoms() rotation = np.zeros((multi, 3, 3), dtype='intc') translation = np.zeros((multi, 3)) # Get symmetry operations magmoms = bulk.get_magnetic_moments() if magmoms == None: num_sym = spg.symmetry(rotation, translation, lattice, positions, numbers, symprec, angle_tolerance) else: num_sym = spg.symmetry_with_collinear_spin(rotation, translation, lattice, positions, numbers, magmoms, symprec, angle_tolerance) return { 'rotations': rotation[:num_sym].copy(), 'translations': translation[:num_sym].copy() }
def populate_intervals(self, interval_nbr): if self.c_var == 0.3: mean_1 = 13 std_1 = 13 size_1 = 0.2 * N_SAMPLES mean_2 = 13 std_2 = 0.5 elif self.c_var == 0.7: mean_1 = 6 std_1 = 6 size_1 = 0.4 * N_SAMPLES mean_2 = 13 std_2 = 13 else: mean_1 = 3 std_1 = 1 size_1 = PARAMS_CV_1_TO_10[self.c_var - 1][0] * N_SAMPLES mean_2 = PARAMS_CV_1_TO_10[self.c_var - 1][1] std_2 = PARAMS_CV_1_TO_10[self.c_var - 1][2] size_2 = N_SAMPLES - size_1 norm_1 = np.random.normal(mean_1, std_1, int(size_1)) norm_2 = np.random.normal(mean_2, std_2, int(size_2)) bimodal = np.concatenate([norm_1, norm_2]) self.bimodal = np.intc((np.round(bimodal[bimodal > 1]))) self.intervals = np.random.choice(self.bimodal, interval_nbr)
def get_grid_triplets_at_q(q_grid_point, grid_points, third_q, weights, mesh): num_ir_tripltes = (weights > 0).sum() triplets = np.zeros((num_ir_tripltes, 3), dtype='intc') spg.grid_triplets_at_q(triplets, q_grid_point, grid_points, third_q, weights, np.intc(mesh).copy()) return triplets
def format_value(value, dtype): """ Set the datatype for a single value. Arguments: value (Series): non-iterable value to set. dtype (str): scalar data type. """ if dtype in ('date', 'datetime', 'timestamp', 'time'): value = np.datetime64(pd.to_datetime(value)) elif dtype in ('int', 'integer', 'bigint'): value = np.int_(value) elif dtype == 'mediumint': value = np.intc(value) elif dtype == 'smallint': value = np.short(value) elif dtype in ('tinyint', 'bit'): value = np.byte(value) elif dtype in ( 'float', 'real', 'double'): # approximate numeric data types for saving memory value = np.single(value) elif dtype in ('decimal', 'dec', 'numeric', 'money'): # exact numeric data types value = np.double(value) elif dtype in ('bool', 'boolean'): value = np.bool_(value) elif dtype in ('char', 'varchar', 'binary', 'text', 'string'): value = np.str_(value) else: value = np.str_(value) return value
def _pinv_multithread(self, matrices): inv_matrices = [] try: import anharmonic._forcefit as forcefit multi = len(matrices) row_nums = np.intc([m.shape[0] for m in matrices]) info = np.zeros(len(row_nums), dtype='intc') max_row_num = max(row_nums) column_num = matrices[0].shape[1] mats_in = np.zeros((multi, max_row_num * column_num), dtype='double') for i in range(multi): mats_in[i, :row_nums[i] * column_num] = matrices[i].flatten() mats_out = np.zeros_like(mats_in) forcefit.pinv_mt(mats_in, mats_out, row_nums, max_row_num, column_num, self._pinv_cutoff, info) inv_matrices = [ mats_out[i, :row_nums[i] * column_num].reshape(column_num, -1) for i in range(multi) ] except ImportError: for mat in matrices: inv_mat = np.linalg.pinv(mat) inv_matrices.append(inv_mat) return inv_matrices
def loop(scr, max_value): scr.clear() height, width = scr.getmaxyx() prefix = intc(100) scr.addstr(0, 0, ' ' * width * (height - 1), 1 << 8) try: scr.addstr(height - 1, 0, ' ' * width, 1 << 8) except: pass scr.refresh() with open('err.txt', 'w') as err: while (True): colors = color_gen(max_value) for y in range(2, height - 1): for x in range(0, 36): try: scr.addstr(y, x, '▓', next(colors)) #scr.addstr(y, x, ' ', next(colors) ) #scr.addstr(y, x, '▄', next(colors) ) except Exception as e: pass #err.write(str(repr(e.args))) #err.write(str(repr(e))) scr.addstr(0, 0, '{}x{}'.format(height, width), 250 << 8) scr.refresh() scr.timeout(300) scr.getch()
def show2(arr): print("按字母顺序排序:") ls1= arr[:,0] ls2= np.intc(arr[:,1]) d = dict(zip(ls1,ls2)) for k in sorted(d): print('{:>30}{:>20}' .format(k, d[k]))
def expansionOnAlpha(self, label): """Do one alpha-expansion move for the specified label. Return True if the energy decreases, return False otherwise.""" if not (0 <= label < self.numLabels): raise IndexOutOfBoundError() _cgco.gcoExpansionOnAlpha(self.handle, np.intc(label), self.tempArray) return self.tempArray[0] == 1
def get_interior_ring(geometry, index, **kwargs): """Returns the nth interior ring of a polygon. Parameters ---------- geometry : Geometry or array_like index : int or array_like Negative values count from the end of the interior rings backwards. **kwargs For other keyword-only arguments, see the `NumPy ufunc docs <https://numpy.org/doc/stable/reference/ufuncs.html#ufuncs-kwargs>`_. See also -------- get_exterior_ring get_num_interior_rings Examples -------- >>> polygon_with_hole = Geometry("POLYGON((0 0, 0 10, 10 10, 10 0, 0 0), (2 2, 2 4, 4 4, 4 2, 2 2))") >>> get_interior_ring(polygon_with_hole, 0) <pygeos.Geometry LINEARRING (2 2, 2 4, 4 4, 4 2, 2 2)> >>> get_interior_ring(Geometry("POINT (1 1)"), 0) is None True """ return lib.get_interior_ring(geometry, np.intc(index), **kwargs)
def _set_nosym(self): translations = [] rotations = [] if 'get_supercell_to_unitcell_map' in dir(self.__cell): s2u_map = self.__cell.get_supercell_to_unitcell_map() positions = self.__cell.get_scaled_positions() for i, j in enumerate(s2u_map): if j == 0: ipos0 = i break for i, p in zip(s2u_map, positions): if i == 0: trans = p - positions[ipos0] trans -= np.floor(trans) translations.append(trans) rotations.append(np.eye(3, dtype='intc')) self.map_atoms = s2u_map else: rotations.append(np.eye(3, dtype=int)) translations.append(np.zeros(3, dtype='double')) self.map_atoms = range(self.__cell.get_number_of_atoms()) self.symmetry_operations = { 'rotations': np.intc(rotations), 'translations': np.array(translations, dtype='double') } self.international_table = 'P1 (1)' self.wyckoff_letters = ['a'] * self.__cell.get_number_of_atoms()
def Candidate_Add(choices, itsct, col_index, dim, answer_found): #If it's deep enough, then the datas in the tree are a set of available resolution, turning answer_foun to True to stop searching. if col_index + 1 == dim: answer_found = True print("Done") #Otherwise, keep searching to the deeper node. if col_index + 1 < dim and not answer_found: itsct_temp = itsct_update(itsct, choices.data, col_index) #Intersection table update row_cnddt = np.where( itsct_temp[:, col_index + 1] == 0)[0] #Find available candidate choices if np.size(row_cnddt ) != 0: #If it's not a deadlock, try those candidates. #Calculate the number of blocking for choosing each candidate. row_cnddt_itsct = np.array([]) for e in row_cnddt: itsct_cnddt_temp = itsct_update(itsct_temp, e, col_index + 1) row_cnddt_itsct = np.append(row_cnddt_itsct, np.sum(itsct_cnddt_temp)) row_cnddt_itsct = np.intc(row_cnddt_itsct) #Choose the candidate node in the increasing order of the number of blocking for e in row_cnddt[np.argsort(row_cnddt_itsct)]: #If the answer has been found, it will stop adding other children by breaking the for loop. if answer_found: break #Otherwise, it will keep trying another candidate node, after removing the previous fail node if exists. elif len(choices.children) != 0: choices.children.pop() choices.children.append(Node(e)) answer_found = Candidate_Add(choices.children[-1], itsct_temp, col_index + 1, dim, answer_found) return answer_found
def get_point(geometry, index): """Returns the nth point of a linestring or linearring. Parameters ---------- geometry : Geometry or array_like index : int or array_like Negative values count from the end of the linestring backwards. See also -------- get_num_points Examples -------- >>> line = Geometry("LINESTRING (0 0, 1 1, 2 2, 3 3)") >>> get_point(line, 1) <pygeos.Geometry POINT (1 1)> >>> get_point(line, -2) <pygeos.Geometry POINT (2 2)> >>> get_point(line, [0, 3]).tolist() [<pygeos.Geometry POINT (0 0)>, <pygeos.Geometry POINT (3 3)>] >>> get_point(Geometry("LINEARRING (0 0, 1 1, 2 2, 0 0)"), 1) <pygeos.Geometry POINT (1 1)> >>> get_point(Geometry("MULTIPOINT (0 0, 1 1, 2 2, 3 3)"), 1) is None True >>> get_point(Geometry("POINT (1 1)"), 0) is None True """ return ufuncs.get_point(geometry, np.intc(index))
def prep_colors(colors, font_color): init_c = curses.init_color init_p = curses.init_pair # The on-all-color font fg. init_c(font_color[0], *font_color[1]) ## Experimenting with half height block as fg character for 2x vertical resolution. ## This guy : '▄' # For now make the max val just have 2x max cn = colors[0][0] init_c(cn, *colors[0][1]) init_p(cn, cn, cn) # For fg == 1 lower. # BG is "actual" value. for color_num, color_values in colors[1:]: init_c(color_num, *color_values) init_p(color_num, color_num, color_num-1) # Real black on white even with weird terminal colors/themes. init_c(98, 0,0,0) init_p(98, 98, colors[-1][0]) return intc(len(colors)-1)
def test_numpy(self): """NumPy objects get serialized to readable JSON.""" l = [ np.float32(12.5), np.float64(2.0), np.float16(0.5), np.bool(True), np.bool(False), np.bool_(True), np.unicode_("hello"), np.byte(12), np.short(12), np.intc(-13), np.int_(0), np.longlong(100), np.intp(7), np.ubyte(12), np.ushort(12), np.uintc(13), np.ulonglong(100), np.uintp(7), np.int8(1), np.int16(3), np.int32(4), np.int64(5), np.uint8(1), np.uint16(3), np.uint32(4), np.uint64(5), ] l2 = [l, np.array([1, 2, 3])] roundtripped = loads(dumps(l2, cls=EliotJSONEncoder)) self.assertEqual([l, [1, 2, 3]], roundtripped)
def get_geometry(geometry, index): """Returns the nth geometry from a collection of geometries. Parameters ---------- geometry : Geometry or array_like index : int or array_like Negative values count from the end of the collection backwards. Notes ----- - simple geometries act as length-1 collections - out-of-range values return None See also -------- get_num_geometries Examples -------- >>> multipoint = Geometry("MULTIPOINT (0 0, 1 1, 2 2, 3 3)") >>> get_geometry(multipoint, 1) <pygeos.Geometry POINT (1 1)> >>> get_geometry(multipoint, -1) <pygeos.Geometry POINT (3 3)> >>> get_geometry(multipoint, 5) is None True >>> get_geometry(Geometry("POINT (1 1)"), 0) <pygeos.Geometry POINT (1 1)> >>> get_geometry(Geometry("POINT (1 1)"), 1) is None True """ return ufuncs.get_geometry(geometry, np.intc(index))