def advect_once(self, dt):
     stime_calc = compute_ptimer_hr()
     fdt = self._ft[1] - self._ft[0]
     if type(fdt) is not numpy.float64:
         fdt = timedelta(fdt).total_seconds()
     etime_calc = compute_ptimer_hr()
     self._compute_time += (etime_calc - stime_calc)
     x = []
     y = []
     t = []
     stime_mem = compute_ptimer_hr()
     for p in self._data:
         x.append(p.pt[0])
         y.append(p.pt[1])
         t.append(p.pt[2])
     pts = (numpy.array(t), numpy.array(y), numpy.array(x))
     etime_mem = compute_ptimer_hr()
     self._io_mem_time += (etime_mem - stime_mem)
     stime_calc = compute_ptimer_hr()
     us = interpn(self._gdims,
                  self._fu,
                  pts,
                  method='linear',
                  fill_value=.0)
     vs = interpn(self._gdims,
                  self._fv,
                  pts,
                  method='linear',
                  fill_value=.0)
     for i, p in enumerate(self._data):
         # p.advect(self._fu, self._fv, self._gdims, dt, fdt)
         p.advect_uv(us[i], vs[i], self._gdims, dt, fdt)
     self._simtime += dt
     etime_calc = compute_ptimer_hr()
     self._compute_time += (etime_calc - stime_calc)
Esempio n. 2
0
def interpolate_complex_slice_2d(x, y, dfl_slice, dgrid):
    """
    Interpolates 2d complex fld/dfl array at points
    
    Input
    x: list of x points to interpolate at
    y: list of y points to interpolate at
    dfl_slice: complex field grid in 2d (ncar, ncar)
    dgrid: extent of field grid from [-dgrid, dgrid] in x and y
    
    Output:
    complex field at points 
    
    """
    dat = dfl_slice
    nx = len(dat)  # = ncar
    dx = 2 * dgrid / (nx - 1)
    xmin = -dgrid
    xlist = [dx * i + xmin for i in range(nx)]
    # interpn only works on real data. Two calls
    xylist = np.transpose([x, y])
    redat = interpn((xlist, xlist), np.real(dat), xylist)
    imdat = interpn((xlist, xlist), np.imag(dat), xylist)
    # rejoin complex number
    return 1j * imdat + redat
def mapped_weight(u, y, x, ttT, xxT, i):
    # Same as 'mapped' function, but also return weight from interpolation
    # Used in the computation of the derivative of the cost function
    ny = len(y)
    nx = len(x)
    yc = np.linspace(0, ny - 1, (2**i + 1), dtype=int)
    xc = np.linspace(0, nx - 1, (2**i + 1), dtype=int)
    xx, tt = np.meshgrid(x, y, indexing='ij')

    # Transform coordinate
    Tt = interpolate.interpn((x[xc], y[yc]),
                             ttT,
                             np.array([xx.reshape(-1),
                                       tt.reshape(-1)]).T,
                             method='linear')
    Tx = interpolate.interpn((x[xc], y[yc]),
                             xxT,
                             np.array([xx.reshape(-1),
                                       tt.reshape(-1)]).T,
                             method='linear')

    # Interpolated function
    uT, uT_x, uT_y = interpn_linear((x, y),
                                    u,
                                    np.array([Tx, Tt]).T,
                                    method='linear',
                                    bounds_error=False,
                                    fill_value=0)  # ,fill_value=1000)

    return uT.reshape(nx, ny), uT_x, uT_y
def mapped_TAHMO(u, y, x, yyT, xxT, lat_sta, lon_sta, i):
    # Return the values of the warped signal at given coordinates (lat_sta,lon_sta)
    ny = len(y)
    nx = len(x)
    yc = np.linspace(0, ny - 1, (2**i + 1), dtype=int)
    xc = np.linspace(0, nx - 1, (2**i + 1), dtype=int)

    # Transform coordinate
    Tt = interpolate.interpn((x[xc], y[yc]),
                             yyT,
                             np.array([lon_sta, lat_sta]).T,
                             method='linear',
                             bounds_error=False,
                             fill_value=None)
    Tx = interpolate.interpn((x[xc], y[yc]),
                             xxT,
                             np.array([lon_sta, lat_sta]).T,
                             method='linear',
                             bounds_error=False,
                             fill_value=None)

    # Interpolated function
    uT = interpolate.interpn((x, y),
                             u,
                             np.array([Tx, Tt]).T,
                             method='linear',
                             bounds_error=False,
                             fill_value=None)  # ,fill_value=1000)
    return uT
Esempio n. 5
0
    def get_uv_wind(self, lon, lat, idx):
        """
        Consult https://docs.scipy.org/doc/scipy-0.18.1/reference/generated/scipy.interpolate.interpn.html

        :param lon: longitude of the point
        :param lat: latitude of the point
        :param idx: idx in the grib file (see physical_time_to_idx)
        :return: -- interpolated -- (u, v) wind conditions at (lon, lat) point, for the corresponding 'idx'
        """
        # find out idx relatively to physical time giv
        idx = idx
        u10 = self.gribs[idx, 0, :, :]
        v10 = self.gribs[idx, 1, :, :]

        interpolated_value_uwind = interpolate.interpn(
            points=(self.latitudes[:, 0], self.longitudes[0, :]),
            values=u10,
            xi=([lat], [lon]),
            method="linear")
        interpolated_value_vwind = interpolate.interpn(
            points=(self.latitudes[:, 0], self.longitudes[0, :]),
            values=v10,
            xi=([lat], [lon]),
            method="linear")

        return interpolated_value_uwind, interpolated_value_vwind
def aero_model(alpha, bet, VT, h, eta, P, Q, R, dela, dele, delr):
    eta1 = eta[0, 0]
    eta2 = eta[1, 0]

    # trimming
    alp_trm = min(max(min(alp_grd), alpha), max(alp_grd))
    dele_trm = min(max(min(dele_grd), dele), max(dele_grd))
    eta1_trm = min(max(min(eta1_grd), eta1), max(eta1_grd))
    eta2_trm = min(max(min(eta2_grd), eta2), max(eta2_grd))

    # longitudinal coefficient interpolation
    CD = interpn((alp_grd, dele_grd, eta1_grd, eta2_grd), CD_grd,
                 (alp_trm, dele_trm, eta1_trm, eta2_trm))
    CL = interpn((alp_grd, dele_grd, eta1_grd, eta2_grd), CL_grd,
                 (alp_trm, dele_trm, eta1_trm, eta2_trm))
    Cm = interpn((alp_grd, dele_grd, eta1_grd, eta2_grd), Cm_grd,
                 (alp_trm, dele_trm, eta1_trm, eta2_trm))

    # lateral coefficient
    CC = 0
    Cl = 0
    Cn = 0

    # coordinate change from wind to body
    CX = m.cos(alpha) * m.cos(bet) * (-CD) - m.cos(alpha) * m.sin(bet) * (
        -CC) - m.sin(alpha) * (-CL)
    CY = m.sin(bet) * (-CD) + m.cos(bet) * (-CC) + 0 * (-CL)
    CZ = m.cos(bet) * m.sin(alpha) * (-CD) - m.sin(alpha) * m.sin(bet) * (
        -CC) + m.cos(alpha) * (-CL)

    return CX, CY, CZ, Cl, Cm, Cn, CL, CD
Esempio n. 7
0
def getPointValue(phys_state, x1, x2, x3, field='velocity'):

    assert (phys_state.geometry == 'shell'
            ), "Tools not implemented for geometry" + phys_state.geometry

    # find the grid in radial and meridional direction
    x1_grid = phys_state.grid_r[::-1]
    x2_grid = phys_state.grid_theta[::-1]
    x3_grid = phys_state.grid_phi

    fields = field_storage[field]
    Field1 = interpn((x1_grid, x2_grid, x3_grid),
                     getattr(phys_state.fields, fields + '_r')[::-1, ::-1, :],
                     (x1, x2, x3))
    Field2 = interpn((x1_grid, x2_grid, x3_grid),
                     getattr(phys_state.fields,
                             fields + '_theta')[::-1, ::-1, :], (x1, x2, x3))
    Field3 = interpn((x1_grid, x2_grid, x3_grid),
                     getattr(phys_state.fields,
                             fields + '_phi')[::-1, ::-1, :], (x1, x2, x3))

    fieldp = field_presentation[field]
    result = {
        'r': x1,
        'theta': x2,
        'phi': x3,
        fieldp + 'R': Field1.T,
        fieldp + 'Theta': Field2.T,
        fieldp + 'Phi': Field3.T
    }
    return result
Esempio n. 8
0
    def probe_data(self, rad, lat, lon, **kwargs):
        '''
       returns the value of the field at the point specified. 
   
       params:
       lat
       lon
       depth
      '''
        type = kwargs.get('type', 'point')
        if type == 'cell':
            p1 = self.rad[0:len(self.rad) - 1]
            p2 = self.lat[0:len(self.lat) - 1]
            p3 = self.lon[0:len(self.lon) - 1]

            return interpn(points=(p1, p2, p3),
                           values=self.data,
                           xi=(rad, lat, lon),
                           bounds_error=False,
                           fill_value=0.0)

        elif type == 'point':
            return interpn(points=(self.rad, self.lat, self.lon),
                           values=self.data_pts,
                           xi=(rad, lat, lon),
                           bounds_error=False,
                           fill_value=0.0)
Esempio n. 9
0
    def test_nonscalar_values(self):
        # Verify that non-scalar valued values also works
        points, values = self._sample_4d_data()

        np.random.seed(1234)
        values = np.random.rand(3, 3, 3, 3, 6)
        sample = np.random.rand(7, 11, 4)

        for method in ['nearest', 'linear']:
            v = interpn(points,
                        values,
                        sample,
                        method=method,
                        bounds_error=False)
            assert_equal(v.shape, (7, 11, 6), err_msg=method)

            vs = [
                interpn(points,
                        values[..., j],
                        sample,
                        method=method,
                        bounds_error=False) for j in range(6)
            ]
            v2 = np.array(vs).transpose(1, 2, 0)

            assert_allclose(v, v2, err_msg=method)

        # Vector-valued splines supported with fitpack
        assert_raises(ValueError,
                      interpn,
                      points,
                      values,
                      sample,
                      method='splinef2d')
Esempio n. 10
0
    def warpImg(self, hi_vol, lo_vol):
        new_coords = np.stack(
            [self._defFieldGen() for idx in range(self._img_dims[0])], axis=0)
        new_hi_vol = np.zeros(self._img_dims)
        new_lo_vol = np.zeros(self._img_dims)

        for idx in range(self._img_dims[0]):
            new_hi_vol[idx, :, :, :, 0] = sci.interpn(
                (np.arange(self._img_dims[1]), np.arange(
                    self._img_dims[2]), np.arange(self._img_dims[3])),
                hi_vol[idx, :, :, :, 0],
                new_coords[idx, ...],
                method='linear',
                fill_value=0,
                bounds_error=False)

            new_lo_vol[idx, :, :, :, 0] = sci.interpn(
                (np.arange(self._img_dims[1]), np.arange(
                    self._img_dims[2]), np.arange(self._img_dims[3])),
                lo_vol[idx, :, :, :, 0],
                new_coords[idx, ...],
                method='linear',
                fill_value=0,
                bounds_error=False)

        self._aff_mat = self._ident_mat
        return new_hi_vol, new_lo_vol
