returns an reikna plan/FFT obj of shape dshape
19555
def fft_plan(shape, dtype=np.complex64, axes=None, fast_math=True):
    
    # if not axes is None and any([a<0 for a in axes]):
    #     raise NotImplementedError("indices of axes have to be non negative, but are: %s"%str(axes))

    axes = _convert_axes_to_absolute(shape, axes)

    mock_buffer = MockBuffer(dtype, shape)

    fft_plan = FFT(mock_buffer, axes=axes).compile(cluda.ocl_api().Thread(get_device().queue),
                                                   fast_math=fast_math)

    return fft_plan
1109015
def project_shape(
        self, projection: Union[pyproj.Proj, crs.Projection, None] = None
    ) -> base.BaseGeometry:
        

        if self.shape is None:
            return None

        if isinstance(projection, crs.Projection):
            projection = pyproj.Proj(projection.proj4_init)

        if projection is None:
            bounds = self.bounds
            projection = pyproj.Proj(
                proj="aea",  # equivalent projection
                lat_1=bounds[1],
                lat_2=bounds[3],
                lat_0=(bounds[1] + bounds[3]) / 2,
                lon_0=(bounds[0] + bounds[2]) / 2,
            )
        projected_shape = transform(
            partial(
                pyproj.transform, pyproj.Proj(init="EPSG:4326"), projection
            ),
            self.shape,
        )

        if not projected_shape.is_valid:
            warnings.warn("The chosen projection is invalid for current shape")
        return projected_shape
805306
def shape(self, i=0):
        """"""
        shp = self.__getFileObj(self.shp)
        i = self.__restrictIndex(i)
        offset = self.__shapeIndex(i)
        if not offset:
            # Shx index not available so iterate the full list.
            for j,k in enumerate(self.iterShapes()):
                if j == i:
                    return k
        shp.seek(offset)
        return self.__shape()
430190
def reconstruct_from_shape(self, shape, optimize=False):
        
        axes_lengths = list(self.elementary_axes_lengths)
        if self.ellipsis_positions != (math.inf, math.inf):
            if len(shape) < len(self.input_composite_axes) - 1:
                raise EinopsError('Expected at least {} dimensions, got {}'.format(
                    len(self.input_composite_axes) - 1, len(shape)))
        else:
            if len(shape) != len(self.input_composite_axes):
                raise EinopsError('Expected {} dimensions, got {}'.format(len(self.input_composite_axes), len(shape)))
        for input_axis, (known_axes, unknown_axes) in enumerate(self.input_composite_axes):
            before_ellipsis = input_axis
            after_ellipsis = input_axis + len(shape) - len(self.input_composite_axes)
            if input_axis == self.ellipsis_positions[0]:
                assert len(known_axes) == 0 and len(unknown_axes) == 1
                unknown_axis, = unknown_axes
                ellipsis_shape = shape[before_ellipsis:after_ellipsis + 1]
                if any(d is None for d in ellipsis_shape):
                    raise EinopsError("Couldn't infer shape for one or more axes represented by ellipsis")
                axes_lengths[unknown_axis] = _product(ellipsis_shape)
            else:
                if input_axis < self.ellipsis_positions[0]:
                    length = shape[before_ellipsis]
                else:
                    length = shape[after_ellipsis]
                known_product = 1
                for axis in known_axes:
                    known_product *= axes_lengths[axis]

                if len(unknown_axes) == 0:
                    if isinstance(length, int) and isinstance(known_product, int) and length != known_product:
                        raise EinopsError('Shape mismatch, {} != {}'.format(length, known_product))
                else:
                    if isinstance(length, int) and isinstance(known_product, int) and length % known_product != 0:
                        raise EinopsError("Shape mismatch, can't divide axis of length {} in chunks of {}".format(
                            length, known_product))

                    unknown_axis, = unknown_axes
                    axes_lengths[unknown_axis] = length // known_product

        init_shapes = axes_lengths
        reduced_axes_lengths = [dim for i, dim in enumerate(axes_lengths) if i not in self.reduced_elementary_axes]
        final_shapes = []
        for output_axis, grouping in enumerate(self.output_composite_axes):
            if output_axis == self.ellipsis_positions[1]:
                final_shapes.extend(ellipsis_shape)
            else:
                lengths = [reduced_axes_lengths[elementary_axis] for elementary_axis in grouping]
                if any(l is None for l in lengths):
                    final_shapes.append(None)
                else:
                    final_shapes.append(_product(lengths))
        reduced_axes = self.reduced_elementary_axes
        axes_reordering = self.final_axes_grouping_flat
        if optimize:
            return _optimize_transformation(init_shapes, reduced_axes, axes_reordering, final_shapes)
        else:
            return init_shapes, reduced_axes, axes_reordering, final_shapes
