Exemplo n.º 1
0
def test_dblint():
    # Basic test to see it runs and gives the correct result on a trivial
    # problem.  Note that `dblint` is not exposed in the interpolate namespace.
    x = np.linspace(0, 1)
    y = np.linspace(0, 1)
    xx, yy = np.meshgrid(x, y)
    rect = interpolate.RectBivariateSpline(x, y, 4 * xx * yy)
    tck = list(rect.tck)
    tck.extend(rect.degrees)

    assert_almost_equal(dblint(0, 1, 0, 1, tck), 1)
    assert_almost_equal(dblint(0, 0.5, 0, 1, tck), 0.25)
    assert_almost_equal(dblint(0.5, 1, 0, 1, tck), 0.75)
    assert_almost_equal(dblint(-100, 100, -100, 100, tck), 1)
Exemplo n.º 2
0
def correct_slitshift2(data, slitshift, mask=None, isreverse=False):
    '''
    Applies horizontal shift to correct tilt in data.

    Parameters
    ----------


    Returns
    -------


    History
    -------
    Written by Kevin Stevenson        June 2012

    '''
    # Create slit-shift-corrected indices
    ny, nx     = np.shape(data)
    xgrid, ygrid = np.meshgrid(range(nx), range(ny))
    if isreverse:
        xgrid    = (xgrid.T - slitshift).T
    else:
        xgrid    = (xgrid.T + slitshift).T
    # Interpolate reduced data to account for slit shift
    spline     = spi.RectBivariateSpline(range(ny), range(nx), data, kx=3, ky=3)
    # Evaluate interpolated array within region containing data
    cordata    = spline.ev(ygrid.flatten(), xgrid.flatten()).reshape(ny,nx)
    # Do the same for the bad pixel mask
    if mask != None:
        spline     = spi.RectBivariateSpline(range(ny), range(nx), mask, kx=3, ky=3)
        #cormask    = np.round(spline.ev(ygrid.flatten(), xgrid.flatten()).reshape(ny,nx),2).astype(int)
        cormask    = spline.ev(ygrid.flatten(), xgrid.flatten()).reshape(ny,nx)
        cormask[np.where(cormask >= 0.9)] = 1
        return cordata, cormask.astype(int)
    else:
        return cordata
Exemplo n.º 3
0
    def _updatePlasmaPsi(self, plasma_psi):
        """
        Sets the plasma psi data, updates spline interpolation coefficients.
        Also updates:

        self.mask        2D (R,Z) array which is 1 in the core, 0 outside
        self.psi_axis    Value of psi on the magnetic axis
        self.psi_bndry   Value of psi on plasma boundary
        """
        self.plasma_psi = plasma_psi

        # Update spline interpolation
        self.psi_func = interpolate.RectBivariateSpline(
            self.R[:, 0], self.Z[0, :], plasma_psi)

        # Update the locations of the X-points, core mask, psi ranges.
        # Note that this may fail if there are no X-points, so it should not raise an error
        # Analyse the equilibrium, finding O- and X-points
        psi = self.psi()
        opt, xpt = critical.find_critical(self.R, self.Z, psi)
        if opt:
            self.psi_axis = opt[0][2]

            if xpt:
                self.psi_bndry = xpt[0][2]
                self.mask = critical.core_mask(self.R, self.Z, psi, opt, xpt)

                # Use interpolation to find if a point is in the core.
                self.mask_func = interpolate.RectBivariateSpline(
                    self.R[:, 0], self.Z[0, :], self.mask)
            elif self._applyBoundary is fixedBoundary:
                # No X-points, but using fixed boundary
                self.psi_bndry = psi[0, 0]  # Value of psi on the boundary
                self.mask = None  # All points are in the core region
            else:
                self.psi_bndry = None
                self.mask = None
Exemplo n.º 4
0
def MakePlotSingleAndDoubleIonizationEnergyDistribution(filename):
    figRatio = 16.0 / 12.0
    offset = figRatio
    gradientFile = "gradient_uib.txt"

    f = tables.openFile(filename, "r")
    try:
        energyDouble = array(f.root.dpde_double._v_attrs.energy)
        dpdeDouble = array(f.root.dpde_double)

        energySingle = array(f.root.dpde_single._v_attrs.energy)
        dpdeSingle = array([f.root.dpde_single[:]])

    finally:
        f.close()

    #2d interpolation
    #newEnergies = linspace(energyDouble[0], energyDouble[-1], 500)
    newEnergies = energySingle[:]
    interpolator = interpolate.RectBivariateSpline(energyDouble,
                                                   energyDouble,
                                                   dpdeDouble,
                                                   kx=3,
                                                   ky=3)
    dpdeDoubleNew = interpolator(newEnergies, newEnergies)

    #load color map
    cmap = LoadColormap(gradientFile, reverse=True)
    figure()

    #plot single dpde
    ax1 = axes([0.1, 0.12, 0.02, 0.8])
    ax1.set_xticks(())
    ax1.pcolormesh(r_[0:2], energySingle, transpose(dpdeSingle), cmap=cmap)
    ylabel("Energy (a.u.)")

    ax2 = axes([0.12, 0.1, 0.8, 0.02])
    ax2.set_yticks(())
    ax2.pcolormesh(energySingle, r_[0:2], dpdeSingle, cmap=cmap)
    xlabel("Energy (a.u.)")

    ax3 = axes([0.13, 0.13, 0.79, 0.79])
    ax3.pcolormesh(newEnergies, newEnergies, dpdeDoubleNew, cmap=cmap)
    ax3.set_xticks(())
    ax3.set_yticks(())
    #xlabel("Energy (a.u.)")
    #ylabel("Energy (a.u.)")

    show()
