Python make grid

60 Python code examples are found related to " make 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: analysis.py    From pypath with GNU General Public License v3.0 6 votes vote down vote up
def make_refs_journals_grid(self):

        self.refs_journals_grid = \
            plot.BarplotsGrid(
                self.pp,
                'journal',
                by='database',
                fname=self.get_path(self.refs_journal_grid_fname),
                ylab='References',
                title='Number of references by databases and journals',
                full_range_x=False,
                xlim=[-0.5, 10.5],
                sort=True,
                desc=True,
                hoffset=10,
                data=self.pubmeds,
                small_xticklabels=True
            ) 
Example 2
Source File: onlinewindow.py    From tridesclous with MIT License 6 votes vote down vote up
def make_grid(self):
        
        #~ n = len(self.channel_groups)
        self.chan_grp_labels = {}
        for r, chan_grp in enumerate(self.channel_groups):
            self.grid.addWidget(QT.QLabel('<b>chan_grp {}</b>'.format(chan_grp)), r, 0)
            self.chan_grp_labels[chan_grp] = label = QT.QLabel('')
            self.grid.addWidget(label, r, 1)
            but = QT.QPushButton('Edit')
            but.chan_grp = chan_grp
            but.clicked.connect(self.edit_catalogue)
            but.setMaximumWidth(30)
            self.grid.addWidget(but, r, 2)
            
            
        self.grid_done = True 
Example 3
Source File: util.py    From hcipy with MIT License 6 votes vote down vote up
def make_pupil_grid(dims, diameter=1):
	'''Makes a new :class:`Grid`, meant for descretisation of a pupil-plane wavefront.

	This grid is symmetric around the origin, and therefore has no point exactly on
	the origin for an even number of pixels.

	Parameters
	----------
	dims : ndarray or integer
		The number of pixels per dimension. If this is an integer, this number
		of pixels is used for all dimensions.
	diameter : ndarray or scalar
		The diameter of the grid in each dimension. If this is a scalar, this diameter
		is used for all dimensions.

	Returns
	-------
	Grid
		A :class:`CartesianGrid` with :class:`RegularCoords`.
	'''
	diameter = (np.ones(2) * diameter).astype('float')
	return make_uniform_grid(dims, diameter) 
Example 4
Source File: visualization.py    From director with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def makeGridPolyData(gridHalfWidth=100,
             majorTickSize=10.0, minorTickSize=1.0,
             majorGridRings=True, minorGridRings=False):

    majorGrid = vtk.vtkGridSource()
    majorGrid.SetSurfaceEnabled(True)
    majorGrid.SetArcsEnabled(majorGridRings)
    majorGrid.SetGridSize(int(gridHalfWidth/majorTickSize))
    majorGrid.SetScale(majorTickSize)
    majorGrid.Update()

    if minorTickSize != majorTickSize:
        minorGrid = vtk.vtkGridSource()
        minorGrid.SetSurfaceEnabled(False)
        minorGrid.SetArcsEnabled(minorGridRings)
        minorGrid.SetScale(minorTickSize)
        minorGrid.SetGridSize(int(gridHalfWidth/minorTickSize))
        minorGrid.Update()
        return filterUtils.appendPolyData([majorGrid.GetOutput(), minorGrid.GetOutput()])
    else:
        return majorGrid.GetOutput() 
Example 5
Source File: events_processors.py    From polyaxon with Apache License 2.0 6 votes vote down vote up
def make_grid(data, ncols=8):
    # I: N1HW or N3HW
    if not np:
        logger.warning(NUMPY_ERROR_MESSAGE)
        return UNKNOWN

    assert isinstance(data, np.ndarray), "plugin error, should pass numpy array here"
    if data.shape[1] == 1:
        data = np.concatenate([data, data, data], 1)
    assert data.ndim == 4 and data.shape[1] == 3 or data.shape[1] == 4
    nimg = data.shape[0]
    H = data.shape[2]  # noqa
    W = data.shape[3]  # noqa
    ncols = min(nimg, ncols)
    nrows = int(np.ceil(float(nimg) / ncols))
    canvas = np.zeros((data.shape[1], H * nrows, W * ncols))
    i = 0
    for y in range(nrows):
        for x in range(ncols):
            if i >= nimg:
                break
            canvas[:, y * H : (y + 1) * H, x * W : (x + 1) * W] = data[i]  # noqa
            i = i + 1
    return canvas 
Example 6
Source File: axes.py    From stdm with GNU General Public License v2.0 6 votes vote down vote up
def makeGrid(self,g,dim=None,parent=None,exclude=[]):
        '''this is only called by a container object'''
        c = self.gridStrokeColor
        w = self.gridStrokeWidth or 0
        if w and c and self.visibleGrid:
            s = self.gridStart
            e = self.gridEnd
            if s is None or e is None:
                if dim and hasattr(dim,'__call__'):
                    dim = dim()
                if dim:
                    if s is None: s = dim[0]
                    if e is None: e = dim[1]
                else:
                    if s is None: s = 0
                    if e is None: e = 0
            if s or e:
                if self.isYAxis: offs = self._x
                else: offs = self._y
                self._makeLines(g,s-offs,e-offs,c,w,self.gridStrokeDashArray,self.gridStrokeLineJoin,self.gridStrokeLineCap,self.gridStrokeMiterLimit,parent=parent,exclude=exclude,specials=getattr(self,'_gridSpecials',{}))
        self._makeSubGrid(g,dim,parent,exclude=[]) 
Example 7
Source File: util.py    From hcipy with MIT License 6 votes vote down vote up
def make_chebyshev_grid(dims, minimum=None, maximum=None):
	if minimum is None:
		minimum = -1

	if maximum is None:
		maximum = 1

	dims = np.array(dims)
	minimum = np.ones(len(dims)) * minimum
	maximum = np.ones(len(dims)) * maximum

	middles = (minimum + maximum) / 2
	intervals = (maximum - minimum) / 2

	sep_coords = []
	for dim, middle, interval in zip(dims, middles, intervals):
		c = np.cos(np.pi * (2 * np.arange(dim) + 1) / (2.0 * dim))
		c = middle + interval * c
		sep_coords.append(c)

	return CartesianGrid(SeparatedCoords(sep_coords)) 