877037
def pad_to_shape(d, dshape, mode = "constant"):
    
    if d.shape == dshape:
        return d

    diff = np.array(dshape)- np.array(d.shape)
    #first shrink
    slices  = tuple(slice(-x//2,x//2) if x<0 else slice(None,None) for x in diff)
    res = d[slices]
    #then pad
    # return np.pad(res,[(n/2,n-n/2) if n>0 else (0,0) for n in diff],mode=mode)
    return np.pad(res,[(int(np.ceil(d/2.)),d-int(np.ceil(d/2.))) if d>0 else (0,0) for d in diff],mode=mode)
591945
def to_fits(self):
        

        max_length_coord = 1
        coord_x = []
        coord_y = []
        shapes = []
        radius = []
        rotangle_deg = []
        components = []

        reg_reverse_mapping = {value: key for key, value in
                               reg_mapping['FITS_REGION'].items()}
        reg_reverse_mapping['rectangle'] = 'ROTBOX'
        reg_reverse_mapping['circleannulus'] = 'ANNULUS'
        reg_reverse_mapping['ellipseannulus'] = 'ELLIPTANNULUS'

        for num, shape in enumerate(self):
            shapes.append(reg_reverse_mapping[shape.region_type])
            if shape.region_type == 'polygon':
                max_length_coord = max(len(shape.coord)/2, max_length_coord)
                coord = [x.value for x in shape.coord]
                coord_x.append(coord[::2])
                coord_y.append(coord[1::2])
                radius.append(0)
                rotangle_deg.append(0)
            else:
                coord_x.append(shape.coord[0].value)
                coord_y.append(shape.coord[1].value)
                if shape.region_type in ['circle', 'circleannulus', 'point']:
                    radius.append([float(val) for val in shape.coord[2:]])
                    rotangle_deg.append(0)
                else:
                    radius.append([float(x) for x in shape.coord[2:-1]])
                    rotangle_deg.append(shape.coord[-1].to('deg').value)

            tag = shape.meta.get('tag', '')
            if tag.isdigit():
                components.append(int(tag))
            else:
                components.append(num + 1)

        # padding every value with zeros at the end to make sure that all values
        # in the column have same length.
        for i in range(len(self)):
            if np.isscalar(coord_x[i]):
                coord_x[i] = np.array([coord_x[i]])
            if np.isscalar(coord_y[i]):
                coord_y[i] = np.array([coord_y[i]])
            if np.isscalar(radius[i]):
                radius[i] = np.array([radius[i]])

            coord_x[i] = np.pad(coord_x[i], (0, int(max_length_coord - len(coord_x[i]))),
                                'constant', constant_values=(0, 0))
            coord_y[i] = np.pad(coord_y[i], (0, int(max_length_coord - len(coord_y[i]))),
                                'constant', constant_values=(0, 0))
            radius[i] = np.pad(radius[i], (0, 4 - len(radius[i])), 'constant',
                               constant_values=(0, 0))

        table = Table([coord_x, coord_y, shapes, radius, rotangle_deg, components],
                       names=('X', 'Y', 'SHAPE', 'R', 'ROTANG', 'COMPONENT'))
        table['X'].unit = 'pix'
        table['Y'].unit = 'pix'
        table['R'].unit = 'pix'
        table['ROTANG'].unit = 'deg'

        return table
801134
def get_shape(self, ds_id, ds_info):
        
        var_path = ds_info.get('file_key', '{}'.format(ds_id.name))
        if var_path + '/shape' not in self:
            # loading a scalar value
            shape = 1
        else:
            shape = self[var_path + "/shape"]
            if "index" in ds_info:
                shape = shape[1:]
            if "pressure_index" in ds_info:
                shape = shape[:-1]
        return shape
299168
function getShapeFour(x,y,options,modules,mod_matrix){

  var EOL = '\r\n';
  var width = options.width;
  var height = options.height;
  var length = modules.length;
  var style = options.style;
  var xsize = width / (length + 2 * options.padding);
  var ysize = height / (length + 2 * options.padding);
  var px = (x * xsize + options.padding * xsize);
  var py = (y * ysize + options.padding * ysize);

  //Else in the center of a horizontal-vertical cross
  var orientation = 0;

  switch(options.style){
    case 'square':
      return '<rect transform="rotate('+orientation+' '+(px+xsize/2)+' '+(py+ysize/2)+')"  x="' + px + '" y="' + py + '" width="' + xsize + '" height="' + ysize + '" style="fill:' + options.color + ';shape-rendering:crispEdges;"/>' + EOL;
    case 'circle':
      return '<rect transform="rotate('+orientation+' '+(px+xsize/2)+' '+(py+ysize/2)+')"  rx="'+xsize+'" x="' + px + '" y="' + py + '" width="' + xsize + '" height="' + ysize + '" style="fill:' + options.color + ';shape-rendering:crispEdges;"/>' + EOL;
    case 'sharp-edge':
      return '<rect transform="rotate('+orientation+' '+(px+xsize/2)+' '+(py+ysize/2)+')" x="' + px + '" y="' + py + '" width="' + xsize + '" height="' + ysize + '" style="fill:' + options.color + ';shape-rendering:crispEdges;"/>' + EOL;
  }
}
373630
def seriesshape(self):
        """"""
        seriesshape = [len(hydpy.pub.timegrids.init)]
        seriesshape.extend(self.shape)
        return tuple(seriesshape)
608589
def ds_fitplane(ds):
    
    from pygeotools.lib import iolib
    bma = iolib.ds_getma(ds)
    gt = ds.GetGeoTransform()
    return ma_fitplane(bma, gt)
834032
def shp2geom(shp_fn):
    
    ds = ogr.Open(shp_fn)
    lyr = ds.GetLayer()
    srs = lyr.GetSpatialRef()
    lyr.ResetReading()
    geom_list = []
    for feat in lyr:
        geom = feat.GetGeometryRef()
        geom.AssignSpatialReference(srs)
        #Duplicate the geometry, or segfault
        #See: http://trac.osgeo.org/gdal/wiki/PythonGotchas
        #g = ogr.CreateGeometryFromWkt(geom.ExportToWkt())
        #g.AssignSpatialReference(srs)
        g = geom_dup(geom)
        geom_list.append(g)
    #geom = ogr.ForceToPolygon(' '.join(geom_list))    
    #Dissolve should convert multipolygon to single polygon 
    #return geom_list[0]
    ds = None
    return geom_list
770272
def shape(self):
        ""
        keys = self.keys()
        if self.ndims == 1:
            return (len(keys), 1)
        return len(set(k[0] for k in keys)), len(set(k[1] for k in keys))
1295670
def _reshape_like(F, x, y):
    """"""
    return x.reshape(y.shape) if F is ndarray else F.reshape_like(x, y)
1115171
def wxRect_to_Rect(self, wr):
        
        r = fitz.Rect(wr.x, wr.y, wr.x + wr.width, wr.y + wr.height)
        return r * self.shrink
180888
def R_rot_2d(th):
    
    s, = np.sin(th).T
    c, = np.cos(th).T
    R = np.empty((len(th), 2, 2), dtype=np.float)

    R[:, 0, 0] = c
    R[:, 0, 1] = -s

    R[:, 1, 0] = s
    R[:, 1, 1] = c

    return R
1028099
def blockshaped(arr, nrows, ncols):
    
    h, w = arr.shape
    return (arr.reshape(h // nrows, nrows, -1, ncols)
               .swapaxes(1, 2)
               .reshape(-1, nrows, ncols))
467416
def shape_list(x):
  """"""
  x = tf.convert_to_tensor(x)

  # If unknown rank, return dynamic shape
  if x.get_shape().dims is None:
    return tf.shape(x)

  static = x.get_shape().as_list()
  shape = tf.shape(x)

  ret = []
  for i, dim in enumerate(static):
    if dim is None:
      dim = shape[i]
    ret.append(dim)
  return ret