Exemplo n.º 5
0
def estimate_distances(wds, radii, blurry_stacks, mask, focused_img, scale):
    print('Estimating distances of foreground pixels...')
    blurry_stacks = np.array(blurry_stacks, np.float32)

    H = blurry_stacks.shape[2]
    W = blurry_stacks.shape[3]
    min_wd = np.min(wds)
    max_wd = np.max(wds)
    init = np.mean(wds)

    depth_map = VERY_FAR * np.ones([H, W], np.float32)
    conf_map = -np.ones([H, W], np.float32)
    total_pixels = np.count_nonzero(mask)
    count = 0
    for y in range(H):
        for x in range(W):
            if mask[y, x] == 0:
                continue
            count += 1
            if count % 1000 == 0:
                print('\tMinimizing integrations for #%d/%d...' %
                      (count, total_pixels))

            ssd = blurry_stacks[:, :, y, x]
            spline = interpolate.RectBivariateSpline(wds,
                                                     radii,
                                                     ssd,
                                                     kx=1,
                                                     ky=1)
            energy_func = lambda d: sum(spline(wd, d / wd)[0, 0] for wd in wds)
            sol = optimize.minimize_scalar(energy_func, \
                bounds=[min_wd, max_wd], method='bounded', tol=1.0)
            depth_map[y, x] = sol.x

            #   plot_x = np.linspace(min_wd, max_wd, num=100)
            #   plot_y = [energy_func(x) for x in plot_x]
            #   plt.plot(plot_x, plot_y)
            #   plt.savefig('./doll_data_out/sampleplot_%d_%d.png' % (x, y))
            #   plt.clf()
            #   viz.visualize_grid_map(ssd, wds, radii, \
            #       outpath='./doll_data_out/%d_%d_%.2f.png' % (x, y, sol.x))

            conf = misc.derivative(energy_func, sol.x, dx=2.0, n=2, order=5)
            conf_map[y, x] = conf / sol.fun

            if count % 100000 == 0:
                output_results(depth_map, conf_map, mask, focused_img, \
                    './doll_data_out/', raw=True, output_model=False)
    return depth_map, conf_map
Exemplo n.º 6
0
    def Apply(self, frame):
        if not self.enabled:
            return
        self.logger.debug("Apply")

        bins = (self._binsX, self._binsY)

        # Find bin's central coordinates
        coordsMatX = np.nanmean(Bin2dData(frame.coords[0], bins), axis=(1, 3))
        coordsMatY = np.nanmean(Bin2dData(frame.coords[1], bins), axis=(1, 3))

        # Calc percentile over self._spanT frames
        # TODO: performance issue if _spanT large
        framesFrom = max(0, frame.nr - int(self._spanT / 2))
        framesTo = min(framesFrom + self._spanT, len(frame._fseries))

        binnedData = None
        for frameNr in range(framesFrom, framesTo):
            # TODO: if not first preprocessor
            dataF = frame._fseries.GetOriginalFrame(frameNr).data
            _binnedData = Bin2dData(dataF, bins)

            if binnedData is None:
                binnedData = _binnedData
            else:
                binnedData = np.append(binnedData, _binnedData, axis=1)

        percentileMat = np.nanpercentile(binnedData,
                                         self._precentile,
                                         axis=(1, 3))

        # Interpolate plane
        #x, y, z = 1e9 * coordsMatX.ravel(), 1e9 * coordsMatY.ravel(), percentileMat.ravel()
        #tck = interpolate.bisplrep(x, y, z, s = self._smoothing)
        #interpolatedBg = interpolate.bisplev(1e9 * xc, 1e9 * yc, tck)

        xc, yc = frame.coords
        interp = interpolate.RectBivariateSpline(coordsMatX[:, 0],
                                                 coordsMatY[0, :],
                                                 percentileMat,
                                                 s=self._smoothing)
        interpolatedBg = interp.ev(xc, yc)

        # Result
        frame.data -= interpolatedBg
        frame._interpolatedBg = interpolatedBg  # TODO:

        self.logger.debug("Apply done")
        return frame
Exemplo n.º 7
0
    def Gen_compositions(self, r, d):
        """ in the interpolation function "Z" should have the shape(x.size,y.size), because the istopes arrays have
        the shape (decay time steps, irradiation time steps), the decay_days is the first argument in the interpolation
        class, but the arguments order is flipped in the outer function (Gen_compositions) for more convenience """

        compositions = []

        for i in range(36):
            Interp = interpolate.RectBivariateSpline(self.Decay_days,
                                                     self.Irradiation_days,
                                                     self.isotopes[i],
                                                     kx=1,
                                                     ky=1)
            compositions.append(Interp(d, r)[0][0])
        return compositions
Exemplo n.º 8
0
    def __init__(self, x, y, z, ofrv=None, type='linear'):
        self.type = type

        if self.type == 'cubic':
            self.interpolant = spi.RectBivariateSpline(x, y, z)
        elif self.type == 'linear':
            self.interpolant = spi.interp2d(y, x, z, kind='linear')
        else:
            raise ValueError('Interpolant type unknown: "%s"' % type)

        self.x_range = (x[0], x[-1])
        self.y_range = (y[0], y[-1])

        # Out of range value:
        self.ofrv = ofrv
