Пример #1
0
def getkgrid(ng=128,boxsize=512.,whattoget = 'k'):
    thirdim=ng/2+1
    sk = (ng,ng,thirdim)

    kx = N.fromfunction(lambda x,y,z:x, sk).astype(N.float32)
    kx[N.where(kx > ng/2)] -= ng
    kz = N.fromfunction(lambda x,y,z:z, sk).astype(N.float32)
    kz[N.where(kz > ng/2)] -= ng

    if whattoget != 'kxkzk2':
        kmin = 2.*N.pi/boxsize
        kx *= kmin
        kz *= kmin
        
    k2 = kx**2+kx.swapaxes(0,1)**2+kz**2
    if whattoget == 'kxkzOk2':
        k2[0,0,0] = 1.
        return kx/k2, kz/k2
    elif whattoget == 'kxkzk2':
        k2[0,0,0]= 1.
        return kx, kz, k2
    elif whattoget == 'k2':
        return k2
    elif whattoget == 'k':
        return N.sqrt(k2)
    else:
        print 'I dunno what to get'
Пример #2
0
def _clusterKMeans(image, K, numIterations, debug=None):
    width, height = image.shape[:2]
    
    ## add an extra channel containing distance from center to make
    ## clusters favor circular features around the center of the image

    # if we have a 2 pixel wide image, the center should be between pixels 0 and 1
    center_x, center_y = (width-1)/2., (height-1)/2.

    # compute distance from center
    dx = np.fromfunction(lambda x,y: x - center_x, (width,1))
    dy = np.fromfunction(lambda x,y: y - center_y, (1,height))
    dist_from_center = np.sqrt(np.add(np.square(dx), np.square(dy)))
    dist_from_center /= dist_from_center[0,0] * COORDINATE_TO_COLOR_RATIO

    # add as a new channel to image
    image = np.dstack([image, dist_from_center])

    # sample 10000 pixels and use K-means to determine the clusters
    channels = image.shape[2]
    pixels = image.reshape(-1, channels)
    npoints = pixels.shape[0]
    indices = np.random.choice(npoints, 10000)
    samples = pixels[indices]

    centroids, _ = kmeans(samples, K, numIterations)
    quantized, _ = vq(pixels, centroids)

    clustered = quantized.reshape(width, height)

    if debug is not None:
        debug["clustered"] = labnorm2rgb(centroids[clustered])
    
    return centroids, clustered
Пример #3
0
def detectorgeometry(ddef, npdtype='float32'):
    """ calculates the geometric properties of the detector
        from its definitions
        parameters:
            ddef is array detector definitions

        returns:
            pixelpositions    The endpoint of all the vectors
            unitnormalvector  of the detector  """
    c0 = np.array([ddef[0],ddef[1],ddef[2]]) # corner c1-c0-c2
    c1 = np.array([ddef[3],ddef[4],ddef[5]]) # corner c0-c1-c3 or 1st axis endposition
    c2 = np.array([ddef[6],ddef[7],ddef[8]]) # corner c0-c2-c3 or 2nd axis endposition
    r1 = ddef[9]   # resolution in 1st dimension
    r2 = ddef[10]  # resolution in 2nd dimension

    dshape = (r2,r1)  # CONTROL of SEQUENCE
    # unit direction vectors of detector sides
    di = (c1 - c0) * (1.0/r1)
    dj = (c2 - c0) * (1.0/r2)
    def pcfun(j,i,k): return  c0[k] + (i+0.5) * di[k] + (j+0.5) * dj[k]
    def pcfunx(j,i):  return pcfun(j,i,0)
    def pcfuny(j,i):  return pcfun(j,i,1)
    def pcfunz(j,i):  return pcfun(j,i,2)
    pxs  = numpy.fromfunction(pcfunx, shape=dshape, dtype=npdtype )
    pys  = numpy.fromfunction(pcfuny, shape=dshape, dtype=npdtype )
    pzs  = numpy.fromfunction(pcfunz, shape=dshape, dtype=npdtype )
    pixelpositions = np.array(numpy.dstack((pxs,pys,pzs))) # shape = (r2,r1,3)

    pixelareavector = np.array(numpy.cross(di, dj))
    result = np.zeros(dshape)

    return  pixelpositions, pixelareavector, dshape, result
Пример #4
0
 def test_masked_full_multi(self):
     data = numpy.ones((50, 10))
     data[:, 5:] = 2
     mask1 = numpy.ones((50, 10))
     mask1[:, :5] = 0
     mask2 = numpy.ones((50, 10))
     mask2[:, 5:] = 0
     mask3 = numpy.ones((50, 10))
     mask3[:25, :] = 0
     data_multi = numpy.column_stack(
         (data.ravel(), data.ravel(), data.ravel()))
     mask_multi = numpy.column_stack(
         (mask1.ravel(), mask2.ravel(), mask3.ravel()))
     masked_data = numpy.ma.array(data_multi, mask=mask_multi)
     lons = numpy.fromfunction(lambda y, x: 3 + x, (50, 10))
     lats = numpy.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, self.area_def, 50000,
                                    fill_value=None, segments=1)
     expected_fill_mask = numpy.fromfile(os.path.join(os.path.dirname(__file__),
                                                      'test_files',
                                                      'mask_test_full_fill_multi.dat'),
                                         sep=' ').reshape((800, 800, 3))
     fill_mask = res.mask
     cross_sum = res.sum()
     expected = 357140.0
     self.assertAlmostEqual(cross_sum, expected,
                            msg='Failed to resample masked data')
     self.assertTrue(numpy.array_equal(fill_mask, expected_fill_mask),
                     msg='Failed to create fill mask on masked data')
Пример #5
0
 def test_masked_multi_from_sample(self):
     data = numpy.ones((50, 10))
     data[:, 5:] = 2
     mask1 = numpy.ones((50, 10))
     mask1[:, :5] = 0
     mask2 = numpy.ones((50, 10))
     mask2[:, 5:] = 0
     mask3 = numpy.ones((50, 10))
     mask3[:25, :] = 0
     data_multi = numpy.column_stack(
         (data.ravel(), data.ravel(), data.ravel()))
     mask_multi = numpy.column_stack(
         (mask1.ravel(), mask2.ravel(), mask3.ravel()))
     masked_data = numpy.ma.array(data_multi, mask=mask_multi)
     lons = numpy.fromfunction(lambda y, x: 3 + x, (50, 10))
     lats = numpy.fromfunction(lambda y, x: 75 - y, (50, 10))
     swath_def = geometry.SwathDefinition(lons=lons, lats=lats)
     valid_input_index, valid_output_index, index_array, distance_array = \
         kd_tree.get_neighbour_info(swath_def,
                                    self.area_def,
                                    50000, neighbours=1, segments=1)
     res = kd_tree.get_sample_from_neighbour_info('nn', (800, 800),
                                                  masked_data,
                                                  valid_input_index,
                                                  valid_output_index, index_array,
                                                  fill_value=None)
     expected_fill_mask = numpy.fromfile(os.path.join(os.path.dirname(__file__),
                                                      'test_files',
                                                      'mask_test_full_fill_multi.dat'),
                                         sep=' ').reshape((800, 800, 3))
     fill_mask = res.mask
     self.assertTrue(numpy.array_equal(fill_mask, expected_fill_mask),
                     msg='Failed to create fill mask on masked data')
Пример #6
0
    def test_custom_multi(self):
        def wf1(dist):
            return 1 - dist / 100000.0

        def wf2(dist):
            return 1

        def wf3(dist):
            return numpy.cos(dist) ** 2

        data = numpy.fromfunction(lambda y, x: (y + x) * 10 ** -6, (5000, 100))
        lons = numpy.fromfunction(
            lambda y, x: 3 + (10.0 / 100) * x, (5000, 100))
        lats = numpy.fromfunction(
            lambda y, x: 75 - (50.0 / 5000) * y, (5000, 100))
        swath_def = geometry.SwathDefinition(lons=lons, lats=lats)
        data_multi = numpy.column_stack((data.ravel(), data.ravel(),
                                         data.ravel()))
        if (sys.version_info < (2, 6) or
                (sys.version_info >= (3, 0) and sys.version_info < (3, 4))):
            res = kd_tree.resample_custom(swath_def, data_multi,
                                          self.area_def, 50000, [wf1, wf2, wf3], segments=1)
        else:
            with warnings.catch_warnings(record=True) as w:
                res = kd_tree.resample_custom(swath_def, data_multi,
                                              self.area_def, 50000, [wf1, wf2, wf3], segments=1)
                self.assertFalse(
                    len(w) != 1, 'Failed to create neighbour radius warning')
                self.assertFalse(('Possible more' not in str(
                    w[0].message)), 'Failed to create correct neighbour radius warning')
        cross_sum = res.sum()
        expected = 1461.842980746
        self.assertAlmostEqual(cross_sum, expected,
                               msg='Swath multi channel custom resampling failed')
Пример #7
0
    def test_masked_gauss(self):
        data = numpy.ones((50, 10))
        data[:, 5:] = 2
        lons = numpy.fromfunction(lambda y, x: 3 + x, (50, 10))
        lats = numpy.fromfunction(lambda y, x: 75 - y, (50, 10))
        swath_def = geometry.SwathDefinition(lons=lons, lats=lats)
        mask = numpy.ones((50, 10))
        mask[:, :5] = 0
        masked_data = numpy.ma.array(data, mask=mask)
        res = kd_tree.resample_gauss(swath_def, masked_data.ravel(),
                                     self.area_def, 50000, 25000, segments=1)
        expected_mask = numpy.fromfile(os.path.join(os.path.dirname(__file__),
                                                    'test_files',
                                                    'mask_test_mask.dat'),
                                       sep=' ').reshape((800, 800))
        expected_data = numpy.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(numpy.array_equal(expected_mask, res.mask),
                        msg='Gauss resampling of swath mask failed')
        self.assertAlmostEqual(cross_sum, expected, places=3,
                               msg='Gauss resampling of swath masked data failed')
