Python create grid
60 Python code examples are found related to "
create grid".
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: features.py From pyvista with MIT License | 6 votes |
def create_grid(dataset, dimensions=(101, 101, 101)): """Create a uniform grid surrounding the given dataset. The output grid will have the specified dimensions and is commonly used for interpolating the input dataset. """ bounds = np.array(dataset.bounds) if dimensions is None: # TODO: we should implement an algorithm to automatically determine an # "optimal" grid size by looking at the sparsity of the points in the # input dataset - I actually think VTK might have this implemented # somewhere raise NotImplementedError('Please specify dimensions.') dimensions = np.array(dimensions, dtype=int) image = pyvista.UniformGrid() image.dimensions = dimensions dims = (dimensions - 1) dims[dims == 0] = 1 image.spacing = (bounds[1::2] - bounds[:-1:2]) / dims image.origin = bounds[::2] return image
Example 2
Source File: gmt.py From geoist with MIT License | 6 votes |
def createSampleGrid(M,N): """Used for internal testing - create an NxN grid with lower left corner at 0.5,0.5, dx/dy = 1.0. :param M: Number of rows in output grid :param N: Number of columns in output grid :returns: GMTGrid object where data values are an NxN array of values from 0 to N-squared minus 1, and geodict lower left corner is at 0.5/0.5 and cell dimensions are 1.0. """ data = np.arange(0,M*N).reshape(M,N) data = data.astype(np.int32) #arange gives int64 by default, not supported by netcdf3 xvar = np.arange(0.5,0.5+N,1.0) yvar = np.arange(0.5,0.5+M,1.0) geodict = {'ny':N, 'nx':N, 'xmin':0.5, 'xmax':xvar[-1], 'ymin':0.5, 'ymax':yvar[-1], 'dx':1.0, 'dy':1.0} gmtgrid = GMTGrid(data,geodict) return gmtgrid
Example 3
Source File: plane.py From autoregressive-energy-machines with MIT License | 6 votes |
def create_gaussian_grid_data(n, width, rotate=True): bound = -2.5 means = np.array([ (x + 1e-3 * np.random.rand(), y + 1e-3 * np.random.rand()) for x in np.linspace(-bound, bound, width) for y in np.linspace(-bound, bound, width) ]) covariance_factor = 0.06 * np.eye(2) index = np.random.choice(range(width ** 2), size=n, replace=True) noise = np.random.randn(n, 2) data = means[index] + noise @ covariance_factor if rotate: rotation_matrix = np.array([ [1 / np.sqrt(2), -1 / np.sqrt(2)], [1 / np.sqrt(2), 1 / np.sqrt(2)] ]) data = data @ rotation_matrix data = data.astype(np.float32) return data
Example 4
Source File: ConGAN.py From ConGAN with MIT License | 6 votes |
def create_grid(self, half_size): X,Y = np.mgrid[-half_size:half_size,-half_size:half_size] + 0.5 grid = np.vstack((X.flatten(), Y.flatten())).T / half_size # This part of code is highly unnecessary, but might be helpful if you have some # kind of rotation diversity in your data ''' #adding ability to construct rotation dependency ref_points = np.array([[-1,-1], [1, 1], [-1, 1], [1, -1]]) sz = grid.shape[0] add = np.empty((sz, 0)) for ref in ref_points: grid_ = grid - ref r = np.linalg.norm(grid_, axis = 1) phi = np.arctan2(grid_[:,1], grid_[:,0]) add = np.concatenate((add, r.reshape(sz,1), np.sin(phi).reshape(sz,1), np.cos(phi).reshape(sz,1)), axis = 1) grid = np.concatenate((grid, add), axis = 1) ''' return grid
Example 5
Source File: structures.py From atomium with MIT License | 6 votes |
def create_grid(self, size=1, margin=0): """A generator which models a grid around the structure and returns the coordinates of all the points in that grid. The origin is always one of those points, and the grid will be a box. :param int size: The spacing between grid points. The default is 1. :param int margin: How far to extend the grid beyond the structure\ coordinates. The default is 0. :rtype: ``tuple``""" atom_locations = [atom.location for atom in self.atoms()] dimension_values = [] for dimension in range(3): coordinates = [loc[dimension] for loc in atom_locations] min_, max_ = min(coordinates) - margin, max(coordinates) + margin values = [0] while values[0] > min_: values.insert(0, values[0] - size) while values[-1] < max_: values.append(values[-1] + size) dimension_values.append(values) for x in dimension_values[0]: for y in dimension_values[1]: for z in dimension_values[2]: yield (x, y, z)
Example 6
Source File: main.py From sudoku-py with MIT License | 6 votes |
def create_grid_mask(vertical, horizontal): grid = cv2.add(horizontal, vertical) grid = cv2.adaptiveThreshold(grid, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 235, 2) grid = cv2.dilate(grid, cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)), iterations=2) pts = cv2.HoughLines(grid, .3, np.pi / 90, 200) def draw_lines(im, pts): im = np.copy(im) pts = np.squeeze(pts) for r, theta in pts: a = np.cos(theta) b = np.sin(theta) x0 = a * r y0 = b * r x1 = int(x0 + 1000 * (-b)) y1 = int(y0 + 1000 * a) x2 = int(x0 - 1000 * (-b)) y2 = int(y0 - 1000 * a) cv2.line(im, (x1, y1), (x2, y2), (255, 255, 255), 2) return im lines = draw_lines(grid, pts) mask = cv2.bitwise_not(lines) return mask
Example 7
Source File: PRO_GAN.py From pro_gan_pytorch with MIT License | 6 votes |
def create_grid(samples, scale_factor, img_file): """ utility function to create a grid of GAN samples :param samples: generated samples for storing :param scale_factor: factor for upscaling the image :param img_file: name of file to write :return: None (saves a file) """ from torchvision.utils import save_image from torch.nn.functional import interpolate # upsample the image if scale_factor > 1: samples = interpolate(samples, scale_factor=scale_factor) # save the images: save_image(samples, img_file, nrow=int(np.sqrt(len(samples))), normalize=True, scale_each=True)
Example 8
Source File: grid.py From chaospy with MIT License | 6 votes |
def create_grid_samples(order, dim=1): """ Create samples from a regular grid. Args: order (int): The order of the grid. Defines the number of samples. dim (int): The number of dimensions in the grid Returns (numpy.ndarray): Regular grid with ``shape == (dim, order)``. """ x_data = numpy.arange(1, order+1)/(order+1.) x_data = chaospy.quadrature.combine([x_data]*dim) return x_data.T
Example 9
Source File: grid.py From gpytorch with MIT License | 6 votes |
def create_grid( grid_sizes: List[int], grid_bounds: List[Tuple[float, float]], extend: bool = True, device="cpu", dtype=torch.float, ) -> List[torch.Tensor]: """ Creates a grid represented by a list of 1D Tensors representing the projections of the grid into each dimension If `extend`, we extend the grid by two points past the specified boundary which can be important for getting good grid interpolations """ grid = [] for i in range(len(grid_bounds)): grid_diff = float(grid_bounds[i][1] - grid_bounds[i][0]) / (grid_sizes[i] - 2) if extend: proj = torch.linspace( grid_bounds[i][0] - grid_diff, grid_bounds[i][1] + grid_diff, grid_sizes[i], device=device, dtype=dtype, ) else: proj = torch.linspace(grid_bounds[i][0], grid_bounds[i][1], grid_sizes[i], device=device, dtype=dtype,) grid.append(proj) return grid
Example 10
Source File: grid.py From gpytorch with MIT License | 6 votes |
def create_data_from_grid(grid: List[torch.Tensor]) -> torch.Tensor: """ Args: :attr:`grid` (List[Tensor]) Each Tensor is a 1D set of increments for the grid in that dimension Returns: `grid_data` (Tensor) Returns the set of points on the grid going by column-major order (due to legacy reasons). """ if torch.is_tensor(grid): grid = convert_legacy_grid(grid) ndims = len(grid) assert all(axis.dim() == 1 for axis in grid) projections = torch.meshgrid(*grid) grid_tensor = torch.stack(projections, axis=-1) # Note that if we did # grid_data = grid_tensor.reshape(-1, ndims) # instead, we would be iterating through the points of our grid from the # last data dimension to the first data dimension. However, due to legacy # reasons, we need to iterate from the first data dimension to the last data # dimension when creating grid_data grid_data = grid_tensor.permute(*(reversed(range(ndims + 1)))).reshape(ndims, -1).transpose(0, 1) return grid_data
Example 11
Source File: misc.py From disentangling_conditional_gans with MIT License | 6 votes |
def create_image_grid(images, grid_size=None): assert images.ndim == 3 or images.ndim == 4 num, img_w, img_h = images.shape[0], images.shape[-1], images.shape[-2] if grid_size is not None: grid_w, grid_h = tuple(grid_size) else: grid_w = max(int(np.ceil(np.sqrt(num))), 1) grid_h = max((num - 1) // grid_w + 1, 1) grid = np.zeros(list(images.shape[1:-2]) + [grid_h * img_h, grid_w * img_w], dtype=images.dtype) for idx in range(num): x = (idx % grid_w) * img_w y = (idx // grid_w) * img_h grid[..., y : y + img_h, x : x + img_w] = images[idx] return grid
Example 12
Source File: gold_to_grid.py From propara with Apache License 2.0 | 6 votes |
def create_grid_from_gold(output_filepath: str): # Start with a clean copy. paras.clear() out_file = open(output_filepath, "w") for process_id in propara.get_para_ids(): sentences = propara.get_sentences(process_id) num_steps = len(sentences) participants = propara.get_participants(process_id) for participant_id in range(0, len(participants), 1): for step_id in range(1, num_steps+1, 1): before_val = propara.get_grid(process_id)[step_id-1][participant_id] after_val = propara.get_grid(process_id)[step_id][participant_id] action = 'NONE' if before_val == "-" and not after_val == '-': action = 'CREATE' elif not before_val == "-" and after_val == '-': action = 'DESTROY' elif not before_val == after_val: action = 'MOVE' out_file.write('\t'.join([str(process_id), str(step_id), participants[participant_id], action, before_val, after_val]) + "\n") out_file.close()
Example 13
Source File: ops.py From blender_autocomplete with GNU General Public License v3.0 | 6 votes |
def create_grid(bm: 'bmesh.types.BMesh', x_segments: int, y_segments: int, size: float, matrix: 'mathutils.Matrix', calc_uvs: bool) -> dict: '''Creates a grid with a variable number of subdivisions :param bm: The bmesh to operate on. :type bm: 'bmesh.types.BMesh' :param x_segments: number of x segments :type x_segments: int :param y_segments: number of y segments :type y_segments: int :param size: size of the grid :type size: float :param matrix: matrix to multiply the new geometry with :type matrix: 'mathutils.Matrix' :param calc_uvs: calculate default UVs :type calc_uvs: bool :return: verts: output vertstype list of (bmesh.types.BMVert) ''' pass
Example 14
Source File: misc.py From Keras-progressive_growing_of_gans with MIT License | 6 votes |
def create_image_grid(images, grid_size=None): assert images.ndim == 3 or images.ndim == 4 num, img_w, img_h = images.shape[0], images.shape[-2], images.shape[-3] if grid_size is not None: grid_w, grid_h = tuple(grid_size) else: grid_w = max(int(np.ceil(np.sqrt(num))), 1) grid_h = max((num - 1) / grid_w + 1, 1) #print("images.shape[1:-2]:",(images.shape[-1],)) grid = np.zeros( [grid_h * img_h, grid_w * img_w]+list((images.shape[-1],)), dtype=images.dtype) for idx in range(num): x = (idx % grid_w) * img_w y = (idx // grid_w) * img_h #print("x:",x) #print("y:",y) #print("grid.shape:",grid.shape) grid[y : y + img_h, x : x + img_w,...] = images[idx] return grid
Example 15
Source File: vizutils.py From xRBM with MIT License | 6 votes |
def create_2d_filters_grid(W, filter_shape, grid_size, grid_gap=(0,0)): out_shape = (grid_size[0]*(filter_shape[0]+grid_gap[0]), grid_size[1]*(filter_shape[1]+grid_gap[1])) out_img = np.zeros(out_shape) r = 0 c = 0 def scaleme(ww): return (ww - ww.min())/(ww.max() - ww.min()) for w in W: im = scaleme(w.reshape(filter_shape)) out_img[r:r+filter_shape[0], c:c+filter_shape[1]] = im c += filter_shape[1]+grid_gap[1] if c>=out_shape[1]: c = 0 r = r + filter_shape[0] + 1 return out_img
Example 16
Source File: grid.py From doatools.py with MIT License | 6 votes |
def create_refined_grid_at(self, coord, density, span): """Creates a finer search grid around the given coordinate. Args: coord: A tuple of integers representing a single coordinate within this grid. density (int): Controls number of new intervals between two adjacent points in the original grid. span (int): Controls how many adjacent intervals in the original grid will be considered around the point specified by ``coord`` when performing the refinement. Returns: A refined grid. """ raise NotImplementedError()
Example 17
Source File: projections.py From DeepDepthDenoising with MIT License | 6 votes |
def create_image_domain_grid(width, height, data_type=torch.float32): v_range = ( torch.arange(0, height) # [0 - h] .view(1, height, 1) # [1, [0 - h], 1] .expand(1, height, width) # [1, [0 - h], W] .type(data_type) # [1, H, W] ) u_range = ( torch.arange(0, width) # [0 - w] .view(1, 1, width) # [1, 1, [0 - w]] .expand(1, height, width) # [1, H, [0 - w]] .type(data_type) # [1, H, W] ) ones = ( torch.ones(1, height, width) # [1, H, W] := 1 .type(data_type) ) return torch.stack((u_range, v_range, ones), dim=1) # [1, 3, H, W]
Example 18
Source File: discretize.py From angela with MIT License | 6 votes |
def create_uniform_grid(low, high, bins=(10,)): """Define a uniformly-spaced grid that can be used to discretize a space. Params ====== low (array_like): Lower bounds for each dimension of the continuous space. high (array_like): Upper bounds for each dimension of the continuous space. bins (tuple): Number of bins along each corresponding dimension. Returns ======= grid (list of array_like): A list of arrays containing split points for each dimension. """ split_list = [] for dim_low, dim_high, dim_bin in zip(low, high, bins): step = (dim_high - dim_low) / dim_bin split_list.append(np.linspace(dim_low+step, dim_high-step, num=dim_bin-1)) return split_list
Example 19
Source File: train_network.py From T2F with MIT License | 6 votes |
def create_grid(samples, scale_factor, img_file, real_imgs=False): """ utility function to create a grid of GAN samples :param samples: generated samples for storing :param scale_factor: factor for upscaling the image :param img_file: name of file to write :param real_imgs: turn off the scaling of images :return: None (saves a file) """ from torchvision.utils import save_image from torch.nn.functional import interpolate samples = th.clamp((samples / 2) + 0.5, min=0, max=1) # upsample the image if not real_imgs and scale_factor > 1: samples = interpolate(samples, scale_factor=scale_factor) # save the images: save_image(samples, img_file, nrow=int(np.sqrt(len(samples))))
Example 20
Source File: utils.py From MONAI with Apache License 2.0 | 6 votes |
def create_grid(spatial_size, spacing=None, homogeneous: bool = True, dtype: np.dtype = float): """ compute a `spatial_size` mesh. Args: spatial_size (sequence of ints): spatial size of the grid. spacing (sequence of ints): same len as ``spatial_size``, defaults to 1.0 (dense grid). homogeneous: whether to make homogeneous coordinates. dtype (type): output grid data type. """ spacing = spacing or tuple(1.0 for _ in spatial_size) ranges = [np.linspace(-(d - 1.0) / 2.0 * s, (d - 1.0) / 2.0 * s, int(d)) for d, s in zip(spatial_size, spacing)] coords = np.asarray(np.meshgrid(*ranges, indexing="ij"), dtype=dtype) if not homogeneous: return coords return np.concatenate([coords, np.ones_like(coords[:1])])
Example 21
Source File: plot_analysed_telemetry.py From SpaceXtract with MIT License | 6 votes |
def create_grid(ax, x, y, major_x_interval, major_y_interval, minor_x_interval=0, minor_y_interval=0): major_x = get_ticks_minor(x, major_x_interval) major_y = get_ticks_minor(y, major_y_interval) ax.set_xticks(major_x) ax.set_yticks(major_y) if minor_x_interval != 0: minor_x = get_ticks_minor(x, minor_x_interval) ax.set_xticks(minor_x, minor=True) if minor_y_interval != 0: minor_y = get_ticks_minor(y, minor_y_interval) ax.set_yticks(minor_y, minor=True) ax.grid(which='major') ax.grid(which='minor', alpha=0.5)
Example 22
Source File: bitmapviz.py From MTSAnomalyDetection with Apache License 2.0 | 6 votes |
def create_bitmap_grid(bitmap, n, num_bins, level_size): """ Arranges a time-series bitmap into a 2-D grid for heatmap visualization """ assert num_bins % n == 0, 'num_bins has to be a multiple of n' m = num_bins // n row_count = int(math.pow(m, level_size)) col_count = int(math.pow(n, level_size)) grid = np.full((row_count, col_count), 0.0) for feat, count in bitmap.items(): i, j = symbols2index(m, n, feat) grid[i, j] = count return grid
Example 23
Source File: grid.py From SphericalViewSynthesis with BSD 2-Clause "Simplified" License | 6 votes |
def create_spherical_grid(width, horizontal_shift=(-numpy.pi - numpy.pi / 2.0), vertical_shift=(-numpy.pi / 2.0), data_type=torch.float32): height = int(width // 2.0) v_range = ( torch.arange(0, height) # [0 - h] .view(1, height, 1) # [1, [0 - h], 1] .expand(1, height, width) # [1, [0 - h], W] .type(data_type) # [1, H, W] ) u_range = ( torch.arange(0, width) # [0 - w] .view(1, 1, width) # [1, 1, [0 - w]] .expand(1, height, width) # [1, H, [0 - w]] .type(data_type) # [1, H, W] ) u_range *= (2 * numpy.pi / width) # [0, 2 * pi] v_range *= (numpy.pi / height) # [0, pi] u_range += horizontal_shift # [-hs, 2 * pi - hs] -> standard values are [-3 * pi / 2, pi / 2] v_range += vertical_shift # [-vs, pi - vs] -> standard values are [-pi / 2, pi / 2] return torch.stack((u_range, v_range), dim=1) # [1, 2, H, W]
Example 24
Source File: gui.py From minesweeper with MIT License | 6 votes |
def create_grid(self, grid_width, grid_height): """Create a grid layout with stacked widgets. Parameters ---------- grid_width : int the width of the grid grid_height : int the height of the grid """ self.grid_layout = QGridLayout() self.setLayout(self.grid_layout) self.grid_layout.setSpacing(1) self.grid_wgs = {} for i in xrange(grid_height): for j in xrange(grid_width): self.grid_wgs[(i, j)] = FieldWidget() self.grid_layout.addWidget(self.grid_wgs[(i, j)], i, j)
Example 25
Source File: geometry.py From renpy-shader with MIT License | 6 votes |
def createGrid(rect, xCount, yCount): vertices = [] uvs = [] indices = [] for y in range(yCount): yUv = y / float(yCount - 1) yPos = _interpolate(rect[1], rect[1] + rect[3], yUv) for x in range(xCount): xUv = x / float(xCount - 1) xPos = _interpolate(rect[0], rect[0] + rect[2], xUv) vertices.append((xPos, yPos)) uvs.append((xUv, yUv)) if y < yCount -1 and x < xCount - 1: index = x * xCount + y indices.extend([index, index + 1, index + xCount]) indices.extend([index + xCount, index + 1, index + xCount + 1]) return vertices, uvs, indices
Example 26
Source File: data.py From bayesian-yolov3 with MIT License | 6 votes |
def create_prior_box_grid(det_layer): boxes_per_cell = len(det_layer.priors) prior_box_grid = np.zeros((det_layer.h, det_layer.w, boxes_per_cell, 4)) for row in range(det_layer.h): for col in range(det_layer.w): for box, prior in enumerate(det_layer.priors): y_center = (row + 0.5) / det_layer.h x_center = (col + 0.5) / det_layer.w h2 = prior.h / 2. w2 = prior.w / 2. ymin = y_center - h2 xmin = x_center - w2 ymax = y_center + h2 xmax = x_center + w2 prior_box_grid[row, col, box, :] = [ymin, xmin, ymax, xmax] # tf.image bbox format return prior_box_grid
Example 27
Source File: GAN.py From BMSG-GAN with MIT License | 6 votes |
def create_grid(self, samples, img_files): """ utility function to create a grid of GAN samples :param samples: generated samples for storing list[Tensors] :param img_files: list of names of files to write :return: None (saves multiple files) """ from torchvision.utils import save_image from torch.nn.functional import interpolate from numpy import sqrt, power # dynamically adjust the colour of the images samples = [Generator.adjust_dynamic_range(sample) for sample in samples] # resize the samples to have same resolution: for i in range(len(samples)): samples[i] = interpolate(samples[i], scale_factor=power(2, self.depth - 1 - i)) # save the images: for sample, img_file in zip(samples, img_files): save_image(sample, img_file, nrow=int(sqrt(sample.shape[0])), normalize=True, scale_each=True, padding=0)
Example 28
Source File: grid_types.py From gempy with GNU Lesser General Public License v3.0 | 6 votes |
def create_regular_grid_3d(extent, resolution): """ Method to create a 3D regular grid where is interpolated Args: extent (list): [x_min, x_max, y_min, y_max, z_min, z_max] resolution (list): [nx, ny, nz]. Returns: numpy.ndarray: Unraveled 3D numpy array where every row correspond to the xyz coordinates of a regular grid """ dx = (extent[1] - extent[0]) / resolution[0] dy = (extent[3] - extent[2]) / resolution[1] dz = (extent[5] - extent[4]) / resolution[2] g = np.meshgrid( np.linspace(extent[0] + dx / 2, extent[1] - dx / 2, resolution[0], dtype="float64"), np.linspace(extent[2] + dy / 2, extent[3] - dy / 2, resolution[1], dtype="float64"), np.linspace(extent[4] + dz / 2, extent[5] - dz / 2, resolution[2], dtype="float64"), indexing="ij" ) values = np.vstack(tuple(map(np.ravel, g))).T.astype("float64") return values
Example 29
Source File: anchors.py From zsgnet-pytorch with MIT License | 6 votes |
def create_grid(size, flatten=True): "Create a grid of a given `size`." if isinstance(size, tuple): H, W = size else: H, W = size, size grid = torch.FloatTensor(H, W, 2) linear_points = torch.linspace(-1+1/W, 1-1/W, W) if W > 1 else torch.tensor([0.]) grid[:, :, 1] = torch.ger(torch.ones( H), linear_points).expand_as(grid[:, :, 0]) linear_points = torch.linspace(-1+1/H, 1-1/H, H) if H > 1 else torch.tensor([0.]) grid[:, :, 0] = torch.ger( linear_points, torch.ones(W)).expand_as(grid[:, :, 1]) return grid.view(-1, 2) if flatten else grid
Example 30
Source File: project.py From albion with GNU General Public License v3.0 | 5 votes |
def create_grid(self): with self.connect() as con: cur = con.cursor() cur.execute("""DROP TABLE IF EXISTS _albion.grid""") cur.execute("""CREATE TABLE _albion.grid as ( SELECT id, geom FROM ST_CreateRegularGrid());""") cur.execute("""ALTER TABLE _albion.grid ADD CONSTRAINT albion_grid_pkey PRIMARY KEY (id);""") cur.execute("""CREATE INDEX sidx_grid_geom ON _albion.grid USING gist (geom);""") con.commit()
Example 31
Source File: advanced_config.py From me-ica with GNU Lesser General Public License v2.1 | 5 votes |
def create_component_grid(self, parent_sizer, components, cols=2): for row in self.chunk(components, cols): hsizer = wx.BoxSizer(wx.HORIZONTAL) for widget in filter(None, row): hsizer.Add(widget.panel, 1, wx.EXPAND | wx.LEFT | wx.RIGHT, 10) parent_sizer.Add(hsizer, 0, wx.EXPAND) parent_sizer.AddSpacer(20)
Example 32
Source File: cf_writer.py From satpy with GNU General Public License v3.0 | 5 votes |
def create_grid_mapping(area): """Create the grid mapping instance for `area`.""" # let pyproj do the heavily lifting # pyproj 2.0+ required grid_mapping = area.crs.to_cf() return area.area_id, grid_mapping
Example 33
Source File: hexbuilder.py From ExCo with GNU General Public License v3.0 | 5 votes |
def create_grid(self, *array_grid): self.draw() paint_all_edges = [False] if isinstance(array_grid[0], bool): paint_all_edges[0] = array_grid[0] array_grid = array_grid[1:] for ag in array_grid: paint_all_edges.append(False) if isinstance(ag, int): self.next_step_draw(ag) elif isinstance(ag, tuple): self.next_step_draw(ag[0]) paint_all_edges[-1] = ag[1] else: raise Exception("create_grid item has to be an int (0 >= i < 6) or a tuple(int, bool)!") # Paint the edges as needed number_of_steps = len(GridGenerator.directions) steps = [self.steps[GridGenerator.directions[x]] for x in range(number_of_steps)] positions = [(int(x[0]), int(x[1])) for x in self.grid_positions] for j, gp in enumerate(self.grid_positions): paint_edge = [True, True, True, True, True, True] if paint_all_edges[j] != True: for i, s in enumerate(steps): test_step = (int(gp[0] + s[0]), int(gp[1] + s[1])) comparisons = [(abs(x[0]-test_step[0]) < 5 and abs(x[1]-test_step[1]) < 5) for x in positions] if any(comparisons): paint_edge[i] = False self.draw_line_hexagon( position = gp, line_width = self.line_width, line_color = self.line_color, paint_enabled = paint_edge, shadow = True )
Example 34
Source File: kitti_utils.py From avod-ssd with MIT License | 5 votes |
def create_voxel_grid_3d(self, sample_name, ground_plane, source='lidar', filter_type='slice'): """Generates a filtered voxel grid from stereo data Args: sample_name: image name to generate stereo pointcloud from ground_plane: ground plane coefficients source: source of the pointcloud to create bev images either "stereo" or "lidar" filter_type: type of point filter to use 'slice' for slice filtering (offset + ground) 'offset' for offset filtering only 'area' for area filtering only Returns: voxel_grid_3d: 3d voxel grid from the given image """ img_idx = int(sample_name) points = self.get_point_cloud(source, img_idx) if filter_type == 'slice': filtered_points = self._apply_slice_filter(points, ground_plane) elif filter_type == 'offset': filtered_points = self._apply_offset_filter(points, ground_plane) elif filter_type == 'area': # A None ground plane will filter the points to the area extents filtered_points = self._apply_offset_filter(points, None) else: raise ValueError("Invalid filter_type {}, should be 'slice', " "'offset', or 'area'".format(filter_type)) # Create Voxel Grid voxel_grid_3d = VoxelGrid() voxel_grid_3d.voxelize(filtered_points, self.voxel_size, extents=self.area_extents) return voxel_grid_3d
Example 35
Source File: kitti_utils.py From avod-ssd with MIT License | 5 votes |
def create_sliced_voxel_grid_2d(self, sample_name, source, image_shape=None): """Generates a filtered 2D voxel grid from point cloud data Args: sample_name: image name to generate stereo pointcloud from source: point cloud source, e.g. 'lidar' image_shape: image dimensions [h, w], only required when source is 'lidar' or 'depth' Returns: voxel_grid_2d: 3d voxel grid from the given image """ img_idx = int(sample_name) ground_plane = obj_utils.get_road_plane(img_idx, self.dataset.planes_dir) point_cloud = self.get_point_cloud(source, img_idx, image_shape=image_shape) filtered_points = self._apply_slice_filter(point_cloud, ground_plane) # Create Voxel Grid voxel_grid_2d = VoxelGrid2D() voxel_grid_2d.voxelize_2d(filtered_points, self.voxel_size, extents=self.area_extents, ground_plane=ground_plane, create_leaf_layout=True) return voxel_grid_2d
Example 36
Source File: tetris.py From Learning-Python-by-building-games with MIT License | 5 votes |
def create_Grid(screen_surface, grid_scene, score=0, last_score = 0): screen_surface.fill((0, 0, 0)) pygame.font.init() font = pygame.font.SysFont('comicsans', 60) label = font.render('Tetris', 1, (255, 255, 255)) screen_surface.blit(label, (top_left_x + game_width / 2 - (label.get_width() / 2), 30)) """ current score and last score are modifications to the game ----------------------------------------------------------------- """ # current score font = pygame.font.SysFont('comicsans', 30) label = font.render('Score: ' + str(score), 1, (255,255,255)) sx = top_left_x + game_width + 50 sy = top_left_y + game_height/2 - 100 screen_surface.blit(label, (sx + 20, sy + 160)) # last score label = font.render('High Score: ' + last_score, 1, (255,255,255)) sx = top_left_x - 200 sy = top_left_y + 200 screen_surface.blit(label, (sx + 20, sy + 160)) for i in range(len(grid_scene)): for j in range(len(grid_scene[i])): pygame.draw.rect(screen_surface, grid_scene[i][j], (top_left_x + j*shape_size, top_left_y + i*shape_size, shape_size, shape_size), 0) pygame.draw.rect(screen_surface, (255, 0, 0), (top_left_x, top_left_y, game_width, game_height), 5) show_grid(screen_surface, grid_scene) #pygame.display.update()
Example 37
Source File: grid_types.py From gempy with GNU Lesser General Public License v3.0 | 5 votes |
def create_irregular_grid_kernel(resolution, radius): """ Create an isometric grid kernel (centered at 0) Args: resolution: [s0] radius (float): Maximum distance of the kernel Returns: tuple: center of the voxel, left edge of each voxel (for xyz), right edge of each voxel (for xyz). """ if radius is not list or radius is not np.ndarray: radius = np.repeat(radius, 3) g_ = [] g_2 = [] d_ = [] for xyz in [0, 1, 2]: if xyz == 2: # Make the grid only negative for the z axis g_.append(np.geomspace(0.01, 1, int(resolution[xyz]))) g_2.append((np.concatenate(([0], g_[xyz])) + 0.05) * - radius[xyz] * 1.2) else: g_.append(np.geomspace(0.01, 1, int(resolution[xyz] / 2))) g_2.append(np.concatenate((-g_[xyz][::-1], [0], g_[xyz])) * radius[xyz]) d_.append(np.diff(np.pad(g_2[xyz], 1, 'reflect', reflect_type='odd'))) g = np.meshgrid(*g_2) d_left = np.meshgrid(d_[0][:-1]/2, d_[1][:-1]/2, d_[2][:-1]/2) d_right = np.meshgrid(d_[0][1:]/2, d_[1][1:]/2, d_[2][1:]/2) kernel_g = np.vstack(tuple(map(np.ravel, g))).T.astype("float64") kernel_d_left = np.vstack(tuple(map(np.ravel, d_left))).T.astype("float64") kernel_d_right = np.vstack(tuple(map(np.ravel, d_right))).T.astype("float64") return kernel_g, kernel_d_left, kernel_d_right
Example 38
Source File: create_warped_grid.py From ANTsPy with Apache License 2.0 | 5 votes |
def create_grid_source(size=(250, 250), sigma=(0.5, 0.5), grid_spacing=(5.0, 5.0), grid_offset=(0.0, 0.0), spacing=(0.2, 0.2), pixeltype='float'): pass
Example 39
Source File: grid.py From chaospy with MIT License | 5 votes |
def create_nested_grid_samples(order, dim=1): """ Create samples from a nested grid. Args: order (int): The order of the grid. Defines the number of samples. dim (int): The number of dimensions in the grid Returns (numpy.ndarray): Regular grid with ``shape == (dim, 2**order-1)``. """ return create_grid_samples(order=2**order-1, dim=dim)
Example 40
Source File: bitmapviz.py From MTSAnomalyDetection with Apache License 2.0 | 5 votes |
def create_unit_grid(m, n): """ :param m: row count :param n: column count :return unit_grid: array of shape `(m,n)` contains all integers in `[0, m*n - 1]` """ unit_grid = np.ndarray(shape=(m, n), dtype=int) pprint(unit_grid) for i in range(0, m): for j in range(0, n): unit_grid[i, j] = i * n + j return unit_grid
Example 41
Source File: enviromentSetter.py From DsgTools with GNU General Public License v2.0 | 5 votes |
def createGrid(self, workingAreaPolygon): """ :param extents: [xmin, ymin, xmax, ymax] Creates the grid of workingAreaPolygon } """ pass
Example 42
Source File: grid.py From SphericalViewSynthesis with BSD 2-Clause "Simplified" License | 5 votes |
def create_image_grid(width, height, data_type=torch.float32): v_range = ( torch.arange(0, height) # [0 - h] .view(1, height, 1) # [1, [0 - h], 1] .expand(1, height, width) # [1, [0 - h], W] .type(data_type) # [1, H, W] ) u_range = ( torch.arange(0, width) # [0 - w] .view(1, 1, width) # [1, 1, [0 - w]] .expand(1, height, width) # [1, H, [0 - w]] .type(data_type) # [1, H, W] ) return torch.stack((u_range, v_range), dim=1) # [1, 2, H, W]
Example 43
Source File: pgVersionTools.py From pgversion with GNU General Public License v2.0 | 5 votes |
def createGridView(self, tabView, tabData, headerText, colWidth, rowHeight): numCols = len(headerText) startVal = 0 numRows = len(tabData[headerText[0].upper()]) tabView.clear() tabView.setColumnCount(numCols) tabView.setRowCount(numRows) tabView.sortItems(2) col = startVal i = 0 for text in headerText: headerItem = QTableWidgetItem() headerItem.setData(Qt.DisplayRole, text) tabView.setHorizontalHeaderItem(i, headerItem) i = i + 1 for i in range(0, numRows): col = startVal for text in headerText: myItem = QTableWidgetItem() myItem.setData(Qt.DisplayRole, tabData[text.upper()][i]) tabView.setItem(i, col, myItem) myItem.setSelected(False) col = col + 1 return
Example 44
Source File: interpolations.py From DAGAN with MIT License | 5 votes |
def create_mine_grid(rows, cols, dim, space, anchors, spherical, gaussian, scale=1.): """Create a grid of latents with splash layout""" lerpv = get_interpfn(spherical, gaussian) u_list = np.zeros((rows, cols, dim)) # compute anchors cur_anchor = 0 for y in range(rows): for x in range(cols): if y%space == 0 and x%space == 0: if anchors is not None and cur_anchor < len(anchors): u_list[y,x,:] = anchors[cur_anchor] cur_anchor = cur_anchor + 1 else: u_list[y,x,:] = np.random.normal(0,scale, (1, dim)) # interpolate horizontally for y in range(rows): for x in range(cols): if y%space == 0 and x%space != 0: lastX = space * (x // space) nextX = lastX + space fracX = (x - lastX) / float(space) # print("{} - {} - {}".format(lastX, nextX, fracX)) u_list[y,x,:] = lerpv(fracX, u_list[y, lastX, :], u_list[y, nextX, :]) # interpolate vertically for y in range(rows): for x in range(cols): if y%space != 0: lastY = space * (y // space) nextY = lastY + space fracY = (y - lastY) / float(space) u_list[y,x,:] = lerpv(fracY, u_list[lastY, x, :], u_list[nextY, x, :]) u_grid = u_list.reshape(rows * cols, dim) return u_grid #print(create_mine_grid(rows=16, cols=16, dim=100, space=1, anchors=None, spherical=True, gaussian=True))
Example 45
Source File: image_grid.py From keras-adversarial with MIT License | 5 votes |
def create_image_grid(imgs, figsize=None, cmap='gray'): n = imgs.shape[0] m = imgs.shape[1] if figsize is None: figsize = (n, m) fig = plt.figure(figsize=figsize) gs1 = gridspec.GridSpec(n, m) gs1.update(wspace=0.025, hspace=0.025) # set the spacing between axes. for i in range(n): for j in range(m): ax = plt.subplot(gs1[i, j]) img = imgs[i, j, :] ax.imshow(img, cmap=cmap) ax.axis('off') return fig
Example 46
Source File: io.py From cosipy with GNU General Public License v3.0 | 5 votes |
def create_grid_restart(self): return self.GRID_RESTART #============================================================================== # The init_data_dataset read the input NetCDF dataset and stores the data in # an xarray. #============================================================================== #---------------------------------------------- # Reads the input data into a xarray dataset #----------------------------------------------
Example 47
Source File: base.py From landlab with MIT License | 5 votes |
def create_active_link_grid(node_status, links, number_of_nodes): active_link_ids = find_active_links(node_status, links) return LinkGrid( (links[0][active_link_ids], links[1][active_link_ids]), number_of_nodes, link_ids=active_link_ids, )
Example 48
Source File: data.py From gempy with GNU Lesser General Public License v3.0 | 5 votes |
def create_regular_grid(self, extent=None, resolution=None, set_active=True, *args, **kwargs): """ Set a new regular grid and activate it. Args: extent (np.ndarray): [x_min, x_max, y_min, y_max, z_min, z_max] resolution (np.ndarray): [nx, ny, nz] RegularGrid Docs """ self.regular_grid = grid_types.RegularGrid(extent, resolution, **kwargs) if set_active is True: self.set_active('regular') return self.regular_grid
Example 49
Source File: generateGrid.py From Python_DIC with Apache License 2.0 | 5 votes |
def createGrid(DICWindow): #start the generateGrid widget and put it in the main window imageFileList = DICWindow.fileNameList #fileList = open(mainWindow.fileDataPath+'/filenamelist.dat',"r") #for element in fileList: # imageFileList.append(element) gridWidget = generateGridWidget(DICWindow, imageFileList) DICWindow.setCentralWidget(gridWidget) gridWidget.topWidget.prepareTools(imageFileList)
Example 50
Source File: data.py From gempy with GNU Lesser General Public License v3.0 | 5 votes |
def create_custom_grid(self, custom_grid: np.ndarray): """ Set a new regular grid and activate it. Args: custom_grid (np.array): [s0] """ self.custom_grid = grid_types.CustomGrid(custom_grid) self.set_active('custom')
Example 51
Source File: data.py From gempy with GNU Lesser General Public License v3.0 | 5 votes |
def create_centered_grid(self, centers, radius, resolution=None): """Initialize gravity grid. Deactivate the rest of the grids""" self.centered_grid = grid_types.CenteredGrid(centers, radius, resolution) # self.active_grids = np.zeros(4, dtype=bool) self.set_active('centered')
Example 52
Source File: utils.py From MGAN with MIT License | 5 votes |
def create_image_grid(x, img_size, tile_shape): assert (x.shape[0] == tile_shape[0] * tile_shape[1]) assert (x[0].shape == img_size) img = np.zeros((img_size[0] * tile_shape[0] + tile_shape[0] - 1, img_size[1] * tile_shape[1] + tile_shape[1] - 1, 3)) for t in range(x.shape[0]): i, j = t // tile_shape[1], t % tile_shape[1] img[i * img_size[0] + i : (i + 1) * img_size[0] + i, j * img_size[1] + j : (j + 1) * img_size[1] + j] = x[t] return img
Example 53
Source File: grid.py From PyMove with MIT License | 5 votes |
def create_update_index_grid_feature( self, data, label_dtype=np.int64, sort=True ): """ Create or update index grid feature. It'srs not necessary pass dic_grid, because if don't pass, the function create a dic_grid. Parameters ---------- data : pandas.core.frame.DataFrame Represents the dataset with contains lat, long and datetime. label_dtype : String Represents the type_ of a value of new column in dataframe. sort : boolean Represents the state of dataframe, if is sorted. """ operation = begin_operation('create_update_index_grid_feature') print('\nCreating or updating index of the grid feature..\n') try: if sort: data.sort_values([TRAJ_ID, DATETIME], inplace=True) lat_, lon_ = self.point_to_index_grid( data[LATITUDE], data[LONGITUDE] ) data[INDEX_GRID_LAT] = label_dtype(lat_) data[INDEX_GRID_LON] = label_dtype(lon_) self.last_operation = end_operation(operation) except Exception as e: self.last_operation = end_operation(operation) raise e
Example 54
Source File: grid.py From PyMove with MIT License | 5 votes |
def create_one_polygon_to_point_on_grid( self, index_grid_lat, index_grid_lon ): """ Create one polygon to point on grid. Parameters ---------- index_grid_lat : int Represents index of grid that reference latitude. index_grid_lon : int Represents index of grid that reference longitude. Returns ------- shapely.geometry.Polygon Represents a polygon of this cell in a grid. """ operation = begin_operation('create_one_polygon_to_point_on_grid') cell_size = self.cell_size_by_degree lat_init = self.lat_min_y + cell_size * index_grid_lat lon_init = self.lon_min_x + cell_size * index_grid_lon polygon = Polygon(( (lat_init, lon_init), (lat_init + cell_size, lon_init), (lat_init + cell_size, lon_init + cell_size,), (lat_init, lon_init + cell_size), )) self.last_operation = end_operation(operation) return polygon
Example 55
Source File: Gan.py From Variational_Discriminator_Bottleneck with MIT License | 5 votes |
def create_grid(samples, img_file): """ utility function to create a grid of GAN samples :param samples: generated samples for visualization: Tensor :param img_file: name of file to write :return: None (saves file to the disk) """ from torchvision.utils import save_image from numpy import sqrt # save the images: samples = th.clamp((samples.detach() / 2) + 0.5, min=0, max=1) save_image(samples, img_file, nrow=int(sqrt(samples.shape[0])))
Example 56
Source File: grid_layout.py From plat with MIT License | 5 votes |
def create_chain_grid(rows, cols, dim, space, anchors, spherical, gaussian): """Create a grid of latents with chained-analogy layout""" ## Map (r/s + c/w - 1) anchors to r/s * c/s, then call create_mine_grid num_row_anchors = (rows + space - 1) / space num_col_anchors = (cols + space - 1) / space u_list = np.zeros((num_row_anchors, num_col_anchors, dim)) for y in range(num_row_anchors): for x in range(num_col_anchors): if x == 0 or y == 0: if x == 0 and y == 0: anchor_index = 0 elif x == 0: anchor_index = y * 2 - 1 else: anchor_index = x * 2 u_list[y,x,:] = anchors[anchor_index] else: anal_vec = u_list[y,x-1,:] + (u_list[y-1,x,:] - u_list[y-1,x-1,:]) anal_len = np.linalg.norm(anal_vec) anal_unit_vec = np.nan_to_num(anal_vec / anal_len) avg_len = (np.linalg.norm(u_list[y,x-1,:]) + np.linalg.norm(u_list[y-1,x,:]) + np.linalg.norm(u_list[y-1,x-1,:])) / 3.0 u_list[y,x,:] = avg_len * anal_unit_vec u_grid = u_list.reshape(num_row_anchors * num_col_anchors, dim) return create_mine_grid(rows, cols, dim, space, u_grid, spherical, gaussian)
Example 57
Source File: grid_layout.py From plat with MIT License | 5 votes |
def create_mine_grid(rows, cols, dim, space, anchors, spherical, gaussian): """Create a grid of latents with splash layout""" lerpv = get_interpfn(spherical, gaussian) u_list = np.zeros((rows, cols, dim)) # compute anchors cur_anchor = 0 for y in range(rows): for x in range(cols): if y%space == 0 and x%space == 0: if anchors is not None and cur_anchor < len(anchors): u_list[y,x,:] = anchors[cur_anchor] cur_anchor = cur_anchor + 1 else: u_list[y,x,:] = np.random.normal(0,1, (1, dim)) # interpolate horizontally for y in range(rows): for x in range(cols): if y%space == 0 and x%space != 0: lastX = space * (x // space) nextX = lastX + space fracX = (x - lastX) / float(space) # print("{} - {} - {}".format(lastX, nextX, fracX)) u_list[y,x,:] = lerpv(fracX, u_list[y, lastX, :], u_list[y, nextX, :]) # interpolate vertically for y in range(rows): for x in range(cols): if y%space != 0: lastY = space * (y // space) nextY = lastY + space fracY = (y - lastY) / float(space) u_list[y,x,:] = lerpv(fracY, u_list[lastY, x, :], u_list[nextY, x, :]) u_grid = u_list.reshape(rows * cols, dim) return u_grid