Example 8
Source File: x2num.py    From tensorboard with Apache License 2.0 6 votes vote down vote up
def make_grid(I, ncols=8):
    assert isinstance(I, np.ndarray), 'plugin error, should pass numpy array here'
    assert I.ndim == 4 and I.shape[1] == 3
    nimg = I.shape[0]
    H = I.shape[2]
    W = I.shape[3]
    ncols = min(nimg, ncols)
    nrows = int(np.ceil(float(nimg) / ncols))
    canvas = np.zeros((3, H * nrows, W * ncols))
    i = 0
    for y in range(nrows):
        for x in range(ncols):
            if i >= nimg:
                break
            canvas[:, y * H:(y + 1) * H, x * W:(x + 1) * W] = I[i]
            i = i + 1
    return canvas 
Example 9
Source File: util.py    From lenstronomy with MIT License 6 votes vote down vote up
def make_grid(numPix, deltapix, subgrid_res=1, left_lower=False):
    """
    creates pixel grid (in 1d arrays of x- and y- positions)
    default coordinate frame is such that (0,0) is in the center of the coordinate grid

    :param numPix: number of pixels per axis
    :param deltapix: pixel size
    :param subgrid_res: sub-pixel resolution (default=1)
    :return: x, y position information in two 1d arrays
    """

    numPix_eff = numPix*subgrid_res
    deltapix_eff = deltapix/float(subgrid_res)
    a = np.arange(numPix_eff)
    matrix = np.dstack(np.meshgrid(a, a)).reshape(-1, 2)
    x_grid = matrix[:, 0] * deltapix_eff
    y_grid = matrix[:, 1] * deltapix_eff
    if left_lower is True:
        shift = -1. / 2 + 1. / (2 * subgrid_res)
    else:
        shift = np.sum(x_grid) / numPix_eff**2
    return x_grid - shift, y_grid - shift 
Example 10
Source File: wmme.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def MakeOrbitalsOnGrid(self, Orbitals, Grid, DerivativeOrder=0):
      """calculate values of molecular orbitals on a grid of 3d points in space.
      Input:
         - Orbitals: nAo x nOrb matrix, where nAo must be compatible with
           self.OrbBasis. The AO dimension must be contravariant AO (i.e., not SMH).
         - Grid: 3 x nGrid array giving the coordinates of the grid points.
         - DerivativeOrder: 0: only orbital values,
                            1: orbital values and 1st derivatives,
                            2: orbital values and up to 2nd derivatives.
      Returns:
         - nGrid x nDerivComp x nOrb array. If DerivativeOrder is 0, the
           DerivComp dimension is omitted.
      """
      Args =    [("--eval-orbitals-dx=%s" % DerivativeOrder)]
      Inputs =  [("--eval-orbitals", "ORBITALS.npy", Orbitals)]\
              + [("--grid-coords", "GRID.npy", Grid)]
      Outputs = [("--save-grid-values", "ORBS_ON_GRID")]

      (ValuesOnGrid,) = self._InvokeBfint(Args, Outputs, Inputs)
      nComp = [1,4,10][DerivativeOrder]
      if nComp != 1:
         ValuesOnGrid = ValuesOnGrid.reshape((Grid.shape[1], nComp, Orbitals.shape[1]))
      return ValuesOnGrid 
Example 11
Source File: axes.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def makeGrid(self,g,dim=None,parent=None,exclude=[]):
        '''this is only called by a container object'''
        c = self.gridStrokeColor
        w = self.gridStrokeWidth or 0
        if w and c and self.visibleGrid:
            s = self.gridStart
            e = self.gridEnd
            if s is None or e is None:
                if dim and hasattr(dim,'__call__'):
                    dim = dim()
                if dim:
                    if s is None: s = dim[0]
                    if e is None: e = dim[1]
                else:
                    if s is None: s = 0
                    if e is None: e = 0
            if s or e:
                if self.isYAxis: offs = self._x
                else: offs = self._y
                self._makeLines(g,s-offs,e-offs,c,w,self.gridStrokeDashArray,self.gridStrokeLineJoin,self.gridStrokeLineCap,self.gridStrokeMiterLimit,parent=parent,exclude=exclude,specials=getattr(self,'_gridSpecials',{}))
        self._makeSubGrid(g,dim,parent,exclude=[]) 