Пример #8
0
 def test_gauss_multi_mp_segments(self):
     data = numpy.fromfunction(lambda y, x: (y + x) * 10 ** -6, (5000, 100))
     lons = numpy.fromfunction(
         lambda y, x: 3 + (10.0 / 100) * x, (5000, 100))
     lats = numpy.fromfunction(
         lambda y, x: 75 - (50.0 / 5000) * y, (5000, 100))
     swath_def = geometry.SwathDefinition(lons=lons, lats=lats)
     data_multi = numpy.column_stack((data.ravel(), data.ravel(),
                                      data.ravel()))
     if (sys.version_info < (2, 6) or
             (sys.version_info >= (3, 0) and sys.version_info < (3, 4))):
         res = kd_tree.resample_gauss(swath_def, data_multi,
                                      self.area_def, 50000, [
                                          25000, 15000, 10000],
                                      nprocs=2, segments=1)
     else:
         with warnings.catch_warnings(record=True) 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, 'Failed to create neighbour radius warning')
             self.assertFalse(('Possible more' not in str(
                 w[0].message)), 'Failed to create correct neighbour radius warning')
     cross_sum = res.sum()
     expected = 1461.84313918
     self.assertAlmostEqual(cross_sum, expected,
                            msg='Swath multi channel segments resampling gauss failed')
Пример #9
0
    def test_custom(self):
        def wf(dist):
            return 1 - dist / 100000.0

        data = numpy.fromfunction(lambda y, x: (y + x) * 10 ** -5, (5000, 100))
        lons = numpy.fromfunction(
            lambda y, x: 3 + (10.0 / 100) * x, (5000, 100))
        lats = numpy.fromfunction(
            lambda y, x: 75 - (50.0 / 5000) * y, (5000, 100))
        swath_def = geometry.SwathDefinition(lons=lons, lats=lats)
        if (sys.version_info < (2, 6) or
                (sys.version_info >= (3, 0) and sys.version_info < (3, 4))):
            res = kd_tree.resample_custom(swath_def, data.ravel(),
                                          self.area_def, 50000, wf, segments=1)
        else:
            with warnings.catch_warnings(record=True) as w:
                res = kd_tree.resample_custom(swath_def, data.ravel(),
                                              self.area_def, 50000, wf, segments=1)
                self.assertFalse(
                    len(w) != 1, 'Failed to create neighbour radius warning')
                self.assertFalse(('Possible more' not in str(
                    w[0].message)), 'Failed to create correct neighbour radius warning')
        cross_sum = res.sum()
        expected = 4872.81050729
        self.assertAlmostEqual(cross_sum, expected,
                               msg='Swath custom resampling failed')
Пример #10
0
def create(synFile, datFile, outDir):

    if not os.path.exists(outDir):
        os.makedirs(outDir)

    syn = Seismogram(synFile)
    dat = Seismogram(datFile)

    # Read
    syn.readHeader()
    dat.readHeader()
    syn.readData()
    dat.readData()

    xDat, yDat = dat.reverse()
    xSyn, ySyn = syn.reverse()

    xDat = cosine_taper(xDat, 0.10)
    yDat = cosine_taper(yDat, 0.10)
    xSyn = cosine_taper(xSyn, 0.10)
    ySyn = cosine_taper(ySyn, 0.10)

    xRes = xSyn - xDat
    yRes = ySyn - yDat

    xRes = np.fromfunction(lambda i: xRes[i] if abs(xRes[i]).any() > 1e-100 else 0, 
                          (xRes.shape), dtype=int)
    yRes = np.fromfunction(lambda i: yRes[i] if abs(yRes[i]).any() > 1e-100 else 0, 
                          (yRes.shape), dtype=int)
    syn.writeAdjointSource(xRes, yRes, outDir)
Пример #11
0
 def ListPlanes_Cubic(self,latticeConstant,k):
     """
     According to the apparatus geometry, make a list of avaible
     reflection planes.
     """
     
     #wave length
     lamb = 2*pi/k
     maxtheta = arctan(self.L/sqrt(2)/self.D)/2
     
     #Bragg's law
     d = latticeConstant
     nmax = int(2*d*sin(maxtheta)/lamb)
     assert nmax>0
     N = nmax*2+1
     nsize = [N, N, N]
     h = fromfunction(lambda a,b,c: (a-nmax), nsize).astype(int)
     k = fromfunction(lambda a,b,c: (b-nmax), nsize).astype(int)
     l = fromfunction(lambda a,b,c: (c-nmax), nsize).astype(int)
     
     #Interplanar spacing calculated
     ds = d/sqrt(h**2+k**2+l**2)
     hkl = {} 
     thetas = arcsin(lamb/2/ds)
     
     #Check for allowed hkls and put in a list
     for i in range(N):
    def load_cifar(self,data_path):
        image_list = []
        label_list = []
        for i in xrange(5):
            fo = open(os.path.join(data_path,'data_batch_'+str(i+1)),'rb')
            dict = cPickle.load(fo)
            fo.close()
            image_list.append(dict['data'])
            label_list.append(dict['labels'])
        train_images = np.r_[image_list[0],image_list[1],image_list[2],image_list[3],image_list[4]]
        train_labels = np.r_[label_list[0],label_list[1],label_list[2],label_list[3],label_list[4]]
        fo = open(os.path.join(data_path,'test_batch'), 'rb')
        dict= cPickle.load(fo)
        fo.close()
        test_images = dict['data']
        test_labels = dict['labels']

        test_images = test_images / 255.0
        train_images = train_images / 255.0

        # resize images to 2D
        dsize = 32
        train_images = train_images.reshape(len(train_images),3,dsize,dsize)
        test_images = test_images.reshape(len(test_images),3,dsize,dsize)
        train_labels = np.array(train_labels)
        test_labels = np.array(test_labels)
        
        self.test_images = test_images
        self.test_labels = np.fromfunction(lambda i,j:j==test_labels[i],(len(test_labels),max(test_labels)+1),dtype=int)+0
        self.train_images = train_images
        self.train_labels = np.fromfunction(lambda i,j:j==train_labels[i],(len(train_labels),max(train_labels)+1),dtype=int)+0
Пример #13
0
 def __init__(self, angle, col, dangle=5, parent=None):
     super().__init__(parent)
     color = QColor(0, 0, 0) if col else QColor(128, 128, 128)
     angle_d = np.rad2deg(angle)
     angle_2 = 90 - angle_d - dangle
     angle_1 = 270 - angle_d + dangle
     dangle = np.deg2rad(dangle)
     arrow1 = pg.ArrowItem(
         parent=self, angle=angle_1, brush=color, pen=pg.mkPen(color)
     )
     arrow1.setPos(np.cos(angle - dangle), np.sin(angle - dangle))
     arrow2 = pg.ArrowItem(
         parent=self, angle=angle_2, brush=color, pen=pg.mkPen(color)
     )
     arrow2.setPos(np.cos(angle + dangle), np.sin(angle + dangle))
     arc_x = np.fromfunction(
         lambda i: np.cos((angle - dangle) + (2 * dangle) * i / 120.),
         (121,), dtype=int
     )
     arc_y = np.fromfunction(
         lambda i: np.sin((angle - dangle) + (2 * dangle) * i / 120.),
         (121,), dtype=int
     )
     pg.PlotCurveItem(
         parent=self, x=arc_x, y=arc_y, pen=pg.mkPen(color), antialias=False
     )
Пример #14
0
def multi_2_func():
    """
    使用函数创建2维数组
    :return: 
    """
    print np.fromfunction(lambda x, y: (x + 1) * y, (10, 5))
    split_line()
Пример #15
0
 def test_gauss_multi_uncert(self):
     data = numpy.fromfunction(lambda y, x: (y + x)*10**-6, (5000, 100))        
     lons = numpy.fromfunction(lambda y, x: 3 + (10.0/100)*x, (5000, 100))
     lats = numpy.fromfunction(lambda y, x: 75 - (50.0/5000)*y, (5000, 100))
     swath_def = geometry.SwathDefinition(lons=lons, lats=lats)
     data_multi = numpy.column_stack((data.ravel(), data.ravel(),\
                                      data.ravel()))
     if sys.version_info < (2, 6):
         res, stddev, counts = kd_tree.resample_gauss(swath_def, data_multi,\
                                             self.area_def, 50000, [25000, 15000, 10000], 
                                             segments=1, with_uncert=True)
     else:
         with warnings.catch_warnings(record=True) as w:
             res, stddev, counts = kd_tree.resample_gauss(swath_def, data_multi,\
                                                 self.area_def, 50000, [25000, 15000, 10000], 
                                                 segments=1, with_uncert=True)
             self.failIf(len(w) != 1, 'Failed to create neighbour radius warning')
             self.failIf(('Possible more' not in str(w[0].message)), 'Failed to create correct neighbour radius warning') 
     cross_sum = res.sum()
     cross_sum_stddev = stddev.sum()
     cross_sum_counts = counts.sum()
     expected = 1461.84313918
     expected_stddev = 0.446204424799
     expected_counts = 4934802.0
     self.assertTrue(res.shape == stddev.shape and stddev.shape == counts.shape and counts.shape == (800, 800, 3))
     self.assertAlmostEqual(cross_sum, expected,
                             msg='Swath multi channel resampling gauss failed on data')
     self.assertAlmostEqual(cross_sum_stddev, expected_stddev,
                             msg='Swath multi channel resampling gauss failed on stddev')
     self.assertAlmostEqual(cross_sum_counts, expected_counts,
                             msg='Swath multi channel resampling gauss failed on counts')
Пример #16
0
def test_false_color():
    N = 100
    M = 100

    part = np.zeros((N,M))

    part[:N/2, :M/2] = 0
    part[N/2:, :M/2] = 1
    part[:N/2, M/2:] = 2
    part[N/2:, M/2:] = 3

    img = np.zeros((N,M,3))

    img[..., 0] = np.fromfunction(lambda i, j: i+j+0, (N,M))
    img[..., 1] = np.fromfunction(lambda i, j: i+j+1, (N,M))
    img[..., 2] = np.fromfunction(lambda i, j: i+j+2, (N,M))

    mean_color = partition_mean_color(img, part)

    colors = np.zeros((3,4))
    colors[:, 0] = np.array([49, 50, 51])
    colors[:, 1] = np.array([99, 100, 101])
    colors[:, 2] = np.array([99, 100, 101])
    colors[:, 3] = np.array([149, 150, 151])

    for i in range(4):
        coords = np.where(part == i)
        for ch in range(3):
            assert_equal(len(np.unique(mean_color[coords[0], coords[1], ch])), 1)
            assert_equal(mean_color[coords[0][0], coords[1][0], ch], colors[ch, i])
