Python numpy.fromfunction() Examples

The following are 30 code examples for showing how to use numpy.fromfunction(). These examples are extracted from open source projects. 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.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: tf-pose   Author: SrikanthVelpuri   File: ROI.py    License: Apache License 2.0 6 votes vote down vote up
def getArrayRegion(self, arr, img=None, axes=(0, 1), **kwds):
        """
        Return the result of ROI.getArrayRegion() masked by the elliptical shape
        of the ROI. Regions outside the ellipse are set to 0.
        """
        # Note: we could use the same method as used by PolyLineROI, but this
        # implementation produces a nicer mask.
        arr = ROI.getArrayRegion(self, arr, img, axes, **kwds)
        if arr is None or arr.shape[axes[0]] == 0 or arr.shape[axes[1]] == 0:
            return arr
        w = arr.shape[axes[0]]
        h = arr.shape[axes[1]]

        ## generate an ellipsoidal mask
        mask = np.fromfunction(lambda x,y: (((x+0.5)/(w/2.)-1)**2+ ((y+0.5)/(h/2.)-1)**2)**0.5 < 1, (w, h))
        
        # reshape to match array axes
        if axes[0] > axes[1]:
            mask = mask.T
        shape = [(n if i in axes else 1) for i,n in enumerate(arr.shape)]
        mask = mask.reshape(shape)
        
        return arr * mask 
Example 2
Project: chainer   Author: chainer   File: from_data.py    License: MIT License 6 votes vote down vote up
def fromfunction(function, shape, **kwargs):
    """ Constructs an array by executing a function over each coordinate.

    This is currently equivalent to :func:`numpy.fromfunction`
    wrapped by :func:`chainerx.array`, given the device argument.

    Note:
        Keywords other than ``dtype`` and ``device`` are passed to
        ```function```.

    .. seealso:: :func:`numpy.fromfunction`

    """
    dtype = kwargs.pop('dtype', float)
    device = kwargs.pop('device', None)
    return chainerx.array(
        numpy.fromfunction(
            function, shape, dtype=dtype, **kwargs),
        device=device)


# TODO(hvy): Optimize with pre-allocated memory using count for non-native
# devices. 
Example 3
Project: nasbench   Author: google-research   File: graph_util.py    License: Apache License 2.0 6 votes vote down vote up
def permute_graph(graph, label, permutation):
  """Permutes the graph and labels based on permutation.

  Args:
    graph: np.ndarray adjacency matrix.
    label: list of labels of same length as graph dimensions.
    permutation: a permutation list of ints of same length as graph dimensions.

  Returns:
    np.ndarray where vertex permutation[v] is vertex v from the original graph
  """
  # vertex permutation[v] in new graph is vertex v in the old graph
  forward_perm = zip(permutation, list(range(len(permutation))))
  inverse_perm = [x[1] for x in sorted(forward_perm)]
  edge_fn = lambda x, y: graph[inverse_perm[x], inverse_perm[y]] == 1
  new_matrix = np.fromfunction(np.vectorize(edge_fn),
                               (len(label), len(label)),
                               dtype=np.int8)
  new_label = [label[inverse_perm[i]] for i in range(len(label))]
  return new_matrix, new_label 
Example 4
Project: eval-nas   Author: kcyu2014   File: graph_util.py    License: MIT License 6 votes vote down vote up
def permute_graph(graph, label, permutation):
    """Permutes the graph and labels based on permutation.

    Args:
      graph: np.ndarray adjacency matrix.
      label: list of labels of same length as graph dimensions.
      permutation: a permutation list of ints of same length as graph dimensions.

    Returns:
      np.ndarray where vertex permutation[v] is vertex v from the original graph
    """
    # vertex permutation[v] in new graph is vertex v in the old graph
    forward_perm = zip(permutation, list(range(len(permutation))))
    inverse_perm = [x[1] for x in sorted(forward_perm)]
    edge_fn = lambda x, y: graph[inverse_perm[x], inverse_perm[y]] == 1
    new_matrix = np.fromfunction(np.vectorize(edge_fn),
                                 (len(label), len(label)),
                                 dtype=np.int8)
    new_label = [label[inverse_perm[i]] for i in range(len(label))]
    return new_matrix, new_label 