Exemplo n.º 9
0
    def __init__(self,galaxy_model):
        if galaxy_model == 'Schober':
            self.modelGamma="Galaxy_Models/Gamma_Schober_normal.dat" #absorption model, model: [Energy [eV], redshift, Gamma [s-1]]
            self.modelChi = "Galaxy_Models/norm_chi_Schober_normal.dat" #photon-photon dispersion model
            
            #Galaxy evolution
            def evo(self,zz):#Redshift evolution of host galaxies
                k1=3./5.
                k2=14./15.
                zm=5.4
                return k2*np.exp(k1*(zz-zm))/(k2-k1+k1*np.exp(k2*(zz-zm)))*(1+zz)**3
            self.evo = evo 

        if galaxy_model == 'Yuksel':
            self.modelGamma="Galaxy_Models/Gamma_Schober_normal_YukselGRB.dat" #absorption model, model: [Energy [eV], redshift, Gamma [s-1]]
            self.modelChi = "Galaxy_Models/norm_chi_Schober_normal_YukselGRB.dat" #photon-photon dispersion model
            
            #Galaxy evolution
            def evo(self,zz):#Redshift evolution of host galaxies
                return ((1.+zz)**(-34.)+((1.+zz)/5160.64)**3+((1.+zz)/9.06)**35.)**(-1./10.)
            self.evo = evo

        #Absorption
        self.GammaDataRaw=np.loadtxt(self.modelGamma) #load data
        self.enLDataG=np.asarray(np.log10(sorted(list(set(self.GammaDataRaw[:,0])))))-12 #extract energy data. Convert to logarithmic form and to TeV
        self.zzDataG=np.asarray(sorted(list(set(self.GammaDataRaw[:,1])))) #redshift data
        self.GDataG=self.GammaDataRaw[:,2].reshape(len(self.enLDataG),len(self.zzDataG)) #reshape Gamma
        self.GammaInt=interpolate.RectBivariateSpline(self.enLDataG,self.zzDataG, self.GDataG,kx=1,ky=1) #Interpolate with linear spline

        #Dispersion
        self.DispDataRaw=np.loadtxt(self.modelChi) #load data
        self.enLDataD=np.asarray(np.log10(sorted(list(set(self.DispDataRaw[:,0])))))-12 #extract energy data. Convert to logarithmic form and to TeV
        #second entry redhift
        self.zzDataD=np.asarray(sorted(list(set(self.DispDataRaw[:,1])))) #redshift data
        self.DDataD=self.DispDataRaw[:,2].reshape(len(self.enLDataD),len(self.zzDataD))
        self.DispInt=interpolate.RectBivariateSpline(self.enLDataD,self.zzDataD,self.DDataD,kx=1,ky=1) #Interpolate with linear spline
Exemplo n.º 10
0
	def adj(self,R,cor):
		N=self.Pgl.N
		Nproj=self.Pgl.Nproj
		Ntheta=self.Pgl.Ntheta
		Nrho=self.Pgl.Nrho
		Nslices=R.shape[0]
		N1=R.shape[1] # N1==N for no padding

		df=zeros([Nslices,N,N],dtype='float32')
		dR=zeros([Nslices,N,Nproj],dtype='float32')

		shift=cor-N1/2
		dR[:,N/2-N1/2+shift:N/2+N1/2+shift,0::self.osangles]=R		
		#padding
		dR[:,:N/2-N1/2+shift,:]=tile(reshape(dR[:,N/2-N1/2+shift,:],[Nslices,1,Nproj]),[1,N/2-N1/2+shift,1])
		dR[:,N/2+N1/2+shift:,:]=tile(reshape(dR[:,N/2+N1/2+shift-1,:],[Nslices,1,Nproj]),[1,N/2-N1/2-shift,1])
	
		if (self.Padj.filter is not None):
			dRos=zeros([Nslices,4*N,Nproj],dtype='float32')
			dRos[:,2*N-N/2:2*N+N/2,:]=dR
			dRos=real(fft.fftshift(fft.ifft(fft.fftshift(fft.fftshift(fft.fft(fft.fftshift(dRos,1),axis=1),1)*tile(transpose(tile(self.Padj.filter,[Nproj,1])),[Nslices,1,1]),1),axis=1),1))
			dR=dRos[:,2*N-N/2:2*N+N/2,:]

		for islice in range(0,Nslices): 
			Rlp0=zeros([Nrho,Ntheta],dtype='float32')
			f0=zeros([N,N],dtype='float32')
			interp_p=interpolate.RectBivariateSpline(arange(0,N), arange(0,Nproj), dR[islice,:,:], kx=3,ky=3)		
			for k in range(0,3):	
				Rlp0[unravel_index(self.Padj.lpids,(Nrho,Ntheta))]=interp_p(self.Padj.lp2p2[k],self.Padj.lp2p1[k],grid=False)
				Rlp0[unravel_index(self.Padj.wids,(Nrho,Ntheta))]=interp_p(self.Padj.lp2p2w[k],self.Padj.lp2p1w[k],grid=False)
				flp=fft.irfft2(fft.rfft2(Rlp0)*self.Padj.fZ)	
				interp_lp=interpolate.RectBivariateSpline(arange(0,Nrho), arange(0,Ntheta), flp, kx=3,ky=3)		
				f0[unravel_index(self.Padj.cids,(N,N))]+=interp_lp(self.Padj.C2lp2[k],self.Padj.C2lp1[k],grid=False)	
			df[islice,:,:]=f0
		f=df[:,N/2-N1/2:N/2+N1/2,N/2-N1/2:N/2+N1/2]*self.osangles*N1/N
                return f