Пример #17
0
def __set_pm__(L, window, taps, fwidth):
    global pm
    if pm['L'] == L and pm['taps'] == taps and \
       pm['fwidth'] == fwidth:
        if type(window) == str and pm['window_name'] == window: return
        elif window is pm['window']: return
    else:
        pm['L'] = L
        pm['taps'] = taps
        pm['fwidth'] = fwidth
        def sinx_x(x):
            t = n.pi * taps * fwidth * (x/float(L) - .5)
            v = n.where(t != 0, t, 1)
            return n.where(t != 0, n.sin(v) / v, 1)
        pm['sinx_x'] = n.fromfunction(sinx_x, (L,))
    if type(window) == str: 
        wf = {}
        wf['blackman'] = lambda x: .42-.5*n.cos(2*n.pi*x/(L-1))+.08*n.cos(4*n.pi*x/(L-1))
        wf['blackman-harris'] = lambda x: .35875 - .48829*n.cos(2*n.pi*x/(L-1)) + .14128*n.cos(4*n.pi*x/(L-1)) - .01168*n.cos(6*n.pi*x/(L-1))
        wf['gaussian0.4'] = lambda x: n.exp(-0.5 * ((x - (L-1)/2)/(0.4 * (L-1)/2))**2)
        wf['kaiser2'] = lambda x: i0(n.pi * 2 * n.sqrt(1-(2*x/(L-1) - 1)**2)) / i0(n.pi * 2)
        wf['kaiser3'] = lambda x: i0(n.pi * 3 * n.sqrt(1-(2*x/(L-1) - 1)**2)) / i0(n.pi * 3)
        wf['hamming'] = lambda x: .54 - .46 * n.cos(2*n.pi*x/(L-1))
        wf['hanning'] = lambda x: .5 - .5 * n.cos(2*n.pi*x/(L-1))
        wf['parzen'] = lambda x: 1 - n.abs(L/2. - x) / (L/2.)
        wf['none'] = lambda x: 1
        pm['window'] = n.fromfunction(wf[window], (L,))
        pm['window_name'] = window
    else: 
        pm['window'] = window
        pm['window_name'] = None
    pm['window_sinx_x'] = pm['window'] * pm['sinx_x']
Пример #18
0
def generate_nearest_neighbour_linesample_arrays(source_area_def, target_area_def,
                                                 radius_of_influence, nprocs=1):
    """Generate linesample arrays for nearest neighbour grid resampling

    Parameters
    -----------
    source_area_def : object 
        Source area definition as AreaDefinition object
    target_area_def : object 
        Target area definition as AreaDefinition object
    radius_of_influence : float 
        Cut off distance in meters
    nprocs : int, optional 
        Number of processor cores to be used

    Returns
    -------
    (row_indices, col_indices) : tuple of numpy arrays
    """

    if not (isinstance(source_area_def, pr.geometry.AreaDefinition) and
            isinstance(target_area_def, pr.geometry.AreaDefinition)):
        raise TypeError('source_area_def and target_area_def must be of type '
                        'geometry.AreaDefinition')

    valid_input_index, valid_output_index, index_array, distance_array = \
        pr.kd_tree.get_neighbour_info(source_area_def,
                                      target_area_def,
                                      radius_of_influence,
                                      neighbours=1,
                                      nprocs=nprocs)
    # Enumerate rows and cols
    rows = np.fromfunction(lambda i, j: i, source_area_def.shape,
                           dtype=np.int32).ravel()
    cols = np.fromfunction(lambda i, j: j, source_area_def.shape,
                           dtype=np.int32).ravel()

    # Reduce to match resampling data set
    rows_valid = rows[valid_input_index]
    cols_valid = cols[valid_input_index]

    # Get result using array indexing
    number_of_valid_points = valid_input_index.sum()
    index_mask = (index_array == number_of_valid_points)
    index_array[index_mask] = 0
    row_sample = rows_valid[index_array]
    col_sample = cols_valid[index_array]
    row_sample[index_mask] = -1
    col_sample[index_mask] = -1

    # Reshape to correct shape
    row_indices = row_sample.reshape(target_area_def.shape)
    col_indices = col_sample.reshape(target_area_def.shape)

    row_indices = _downcast_index_array(row_indices,
                                        source_area_def.shape[0])
    col_indices = _downcast_index_array(col_indices,
                                        source_area_def.shape[1])

    return row_indices, col_indices
def register_reproject_with_errors(inputImages, outputImages, intErrorImages, outputErrorImages, refImage, processDir, headerName="header.hdr"):
	cmds.mGetHdr(refImage,headerName)
	mw.reproject(inputImages,outputImages,header=headerName,north_aligned=True,system='EQUJ',exact_size=True,common=True,silent_cleanup=True)
	for i in range(len(inputImages)):
		idenList=inputImages[i].split('/')[2].split('-')
		run=int(idenList[0])
		camcol=int(idenList[1])
		field=int(idenList[2])
		band=idenList[3].split('.')[0]
		fitsFile=fits.open(inputImages[i])
		fitsImage=fitsFile[0].data
		errorData=fitsFile[1].data
		errorImg=[]
		for j in range(1489):
			errorImg.append(errorData)
		errorImage=np.asarray(errorImg)
		skyImageInit=fitsFile[2].data[0][0]
		xs=np.fromfunction(lambda k: k, (skyImageInit.shape[0],), dtype=int)
		ys=np.fromfunction(lambda k: k, (skyImageInit.shape[1],), dtype=int)
		interpolator=interp2d(xs, ys, skyImageInit, kind='cubic')
		for j in range(errorImage.shape[1]):
			for k in range(errorImage.shape[0]):
				skyImageValue=interpolator.__call__(j*skyImageInit.shape[0]/errorImage.shape[0],k*skyImageInit.shape[1]/errorImage.shape[1])
				errorImage[k][j]=return_sdss_pixelError(band, camcol, run, fitsImage[k][j], skyImageValue, errorImg[k][j])
		fitsFile[0].data=errorImage
		fitsFile.writeto(intErrorImages[i])
	mw.reproject(intErrorImages,outputErrorImages,header=headerName,north_aligned=True,system='EQUJ',exact_size=True,common=True,silent_cleanup=True)
Пример #20
0
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
Пример #21
0
 def test_from_latlon(self):
     data = np.fromfunction(lambda y, x: y * x, (800, 800))
     lons = np.fromfunction(lambda y, x: x, (10, 10))
     lats = np.fromfunction(lambda y, x: 50 - (5.0 / 10) * y, (10, 10))
     #source_def = grid.AreaDefinition.get_from_area_def(self.area_def)
     source_def = self.area_def
     res = grid.get_image_from_lonlats(lons, lats, source_def, data)
     expected = np.array([[129276.,  141032.,  153370.,  165804.,  178334.,  190575.,
                           202864.,  214768.,  226176.,  238080.],
                          [133056.,  146016.,  158808.,  171696.,  184320.,  196992.,
                           209712.,  222480.,  234840.,  247715.],
                          [137026.,  150150.,  163370.,  177215.,  190629.,  203756.,
                           217464.,  230256.,  243048.,  256373.],
                          [140660.,  154496.,  168714.,  182484.,  196542.,  210650.,
                           224257.,  238464.,  251712.,  265512.],
                          [144480.,  158484.,  173148.,  187912.,  202776.,  217358.,
                           231990.,  246240.,  259920.,  274170.],
                          [147968.,  163261.,  178398.,  193635.,  208616.,  223647.,
                           238728.,  253859.,  268584.,  283898.],
                          [151638.,  167121.,  182704.,  198990.,  214775.,  230280.,
                           246442.,  261617.,  276792.,  292574.],
                          [154980.,  171186.,  187860.,  204016.,  220542.,  237120.,
                           253125.,  269806.,  285456.,  301732.],
                          [158500.,  175536.,  192038.,  209280.,  226626.,  243697.,
                           260820.,  277564.,  293664.,  310408.],
                          [161696.,  179470.,  197100.,  214834.,  232320.,  250236.,
                           267448.,  285090.,  302328.,  320229.]])
     self.assertTrue(
         np.array_equal(res, expected), 'Sampling from lat lon failed')
Пример #22
0
	def kerph2im(self,theta=0):
		"""
		adds up the sine transform for uv phases & then multiplies Kmat,
		the transfer matrix from uv phases to kernel phases.
	
		Returns image to kernel phase transfer matrix.
		"""
		# To make the image pixel centered:
		self.off = np.array([self.fov/2.-0.5, self.fov/2.-0.5])
		# empty sine transform matrix:
		self.ph2im = np.zeros((len(self.uv), self.fov,self.fov))
		self.sym2im = np.zeros((len(self.uv), self.fov,self.fov))
		rotMatrix = np.array([[np.cos(theta), -np.sin(theta)], 
						 [np.sin(theta),  np.cos(theta)]])
		for q,one_uv in enumerate(self.uv):
			self.rcoord = np.dot(rotMatrix,one_uv)
			self.ph2im[q,:,:] = self.red[q]*np.fromfunction(self.ffs, (self.fov, self.fov))
			self.sym2im[q,:,:] = self.red[q]*np.fromfunction(self.ffc, (self.fov,self.fov))
		# flatten for matrix multiplication
		#self.ph2im = self.ph2im.reshape(len(self.uv), self.fov*self.fov)
		# Matrix multiply Kmat & flattened sin transform matrix
		self.kerim = np.dot(self.Kmat, self.ph2im.reshape(len(self.uv), self.fov*self.fov))
		# Reshape back to image dimensions
		self.kerim = self.kerim.reshape(len(self.Kmat), self.fov,self.fov)
		return self.kerim, self.sym2im