Example 5
Project: pyresample   Author: pytroll   File: test_kd_tree.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_nearest_masked_swath_target(self):
        """Test that a masked array works as a target."""
        data = np.fromfunction(lambda y, x: y * x, (50, 10))
        lons = np.fromfunction(lambda y, x: 3 + x, (50, 10))
        lats = np.fromfunction(lambda y, x: 75 - y, (50, 10))
        mask = np.ones_like(lons, dtype=np.bool)
        mask[::2, ::2] = False
        swath_def = geometry.SwathDefinition(
            lons=np.ma.masked_array(lons, mask=mask),
            lats=np.ma.masked_array(lats, mask=False)
        )
        res = kd_tree.resample_nearest(swath_def, data.ravel(),
                                       swath_def, 50000, segments=3)
        cross_sum = res.sum()
        # expected = 12716  # if masks aren't respected
        expected = 12000
        self.assertEqual(cross_sum, expected) 
Example 6
Project: pyresample   Author: pytroll   File: test_kd_tree.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_gauss_multi(self):
        data = np.fromfunction(lambda y, x: (y + x) * 10 ** -6, (5000, 100))
        lons = np.fromfunction(
            lambda y, x: 3 + (10.0 / 100) * x, (5000, 100))
        lats = np.fromfunction(
            lambda y, x: 75 - (50.0 / 5000) * y, (5000, 100))
        swath_def = geometry.SwathDefinition(lons=lons, lats=lats)
        data_multi = np.column_stack((data.ravel(), data.ravel(),
                                      data.ravel()))
        with catch_warnings(UserWarning) as w:
            res = kd_tree.resample_gauss(swath_def, data_multi,
                                         self.area_def, 50000, [25000, 15000, 10000], segments=1)
            self.assertFalse(len(w) != 1)
            self.assertFalse(('Possible more' not in str(w[0].message)))
        cross_sum = res.sum()
        expected = 1461.8429990248171
        self.assertAlmostEqual(cross_sum, expected) 
Example 7
Project: pyresample   Author: pytroll   File: test_kd_tree.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_gauss_multi_mp(self):
        data = np.fromfunction(lambda y, x: (y + x) * 10 ** -6, (5000, 100))
        lons = np.fromfunction(
            lambda y, x: 3 + (10.0 / 100) * x, (5000, 100))
        lats = np.fromfunction(
            lambda y, x: 75 - (50.0 / 5000) * y, (5000, 100))
        swath_def = geometry.SwathDefinition(lons=lons, lats=lats)
        data_multi = np.column_stack((data.ravel(), data.ravel(),
                                      data.ravel()))
        with catch_warnings(UserWarning) as w:
            res = kd_tree.resample_gauss(swath_def, data_multi,
                                         self.area_def, 50000, [
                                             25000, 15000, 10000],
                                         nprocs=2, segments=1)
            self.assertFalse(len(w) != 1)
            self.assertFalse(('Possible more' not in str(w[0].message)))
        cross_sum = res.sum()
        expected = 1461.8429990248171
        self.assertAlmostEqual(cross_sum, expected) 