Example 12
Source File: utils.py    From Disentangled-Person-Image-Generation with MIT License 6 votes vote down vote up
def make_grid(tensor, nrow=8, padding=2,
              normalize=False, scale_each=False):
    """Code based on https://github.com/pytorch/vision/blob/master/torchvision/utils.py"""
    nmaps = tensor.shape[0]
    xmaps = min(nrow, nmaps)
    ymaps = int(math.ceil(float(nmaps) / xmaps))
    height, width = int(tensor.shape[1] + padding), int(tensor.shape[2] + padding)
    grid = np.zeros([height * ymaps + 1 + padding // 2, width * xmaps + 1 + padding // 2, 3], dtype=np.uint8)
    k = 0
    for y in range(ymaps):
        for x in range(xmaps):
            if k >= nmaps:
                break
            h, h_width = y * height + 1 + padding // 2, height - padding
            w, w_width = x * width + 1 + padding // 2, width - padding

            grid[h:h+h_width, w:w+w_width] = tensor[k]
            k = k + 1
    return grid 
Example 13
Source File: mrf.py    From image-analogies with MIT License 6 votes vote down vote up
def make_patches_grid(x, patch_size, patch_stride):
    '''Break image `x` up into a grid of patches.

    input shape: (channels, rows, cols)
    output shape: (rows, cols, channels, patch_rows, patch_cols)
    '''
    from theano.tensor.nnet.neighbours import images2neibs  # TODO: all K, no T
    x = K.expand_dims(x, 0)
    xs = K.shape(x)
    num_rows = 1 + (xs[-2] - patch_size) // patch_stride
    num_cols = 1 + (xs[-1] - patch_size) // patch_stride
    num_channels = xs[-3]
    patches = images2neibs(x,
        (patch_size, patch_size), (patch_stride, patch_stride),
        mode='valid')
    # neibs are sorted per-channel
    patches = K.reshape(patches, (num_channels, K.shape(patches)[0] // num_channels, patch_size, patch_size))
    patches = K.permute_dimensions(patches, (1, 0, 2, 3))
    # arrange in a 2d-grid (rows, cols, channels, px, py)
    patches = K.reshape(patches, (num_rows, num_cols, num_channels, patch_size, patch_size))
    patches_norm = K.sqrt(K.sum(K.square(patches), axis=(2,3,4), keepdims=True))
    return patches, patches_norm 
Example 14
Source File: common.py    From magenta with Apache License 2.0 6 votes vote down vote up
def make_batch_image_grid(dim_grid, number_grid):
  """Returns a patched `make_grid` function for grid."""
  assert dim_grid in (1, 2)
  if dim_grid == 1:
    batch_image_grid = functools.partial(
        batch_image,
        max_images=number_grid,
        rows=1,
        cols=number_grid,
    )
  else:
    batch_image_grid = functools.partial(
        batch_image,
        max_images=number_grid * number_grid,
        rows=number_grid,
        cols=number_grid,
    )
  return batch_image_grid 
Example 15
Source File: common.py    From occupancy_flow with MIT License 6 votes vote down vote up
def make_3d_grid(bb_min, bb_max, shape):
    ''' Makes a 3D grid.

    Args:
        bb_min (tuple): bounding box minimum
        bb_max (tuple): bounding box maximum
        shape (tuple): output shape
    '''
    size = shape[0] * shape[1] * shape[2]

    pxs = torch.linspace(bb_min[0], bb_max[0], shape[0])
    pys = torch.linspace(bb_min[1], bb_max[1], shape[1])
    pzs = torch.linspace(bb_min[2], bb_max[2], shape[2])

    pxs = pxs.view(-1, 1, 1).expand(*shape).contiguous().view(size)
    pys = pys.view(1, -1, 1).expand(*shape).contiguous().view(size)
    pzs = pzs.view(1, 1, -1).expand(*shape).contiguous().view(size)
    p = torch.stack([pxs, pys, pzs], dim=1)

    return p 
Example 16
Source File: generation.py    From texture_fields with MIT License 6 votes vote down vote up
def make_3d_grid(bb_min, bb_max, shape):
    '''
    Outputs gird points of a 3d grid

    '''
    size = shape[0] * shape[1] * shape[2]

    pxs = torch.linspace(bb_min[0], bb_max[0], shape[0])
    pys = torch.linspace(bb_min[1], bb_max[1], shape[1])
    pzs = torch.linspace(bb_min[2], bb_max[2], shape[2])

    pxs = pxs.view(-1, 1, 1).expand(*shape).contiguous().view(size)
    pys = pys.view(1, -1, 1).expand(*shape).contiguous().view(size)
    pzs = pzs.view(1, 1, -1).expand(*shape).contiguous().view(size)
    p = torch.stack([pxs, pys, pzs], dim=1)

    return p 
Example 17
Source File: well1.py    From xtgeo with GNU Lesser General Public License v3.0 6 votes vote down vote up
def make_ijk_from_grid(self, grid, grid_id="", algorithm=2, activeonly=True):
        """Look through a Grid and add grid I J K as discrete logs.

        Note that the the grid counting has base 1 (first row is 1 etc).

        By default, log (i.e. column names in the dataframe) will be
        ICELL, JCELL, KCELL, but you can add a tag (ID) to that name.

        Args:
            grid (Grid): A XTGeo Grid instance
            grid_id (str): Add a tag (optional) to the current log name
            algorithm (int): Which interbal algorithm to use, default is 2 (expert
                setting)
            activeonly (bool): If True, only active cells are applied (algorithm 2 only)
        Raises:
            RuntimeError: 'Error from C routine, code is ...'

        .. versionchanged:: 2.9.0 Added keys for and `activeonly`
        """

        _well_oper.make_ijk_from_grid(
            self, grid, grid_id=grid_id, algorithm=algorithm, activeonly=activeonly,
        ) 
Example 18
Source File: _utils.py    From scanpy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def make_grid_spec(
    ax_or_figsize: Union[Tuple[int, int], _AxesSubplot],
    nrows: int,
    ncols: int,
    wspace: Optional[float] = None,
    hspace: Optional[float] = None,
    width_ratios: Optional[Sequence[float]] = None,
    height_ratios: Optional[Sequence[float]] = None,
) -> Tuple[Figure, gridspec.GridSpecBase]:
    kw = dict(
        wspace=wspace,
        hspace=hspace,
        width_ratios=width_ratios,
        height_ratios=height_ratios,
    )
    if isinstance(ax_or_figsize, tuple):
        fig = pl.figure(figsize=ax_or_figsize)
        return fig, gridspec.GridSpec(nrows, ncols, **kw)
    else:
        ax = ax_or_figsize
        ax.axis('off')
        ax.set_frame_on(False)
        ax.set_xticks([])
        ax.set_yticks([])
        return ax.figure, ax.get_subplotspec().subgridspec(nrows, ncols, **kw) 
Example 19
Source File: utils.py    From GP-GAN with MIT License 6 votes vote down vote up
def make_grid(tensor, padding=2):
    """
    Given a 4D mini-batch Tensor of shape (B x C x H x W), makes a grid of images
    """
    # make the mini-batch of images into a grid
    nmaps = tensor.shape[0]
    xmaps = int(nmaps ** 0.5)
    ymaps = int(math.ceil(nmaps / xmaps))
    height, width = int(tensor.shape[2] + padding), int(tensor.shape[3] + padding)
    grid = np.ones((3, height * ymaps, width * xmaps))
    k = 0
    sy = 1 + padding // 2
    for y in range(ymaps):
        sx = 1 + padding // 2
        for x in range(xmaps):
            if k >= nmaps:
                break
            grid[:, sy:sy + height - padding, sx:sx + width - padding] = tensor[k]
            sx += width
            k = k + 1
        sy += height
    return grid 
Example 20
Source File: bubbly.py    From bubbly with MIT License 6 votes vote down vote up
def make_grid(dataset, column_names, time_column, years=None):
    '''Makes the grid for the plot as a pandas DataFrame by-passing the use of `plotly.grid_objs`
    that is unavailable in the offline mode for `plotly`. The grids are designed using the `col_name_template`
    from the `column_names` of the `dataset`.'''
    
    grid = pd.DataFrame()
    if time_column:
        col_name_template = '{}+{}_grid'
        if years is None:
            years = dataset[time_column].unique()

        for year in years:
            dataset_by_year = dataset[(dataset[time_column] == int(year))]
            for col_name in column_names:
                # Each column name is unique
                temp = col_name_template.format(year, col_name)
                if dataset_by_year[col_name].size != 0:
                    grid = grid.append({'value': list(dataset_by_year[col_name]), 'key': temp}, ignore_index=True)
    else:
        # Check if this can be simplified
        for col_name in column_names:
            # Each column name is unique
            grid = grid.append({'value': list(dataset[col_name]), 'key': col_name + '_grid'}, ignore_index=True)
        
    return grid 
Example 21
Source File: vis_utils.py    From ACAN with MIT License 6 votes vote down vote up
def make_grid(images, nrow=4):
    """
    Parameters
    ----------
    images : numpy.ndarray
            shape [batch_size, h, w, c]
    nrow : int 
           Number of images displayed in each row of the grid.
           The Final grid size is (batch_size / nrow, nrow).
    
    Return
    ------
    images : numpy.ndarray
             shape [batch_size/nrow * h, nrow * w, c]
    """
    b, h, w, c = images.shape
    ncol = b // nrow
    assert b // nrow * nrow == b, "batch size of images can not be exactly divided by nrow"
    images = images.reshape(ncol, nrow * h, w, c)
    images = images.transpose(1, 0, 2, 3)
    images = images.reshape(nrow * h, ncol * w, c)
    return images 
Example 22
Source File: utils.py    From CausalGAN with MIT License 6 votes vote down vote up
def make_grid(tensor, nrow=8, padding=2,
              normalize=False, scale_each=False):
    """Code based on https://github.com/pytorch/vision/blob/master/torchvision/utils.py
    minor improvement, row/col was reversed"""
    nmaps = tensor.shape[0]
    ymaps = min(nrow, nmaps)
    xmaps = int(math.ceil(float(nmaps) / ymaps))
    height, width = int(tensor.shape[1] + padding), int(tensor.shape[2] + padding)
    grid = np.zeros([height * ymaps + 1 + padding // 2, width * xmaps + 1 + padding // 2, 3], dtype=np.uint8)
    k = 0
    for y in range(ymaps):
        for x in range(xmaps):
            if k >= nmaps:
                break
            h, h_width = y * height + 1 + padding // 2, height - padding
            w, w_width = x * width + 1 + padding // 2, width - padding

            grid[h:h+h_width, w:w+w_width] = tensor[k]
            k = k + 1
    return grid 
Example 23
Source File: x2num.py    From c2board with MIT License 6 votes vote down vote up
def make_grid(I, ncols=4):
    '''Make a grid view out of all the images.'''
    assert isinstance(I, np.ndarray), 'ERROR: should pass numpy array here'
    assert I.ndim == 4 and I.shape[1] == 3, \
        'ERROR: should have dimension for N to put them in grid'
    nimg = I.shape[0]
    H = I.shape[2]
    W = I.shape[3]
    ncols = min(nimg, ncols)
    nrows = int(np.ceil(float(nimg) / ncols))
    canvas = np.zeros((3, H * nrows, W * ncols))
    i = 0
    for y in range(nrows):
        for x in range(ncols):
            if i >= nimg:
                break
            canvas[:, y * H:(y + 1) * H, x * W:(x + 1) * W] = I[i]
            i = i + 1
    return canvas 
Example 24
Source File: analysis.py    From pypath with GNU General Public License v3.0 5 votes vote down vote up
def make_refs_years_grid(self):

        self.refs_years_grid = \
            plot.BarplotsGrid(
                self.pp,
                'year',
                xmin=1970,
                by='database',
                fname=self.get_path(self.refs_year_grid_fname),
                ylab='References',
                title='Number of references by databases and years',
                data=self.pubmeds,
                uniform_ylim=True
            ) 
Example 25
Source File: utilities.py    From uncertainty-adversarial-paper with MIT License 5 votes vote down vote up
def make_grid(im_batch, rect):
    """
    Concatenate a batch of samples into an n by n image
    """
    h, w = rect
    ims = [im.squeeze() for im in im_batch]

    ims = [ims[i* w:(i+1)*w] for i in range(h)]

    ims = [np.concatenate(xs, axis=0) for xs in ims]

    ims = np.concatenate(ims, axis=1)
    return ims 
Example 26
Source File: utils.py    From pytorch-TP-GAN with MIT License 5 votes vote down vote up
def make_image_grid(x, ngrid):
    x = x.clone().cpu()
    if pow(ngrid,2) < x.size(0):
        grid = make_grid(x[:ngrid*ngrid], nrow=ngrid, padding=0, normalize=True, scale_each=False)
    else:
        grid = torch.FloatTensor(ngrid*ngrid, x.size(1), x.size(2), x.size(3)).fill_(1)
        grid[:x.size(0)].copy_(x)
        grid = make_grid(grid, nrow=ngrid, padding=0, normalize=True, scale_each=False)
    return grid 
Example 27
Source File: __init__.py    From PyESAPI with MIT License 5 votes vote down vote up
def make_dose_for_grid(dose, image=None):
    '''returns a 3D numpy.ndarray of doubles matching dose (default) or image grid indexed like [x,y,z]'''

    if image is not None:
        row_buffer = Array.CreateInstance(Double, image.ZSize)
        dose_array = fill_in_profiles(image, dose.GetDoseProfile, row_buffer, c_double)
    else:
        # default
        dose_array = dose_to_nparray(dose)

    dose_array[np.where(np.isnan(dose_array))] = 0.0
    return dose_array 
Example 28
Source File: mazes.py    From receipt-printer with MIT License 5 votes vote down vote up
def make_grid():
	weights = undirected_graph()
	for x in range(GRID_WIDTH):
		for y in range(GRID_HEIGHT):
			vertex = (x,y)
			for neighbor in grid_adjacent(vertex):
				weights[(vertex,neighbor)] = rnd.random()

	return weights 
Example 29
Source File: plot_xor_example.py    From DESlib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_grid(x, y, h=.02):

    x_min, x_max = x.min() - 1, x.max() + 1
    y_min, y_max = y.min() - 1, y.max() + 1
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h),
                         np.arange(y_min, y_max, h))
    return xx, yy


# Prepare the DS techniques. Changing k value to 5. 
Example 30
Source File: prism.py    From ArcPy with GNU General Public License v2.0 5 votes vote down vote up
def makeGridMask(grid_pnts, grid_codes=None):
    """
    Makes a mask with the same shape as the PRISM grid.
    'grid_codes' is a list containing the grid id's of those cells to INCLUDE in your analysis.
    """
    mask = np.ones((nrow, ncol), dtype=bool)
    for row in range(mask.shape[0]):
        mask[row] = np.in1d(grid_pnts[row], grid_codes, invert=True)
    return mask 
Example 31
Source File: image.py    From cleverhans with MIT License 5 votes vote down vote up
def make_grid(image_batch):
  """
  Turns a batch of images into one big image.
  :param image_batch: ndarray, shape (batch_size, rows, cols, channels)
  :returns : a big image containing all `batch_size` images in a grid
  """
  m, ir, ic, ch = image_batch.shape

  pad = 3

  padded = np.zeros((m, ir + pad * 2, ic + pad * 2, ch))
  padded[:, pad:-pad, pad:-pad, :] = image_batch

  m, ir, ic, ch = padded.shape

  pr = int(np.sqrt(m))
  pc = int(np.ceil(float(m) / pr))
  extra_m = pr * pc
  assert extra_m > m

  padded = np.concatenate((padded, np.zeros((extra_m - m, ir, ic, ch))), axis=0)

  row_content = np.split(padded, pr)
  row_content = [np.split(content, pc) for content in row_content]
  rows = [np.concatenate(content, axis=2) for content in row_content]
  grid = np.concatenate(rows, axis=1)
  assert grid.shape[0] == 1, grid.shape
  grid = grid[0]

  return grid 
Example 32
Source File: common.py    From occupancy_flow with MIT License 5 votes vote down vote up
def make_2d_grid(bb_min, bb_max, shape):
    size = shape[0] * shape[1]

    pxs = torch.linspace(bb_min[0], bb_max[0], shape[0])
    pys = torch.linspace(bb_min[1], bb_max[1], shape[1])
    pxs = pxs.view(-1, 1).expand(*shape).contiguous().view(size)
    pys = pys.view(1, -1).expand(*shape).contiguous().view(size)
    p = torch.stack([pxs, pys], dim=1)

    return p 
Example 33
Source File: picArranging.py    From python-urbanPlanning with MIT License 5 votes vote down vote up
def make_im_grid(ims, n_rows, n_cols, space, pad_val):
  """Make a grid of images with space in between.
  Args:
    ims: a list of [3, im_h, im_w] images
    n_rows: num of rows
    n_cols: num of columns
    space: the num of pixels between two images
    pad_val: scalar, or numpy array with shape [3]; the color of the space
  Returns:
    ret_im: a numpy array with shape [3, H, W]
  """
  assert (ims[0].ndim == 3) and (ims[0].shape[0] == 3)
  assert len(ims) <= n_rows * n_cols
  h, w = ims[0].shape[1:]
  H = h * n_rows + space * (n_rows - 1)
  W = w * n_cols + space * (n_cols - 1)
  if isinstance(pad_val, np.ndarray):
    # reshape to [3, 1, 1]
    pad_val = pad_val.flatten()[:, np.newaxis, np.newaxis]
  ret_im = (np.ones([3, H, W]) * pad_val).astype(ims[0].dtype)
  for n, im in enumerate(ims):
    r = n // n_cols
    c = n % n_cols
    h1 = r * (h + space)
    h2 = r * (h + space) + h
    w1 = c * (w + space)
    w2 = c * (w + space) + w
    ret_im[:, h1:h2, w1:w2] = im
  return ret_im 
Example 34
Source File: util.py    From lenstronomy with MIT License 5 votes vote down vote up
def make_grid_with_coordtransform(numPix, deltapix, subgrid_res=1, center_ra=0, center_dec=0, left_lower=False, inverse=True):
    """
    same as make_grid routine, but returns the transformation matrix and shift between coordinates and pixel

    :param numPix: number of pixels per axis
    :param deltapix: pixel scale per axis
    :param subgrid_res: supersampling resolution relative to the stated pixel size
    :param center_ra: center of the grid
    :param center_dec: center of the grid
    :param left_lower: sets the zero point at the lower left corner of the pixels
    :param inverse: bool, if true sets East as left, otherwise East is righrt
    :return:
    """
    numPix_eff = numPix*subgrid_res
    deltapix_eff = deltapix/float(subgrid_res)
    a = np.arange(numPix_eff)
    matrix = np.dstack(np.meshgrid(a, a)).reshape(-1, 2)
    if inverse is True:
        delta_x = -deltapix_eff
    else:
        delta_x = deltapix_eff
    if left_lower is True:
        ra_grid = matrix[:, 0] * delta_x
        dec_grid = matrix[:, 1] * deltapix_eff
    else:
        ra_grid = (matrix[:, 0] - (numPix_eff-1)/2.) * delta_x
        dec_grid = (matrix[:, 1] - (numPix_eff-1)/2.) * deltapix_eff
    shift = (subgrid_res-1)/(2.*subgrid_res)*deltapix
    ra_grid -= shift + center_ra
    dec_grid -= shift + center_dec
    ra_at_xy_0 = ra_grid[0]
    dec_at_xy_0 = dec_grid[0]

    Mpix2coord = np.array([[delta_x, 0], [0, deltapix_eff]])
    Mcoord2pix = np.linalg.inv(Mpix2coord)
    x_at_radec_0, y_at_radec_0 = map_coord2pix(-ra_at_xy_0, -dec_at_xy_0, x_0=0, y_0=0, M=Mcoord2pix)
    return ra_grid, dec_grid, ra_at_xy_0, dec_at_xy_0, x_at_radec_0, y_at_radec_0, Mpix2coord, Mcoord2pix 
Example 35
Source File: util.py    From lenstronomy with MIT License 5 votes vote down vote up
def make_grid_transformed(numPix, Mpix2Angle):
    """
    returns grid with linear transformation (deltaPix and rotation)
    :param numPix: number of Pixels
    :param Mpix2Angle: 2-by-2 matrix to mat a pixel to a coordinate
    :return: coordinate grid
    """
    x_grid, y_grid = make_grid(numPix, deltapix=1)
    ra_grid, dec_grid = map_coord2pix(x_grid, y_grid, 0, 0, Mpix2Angle)
    return ra_grid, dec_grid 
Example 36
Source File: util.py    From neural-flow-style with MIT License 5 votes vote down vote up
def make_grid(tensor, nrow=8, padding=2,
              normalize=False, scale_each=False, gray=True):
    """Code based on https://github.com/pytorch/vision/blob/master/torchvision/utils.py"""
    nmaps = tensor.shape[0]
    xmaps = min(nrow, nmaps)
    ymaps = int(np.ceil(float(nmaps) / xmaps))
    height, width = int(tensor.shape[1] + padding), int(tensor.shape[2] + padding)
    if padding == 0:
        if gray:
            grid = np.zeros([height * ymaps, width * xmaps], dtype=np.uint8)
        else:
            grid = np.zeros([height * ymaps, width * xmaps, 3], dtype=np.uint8)
    else:
        if gray:
            grid = np.zeros([height * ymaps + 1 + padding // 2, width * xmaps + 1 + padding // 2], dtype=np.uint8)
        else:
            grid = np.zeros([height * ymaps + 1 + padding // 2, width * xmaps + 1 + padding // 2, 3], dtype=np.uint8)
    k = 0
    for y in range(ymaps):
        for x in range(xmaps):
            if k >= nmaps:
                break
            if padding == 0:
                h, h_width = y * height, height
                w, w_width = x * width, width
            else:
                h, h_width = y * height + 1 + padding // 2, height - padding
                w, w_width = x * width + 1 + padding // 2, width - padding

            grid[h:h+h_width, w:w+w_width] = tensor[k]
            k = k + 1
    return grid 
Example 37
Source File: train.py    From srgan with MIT License 5 votes vote down vote up
def make_comparison_grid(targets, predictions, num_images):
  if isinstance(targets, Variable):
    targets = targets.data
  if isinstance(predictions, Variable):
    predictions = predictions.data

  images = []
  for idx, (target, prediction) in enumerate(zip(targets, predictions)):
    if idx >= num_images:
      break

    images += [target, prediction]

  nrows = int(math.ceil(len(images) / 4))
  return make_grid(images, nrow=nrows) 
Example 38
Source File: nql_test_lib.py    From language with Apache License 2.0 5 votes vote down vote up
def make_grid():
  """Create a grid, with relations for going n, s, e, w."""
  result = nql.NeuralQueryContext()
  result.declare_relation('n', 'place_t', 'place_t')
  result.declare_relation('s', 'place_t', 'place_t')
  result.declare_relation('e', 'place_t', 'place_t')
  result.declare_relation('w', 'place_t', 'place_t')
  result.declare_relation('color', 'place_t', 'color_t')
  result.declare_relation('distance_to', 'place_t', 'corner_t')

  kg_lines = []
  dij = {'n': (-1, 0), 's': (+1, 0), 'e': (0, +1), 'w': (0, -1)}
  for i in range(0, 4):
    for j in range(0, 4):
      cell_color = 'black' if (i % 2) == (j % 2) else 'white'
      kg_lines.append('\t'.join(['color', cell(i, j), cell_color]) + '\n')
      kg_lines.append(
          '\t'.join(['distance_to', cell(i, j), 'ul',
                     str(i + j)]) + '\n')
      for direction, (di, dj) in dij.items():
        if (0 <= i + di < 4) and (0 <= j + dj < 4):
          kg_lines.append(
              '\t'.join([direction, cell(i, j),
                         cell(i + di, j + dj)]) + '\n')
  result.load_kg(lines=kg_lines, freeze=True)
  return result 
Example 39
Source File: run this one.py    From my_research with Apache License 2.0 5 votes vote down vote up
def make_grid(n_by_m):
    # Build window
    if len(n_by_m) != 2:
        raise ValueError('Wrong grid geometry')
    main_window = Window(n_by_m, size='600x800')
    main_window.make_window()
    return main_window 
Example 40
Source File: bubbly.py    From bubbly with MIT License 5 votes vote down vote up
def make_grid_with_categories(dataset, column_names, time_column, category_column, years=None, categories=None):
    '''Makes the grid for the plot as a pandas DataFrame by-passing the use of plotly.grid_objs
    that is unavailable in the offline mode for plotly. The grids are designed using the `col_name_template`
    from the `column_names` of the `dataset` using the `category_column` for catergories.'''
    
    grid = pd.DataFrame()
    if categories is None:
        categories = dataset[category_column].unique()
    if time_column:
        col_name_template = '{}+{}+{}_grid'
        if years is None:
            years = dataset[time_column].unique()
            
        for year in years:
            for category in categories:
                dataset_by_year_and_cat = dataset[(dataset[time_column] == int(year)) & (dataset[category_column] == category)]
                for col_name in column_names:
                    # Each column name is unique
                    temp = col_name_template.format(year, col_name, category)
                    if dataset_by_year_and_cat[col_name].size != 0:
                        grid = grid.append({'value': list(dataset_by_year_and_cat[col_name]), 'key': temp}, ignore_index=True) 
    else:
        col_name_template = '{}+{}_grid'
        for category in categories:
            dataset_by_cat = dataset[(dataset[category_column] == category)]
            for col_name in column_names:
                # Each column name is unique
                temp = col_name_template.format(col_name, category)
                if dataset_by_cat[col_name].size != 0:
                        grid = grid.append({'value': list(dataset_by_cat[col_name]), 'key': temp}, ignore_index=True) 
        
    return grid 
Example 41
Source File: predict_multianimal.py    From DeepLabCut with GNU Lesser General Public License v3.0 5 votes vote down vote up
def make_nms_grid(nms_radius):
    nms_radius = int(np.ceil(nms_radius))
    size = np.arange(2 * nms_radius + 1)
    xx, yy = np.meshgrid(size, size)
    dist_grid = np.where(
        (xx - nms_radius) ** 2 + (yy - nms_radius) ** 2 <= nms_radius ** 2, 1, 0
    )
    return np.array(dist_grid, dtype=np.uint8) 
Example 42
Source File: datetime.py    From torch-kalman with MIT License 5 votes vote down vote up
def make_grid(self, start_datetimes: Union[np.ndarray, Sequence], num_timesteps: int) -> np.ndarray:
        assert len(start_datetimes.shape) == 1
        datetimes = self.validate_datetimes(start_datetimes)
        offset = np.arange(0, num_timesteps)
        if self.dt_unit == 'W':
            offset *= 7
        return datetimes[:, None] + offset 
Example 43
Source File: fast_fourier_transform.py    From hcipy with MIT License 5 votes vote down vote up
def make_fft_grid(input_grid, q=1, fov=1):
	'''Calculate the grid returned by a Fast Fourier Transform.

	Parameters
	----------
	input_grid : Grid
		The grid defining the sampling in the real domain..
	q : scalar
		The amount of zeropadding to perform. A value of 1 denotes no zeropadding.
	fov : scalar
		The amount of cropping to perform in the Fourier domain.

	Returns
	-------
	Grid
		The grid defining the sampling in the Fourier domain.
	'''
	q = np.ones(input_grid.ndim, dtype='float') * q
	fov = np.ones(input_grid.ndim, dtype='float') * fov

	# Check assumptions
	if not input_grid.is_regular:
		raise ValueError('The input_grid must be regular.')
	if not input_grid.is_('cartesian'):
		raise ValueError('The input_grid must be cartesian.')

	delta = (2 * np.pi / (input_grid.delta * input_grid.dims)) / q
	dims = (input_grid.dims * fov * q).astype('int')
	zero = delta * (-dims / 2 + np.mod(dims, 2) * 0.5)

	return CartesianGrid(RegularCoords(delta, dims, zero)) 
Example 44
Source File: utils.py    From oft with MIT License 5 votes vote down vote up
def make_grid(grid_size, grid_offset, grid_res):
    """
    Constructs an array representing the corners of an orthographic grid 
    """
    depth, width = grid_size
    xoff, yoff, zoff = grid_offset

    xcoords = torch.arange(0., width, grid_res) + xoff
    zcoords = torch.arange(0., depth, grid_res) + zoff

    zz, xx = torch.meshgrid(zcoords, xcoords)
    return torch.stack([xx, torch.full_like(xx, yoff), zz], dim=-1) 
Example 45
Source File: util.py    From hcipy with MIT License 5 votes vote down vote up
def make_subsampled_grid(grid, undersampling):
	'''Make a new grid that undersamples by a factor `undersampling`.

	.. note ::
		The dimensions of the `grid` must be divisible by `undersampling`.

	Parameters
	----------
	grid : Grid
		The grid that we want to oversample.
	undersampling : integer or scalar or ndarray
		The factor by which to undersample. If this is a scalar, it will be rounded to
		the nearest integer. If this is an array, a different undersampling factor will
		be used for each dimension.

	Returns
	-------
	Grid
		The undersampled grid.
	'''
	undersampling = (np.round(undersampling)).astype('int')

	if grid.is_regular:
		delta_new = grid.delta * undersampling
		zero_new = grid.zero - grid.delta / 2 + delta_new / 2
		dims_new = grid.dims // undersampling

		return grid.__class__(RegularCoords(delta_new, dims_new, zero_new))
	elif grid.is_separated:
		raise NotImplementedError()

	raise ValueError("Cannot create a subsampled grid from a non-separated grid.") 
Example 46
Source File: util.py    From hcipy with MIT License 5 votes vote down vote up
def make_supersampled_grid(grid, oversampling):
	'''Make a new grid that oversamples by a factor `oversampling`.

	.. note ::
		The Grid `grid` must be a grid with separable coordinates.

	Parameters
	----------
	grid : Grid
		The grid that we want to oversample.
	oversampling : integer or scalar or ndarray
		The factor by which to oversample. If this is a scalar, it will be rounded to
		the nearest integer. If this is an array, a different oversampling factor will
		be used for each dimension.

	Returns
	-------
	Grid
		The oversampled grid.
	'''
	oversampling = (np.round(oversampling)).astype('int')

	if grid.is_regular:
		delta_new = grid.delta / oversampling
		zero_new = grid.zero - grid.delta / 2 + delta_new / 2
		dims_new = grid.dims * oversampling

		return grid.__class__(RegularCoords(delta_new, dims_new, zero_new))
	elif grid.is_separated:
		raise NotImplementedError()

	raise ValueError('Cannot create a supersampled grid from a non-separated grid.') 
Example 47
Source File: mpl.py    From pwtools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make_axes_grid_fig(num=None):
    """Create an mpl Figure and add to it an axes_grid.SubplotHost subplot
    (`hostax`).

    Returns
    -------
    fig, hostax
    """
    if num is not None:
        fig = plt.figure(num)
    else:
        fig = plt.figure()
    hostax = SubplotHost(fig, 111)
    fig.add_axes(hostax)
    return fig, hostax 
Example 48
Source File: neural_rerendering.py    From neural_rerendering_in_the_wild with Apache License 2.0 5 votes vote down vote up
def make_sample_grid_and_save(est, dataset_name, dataset_parent_dir, grid_dims,
                              output_dir, cur_nimg):
  """Evaluate a fixed set of validation images and save output.

  Args:
    est: tf,estimator.Estimator, TF estimator to run the predictions.
    dataset_name: basename for the validation tfrecord from which to load
      validation images.
    dataset_parent_dir: path to a directory containing the validation tfrecord.
    grid_dims: 2-tuple int for the grid size (1 unit = 1 image).
    output_dir: string, where to save image samples.
    cur_nimg: int, current number of images seen by training.

  Returns:
    None.
  """
  num_examples = grid_dims[0] * grid_dims[1]
  def input_val_fn():
    dict_inp = data.provide_data(
        dataset_name=dataset_name, parent_dir=dataset_parent_dir, subset='val',
        batch_size=1, crop_flag=True, crop_size=opts.train_resolution,
        seeds=[0], max_examples=num_examples,
        use_appearance=opts.use_appearance, shuffle=0)
    x_in = dict_inp['conditional_input']
    x_gt = dict_inp['expected_output']  # ground truth output
    x_app = dict_inp['peek_input']
    return x_in, x_gt, x_app

  def est_input_val_fn():
    x_in, _, x_app = input_val_fn()
    features = {'conditional_input': x_in, 'peek_input': x_app}
    return features

  images = [x for x in est.predict(est_input_val_fn)]
  images = np.array(images, 'f')
  images = images.reshape(grid_dims + images.shape[1:])
  utils.save_images(utils.to_png(utils.images_to_grid(images)), output_dir,
                    cur_nimg) 
Example 49
Source File: utils.py    From tensorboardX with MIT License 5 votes vote down vote up
def make_grid(I, ncols=8):
    # I: N1HW or N3HW
    import numpy as np
    assert isinstance(
        I, np.ndarray), 'plugin error, should pass numpy array here'
    if I.shape[1] == 1:
        I = np.concatenate([I, I, I], 1)
    assert I.ndim == 4 and I.shape[1] == 3 or I.shape[1] == 4
    nimg = I.shape[0]
    H = I.shape[2]
    W = I.shape[3]
    ncols = min(nimg, ncols)
    nrows = int(np.ceil(float(nimg) / ncols))
    canvas = np.zeros((I.shape[1], H * nrows, W * ncols), dtype=I.dtype)
    i = 0
    for y in range(nrows):
        for x in range(ncols):
            if i >= nimg:
                break
            canvas[:, y * H:(y + 1) * H, x * W:(x + 1) * W] = I[i]
            i = i + 1
    return canvas

    # if modality == 'IMG':
    #     if x.dtype == np.uint8:
    #         x = x.astype(np.float32) / 255.0 
Example 50
Source File: datetime.py    From torch-kalman with MIT License 5 votes vote down vote up
def make_delta_grid(self, start_datetimes: Union[np.ndarray, Sequence], num_timesteps: int) -> np.ndarray:
        dts = self.make_grid(start_datetimes, num_timesteps)
        if self.dt_unit is None:
            out = dts.view('int64')
        else:
            out = (dts - DEFAULT_START_DT).view('int64')
        if self.dt_unit == 'W':
            out //= 7
        return out 
Example 51
Source File: util.py    From hcipy with MIT License 5 votes vote down vote up
def make_uniform_grid(dims, extent, center=0, has_center=False):
	'''Create a uniformly-spaced :class:`Grid` of a certain shape and size.

	Parameters
	----------
	dims : scalar or ndarray
		The number of points in each dimension. If this is a scalar, it will
		be multiplexed over all dimensions.
	extent : scalar or ndarray
		The total extent of the grid in each dimension.
	center : scalar or ndarray
		The center point. The grid will by symmetric around this point.
	has_center : boolean
		Does the grid has to have the center as one of its points. If this is
		False, this does not mean that the grid will not have the center.

	Returns
	-------
	Grid
		A :class:`Grid` with :class:`RegularCoords`.
	'''
	num_dims = max(np.array([dims]).shape[-1], np.array([extent]).shape[-1], np.array([center]).shape[-1])

	dims = (np.ones(num_dims) * dims).astype('int')
	extent = (np.ones(num_dims) * extent).astype('float')
	center = (np.ones(num_dims) * center).astype('float')

	delta = extent / dims
	zero = -extent / 2 + center + delta / 2

	if has_center:
		zero -= delta / 2 * (1 - np.mod(dims, 2))

	return CartesianGrid(RegularCoords(delta, dims, zero)) 
Example 52
Source File: util.py    From terrain-erosion-3-ways with MIT License 5 votes vote down vote up
def make_grid_points(shape):
  [Y, X] = np.meshgrid(np.arange(shape[0]), np.arange(shape[1])) 
  grid_points = np.column_stack([X.flatten(), Y.flatten()])
  return grid_points


# Returns a list of points sampled within the bounds of `shape` and with a
# minimum spacing of `radius`.
# NOTE: This function is fairly slow, given that it is implemented with almost
# no array operations. 
Example 53
Source File: misc.py    From Human-Pose-Transfer with MIT License 5 votes vote down vote up
def make_2d_grid(tensors, padding=0, normalize=True, range=None, scale_each=False, pad_value=0):
    # merge image in a batch in `y` direction first.
    grids = [make_grid(
        img_batch, padding=padding, nrow=1, normalize=normalize, range=range, scale_each=scale_each,
        pad_value=pad_value)
        for img_batch in tensors
    ]
    # merge images in `x` direction.
    return make_grid(grids, padding=0, nrow=len(grids)) 
Example 54
Source File: visualize_activations.py    From DeepDIVA with GNU Lesser General Public License v3.0 5 votes vote down vote up
def make_grid_own(activations):
    """
    Plots all activations of a layer in a grid format.
    Parameters
    ----------
    activations: numpy.ndarray
        array of activation values for each filter in a layer

    Returns
    -------
    large_fig: numpy.ndarray
        image array containing all activation heatmaps of a layer
    """
    activations = (activations / np.max(activations)) * 255
    num_plots = int(np.ceil(np.sqrt(activations.shape[0])))
    large_fig = np.zeros((num_plots * activations.shape[1], num_plots * activations.shape[2]))
    y_level = -1
    for idx in range(activations.shape[0]):
        if idx % num_plots == 0:
            y_level += 1
        beg_x = (idx % num_plots) * activations.shape[1]
        end_x = (idx % num_plots + 1) * activations.shape[1]
        beg_y = y_level * activations.shape[2]
        end_y = (y_level + 1) * activations.shape[2]
        large_fig[beg_x:end_x, beg_y:end_y] = activations[idx]
    return large_fig.astype(np.uint8)