Пример #23
0
def vertical_flip_map(rows, cols):
    map_x = numpy.fromfunction(
        lambda r, c: c, (rows, cols), dtype=numpy.float32)
    map_y = numpy.fromfunction(
        lambda r, c: rows - 1 - r, (rows, cols), dtype=numpy.float32)

    return map_x, map_y
Пример #24
0
    def test_custom_multi(self):
        def wf1(dist):
            return 1 - dist / 100000.0

        def wf2(dist):
            return 1

        def wf3(dist):
            return np.cos(dist) ** 2

        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_custom(swath_def, data_multi,
                                          self.area_def, 50000, [wf1, wf2, wf3], segments=1)
            self.assertFalse(len(w) != 1)
            self.assertFalse('Possible more' not in str(w[0].message))
        cross_sum = res.sum()
        expected = 1461.8428378742638
        self.assertAlmostEqual(cross_sum, expected)
Пример #25
0
def planeRegression(imgarray):
	"""
	performs a two-dimensional linear regression and subtracts it from an image
	essentially a fast high pass filter
	"""
	size = (imgarray.shape)[0]
	count = float((imgarray.shape)[0]*(imgarray.shape)[1])
	def retx(y,x):
		return x
	def rety(y,x):
		return y
	xarray = numpy.fromfunction(retx, imgarray.shape)
	yarray = numpy.fromfunction(rety, imgarray.shape)
	xsum = float(xarray.sum())
	xsumsq = float((xarray*xarray).sum())
	ysum = xsum
	ysumsq = xsumsq
	xysum = float((xarray*yarray).sum())
	xzsum = float((xarray*imgarray).sum())
	yzsum = float((yarray*imgarray).sum())
	zsum = imgarray.sum()
	zsumsq = (imgarray*imgarray).sum()
	xarray = xarray.astype(numpy.float32)
	yarray = yarray.astype(numpy.float32)
	leftmat = numpy.array( [[xsumsq, xysum, xsum], [xysum, ysumsq, ysum], [xsum, ysum, count]] )
	rightmat = numpy.array( [xzsum, yzsum, zsum] )
	resvec = linalg.solve(leftmat,rightmat)
	#print " ... plane_regress: x-slope:",round(resvec[0]*size,5),\
	#	", y-slope:",round(resvec[1]*size,5),", xy-intercept:",round(resvec[2],5)
	newarray = imgarray - xarray*resvec[0] - yarray*resvec[1] - resvec[2]
	#del imgarray,xarray,yarray,resvec
	return newarray
Пример #26
0
def test_2():
    Temp1, Temp2 = Temp, Temp/temp_ratio
    double_temp = np.sqrt(Temp1*Temp2)
    ss_temp = np.sqrt(Temp1) + np.sqrt(Temp2)
    delta_temp = np.abs(Temp2 - Temp1)

    Rho1, Rho2 = 2*Rho*np.sqrt(Temp2)/ss_temp, 2*Rho*np.sqrt(Temp1)/ss_temp
    f = Rho1/(np.pi*Temp1)**1.5 * np.fromfunction(lambda i,j,k: np.exp(-sqr_xi(i,j,k,Speed)/(Temp1))*dxi(i,j,k), dimension)
    negative = np.fromfunction(lambda i,j,k: j<N_y, dimension)
    f[negative] = Rho2/(np.pi*Temp2)**1.5 * np.fromfunction(lambda i,j,k: np.exp(-sqr_xi(i,j,k,-Speed)/(Temp2))*dxi(i,j,k), dimension)[negative]

    rho, temp, speed, qflow, tau = calc_macro(f)

    Rho_ = Rho
    Temp_ = double_temp * (1 + 8./3*np.dot(Speed,Speed)/ss_temp**2)
    Speed_ = -Speed * delta_temp / ss_temp**2
    Qflow_ = [ 0, 2*Rho*double_temp*delta_temp/ss_temp/np.sqrt(np.pi) * (1 + 2*np.dot(Speed,Speed)/ss_temp**2), 0 ]
    Tau_ = [ 0, 0, 4*Rho*Speed[0]*double_temp/ss_temp/np.sqrt(np.pi) ]

    #splot(f)
    #splot(f*c[0]*c[1])

    print "\n-- Test #2: free molecular flows - sum of 2 half-Maxwellians"
    print "rho =", err(Rho_, rho)
    print "temp =", err(Temp_, temp)
    print "speed =", err(Speed_, speed)
    print "qflow =", err(Qflow_, qflow/rho)
    print "tau =", err(Tau_, tau/rho)
Пример #27
0
    def test_gauss_multi_uncert(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:
            # The assertion below checks if there is only one warning raised
            # and whether it contains a specific message from pyresample
            # On python 2.7.9+ the resample_gauss method raises multiple deprecation warnings
            # that cause to fail, so we ignore the unrelated warnings.
            res, stddev, counts = kd_tree.resample_gauss(swath_def, data_multi,
                                                         self.area_def, 50000, [
                                                             25000, 15000, 10000],
                                                         segments=1, with_uncert=True)
            self.assertTrue(len(w) >= 1)
            self.assertTrue(
                any(['Possible more' in str(x.message) for x in w]))
        cross_sum = res.sum()
        cross_sum_counts = counts.sum()
        expected = 1461.8429990248171
        expected_stddev = [0.44621800779801657, 0.44363137712896705,
                           0.43861019464274459]
        expected_counts = 4934802.0
        self.assertTrue(res.shape == stddev.shape and stddev.shape ==
                        counts.shape and counts.shape == (800, 800, 3))
        self.assertAlmostEqual(cross_sum, expected)

        for i, e_stddev in enumerate(expected_stddev):
            cross_sum_stddev = stddev[:, :, i].sum()
            self.assertAlmostEqual(cross_sum_stddev, e_stddev)
        self.assertAlmostEqual(cross_sum_counts, expected_counts)
Пример #28
0
def horizontal_flip_map(rows, cols):
    map_x = numpy.fromfunction(
        lambda r, c: cols - 1 - c, (rows, cols), dtype=numpy.float32)
    map_y = numpy.fromfunction(
        lambda r, c: r, (rows, cols), dtype=numpy.float32)

    return map_x, map_y
Пример #29
0
def __set_pm__(L, window, taps, fwidth):
    global pm
    if pm['L'] == L and pm['taps'] == taps and pm['fwidth'] == fwidth:
        if type(window) == str and pm['window_name'] == window: return
        elif window is pm['window']: return
    else:
        pm['L'] = L
        pm['taps'] = taps
        pm['fwidth'] = fwidth
        def sinx_x(x):
            t = n.pi * taps * fwidth * (x/float(L) - .5)
            v = n.where(t != 0, t, 1)
            return n.where(t != 0, n.sin(v) / v, 1)
        pm['sinx_x'] = n.fromfunction(sinx_x, (L,))
    if type(window) == str:
        wf = {}
        wf['hamming'] = lambda x: .54 + .46 * cos(2*n.pi*x/L - n.pi)
        wf['hanning'] = lambda x: .5 + .5 * n.cos(2*n.pi*x/(L+1) - n.pi)
        wf['none'] = lambda x: 1
        pm['window'] = n.fromfunction(wf[window], (L,))
        pm['window_name'] = window
    else:
        pm['window'] = window
        pm['window_name'] = None
    pm['window_sinx_x'] = pm['window'] * pm['sinx_x']
Пример #30
0
def make_gauss_init(pkinit, boxsize=100.0, ngrid=100, seed=314159, exactpk=True, smw=2.0):
    
    #mathematical artifact of Fourier transform, possibly incorrect? (ngrid+1)/2)
    thirdim = ngrid/2+1
    
    
    #inverse(?) of the cell size (in 2pi)
    kmin = 2*np.pi/np.float(boxsize)
    
    #shape of k grid
    sk = (ngrid,ngrid,thirdim)
    
    #No clue. it represents the grid, but the method / definition is non-trivial.
    a = np.fromfunction(lambda x,y,z:x, sk).astype(np.float)
    a[np.where(a > ngrid/2)] -= ngrid
    b=np.transpose(a, (1, 0, 2))
    c = np.fromfunction(lambda x,y,z:z, sk).astype(np.float)
    c[np.where(c > ngrid/2)] -= ngrid
    
    #From this, a/b/c = x/y/z but why are 3x10x10x6 arrays necessary?
    kgrid = kmin*np.sqrt(a**2+b**2+c**2).astype(np.float)
    a = 0
    b = 0
    c = 0
    #K-space is a bitch.
    
    
    #self-explanatory
    rs = np.random.RandomState(seed)
    
    #What are these complex numbers representing?
    if (exactpk):
        dk = np.exp(2j*np.pi*rs.rand(ngrid*ngrid*(thirdim))).reshape(sk).astype(np.complex64)
    else:
        dk = np.empty(sk,dtype=np.complex64)
        dk.real = rs.normal(size=ngrid*ngrid*(thirdim)).reshape(sk).astype(np.float32)
        dk.imag = rs.normal(size=ngrid*ngrid*(thirdim)).reshape(sk).astype(np.float32)
        dk /= np.sqrt(2.0)
    #This section provides a unit length, random(?) phase complex number associated with
    #each point on the grid.
    
    #Gaussian filter
    filt=np.exp(-kgrid**2*smw**2)
    
    #interpolate power spectrum to approximate at non-keyed values.
    pkinterp=ip.interp1d(pkinit[:,0], pkinit[:,1])
    
    #Pk undefined at 0, so this provides an explicit exception.
    if (kgrid[0,0,0]==0):
        dk[0,0,0]=0
        wn0=np.where(kgrid!=0)
        
        #The mathematics? 
        dk[wn0] *= np.sqrt(filt[wn0]*pkinterp(kgrid[wn0]))*ngrid**3/boxsize**1.5   
    #Why is this if statement necessary? We know the P(k) will be undefined.
    else:
        dk *= np.sqrt(filt*pkinterp(kgrid.flatten())).reshape(sk)*ngrid**3/boxsize**1.5
        
    dk=nyquist(dk)
    return dk
Пример #31
0
import numpy as np
import pyresample as pr

print(pr.version.get_versions())

area_def = pr.geometry.AreaDefinition(
    'areaD', 'Europe (3km, HRV, VTC)', 'areaD', {
        'a': '6378144.0',
        'b': '6356759.0',
        'lat_0': '50.00',
        'lat_ts': '50.00',
        'lon_0': '8.00',
        'proj': 'stere'
    }, 800, 800, [-1370912.72, -909968.64, 1029087.28, 1490031.36])

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))
swath_def = pr.geometry.SwathDefinition(lons=lons, lats=lats)