Example 8
Project: pyresample   Author: pytroll   File: test_kd_tree.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_gauss_multi_mp_segments(self):
        data = np.fromfunction(lambda y, x: (y + x) * 10 ** -6, (5000, 100))
        lons = np.fromfunction(
            lambda y, x: 3 + (10.0 / 100) * x, (5000, 100))
        lats = np.fromfunction(
            lambda y, x: 75 - (50.0 / 5000) * y, (5000, 100))
        swath_def = geometry.SwathDefinition(lons=lons, lats=lats)
        data_multi = np.column_stack((data.ravel(), data.ravel(),
                                      data.ravel()))
        with catch_warnings(UserWarning) as w:
            res = kd_tree.resample_gauss(swath_def, data_multi,
                                         self.area_def, 50000, [
                                             25000, 15000, 10000],
                                         nprocs=2, segments=1)
            self.assertFalse(len(w) != 1)
            self.assertFalse('Possible more' not in str(w[0].message))
        cross_sum = res.sum()
        expected = 1461.8429990248171
        self.assertAlmostEqual(cross_sum, expected) 
Example 9
Project: pyresample   Author: pytroll   File: test_kd_tree.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_masked_gauss(self):
        data = np.ones((50, 10))
        data[:, 5:] = 2
        lons = np.fromfunction(lambda y, x: 3 + x, (50, 10))
        lats = np.fromfunction(lambda y, x: 75 - y, (50, 10))
        swath_def = geometry.SwathDefinition(lons=lons, lats=lats)
        mask = np.ones((50, 10))
        mask[:, :5] = 0
        masked_data = np.ma.array(data, mask=mask)
        res = kd_tree.resample_gauss(swath_def, masked_data.ravel(),
                                     self.area_def, 50000, 25000, segments=1)
        expected_mask = np.fromfile(os.path.join(os.path.dirname(__file__),
                                                 'test_files',
                                                 'mask_test_mask.dat'),
                                    sep=' ').reshape((800, 800))
        expected_data = np.fromfile(os.path.join(os.path.dirname(__file__),
                                                 'test_files',
                                                 'mask_test_data.dat'),
                                    sep=' ').reshape((800, 800))
        expected = expected_data.sum()
        cross_sum = res.data.sum()

        self.assertTrue(np.array_equal(expected_mask, res.mask))
        self.assertAlmostEqual(cross_sum, expected, places=3) 
Example 10
Project: pyresample   Author: pytroll   File: test_kd_tree.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_masked_full(self):
        data = np.ones((50, 10))
        data[:, 5:] = 2
        mask = np.ones((50, 10))
        mask[:, :5] = 0
        masked_data = np.ma.array(data, mask=mask)
        lons = np.fromfunction(lambda y, x: 3 + x, (50, 10))
        lats = np.fromfunction(lambda y, x: 75 - y, (50, 10))
        swath_def = geometry.SwathDefinition(lons=lons, lats=lats)
        res = kd_tree.resample_nearest(swath_def,
                                       masked_data.ravel(
                                       ), self.area_def, 50000,
                                       fill_value=None, segments=1)
        expected_fill_mask = np.fromfile(os.path.join(os.path.dirname(__file__),
                                                      'test_files',
                                                      'mask_test_full_fill.dat'),
                                         sep=' ').reshape((800, 800))
        fill_mask = res.mask

        self.assertTrue(np.array_equal(fill_mask, expected_fill_mask)) 