Exemplo n.º 11
0
    def make_Tau(self):
        """
        Create EBL interpolation (model based on Finke et al)
        """

        # Load and combined EBL files downloaded from http://www.phy.ohiou.edu/~finke/EBL/
        tau_files = '/group/hepheno/smsharma/Fermi_High_Latitudes/Fermi-HighLat/sim/tau_modelC_total/tau_modelC_total_z%.2f.dat'
        z_list = np.arange(0, 5, 0.01)  # z values to load files for
        E_list, tau_list = [], []
        for z in z_list:
            d = np.genfromtxt(tau_files % z, unpack=True)
            E_list = d[0]
            tau_list.append(d[1])
        self.Tau_ip = ip.RectBivariateSpline(
            z_list, E_list, np.array(tau_list))  # Create interpolation
Exemplo n.º 12
0
 def _radial_derivative(self):
     """
     Generate the radial derivative of rho
     """
     z = self.z_bins
     r = self.r_bins
     rho = self.rho_binned
     
     dz = z[[1]] - z[[0]]
     dr = r[[1]] - r[[0]]
     
     drho_dr_binned = np.gradient(rho, dz, dr)[1]
     
     drho_dr_spline = interp.RectBivariateSpline(z, r, drho_dr_binned)
     self._drho_dr = drho_dr_spline
Exemplo n.º 13
0
def colorcode(datax, datay):
    from scipy import interpolate
    import numpy as np
    H, xedges, yedges = np.histogram2d(datax, datay, bins=30)
    xedges = (xedges[:-1] + xedges[1:]) / 2
    yedges = (yedges[:-1] + yedges[1:]) / 2
    f = interpolate.RectBivariateSpline(xedges, yedges, H)

    z = np.array([])
    for i in datax.index:
        z = np.append(z, f(datax[i], datay[i]))
    #z=(z-min(z))/(max(z)-min(z))
    z[z < 0] = 0
    idx = z.argsort()
    return z, idx
Exemplo n.º 14
0
def find_separatrix(eq, opoint=None, xpoint=None, ntheta=20, psi=None, axis=None, psival=1.0):
    """Find the R, Z coordinates of the separatrix for equilbrium
    eq. Returns a tuple of (R, Z, R_X, Z_X), where R_X, Z_X are the
    coordinates of the X-point on the separatrix. Points are equally
    spaced in geometric poloidal angle.

    If opoint, xpoint or psi are not given, they are calculated from eq

    eq - Equilibrium object
    opoint - List of O-point tuples of (R, Z, psi)
    xpoint - List of X-point tuples of (R, Z, psi)
    ntheta - Number of points to find
    psi - Grid of psi on (R, Z)
    axis - A matplotlib axis object to plot points on
    """
    if psi is None:
        psi = eq.psi()

    if (opoint is None) or (xpoint is None):
        opoint, xpoint = find_critical(eq.R, eq.Z, psi)

    psinorm = (psi - opoint[0][2])/(xpoint[0][2] - opoint[0][2])
    
    psifunc = interpolate.RectBivariateSpline(eq.R[:,0], eq.Z[0,:], psinorm)

    r0, z0 = opoint[0][0:2]

    theta_grid = linspace(0, 2*pi, ntheta, endpoint=False)
    dtheta = theta_grid[1] - theta_grid[0]

    # Avoid putting theta grid points exactly on the X-points
    xpoint_theta = arctan2(xpoint[0][0] - r0, xpoint[0][1] - z0)
    # How close in theta to allow theta grid points to the X-point
    TOLERANCE = 1.e-3
    if any(abs(theta_grid - xpoint_theta) < TOLERANCE):
        warn("Theta grid too close to X-point, shifting by half-step")
        theta_grid += dtheta / 2

    isoflux = []
    for theta in theta_grid:
        r, z = find_psisurface(eq, psifunc,
                               r0, z0,
                               r0 + 10.*sin(theta), z0 + 10.*cos(theta),
                               psival=psival,
                               axis=axis)
        isoflux.append((r, z, xpoint[0][0], xpoint[0][1]))

    return isoflux
Exemplo n.º 15
0
    def __init__(self, grid_data):
        super(TerrainElevationComp, self).__init__(grid_data, time_units='s')

        self.deriv_options['type'] = 'fd'

        nn = grid_data['num_nodes']

        self.add_param('lat',
                       shape=(nn, ),
                       desc='latitude',
                       units='deg',
                       eom_state=False)
        self.add_param('long',
                       shape=(nn, ),
                       desc='longitude',
                       units='deg',
                       eom_state=False)
        self.add_param('z',
                       shape=(nn, ),
                       desc='vertical component of position, positive down',
                       units='m',
                       eom_state=False)

        mydir = os.path.dirname(os.path.realpath(__file__))
        data_file_path = os.path.join(mydir, 'usgs_data.npz')

        usgs_file = np.load(data_file_path)

        self.add_output('elev',
                        shape=(nn, ),
                        desc='terrain elevation at the given point',
                        units='m/s/s')
        self.add_output('alt',
                        shape=(nn, ),
                        desc='ground-relative altitude of the track',
                        units='m')

        self.interpolant = interpolate.RectBivariateSpline(
            usgs_file['Longitude'], usgs_file['Latitude'],
            usgs_file['Elevation'])

        import matplotlib.pyplot as plt

        xx = usgs_file['XX']
        yy = usgs_file['YY']
        zz = usgs_file['Elevation']

        plt.contourf(xx, yy, zz)