Esempio n. 11
0
def RAngCalc(data,sweep_slope,fs):
    '''create Range angle map for a given data set'''

    Angle1 = np.linspace(-1,1,len(data.T),endpoint=True)
    Angle1 = np.degrees(np.arcsin(Angle1))                  #arcsin as the array factor is proportional to the sin

    Freq = np.linspace(0,fs,len(data),endpoint=True)   
    Range = (Freq*3e8) / (2*sweep_slope)

    R = np.fft.fft(data,None,0)

    A = np.fft.fft(data,None,1)
    A = np.fft.fftshift(A,1)

    ReflecMap = np.fft.fft(R,None,1)
    ReflecMap = np.fft.fftshift(ReflecMap,1)        #create range and angle map for input data

    
    interp_ratio = 1#20                                #ratio of initial array elements vs interpolated elements
    
    Angle = np.linspace(-1,1,len(data.T)*interp_ratio,endpoint=True) #create new angle vector to plot against
    Angle = np.degrees(np.arcsin(Angle))                    #to go from psi to angle representations
    
    interp_mesh = np.array(np.meshgrid(Range, Angle, indexing='ij'))
    interp_points = np.rollaxis(interp_mesh, 0, 3).reshape((-1, 2)) #create list of cooridnates to interpolate at

    A = si.interpn((Range,Angle1),A,interp_points)
    A = np.reshape(A,(len(Range), len(Angle)))

    ReflecMap = si.interpn((Range,Angle1),ReflecMap,interp_points)
    ReflecMap = np.reshape(ReflecMap,(len(Range), len(Angle)))
    
    return [Range, Angle, R, A, ReflecMap]
Esempio n. 12
0
   def probe_data(self,rad,lat,lon,**kwargs):
      '''
       returns the value of the field at the point specified. 
   
       params:
       lat
       lon
       depth
      '''
      type = kwargs.get('type','point')
      if type == 'cell':
         p1    = self.rad[0:len(self.rad)-1]
         p2    = self.lat[0:len(self.lat)-1]
         p3    = self.lon[0:len(self.lon)-1]
      
         return interpn(points = (p1,p2,p3),
                        values = self.data,
                        xi = (rad,lat,lon),
                        bounds_error=False,
                        fill_value = 0.0)

      elif type == 'point':
         return interpn(points=(self.rad,self.lat,self.lon),
                        values=self.data_pts,
                        xi = (rad,lat,lon),
                        bounds_error=False,
                        fill_value = 0.0)
Esempio n. 13
0
    def test_descending_points(self):
        def value_func_4d(x, y, z, a):
            return 2 * x**3 + 3 * y**2 - z - a

        x1 = np.array([0, 1, 2, 3])
        x2 = np.array([0, 10, 20, 30])
        x3 = np.array([0, 10, 20, 30])
        x4 = np.array([0, .1, .2, .30])
        points = (x1, x2, x3, x4)
        values = value_func_4d(
            *np.meshgrid(*points, indexing='ij', sparse=True))
        pts = (0.1, 0.3, np.transpose(np.linspace(0, 30,
                                                  4)), np.linspace(0, 0.3, 4))
        correct_result = interpn(points, values, pts)

        x1_descend = x1[::-1]
        x2_descend = x2[::-1]
        x3_descend = x3[::-1]
        x4_descend = x4[::-1]
        points_shuffled = (x1_descend, x2_descend, x3_descend, x4_descend)
        values_shuffled = value_func_4d(
            *np.meshgrid(*points_shuffled, indexing='ij', sparse=True))
        test_result = interpn(points_shuffled, values_shuffled, pts)

        assert_array_equal(correct_result, test_result)
Esempio n. 14
0
def interp_depth_model(model, lat, lon, new_dep):
    """ Interpolate Vp and Vs from 3D velocity with a specified depth range.

    Parameters
    ----------
    mod3d : :meth:`np.lib.npyio.NpzFile`
        3D velocity loaded from a ``.npz`` file
    lat : float
        Latitude of position in 3D velocity model
    lon : float
        Longitude of position in 3D velocity model
    new_dep : :meth:`np.ndarray`
        1D array of depths in km

    Returns
    -------
    Vp : :meth:`np.ndarray`
        Vp in ``new_dep``
    Vs : :meth:`np.ndarray`
        Vs in ``new_dep``
    """
    #  model = np.load(modpath)
    points = [[depth, lat, lon] for depth in new_dep]
    vp = interpn((model['dep'], model['lat'], model['lon']),
                 model['vp'],
                 points,
                 bounds_error=False,
                 fill_value=None)
    vs = interpn((model['dep'], model['lat'], model['lon']),
                 model['vs'],
                 points,
                 bounds_error=False,
                 fill_value=None)
    return vp, vs
def mapped(u, y, x, yyT, xxT, i):
    # Return the warped signal
    ny = len(y)
    nx = len(x)
    yc = np.linspace(0, ny - 1, (2**i + 1), dtype=int)
    xc = np.linspace(0, nx - 1, (2**i + 1), dtype=int)
    xx, yy = np.meshgrid(x, y, indexing='ij')

    # Transform coordinate
    Tt = interpolate.interpn((x[xc], y[yc]),
                             yyT,
                             np.array([xx.reshape(-1),
                                       yy.reshape(-1)]).T,
                             method='linear')
    Tx = interpolate.interpn((x[xc], y[yc]),
                             xxT,
                             np.array([xx.reshape(-1),
                                       yy.reshape(-1)]).T,
                             method='linear')

    # Interpolated function
    uT = interpolate.interpn((x, y),
                             u,
                             np.array([Tx, Tt]).T,
                             method='linear',
                             bounds_error=False,
                             fill_value=None)  # ,fill_value=1000)
    return uT.reshape(nx, ny)
Esempio n. 16
0
    def test_length_one_axis(self):
        # gh-5890, gh-9524 : length-1 axis is legal for method='linear'.
        # Along the axis it's linear interpolation; away from the length-1
        # axis, it's an extrapolation, so fill_value should be used.

        values = np.array([[0.1, 1, 10]])
        xi = np.array([[1, 2.2], [1, 3.2], [1, 3.8]])

        res = interpn(([1], [2, 3, 4]), values, xi)
        wanted = [
            0.9 * 0.2 + 0.1,  # on [2, 3) it's 0.9*(x-2) + 0.1
            9 * 0.2 + 1,  # on [3, 4] it's 9*(x-3) + 1
            9 * 0.8 + 1
        ]

        assert_allclose(res, wanted, atol=1e-15)

        # check extrapolation
        xi = np.array([[1.1, 2.2], [1.5, 3.2], [-2.3, 3.8]])
        res = interpn(([1], [2, 3, 4]),
                      values,
                      xi,
                      bounds_error=False,
                      fill_value=None)

        assert_allclose(res, wanted, atol=1e-15)
Esempio n. 17
0
 def test_xi_1d(self):
     # verify that 1-D xi works as expected
     points, values = self._sample_4d_data()
     sample = np.asarray([0.1, 0.1, 10., 9.])
     v1 = interpn(points, values, sample, bounds_error=False)
     v2 = interpn(points, values, sample[None, :], bounds_error=False)
     assert_allclose(v1, v2)
Esempio n. 18
0
def shiftParticle(original, displacement, gridNumber, boxsize, boxmin):
    boxRange = np.arange(gridNumber)
    boxGrid = np.array([boxRange for i in range(3)])
    new = original.copy()
    new[0] = (original[0] - boxmin) * (gridNumber - 1) / boxsize
    new[1] = (original[1] - boxmin) * (gridNumber - 1) / boxsize
    new[2] = (original[2] - boxmin) * (gridNumber - 1) / boxsize
    xinterp = interpolate.interpn(boxGrid,
                                  displacement[0],
                                  new.T,
                                  bounds_error=False,
                                  fill_value=0).real
    yinterp = interpolate.interpn(boxGrid,
                                  displacement[1],
                                  new.T,
                                  bounds_error=False,
                                  fill_value=0).real
    zinterp = interpolate.interpn(boxGrid,
                                  displacement[2],
                                  new.T,
                                  bounds_error=False,
                                  fill_value=0).real
    new[0] = (new[0]) * (boxsize) / (gridNumber - 1) + boxmin + xinterp
    new[1] = (new[1]) * (boxsize) / (gridNumber - 1) + boxmin + yinterp
    new[2] = (new[2]) * (boxsize) / (gridNumber - 1) + boxmin + zinterp
    new = new.transpose()
    return (new)
 def advect_once(self, dt):
     fdt = self._ft[1] - self._ft[0]
     if type(fdt) is not numpy.float64:
         fdt = timedelta(fdt).total_seconds()
     x = []
     y = []
     t = []
     for p in self._data:
         x.append(p.pt[0])
         y.append(p.pt[1])
         t.append(p.pt[2])
     pts = (numpy.array(t), numpy.array(y), numpy.array(x))
     us = interpn(self._gdims,
                  self._fu,
                  pts,
                  method='linear',
                  fill_value=.0)
     vs = interpn(self._gdims,
                  self._fv,
                  pts,
                  method='linear',
                  fill_value=.0)
     for i, p in enumerate(self._data):
         # p.advect(self._fu, self._fv, self._gdims, dt, fdt)
         p.advect_uv(us[i], vs[i], self._gdims, dt, fdt)
     self._simtime += dt
Esempio n. 20
0
    def test_xi_broadcast(self):
        # verify that the interpolators broadcast xi
        x, y, values = self._sample_2d_data()
        points = (x, y)

        xi = np.linspace(0, 1, 2)
        yi = np.linspace(0, 3, 3)

        for method in ['nearest', 'linear', 'splinef2d']:
            sample = (xi[:, None], yi[None, :])
            v1 = interpn(points,
                         values,
                         sample,
                         method=method,
                         bounds_error=False)
            assert_equal(v1.shape, (2, 3))

            xx, yy = np.meshgrid(xi, yi)
            sample = np.c_[xx.T.ravel(), yy.T.ravel()]

            v2 = interpn(points,
                         values,
                         sample,
                         method=method,
                         bounds_error=False)
            assert_allclose(v1, v2.reshape(v1.shape))
Esempio n. 21
0
    def build_basement(self,tXY,id):
        """
        Using Pandas library to read the basement map file and define consolidated and
        soft sediment region.
        """
        self.tXY = tXY

        # Read basement file
        if id == 1:
            self.tinBase1 = numpy.ones(len(tXY))
            Bmap = pandas.read_csv(str(self.baseMap), sep=r'\s+', engine='c',
                        header=None, na_filter=False, dtype=numpy.float, low_memory=False)

            rectBase = numpy.reshape(Bmap.values,(len(self.regX), len(self.regY)),order='F')
            self.tinBase1[self.boundsPt:] = interpolate.interpn( (self.regX, self.regY), rectBase,
                                                        tXY[self.boundsPt:,:], method='linear')
        elif id == 2:
            self.tinBase2 = numpy.ones(len(tXY))
            Bmap = pandas.read_csv(str(self.baseMap2), sep=r'\s+', engine='c',
                        header=None, na_filter=False, dtype=numpy.float, low_memory=False)

            rectBase = numpy.reshape(Bmap.values,(len(self.regX), len(self.regY)),order='F')
            self.tinBase2[self.boundsPt:] = interpolate.interpn( (self.regX, self.regY), rectBase,
                                                        tXY[self.boundsPt:,:], method='linear')

        return