Example 11
Project: tf-pose   Author: SrikanthVelpuri   File: GLScatterPlotItem.py    License: Apache License 2.0 5 votes vote down vote up
def initializeGL(self):
        
        ## Generate texture for rendering points
        w = 64
        def fn(x,y):
            r = ((x-w/2.)**2 + (y-w/2.)**2) ** 0.5
            return 255 * (w/2. - np.clip(r, w/2.-1.0, w/2.))
        pData = np.empty((w, w, 4))
        pData[:] = 255
        pData[:,:,3] = np.fromfunction(fn, pData.shape[:2])
        #print pData.shape, pData.min(), pData.max()
        pData = pData.astype(np.ubyte)
        
        if getattr(self, "pointTexture", None) is None:
            self.pointTexture = glGenTextures(1)
        glActiveTexture(GL_TEXTURE0)
        glEnable(GL_TEXTURE_2D)
        glBindTexture(GL_TEXTURE_2D, self.pointTexture)
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, pData.shape[0], pData.shape[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, pData)
        
        self.shader = shaders.getShaderProgram('pointSprite')
        
    #def getVBO(self, name):
        #if name not in self.vbo:
            #self.vbo[name] = vbo.VBO(getattr(self, name).astype('f'))
        #return self.vbo[name]
        
    #def setupGLState(self):
        #"""Prepare OpenGL state for drawing. This function is called immediately before painting."""
        ##glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)  ## requires z-sorting to render properly.
        #glBlendFunc(GL_SRC_ALPHA, GL_ONE)
        #glEnable( GL_BLEND )
        #glEnable( GL_ALPHA_TEST )
        #glDisable( GL_DEPTH_TEST )
        
        ##glEnable( GL_POINT_SMOOTH )

        ##glHint(GL_POINT_SMOOTH_HINT, GL_NICEST)
        ##glPointParameterfv(GL_POINT_DISTANCE_ATTENUATION, (0, 0, -1e-3))
        ##glPointParameterfv(GL_POINT_SIZE_MAX, (65500,))
        ##glPointParameterfv(GL_POINT_SIZE_MIN, (0,)) 
Example 12
Project: DenseMatchingBenchmark   Author: DeepMotionAIResearch   File: flow_trans.py    License: MIT License 5 votes vote down vote up
def __call__(self, sample):
        if 'flow' not in sample.keys():
            return sample

        applied_angle = random.uniform(-self.angle,self.angle)
        diff = random.uniform(-self.diff_angle,self.diff_angle)
        angle1 = applied_angle - diff/2
        angle2 = applied_angle + diff/2
        angle1_rad = angle1*np.pi/180

        h, w = sample['leftImage'].shape[-2:]

        def rotate_flow(k, i, j):
            return -k*(j-w/2)*(diff*np.pi/180) + (1-k)*(i-h/2)*(diff*np.pi/180)

        rotate_flow_map = np.fromfunction(rotate_flow, sample['flow'].shape)
        sample['flow'] += rotate_flow_map

        sample['leftImage'] = ndimage.interpolation.rotate(sample['leftImage'], angle1, axes=(-2, -1), reshape=self.reshape, order=self.order)
        sample['rightImage'] = ndimage.interpolation.rotate(sample['rightImage'], angle2, axes=(-2, -1), reshape=self.reshape, order=self.order)
        sample['flow'] = ndimage.interpolation.rotate(sample['flow'], angle1, axes=(-2, -1), reshape=self.reshape, order=self.order)
        # flow vectors must be rotated too! careful about Y flow which is upside down, clockwise
        flow = np.copy(sample['flow'])
        sample['flow'][0,:,:] = np.cos(angle1_rad)*flow[0,:,:] + np.sin(angle1_rad)*flow[1,:,:]
        sample['flow'][1,:,:] = -np.sin(angle1_rad)*flow[0,:,:] + np.cos(angle1_rad)*flow[1,:,:]

        return sample 