Exemplo n.º 16
0
def test_voxel_interpolation():
    # Create a grid and a function within that grid
    scale = 0.1
    grid_size = np.array([31, 31])
    grid_origin = np.array([5., 6.])

    x = np.linspace(grid_origin[0],
                    grid_origin[0] + scale * (grid_size[0] - 1), grid_size[0])
    y = np.linspace(grid_origin[1],
                    grid_origin[1] + scale * (grid_size[1] - 1), grid_size[1])

    xv, yv = np.meshgrid(x, y, sparse=False, indexing='xy')
    zv = 3 * xv + 5 * yv

    voxel_map = VoxelMap(scale=scale,
                         origin_2=np.array(grid_origin / scale,
                                           dtype=np.float32),
                         map_size_2=np.array(grid_size, dtype=np.float32),
                         function_array_mn=np.array(zv, dtype=np.float32))

    # Let's have a bunch of points to test the interpolation
    test_positions = np.array([[[5.02, 6.01], [5.67, 7.73], [6.93, 6.93]],
                               [[9.1, 7.2], [7.889, 8.22], [7.1, 8.1]]],
                              dtype=np.float32)

    # Get the interpolated output of the voxel map
    interpolated_values = voxel_map.compute_voxel_function(test_positions,
                                                           invalid_value=-1.)
    interpolated_values = np.reshape(interpolated_values, [-1])

    # Expected interpolated values
    expected_interpolated_values = 3 * \
        test_positions[:, :, 0] + 5 * test_positions[:, :, 1]
    expected_interpolated_values = np.reshape(expected_interpolated_values,
                                              [-1])
    expected_interpolated_values[3] = -1.

    # Scipy Interpolated values
    f_scipy = interpolate.RectBivariateSpline(y, x, zv, kx=1, ky=1)
    scipy_interpolated_values = f_scipy.ev(
        np.reshape(test_positions[:, :, 1], [-1]),
        np.reshape(test_positions[:, :, 0], [-1]))
    scipy_interpolated_values[3] = -1.

    assert np.sum(
        abs(expected_interpolated_values - interpolated_values) <= 0.01) == 6
    assert np.sum(
        abs(scipy_interpolated_values - interpolated_values) <= 0.01) == 6
def procesar_magnus_moment_coef():
    # colocar en el vecto n_magnus los distintos 'angulos que se disponen de coeficientes

    [rows, cols] = np.shape(globals.data)

    n = cols - 8
    n_magnus = globals.data[0:rows, 8:8 + n]
    #Convert deg to rad
    magnus_ang = globals.data_raw[rows, 8:8 + n] * np.pi / 180
    tot = rows * n
    M_0 = globals.data[:, 0]

    # Mach para doble interpolaci'on
    globals.Mpa = np.zeros(tot)
    for i in range(rows):
        for k in range(n):
            globals.Mpa[i * n + k] = M_0[i]
    print('globals.Mpa')
    print(globals.Mpa)
    print(np.shape(globals.Mpa))

    # angulos de magnus
    globals.ang = []
    for ii in range(rows):
        globals.ang = np.append(globals.ang, magnus_ang)
    print('globals.ang')
    print(globals.ang)
    print(np.shape(globals.ang))

    # Cnpa
    globals.Cnpa_proce = np.zeros(tot)
    for i in range(rows):
        for k in range(n):
            globals.Cnpa_proce[i * n + k] = globals.data[i, k + 8]
    print('globals.Cnpa_proce')
    print(globals.Cnpa_proce)
    print(np.shape(globals.Cnpa_proce))

    #interp2d option
    #globals.interp = interpolate.interp2d(globals.Mpa, globals.ang, globals.Cnpa_proce)

    #RectBivariateSpline option
    n = np.shape(globals.Mpa[0::4])
    m = np.shape(globals.ang[0:4])
    globals.interp = interpolate.RectBivariateSpline(
        globals.Mpa[0::4], globals.ang[0:4],
        np.reshape(np.asarray(globals.Cnpa_proce), (n[0], m[0])))
    return []
Exemplo n.º 18
0
def filtered_wvd(wvd, stft):
    qstft = abs(stft)
    qstft = float64(qstft * qstft)
    bigstft = zeros(shape[wvd[0]], float64)

    x = arange(0, shape(qstft)[0])
    y = arange(0, shape(sqtft)[1])

    xx = linspace(x.min(), x.max(), shape(wvd[0])[0])
    yy = linspace(y.min(), y.max(), shape(wvd[0])[1])

    interpolator = interpolate.RectBivariateSpline(x, y, qstft, kx=1, ky=1)

    bigstft = interpolator(xx, yy)

    return (sqrt(abs(bigstft * wvd[0])), wvd[1], wvd[2])