Esempio n. 22
0
def main():
    """
    Main routine
    """
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--input", help="Input file", default="data.cub")
    parser.add_argument("-p", "--point", help="One point of the plane", type=float, nargs=3, default=(0., 0., 0.))
    parser.add_argument("-n", "--normal", help="The normal of the plane", type=float, nargs=3, default=(1., 0., 0.))
    args = parser.parse_args()
    point_in_plane = np.array([args.point[0], args.point[1], args.point[2]])
    normal_to_plane = np.array([args.normal[0], args.normal[1], args.normal[2]])
    filename = args.input
    cubedata = Cubefile(filename)
    cubedata.print()
    print(cubedata.origin)
    print(cubedata.getgrid()[0])
    print(cubedata.data[0, 0, 0])
    Vi = interpn((cubedata.getXvalues(), cubedata.getYvalues(), cubedata.getZvalues()), cubedata.data,
                 np.array([[-17.5615, -12.8185, -6.83306 + i*0.759228] for i in range(19)]))
    for i in range(19):
        print("{:1.8f} {:1.12f}".format(-6.83306+i*0.759228, Vi[i]))
    Vi = interpn((cubedata.getXvalues(), cubedata.getYvalues(), cubedata.getZvalues()), cubedata.data,
                 np.array([[-17.5615, -12.8185, -6.83306 + i*0.075922] for i in range(179)]))
    for i in range(179):
        print("{:1.8f} {:1.12f}".format(-6.83306 + i * 0.075922, Vi[i]))