Example 13
Project: nas_benchmarks   Author: automl   File: nas_cifar10.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def objective_function(self, config, budget=108):
        if self.multi_fidelity is False:
            assert budget == 108

        bitlist = [0] * (VERTICES * (VERTICES - 1) // 2)
        for i in range(MAX_EDGES):
            bitlist[config["edge_%d" % i]] = 1
        out = 0
        for bit in bitlist:
            out = (out << 1) | bit

        matrix = np.fromfunction(graph_util.gen_is_edge_fn(out),
                                 (VERTICES, VERTICES),
                                 dtype=np.int8)
        # if not graph_util.is_full_dag(matrix) or graph_util.num_edges(matrix) > MAX_EDGES:
        if graph_util.num_edges(matrix) > MAX_EDGES:
            self.record_invalid(config, 1, 1, 0)
            return 1, 0

        labeling = [config["op_node_%d" % i] for i in range(5)]
        labeling = ['input'] + list(labeling) + ['output']
        model_spec = api.ModelSpec(matrix, labeling)
        try:
            data = self.dataset.query(model_spec, epochs=budget)
        except api.OutOfDomainError:
            self.record_invalid(config, 1, 1, 0)
            return 1, 0

        self.record_valid(config, data, model_spec)

        return 1 - data["validation_accuracy"], data["training_time"] 
Example 14
Project: Computable   Author: ktraunmueller   File: functions.py    License: MIT License 5 votes vote down vote up
def fromfunction(shape, dimensions, type=None, typecode=None, dtype=None):
    dtype = type2dtype(typecode, type, dtype, 1)
    return np.fromfunction(shape, dimensions, dtype=dtype) 
Example 15
Project: Computable   Author: ktraunmueller   File: functions.py    License: MIT License 5 votes vote down vote up
def fromfunction(args, dimensions):
    return np.fromfunction(args, dimensions, dtype=int) 
Example 16
Project: Cura   Author: Ultimaker   File: Arrange.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def centerFirst(self):
        """Fill priority, center is best. Lower value is better. """

        # Square distance: creates a more round shape
        self._priority = numpy.fromfunction(
            lambda j, i: (self._offset_x - i) ** 2 + (self._offset_y - j) ** 2, self._shape, dtype=numpy.int32)
        self._priority_unique_values = numpy.unique(self._priority)
        self._priority_unique_values.sort() 
Example 17
Project: Cura   Author: Ultimaker   File: Arrange.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def backFirst(self):
        """Fill priority, back is best. Lower value is better """

        self._priority = numpy.fromfunction(
            lambda j, i: 10 * j + abs(self._offset_x - i), self._shape, dtype=numpy.int32)
        self._priority_unique_values = numpy.unique(self._priority)
        self._priority_unique_values.sort() 
Example 18
Project: gridfinder   Author: carderne   File: prepare.py    License: MIT License 5 votes vote down vote up
def create_filter():
    """Create and return a numpy array filter to be applied to the raster."""
    vec_filter_func = np.vectorize(filter_func)
    ntl_filter = np.fromfunction(vec_filter_func, (41, 41), dtype=float)

    ntl_filter = ntl_filter / ntl_filter.sum()

    return ntl_filter 
Example 19
Project: ektelo   Author: ektelo   File: mapper.py    License: Apache License 2.0 5 votes vote down vote up
def partition_grid(domain_shape, grid_shape, canonical_order=False):
    """
    :param domain_shape: a shape tuple describing the domain, e.g (6,6) (in 2D)
    :param grid_shape: a shape tuple describing cells to be grouped, e.g. (2,3) to form groups of 2 rows and 3 cols
        note: in 1D both of the above params can simply be integers
    :return: a partition array in which grouped cells are assigned some unique 'group id' values
             no guarantee on order of the group ids, only that they are unique
    """

    # allow for integers instead of shape tuples in 1D
    if isinstance(domain_shape, int):
        domain_shape = (domain_shape, )
    if isinstance(grid_shape, int):
        grid_shape = (grid_shape,)

    assert sum(divmod(d,b)[1] for (d,b) in zip(domain_shape, grid_shape)) == 0, "Domain size along each dimension should be a multiple of size of block"

    def g(*idx):
        """
        This function will receive an index tuple from numpy.fromfunction
        It's behavior depends on grid_shape: take (i,j) and divide by grid_shape (in each dimension)
        That becomes an identifier of the block; then assign a unique integer to it using pairing.
        """
        x = np.array(idx)
        y = np.array(grid_shape)

        return general_pairing( util.old_div(x,y) )  # broadcasting integer division

    h = np.vectorize(g)

    # numpy.fromfunction builds an array of domain_shape by calling a function with each index tuple (e.g. (i,j))
    partition_array = np.fromfunction(h, domain_shape, dtype=int)

    if canonical_order:
        partition_array = support.canonical_ordering(partition_array)

    return partition_array 
Example 20
Project: ektelo   Author: ektelo   File: dataset.py    License: Apache License 2.0 5 votes vote down vote up
def partition_grid(domain_shape, grid_shape):
    """
    :param domain_shape: a shape tuple describing the domain, e.g (6,6) (in 2D)
    :param grid_shape: a shape tuple describing cells to be grouped, e.g. (2,3) to form groups of 2 rows and 3 cols
        note: in 1D both of the above params can simply be integers
    :return: a partition array in which grouped cells are assigned some unique 'group id' values
             no guarantee on order of the group ids, only that they are unique
    """

    # allow for integers instead of shape tuples in 1D
    if isinstance(domain_shape, int):
        domain_shape = (domain_shape, )
    if isinstance(grid_shape, int):
        grid_shape = (grid_shape,)

    assert sum(divmod(d,b)[1] for (d,b) in zip(domain_shape, grid_shape)) == 0, "Domain size along each dimension should be a multiple of size of block"

    def g(*idx):
        """
        This function will receive an index tuple from numpy.fromfunction
        It's behavior depends on grid_shape: take (i,j) and divide by grid_shape (in each dimension)
        That becomes an identifier of the block; then assign a unique integer to it using pairing.
        """
        x = numpy.array(idx)
        y = numpy.array(grid_shape)
        return general_pairing( util.old_div(x,y) )  # broadcasting integer division

    h = numpy.vectorize(g)

    # numpy.fromfunction builds an array of domain_shape by calling a function with each index tuple (e.g. (i,j))
    partition_array = numpy.fromfunction(h, domain_shape, dtype=int)
    # transform to canonical order
    partition_array = canonicalTransform(partition_array)
    return partition_array 
Example 21
Project: Deep_MRI_brain_extraction   Author: GUR9000   File: NN_PerceptronLayer.py    License: MIT License 5 votes vote down vote up
def __make_window(self):
        print "window is on 32x32, fixed sigma, assuming RGB."
        denom = 29.8
        x0= 16
        sig = 19
        fun = lambda z,x,y: (32/denom* np.exp(-(abs(x - x0))**3/(2*sig**3)))*(32/denom*np.exp(-(abs(y - x0))**3/(2*sig**3)))#, {x, 0, 32}, {y, 0, 32}
        return np.fromfunction(fun,(3,32,32)) 
Example 22
Project: chainer   Author: chainer   File: independent.py    License: MIT License 5 votes vote down vote up
def _block_indicator(self):
        n_repeats = array.size_of_shape(
            self.distribution.batch_shape[-self.reinterpreted_batch_ndims:])
        dim = array.size_of_shape(self.distribution.event_shape)
        block_indicator = numpy.fromfunction(
            lambda i, j: i // dim == j // dim,
            (n_repeats * dim, n_repeats * dim)).astype(int)
        if self.xp is cuda.cupy:
            block_indicator = cuda.to_gpu(block_indicator)
        return block_indicator 
Example 23
Project: Python-notes   Author: tomoncle   File: numpy_ndarray.py    License: MIT License 5 votes vote down vote up
def np_list_by_func():
    """
    通过函数创建数组
    :return: 
    """
    # fromfunction 传入一个函数,和表示一个维度大小的可迭代对象(元组,列表)
    # 即(10,)表示一维数组,一维元素10个,此时函数接收一个参数
    #   (5,6)表示二维数组,一维元素5个,二维元素6个,此时函数接收2个参数
    print np.fromfunction(lambda x: x + 1, (10,))
    print np.fromfunction(lambda x, y: (x + 1) * (y + 1), (5, 6))
    split_line() 
Example 24
Project: Python-notes   Author: tomoncle   File: numpy_multidimensional.py    License: MIT License 5 votes vote down vote up
def multi_2_func():
    """
    使用函数创建2维数组
    :return: 
    """
    print np.fromfunction(lambda x, y: (x + 1) * y, (10, 5))
    split_line() 
Example 25
Project: landmark-detection   Author: D-X-Y   File: pts_utils.py    License: MIT License 5 votes vote down vote up
def generate_label_map_laplacian(pts, height, width, sigma, downsample, visiable=None):
  if isinstance(pts, numbers.Number):
    # this image does not provide the annotation, pts is a int number representing the number of points
    return np.zeros((height,width,pts+1), dtype='float32'), np.ones((1,1,1+pts), dtype='float32')

  assert isinstance(pts, np.ndarray) and len(pts.shape) == 2 and pts.shape[0] == 3, 'The shape of points : {}'.format(pts.shape)
  if isinstance(sigma, numbers.Number):
    sigma = np.zeros((pts.shape[1])) + sigma
  assert isinstance(sigma, np.ndarray) and len(sigma.shape) == 1 and sigma.shape[0] == pts.shape[1], 'The shape of sigma : {}'.format(sigma.shape)

  offset = downsample / 2.0 - 0.5
  num_points, threshold = pts.shape[1], 0.01

  if visiable is None: visiable = pts[2, :].astype('bool')
  assert visiable.shape[0] == num_points

  transformed_label = np.fromfunction( lambda y, x, pid : ((offset + x*downsample - pts[0,pid])**2 \
                                                        + (offset + y*downsample - pts[1,pid])**2) \
                                                          / -2.0 / sigma[pid] / sigma[pid],
                                                          (height, width, num_points), dtype=int)

  mask_heatmap      = np.ones((1, 1, num_points+1), dtype='float32')
  mask_heatmap[0, 0, :num_points] = visiable
  mask_heatmap[0, 0, num_points]  = 1
  
  transformed_label = (1+transformed_label) * np.exp(transformed_label)
  transformed_label[ transformed_label < threshold ] = 0
  transformed_label[ transformed_label >         1 ] = 1

  background_label  = 1 - np.amax(transformed_label, axis=2)
  background_label[ background_label < 0 ] = 0
  heatmap           = np.concatenate((transformed_label, np.expand_dims(background_label, axis=2)), axis=2).astype('float32')
  
  return heatmap*mask_heatmap, mask_heatmap 
Example 26
Project: landmark-detection   Author: D-X-Y   File: pts_utils.py    License: MIT License 5 votes vote down vote up
def generate_label_map_gaussian(pts, height, width, sigma, downsample, visiable=None):
  if isinstance(pts, numbers.Number):
    # this image does not provide the annotation, pts is a int number representing the number of points
    return np.zeros((height,width,pts+1), dtype='float32'), np.ones((1,1,1+pts), dtype='float32')

  assert isinstance(pts, np.ndarray) and len(pts.shape) == 2 and pts.shape[0] == 3, 'The shape of points : {}'.format(pts.shape)
  if isinstance(sigma, numbers.Number):
    sigma = np.zeros((pts.shape[1])) + sigma
  assert isinstance(sigma, np.ndarray) and len(sigma.shape) == 1 and sigma.shape[0] == pts.shape[1], 'The shape of sigma : {}'.format(sigma.shape)

  offset = downsample / 2.0 - 0.5
  num_points, threshold = pts.shape[1], 0.01

  if visiable is None: visiable = pts[2, :].astype('bool')
  assert visiable.shape[0] == num_points

  transformed_label = np.fromfunction( lambda y, x, pid : ((offset + x*downsample - pts[0,pid])**2 \
                                                        + (offset + y*downsample - pts[1,pid])**2) \
                                                          / -2.0 / sigma[pid] / sigma[pid],
                                                          (height, width, num_points), dtype=int)

  mask_heatmap      = np.ones((1, 1, num_points+1), dtype='float32')
  mask_heatmap[0, 0, :num_points] = visiable
  mask_heatmap[0, 0, num_points]  = 1
  
  transformed_label = np.exp(transformed_label)
  transformed_label[ transformed_label < threshold ] = 0
  transformed_label[ transformed_label >         1 ] = 1

  background_label  = 1 - np.amax(transformed_label, axis=2)
  background_label[ background_label < 0 ] = 0
  heatmap           = np.concatenate((transformed_label, np.expand_dims(background_label, axis=2)), axis=2).astype('float32')
  
  return heatmap*mask_heatmap, mask_heatmap 
Example 27
Project: landmark-detection   Author: D-X-Y   File: basic_utils.py    License: MIT License 5 votes vote down vote up
def Generate_Weight(patch_size, sigma=None):
  assert isinstance(patch_size, list) or isinstance(patch_size, tuple)
  assert patch_size[0] > 0 and patch_size[1] > 0, 'the patch size must > 0 rather :{}'.format(patch_size)
  center = [(patch_size[0]-1.)/2, (patch_size[1]-1.)/2]
  maps = np.fromfunction( lambda x, y: (x-center[0])**2 + (y-center[1])**2, (patch_size[0], patch_size[1]), dtype=int)
  if sigma is None: sigma = min(patch_size[0], patch_size[1])/2.
  maps = np.exp(maps / -2.0 / sigma / sigma)
  maps[0, :] = maps[-1, :] = maps[:, 0] = maps[:, -1] = 0
  return maps.astype(np.float32) 
Example 28
Project: hyppo   Author: neurodata   File: test_dcorrx.py    License: Apache License 2.0 5 votes vote down vote up
def test_distance(self):
        n = 6
        x = np.ones(n)
        y = np.arange(1, n + 1)

        distx = np.zeros((n, n))
        disty = np.fromfunction(lambda i, j: np.abs(i - j), (n, n))

        stat1 = DcorrX(max_lag=1).test(x, y)[0]
        stat2 = DcorrX(max_lag=1).test(distx, disty)[0]

        assert_almost_equal(stat1, stat2, decimal=0) 
Example 29
Project: hyppo   Author: neurodata   File: test_mgcx.py    License: Apache License 2.0 5 votes vote down vote up
def test_distance(self):
        n = 10
        x = np.arange(1, n + 1)
        y = np.arange(1, n + 1)

        distx = np.fromfunction(lambda i, j: np.abs(i - j), (n, n))
        disty = np.fromfunction(lambda i, j: np.abs(i - j), (n, n))

        stat1 = MGCX(max_lag=1).test(x, y)[0]
        stat2 = MGCX(max_lag=1).test(distx, disty)[0]

        assert_almost_equal(stat1, stat2, decimal=0) 
Example 30
Project: PyAbel   Author: PyAbel   File: linbasex.py    License: MIT License 5 votes vote down vote up
def _Slices(Beta, legendre_orders, smoothing=0):
    """Convolve Beta with a Gaussian function of 1/e width smoothing.

    """

    pol = len(legendre_orders)
    NP = len(Beta[0])  # number of points in 3_d plot.
    index = range(NP)

    Beta_convol = np.zeros((pol, NP))
    Slice_3D = np.zeros((pol, 2*NP, 2*NP))

    # Convolve Beta's with smoothing function
    if smoothing > 0:
        # smoothing function
        Basis_s = np.fromfunction(lambda i: np.exp(-(i - (NP)/2)**2 /
                                  (2*smoothing**2))/(smoothing*2.5), (NP,))
        for i in range(pol):
            Beta_convol[i] = np.convolve(Basis_s, Beta[i], mode='same')
    else:
        Beta_convol = Beta

    # Calculate ordered slices:
    for i in range(pol):
        Slice_3D[i] = np.fromfunction(lambda k, l: _SL(i, (k-NP), (l-NP),
                       Beta_convol, index, legendre_orders), (2*NP, 2*NP))
    # Sum ordered slices up
    Slice = np.sum(Slice_3D, axis=0)

    return Slice, Beta_convol