Exemplo n.º 19
0
def qbubbleRefineContours(lv1, img, vb = 0):
    h, w = img.shape
    # Refines contours according to an image
    f = inpo.RectBivariateSpline(np.arange(h)+0.5,np.arange(w)+0.5,img)
    lv2 = []
    if (vb > 0): t0 = time.time()
    for i in range(len(lv1)):
        if (vb > 1): t1 = time.time()
        v = lv1[i].copy()
        if (vb > 1): print(i, end =" ")
        pv = v+10000
        v, pv = qbubbleStep(v, pv, f, w, h, 0, 1, 0.001, 1, 0.0001, 200, 4, 1, 1, 1)
        lv2.append(v)
        if (vb > 1): print("%.2f" % (time.time()-t1))
    if (vb > 0): print("Elapsed: ",time.time()-t0)
    return(lv2)
Exemplo n.º 20
0
 def interpolate_data(self,data_matrix,energies):
     """ interpolation based on the small matrices matrix_data
     """
     #create the correct form for the array z values
     #the values of energy are related to the values on which the interpolation has been made.
     r = len(data_matrix)
     c = len(self.frequencies)
     data_matrix = np.reshape(data_matrix, (r, c))
     val_flux = np.transpose(data_matrix)
     self.ei = self.ui.incidentEnergyValue.text()
     self.ei= float(self.ei)
     ei = [self.ei]
     #linear interpolation
     self.interpolation = interpolate.RectBivariateSpline(self.frequencies, energies, val_flux,kx=1, ky=1) #spline interpolation over the values of energy given.
     result = self.interpolation(self.frequencies, ei)#returns the value for the specific energy required ei.
     return result
Exemplo n.º 21
0
def load_chg_plane(fname):
    """Load charge density in a plane, in the format used by lev00"""
    dat = np.loadtxt(fname)

    # Data is stored in text form, with each line containing
    # X Y Z
    # where Z is the charge density
    # However, if the width along the axises are different, the grid points in
    # each direction stay constant, but the grid spacing changes.
    # So we might need to reinterpolate on a regular grid

    # Original num of points in both X and Y directions.
    n = np.sqrt(dat.shape[0])
    # x, y = meshgrid(dat[0:n, 0], dat[0:n, 1])
    x = dat[:, 0]
    y = dat[:, 1]
    xmax = x.max()
    xmin = x.min()
    ymax = y.max()
    ymin = y.min()
    xr = xmax - xmin
    yr = ymax - ymin

    xl = np.linspace(xmin, xmax, n)
    yl = np.linspace(ymin, ymax, n)
    z = np.reshape(dat[:, 2], (n, n))

    if xr == yr:
        # No interpolation needed
        pass
    else:
        import scipy.interpolate as spi
        # Create 2D interpolator object with original data
        # interp2d goes into an infinite loop?
        # inter2 = spi.interp2d(xl, yl, z)
        inter2 = spi.RectBivariateSpline(xl, yl, z)
        # Reinterpolate only along the bigger dimension
        idim = xr < yr
        if idim:  # Y range is bigger
            fac = int(round(n * yr / xr))
            yl = np.linspace(ymin, ymax, fac)
        else:
            fac = int(round(n * xr / yr))
            xl = np.linspace(xmin, xmax, fac)
        z = inter2(xl, yl)

    return xl, yl, z
Exemplo n.º 22
0
def Q(Varray, Rarray, nx=2000, ny=2000, print_points=True):
    '''
    Take in all Voltage/Resistance Pairs and return the conditional PDF: Q= P(R|V)
    Performs Gaussian Kernel Density Estimate and Linear Interpolation
    
    Params
    ------
    Varray, Rarray
        ndarray, same size (n_examples,)
    
    Returns
    -------
    Q
        ndarray (__, __)
    '''
    V_list = np.sort(np.unique(Varray))

    #Gaussian KDE
    Pyx_func = []

    for i, v in enumerate(V_list):
        idx = (Varray == v)
        data = Rarray[idx]
        if print_points == True:
            print('%0.2f Volts, %d Points' % (v, sum(idx)))
        Pyx_func.append(stats.gaussian_kde(
            data, bw_method='scott'))  #scott, silvermann, scalar

    Pyx_func = FunctionList(Pyx_func)

    x = np.linspace(V_list.min(), V_list.max(), nx)
    y = np.linspace(Rarray.min() * 0.7, Rarray.max() * 1.3, ny)

    # Bivariate Spline
    Pyx = np.atleast_2d(Pyx_func(y))
    Pyx_interp = interpolate.RectBivariateSpline(V_list,
                                                 y,
                                                 Pyx,
                                                 kx=3,
                                                 ky=3,
                                                 s=0)
    Pyx_new = np.rot90(Pyx_interp(x, y))

    # Normalize (each input needs to end up in an output (column=1))
    Pyx_new = Pyx_new / np.sum(Pyx_new, axis=0)

    return Pyx_new, x, y