Esempio n. 23
0
def fscaling3D(X_train, X_test, scpatchSize, iscalefactor):
    afterSize = np.ceil(np.multiply(scpatchSize, iscalefactor)).astype(int)

    # Prepare for the using of scipy.interpolation: create the coordinates of grid
    if iscalefactor == 1:
        return X_train, X_test, scpatchSize
    else:
        xaxis = np.linspace(0, afterSize[0], scpatchSize[0])
        yaxis = np.linspace(0, afterSize[1], scpatchSize[1])
        zaxis = np.linspace(0, afterSize[2], scpatchSize[2])

    dAllx_train = None
    dAllx_test = None

    for ifold in range(len(X_train)):
        lenTrain = X_train[ifold].shape[0]
        lenTest = X_test[ifold].shape[0]

        start = time.clock()

        # no batch
        inter_train0 = np.mgrid[0:lenTrain, 0:afterSize[0], 0:afterSize[1], 0:afterSize[2]]
        inter_train1 = np.rollaxis(inter_train0, 0, 5)
        inter_train = np.reshape(inter_train1, [inter_train0.size // 4, 4])  # 4 for the dimension of coordinates

        zaxis_train = np.arange(lenTrain)

        upedTrain = interpolate.interpn((zaxis_train, xaxis, yaxis, zaxis),
                                        X_train[ifold],
                                        inter_train, method='linear', bounds_error=False, fill_value=0)
        dFoldx_train = np.reshape(upedTrain, [1, lenTrain, afterSize[0], afterSize[1], afterSize[2]])


        inter_test0 = np.mgrid[0:lenTest, 0:afterSize[0], 0:afterSize[1], 0:afterSize[2]]
        inter_test1 = np.rollaxis(inter_test0, 0, 5)
        inter_test = np.reshape(inter_test1, [inter_test0.size // 4, 4])  # 4 for the dimension of coordinates

        zaxis_test = np.arange(lenTest)

        upedTest = interpolate.interpn((zaxis_test, xaxis, yaxis, zaxis),
                                       X_test[ifold],
                                       inter_test, method='linear', bounds_error=False, fill_value=0)
        dFoldx_test = np.reshape(upedTest, [1, lenTest, afterSize[0], afterSize[1], afterSize[2]])

        stop = time.clock()
        print(stop-start)

        if dAllx_train is None:
            dAllx_train = dFoldx_train
        else:
            dAllx_train = np.concatenate((dAllx_train, dFoldx_train), axis=0)

        if dAllx_test is None:
            dAllx_test = dFoldx_test
        else:
            dAllx_test = np.concatenate((dAllx_test, dFoldx_test), axis=0)

    return dAllx_train, dAllx_test, afterSize
Esempio n. 24
0
def create_scales(input, idx):
    if 'stacks_v_s4' in input:
        input['stacks_v_s4'][idx] = np.clip(input['stacks_v_HR'][idx],
                                            16.0 / 255.0, 240 / 255)
        input['stacks_h_s4'][idx] = np.clip(input['stacks_h_HR'][idx],
                                            16.0 / 255.0, 240 / 255)

        input['stacks_v_s2'][idx] = np.clip(
            np.stack([
                cv2.resize(input['stacks_v_HR'][idx][i, :, :, :], (96, 96),
                           interpolation=cv2.INTER_CUBIC) for i in range(0, 9)
            ]), 16.0 / 255.0, 240 / 255)
        input['stacks_h_s2'][idx] = np.clip(
            np.stack([
                cv2.resize(input['stacks_h_HR'][idx][i, :, :, :], (96, 96),
                           interpolation=cv2.INTER_CUBIC) for i in range(0, 9)
            ]), 16.0 / 255.0, 240 / 255)
        input['stacks_v'][idx] = np.clip(
            np.stack([
                cv2.resize(input['stacks_v_HR'][idx][i, :, :, :], (48, 48),
                           interpolation=cv2.INTER_CUBIC) for i in range(0, 9)
            ]), 16.0 / 255.0, 240 / 255)
        input['stacks_h'][idx] = np.clip(
            np.stack([
                cv2.resize(input['stacks_h_HR'][idx][i, :, :, :], (48, 48),
                           interpolation=cv2.INTER_CUBIC) for i in range(0, 9)
            ]), 16.0 / 255.0, 240 / 255)
    else:
        input['stacks_v_s2'][idx] = np.clip(input['stacks_v_HR'][idx],
                                            16.0 / 255.0, 240 / 255)
        input['stacks_h_s2'][idx] = np.clip(input['stacks_h_HR'][idx],
                                            16.0 / 255.0, 240 / 255)
        input['stacks_v'][idx][..., 0:3] = np.clip(
            np.stack([
                cv2.resize(input['stacks_v_HR'][idx][i, :, :, :], (48, 48),
                           interpolation=cv2.INTER_CUBIC) for i in range(0, 9)
            ]), 16.0 / 255.0, 240 / 255)
        input['stacks_h'][idx][..., 0:3] = np.clip(
            np.stack([
                cv2.resize(input['stacks_h_HR'][idx][i, :, :, :], (48, 48),
                           interpolation=cv2.INTER_CUBIC) for i in range(0, 9)
            ]), 16.0 / 255.0, 240 / 255)

    # biclinear stuff
    [tq, vq, uq] = np.meshgrid(range(9), range(48), range(48))
    tq = tq.transpose(1, 0, 2)
    vq = vq.transpose(1, 0, 2)
    uq = uq.transpose(1, 0, 2)
    points = [[0, 4, 8], np.arange(48), np.arange(48)]
    xi = (tq.ravel(), vq.ravel(), uq.ravel())
    for ch in range(0, 3):
        input['stacks_bicubic_v'][idx][:, :, :, ch] = np.clip(
            interpn(points, input['stacks_v'][idx][0:9:4, :, :, ch],
                    xi).reshape((9, 48, 48)), 16.0 / 255.0, 240 / 255)
        input['stacks_bicubic_h'][idx][:, :, :, ch] = np.clip(
            interpn(points, input['stacks_h'][idx][0:9:4, :, :, ch],
                    xi).reshape((9, 48, 48)), 16.0 / 255.0, 240 / 255)
    return (input)
Esempio n. 25
0
def reddening(vlong, ulong, vlat, ulat, frame, step_pc=5):
    """Calculate Reddening versus distance from Sun.

    Args:
        vlong (str or double): Longitude value.
        ulong (str): Longitude unit used in :class:`SkyCoord`.
        vlat (str or double): Latitude value.
        ulat (str): Latitude unit used in :class:`SkyCoord`.
        frame (str): Galactic, icrs ... values supported by :class:`SkyCoord`.

    Kwargs:
        step_pc (int): Incremental distance in parsec

    Returns:
        array: Parsec values.
        array: E(B-V) value obtain with integral of linear extrapolation.

    """
    # Calculate the position for 1pc
    sc = SkyCoord(vlong,
                  vlat,
                  distance=1 * u.pc,
                  unit=(ulong, ulat),
                  frame=frame)
    coords_xyz = sc.transform_to('galactic').represent_as(
        'cartesian').get_xyz().value

    # Find the number of parsec I can calculate before go out the cube
    # (exclude divide by 0)
    not0 = np.where(coords_xyz != 0)
    max_pc = np.amin(
        np.abs(np.take(max_axes, not0) / np.take(coords_xyz, not0)))

    # Calculate all coordinates to interpolate (use step_pc)
    distances = np.arange(0, max_pc, step_pc)
    sc = SkyCoord(vlong,
                  vlat,
                  distance=distances,
                  unit=(ulong, ulat, 'pc'),
                  frame=frame)
    sc = sc.transform_to('galactic').represent_as('cartesian')
    coords_xyz = np.array([coord.get_xyz().value for coord in sc])

    # linear interpolation with coordinates
    interpolation = spi.interpn(axes, cube, coords_xyz, method='linear')
    xvalues = np.arange(0, len(interpolation) * step_pc, step_pc)
    yvalues = np.cumsum(interpolation) * step_pc

    # errors
    xerrors = spi.interpn(axes, cubeXErr, coords_xyz, method='linear')
    yerrorsMin = spi.interpn(axes, cubeYErrMin, coords_xyz, method='linear')
    yerrorsMax = spi.interpn(axes, cubeYErrMax, coords_xyz, method='linear')

    return (xvalues, np.around(yvalues,
                               decimals=3), np.around(xerrors, decimals=0),
            np.around(yerrorsMin, decimals=3), np.around(yerrorsMax,
                                                         decimals=3))
Esempio n. 26
0
def test__resample():

    # Test proper use.

    shape = (3,4)
    resolution = 1.5
    origin = 'zero'
    attempted_scales = 1
    image = np.arange(np.prod(shape)).reshape(shape)
    real_axes = _compute_axes(image.shape, resolution, origin=origin)
    new_shape = np.floor(np.multiply(image.shape, attempted_scales))
    real_scales = np.divide(new_shape, image.shape)
    new_shape = np.floor(np.multiply(np.subtract(image.shape, 1), real_scales)) + 1
    new_real_coords = _compute_coords(new_shape, resolution / real_scales, origin=origin)
    correct_output = interpn(points=real_axes, values=image, xi=new_real_coords)
    assert np.array_equal(_resample(image, real_axes, new_real_coords), correct_output)

    shape = (3)
    resolution = 1
    origin = 'zero'
    attempted_scales = 1
    image = np.arange(np.prod(shape)).reshape(shape)
    real_axes = _compute_axes(image.shape, resolution, origin=origin)
    new_shape = np.floor(np.multiply(image.shape, attempted_scales))
    real_scales = np.divide(new_shape, image.shape)
    new_shape = np.floor(np.multiply(np.subtract(image.shape, 1), real_scales)) + 1
    new_real_coords = _compute_coords(new_shape, resolution / real_scales, origin=origin)
    correct_output = interpn(points=real_axes, values=image, xi=new_real_coords)
    assert np.array_equal(_resample(image, real_axes, new_real_coords), correct_output)

    shape = (3,4,5)
    resolution = (0.5,1,1.5)
    origin = 'center'
    attempted_scales = (1/2,1/3,1/4)

    image = np.arange(np.prod(shape)).reshape(shape)
    real_axes = _compute_axes(image.shape, resolution, origin=origin)
    new_shape = np.floor(np.multiply(image.shape, attempted_scales))
    real_scales = np.divide(new_shape, image.shape)
    new_shape = np.floor(np.multiply(np.subtract(image.shape, 1), real_scales)) + 1
    new_real_coords = _compute_coords(new_shape, resolution / real_scales, origin=origin)
    correct_output = interpn(points=real_axes, values=image, xi=new_real_coords)
    assert np.array_equal(_resample(image, real_axes, new_real_coords), correct_output)

    shape = (6,7,8,9)
    resolution = (0.5,1,1.5,2.5)
    origin = 'center'
    attempted_scales = (2,3,3.5,np.pi)

    image = np.arange(np.prod(shape)).reshape(shape)
    real_axes = _compute_axes(image.shape, resolution, origin=origin)
    new_shape = np.floor(np.multiply(image.shape, attempted_scales))
    real_scales = np.divide(new_shape, image.shape)
    new_shape = np.floor(np.multiply(np.subtract(image.shape, 1), real_scales)) + 1
    new_real_coords = _compute_coords(new_shape, resolution / real_scales, origin=origin)
    correct_output = interpn(points=real_axes, values=image, xi=new_real_coords)
    assert np.array_equal(_resample(image, real_axes, new_real_coords), correct_output)
Esempio n. 27
0
def _pcax(psd: np.ndarray) -> (np.ndarray, np.ndarray):
    """
    Calculate integrals through the principal axes of psd.
    :param psd: psd.
    :return: (intg1, intg2) : two integrals along the two axes.
    """
    n = psd.shape[0]
    [g2, g1] = np.meshgrid([i for i in range(1, n + 1)],
                           [i for i in range(1, n + 1)])

    def trapz2d(tg2, tg1, p):
        return np.trapz(_trapz2(tg2, p, 1), tg1[:, 0], axis=0)

    p_n = psd / trapz2d(g2, g1, psd)

    m2 = trapz2d(g2, g1, p_n * g2)
    m1 = trapz2d(g2, g1, p_n * g1)
    c = np.zeros(4)

    q1 = [2, 1, 1, 0]
    q2 = [0, 1, 1, 2]

    for jj in [0, 1, 3]:
        c[jj] = np.squeeze(
            trapz2d(g2, g1,
                    p_n * (g2 - m2)**q1[jj] * (g1 - m1)**q2[jj]))

    c[2] = c[1]
    c = c.reshape((2, 2))
    u, s, v = svd(c)

    n3 = 3 * n

    g2_n3, g1_n3 = np.meshgrid(
        np.array([i for i in range(1, n3 + 1)]) - (n3 + 1) / 2,
        np.array([i for i in range(1, n3 + 1)]) - (n3 + 1) / 2)

    # Rotate PSDs and calculate integrals along the rotated PSDs
    theta = np.angle(u[0, 0] + 1j * u[0, 1])
    g2_rot = g2_n3[n:2 * n, n:2 * n] * np.cos(theta) - g1_n3[n:2 * n, n:2 *
                                                             n] * np.sin(theta)
    g1_rot = g1_n3[n:2 * n, n:2 * n] * np.cos(theta) + g2_n3[n:2 * n, n:2 *
                                                             n] * np.sin(theta)

    psd_rep = np.tile(psd, (3, 3))
    psd_rot = interpn((g2_n3[0, :], g2_n3[0, :]), psd_rep, (g1_rot, g2_rot))
    int_rot = _trapz2(g1, psd_rot, 0)

    theta2 = np.angle(u[1, 0] + 1j * u[1, 1])
    g2_rot = g2_n3[n:2 * n, n:2 * n] * np.cos(theta2) - g1_n3[
        n:2 * n, n:2 * n] * np.sin(theta2)
    g1_rot = g1_n3[n:2 * n, n:2 * n] * np.cos(theta2) + g2_n3[
        n:2 * n, n:2 * n] * np.sin(theta2)
    psd_rot2 = interpn((g2_n3[0, :], g2_n3[0, :]), psd_rep, (g1_rot, g2_rot))
    int_rot2 = _trapz2(g1, psd_rot2, 0)

    return int_rot, int_rot2
Esempio n. 28
0
 def test_invalid_xi_dimensions(self):
     # https://github.com/scipy/scipy/issues/16519
     points = [(0, 1)]
     values = [0, 1]
     xi = np.ones((1, 1, 3))
     msg = ("The requested sample points xi have dimension 3, but this "
            "RegularGridInterpolator has dimension 1")
     with assert_raises(ValueError, match=msg):
         interpn(points, values, xi)
Esempio n. 29
0
def generate_surface_image(image_pk):
    from neurovault.apps.statmaps.models import Image
    from scipy.io import loadmat
    import numpy.matlib as matlib
    from scipy.interpolate import interpn

    img = Image.objects.get(pk=image_pk)
    if img.target_template_image in ['GenericMNI', 'MNI152NLin2009cAsym'] and \
            img.data_origin == 'volume':
        img_vol = nib.load(img.file.path)
        data_vol = img_vol.get_data()
        if data_vol.ndim > 3:
            data_dim = data_vol.shape[3]  #number of time points
        else:
            data_dim = 1
        this_path = os.path.abspath(os.path.dirname(__file__))

        for hemi in ['lh', 'rh']:
            if hemi == 'lh':
                ras_coor = loadmat(os.path.abspath(os.path.join(this_path, "static", "anatomical",
                                                                "lh.avgMapping_allSub_RF_ANTs_MNI2fs.mat")))['ras']
            else:
                ras_coor = loadmat(os.path.abspath(os.path.join(this_path, "static", "anatomical",
                                                                "rh.avgMapping_allSub_RF_ANTs_MNI2fs.mat")))['ras']

            vox2ras = img_vol.get_sform()
            ras_centered = ras_coor - matlib.repmat(vox2ras[0:3, 3], ras_coor.shape[1], 1).T
            vox_coor = numpy.dot(numpy.linalg.inv(vox2ras[0:3, 0:3]), ras_centered)  # convert to voxel coordinates

            img_surf = nib.gifti.GiftiImage()
            for i in range(data_dim):
                if data_vol.ndim > 3:
                    data_curr = data_vol[:, :, :, i]
                    data_surf = interpn([range(data_vol.shape[0]), range(data_vol.shape[1]), range(data_vol.shape[2])],
                                        data_curr, vox_coor.T, 'linear')
                    data_surf_gifti = nib.gifti.GiftiDataArray(data_surf, 'NIFTI_INTENT_TIME_SERIES', 'NIFTI_TYPE_FLOAT32',
                                                               'ASCII')
                else:
                    data_curr = data_vol
                    data_surf = interpn([range(data_vol.shape[0]), range(data_vol.shape[1]), range(data_vol.shape[2])],
                                        data_curr, vox_coor.T, 'linear')
                    data_surf_gifti = nib.gifti.GiftiDataArray(data_surf, 'NIFTI_INTENT_NONE', 'NIFTI_TYPE_FLOAT32',
                                                               'ASCII')
                img_surf.add_gifti_data_array(data_surf_gifti)

            f = BytesIO()
            fmap = {'image': nib.FileHolder(fileobj=f), 'header': nib.FileHolder(fileobj=f)}
            img_surf.to_file_map(fmap)
            f.seek(0)
            content_file = ContentFile(f.read())
            if hemi == 'lh':
                img.surface_left_file.save("surface_%s_%s.gii" % (hemi, img.pk), content_file)
            else:
                img.surface_right_file.save("surface_%s_%s.gii" % (hemi, img.pk), content_file)
        img.save()
    print("Surface image generation done.")
Esempio n. 30
0
 def add_latlon(self, latmat=None, lonmat=None):
     if latmat is None:
         latmat = self.latmat
     if lonmat is None:
         lonmat = self.lonmat
     ijtup = (np.arange(lonmat.shape[0]),np.arange(lonmat.shape[1]))
     xyarr = self._obj[["ypos","xpos"]].values
     xyarr[xyarr<0] = 0
     self._obj["lon"] = interpn(ijtup, lonmat, xyarr).astype(np.float32)
     self._obj["lat"] = interpn(ijtup, latmat, xyarr).astype(np.float32)
Esempio n. 31
0
    def test_duck_typed_values(self):
        x = np.linspace(0, 2, 5)
        y = np.linspace(0, 1, 7)

        values = MyValue((5, 7))

        for method in ('nearest', 'linear'):
            v1 = interpn((x, y), values, [0.4, 0.7], method=method)
            v2 = interpn((x, y), values._v, [0.4, 0.7], method=method)
            assert_allclose(v1, v2)
Esempio n. 32
0
def convert_hintp(sio, bmap, conf, X3d, X2d, dlon, dlat, missing):
    """
    """
    nv3d = X3d.shape[0]
    nv2d = X2d.shape[0]
    nz = X3d.shape[1]
    ny = X3d.shape[2]
    nx = X3d.shape[3]

    dx = sio.dimdef['coor_g']['x'][sio.bufsize+1] - sio.dimdef['coor_g']['x'][sio.bufsize]
    dy = sio.dimdef['coor_g']['y'][sio.bufsize+1] - sio.dimdef['coor_g']['y'][sio.bufsize]

    lon = sio.readvar('lon')
    lat = sio.readvar('lat')
    lon_s = np.floor(np.min(lon) / dlon) * dlon
    lon_e = np.ceil(np.max(lon) / dlon) * dlon
    lat_s = np.floor(np.min(lat) / dlat) * dlat
    lat_e = np.ceil(np.max(lat) / dlat) * dlat

    lono1d = np.arange(lon_s, lon_e+1.e-6, dlon)
    lato1d = np.arange(lat_s, lat_e+1.e-6, dlat)
    nxo = len(lono1d)
    nyo = len(lato1d)
    lono, lato = np.meshgrid(lono1d, lato1d)

    X3dout = np.empty((nv3d, nz, nyo, nxo), dtype=X3d.dtype)
    X2dout = np.empty((nv2d, nyo, nxo), dtype=X2d.dtype)

    ri, rj = bmap(lono, lato)
    ri /= dx
    rj /= dy
    rij_interp = np.empty((nxo*nyo, 2), dtype=X3d.dtype)
    rij_interp[:,0] = rj.ravel()
    rij_interp[:,1] = ri.ravel()

    xic = np.arange(nx, dtype=X3d.dtype) + sio.bufsize
    xjc = np.arange(ny, dtype=X3d.dtype) + sio.bufsize

    missing = np.array(missing, dtype=X3d.dtype).ravel()[0]

    for iv in range(nv3d):
        for iz in range(nz):
            tmp2d = np.copy(X3d[iv,iz,:,:])
            tmp2d[tmp2d == missing] = np.nan
            X3dout[iv,iz,:,:] = interpn((xjc, xic), tmp2d, rij_interp, method='linear', bounds_error=False, fill_value=missing).reshape(nyo, nxo)

    for iv in range(nv2d):
        tmp2d = np.copy(X2d[iv,:,:])
        tmp2d[tmp2d == missing] = np.nan
        X2dout[iv,:,:] = interpn((xjc, xic), tmp2d, rij_interp, method='linear', bounds_error=False, fill_value=missing).reshape(nyo, nxo)

    return X3dout, X2dout, lon_s, lon_e, nxo, lat_s, lat_e, nyo
Esempio n. 33
0
    def interp(self, mask, spacing):
        '''
        :param mask: new mask in space of 7.5 mm around keypoint
        :param spacing :spacing after interpolation
        :return: mask after interpolation
        '''
        self.spacing = spacing
        # new grid in mm in range of 15 mm from 0-8 mm, with points on a cross in a ceneter of mask

        new_grid_range_x = np.arange(0, self.mask_shape / 2 + 1, 1)
        new_pixel_distance_x = np.sort(np.concatenate((-new_grid_range_x[1:], new_grid_range_x)))
        # new_pixel_distance_z = np.sort(np.concatenate((-new_grid_range_x[1:], new_grid_range_x)))
        # grid from mask in mm after rotate, spacing under consideration grid is irregular
        print(spacing)
        grid_range_x = np.arange(0, ((mask.shape[0] / 2.) * self.spacing[0]), self.spacing[0])
        grid_range_y = np.arange(0, ((mask.shape[1] / 2.) * self.spacing[1]), self.spacing[1])
        grid_range_z = np.arange(0, ((mask.shape[2] / 2.) * self.spacing[2]), self.spacing[2])

        pixel_distance_x = np.sort(np.concatenate((-grid_range_x[1:], grid_range_x)))
        pixel_distance_y = np.sort(np.concatenate((-grid_range_y[1:], grid_range_y)))
        pixel_distance_z = np.sort(np.concatenate((-grid_range_z[1:], grid_range_z)))
        print(pixel_distance_x.max(),pixel_distance_y.max(),pixel_distance_z.max())
        print(new_grid_range_x.max())
        x, y, z = np.meshgrid(new_pixel_distance_x, new_pixel_distance_x, new_pixel_distance_x, indexing='ij')
        interpolate_grid = np.array([x[:, :, :], y[:, :, :], z[:, :, :]]).T



        new_mask = interpn((pixel_distance_x, pixel_distance_y, pixel_distance_z ), mask, interpolate_grid,
                           bounds_error=True, fill_value=np.float32(0.0))

        return new_mask.T
Esempio n. 34
0
def atk3(dataobj, Eb, kx, ky, makegrid=True):

    if makegrid:
        if not (type(kx) == np.ndarray):
            kx = np.array([kx])
        if not (type(ky) == np.ndarray):
            ky = np.array([ky])
        if not (type(Eb) == np.ndarray):
            Eb = np.array([Eb])
        gridEb, gridkx, gridky = np.meshgrid(Eb, kx, ky)
    else:  # if providing own grid
        gridEb = Eb
        gridkx = kx
        gridky = ky

    gridth, gridphi = anglesfromk(
        gridkx,
        gridky,
        dataobj.EkatEF + gridEb,
        theta_m=dataobj.theta_m,
        phi_m=dataobj.phi_m,
        alpha0=dataobj.alpha0,
        theta0=dataobj.theta0,
        phi0=dataobj.phi0,
    )

    intgrid = np.array([gridEb, gridth, gridphi]).transpose((2, 1, 3, 0))

    return interpn(
        (dataobj.xaxis, dataobj.yaxis, dataobj.zaxis), dataobj.data, intgrid, bounds_error=False, fill_value=0.0
    )
Esempio n. 35
0
    def __call__(self, mask_size, sigma):
        """

        :param mask_size: size of mask in [mm] should depend on real size od
        :param sigma: sigma is a LoG parameter
        :return: kernel with new size depending on mask_size and spacing and new values
        """
        pixel_size_of_mask = ceil(mask_size / self.spacing[0])
        pixel_size_of_mask = pixel_size_of_mask + ((pixel_size_of_mask - 1) % 2)
        # object for getting log with appropriate sigma
        self.LoG2D = LoG2D(sigma)
        LoG_kernel = self.LoG2D.get_LoG()
        self.x, self.y = self.LoG2D.get_grid_x_y()
        # grid for interpolate value
        index_value = np.linspace(0, self.x.size - 1, pixel_size_of_mask).astype(dtype=np.int)
        index_value[-1] = self.x.size - 1
        max_value_index = np.unravel_index(LoG_kernel.argmax(), LoG_kernel.shape)[0]
        if not (max_value_index in index_value):
            index_value[-2] = max_value_index
            index_value.sort()

        #1D array
        one = np.ones((pixel_size_of_mask,)).astype(dtype=np.int)

        list_for_grid_temp = []
        for i in index_value:
            list_for_grid_temp.append(np.array([self.x[index_value], self.x[i * one]]).T)
        interpolate_grid = np.array(list_for_grid_temp)

        print(interpolate_grid)
        #interpolation
        kernel = interpn((self.x, self.y), LoG_kernel, interpolate_grid)

        return kernel
Esempio n. 36
0
def getElevation(rX, rY, rZ, coords, interp='linear'):
    """
    This function interpolates elevation from a regular grid to a cloud of points using SciPy interpolation.

    Parameters
    ----------
    variable : rX, rY, rZ
        Numpy arrays containing the X, Y & Z coordinates from the regular grid.

    variable : coords
        Numpy float-type array containing X, Y coordinates for the TIN nodes.

    variable : interp
        Define the interpolation technique as in SciPy interpn function. The default is 'linear'

    Return
    ----------
    variable: elev
        Numpy array containing the updated elevations for the local domain.
    """

    # Set new elevation to 0
    elev = numpy.zeros(len(coords[:,0]))

    # Get the TIN points elevation values using the regular grid dataset
    elev = interpn( (rX, rY), rZ, (coords[:,:2]), method=interp)

    return elev
Esempio n. 37
0
    def evaluate(self, *inputs):
        """
        Return the interpolated values at the input coordinates.

        Parameters
        ----------
        inputs : list of scalars or ndarrays
            Input coordinates. The number of inputs must be equal
            to the dimensions of the lookup table.
        """
        if isinstance(inputs, u.Quantity):
            inputs = inputs.value
        shape = inputs[0].shape
        inputs = [inp.flatten() for inp in inputs[: self.n_inputs]]
        inputs = np.array(inputs).T
        if not has_scipy:  # pragma: no cover
            raise ImportError("This model requires scipy >= v0.14")
        result = interpn(self.points, self.lookup_table, inputs,
                         method=self.method, bounds_error=self.bounds_error,
                         fill_value=self.fill_value)

        # return_units not respected when points has no units
        if (isinstance(self.lookup_table, u.Quantity) and
                not isinstance(self.points[0], u.Quantity)):
            result = result * self.lookup_table.unit

        if self.n_outputs == 1:
            result = result.reshape(shape)
        else:
            result = [r.reshape(shape) for r in result]
        return result
Esempio n. 38
0
File: freq.py Progetto: mattja/nsim
def _plot_cwt(ts, coefs, freqs, tsize=1024, fsize=512):
    """Plot time resolved power spectral density from cwt results
    Args:
      ts: the original Timeseries
      coefs:  continuous wavelet transform coefficients as calculated by cwt()
      freqs: list of frequencies (in Hz) corresponding to coefs.
      tsize, fsize: size of the plot (time axis and frequency axis, in pixels)
    """
    import matplotlib.style
    import matplotlib as mpl
    mpl.style.use('classic')
    import matplotlib.pyplot as plt
    from scipy import interpolate
    channels = ts.shape[1]
    fig = plt.figure()
    for i in range(channels):
        rect = (0.1, 0.85*(channels - i - 1)/channels + 0.1, 
                0.8, 0.85/channels)
        ax = fig.add_axes(rect)
        logpowers = np.log((coefs[:, :, i] * coefs[:, :, i].conj()).real)
        tmin, tmax = ts.tspan[0], ts.tspan[-1]
        fmin, fmax = freqs[0], freqs[-1]
        tgrid, fgrid = np.mgrid[tmin:tmax:tsize*1j, fmin:fmax:fsize*1j]
        gd = interpolate.interpn((ts.tspan, freqs), logpowers, 
                                 (tgrid, fgrid)).T
        ax.imshow(gd, cmap='gnuplot2', aspect='auto', origin='lower',
                   extent=(tmin, tmax, fmin, fmax))
        ax.set_ylabel('freq (Hz)')
    fig.axes[0].set_title(u'log(power spectral density)')
    fig.axes[channels - 1].set_xlabel('time (s)')
    fig.show()
Esempio n. 39
0
def CalibrationHa(z,oldLum,it):
	newLum = [0. for x in range((it.shape[0]))]
	oldpara = np.array([[0. for i in range(3)] for i in range(it.shape[0])])
	oldLF = np.array([0. for i in range(it.shape[0])])
	interpolatingSize =100
	for i in range(oldpara.shape[0]):
	        oldpara[i][0] = 1.37e-3
	        oldpara[i][2] = -1.35
	        if z[it[i]] <1.3 :oldpara[i][1] = 5.1e41*np.power((1+z[it[i]]),3.1)
	        if z[it[i]] >=1.3:oldpara[i][1] =6.8e42
	        oldLF[i] = LuminosityFunction(oldpara[i],oldLum[i])
	rangea = oldLF.copy()
	rangea.sort()
	rangea = rangea[rangea>0]
	grid = np.array([[0. for i in range(interpolatingSize)] for i in range(2)])
	mpgrid = mpmath.arange(mpmath.log10(rangea.min()),mpmath.log10(rangea.max()),(np.log10(rangea.max())-np.log10(rangea.min()))/interpolatingSize)
	grid[0] = np.ogrid[np.log10(rangea.min()):np.log10(oldLF.max()):interpolatingSize*1j]
	grid[1] = np.ogrid[0:6:interpolatingSize*1j]
	newLF = np.array([[0.for i in range(interpolatingSize)] for i in range(interpolatingSize)])
	for i in range(interpolatingSize):
		for j in range(interpolatingSize):
			newLF[i][j]= optimize.brentq(rootfinding,1e30,1e50,args=(luminosityParameterHa(grid[1][i]),mpgrid[j]))
	newLum = interpolate.interpn([grid[0],grid[1]],newLF,np.array([np.log10(oldLF),z[it]]).T,bounds_error=False,fill_value=0.0)
	newLum = np.power(10,newLum)
	return newLum
Esempio n. 40
0
    def eval(self, dx, dy, x0, y0, x_box=None, y_box=None):
        """Return the PSF at a certain grid position.

        :param float dx: x offset relative to PSF center
        :param float dy: y offset relative to PSF center
        :param float x0: x position on grid
        :param float y0: y position on grid

        :return: interpolated PSF
        :rtype: array
        """
        grid_points = self.grid_points
        grid_size = self.grid_size

        if x_box is None:
            x_box = self.x_box
        if y_box is None:
            y_box = self.y_box

        # get individual PSFs at the given offset
        values = np.empty((grid_size, grid_size, len(x_box), len(y_box)))
        for i, j in np.ndindex(grid_size, grid_size):
            values[i, j] = self.psf_arr[i, j].eval(x_box+dx, y_box+dy)

        # get the local PSF at the given grid position
        if self.grid_size == 1:
            return values[0, 0]
        else:
            return interpn(grid_points, values, (x0, y0), method="linear",
                           bounds_error=False, fill_value=None)[0]           
Esempio n. 41
0
def interpolatePoints(array, points, pointbounds):
    depth, rows, cols = array.shape

    y = np.linspace(pointbounds.bottom, pointbounds.top, rows)
    x = np.linspace(pointbounds.left, pointbounds.right, cols)

    return np.rot90(np.array(
        [interpolate.interpn((x, y), np.rot90(arr, k=3), points, bounds_error=False).astype(array.dtype) for arr in array]
        )[::-1], k=3)
Esempio n. 42
0
def shiftParticle(original,displacement,gridNumber,boxsize,boxmin):
	boxRange = np.arange(gridNumber)
	boxGrid = np.array([boxRange for i in range(3)])
	new = original.copy()
	new[0] = (original[0]-boxmin)*(gridNumber-1)/boxsize
	new[1] = (original[1]-boxmin)*(gridNumber-1)/boxsize
	new[2] = (original[2]-boxmin)*(gridNumber-1)/boxsize
	xinterp = interpolate.interpn(boxGrid,displacement[0],new.T,bounds_error=False,fill_value = 0).real
	yinterp = interpolate.interpn(boxGrid,displacement[1],new.T,bounds_error=False,fill_value = 0).real
	zinterp = interpolate.interpn(boxGrid,displacement[2],new.T,bounds_error=False,fill_value = 0).real
	print 'The rms displacement is'
	print np.sqrt(np.sum(xinterp*xinterp+yinterp*yinterp+zinterp*zinterp)/(3*xinterp.size()))
	print 'The first 10 interpolated value of x displacement is'
	print new[0].min(),new[0].max(),new[1].min(),new[1].max(),new[2].min(),new[2].max(),xinterp.max(),yinterp.max(),zinterp.max(),xinterp.min(),yinterp.min(),zinterp.min()
	new[0] = (new[0])*(boxsize)/(gridNumber-1)+boxmin+xinterp
	new[1] = (new[1])*(boxsize)/(gridNumber-1)+boxmin+yinterp
	new[2] = (new[2])*(boxsize)/(gridNumber-1)+boxmin+zinterp
	new = new.transpose()
	return new
Esempio n. 43
0
    def triangulation_compute_gradient(self, values, res=None, second=False):

        from scipy.interpolate import griddata
        from scipy.interpolate import interpn

        if res == None:
            res = int(1.0 / self.edge_lengths.max())

        resX=res
        resY=res

        space = 1.0 / (res-1.0)

        minX, minY = self.lagrSwarm.mesh.data.min(axis=0)
        maxX, maxY = self.lagrSwarm.mesh.data.max(axis=0)

        xs = np.linspace(minX, maxX, resX)
        ys = np.linspace(minY, maxY, resY)

        gradmesh = np.array(np.meshgrid(xs, ys)).transpose(2,1,0)
        gradvals = griddata( self.triangulation.points, values, gradmesh, method="cubic" ) # Cubic not available in 3D ...

        dFdx, dFdy      = np.gradient(gradvals.reshape(resX,resY), space, edge_order=1)

        if second:
            d2Fdx2, d2Fdxdy = np.gradient(dFdx.reshape(resX,resY), space, edge_order=1)
            d2Fdydx, d2Fdy2 = np.gradient(dFdy.reshape(resX,resY), space, edge_order=1)

        # Now map these back to the node points

        dFdxN   = interpn((xs,ys),   dFdx, self.triangulation.points,   method="linear")
        dFdyN   = interpn((xs,ys),  -dFdy, self.triangulation.points,   method="linear")

        if second:
            dF2dx2N = interpn((xs,ys),   d2Fdx2, self.triangulation.points, method="linear")
            dF2dy2N = interpn((xs,ys),   d2Fdy2, self.triangulation.points, method="linear")
            dF2dyxN = interpn((xs,ys),   d2Fdydx+d2Fdxdy, self.triangulation.points, method="linear")

        if not second:
            return dFdxN, dFdyN
        else:
            return dFdxN, dFdyN, dF2dx2N, dF2dyxN, dF2dy2N
Esempio n. 44
0
def generate_surface_image(image_pk):
    from neurovault.apps.statmaps.models import Image
    from scipy.io import loadmat
    from scipy.interpolate import interpn

    img = Image.objects.get(pk=image_pk)
    if img.target_template_image in ['GenericMNI', 'MNI152NLin2009cAsym'] and \
            img.data_origin == 'volume':
        img_vol = nib.load(img.file.path)
        data_vol = img_vol.get_data()
        if data_vol.ndim > 3:
            data_vol = data_vol[:, :, :, 0]  #number of time points
        this_path = os.path.abspath(os.path.dirname(__file__))

        for hemi in ['lh', 'rh']:
            ras_coor = loadmat(os.path.abspath(os.path.join(this_path, "static", "anatomical",
                                                                "%s.avgMapping_allSub_RF_ANTs_MNI2fs.mat" % hemi)))['ras']

            vox_coor = nib.affines.apply_affine(numpy.linalg.inv(img_vol.affine), ras_coor.T).T
            img_surf = nib.gifti.GiftiImage()

            if img.polymorphic_ctype.model == 'atlas' or (hasattr(img, 'map_type') and img.map_type in ['Pa', 'R']):
                method = 'nearest'
            else:
                method = 'linear'

            data_surf = interpn(points=[range(data_vol.shape[0]), range(data_vol.shape[1]), range(data_vol.shape[2])],
                                values=data_vol,
                                xi=vox_coor.T,
                                method=method,
                                bounds_error=False,
                                fill_value=0)
            # without turning nan's to zeros Connectome Workbench behaves weird
            data_surf[numpy.isnan(data_surf)] = 0

            # ASCII is the only encoding that produces outputs compatible with Connectome Workbench
            data_surf_gifti = nib.gifti.GiftiDataArray(data_surf, 'NIFTI_INTENT_NONE',
                                                       'NIFTI_TYPE_FLOAT32', 'ASCII')
            img_surf.add_gifti_data_array(data_surf_gifti)
            img_surf.meta.data.insert(0, nib.gifti.GiftiNVPairs('AnatomicalStructurePrimary',
                                                                {'lh': 'CortexLeft',
                                                                 'rh': 'CortexRight'}[hemi]))

            f = BytesIO()
            fmap = {'image': nib.FileHolder(fileobj=f), 'header': nib.FileHolder(fileobj=f)}
            img_surf.to_file_map(fmap)
            f.seek(0)
            content_file = ContentFile(f.read())
            if hemi == 'lh':
                img.surface_left_file.save("%s.%s.func.gii" % (img.pk, {'lh': 'L', 'rh': 'R'}[hemi]), content_file)
            else:
                img.surface_right_file.save("%s.%s.func.gii" % (img.pk, {'lh': 'L', 'rh': 'R'}[hemi]), content_file)
        img.save()
        print("Surface image generation done.")
Esempio n. 45
0
def test(model_name, iter_num, gpu_id, vol_size=(160,192,224), nf_enc=[16,32,32,32], nf_dec=[32,32,32,32,32,16,16,3]):
	"""
	test

	nf_enc and nf_dec
	#nf_dec = [32,32,32,32,32,16,16,3]
    # This needs to be changed. Ideally, we could just call load_model, and we wont have to
    # specify the # of channels here, but the load_model is not working with the custom loss...
    """  

	gpu = '/gpu:' + str(gpu_id)

	# Anatomical labels we want to evaluate
	labels = sio.loadmat('../data/labels.mat')['labels'][0]

	atlas = np.load('../data/atlas_norm.npz')
	atlas_vol = atlas['vol']
	atlas_seg = atlas['seg']
	atlas_vol = np.reshape(atlas_vol, (1,)+atlas_vol.shape+(1,))

	config = tf.ConfigProto()
	config.gpu_options.allow_growth = True
	config.allow_soft_placement = True
	set_session(tf.Session(config=config))

	# load weights of model
	with tf.device(gpu):
		net = networks.unet(vol_size, nf_enc, nf_dec)
		net.load_weights('../models/' + model_name +
                         '/' + str(iter_num) + '.h5')

	xx = np.arange(vol_size[1])
	yy = np.arange(vol_size[0])
	zz = np.arange(vol_size[2])
	grid = np.rollaxis(np.array(np.meshgrid(xx, yy, zz)), 0, 4)

	X_vol, X_seg = datagenerators.load_example_by_name('../data/test_vol.npz', '../data/test_seg.npz')

	with tf.device(gpu):
		pred = net.predict([X_vol, atlas_vol])

	# Warp segments with flow
	flow = pred[1][0, :, :, :, :]
	sample = flow+grid
	sample = np.stack((sample[:, :, :, 1], sample[:, :, :, 0], sample[:, :, :, 2]), 3)
	warp_seg = interpn((yy, xx, zz), X_seg[0, :, :, :, 0], sample, method='nearest', bounds_error=False, fill_value=0)

	vals, _ = dice(warp_seg, atlas_seg, labels=labels, nargout=2)
	print(np.mean(vals), np.std(vals))
Esempio n. 46
0
    def evaluate(self, *inputs):
        """
        Return the interpolated values at the input coordinates.

        Parameters
        ----------
        inputs : list of scalars or ndarrays
            Input coordinates. The number of inputs must be equal
            to the dimensions of the lookup table.
        """
        inputs = np.array(inputs[: self.n_inputs]).T
        if not has_scipy:
            raise ImportError("This model requires scipy >= v0.14")
        return interpn(self._points, self.lookup_table, inputs,
                       method=self.method, bounds_error=self.bounds_error,
                       fill_value=self.fill_value)
Esempio n. 47
0
    def build_OrographicRain_map(self, event, elev, inIDs):
        """
        Build rain map using SMith & Barstad (2004) model for a given period and perform interpolation from regular grid to
        unstructured TIN one.

        Parameters
        ----------
        float : event
            rain event number.

        float : elev
            Unstructured grid (TIN) Z coordinates.

        integer : inDs
            List of unstructured vertices contained in each partition.

        Return
        ----------
        variable: tinRain
            Numpy array containing the updated rainfall for the local domain.
        """

        # Interpolate elevation on regular grid
        distances, indices = self.tree.query(self.xyi, k=8)
        if len(elev[indices].shape) == 3:
            elev_vals = elev[indices][:,:,0]
        else:
            elev_vals = elev[indices]
        oelev = numpy.average(elev_vals,weights=(1./distances), axis=1)
        onIDs = numpy.where(distances[:,0] == 0)[0]
        if len(onIDs) > 0:
            oelev[onIDs] = elev[indices[onIDs,0]]
        oelev -= self.sealevel
        oelev = oelev.clip(0)
        regZ = numpy.reshape(oelev,(len(self.regX), len(self.regY)),order='F')
        # Use Smith & Barstad model
        rectRain = ORmodel.orographicrain.compute(regZ, self.dx, self.windx[event], self.windy[event],
            self.rmin[event], self.rmax[event], self.rbgd[event], self.nm[event], self.cw[event],
            self.hw[event], self.tauc[event], self.tauf[event])

        # Apply smoothing here
        smthRain = gaussian_filter(rectRain, sigma=3)

        # Interpolate
        tinRain = interpolate.interpn( (self.regX, self.regY), smthRain, self.tXY[inIDs,:], method='linear')

        return tinRain
Esempio n. 48
0
def downsample_axis(infile, outfile, axis, new_pixdim, method='linear'):
    """
    Downsamples a volume along a specified axis.

    Inputs
    ------
    infile : a filename from which to read data
    outfile : a filename to which to save data
    axis : the axis along which to downsample
    pixdim_ratio : the ratio by which to decrease pixdim.
    method : interpolation method ('linear' or 'nearest')
    """
    if type(new_pixdim) is str:
        new_pixdim = ast.literal_eval(new_pixdim)
    if type(axis) is str:
        axis = ast.literal_eval(axis)
    from scipy.interpolate import interpn
    nii = nib.load(infile)
    hdr = nii.get_header()
    aff = nii.get_affine()
    data = nii.get_data().astype('float32')

    in_coords = []
    out_coords = []
    affine_modifier = np.eye(3)
    for ax in [0,1,2]:
        in_coords.append(np.arange(256))
        if ax == axis:
            out_slice = slice(0, 252, new_pixdim)
            affine_modifier[ax,ax] = new_pixdim
        else:
            out_slice = slice(0, 256)
        out_coords.append(out_slice)

    out_grid = np.mgrid[out_coords].transpose(1,2,3,0)

    new_data = interpn(in_coords, data, out_grid, method=method, fill_value=None)
    hdr['pixdim'][1+axis] = new_pixdim
    # Multiply affine matrix by resampling matrix.
    # WARNING: no guarantees this'll work for non-axis-aligned images...
    aff[:3, :3] = np.dot(affine_modifier, aff[:3, :3])
    #new_aff = np.vstack((np.dot(affine_modifier, aff[:-1,:]), aff[-1:,:]))

    out = nib.Nifti1Image(new_data.astype('uint8'), header=hdr.copy(), affine=aff)
    out.update_header()
    out.to_filename(outfile)
Esempio n. 49
0
    def load_Tecto_map(self, time, inIDs):
        """
        Load vertical displacement map for a given period and perform interpolation from regular grid to unstructured TIN one.

        Parameters
        ----------
        float : time
            Requested time interval rain map to load.

        integer : inDs
            List of unstructured vertices contained in each partition.

        Return
        ----------
        variable: tinDisp
            Numpy array containing the updated displacement rate for the local domain.
        """

        events = numpy.where( (self.T_disp[:,1] - time) <= 0)[0]
        event = len(events)

        if not (time >= self.T_disp[event,0]) and not (time < self.T_disp[event,1]):
            raise ValueError('Problem finding the displacements map to load!')

        self.next_disp = self.T_disp[event,1]

        if self.injected_disps is not None or self.Map_disp[event] != None:
            if self.injected_disps is not None:
                dispMap = self.injected_disps
            else:
                dispMap = pandas.read_csv(str(self.Map_disp[event]), sep=r'\s+', engine='c', header=None, na_filter=False, \
                                   dtype=numpy.float, low_memory=False).values


            rectDisp = numpy.reshape(dispMap,(len(self.regX), len(self.regY)),order='F')
            tinDisp = interpolate.interpn( (self.regX, self.regY), rectDisp, self.tXY[inIDs,:], method='linear')
            dt = (self.T_disp[event,1] - self.T_disp[event,0])
            if dt <= 0:
                raise ValueError('Problem computing the displacements rate for event %d.'%event)
            tinDisp = tinDisp / dt
        else:
            tinDisp = numpy.zeros(len(self.tXY[:,0]), dtype=float)

        return tinDisp
Esempio n. 50
0
def lnlike(theta, spec, sn, mod, chigrid):
    mt, z, g, t = theta
    points = (mod.mt, mod.z, mod.g, mod.t)
    # Index the chisq grid
    # chi = bfobj.vchi
    chi = chigrid

    # Nearest neighbour
    chidx = [find_nearest(i, j) for i, j in zip(points, theta)]
    like_check = -(chi[chidx[0], chidx[1], chidx[2], chidx[3]])/2.
    # Interpolate the grid
    if like_check is np.ma.masked:
        like = -np.inf
    else:
        like = -(interpn(points, chi, theta, fill_value=np.inf))/2.

    if not np.isfinite(like) or np.abs(like) == 0.0:
        return -np.inf
    return np.sum(like)
Esempio n. 51
0
    def get_Rain(self, time, elev, inIDs):
        """
        Get rain value for a given period and perform interpolation from regular grid to unstructured TIN one.

        Parameters
        ----------
        float : time
            Requested time interval rain map to load.

        float : elev
            Unstructured grid (TIN) Z coordinates.

        integer : inDs
            List of unstructured vertices contained in each partition.

        Return
        ----------
        variable: tinRain
            Numpy array containing the updated rainfall for the local domain.
        """

        events = numpy.where( (self.T_rain[:,1] - time) <= 0)[0]
        event = len(events)

        if not (time >= self.T_rain[event,0]) and not (time < self.T_rain[event,1]):
            raise ValueError('Problem finding the rain map to load!')

        if self.orographic[event]:
            tinRain = self.build_OrographicRain_map(event, elev, inIDs)
            self.next_rain = min(time + self.ortime[event], self.T_rain[event,1])
        elif self.Map_rain[event] == None:
            tinRain = numpy.zeros(len(self.tXY[inIDs,0]), dtype=float)
            tinRain = self.rainVal[event]
            self.next_rain = self.T_rain[event,1]
        else:
            rainMap = pandas.read_csv(str(self.Map_rain[event]), sep=r'\s+', engine='c',
                               header=None, na_filter=False, dtype=numpy.float, low_memory=False)

            rectRain = numpy.reshape(rainMap.values,(len(self.regX), len(self.regY)),order='F')
            tinRain = interpolate.interpn( (self.regX, self.regY), rectRain, self.tXY[inIDs,:], method='linear')
            self.next_rain = self.T_rain[event,1]

        return tinRain
Esempio n. 52
0
    def interpolate(self, *vecs, **kwargs):
        """Interpolate the function at given points. The points are either
        provided as a large array with each row consisting of one point
        or as a tuple of vectors each defining one coordinate of the
        interpolation points. If `as_grid` is True, each combination of
        coordinates will be used (each point on the grid defined by the
        coordinates). Additional keyword args are passed to
        scipy.interpolate.interpn.
        TODO: write up properly"""

        as_grid = kwargs.get('as_grid', False)
        if as_grid:
            coo = Coord(*vecs)
            vecs = coo.asarr()

        method = kwargs.get('method', 'linear')
        bounds_error = kwargs.get('bounds_error', False)
        fill_value = kwargs.get('fill_value', 0.0)

        return interpn(self.coord.vecs, self.fvals, vecs, method=method,
                       bounds_error=bounds_error, fill_value=fill_value)
Esempio n. 53
0
File: grid.py Progetto: zerothi/sisl
    def interp(self, shape, *args, **kwargs):
        """ Returns an interpolated version of the grid

        Parameters
        ----------
        shape : int, array_like
            the new shape of the grid
        *args, **kwargs :
            optional arguments passed to the interpolation algorithm
            The interpolation routine is `scipy.interpolate.interpn`
        """
        # Get current grid spacing
        dold = (
            np.linspace(0, 1, self.shape[0]),
            np.linspace(0, 1, self.shape[1]),
            np.linspace(0, 1, self.shape[2])
        )

        # Interpolate
        from scipy.interpolate import interpn

        # Create new grid
        grid = self.__class__(shape, bc=np.copy(self.bc), sc=self.sc.copy())
        # Clean-up to reduce memory
        del grid.grid
        
        # Create new mesh-grid
        dnew = np.vstack(np.meshgrid(
            np.linspace(0, 1, shape[0]),
            np.linspace(0, 1, shape[1]),
            np.linspace(0, 1, shape[2])))
        dnew.shape = (-1, 3)
   
        grid.grid = interpn(dold, self.grid, dnew, *args, **kwargs)
        # immediately delete the dnew (which is VERY large)
        del dold, dnew
        # Ensure that the grid has the correct shape
        grid.grid.shape = tuple(shape)

        return grid
Esempio n. 54
0
    def __call__(self, mask_size, sigma):
        """

        :param mask_size: size of mask in [mm] should depend on real size od
        :param sigma: sigma is a LoG parameter
        :return: kernel with new size depending on mask_size and spacing and new values
        """
        pixel_size_of_mask = ceil(mask_size / self.spacing[0])
        pixel_size_of_mask = pixel_size_of_mask + ((pixel_size_of_mask - 1) % 2)
        pixel_size_of_mask_z = ceil(mask_size / self.spacing[2])
        pixel_size_of_mask_z = pixel_size_of_mask_z + ((pixel_size_of_mask_z - 1) % 2)
        # object for getting log with appropriate sigma

        self.LoG3D = LoG3D(sigma)
        LoG_kernel = self.LoG3D.get_LoG()
        self.x, self.y, self.z = self.LoG3D.get_grid_x_y_z()
        index_value = np.linspace(0, self.x.size - 1, pixel_size_of_mask).astype(dtype=np.int)
        index_value_z = np.linspace(0, self.x.size - 1, pixel_size_of_mask_z).astype(dtype=np.int)
        index_value[-1] = self.x.size - 1
        max_value_index = np.unravel_index(LoG_kernel.argmax(), LoG_kernel.shape)[0]
        index_value_z[-1] = self.x.size - 1
        max_value_index_z = np.unravel_index(LoG_kernel.argmax(), LoG_kernel.shape)[2]
        if not (max_value_index in index_value):
            index_value[-2] = max_value_index
            index_value.sort()
        if not (max_value_index_z in index_value_z):
            index_value_z[-2] = max_value_index_z
            index_value_z.sort()
        one = np.ones(pixel_size_of_mask_z).astype(dtype=np.int)
        list_end = []

        for j in index_value:
            list_for_grid_temp = []
            for i in index_value:
                list_for_grid_temp.append(np.array([one * self.x[j], one * self.y[i], self.z[index_value_z]]).T)
            list_end.append(list_for_grid_temp)
        interpolate_grid = np.array(list_end)
        print(interpolate_grid[1,0,0])
        kernel = interpn((self.x, self.y, self.z), LoG_kernel, interpolate_grid)
Esempio n. 55
0
    def interp(self, in_data, inverse=False, fwd_pe=True):
        dshape = tuple(in_data.shape)
        gridxyz = self._fmapxyz.reshape((dshape[0], dshape[1], dshape[2], -1))

        x = gridxyz[:, 0, 0, 0]
        y = gridxyz[0, :, 0, 1]
        z = gridxyz[0, 0, :, 2]

        targets = self._fmapxyz.copy()

        if inverse:
            factor = 1.0 if fwd_pe else -1.0
            targets[:, self._pedir] += factor * \
                self._inverted[tuple(self._fmapijk.T)]
        else:
            targets[:, self._pedir] += self._smoothed[tuple(self._fmapijk.T)]

        interpolated = np.zeros_like(self._data)
        interpolated[tuple(self._fmapijk.T)] = interpn(
            (x, y, z), in_data, [tuple(v) for v in targets],
            bounds_error=False, fill_value=0)

        return nb.Nifti1Image(interpolated, self._fmapnii.affine, self._fmapnii.header)
Esempio n. 56
0
def interp_grid_to_spherical(grid, radii, num_phi, num_theta, 
                             grid_origin=(0,0,0), return_spherical_coords=False):
    """
    Compute interpolated values in 3D spherical coordinates from a 3D square 
    grid. The interpolated values lie equally spaced along the azumithal and
    polar directions for a series of concentric spheres.
    
    Interpolation used is linear.
    
    Parameters
    ----------
    grid : np.ndarray, float
        The 3D square grid of values definiting a scalar field
    radii : np.ndarray, float
        The radial values of the interpolant grid
    num_theta : int
        The number of points along the polar angle to interpolate
    num_phi : int
        The number of points along the azmuthal angle to interpolate
    grid_origin : 3-tuple, floats
        The origin of the grid, which forms the center of the interpolant 
        spheres
        
    Optional Parameters
    -------------------
    return_spherical_coords : bool
        If true, the spherical coordiantes used are also returned as an N x 3
        array.
        
    Returns
    -------
    interpolated : np.ndarray
        A 3D array of the interpolated values. The dimensions are 
        (radial, polar [theta], azmuthal [phi]).
    """
    
    # find the cartesian x,y,z values for each interpolant
    xi = np.zeros( (len(radii) * num_theta * num_phi, 3), dtype=grid.dtype )
    
    thetas = np.arange(0.0, 2.0*np.pi, 2.0*np.pi / num_theta)
    phis = np.arange(0.0, np.pi, np.pi / num_phi)
    assert len(thetas) == num_theta, 'thetas len mistmatch %d %d' % (len(thetas), num_theta)
    assert len(phis) == num_phi, 'phi len mistmatch %d %d' % (len(phis), num_phi)
    
    # the repeat rate will be important for the reshape, below
    r = np.repeat(radii, num_theta * num_phi)            # radius, slowest
    t = np.repeat( np.tile(thetas, num_phi), len(radii)) # theta
    p = np.tile(phis, len(radii) * num_theta)            # phi, fastest
    
    xi[:,0] = r * np.sin(t) * np.cos(p) # x
    xi[:,1] = r * np.sin(t) * np.sin(p) # y
    xi[:,2] = r * np.cos(t)             # z
    
    xi += np.array(grid_origin)[None,:]
    
    # compute an interpolator for the rectangular grid
    gi = [ np.arange(l) for l in grid.shape ]
    interpolated = interpn(gi, grid, xi, bounds_error=False)
    
    res = interpolated.reshape(len(radii), num_theta, num_phi)
    
    if return_spherical_coords:
        rtp = np.array([r, t, p])
        return res, rtp
    else:
        return res
Esempio n. 57
0
 def interpolation_handle(self, desired_coordinates):
     return si.interpn(tuple(self.input_data), self.output_data, desired_coordinates)
Esempio n. 58
0
    def load_Disp_map(self, time, tXY, inIDs, strata=False, sXY=None, insIDs=None):
        """
        Load 3D displacements map for a given period and perform interpolation from regular grid to unstructured TIN one.

        Parameters
        ----------
        float : time
            Requested time interval rain map to load.

        float : tXY
            Unstructured grid (TIN) XY coordinates.

        integer : inIDs
            List of unstructured vertices contained in each partition.

        boolean : strata
            Stratigraphic module flag.

        float : sXY
            Stratigraphic regular grid XY coordinates.

        integer : insIDs
            List of stratigraphic vertices contained in each partition.
        """

        # Initialise MPI communications
        comm = mpi.COMM_WORLD
        rank = comm.Get_rank()
        size = comm.Get_size()

        self.tXY = tXY
        totPts = len(tXY[:,0])
        dispX = numpy.zeros(totPts, dtype=float)
        dispY = numpy.zeros(totPts, dtype=float)
        dispZ = numpy.zeros(totPts, dtype=float)
        dpXY = tXY[inIDs,:]

        if strata:
            totsPts = len(sXY[:,0])
            sdispX = numpy.zeros(totsPts, dtype=float)
            sdispY = numpy.zeros(totsPts, dtype=float)
            sdispZ = numpy.zeros(totsPts, dtype=float)
            dpsXY = sXY[insIDs,:]

        events = numpy.where( (self.T_disp[:,1] - time) <= 0)[0]
        event = len(events)

        if not (time >= self.T_disp[event,0]) and not (time < self.T_disp[event,1]):
            raise ValueError('Problem finding the 3D displacements map to load!')

        if self.time3d > 0.:
            if time + self.time3d > self.T_disp[event,1]:
                self.next_disp = self.T_disp[event,1]
            else:
                self.next_disp = self.time3d + time
        else:
            self.next_disp = self.T_disp[event,1]

        update = False
        if self.injected_disps is not None or self.Map_disp[event] != None:
            dispX.fill(-1.e6)
            dispY.fill(-1.e6)
            dispZ.fill(-1.e6)

            if self.injected_disps is not None:
                dvals = self.injected_disps
            else:
                disps = pandas.read_csv(str(self.Map_disp[event]), sep=r'\s+', engine='c', header=None, na_filter=False, \
                            dtype=numpy.float, low_memory=False)
                dvals = disps.values


            disprX = numpy.reshape(dvals[:,0],(len(self.regX), len(self.regY)),order='F')
            disprY = numpy.reshape(dvals[:,1],(len(self.regX), len(self.regY)),order='F')
            disprZ = numpy.reshape(dvals[:,2],(len(self.regX), len(self.regY)),order='F')
            dispX[inIDs] = interpolate.interpn( (self.regX, self.regY), disprX, dpXY, method='linear')
            dispY[inIDs] = interpolate.interpn( (self.regX, self.regY), disprY, dpXY, method='linear')
            dispZ[inIDs] = interpolate.interpn( (self.regX, self.regY), disprZ, dpXY, method='linear')
            comm.Allreduce(mpi.IN_PLACE, dispX, op=mpi.MAX)
            comm.Allreduce(mpi.IN_PLACE, dispY, op=mpi.MAX)
            comm.Allreduce(mpi.IN_PLACE, dispZ, op=mpi.MAX)
            update = True

            if strata:
                sdispX.fill(-1.e6)
                sdispY.fill(-1.e6)
                sdispX[insIDs] = interpolate.interpn( (self.regX, self.regY), disprX, dpsXY, method='linear')
                sdispY[insIDs] = interpolate.interpn( (self.regX, self.regY), disprY, dpsXY, method='linear')
                comm.Allreduce(mpi.IN_PLACE, sdispX, op=mpi.MAX)
                comm.Allreduce(mpi.IN_PLACE, sdispY, op=mpi.MAX)

        if self.time3d > 0. and (self.injected_disps is not None or self.Map_disp[event] != None):
            rate = (self.next_disp - time) / (self.T_disp[event,1] - self.T_disp[event,0])
            assert rate > 0
            dispX = dispX * rate
            dispY = dispY * rate
            dispZ = dispZ * rate
            if strata:
                sdispX = sdispX * rate
                sdispY = sdispY * rate

        self.dispX = dispX
        self.dispY = dispY
        self.dispZ = dispZ

        if strata:
            return update, sdispX, sdispY
        else:
            return update
Esempio n. 59
0
#verts0, faces = pg.isosurface(absw,f_isovalue)#the verts are depending on ogrid index nor ogrid value
verts0, faces = pg.isosurface(realwf,f_isovalue)
verts1, facesm = pg.isosurface(realwf,-f_isovalue)
#verts0, faces = pg.isosurface(absw,f_isovalue)
#isophase0 = linterp3d(wphase,verts0)

xx=numpy.linspace(0,50,51)
yy=numpy.linspace(0,50,51)
zz=numpy.linspace(0,50,51)
from scipy.interpolate import griddata
from scipy.interpolate import RegularGridInterpolator
from scipy.interpolate import interpn
#inter_function = griddata((xx,yy,zz),wphase)
#isophase = griddata((xx,yy,zz),wphase,verts0,method='linear')
#inter_function = RegularGridInterpolator((xx,yy,zz),wphase)
isophase = interpn((xx,yy,zz),wphase,verts0,method = 'linear')#both RegularGridInterpolator and interpn can do the interpolation
isophasem = interpn((xx,yy,zz),wphase,verts1,method = 'linear')
#isophase = inter_function(verts0)
#isophasem = inter_function(verts1)
#numpy.savetxt('isop',isophase)

verts = verts0*2-(50,50,50)
N_vertices = int(verts.size/3)
N_triangles = int(faces.size/3)
N_isophase = int (isophase.size)

vertsm = verts1*2-(50,50,50)
N_verticesm = int(vertsm.size/3)
N_trianglesm = int(facesm.size/3)
N_isophasem = int (isophasem.size)
Esempio n. 60
0
    if z[it[i]] >= 1.3:
        oldpara[i][1] = 6.8e42
    oldLF[i] = LF.LuminosityFunction(oldpara[i], lumHa[i])
grid = np.array([[0.0 for i in range(interpolatingSize)] for i in range(2)])
mpgrid = mpmath.arange(
    oldLF[oldLF < -5].max(), oldLF.max(), (oldLF.max() - oldLF[oldLF < -5].max()) / interpolatingSize
)
grid[1] = np.ogrid[0 : 6 : interpolatingSize * 1j]
newLF = np.array([[0.0 for i in range(interpolatingSize)] for i in range(interpolatingSize)])
for i in range(interpolatingSize):
    for j in range(interpolatingSize):
        newLF[i][j] = optimize.brentq(
            LF.rootfinding, 1e30, 1e50, args=(LF.luminosityParameterHa(grid[1][i]), mpgrid[j])
        )
z = (z + 1) * (5007.0 / 6563.0) - 1
newLum = interpolate.interpn([grid[1], mpgrid], newLF, np.array([z[it], oldLF]).T, bounds_error=False, fill_value=0.0)
for i in np.where(oldLF < -5)[0]:
    newLum[i] = optimize.brentq(LF.rootfinding, 1e30, 1e50, args=(LF.luminosityParameterHa(z[it][i]), oldLF[i]))
z = (z + 1) * (6563.0 / 5007.0) - 1

Ha[it] = newLum / (4 * np.pi * (dl ** 2))

print "Calibrating OIIIb line"
newLumO3b = [0.0 for x in range((it.shape[0]))]
grid = np.array([[0.0 for i in range(interpolatingSize)] for i in range(2)])
mpgrid = mpmath.linspace(oldLF[oldLF < -2.7].max(), oldLF.max(), interpolatingSize)
grid[1] = np.ogrid[0 : 6 : interpolatingSize * 1j]
newLF = np.array([[0.0 for i in range(interpolatingSize)] for i in range(interpolatingSize)])
for i in range(interpolatingSize):
    for j in range(interpolatingSize):
        newLF[i][j] = optimize.brentq(