mapcenter = [-111.4223, 34.7443]
clon = mapcenter[0]
clat = mapcenter[1]

latMin = clat - 5
latMax = clat + 5

lonMin = clon - 5
lonMax = clon + 5
gridRes = 1
Пример #32
0
def fromfunction(args, dimensions):
    return np.fromfunction(args, dimensions, dtype=int)
Пример #33
0
 def planeGen():
     for p in range(sizeZ * sizeC * sizeT):
         yield fromfunction(f, (sizeY, sizeX), dtype=int16)
Пример #34
0
LY = 2.3
DX = LX / NX
DY = LY / NY
X0 = 1.0
Y0 = 2.0

amplitude = 2.0


def nonGroundedWall(Yindex):
    return amplitude * np.sin(np.pi * Yindex / NY)


# Boundary conditions
V0x = dirBC(np.zeros((NY + 1)))
VNx = dirBC(np.fromfunction(nonGroundedWall, (NY + 1, )))

V0y = dirBC(np.zeros((NX + 1)))
VNy = dirBC(np.zeros((NX + 1)))

start = time.time()

potential_1 = laplace2D(NX,
                        DX,
                        V0x,
                        VNx,
                        NY,
                        DY,
                        V0y,
                        VNy,
                        "gaussSeidel",
Пример #35
0
def plot_head_outline(scale=1,
                      shift=(0, 0),
                      color='k',
                      linewidth='3',
                      ax=P,
                      view='top',
                      **kwargs):
    """Plots a simple outline of a head viewed from the top.

    The plot contains schematic representations of the nose and ears. The
    size of the head is basically a unit circle for nose and ears attached
    to it.

    :Parameters:
      scale: float
        Factor to scale the size of the head.
      shift: 2-tuple of floats
        Shift the center of the head circle by these values.
      color: matplotlib color spec
        The color the outline should be plotted in.
      linewidth: int
        Linewidth of the head outline.
      ax: mpl axes
        axes to plot to. Standard is pylab.
      view: one of 'top' and 'rear'
        Defines from where the head is viewed.
      kwargs:
        All additional arguments are passed to `P.plot()`.

    :Returns:
      Matplotlib lines2D object
        can be used to tweak the look of the head outline.
    """

    rmax = 0.5
    # factor used all the time
    fac = 2 * N.pi * 0.01

    if view == 'top':
        # Koordinates for the ears
        EarX1 = -1 * N.array([
            .497, .510, .518, .5299, .5419, .54, .547, .532, .510,
            rmax * N.cos(fac * (54 + 42))
        ])
        EarY1 = N.array([
            .0655, .0775, .0783, .0746, .0555, -.0055, -.0932, -.1313, -.1384,
            rmax * N.sin(fac * (54 + 42))
        ])
        EarX2 = N.array([
            rmax * N.cos(fac * (54 + 42)), .510, .532, .547, .54, .5419, .5299,
            .518, .510, .497
        ])
        EarY2 = N.array([
            rmax * N.sin(fac * (54 + 42)), -.1384, -.1313, -.0932, -.0055,
            .0555, .0746, .0783, .0775, .0655
        ])

        # Coordinates for the Head
        HeadX1 = N.fromfunction(lambda x: rmax * N.cos(fac * (x + 2)), (21, ))
        HeadY1 = N.fromfunction(lambda y: rmax * N.sin(fac * (y + 2)), (21, ))
        HeadX2 = N.fromfunction(lambda x: rmax * N.cos(fac * (x + 28)), (21, ))
        HeadY2 = N.fromfunction(lambda y: rmax * N.sin(fac * (y + 28)), (21, ))
        HeadX3 = N.fromfunction(lambda x: rmax * N.cos(fac * (x + 54)), (43, ))
        HeadY3 = N.fromfunction(lambda y: rmax * N.sin(fac * (y + 54)), (43, ))

        # Coordinates for the Nose
        NoseX = N.array([.18 * rmax, 0, -.18 * rmax])
        NoseY = N.array([rmax - 0.004, rmax * 1.15, rmax - 0.004])

        # Combine to one
        X = N.concatenate((EarX2, HeadX1, NoseX, HeadX2, EarX1, HeadX3))
        Y = N.concatenate((EarY2, HeadY1, NoseY, HeadY2, EarY1, HeadY3))

        X *= 2 * scale
        Y *= 2 * scale
        X += shift[0]
        Y += shift[1]
    elif view == 'rear':
        # Koordinates for the ears
        EarX1 = -1 * N.array([
            .497, .510, .518, .5299, .5419, .54, .537, .525, .510,
            rmax * N.cos(fac * (54 + 42))
        ])
        EarY1 = N.array([
            .0655, .0775, .0783, .0746, .0555, -.0055, -.0932, -.1713, -.1784,
            rmax * N.sin(fac * (54 + 42))
        ])
        EarX2 = N.array([
            rmax * N.cos(fac * (54 + 42)), .510, .525, .537, .54, .5419, .5299,
            .518, .510, .497
        ])
        EarY2 = N.array([
            rmax * N.sin(fac * (54 + 42)), -.1784, -.1713, -.0932, -.0055,
            .0555, .0746, .0783, .0775, .0655
        ])

        # Coordinates for the Head
        HeadX1 = N.fromfunction(lambda x: rmax * N.cos(fac * (x + 2)), (23, ))
        HeadY1 = N.fromfunction(lambda y: rmax * N.sin(fac * (y + 2)), (23, ))
        HeadX2 = N.fromfunction(lambda x: rmax * N.cos(fac * (x + 26)), (23, ))
        HeadY2 = N.fromfunction(lambda y: rmax * N.sin(fac * (y + 26)), (23, ))
        HeadX3 = N.fromfunction(lambda x: rmax * N.cos(fac * (x + 54)), (17, ))
        HeadY3 = N.fromfunction(lambda y: rmax * N.sin(fac * (y + 54)), (17, ))
        HeadX4 = N.fromfunction(lambda x: rmax * N.cos(fac * (x + 80)), (17, ))
        HeadY4 = N.fromfunction(lambda y: rmax * N.sin(fac * (y + 80)), (17, ))

        # Coordinates for the Neck
        NeckX = N.array([rmax * N.cos(fac * 70), rmax * N.cos(fac * 80)])
        NeckY = N.array([rmax * -1.1, rmax * -1.1])

        # Combine to one
        X = N.concatenate(
            (EarX2, HeadX1, HeadX2, EarX1, HeadX3, NeckX, HeadX4))
        Y = N.concatenate(
            (EarY2, HeadY1, HeadY2, EarY1, HeadY3, NeckY, HeadY4))

        X *= 2 * scale
        Y *= 2 * scale
        X += shift[0]
        Y += shift[1]
    else:
        raise ValueError("view must be one of 'top' and 'rear'")

    return ax.plot(X, Y, color=color, linewidth=linewidth)
def mascara_nubes(img_bgr, centroide=None):
    '''
    Función que genera la máscara de nubes de una imágen según el método propio.

    Parameters
    ----------
    img_bgr :
        Imagen original.
    centroide : list, (Y,X)
        Posición del sol. 
        En el caso de que se indique, se eliminará
        el contorno que encierre al centroide,
        según el algoritmo propuesto.

    Returns
    -------
    mask_cloud
    '''

    # Separación de los canales de la imagen:
    Blue = img_bgr[:, :, 0]
    Green = img_bgr[:, :, 1]
    Red = img_bgr[:, :, 2]

    # Método propio en base a las máscaras de los canales
    mask_green = cv2.inRange(Green, 0, 140)
    mask_red = cv2.inRange(Red, 0, 70)
    mask_R_B = cv2.inRange(Red - Blue, 90, 255)
    mask_B_G = cv2.inRange(Blue - Green, 30, 255)

    # Creación de las máscaras de cielo despejado
    mask_sky = cv2.bitwise_or(mask_R_B, mask_green, mask=mask_B_G)
    mask_sky = cv2.bitwise_or(mask_sky, mask_red, mask=mask_B_G)
    mask_sky = cv2.bitwise_and(mask_sky, mask_sky, mask=cielo)

    # Se crea la máscara de las nubes negando la máscara del cielo despejado
    mask_cloud = cv2.bitwise_not(mask_sky)
    mask_cloud = cv2.bitwise_and(mask_cloud, mask_cloud, mask=cielo)

    # Si se indica centroide, se elimina la falsa nube que se puede detectar en casos en los que el sol sature la cámara
    if centroide != None:
        # Se obtiene los contornos de las nubes
        mask_cloud = cv2.medianBlur(mask_cloud.astype(np.uint8), 5)
        cnt_nubes, hierarchy = cv2.findContours(mask_cloud, cv2.RETR_EXTERNAL,
                                                cv2.CHAIN_APPROX_NONE)

        # Se obtiene el contorno de nube que encierra al centroide:
        for i in cnt_nubes:
            if cv2.pointPolygonTest(i, centroide, False) >= 0:
                cnt_sol = i

        # Se obtiene la máscara en la que se encuentra la "sombra" del sol, con el fin de quitar esta zona de la máscara de nubes
        # f_mask_sol = lambda pos: 255 if (cv2.pointPolygonTest(cnt_sol, pos, False) >= 0) else 0
        # mask_sol = [[f_mask_sol((y,x)) for y in range(Y)] for x in range(X)]
        # mask_sol = np.array(mask_sol, np.uint8)
        f_mask_sol = lambda x, y: 255 if (cv2.pointPolygonTest(
            cnt_sol, (y, x), False) >= 0) else 0
        mask_sol = np.fromfunction(np.vectorize(f_mask_sol), (X, Y),
                                   dtype=int).astype(np.uint8)

        mask_no_sol = cv2.bitwise_not(mask_sol)
        mask_cloud = cv2.bitwise_and(mask_cloud, mask_no_sol)

    return mask_cloud
Пример #37
0
print("Max",a.max())
b=np.arange(12).reshape(3,4)
print("Somatorio do primeiro eixo",b.sum(axis=0))
print("min do segundo eixo",b.min(axis=1))
print("Somatorio acumulado do primeiro eixo",b.cumsum(axis=0))#integração
a=np.arange(10)**3
print(a[2])
print(a[2:5])
a[:6:2]=-1000#susbtitui
print(a)
print(a[::-1])#inverte a posição
for i in a:
    print(i**(1/3))
def f(x,y):
    return 10*x+y
b=np.fromfunction(f,(5,4),dtype=int)
print(b)
print(b[2,3])
print(b[0:5,1])
c=np.array([[[0, 1, 2],[10, 12, 13]],[[100, 101, 102],[110, 112, 113]]])
print(c)
print(c[-1])
print(c[1,...])#pegar tudo na linha 1
#Pegar toda uma linha
for row in c:
    print(row)
for element in c.flat:
    print(element)
a=np.random.random((2,3))
print(a.T)#transposta
print(a.resize(3,2))#reshape que n retorna nada
Пример #38
0
reveal_type(np.full_like(A, i8))  # E: numpy.ndarray
reveal_type(np.full_like(C, i8))  # E: numpy.ndarray
reveal_type(np.full_like(B, i8))  # E: SubClass
reveal_type(np.full_like(B, i8, dtype=np.int64))  # E: numpy.ndarray

reveal_type(np.ones(1))  # E: numpy.ndarray
reveal_type(np.ones([1, 1, 1]))  # E: numpy.ndarray

reveal_type(np.full(1, i8))  # E: numpy.ndarray
reveal_type(np.full([1, 1, 1], i8))  # E: numpy.ndarray

reveal_type(np.indices([1, 2, 3]))  # E: numpy.ndarray
reveal_type(np.indices([1, 2, 3], sparse=True))  # E: tuple[numpy.ndarray]

reveal_type(np.fromfunction(func, (3, 5)))  # E: SubClass

reveal_type(np.identity(10))  # E: numpy.ndarray

reveal_type(np.atleast_1d(A))  # E: numpy.ndarray
reveal_type(np.atleast_1d(C))  # E: numpy.ndarray
reveal_type(np.atleast_1d(A, A))  # E: list[numpy.ndarray]
reveal_type(np.atleast_1d(A, C))  # E: list[numpy.ndarray]
reveal_type(np.atleast_1d(C, C))  # E: list[numpy.ndarray]

reveal_type(np.atleast_2d(A))  # E: numpy.ndarray

reveal_type(np.atleast_3d(A))  # E: numpy.ndarray

reveal_type(np.vstack([A, A]))  # E: numpy.ndarray
reveal_type(np.vstack([A, C]))  # E: numpy.ndarray
Пример #39
0
particle_force1 = np.copy(system.part[1].f)
checkpoint.register("particle_force0")
checkpoint.register("particle_force1")
if espressomd.has_features("COLLISION_DETECTION"):
    system.collision_detection.set_params(mode="bind_centers",
                                          distance=0.11,
                                          bond_centers=harmonic_bond)

if LB_implementation:
    m = np.pi / 12
    nx = int(np.round(system.box_l[0] / lbf.get_params()["agrid"]))
    ny = int(np.round(system.box_l[1] / lbf.get_params()["agrid"]))
    nz = int(np.round(system.box_l[2] / lbf.get_params()["agrid"]))
    # Create a 3D grid with deterministic values to fill the LB fluid lattice
    grid_3D = np.fromfunction(
        lambda i, j, k: np.cos(i * m) * np.cos(j * m) * np.cos(k * m),
        (nx, ny, nz),
        dtype=float)
    for i in range(nx):
        for j in range(ny):
            for k in range(nz):
                lbf[i, j, k].population = grid_3D[i, j, k] * np.arange(1, 20)
    cpt_mode = int("@TEST_BINARY@")
    # save LB checkpoint file
    lbf_cpt_path = checkpoint.checkpoint_dir + "/lb.cpt"
    lbf.save_checkpoint(lbf_cpt_path, cpt_mode)

if EK_implementation:
    m = np.pi / 12
    nx = int(np.round(system.box_l[0] / ek.get_params()["agrid"]))
    ny = int(np.round(system.box_l[1] / ek.get_params()["agrid"]))
    nz = int(np.round(system.box_l[2] / ek.get_params()["agrid"]))
Пример #40
0
#     xx= xx /s1 * (g1-1)
#     return yy,xx



if __name__ == '__main__':
    #this example shows extrapolation on an offset grid
    #where first and last row/column are skewed depending 
    #on the size of [offs]
    
    import pylab as plt
    import sys
    from imgProcessor.interpolate.polyfit2d import polyfit2dGrid
    
    g = (7,10)#small grid size
    small = np.fromfunction(lambda x,y: np.sin(7*x/g[0])
                            +np.cos(9*y/g[1]), g)
    g2 = (70,100) #big grid size

    if 'no_window' not in sys.argv:
        f, ax = plt.subplots(3,2)

    for i, offs in zip( (0,1,2), ((0,0),(8,9),(-5,-3)) ):
        ########
        yy,xx = offsetMeshgrid(offs, g, g2)
        big = polyfit2dGrid(small, outgrid=(yy,xx),
                            order=7)
        #######
        if 'no_window' not in sys.argv:
            ax[i,0].set_title('input data')
            ax[i,0].imshow(small, interpolation='none')
            
Пример #41
0
def model_array(ctrs, lam, oversample, pitch, fov, d,
                 centering='PIXELCENTERED', shape='circ'):
    """
    Short Summary
    -------------
    Create a model using the specified wavelength.

    Parameters
    ----------
    ctrs: 2D float array
        centers of holes

    lam: float
        wavelength in the bandpass for this particular model

    oversample: integer
        oversampling factor

    pitch: float
        sampling pitch in radians in image plane

    fov: integer
        number of detector pixels on a side.

    d: float
        hole diameter for 'circ'; flat to flat distance for 'hex

    centering: string
        subpixel centering; for now only option is PIXELCENTERED, which means
        putting the brightest detector pixel at the center of the trimmed data
        frame or simulated image.

    shape: string
        shape of hole; possible values are 'circ', 'hex', and 'fringe'

    Returns
    -------
    if 'shape' == 'circ', returns the primary beam (2D float array)
        for circular holes.
    if 'shape' == 'hex', returns the primary beam (2D float array)
        for hexagonal holes.

    ffmodel: list of 3 2D float arrays
        model array
    """

    if centering == 'PIXELCORNER':
        off = np.array([0.0, 0.0])
    elif centering == 'PIXELCENTERED':
        off = np.array([0.5, 0.5])
    else:
        off = centering

    log.debug('------------------')
    log.debug('Model Parameters:')
    log.debug('------------------')
    log.debug('pitch:%s fov:%s oversampling:%s ', pitch, fov, oversample)
    log.debug('centers:%s', ctrs)
    log.debug('wavelength:%s  centering:%s off:%s ', lam, centering, off)
    log.debug('shape:%s d:%s ', shape, d)

    #### dg - should I make some of the next blocks new/separate functions ?
    # primary beam parameters:
    primarybeam.shape = shape
    primarybeam.lam = lam
    primarybeam.size = (oversample * fov, oversample * fov)
    primarybeam.offx = oversample * fov / 2.0 - off[0] # in pixels
    primarybeam.offy = oversample * fov / 2.0 - off[1]
    primarybeam.pitch = pitch / float(oversample)
    primarybeam.d = d

    hexpb.shape = shape
    hexpb.lam = lam
    hexpb.size = (oversample * fov, oversample * fov)
    hexpb.offx = oversample * fov / 2.0 - off[0] # in pixels
    hexpb.offy = oversample * fov / 2.0 - off[1]
    hexpb.pitch = pitch / float(oversample)
    hexpb.d = d

    # model fringe matrix parameters:
    ffc.N = len(ctrs) # number of holes
    ffc.lam = lam
    ffc.over = oversample
    ffc.pitch = pitch / float(oversample)
    ffc.size = (oversample * fov, oversample * fov)
    ffc.offx = oversample * fov / 2.0 - off[0]
    ffc.offy = oversample * fov / 2.0 - off[1]

    ffs.N = len(ctrs) # number of holes
    ffs.lam = lam
    ffs.over = oversample
    ffs.pitch = pitch / float(oversample)
    ffs.size = (oversample * fov, oversample * fov)
    ffs.offx = oversample * fov / 2.0 - off[0]
    ffs.offy = oversample * fov / 2.0 - off[1]

    alist = []
    for i in range(ffc.N - 1):
        for j in range(ffc.N - 1):
            if j + i + 1 < ffc.N:
                alist = np.append(alist, i)
                alist = np.append(alist, j + i + 1)
    alist = alist.reshape(len(alist) // 2, 2)

    ffmodel = []
    ffmodel.append(ffc.N * np.ones(ffc.size))
    for q, r in enumerate(alist):
        # r[0] and r[1] are holes i and j, x-coord: 0, y-coord: 1
        ffc.ri = ctrs[int(r[0])]
        ffc.rj = ctrs[int(r[1])]
        ffs.ri = ctrs[int(r[0])]
        ffs.rj = ctrs[int(r[1])]
        ffmodel.append(np.fromfunction(ffc, ffc.size))
        ffmodel.append(np.fromfunction(ffs, ffs.size))

    if shape == 'circ': # if unspecified (default), or specified as 'circ'
        return np.fromfunction(primarybeam, ffc.size), ffmodel
    elif shape == 'hex':
        return hexpb(), ffmodel
    else:
        log.critical('Must provide a valid hole shape. Current supported shapes \
        are circ and hex.')
        return None
Пример #42
0
def first_cancel(array):
    import numpy
    cancel = numpy.fromfunction(lambda i: -(array[0] - array[-1]) / array.shape[0]\
             * i + array[0], (array.shape[0],), dtype=array.dtype)
    return array - cancel
Пример #43
0
    cu[5] = (c[5, 0] * u[0] + c[5, 1] * u[1])
    cu[6] = (c[6, 0] * u[0] + c[6, 1] * u[1])
    cu[7] = (c[7, 0] * u[0] + c[7, 1] * u[1])
    cu[8] = (c[8, 0] * u[0] + c[8, 1] * u[1])

    usqr = (u[0] * u[0] + u[1] * u[1])

    #feq = np.empty((q, xsize, ysize))
    feq = np.zeros((9, xsize, ysize), dtype=float).astype(np.float32)
    for i in range(q):
        feq[i, :, :] = rho * t[i] * (
            1. + 3.0 * cu[i] + 9 * 0.5 * cu[i] * cu[i] - 3.0 * 0.5 * usqr)
    return feq


LeftWall = np.fromfunction(lambda x, y: x == 0, (xsize, ysize))
RightWall = np.fromfunction(lambda x, y: x == xsize_max, (xsize, ysize))
BottomWall = np.fromfunction(lambda x, y: y == ysize_max, (xsize, ysize))

wall = np.logical_or(np.logical_or(LeftWall, RightWall), BottomWall)

# velocity initial/boundary conditions
InitVel = np.zeros((2, xsize, ysize))
InitVel[0, :, 0] = uLB
u[:] = InitVel[:]
# initial distributions
feq = equ(rho, InitVel)

np.copyto(fin, feq)
np.copyto(ftemp, feq)
np.copyto(fpost, feq)
Пример #44
0
def disc(r):
    r2 = r//2
    t = np.fromfunction(lambda x,y: (x-r2)**2+(y-r2)**2 <=r2**2,(r,r))
    w = np.zeros((r,r))
    w[t]=1
    return w
            VlocRN = np.zeros(order)
            VexRN = np.zeros((order, order))

            nu = mu * omega / (2 * hbar)

            for y in range(NState):
                for x in range(order):
                    psiRN[x, y] = psi(t[x], y, Lrel, nu)
                    ddpsiRN[x, y] = ddpsi(t[x], y, Lrel, nu)

            VlocRN[:] = pot_local(t[:],
                                  potargs) + mh2 * Lrel * (Lrel + 1) / t[:]**2

            if (interaction == "NonLocal"):
                VexRN = np.fromfunction(
                    lambda x, y: exchange_kernel(t[x], t[y], potargs),
                    (order, order),
                    dtype=int)
                VnolRN = np.fromfunction(
                    lambda x, y: pot_nonlocal(t[x], t[y], potargs),
                    (order, order),
                    dtype=int)

            # fill the lower triangular matrices only and exploit the symmetry
            # ECCE: I reduced the calculation to one loop
            for i in np.arange(NState):
                for j in np.arange(i + 1):
                    U[i][j] = np.sum(
                        psiRN[:, i] * psiRN[:, j] * w[:]) * gauss_scale
                    U[j][i] = U[i][j]
                    Kin[i][j] = np.sum(
                        psiRN[:, i] * ddpsiRN[:, j] * w[:]) * gauss_scale
Пример #46
0
def getA(n):
    return np.fromfunction(lambda i, j: 1 / (i + j + 1), (n, n))
Пример #47
0
def matrix(E):
    A = np.fromfunction(lambda i, ii: V(x(ii))*G(np.abs(x(i)-x(ii)),E), (nx,nx))
    A = 2*A*dx
    return A
    Vk2 = np.fft.fftshift(Vk2, axes=(0, 1))
    Vk3 = np.fft.fftshift(Vk3, axes=(0, 1))
    print("--- %s seconds ---" % (time.time() - start_time))

    np.savetxt('vk1_shift' + str(filenumber) + '.txt',
               np.absolute(Vk1[20][70]))

    #Square and add the absolute values of Vk1, Vk2, Vk3

    Vk_sq = np.add(
        np.add(np.square(np.absolute(Vk1)), np.square(np.absolute(Vk2))),
        np.square(np.absolute(Vk3)))

    #Write k_sq as a functional 3d array, with value at each element given by (nx/2-i)^2+(ny/2-j)^2+(k)^2
    k_sq = np.fromfunction(
        lambda i, j, k: (i - n[0] / 2)**2 + (j - n[1] / 2)**2 + k**2,
        np.shape(Vk1))

    #Energy density is given by Vk^2
    E_k = Vk_sq

    #Flatten E_k and k now, and store them in a single  2D array

    K = np.transpose(
        np.vstack((np.ndarray.flatten(k_sq), np.ndarray.flatten(E_k))))

    #K[][0] stores k, K[][1] stores E(k).

    print("--- %s seconds ---" % (time.time() - start_time))

    #The following code adds up E(k) values for the same k^2
Пример #49
0
def __fromfunction(f, s, t):
    return N.fromfunction(f,s).astype(t)
Пример #50
0
def	GeneralizedFFT(Input,b=1.0,a=0.0): 
	dim = len(Input)
	print 'numpy.shape(Input) = ',numpy.shape(Input)
	t1 = numpy.fromfunction(lambda X,Y: 2.0*pi*complex(0.0,1.0)*b*(X-1.0)*(Y-1.0)/dim,shape=[dim,dim])
	t1 = numpy.exp(t1)
	return (pow(dim,-(1.0-a)/2.0)*numpy.tensordot(Input,t1,axes=([0],[0])))
Пример #51
0
    y = j - offset[1]
    z = k - offset[2]
    th = np.arctan2(z, (x**2 + y**2)**0.5)
    phi = np.arctan2(y, x)
    r = (x**2 + y**2 + z**2)**0.5
    a0 = 2
    #ps = (1./81.) * (2./np.pi)**0.5 * (1./a0)**(3/2) * (6 - r/a0) * (r/a0) * np.exp(-r/(3*a0)) * np.cos(th)
    ps = (1. / 81.) * 1. / (6. * np.pi)**0.5 * (1. / a0)**(3 / 2) * (
        r / a0)**2 * np.exp(-r / (3 * a0)) * (3 * np.cos(th)**2 - 1)

    return ps

    #return ((1./81.) * (1./np.pi)**0.5 * (1./a0)**(3/2) * (r/a0)**2 * (r/a0) * np.exp(-r/(3*a0)) * np.sin(th) * np.cos(th) * np.exp(2 * 1j * phi))**2


data = np.fromfunction(psi, (100, 100, 200))
positive = np.log(np.clip(data, 0, data.max())**2)
negative = np.log(np.clip(-data, 0, -data.min())**2)

d2 = np.empty(data.shape + (4, ), dtype=np.ubyte)
d2[..., 0] = positive * (255. / positive.max())
d2[..., 1] = negative * (255. / negative.max())
d2[..., 2] = d2[..., 1]
d2[..., 3] = d2[..., 0] * 0.3 + d2[..., 1] * 0.3
d2[..., 3] = (d2[..., 3].astype(float) / 255.)**2 * 255

d2[:, 0, 0] = [255, 0, 0, 100]
d2[0, :, 0] = [0, 255, 0, 100]
d2[0, 0, :] = [0, 0, 255, 100]

v = gl.GLVolumeItem(d2)
Пример #52
0
def generate_radiation(x, y, size=700):
	return np.fromfunction(dose(x, y), (size, size))
Пример #53
0
        self._last_time = t
        self.shared_program['time'] = self._time
        self.update()


VectorField = scene.visuals.create_visual_node(VectorFieldVisual)


def fn(y, x):
    dx = x - 50
    dy = y - 30
    l = (dx**2 + dy**2)**0.5 + 0.01
    return np.array([100 * dy / l**1.7, -100 * dx / l**1.8])


field = np.fromfunction(fn, (100, 100)).transpose(1, 2, 0).astype('float32')
field[..., 0] += 10 * np.cos(np.linspace(0, 2 * 3.1415, 100))

color = np.zeros((100, 100, 4), dtype='float32')
color[..., :2] = (field + 5) / 10.
color[..., 2] = 0.5
color[..., 3] = 0.5

canvas = scene.SceneCanvas(keys='interactive', show=True)
view = canvas.central_widget.add_view(camera='panzoom')

vfield = VectorField(field[..., :2],
                     spacing=0.5,
                     segments=30,
                     seg_len=0.05,
                     parent=view.scene,
Пример #54
0
def eeg_plot_head_outline(scale=1,
                          shift=(0, 0),
                          color='k',
                          linewidth='5',
                          **kwargs):
    """Plots a simple outline of a head viewed from the top.
    Function borrowed from the PyMVPA package (http://www.pymvpa.org)
    see e.g., https://github.com/PyMVPA/PyMVPA/blob/master/mvpa2/misc/plot/topo.py

    The plot contains schematic representations of the nose and ears. The
    size of the head is basically a unit circle for nose and ears attached
    to it.

    Parameters
    ----------
    scale : float
      Factor to scale the size of the head.
    shift : 2-tuple of floats
      Shift the center of the head circle by these values.
    color : matplotlib color spec
      The color the outline should be plotted in.
    linewidth : int
      Linewidth of the head outline.
    **kwargs
      All additional arguments are passed to `pylab.plot()`.

    Returns
    -------
    Matplotlib lines2D object
      can be used to tweak the look of the head outline.
    """

    rmax = 0.5
    # factor used all the time
    fac = 2 * np.pi * 0.01

    # Koordinates for the ears
    EarX1 = -1 * np.array([
        .497, .510, .518, .5299, .5419, .54, .547, .532, .510,
        rmax * np.cos(fac * (54 + 42))
    ])
    EarY1 = np.array([
        .0655, .0775, .0783, .0746, .0555, -.0055, -.0932, -.1313, -.1384,
        rmax * np.sin(fac * (54 + 42))
    ])
    EarX2 = np.array([
        rmax * np.cos(fac * (54 + 42)), .510, .532, .547, .54, .5419, .5299,
        .518, .510, .497
    ])
    EarY2 = np.array([
        rmax * np.sin(fac * (54 + 42)), -.1384, -.1313, -.0932, -.0055, .0555,
        .0746, .0783, .0775, .0655
    ])

    # Coordinates for the Head
    HeadX1 = np.fromfunction(lambda x: rmax * np.cos(fac * (x + 2)), (21, ))
    HeadY1 = np.fromfunction(lambda y: rmax * np.sin(fac * (y + 2)), (21, ))
    HeadX2 = np.fromfunction(lambda x: rmax * np.cos(fac * (x + 28)), (21, ))
    HeadY2 = np.fromfunction(lambda y: rmax * np.sin(fac * (y + 28)), (21, ))
    HeadX3 = np.fromfunction(lambda x: rmax * np.cos(fac * (x + 54)), (43, ))
    HeadY3 = np.fromfunction(lambda y: rmax * np.sin(fac * (y + 54)), (43, ))

    # Coordinates for the Nose
    NoseX = np.array([.18 * rmax, 0, -.18 * rmax])
    NoseY = np.array([rmax - 0.004, rmax * 1.15, rmax - 0.004])

    # Combine to one
    X = np.concatenate((EarX2, HeadX1, NoseX, HeadX2, EarX1, HeadX3))
    Y = np.concatenate((EarY2, HeadY1, NoseY, HeadY2, EarY1, HeadY3))

    X *= 2 * scale
    Y *= 2 * scale
    X += shift[0]
    Y += shift[1]

    return plt.plot(X, Y, color=color, linewidth=linewidth)
 def mktile(w, h):
     tile = fromfunction(f, (w, h))
     tile = tile.astype(int)
     tile[tile > tile_max] = tile_max
     return list(tile.flatten())
Пример #56
0
 def from_function(cls, func, length, dtype=np.float):
     return np.fromfunction(func, shape=(length, ), dtype=dtype).view(cls)
Пример #57
0
f = np.array([[1, 2, 3, 4], [4, 5, 6, 7], [7, 8, 9, 10]], dtype=np.complex)

print(f)

print((np.typeDict["d"]))
print((np.typeDict["double"]))
print((np.typeDict["float64"]))
print((set(np.typeDict.values())))

print((np.arange(0, 1, 0.1)))
print((np.linspace(0, 1, 12)))
print((np.logspace(0, 2, 20)))

s = "abcdefgh"
print((np.fromstring(s, dtype=np.int16)))
print((np.fromstring(s, dtype=np.float)))


def func(i):
    return i % 4 + 1


print((np.fromfunction(func, (10, ))))


def func2(i, j):
    return (i + 1) * (j + 1)


print((np.fromfunction(func2, (9, 9))))
Пример #58
0
def exer6(odir):
    """ Coronagraph train, no optimization for speed.  
    2nd order BLC, didactic example, fftlike """
    # instantiate an mft object:
    ft = matrixDFT.MatrixFourierTransform()

    npup = 250 # Size of all arrays
    radius = 50.0

    # Numerical reselts in DFT setup cf telescope reselts:
    # reselts of telescope - here its 0.4 reselts per DFT output image pixel if npup=250,radius=50.
    dftpixel = 2.0 * radius / npup
    # Jinc first zero in reselts of telescope...
    firstzero_optical_reselts = 10.0
    firstzero_numericalpixels = firstzero_optical_reselts / dftpixel
    print("Jinc firstzero_numericalpixels", firstzero_numericalpixels)

    jinc = np.fromfunction(utils.Jinc, (npup,npup),
                           c=utils.centerpoint(npup),
                           scale=firstzero_numericalpixels)
    fpm_blc2ndorder = 1 - jinc*jinc
    print("Jinc fpm min = ", fpm_blc2ndorder.min(), 
          "Jinc fpm max = ", fpm_blc2ndorder.max())

    # Pupil, Pupilphase, Apodizer, FP intensity, Intensity after FPM, 
    # Lyot intensity, Lyot Stop, Post-Lyot Stop Intensity, Final image.
    #
    # Set up optical train for a typical Lyot style or phase mask coronagraph:
    Cordict = {
        "Pupil": utils.makedisk(npup, radius=radius),
        "Pupilphase": None,
        "Apodizer": None,
        "FPintensity": None,
        "FPM": fpm_blc2ndorder,
        "LyotIntensity": None,
        "LyotStop":  utils.makedisk(npup, radius=41),
        "PostLyotStopIntensity": None,
        "FinalImage": None,
        "ContrastImage": None}


    # Propagate through the coronagraph train...
    # Start with perfect incoming plane wave, no aberrations
    efield = Cordict["Pupil"]
    # Put in phase aberrations:
    if Cordict["Pupilphase"] is not None:
        efield *= np.exp(1j*Cordict["Pupilphase"])
    # Apodize the entrance pupil:
    if Cordict["Apodizer"] is not None:
        efield *= Cordict["Apodizer"]
    # PROPAGATE TO FIRST FOCAL PLANE:
    efield = ft.perform(efield, npup, npup)
    # Store FPM intensity:
    Cordict["FPintensity"] = (efield * efield.conj()).real

    # Save no-Cor efield for normalization of cor image by peak of no-FPM image
    efield_NC = efield.copy()
    # Multiply by FPM transmission function
    # Lyot style - zero in center, phase mask style: zero integral over domain
    efield *=  Cordict["FPM"]

    # PROPAGATE TO LYOT PLANE:
    efield_NC = ft.perform(efield_NC, npup, npup)
    efield = ft.perform(efield, npup, npup)
    # Save Cor Lyot intensity;
    Cordict["LyotIntensity"] = (efield * efield.conj()).real
    # Apply Lyot stop:
    if Cordict["LyotStop"] is not None: efield_NC *= Cordict["LyotStop"]
    if Cordict["LyotStop"] is not None: efield *= Cordict["LyotStop"]
    # Save Cor Lyot intensity after applying Lyot stop;
    Cordict["PostLyotStopIntensity"] = (efield * efield.conj()).real

    # PROPAGATE TO FINAL IMAGE PLANE:
    efield_NC = ft.perform(efield_NC, npup, npup)
    efield = ft.perform(efield, npup, npup)
    final_image_intensity_NC = (efield_NC * efield_NC.conj()).real
    final_image_intensity = (efield * efield.conj()).real
    Cordict["FinalImage"] = (efield * efield.conj()).real
    Cordict["ContrastImage"] = (efield * efield.conj()).real / final_image_intensity_NC.max()

    # Write our coronagraph planes:
    planenames, cube = corcube(Cordict)
    # write planemames as fits keywords
    print(odir+"/ex6_BLC_2ndOrder.fits")
    fits.PrimaryHDU(cube).writeto(odir+"/ex6_BLC_2ndOrder.fits", overwrite=True)
    fobj = fits.open(odir+"/ex6_BLC_2ndOrder.fits")
    fobj[0].header["Pupil"] = 1
    fobj[0].header["FPI"] = (2, "focal plane Intensity")
    fobj[0].header["FPM"] = (3, "focal plane mask")
    fobj[0].header["LyotIntn"] = (4, "Lyot Intensity")
    fobj[0].header["LyotStop"] = 5
    fobj[0].header["PostLyot"] = (6, "Post Lyot Stop Intensity")
    fobj[0].header["CorIm"] = (7, "Raw cor image")
    fobj[0].header["Contrast"] = (8, "Cor image in contrast units")
    fobj.writeto(odir+"/ex6_BLC_2ndOrder.fits", overwrite=True)
Пример #59
0
def main():

    # ********************************************************************
    # read and test input parameters
    # ********************************************************************

    print('Parallel Research Kernels version ')  #, PRKVERSION
    print('Python Numpy Matrix transpose: B = A^T')

    if len(sys.argv) != 3:
        print('argument count = ', len(sys.argv))
        sys.exit("Usage: ./transpose <# iterations> <matrix order>")

    iterations = int(sys.argv[1])
    if iterations < 1:
        sys.exit("ERROR: iterations must be >= 1")

    order = int(sys.argv[2])
    if order < 1:
        sys.exit("ERROR: order must be >= 1")

    print('Number of iterations = ', iterations)
    print('Matrix order         = ', order)

    # ********************************************************************
    # ** Allocate space for the input and transpose matrix
    # ********************************************************************

    A = numpy.fromfunction(lambda i, j: i * order + j, (order, order),
                           dtype=float)
    B = numpy.zeros((order, order))

    for k in range(0, iterations + 1):

        if k < 1: t0 = timer()

        transpose(order, A, B)
        add(order, A, 1.0)
        #kernel(order,A,B)

    t1 = timer()
    trans_time = t1 - t0

    # ********************************************************************
    # ** Analyze and output results.
    # ********************************************************************

    A = numpy.fromfunction(lambda i, j: ((iterations / 2.0) +
                                         (order * j + i)) * (iterations + 1.0),
                           (order, order),
                           dtype=float)
    abserr = numpy.linalg.norm(numpy.reshape(B - A, order * order), ord=1)

    epsilon = 1.e-8
    nbytes = 2 * order**2 * 8  # 8 is not sizeof(double) in bytes, but allows for comparison to C etc.
    if abserr < epsilon:
        print('Solution validates')
        avgtime = trans_time / iterations
        print('Rate (MB/s): ', 1.e-6 * nbytes / avgtime, ' Avg time (s): ',
              avgtime)
    else:
        print('error ', abserr, ' exceeds threshold ', epsilon)
        sys.exit("ERROR: solution did not validate")
Пример #60
0
			count+=trix[i,j]
		if (count>inf):
			inf = count
	return inf

def infinite(trix):
	shape = trix.shape
	row = shape[0]
	col = shape[1]
	first = 0
	for i in range(col):
		count = 0
		for j in range(row):
			count+=trix[j,i]
		if(count>first):
			first = count
	return first

A = np.fromfunction(lambda x,y : 2*x+y, (4,5))
B = A.transpose()
C = A.dot(B)
#print(A)
#print(B)
#print(C)
print()
print('     Frobenious for C:    {0:10.5f} Norm:    {1:10.5f} Infinite:    {2:10.5f}'.format(froben(C),norm(C),infinite(C)))
matrix = np.fromfunction(lambda x,y : 2*x+y, (1000,1000))
print('Frobenious for Matrix: {0:10.5f} Norm: {1:10.5f} Infinite: {2:10.5f}'.format(froben(matrix),norm(matrix),infinite(matrix)))
print()
print('Code Run Time:',clock.time() - start)