Exemplo n.º 23
0
def get_fluence(e_0=100.0):
    """
    Returns a function representing the electron
    fluence with the distance in CSDA units.

    Args:
        e_0 (float): The kinetic energy whose
        CSDA range is used to scale the distances.

    Returns:
        A function representing fluence(x,u) with x in CSDA units.
    """
    # List of available energies
    e0_str_list = list(
        map(
            lambda x: (os.path.split(x)[1]).split(".csv")[0],
            glob(os.path.join(data_path, "fluence", "*.csv")),
        ))
    e0_list = sorted(list(map(int, list(filter(str.isdigit, e0_str_list)))))

    e_closest = min(e0_list, key=lambda x: abs(x - e_0))

    with open(os.path.join(data_path, "fluence/grid.csv"), "r") as csvfile:
        r = csv.reader(csvfile,
                       delimiter=" ",
                       quotechar="|",
                       quoting=csv.QUOTE_MINIMAL)
        t = next(r)
        x = np.array([float(a) for a in t[0].split(",")])
        t = next(r)
        u = np.array([float(a) for a in t[0].split(",")])
    t = []
    with open(
            os.path.join(data_path, "fluence",
                         "".join([str(e_closest), ".csv"])),
            "r",
    ) as csvfile:
        r = csv.reader(csvfile,
                       delimiter=" ",
                       quotechar="|",
                       quoting=csv.QUOTE_MINIMAL)
        for row in r:
            t.append([float(a) for a in row[0].split(",")])
    t = np.array(t)
    f = interpolate.RectBivariateSpline(x, u, t, kx=1, ky=1)
    # Note f is returning numpy 1x1 arrays
    return f
Exemplo n.º 24
0
def _lens_chk_N(args):
    assert len(args) == 15, args

    N, path_to_map, path_to_dx, path_to_dy, buff0, buff1, \
    lside0, lside1, HD_res0, HD_res1, NR_iter, kspl, LD0, LD1, do_not_prefilter = args
    HD_res = (HD_res0, HD_res1)
    LD = (LD0, LD1)
    s = (2**LD[0] + 2 * buff0, 2**LD[1] + 2 * buff1)  # Chunk shape

    dx = np.load(path_to_dx, mmap_mode='r')
    dy = np.load(path_to_dy, mmap_mode='r')
    map = np.load(path_to_map, mmap_mode='r')

    rmin0 = lside0 / 2**HD_res[0]
    rmin1 = lside1 / 2**HD_res[1]

    map_chk_N = np.empty(s, dtype=float)
    dx_gu = np.empty(
        s, dtype=float
    )  # will dx displ. in grid units of each chunk (typ. (256 * 256) )
    dy_gu = np.empty(
        s, dtype=float
    )  # will dy displ. in grid units of each chunk (typ. (256 * 256) )
    sLDs, sHDs = periodicmap_spliter().get_slices_chk_N(
        N, LD, HD_res, (buff0, buff1))
    for sLD, sHD in zip(sLDs, sHDs):
        # Displacements chunk in grid units, and map chunk to displace.
        dx_gu[sLD] = dx[sHD] / rmin1
        dy_gu[sLD] = dy[sHD] / rmin0
        map_chk_N[sLD] = map[sHD]

    if do_not_prefilter:
        # Undoing the prefiltering prior to apply bicubic interpolation
        map_chk_N = np.fft.rfft2(map_chk_N)
        w0 = 6. / (2. * np.cos(2. * np.pi * np.fft.fftfreq(s[0])) + 4.)
        map_chk_N /= np.outer(w0, w0[0:map_chk_N.shape[1]])
        map_chk_N = np.fft.irfft2(map_chk_N, s)

    idc0, idc1 = np.indices(
        s)  # Two typically (256 + 2 * buff * 256 + 2* buff) maps
    lx = (idc1 + dx_gu).flatten()  # No need to enforce periodicity here.
    ly = (idc0 + dy_gu).flatten()  # No need to enforce periodicity here.
    return (interpolate.RectBivariateSpline(np.arange(s[0]),
                                            np.arange(s[1]),
                                            map_chk_N,
                                            kx=kspl,
                                            ky=kspl).ev(ly, lx).reshape(s), )
Exemplo n.º 25
0
    def rotate_ground(original,
                      theta,
                      horizon=60,
                      half_height=360 / 2,
                      focal=1.0):
        height, width, channel = original.shape
        # the target grids
        yp = range(height - horizon, height)
        xp = range(0, width)

        # from pixel to coordinates
        y0 = (np.array(yp) - half_height) * 1.0 / half_height
        x0 = (np.array(xp) - width / 2) / (width / 2.0)

        # form the mesh
        mesh = MyDataset.generate_meshlist(x0, y0)
        # compute the source coordinates
        st = math.sin(theta)
        ct = math.cos(theta)
        deno = ct * focal + st * mesh[:, 0]
        out = np.array([(-st * focal + ct * mesh[:, 0]) / deno,
                        mesh[:, 1] / deno])

        # interpolate
        vout = []
        for i in range(3):
            f = interpolate.RectBivariateSpline(y0, x0, original[-horizon:, :,
                                                                 i])
            values = f(out[1, :], out[0, :], grid=False)
            vout.append(values)

        lower = np.reshape(vout, (3, width, horizon)).transpose(
            (2, 1, 0)).astype("uint8")

        # compute the upper part
        out = np.reshape(out[0, :], (width, horizon))
        out = out[:, 0]
        f = interpolate.interp1d(x0,
                                 original[:-horizon, :, :],
                                 axis=1,
                                 fill_value=(original[:-horizon, 0, :],
                                             original[:-horizon, -1, :]),
                                 bounds_error=False)
        ans = f(out)
        ans = ans.astype("uint8")

        return np.concatenate((ans, lower), axis=0)
Exemplo n.º 26
0
    def interpolate(self, degree=1):
        #create an interpolating spline to evaluate at arbitrary points
        #use first order as standard as this can cause no problems
        #better (higher order) interpolation possible by using 'degree'

        #It is recommended to use logarithmic values for interpolation
        #adf11 values are already written as log10
        logtemp = self.temp
        logdens = self.dens
        logdata = self.data

        #do actual interpolation
        self.logInterpolate = []
        for i in range(self.izmax):
            self.logInterpolate.append(spi.RectBivariateSpline(logdens, \
                logtemp, logdata[:,:,i], kx=degree, ky=degree))
        print("Ionization coefficient interpolation done.")
Exemplo n.º 27
0
 def interpolate_model_field(self):
     """Interpolate the model fields in self.model_field_coarse to the fine
         grid, store it in self.model_field
     """
     self.model_field = {}
     for key, model_field in self.model_field_coarse.items():
         self.model_field[key] = []
         for i in range(len(self.time_array)):
             interpolator = interpolate.RectBivariateSpline(
                 np.flip(LATITUDE_COARSE_ARRAY), LONGITUDE_COARSE_ARRAY,
                 np.flip(model_field[i, :, :], 0))
             model_field_interpolate_i = interpolator(
                 np.flip(LATITUDE_ARRAY), LONGITUDE_ARRAY)
             model_field_interpolate_i = np.flip(model_field_interpolate_i,
                                                 0)
             self.model_field[key].append(model_field_interpolate_i)
         self.model_field[key] = np.asarray(self.model_field[key])
    def get_interp_single(self, flu):
        my_flu = flu
        flu_y = [-19.5, -18.5, -17.5, -16.5, -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.75,
         -9.25, -8.75, -8.25, -7.75, -7.25, -6.75, -6.25, -5.75, -5.25, -4.75, -4.25,
         -3.75, -3.25, -2.75, -2.25, -1.75, -1.25, -0.75, -0.25, 0.25, 0.75, 1.25,
         1.75, 2.25, 2.75, 3.25, 3.75, 4.25, 4.75, 5.25, 5.75, 6.25, 6.75, 7.25, 7.75,
         8.25, 8.75, 9.25, 9.75, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5, 16.5, 17.5, 18.5,
         19.5]

        flu_x = np.linspace(-19.95, 19.95, 400)
        flu_yy = np.linspace(-19.95, 19.95, 400)

        #first create interpolating object tmp
        tmp = interpl.RectBivariateSpline(flu_y, flu_x, my_flu,kx=1, ky=1,s=0)

        tmp2 = tmp(flu_yy, flu_x)
        return tmp2
Exemplo n.º 29
0
def img_resample(inarr, inpixsize, outpixsize, \
                 xyctr = None, newdim = None, normalize = True):

    inarr = inarr[1:-1, 1:-1].copy()
    nkx, nky = inarr.shape
    X, Y = arange(nkx) + 0.5, arange(nky) + 0.5

    # Define the desired center from the input map.
    # Xctr and Yctr can both be non-integers.
    if xyctr == None:
        Xctr, Yctr = nkx / 2., nky / 2.
    else:
        Xctr, Yctr = xyctr[0], xyctr[1]

    # Define the new dimension of the regridded map if not given
    if newdim == None:
        new_nkx, new_nky = array(inarr.shape) / (outpixsize / inpixsize)
        new_nkx = int(new_nkx)
        new_nky = int(new_nky)
        if mod(new_nkx, 2) == 0:
            new_nkx = new_nkx - 1
            new_nky = new_nky - 1
    else:
        new_nkx, new_nky = newdim[0], newdim[1]

    new_Xctr, new_Yctr = (new_nkx) / 2., (new_nky) / 2.

    halfnewpix = outpixsize / inpixsize * 0.5
    new_X = (arange(new_nkx)-new_Xctr+0.5)*outpixsize/inpixsize +  \
            Xctr
    new_Y = (arange(new_nky)-new_Yctr+0.5)*outpixsize/inpixsize + \
            Yctr
    valuesum \
        = nansum(inarr[int(new_Y[0]-halfnewpix):int(new_Y[-1]+halfnewpix), \
                       int(new_X[0]-halfnewpix):int(new_X[-1]+halfnewpix)])
    f = interpolate.RectBivariateSpline(X, Y, inarr, kx=3, ky=3)

    outarr = f(new_Y, new_X)
    outarr[where(outarr == -999.)] = nan
    # Conserve the sum of the initial array
    outarr = outarr.copy()/nansum(outarr.copy())* \
             valuesum*(outpixsize/inpixsize)**(-2.)
    if normalize:
        outarr = outarr.copy() / nansum(outarr.copy())

    return outarr
Exemplo n.º 30
0
    def getPoints(self, sensorLocation):
        #assert type(sensorLocation)==SensorLocation, "invalid input type"

        out = np.zeros((sensorLocation.s[0], self.s[2]))
        for i in range(self.s[2]):
            f = sci.RectBivariateSpline(
                np.linspace(self.dims[0].min, self.dims[0].max,
                            self.data.shape[0]),
                np.linspace(self.dims[1].min, self.dims[1].max,
                            self.data.shape[1]), self.data[..., i])
            out[:, i] = f(sensorLocation.data[:, 0],
                          sensorLocation.data[:, 1],
                          grid=False)

        return SensorValue(out, [SensorDim(), ParameterDim()],
                           name="(%s) at points (%s)" %
                           (self.name, sensorLocation.name))