Ejemplo n.º 1
0
    def rebin_data(self, grid, use_psf=True):
        """Calculates the center of mass of the grid and then
        rebins so that the center pixel really is the center of the array
        For this we do a 2-d interpolation on the grid
        """
        a = psf_fitter.psffit(abs(grid), circle=False, rotate=1)
        xcen = a[2]
        ycen = a[2]
        xlen, ylen = grid.shape
        xval = arange(xlen)
        yval = arange(ylen)

        xint = interp1d(xval, self.xpos_abs)
        yint = interp1d(yval, self.ypos_abs)

        xintcen = self.xmax_pos-xint(xcen)
        yintcen = self.ymax_pos-yint(ycen)

        print self.xmax_pos, xintcen, self.ymax_pos, yintcen
        f_real = interp2d(self.xpos_rel, self.ypos_rel, real(grid))
        f_imag = interp2d(self.xpos_rel, self.ypos_rel, imag(grid))

        xnew = self.xpos_rel - xintcen
        ynew = self.ypos_rel - yintcen

        recen_grid = f_real(xnew, ynew) + 1j*f_imag(xnew, ynew)

        print nd.center_of_mass(abs(recen_grid))

        return recen_grid
Ejemplo n.º 2
0
def ijcoast(coast, grd):

    if type(grd).__name__ == "ROMS_Grid":
        lon = grd.hgrid.lon_vert
        lat = grd.hgrid.lat_vert
    if type(grd).__name__ == "CGrid_geo":
        lon = grd.lon_vert
        lat = grd.lat_vert

    ijcoast = []

    for k in range(coast.shape[0]):
        if np.isnan(coast[k, 0]):
            ijcoast.append([np.nan, np.nan])
        else:
            iindex, jindex = find_nearestgridpoints(coast[k, 0], coast[k, 1], grd, Cpos="vert")
            if iindex:
                i, j = np.meshgrid(iindex, jindex)
                x = lon[j, i]
                y = lat[j, i]
                funct_i = interpolate.interp2d(x.flatten(), y.flatten(), i.flatten())
                funct_j = interpolate.interp2d(x.flatten(), y.flatten(), j.flatten())
                i_coast = funct_i(coast[k, 0], coast[k, 1])[0]
                j_coast = funct_j(coast[k, 0], coast[k, 1])[0]
                ijcoast.append([i_coast, j_coast])

    return np.array(ijcoast)
Ejemplo n.º 3
0
    def __init__(self, textureData):
        cols = len(textureData[0])
        rows = len(textureData)
        self.cols = cols
        self.rows = rows

        indicators = np.empty_like(textureData)

        for i in range(rows):
            for j in range(cols):
                if textureData[i][j] == -1:
                    indicators[i][j] = 1.0
                else:
                    indicators[i][j] = 0.0

        marginX = 1.0/(2.0 * cols)
        marginY = 1.0/(2.0 * rows)

        x = np.linspace(marginX, 1.0-marginX, cols)
        y = np.linspace(marginY, 1.0-marginY, rows)

        self.indicator = interpolate.interp2d(x, y, indicators, kind='linear')

        data = textureData
        data = np.vstack((data[0], data))
        data = np.vstack((data, data[-1]))
        data = np.column_stack((data[:,0],data))
        data = np.column_stack((data, data[:,-1]))
        self.textureData = data

        x = np.linspace(-marginX, 1.0+marginX, cols+2)
        y = np.linspace(-marginY, 1.0+marginY, rows+2)

        self.f = interpolate.interp2d(x, y, data, kind='linear')
def applyInterpolatedNoise(image, targets, noise_factor=10, stride=64):

    size = image.shape[0]

    x = np.arange(0, size, stride)
    y = np.arange(0, size, stride)

    interp_size = x.shape[0]

    delta_x = np.random.normal(scale=noise_factor, size=(interp_size, interp_size))
    delta_y = np.random.normal(scale=noise_factor, size=(interp_size, interp_size))

    f_x = interpolate.interp2d(x, y, delta_x, kind='cubic')
    f_y = interpolate.interp2d(x, y, delta_y, kind='cubic')

    noise_x = f_x(np.arange(0, size), np.arange(0, size))
    noise_y = f_y(np.arange(0, size), np.arange(0, size))

    grid_x = np.asarray([range(size)]*size)
    grid_y = np.asarray([size*[i] for i in range(size)])

    x_jitter = grid_x + noise_x
    y_jitter = grid_y + noise_y

    labels = [None for t in range(targets.shape[0])]
    for t in range(targets.shape[0]):
        labels[t] = lookupNearest(targets[t, :, :], x_jitter, y_jitter)

    return bilinear_interpolate(image, x_jitter, y_jitter), labels
Ejemplo n.º 5
0
def refine_data(lon, lat, f, refine):
    lon = lon[0, :]
    lat = lat[:, 0]

    dlon = lon[1] - lon[0]
    dlat = lat[1] - lat[0]

    lat_hi = np.arange(lat[0],lat[-1],dlat/refine)
    lon_hi = np.arange(lon[0],lon[-1],dlon/refine)

    nx = len(lon_hi)
    ny = len(lat_hi)

    a = np.array(f.mask).astype(int)

    f[np.isnan(f)] = 100000

    ipol = interp2d(lon, lat, f)
    apol = interp2d(lon, lat, a)
    f = ipol(lon_hi, lat_hi)
    a = apol(lon_hi, lat_hi)
    f = np.ma.masked_where(a>.2, f)


    lon_hi, lat_hi = np.meshgrid(lon_hi, lat_hi)
    return lon_hi, lat_hi, f
Ejemplo n.º 6
0
def interpolate_isentropic_T_rho_Vp_Vs(T_ref, filename):
    pressures, temperatures, property_array = table_from_tab(filename)
    s, rho, vp, vs = property_array
    entropy = interpolate.interp2d(pressures, temperatures, s, kind='linear')
    density = interpolate.interp2d(pressures, temperatures, rho, kind='linear')
    v_p = interpolate.interp2d(pressures, temperatures, vp, kind='linear')
    v_s = interpolate.interp2d(pressures, temperatures, vs, kind='linear')
    S_ref = entropy(pressures.min(), T_ref)
    if isnan(S_ref):
        print('Oh no! For some reason the entropy interpolation on your perplex file returns NaN at the minimum pressure.')
        print('Conditions: P='+str(pressures.min()/1.e5)+' bar, T='+str(T_ref)+' K.')
        exit()
    adiabatic_temperatures = np.empty_like(pressures)
    adiabatic_densities = np.empty_like(pressures)
    adiabatic_Vps = np.empty_like(pressures)
    adiabatic_Vss = np.empty_like(pressures)
    for i, s_p in enumerate(zip(*s)):
        entropy_slice = interpolate.interp1d(s_p, temperatures, kind='linear')
        adiabatic_temperatures[i] = entropy_slice(S_ref)
        adiabatic_densities[i] = density(pressures[i], adiabatic_temperatures[i])
        adiabatic_Vps[i] = v_p(pressures[i], adiabatic_temperatures[i])
        adiabatic_Vss[i] = v_s(pressures[i], adiabatic_temperatures[i])
    
    adiabat_density = interpolate.interp1d(pressures, adiabatic_densities, kind='linear')
    adiabat_Vp = interpolate.interp1d(pressures, adiabatic_Vps, kind='linear')
    adiabat_Vs = interpolate.interp1d(pressures, adiabatic_Vss, kind='linear')
    adiabat_temperature = interpolate.interp1d(pressures, adiabatic_temperatures, kind='linear')

    return adiabat_temperature, adiabat_density, adiabat_Vp, adiabat_Vs
Ejemplo n.º 7
0
def get_translate(workdir=None):

    filename = os.path.join(workdir, "Vicalloy/Fe-Co-V_140922a_META_DATA.csv")
    compdata_f = pd.read_csv(filename, sep='\t').dropna()
    print compdata_f.head()
    x = compdata_f["Xnom (mm)"].values
    y = compdata_f["Ynom (mm)"].values
    Co_concentration = compdata_f["Co (at%)"].values
    Fe_concentration = compdata_f["Fe (at%)"].values
    V_concentration  = compdata_f["V (at%)"].values
    method = 'linear'
    # method = 'nearest'

    with warnings.catch_warnings():
        warnings.simplefilter("ignore")
        Co_concI = interp2d(x,y,Co_concentration, kind = method)
        Fe_concI = interp2d(x,y,Fe_concentration, kind = method)
        V_concI = interp2d(x,y,V_concentration , kind = method)

    def translate(key):
        manip_z, manip_y = key
        sample_y = manip_z - 69.5
        sample_x = (manip_y +8) *2
        Co = Co_concI(sample_x,sample_y)[0]/100.
        Fe = Fe_concI(sample_x,sample_y)[0]/100.
        V  = V_concI(sample_x,sample_y)[0]/100.
        return (
            "Fe{:.2f}Co{:.2f}V{:.2f}".format(Fe,Co,V),
            sample_x, sample_y
        )


    return translate
Ejemplo n.º 8
0
def cdcl(v, nrpm):
    """Gives the value of the drag and lift coefficients as function of velocity and spin.
    Is only valid for velocities between 13.7 and 88.1 m/s, and spins between 2000 and 6000 rpm.
    The value is determined with linear interpolation of the data given by Bearman and Harvey, 
    Golf Ball Aerodynamics, volume 27, Aeronautival Quarterly, 1976."""
    
    from numpy import array, linspace
    from scipy.interpolate import interp2d
    import sys
    
    if (v<13.7 or v>88.1):
        sys.exit('v is out of bounds. Must be between 13.7 and 88.41 m/s.')
        return
    
    if (nrpm<2000 or nrpm>6000):
        sys.exit('nrpm is out of bounds. Must be between 2000 and 6000 rpm.')
        return
    
    v0 = array([13.7, 21.6, 29.9, 38.4, 46.9, 55.2, 63.1, 71.9, 80.2, 88.1])
    nrpm0 = linspace(2000,6000,21)
    
    CD = array([[0.3624,0.2885,0.2765,0.2529,0.2472,0.2481,0.2467,0.2470,0.2470,0.2470],[0.3806,0.3102,0.2853,0.2590,0.2507,0.2498,0.2485,0.2486,0.2484,0.2484],[0.3954,0.3288,0.2937,0.2649,0.2543,0.2516,0.2504,0.2502,0.2497,0.2497],[0.4070,0.3443,0.3018,0.2708,0.2580,0.2535,0.2522,0.2518,0.2511,0.2511],[0.4153,0.3566,0.3095,0.2765,0.2617,0.2556,0.2541,0.2534,0.2524,0.2524],[0.4203,0.3658,0.3169,0.2822,0.2655,0.2578,0.2560,0.2550,0.2538,0.2538],[0.4120,0.3719,0.3240,0.2876,0.2693,0.2602,0.2579,0.2566,0.2551,0.2551],[0.3960,0.3749,0.3308,0.2930,0.2732,0.2627,0.2599,0.2582,0.2565,0.2565],[0.3876,0.3766,0.3372,0.2983,0.2772,0.2653,0.2619,0.2598,0.2578,0.2578],[0.4100,0.3854,0.3433,0.3034,0.2811,0.2681,0.2639,0.2614,0.2592,0.2592],[0.4288,0.4003,0.3490,0.3084,0.2852,0.2710,0.2659,0.2630,0.2605,0.2605],[0.4445,0.4082,0.3544,0.3133,0.2893,0.2741,0.2680,0.2646,0.2619,0.2619],[0.4575,0.4153,0.3595,0.3180,0.2934,0.2772,0.2701,0.2662,0.2632,0.2632],[0.4682,0.4215,0.3643,0.3227,0.2976,0.2806,0.2722,0.2678,0.2646,0.2646],[0.4772,0.4269,0.3687,0.3272,0.3019,0.2840,0.2743,0.2694,0.2659,0.2659],[0.4848,0.4314,0.3728,0.3316,0.3062,0.2876,0.2765,0.2710,0.2673,0.2673],[0.4914,0.4350,0.3765,0.3358,0.3105,0.2913,0.2787,0.2726,0.2686,0.2686],[0.4976,0.4377,0.3799,0.3400,0.3149,0.2952,0.2809,0.2742,0.2700,0.2700],[0.5039,0.4395,0.3830,0.3440,0.3194,0.2992,0.2831,0.2758,0.2713,0.2713],[0.5105,0.4405,0.3858,0.3479,0.3239,0.3034,0.2854,0.2774,0.2727,0.2727],[0.5180,0.4406,0.3882,0.3517,0.3285,0.3076,0.2877,0.2790,0.2740,0.2740]])
    CL = array([[0.1040,0.1846,0.2460,0.1984,0.1762,0.1538,0.1418,0.1360,0.1280,0.1276],[0.1936,0.2318,0.2590,0.2089,0.1824,0.1603,0.1476,0.1405,0.1321,0.1324],[0.2608,0.2694,0.2715,0.2191,0.1886,0.1668,0.1533,0.1450,0.1362,0.1367],[0.3090,0.2986,0.2835,0.2289,0.1949,0.1731,0.1589,0.1494,0.1403,0.1404],[0.3418,0.3205,0.2947,0.2384,0.2011,0.1794,0.1646,0.1539,0.1444,0.1436],[0.3624,0.3362,0.3049,0.2475,0.2073,0.1856,0.1702,0.1584,0.1485,0.1464],[0.3743,0.3470,0.3140,0.2562,0.2135,0.1916,0.1757,0.1629,0.1526,0.1488],[0.3808,0.3541,0.3217,0.2644,0.2197,0.1976,0.1813,0.1673,0.1567,0.1508],[0.3854,0.3584,0.3280,0.2722,0.2259,0.2035,0.1868,0.1718,0.1608,0.1524],[0.3915,0.3614,0.3325,0.2795,0.2322,0.2092,0.1923,0.1763,0.1649,0.1539],[0.4005,0.3640,0.3347,0.2862,0.2384,0.2149,0.1977,0.1807,0.1690,0.1582],[0.4010,0.3696,0.3380,0.2925,0.2446,0.2205,0.2032,0.1852,0.1731,0.1624],[0.4026,0.3748,0.3412,0.2982,0.2508,0.2259,0.2086,0.1897,0.1772,0.1666],[0.4050,0.3797,0.3440,0.3033,0.2570,0.2313,0.2139,0.1941,0.1813,0.1707],[0.4084,0.3845,0.3468,0.3078,0.2632,0.2366,0.2193,0.1986,0.1854,0.1749],[0.4130,0.3894,0.3496,0.3119,0.2695,0.2418,0.2246,0.2031,0.1895,0.1791],[0.4192,0.3947,0.3527,0.3149,0.2757,0.2469,0.2298,0.2076,0.1936,0.1833],[0.4271,0.4004,0.3563,0.3184,0.2819,0.2518,0.2351,0.2120,0.1977,0.1875],[0.4371,0.4069,0.3607,0.3233,0.2881,0.2567,0.2403,0.2165,0.2018,0.1916],[0.4494,0.4143,0.3660,0.3300,0.2943,0.2615,0.2455,0.2210,0.2059,0.1958],[0.4644,0.4227,0.3724,0.3393,0.3005,0.2662,0.2507,0.2254,0.2100,0.2000]])
    
    cd = interp2d(v0, nrpm0, CD, kind='linear')
    cl = interp2d(v0, nrpm0, CL, kind='linear')
    return cd(v, nrpm), cl(v, nrpm)
Ejemplo n.º 9
0
 def __init__(self,folder,T_unit='C',S_unit = 'kg/kg'):
     self.name = 'Liu'
     self.folder = folder
     self.T_unit = T_unit
     self.S_unit = S_unit
     #Simple dictionary for converting units of temperature and salinity
     #Pressure will always be in MPa
     self.S_multiply = {'kg/kg': 1.0, 'ppt': 0.001, 'wt. %': 0.01}#Liu calculation is in kg/kg
     self.T_add = {'K': -273.15, 'C': 0.0, 'F': 32}#Liu calculation is in C
     self.T_multiply = {'K': 1.0, 'C': 1.0, 'F': 5.0/9.0}#Liu calculation is in C
     #Load calculated dissociation pressure from file
     P_file = self.folder + 'Liu_method_Pmat.csv'
     A = np.loadtxt(P_file,delimiter=',')
     Temp = A[1:,0]#Celsius
     Sal = A[0,1:]#kg/kg
     Peq = A[1:,1:]#MPa
     self.P_func = interpolate.interp2d(Sal,Temp,Peq,kind='cubic')
     #Load calculated dissociation salinity from file
     S_file = self.folder + 'Liu_method_Smat.csv'
     B = np.loadtxt(S_file,delimiter=',')
     Pres = B[1:,0]#Celsius
     Temp2 = B[0,1:]#MPa
     Seq = B[1:,1:]*self.S_multiply[self.S_unit]#kg/kg
     Seq[Seq<1e-3]=0
     self.S_func = interpolate.interp2d(Temp2,Pres,Seq,kind='cubic')
Ejemplo n.º 10
0
def driftcorr(A, ux, uy, interpolation='cubic'):
    ''' 
    drift correction on 2D image or 3D DOS map, use ux, uy calculated by driftmap. Crop edges of A_corr if needed.
    interpolation: 'linear', 'cubic' or 'quintic'. Default is 'cubic'
    '''

    A_corr = np.zeros_like(A)
    s = A.shape[-1]
    t = np.arange(s, dtype='float')
    x, y = np.meshgrid(t, t)
    xnew = (x - ux).ravel()
    ynew = (y - uy).ravel()
    tmp = np.zeros(s**2)

    if len(A.shape) is 2:
        tmp_f = interp2d(t, t, A, kind=interpolation)
        for ix in range(tmp.size):
            tmp[ix] = tmp_f(xnew[ix], ynew[ix])
        A_corr = tmp.reshape(s, s)
        return A_corr
    elif len(A.shape) is 3:
        for iz, layer in enumerate(A):
            tmp_f = interp2d(t, t, layer, kind=interpolation)
            for ix in range(tmp.size):
                tmp[ix] = tmp_f(xnew[ix], ynew[ix])
            A_corr[iz] = tmp.reshape(s, s)
            print('Processing slice %d/%d...'%(iz+1, A.shape[0]), end='\r')
        return A_corr
    else:
        print('ERR: Input must be 2D or 3D numpy array!')
Ejemplo n.º 11
0
 def __init__(self, filename):
     nc = Dataset(filename)
     self.debug_mode = 1.
     print self.debug_mode
     self.dt = nc.variables["time"][1]-nc.variables["time"][0]
     self.xlon = nc.variables["xlon"][:]
     self.xlat = nc.variables["xlat"][:]
     N_lon = self.xlon.shape[1]
     N_lat = self.xlat.shape[0]
     #self.idx_to_lon = interp1d(numpy.arange(N_lon), self.xlon[0,:])
     #self.idx_to_lat = interp1d(numpy.arange(N_lat), self.xlat[:,0])
     self.idx_to_lon = interp2d(numpy.arange(N_lon), numpy.arange(N_lat), self.xlon)
     self.idx_to_lat = interp2d(numpy.arange(N_lon), numpy.arange(N_lat), self.xlat)
     self.left = self.xlon.min()
     self.right = self.xlon.max()
     self.bottom = self.xlat.min()+18
     self.top = self.xlat.max()-8
     self.m = Basemap(llcrnrlon=self.left,
                      llcrnrlat=self.bottom,
                      urcrnrlon=self.right,
                      urcrnrlat=self.top,
                      projection='cyl', resolution='l')
     self.ocean_mask = maskoceans(self.xlon, self.xlat, self.xlon).mask
     self.time_min = 0.
     self.time_max = 0.
     self.no_ingested = 0
     self.masks = numpy.empty((0,)+self.ocean_mask.shape)
     self.tc_table = numpy.empty((0,5))
     self.time = numpy.empty((0,))
Ejemplo n.º 12
0
def default_absorbers(Tatm, ozone_file = 'apeozone_cam3_5_54.nc'):
    '''Initialize a dictionary of well-mixed radiatively active gases
    All values are volumetric mixing ratios.

    Ozone is set to a climatology.

    All other gases are assumed well-mixed:

        - CO2
        - CH4
        - N2O
        - O2
        - CFC11
        - CFC12
        - CFC22
        - CCL4

    Specific values are based on the AquaPlanet Experiment protocols,
    except for O2 which is set the realistic value 0.21
    (affects the RRTMG scheme).
    '''
    absorber_vmr = {}
    absorber_vmr['CO2']   = 348. / 1E6
    absorber_vmr['CH4']   = 1650. / 1E9
    absorber_vmr['N2O']   = 306. / 1E9
    absorber_vmr['O2']    = 0.21
    absorber_vmr['CFC11'] = 0.
    absorber_vmr['CFC12'] = 0.
    absorber_vmr['CFC22'] = 0.
    absorber_vmr['CCL4']  = 0.

    datadir = os.path.join(os.path.dirname(__file__), 'data', 'ozone')
    ozonefilepath = os.path.join(datadir, ozone_file)
    #  Open the ozone data file
    print 'Getting ozone data from', ozonefilepath
    ozonedata = nc.Dataset(ozonefilepath)
    ozone_lev = ozonedata.variables['lev'][:]
    ozone_lat = ozonedata.variables['lat'][:]
    #  zonal and time average
    ozone_zon = np.mean(ozonedata.variables['OZONE'], axis=(0,3))
    ozone_global = np.average(ozone_zon, weights=np.cos(np.deg2rad(ozone_lat)), axis=1)
    lev = Tatm.domain.axes['lev'].points
    if Tatm.shape == lev.shape:
        # 1D interpolation on pressure levels using global average data
        f = interp1d(ozone_lev, ozone_global)
        #  interpolate data to model levels
        absorber_vmr['O3'] = f(lev)
    else:
        #  Attempt 2D interpolation in pressure and latitude
        f2d = interp2d(ozone_lat, ozone_lev, ozone_zon)
        try:
            lat = Tatm.domain.axes['lat'].points
            f2d = interp2d(ozone_lat, ozone_lev, ozone_zon)
            absorber_vmr['O3'] = f2d(lat, lev).transpose()
        except:
            print 'Interpolation of ozone data failed.'
            print 'Reverting to default O3.'
            absorber_vmr['O3'] = np.zeros_like(Tatm)
    return absorber_vmr
Ejemplo n.º 13
0
def streamline(u1,u2,d,x1_0,x2_0,dl=1.,fig=None,nmax=600):

    if fig==None:
        ax=plt.gca()
    else:
        ax=fig.figure.gca()

    xrange=[ax.get_xlim()[0],ax.get_xlim()[1]]
    yrange=[ax.get_ylim()[0],ax.get_ylim()[1]]

    if nmax == 600 and fig != None:
        nmax = fig.dpi * max([fig.fig_w,fig.fig_h])


    # Aspect ratio:
    r=(xrange[1]-xrange[0])/(yrange[1]-yrange[0])
    if r<1:
        ny=nmax
        nx=int(r*nmax)
    else:
        nx=nmax
        ny=int(nmax/r)
    nregrid = [nx,ny]

    CC=d.getCenterPoints()
    tmp0=np.complex(0,nregrid[0])
    tmp1=np.complex(0,nregrid[1])
    x=np.linspace(xrange[0],xrange[1],nregrid[0])
    y=np.linspace(yrange[0],yrange[1],nregrid[1])
    grid_x, grid_y = np.mgrid[xrange[0]:xrange[1]:tmp0, yrange[0]:yrange[1]:tmp1]

    u = griddata(CC, u1, (grid_x, grid_y), method='linear')
    v = griddata(CC, u2, (grid_x, grid_y), method='linear')
    uisnan=np.isnan(u)
    visnan=np.isnan(v)
    un = np.empty(np.shape(u))
    vn = np.empty(np.shape(v))
    un[uisnan] = griddata(CC, u1, (grid_x[uisnan], grid_y[uisnan]), method='nearest')
    vn[visnan] = griddata(CC, u2, (grid_x[visnan], grid_y[visnan]), method='nearest')
    u[uisnan]=un[uisnan]
    v[visnan]=vn[visnan]
# Normalize:
    mag=np.sqrt(u**2+v**2)
    u=u/mag
    v=v/mag

    fu = interpolate.interp2d(grid_x, grid_y, u, kind='cubic')
    fv = interpolate.interp2d(grid_x, grid_y, v, kind='cubic')
    x1=[x1_0]
    x2=[x2_0]
    while(x1[-1] >= xrange[0] and x1[-1] <= xrange[1] and
    x2[-1] >= yrange[0] and x2[-1] <= yrange[1]):
        dt=dl
        x1.append(x1[-1]+fu(x1[-1],x2[-1])*dt)
        x2.append(x2[-1]+fv(x1[-1],x2[-1])*dt)
    return [np.array(x1),np.array(x2)]
def bad_make_star(mass, age, model='Burrows97'):
    
    '''
    Calculates stellar properties such as Teff, radii, logg and logL using evolutionary models
    '''

    if np.min(mass) < 0.0005:
        raise NameError('Mass below minimum mass of 0.0005Msun')

    if np.max(mass) > 0.1 and model=='Baraffe03':
       warnings.warn('Mass above maximum mass of 0.1Msun for Baraffe 2003. Using Burrows 1997 instead.')  
       model = 'Burrows97'

    if np.min(mass) > 0.2:
        raise NameError('Mass above maximum mass of 0.2Msun for Burrows 1997')    

    if model == 'Burrows97':
        #0.0005 - 0.2 Msun
        burrows = pd.read_pickle("burrows97.pickle")
        allages = burrows["Age (Gyr)"]
        allmasses = burrows["M/Ms"]
        teff = burrows["Teff"]
        radius = burrows["R/Rs"]
        logg = burrows["logg(cgs)"]
        logL = burrows["logL/Ls"]
        
    if model == 'Baraffe03':
        #0.0005 - 0.1 Msun
        baraffe = pd.read_pickle("baraffe03.pickle")
        allages = baraffe["Age (Gyr)"]
        allmasses = baraffe["M/Ms"]
        teff = baraffe["Teff"]
        radius = baraffe["R/Rs"]
        logg = baraffe["logg(cgs)"]
        logL = baraffe["logL/Ls"]

    interpteff = interpolate.interp2d(allages,allmasses,teff,kind='linear')
    interprad = interpolate.interp2d(allages,allmasses,radius,kind='linear')
    interplogg = interpolate.interp2d(allages,allmasses,logg,kind='linear')
    interplogL = interpolate.interp2d(allages,allmasses,logL,kind='linear')  
        
    mass = np.array(mass).flatten()
    age = np.array(age).flatten()
    
    newteff = np.array([interpteff(i,j) for i,j in zip(age,mass)])
    newrad = np.array([interprad(i,j) for i,j in zip(age,mass)])
    newlogg = np.array([interplogg(i,j) for i,j in zip(age,mass)])
    newlogL = np.array([interplogL(i,j) for i,j in zip(age,mass)])
    
    stardict = {'Teff (K)':newteff,'Radius (Rs)':newrad, 'log g':newlogg, 'log L':newlogL}    
    
    starTable = Table(stardict)
    
    return starTable
Ejemplo n.º 15
0
def interp(iqehist, newE):
    """compute a new IQE histogram using the new energy array
    
    * iqehist: input IQE histogram
    * newE: new energy centers array
    """
    from scipy import interpolate

    mask = iqehist.I != iqehist.I
    # find energy boundaries of dynamic range for each Q
    def get_boundary_indexes(a):
        nz = np.nonzero(a)[0]
        if nz.size:
            return nz[0], nz[-1]
        else:
            return 0, 0

    boundary_indexes = [get_boundary_indexes(row) for row in np.logical_not(mask)]
    try:
        E = iqehist.energy
    except:
        E = iqehist.E
    Eranges = [(E[ind1], E[ind2]) for ind1, ind2 in boundary_indexes]
    #
    iqehist.I[mask] = 0
    iqehist.E2[mask] = 0
    Q = iqehist.Q
    f = interpolate.interp2d(E, Q, iqehist.I, kind="linear")
    E2f = interpolate.interp2d(E, Q, iqehist.E2, kind="linear")
    dE = E[1] - E[0]
    Emin = E[0] // dE * dE
    Emax = E[-1] // dE * dE
    # Enew = np.arange(Emin, Emax+dE/2, dE)
    newS = f(newE, Q)
    newS_E2 = E2f(newE, Q)
    # create new histogram
    Eaxis = H.axis("E", newE, unit="meV")
    Qaxis = H.axis("Q", Q, unit="1./angstrom")
    newHist = H.histogram("IQE", [Qaxis, Eaxis], data=newS, errors=newS_E2)
    #
    for Erange, q in zip(Eranges, Q):
        Emin, Emax = Erange
        if Emin > newE[0]:
            Emin = min(Emin, newE[-1])
            newHist[q, (None, Emin)].I[:] = np.nan
            newHist[q, (None, Emin)].E2[:] = np.nan
        if Emax < newE[-1]:
            Emax = max(Emax, newE[0])
            newHist[q, (Emax, None)].I[:] = np.nan
            newHist[q, (Emax, None)].E2[:] = np.nan
        continue
    return newHist
Ejemplo n.º 16
0
	def __init__(self,**kwargs):
		fieldlineTracer.__init__(self,**kwargs)
		from scipy.interpolate import interp2d
		
		if 'interp' not in kwargs or kwargs['interp'] is None:
			interp = 'linear'
		else:
			interp = kwargs['interp']
		if self.eq.B is None:
			self.eq.calc_bfield()
			
		self._bR = interp2d(self.eq.R,self.eq.Z,self.eq.BR/self.eq.B,kind=interp)
		self._bZ = interp2d(self.eq.R,self.eq.Z,self.eq.BZ/self.eq.B,kind=interp)
		self._bt = interp2d(self.eq.R,self.eq.Z,self.eq.Bt/self.eq.B,kind=interp)
Ejemplo n.º 17
0
	def GetAllAlignment(self,e):	#Get Alignment data for the entire 2D data range, interpolate results
		global AllAlignmentFxn, AllERotFxn, AlignmentProgPath, AllERotData, AllAlignmentData, alignment_params, inputfile,Nx,Ny
		alignment_params['FDTDField']['File'] = os.path.abspath(inputfile) 		#Change json input file to full 2D file
		WriteJSON()																#Write json
		WriteRunFile(AlignmentProgPath,os.path.abspath('inputs_mod.json'))		#write temp bash script
		os.system("chmod +x temp_script.sh")									#make executable
		subprocess.call("./temp_script.sh", shell=True)							#run script
		os.system("rm temp_script.sh")											#remove temp

		#Import the calculated data and make global interpolations
		AllAlignmentData = np.genfromtxt("output_data/AlignmentData.txt", usecols=(3), dtype=float).reshape(Ny,Nx)
		AllAlignmentFxn = interpolate.interp2d(self.panel1.X,self.panel1.Y,AllAlignmentData,kind='cubic')
		AllERotData = np.genfromtxt("output_data/AlignmentData.txt", usecols=(4), dtype=float).reshape(Ny,Nx)
		AllERotFxn = interpolate.interp2d(self.panel1.X,self.panel1.Y,AllERotData,kind='cubic')
Ejemplo n.º 18
0
	def __init__(self,**kwargs):
		fieldlineTracer.__init__(self,**kwargs)
			
		if self.eq.B is None:
			self.eq.calc_bfield()
			
		if 'interp' not in kwargs:
			interp = 'linear'
		else:
			interp = kwargs['interp']
			
		self._bR = interp2d(self.eq.R,self.eq.Z,self.eq.BR/self.eq.B,kind=interp)
		self._bZ = interp2d(self.eq.R,self.eq.Z,self.eq.BZ/self.eq.B,kind=interp)
		self._bt = interp2d(self.eq.R,self.eq.Z,self.eq.Bt/self.eq.B,kind=interp)
Ejemplo n.º 19
0
def zoom(array, newSize, order=3):
    """
    A Class to zoom 2-dimensional arrays using interpolation

    Uses the scipy `Interp2d` interpolation routine to zoom into an array. Can cope with real of complex data.

    Parameters:
        array (ndarray): 2-dimensional array to zoom
        newSize (tuple): the new size of the required array
        order (int, optional): Order of interpolation to use. default is 3

    Returns:
        ndarray : zoom array of new size.
    """
   
    if order not in INTERP_KIND:
       raise ValueError("Order can either be 1, 3, or 5 only")

    try:
        xSize = newSize[0]
        ySize = newSize[1]

    except (IndexError, TypeError):
        xSize = ySize = newSize

    coordsX = numpy.linspace(0, array.shape[0]-1, xSize)
    coordsY = numpy.linspace(0, array.shape[1]-1, ySize)

    #If array is complex must do 2 interpolations
    if array.dtype==numpy.complex64 or array.dtype==numpy.complex128:

        realInterpObj = interp2d(   numpy.arange(array.shape[0]),
                numpy.arange(array.shape[1]), array.real, copy=False, 
                kind=INTERP_KIND[order])
        imagInterpObj = interp2d(   numpy.arange(array.shape[0]),
                numpy.arange(array.shape[1]), array.imag, copy=False,
                kind=INTERP_KIND[order])                 
        return (realInterpObj(coordsY,coordsX) 
                            + 1j*imagInterpObj(coordsY,coordsX))

        

    else:

        interpObj = interp2d(   numpy.arange(array.shape[0]),
                numpy.arange(array.shape[1]), array, copy=False,
                kind=INTERP_KIND[order])

        #return numpy.flipud(numpy.rot90(interpObj(coordsY,coordsX)))
        return interpObj(coordsY,coordsX) 
Ejemplo n.º 20
0
 def __init__(self,obsBand,restBand,datFile=None):
     super(EmissionLineKCorr,self).__init__(obsBand,restBand)
     if not obsBand.startswith('SDSS'):
         raise ValueError
     if datFile is None:
         datFile = os.path.join(datadir,'bossdr9kcorr_ugriz.npz')
     self.data = np.load(datFile)
     b_j = 'ugriz'.find(obsBand[-1])
     self.kcorr = self.data['kcorr'][...,b_j]
     self.mbins = self.data['mbins'][...,b_j]
     self.Mbins = self.data['Mbins']
     self.zbins = self.data['zbins']
     self.zz = np.tile(self.zbins,(len(self.Mbins),1))
     self.K_M = interp2d(self.Mbins,self.zbins,self.kcorr.transpose())
     self.K_m = interp2d(self.mbins,self.zz,self.kcorr)
Ejemplo n.º 21
0
def crop_to_bbox(lon, lat, data, bbox, nx=200, ny=200):
#    lati = np.where(np.logical_and(lat>=bbox[0]-1, lat<=bbox[2]+1))[0]
#    loni = np.where(np.logical_and(lon>=bbox[1]-1, lon<=bbox[3]+1))[0]
#    lon = lon[loni[0]:loni[-1]] 
#    lat = lat[lati[0]:lati[-1]] 
#    data = data[lati[0]:lati[-1], loni[0]:loni[-1]]
#    return lon, lat, data
    def __fill(data):
        invalid = np.isnan(data)

        ind = nd.distance_transform_edt(invalid,
                                        return_distances=False,
                                        return_indices=True)

        return data[tuple(ind)]


    lat_min = bbox[0]
    lat_max = bbox[2]
    lon_min = bbox[1]
    lon_max = bbox[3]

    a = np.array(data.mask).astype(int)
    print a
    a[:, 0] = 1
    a[-1, :] = 1
    print(a)

    data = __fill(data)
#    data[np.isnan(data)] = 9e99



    dlat = (lat_max - lat_min) / ny
    dlon = (lon_max - lon_min) / nx

    lat_hi = np.arange(lat_min, lat_max + dlat, dlat)
    lon_hi = np.arange(lon_min, lon_max + dlon, dlon)

    ipol = interp2d(lon, lat, data)
    apol = interp2d(lon, lat, a)

    data_hi = ipol(lon_hi, lat_hi)
    mask_hi = apol(lon_hi, lat_hi)

    data_hi = np.ma.masked_where(mask_hi>.2, data_hi)

    return lon_hi, lat_hi, data_hi
Ejemplo n.º 22
0
def make_let_im(let_file, dim = 16, y_lo = 70, y_hi = 220, x_lo = 10, x_hi = 200, edge_pix = 150, plot_let = False):

    letter = mpimg.imread(let_file)

    letter = letter[y_lo:y_hi, x_lo:x_hi, 0]
    for i in range(letter.shape[1]):
        if letter[0:edge_pix, i].any() == 0:   # here is to remove the edge
            letter[0:edge_pix, i] = 1
    
    plt.imshow(letter, cmap='gray')
    plt.grid('off')
    plt.show()
        
    x = np.arange(letter.shape[1])
    y = np.arange(letter.shape[0])

    f2d = interp2d(x, y, letter)

    x_new = np.linspace(0, letter.shape[1], dim)    # dim = 16
    y_new = np.linspace(0, letter.shape[0], dim)

    letter_new = f2d(x_new, y_new)
    letter_new -= np.mean(letter_new)
    
    if plot_let: 
        plt.imshow(letter_new, cmap = 'gray')
        plt.grid('off')
        plt.show()
        
    letter_flat = letter_new.flatten()   # letter_flat is a 1-dimensional array containing 256 elements
    
    return letter_new, letter_flat
Ejemplo n.º 23
0
 def remove_unresponsive_and_fluctuating_stripe(self, sinogram, snr, size):
     """
     Algorithm 6 in the paper. Remove unresponsive or fluctuating stripes.
     ---------
     Parameters: - sinogram: 2D array.
                 - snr: ratio used to discriminate between useful
                     information and noise
                 - size: window size of the median filter.
     ---------
     Return:     - stripe-removed sinogram.
     """
     (nrow, _) = sinogram.shape
     sinosmoothed = np.apply_along_axis(uniform_filter1d, 0, sinogram, 10)
     listdiff = np.sum(np.abs(sinogram - sinosmoothed), axis=0)
     nmean = np.mean(listdiff)
     listdiffbck = median_filter(listdiff, size)
     listdiffbck[listdiffbck == 0.0] = nmean
     listfact = listdiff / listdiffbck
     listmask = self.detect_stripe(listfact, snr)
     listmask = binary_dilation(listmask, iterations=1).astype(listmask.dtype)
     listmask[0:2] = 0.0
     listmask[-2:] = 0.0
     listx = np.where(listmask < 1.0)[0]
     listy = np.arange(nrow)
     matz = sinogram[:, listx]
     finter = interpolate.interp2d(listx, listy, matz, kind='linear')
     listxmiss = np.where(listmask > 0.0)[0]
     if len(listxmiss) > 0:
         matzmiss = finter(listxmiss, listy)
         sinogram[:, listxmiss] = matzmiss
     return sinogram
Ejemplo n.º 24
0
	def evalDiff(self, x, y, diff):

		imin = int(x) - 5
		imax = imin + 10
		jmin = int(y) - 5
		jmax = jmin + 10

		if jmin < 0:
			return 0
		if jmax > len(diff[1,:]):
			return 0

		xticks = np.arange(0,len(diff[:,1]))
		yticks = np.arange(0,len(diff[1,:]))
		ygrid, xgrid = np.meshgrid(yticks,xticks)

		xgrid = xgrid[imin:imax,jmin:jmax]
		ygrid = ygrid[imin:imax,jmin:jmax]
		diff  = diff[imin:imax,jmin:jmax]

		print xgrid.shape
		print ygrid.shape
		print diff.shape

		diffAt = sp.interp2d(xgrid, ygrid, diff, kind='linear')
		return diffAt(x,y)
Ejemplo n.º 25
0
def interpolarMapa(probeMap):
    # Obtener la lista de valores x,y,z
    xm, ym, zm = probeMapToList(probeMap)
    # Interpolar la funcion
    f = interpolate.interp2d(xm, ym, zm, kind='cubic')
    # Devuelve el objeto de funcion
    return f
Ejemplo n.º 26
0
	def evalStrainY(self, x, y, diff):

		imin = int(x) - 5
		imax = imin + 10
		jmin = int(y) - 5
		jmax = jmin + 10

		if jmin < 0:
			return 0
		if jmax > len(diff[1,:]):
			return 0

		xticks = np.arange(0,len(diff[:,1]))
		yticks = np.arange(0,len(diff[1,:]))
		yticks = yticks[self.lag:]
		ygrid, xgrid = np.meshgrid(yticks,xticks)

		strainY = (diff[:,self.lag:] - diff[:,:-self.lag])/(self.lag*self.stepy)
		
		xgrid = xgrid[imin:imax,jmin:jmax]
		ygrid = ygrid[imin:imax,jmin:jmax]
		strainY  = strainY[imin:imax,jmin:jmax]

		strainAt = sp.interp2d(xgrid, ygrid, strainY, kind='linear')

		return strainAt(x,y)
Ejemplo n.º 27
0
def plotSurf():
    from scipy import interpolate
    a=pd.read_pickle(utl.outpath+'real/real.maxLikelihoods.df')
    idx=(a.s.abs()*a.h.abs()*(a.alt-a.null)).sort_values().index[-1]
    R=pd.DataFrame(pd.read_pickle(utl.outpath+'real/real.replicates.df').loc[idx]).T
    SH=dta.getSH()
    ARGS=[(R,)+sh for sh in SH]
    likelihoods=pd.concat(map(mkv.computeLikelihoodReal,ARGS),axis=1);likelihoods.columns.names=['s','h']


    fig = plt.figure()
    ax = fig.gca(projection='3d')
    df=pd.concat([pd.Series(z[1].loc[z[0]].values,index=z[1].loc[z[0]].index,name=z[0]) for z in b.groupby(level=0)],axis=1)
    Z=df.values
    # Z[Z==Z.min()]=-1e3
    X=np.tile(df.index.values[:,None],Z.shape[1])
    Y=np.tile(df.columns.values[:,None],Z.shape[0]).T
    Z.min()
    Z.max()

    nn = 401;
    xi = np.linspace(-1.0, 2.0, 10);
    yi = np.linspace(-0.5, 0.5, nn);

    f = interpolate.interp2d(X,Y,Z,kind='cubic')
    zi = f(xi, yi)
    [xi, yi] = np.meshgrid(xi, yi);
    # surf = ax.plot_surface(X, Y, Z, cmap=mpl.cm.autumn)
    surf = ax.plot_surface(xi, yi, zi, cmap=mpl.cm.autumn)
    fig.colorbar(surf, shrink=0.5, aspect=5)

    # surf(xi, yi, zi, 'LineStyle', 'none', 'FaceColor', 'interp')
    plt.show()
Ejemplo n.º 28
0
def _rs_dead(sinogram, snr, size, matindex):
    """
    Remove unresponsive and fluctuating stripes.
    """
    sinogram = np.copy(sinogram)  # Make it mutable
    (nrow, _) = sinogram.shape
    sinosmoothed = np.apply_along_axis(uniform_filter1d, 0, sinogram, 10)
    listdiff = np.sum(np.abs(sinogram - sinosmoothed), axis=0)
    nmean = np.mean(listdiff)
    listdiffbck = median_filter(listdiff, size)
    listdiffbck[listdiffbck == 0.0] = nmean
    listfact = listdiff / listdiffbck
    listmask = _detect_stripe(listfact, snr)
    listmask = binary_dilation(listmask, iterations=1).astype(listmask.dtype)
    listmask[0:2] = 0.0
    listmask[-2:] = 0.0
    listx = np.where(listmask < 1.0)[0]
    listy = np.arange(nrow)
    matz = sinogram[:, listx]
    finter = interpolate.interp2d(listx, listy, matz, kind='linear')
    listxmiss = np.where(listmask > 0.0)[0]
    if len(listxmiss) > 0:
        matzmiss = finter(listxmiss, listy)
        sinogram[:, listxmiss] = matzmiss
    # Use algorithm 5 to remove residual stripes
    sinogram = _rs_large(sinogram, snr, size, matindex)
    return sinogram
Ejemplo n.º 29
0
    def __init__(self, pupil_diameter=0.003, focal_length=0.017, dist=1.0, wave=None):
        """ Constructor for Optics Class
        Initialize parameters for human ocular system

        Args:
            pupil_diameter (float): pupil diameter in meters, usually human pupil diameter should be between 2 and 8
            focal_length (float): focal length of human, usually this is around 17 mm
            dist (float): object distance in meters, will be overrrided by scene.dist in compute method

        Note:
            To alter lens and macular pigment transmittance, we need to create a default optics instance first and then
            set the corresponding parameters

        Examples:
            >>> oi = Optics(pupil_diameter=0.5)
            >>> oi.macular_transmittance[:] = 1

        """
        # check inputs
        if wave is None:
            wave = np.arange(400.0, 710.0, 10)

        # turn off numpy warning for invalid input
        np.seterr(invalid='ignore')

        # initialize instance attribute to default values
        self.name = "Human Optics"                   # name of the class instance
        self._wave = wave.astype(float)              # wavelength samples in nm
        self.photons = np.array([])                  # irradiance image
        self.pupil_diameter = pupil_diameter         # pupil diameter in meters
        self.dist = dist                             # Object distance in meters
        self.fov = 1.0                               # field of view of the optical image in degree
        self.focal_length = focal_length             # focal lens of optics in meters
        self._otf = None                             # optical transfer function

        # set lens quanta transmittance
        self.lens_transmittance = 10**(-spectra_read("lensDensity.mat", wave))

        # set macular pigment quanta transmittance
        self.macular_transmittance = 10**(-spectra_read("macularPigment.mat", wave))

        # compute human optical transfer function
        # Reference: Marimont & Wandell, J. Opt. Soc. Amer. A,  v. 11, p. 3113-3122 (1994)
        max_freq = 90
        defocus = 1.7312 - (0.63346 / (wave*1e-3 - 0.2141))  # defocus as function of wavelength

        w20 = pupil_diameter**2 / 8 * (1/focal_length * defocus) / (1/focal_length + defocus)  # Hopkins w20 parameter
        sample_sf = np.arange(max_freq)
        achromatic_mtf = 0.3481 + 0.6519 * np.exp(-0.1212 * sample_sf)

        # compute otf at each wavelength
        otf = np.zeros([sample_sf.size, wave.size])
        for ii in range(wave.size):
            s = 1 / tan(deg_to_rad(1)) * wave[ii] * 2e-9 / pupil_diameter * sample_sf  # reduced spatial frequency
            alpha = 4*pi / (wave[ii] * 1e-9) * w20[ii] * s
            otf[:, ii] = self.optics_defocus_mtf(s, alpha) * achromatic_mtf

        # set otf as 2d interpolation function to object
        # To get otf at given wavelength and frequency, use object.otf() method
        self._otf = interp2d(self.wave, sample_sf, otf, bounds_error=False, fill_value=0)
Ejemplo n.º 30
0
def pair_fin(clos_app,dt, aa, src, freq,fbmamp,multweight=True,noiseweight=True,ovlpweight=True,cutoff=9000.*0.005*0.005,puv=False):
    final = []
    cnt, N = 0,len(clos_app)
    bm_intpl = export_beam.beam_interpol(freq,fbmamp,'cubic')
    if ovlpweight: #rbm2interp: FT of sq of beam
        fbm2 = n.multiply(fbmamp,fbmamp)   #element wise square for power beam
        rbm2 = n.fft.fft2(fbm2); rbm2 = n.fft.fftshift(rbm2)
        freqlm = n.fft.fftfreq(len(freq),d=(freq[1]-freq[0])); freqlm = n.fft.fftshift(freqlm)
        print "###small imaginary components are error, nothing to worry about"
        rbm2interp = interpolate.interp2d(freqlm, freqlm, rbm2, kind='cubic')
    for key in clos_app:
        cnt = cnt+1
        if (cnt/1000)*1000 == cnt:
            print 'Calculating baseline pair %d out of %d:' % (cnt,N)
        bl1,bl2 = key[0],key[1]
        t1,t2 = clos_app[key][1],clos_app[key][2]
        correlation,(uvw1,uvw2) = get_corr(aa, src, bm_intpl, t1,t2, bl1, bl2)
        if correlation == 0: continue
        if ovlpweight: ovlp = get_ovlp(aa,t1,t2,rbm2interp)
        else: ovlp = 1.
        weight = get_weight(aa,bl1,bl2,uvw1,multweight,noiseweight,ovlp)
        #while correlation > cutoff:
        if puv: final.append((weight*correlation,correlation,(bl1,t1,uvw1),(bl2,t2,uvw2)))
        else: final.append((weight*correlation,correlation,(bl1,t1),(bl2,t2)))
        #t1,t2 = t1+dt,t2+dt
        try: correlation,(uvw1,uvw2)  = get_corr(aa, src,bm_intpl, t1,t2, bl1, bl2)
        except(TypeError): correlation  = 0.
        else:
            if ovlpweight: ovlp = get_ovlp(aa,t1,t2,rbm2interp)
            else: ovlp = 1.
            weight = get_weight(aa,bl1,bl2,uvw1,multweight,noiseweight,ovlp)

    quick_sort.quick_sort(final,0,len(final)-1)
    return final
Ejemplo n.º 31
0
def compute(myVelfield, MyParams):

    interp_kind = 'quintic'

    # Scipy returns a function that you can use on a new set of x,y pairs.
    f_east = interpolate.interp2d(myVelfield.elon,
                                  myVelfield.nlat,
                                  myVelfield.e,
                                  kind=interp_kind)
    f_north = interpolate.interp2d(myVelfield.elon,
                                   myVelfield.nlat,
                                   myVelfield.n,
                                   kind=interp_kind)

    # The new interpolation grid: a new set of points with some chosen spacing
    xarray = np.arange(MyParams.coord_box[0], MyParams.coord_box[1],
                       MyParams.grid_inc)
    yarray = np.arange(MyParams.coord_box[2], MyParams.coord_box[3],
                       MyParams.grid_inc)
    [X, Y] = np.meshgrid(xarray, yarray)

    # Evaluate the linear or cubic interpolation function at new points
    new_east = np.zeros(np.shape(X))
    new_north = np.zeros(np.shape(X))
    for i in range(len(yarray)):
        for j in range(len(xarray)):
            new_east[i][j] = f_east(xarray[j], yarray[i])
            # only want to give the functions one point at a time.
            new_north[i][j] = f_north(xarray[j], yarray[i])

    # Grid increments
    typical_lat = float(MyParams.map_range[2])
    xinc = MyParams.grid_inc * 111.000 * np.cos(np.deg2rad(typical_lat))
    # in km (not degrees)
    yinc = MyParams.grid_inc * 111.000
    # in km (not degrees)

    # Computing the elements of the strain tensor from the
    rot = np.zeros(np.shape(X))
    # 2nd invariant of rotation rate tensor
    I2nd = np.zeros(np.shape(X))
    # 2nd invariant of strain rate tensor
    max_shear = np.zeros(np.shape(X))
    # max shear of strain rate tensor
    e1 = np.zeros(np.shape(X))
    # maximum principal strain (array of float)
    e2 = np.zeros(np.shape(X))
    # minimum principal strain (array of float)
    v00 = np.zeros(np.shape(X))
    # more complicated: eigenvectors (array of matrix 2x2)
    v01 = np.zeros(np.shape(X))
    # more complicated: eigenvectors (array of matrix 2x2)
    v10 = np.zeros(np.shape(X))
    # more complicated: eigenvectors (array of matrix 2x2)
    v11 = np.zeros(np.shape(X))
    # more complicated: eigenvectors (array of matrix 2x2)
    dilatation = np.zeros(np.shape(X))

    # the strain calculation
    for j in range(len(yarray) - 1):
        for i in range(len(xarray) - 1):
            up = new_east[j][i]
            vp = new_north[j][i]
            uq = new_east[j][i + 1]
            vq = new_north[j][i + 1]
            ur = new_east[j + 1][i]
            vr = new_north[j + 1][i]

            [dudx, dvdx, dudy,
             dvdy] = strain_tensor_toolbox.compute_displacement_gradients(
                 up, vp, ur, vr, uq, vq, xinc, yinc)

            # The components that are easily computed
            # Units: nanostrain per year.
            [exx, exy, eyy, rotation
             ] = strain_tensor_toolbox.compute_strain_components_from_dx(
                 dudx, dvdx, dudy, dvdy)
            rot[j][i] = abs(rotation)

            # Compute a number of values based on tensor properties.
            I2nd[j][i] = np.log10(
                np.abs(strain_tensor_toolbox.second_invariant(exx, exy, eyy)))
            [e11, e22,
             v1] = strain_tensor_toolbox.eigenvector_eigenvalue(exx, exy, eyy)
            e1[j][i] = e11
            e2[j][i] = e22
            v00[j][i] = v1[0][0]
            v10[j][i] = v1[1][0]
            v01[j][i] = v1[0][1]
            v11[j][i] = v1[1][1]
            max_shear[j][i] = (e11 - e22) / 2
            dilatation[j][i] = e11 + e22

    return [
        xarray, yarray, I2nd, max_shear, rot, e1, e2, v00, v01, v10, v11,
        dilatation
    ]
Ejemplo n.º 32
0
    def at_val(self,
               new_in_eng,
               new_eng,
               interp_type='val',
               log_interp=False,
               bounds_error=None,
               fill_value=np.nan):
        """2D interpolation at specified abscissa.

        Interpolation is logarithmic. 2D interpolation should be preferred over 1D interpolation over each abscissa in the interest of accuracy.

        Parameters
        ----------
        new_in_eng : ndarray
            The injection energy abscissa or injection energy bin indices at which to interpolate.
        new_eng : ndarray
            The energy abscissa or energy abscissa bin indices at which to interpolate.
        interp_type : {'val', 'bin'}
            The type of interpolation. 'bin' uses bin index, while 'val' uses the actual injection energies.
        log_interp : bool, optional
            Whether to perform an interpolation over log of the grid values. Default is False.
        bounds_error : bool, optional
            See scipy.interpolate.interp1d.
        fill_value : array-like or (array-like, array-like) or "extrapolate", optional
            See scipy.interpolate.interp1d.

        Returns
        -------
        TransFuncAtRedshift
            New transfer function at the new abscissa.
        """

        # 2D interpolation, specified by vectors of length eng, in_eng,
        # and grid dimensions in_eng x eng.
        # interp_func takes (eng, in_eng) as argument.

        non_zero_grid = self.grid_vals
        non_zero_N_und = self.N_underflow
        non_zero_eng_und = self.eng_underflow
        # set zero values to some small value for log interp.
        non_zero_grid[np.abs(non_zero_grid) < 1e-100] = 1e-200
        non_zero_N_und[np.abs(non_zero_N_und) < 1e-100] = 1e-200
        non_zero_eng_und[np.abs(non_zero_eng_und) < 1e-100] = 1e-200

        if interp_type == 'val':

            if log_interp:
                interp_grid = np.log(non_zero_grid)
                N_und_grid = np.log(non_zero_N_und)
                eng_und_grid = np.log(non_zero_eng_und)
            else:
                interp_grid = non_zero_grid
                N_und_grid = non_zero_N_und
                eng_und_grid = non_zero_eng_und

            interp_func = interpolate.interp2d(np.log(self.eng),
                                               np.log(self.in_eng),
                                               interp_grid,
                                               bounds_error=bounds_error,
                                               fill_value=np.log(fill_value))

            interp_func_N_und = interpolate.interp1d(np.log(self.in_eng),
                                                     N_und_grid,
                                                     bounds_error=False,
                                                     fill_value=0)

            interp_func_eng_und = interpolate.interp1d(np.log(self.in_eng),
                                                       eng_und_grid,
                                                       bounds_error=False,
                                                       fill_value=0)

            new_tf = TransFuncAtRedshift([])

            new_tf._spec_type = self.spec_type

            if log_interp:
                new_tf._grid_vals = np.atleast_2d(
                    np.exp(interp_func(np.log(new_eng), np.log(new_in_eng))))
                interp_vals_N_und = np.exp(
                    interp_func_N_und(np.log(new_in_eng)))
                interp_vals_eng_und = np.exp(
                    interp_func_eng_und(np.log(new_in_eng)))
            else:
                new_tf._grid_vals = np.atleast_2d(
                    interp_func(np.log(new_eng), np.log(new_in_eng)))
                interp_vals_N_und = interp_func_N_und(np.log(new_in_eng))
                interp_vals_eng_und = interp_func_eng_und(np.log(new_in_eng))

            # Re-zero small values.
            new_tf._grid_vals[new_tf.grid_vals < 1e-100] = 0
            interp_vals_N_und[interp_vals_N_und < 1e-100] = 0
            interp_vals_eng_und[interp_vals_eng_und < 1e-100] = 0

            new_tf._eng = new_eng
            new_tf._in_eng = new_in_eng
            new_tf._rs = self.rs
            new_tf._N_underflow = interp_vals_N_und
            new_tf._eng_underflow = interp_vals_eng_und

            return new_tf

        elif interp_type == 'bin':

            if issubclass(new_eng.dtype.type, np.integer):
                return self.at_in_eng(new_in_eng,
                                      interp_type='bin',
                                      log_interp=log_interp).at_eng(
                                          new_eng, interp_type='bin')

            log_new_in_eng = np.interp(np.log(new_in_eng),
                                       np.arange(self.in_eng.size),
                                       np.log(self.in_eng))

            log_new_eng = np.interp(np.log(new_eng), np.arange(self.eng.size),
                                    np.log(self.eng))

            return self.at_val(np.exp(log_new_in_eng),
                               np.exp(log_new_eng),
                               interp_type='val',
                               log_interp=log_interp,
                               bounds_error=bounds_error,
                               fill_value=fill_value)
Ejemplo n.º 33
0
    def interp_image(self, x, y, z):

        if isMPL2:
            return x, y, z
        else:
            axes = self.get_container()

            atrans = axes.transAxes.transform
            idtrans = axes.transData.inverted().transform
            p0, p1 = atrans([(0, 0), (1, 1)])
            dx = np.floor(p1[0]-p0[0])+2
            dy = np.floor(p1[1]-p0[1])+2
            xp = idtrans(
                np.transpose(
                    np.vstack((np.floor(p0[0])+np.arange(int(dx)),
                               np.linspace(p0[0], p1[0], dx)))))[:, 0]
            yp = idtrans(
                np.transpose(
                    np.vstack((np.floor(p0[1])-1+np.zeros(int(dy)),
                               np.linspace(p0[1], p1[1], dy)))))[:, 1]

            # eliminate points outside the data range
            #xp = np.array([tmp for tmp in xp if (tmp > np.min(x) and tmp < np.max(x))])
            #yp = np.array([tmp for tmp in yp if (tmp > np.min(y) and tmp < np.max(y))])

            interp = self.getp("interp")
            from scipy.interpolate import RegularGridInterpolator
            if ((x.size*y.size == z.size and interp == 'nearest') or
                    (x.size*y.size == z.size and interp == 'linear')):
                f = RegularGridInterpolator((y, x), z, method=interp,
                                            bounds_error=False, fill_value=np.nan)
                XP, YP = np.meshgrid(xp, yp)
                p1 = np.transpose(np.vstack((YP.flatten(), XP.flatten())))
                zp = f(p1)
                zp = zp.reshape((len(yp), len(xp))).astype(float)
            elif (x.size*y.size != z.size or interp == 'nearest' or
                  np.any(np.isnan(z))):
                if interp == 'quintic':
                    interp = 'cubic'
                X, Y = np.meshgrid(x, y)
                p1 = np.transpose(np.vstack((X.flatten(), Y.flatten())))
                XP, YP = np.meshgrid(xp, yp)
                interp = self.getp("interp")
                # print 'griddata', interp
                zp = griddata(p1, z.flatten(),
                              (XP.flatten(), YP.flatten()),
                              method=str(interp))
                zp = zp.reshape((len(yp), len(xp))).astype(float)

            else:
                f = interp2d(x, y, z, kind=interp)
                zp = f(xp, yp)
    #           print(zp)
    #        if interp == 'nearest':
            # this hide the outside of image when even 'nearest' is
            # used
            zp[:, xp < np.min(x)] = np.nan
            zp[:, xp > np.max(x)] = np.nan
            zp[yp < np.min(y), :] = np.nan
            zp[yp > np.max(y), :] = np.nan

            return xp, yp, zp
Ejemplo n.º 34
0
def grib2csv(file_dict):
    r"""Convert a dict of grib files to a CSV."""
    pass
    import numpy as np
    from collections import defaultdict
    import pandas as pd
    from scipy.interpolate import interp2d
    from functools import reduce
    # Resolution of lat and lon on the uniformly interpolated grid.
    lat_uniform = np.arange(30, 35, 0.125)
    lon_uniform = np.arange(110, 123, 0.125)
    pivoted_dataframes = defaultdict(
        dict)  # Dimensions: (Time, Model, (Lat, Lon))
    unpivoted_dataframes = dict(
    )  # Dimensions: (Time, DataFrame: (Model, lat, lon))
    for model, model_file_list in file_dict.items():
        for model_file in model_file_list:
            # Open and read file
            grbmsg = pygrib.open(model_file)[1]
            lat, lon, values = read_from_single_grbmsg(grbmsg)

            # Unit conversion
            units_grbmsg = grbmsg['parameterUnits']
            short_name = 'PRCP'
            if units_grbmsg == 'm':
                values = values * 1000.
            elif units_grbmsg != 'kg m-2':
                print('Other kinds of precipitation units detected: {}'.format(
                    units_grbmsg))

            # Get validity datetime
            initial_datetime = "{:08d}{:02d}".format(grbmsg['validityDate'],
                                                     grbmsg['validityTime'])
            validity_datetime = "{:08d}{:02d}".format(grbmsg['dataDate'],
                                                      grbmsg['dataTime'])

            # Do 2d-interpolation on all data to uniform grids.
            f = interp2d(lon, lat,
                         values)  # TODO: May modify parameter 'kind' later
            values_uniform = f(lon_uniform, lat_uniform)
            values_uniform[values_uniform < 0.1] = 0.0

            # TODO:
            # Dimensions: (Time, Model, (Lat, Lon))
            # 1. Put (lat, lon) data into DataFrames with lat, lon axes.
            pivoted_dataframes[validity_datetime][model] = pd.DataFrame(
                values_uniform, lat_uniform, lon_uniform)
            # 2. Do melting ("Unpivoting") to the DataFrames.
            pivoted_dataframes[validity_datetime][model][
                'lat'] = pivoted_dataframes[validity_datetime][model].index
            pivoted_dataframes[validity_datetime][model] = pd.melt(
                pivoted_dataframes[validity_datetime][model],
                id_vars=['lat'],
                var_name='lon',
                value_name='prcp.{}'.format(model))
            # Test

    # 3. Merge them together as one DataFrame
    for key_date in pivoted_dataframes.keys():
        unpivoted_dataframes[key_date] = reduce(
            lambda left, right: pd.merge(left, right, on=['lat', 'lon']),
            pivoted_dataframes[key_date].values())
        unpivoted_dataframes[key_date]['time'] = key_date
    unpivoted_dataframes = pd.concat(
        [value for value in unpivoted_dataframes.values()])
    return unpivoted_dataframes
Ejemplo n.º 35
0
def begin(index):
    #i = int(index)
    i = int(index.split('-')[0])
    mgi = int(index.split('-')[1])
    color = index.split('-')[2]

    #try:
    print(index)
    #filename = 'Test Data Extract/' + str(i) + '.fit'
    #filename = str(i) + '-g.fit'

    try:
        # Open the Experiment Absorber's data
        qlist = fits.open('/data/marvels/billzhu/Experiment Absorbers/' +
                          color + '/' + str(index) + '_EA.fit')
        abs_data = qlist[0].data.astype(float)

        # Open a reference QSO's data
        qsofile = fits.open(
            '/data/marvels/billzhu/2175 Reference Quasar Cut/' + color + '/' +
            str(index) + '_REF.fit')
        qsodata = qsofile[0].data.astype(float)

        # Open the reference QSO's field image
        scifile = fits.open('/data/marvels/billzhu/2175 Reference Dataset/' +
                            color + '/' + str(index) + '.fit')
        scidata = scifile[0].data.astype(float)

        # Open the object binary table
        obj_table = Table.read('/data/marvels/billzhu/2175 Reference Obj/' +
                               str(i) + '-' + str(mgi) + '.fit',
                               hdu=1)
    except:
        return

    pointer = 0
    if color == 'g':
        pointer = 1
    if color == 'r':
        pointer = 2
    if color == 'i':
        pointer = 3
    if color == 'z':
        pointer = 4
    if color == 'u':
        pointer = 0

    #line_data = linecache.getline('Full Data.txt', i).split()
    #line_data = linecache.getline('DR12 QSO.txt', i).split()
    #print(len(line_data))
    #obj_id = int(line_data[52])

    # Recalculate the sigma stats after background subtraction
    #mean, median, std = sigma_clipped_stats(scidata, sigma=3.0, iters=5)
    #print("%f, %f, %f" % (mean, median, std))

    largearr = []
    stars = []
    chunk_size = 50

    qx = qsofile[0].header['XCOORD']
    qy = qsofile[0].header['YCOORD']
    obj_id = qsofile[0].header['ID']

    for j in range(len(obj_table)):
        sx = obj_table['COLC'][j][pointer]
        sy = obj_table['ROWC'][j][pointer]
        flags1 = detflags(obj_table['OBJC_FLAGS'][j])
        flags2 = detflags(obj_table['OBJC_FLAGS2'][j])

        #try:
        if obj_table['OBJC_TYPE'][j] == 6 and flags1[12] == False and flags1[
                17] == False and flags1[18] == False and flags2[
                    27] == False and distance(sx, sy, qx, qy) > 5 and inbounds(
                        sx + chunk_size + 6, sy + chunk_size + 6
                    ) and inbounds(
                        sx - chunk_size - 5, sy - chunk_size - 5
                    ) and obj_table['PSFMAG'][j][pointer] < 18 and obj_table[
                        'M_RR_CC'][j][pointer] > 0 and abs(
                            obj_table['M_RR_CC'][j][pointer] -
                            obj_table['M_RR_CC'][obj_id - 1][pointer]
                        ) < 0.1 * obj_table['M_RR_CC'][obj_id - 1][pointer]:

            #try:
            """
			preshift = scidata[int(sy - 10) : int(sy + 11), int(sx - 10) : int(sx + 11)]
			xc, yc = centroid_2dg(preshift, mask = None)
			xc += quasar['COLC'][pointer] - 10
			yc += quasar['ROWC'][pointer] - 10
			"""

            xc = obj_table['COLC'][j][pointer]
            yc = obj_table['ROWC'][j][pointer]
            preshift = scidata[int(yc - chunk_size - 5):int(yc + chunk_size +
                                                            6),
                               int(xc - chunk_size - 5):int(xc + chunk_size +
                                                            6)]
            spline = interpolate.interp2d(
                np.arange(int(xc - chunk_size - 5), int(xc + chunk_size + 6)),
                np.arange(int(yc - chunk_size - 5), int(yc + chunk_size + 6)),
                preshift)

            xrang = np.arange(xc - chunk_size, xc + chunk_size + 1)
            yrang = np.arange(yc - chunk_size, yc + chunk_size + 1)

            if len(xrang) > 2 * chunk_size + 1:
                xrang = xrang[:-1]
            if len(yrang) > 2 * chunk_size + 1:
                yrang = yrang[:-1]

            shifted1 = spline(xrang, yrang)

            # Subtract off accurate local sky background
            shifted1 -= sigma_clipped_stats(shifted1, sigma=3.0, iters=5)[1]
            """
			background = []

			for r in range(len(shifted1)):
				for c in range(len(shifted1)):
					if distance(r, c, 150, 150) > 150:
						background.append(shifted1[r, c])

			true_bkg = sigma_clipped_stats(background, sigma=3.0, iters=5)[1]
			shifted1 -= true_bkg
			"""

            # Take out the PSF star's image, and any absorbers associated with it if very close

            mean, median, std = sigma_clipped_stats(shifted1,
                                                    sigma=3.0,
                                                    iters=5)

            visited = connected(
                shifted1, chunk_size, chunk_size, mean + std / 4,
                np.zeros((2 * chunk_size + 1, 2 * chunk_size + 1), dtype=bool),
                obj_table['PETROTHETA'][j][pointer] / 0.396 * 1.2 + 3)
            """
			poststamp = np.zeros((2 * chunk_size + 1, 2 * chunk_size + 1))
			for r in range(len(shifted1)):
				for c in range(len(shifted1)):
					if visited[c][r] == True:
						poststamp[c][r] = shifted1[c][r]
		 
			shifted1 -= poststamp
			"""
            """
			mag22 = 0
			if color == 'g':
				mag22 = 2500
			if color == 'r':
				mag22 = 1900
			if color == 'i':
				mag22 = 1400
			if color == 'z':
				mag22 = 300
			"""

            #print("%f, %f" % (xc, yc))
            shifted1 = checkInner(shifted1, obj_table, xc, yc, mean, std,
                                  pointer)
            shifted1 = perimeter(shifted1, mean, std)
            #shifted1 += poststamp

            #gauss1 = photutils.fit_2dgaussian(shifted1[40 : 61, 40 : 61], mask = None)
            #fit_fwhm_x = 2*np.sqrt(2*np.log(2))*np.sqrt(abs(gauss1.x_stddev.value))
            #fit_fwhm_y = 2*np.sqrt(2*np.log(2))*np.sqrt(abs(gauss1.y_stddev.value))

            #print("%f, %f, %f, %f" % (fit_fwhm_x, fit_fwhm_y, fwhm_x, fwhm_y))

            #if abs(fit_fwhm_x - fwhm_x) < 0.25 and abs(fit_fwhm_y - fwhm_y) < 0.25:
            #print(shifted1[50][50])

            if shifted1[50][50] > 0.05:

                #shifted1 = normalize(shifted1, 50, 50, np.max(shifted1), np.max(qsodata), mean1 + 5 * std1, np.zeros((101, 101), dtype=bool))

                #visited = connected(shifted1, 50, 50, mean + 1 * std, np.zeros((101, 101), dtype=bool))
                #shifted1 = gaussian_filter(shifted1, sigma=std)
                #smax = np.max(shifted1)

                for r in range(len(visited)):
                    for c in range(len(visited)):
                        #if distance(r, c, 50, 50) < 1.2 * obj_table['iso_a'][obj_id - 1][pointer]/2 + 3:
                        shifted1[c][r] /= obj_table['PSFFLUX'][j][pointer]
                        shifted1[c][r] *= obj_table['PSFFLUX'][obj_id -
                                                               1][pointer]

                #shifted1 /= obj_table['PSFFLUX'][j][pointer]
                #shifted1 *= obj_table['PSFFLUX'][obj_id - 1][pointer]

                largearr.append(np.reshape(shifted1, 10201))
                stars.append(j)
                #print(True)

                #stars.append(shifted1)
        #except:
        #continue

    largearr = np.array(largearr)
    #largearr *= 1 + 10**((obj_table['PSFMAG'][obj_id - 1][pointer] - 24.5) / 2.5)
    #largearr /= photonCount(50, 50, obj_table['PETROTHETA'][obj_id - 1][pointer] / 0.396 , qsodata)
    #largearr *= photonCount(50, 50, obj_table['PETROTHETA'][obj_id - 1][pointer] / 0.396 , qsodata_copy)
    print(np.shape(largearr))

    # Set number of components in PCA, use Incremental PCA (IPCA) due to high efficiency and speed
    numcomp = len(largearr)

    # Need a healthy number of sources to make the PSF fitting in order to decrease noise, setting at 5% threshold

    #if len(largearr) < 10:
    #    print('No Sources')
    #    return

    print(numcomp)
    mean_vector = []

    #print(np.shape(largearr))

    try:
        for j in range(0, 10201):
            mean_vector.append(np.mean(largearr[:, j]))
    except:
        print("NO SOURCE FOUND")
        return

    largearr -= mean_vector

    ipca = IncrementalPCA(n_components=numcomp)
    ipca.fit(largearr)
    ipca_comp = ipca.components_
    #print(np.shape(ipca_comp))

    # Only use the components of the central portion of the quasar, since there may be overfitting due to strength of ipca

    new_comp = []
    for j in range(len(largearr)):
        temp = np.reshape(ipca_comp[j, :],
                          (2 * chunk_size + 1, 2 * chunk_size + 1))
        new_comp.append(np.reshape(temp[47:54, 47:54], 49))

    new_comp = np.array(new_comp)
    new_comp = new_comp.T
    print(np.shape(new_comp))

    ipca_comp = ipca_comp.T

    #print(ipca_comp)
    take_final = numcomp

    # Calculate the residues with offsets from 1 to 8 pixels

    pixel = np.arange(0, 8)

    for offset in pixel:
        qsodata_copy = np.array(qsodata)
        abs_data_copy = np.array(abs_data)

        print(qlist[0].header['PSFMAG'])
        factor = 10**(qlist[0].header['PSFMAG'] / -2.5 - 19.5 / -2.5)
        abs_data_copy /= (factor * 10)
        qsodata_copy[:, offset:101] += abs_data_copy[:, 0:101 - offset]

        # Final fitting of the first n components, as determined by take_final, into the quasar to build a PSF fit
        #print(np.shape(ipca_comp))
        qsodata_copy = np.reshape(qsodata_copy, (2 * chunk_size + 1)**2)
        qsodata_copy -= mean_vector
        qsodata_copy = np.reshape(qsodata_copy,
                                  (2 * chunk_size + 1, 2 * chunk_size + 1))
        coeff = np.dot(np.reshape(qsodata_copy[47:54, 47:54], 49), new_comp)

        #coeff = np.dot(qsodata, ipca_comp)

        final_fit = np.dot(ipca_comp[:, 0:take_final], coeff[0:take_final])
        final_fit += mean_vector
        final_fit = np.reshape(final_fit,
                               (2 * chunk_size + 1, 2 * chunk_size + 1))
        #final_fit /= len(largearr)

        qsodata_copy = np.reshape(qsodata_copy, (2 * chunk_size + 1)**2)
        qsodata_copy += mean_vector
        qsodata_copy = np.reshape(qsodata_copy,
                                  (2 * chunk_size + 1, 2 * chunk_size + 1))
        """
		background = []

		for r in range(len(final_fit)):
			for c in range(len(final_fit)):
				if distance(r, c, 50, 50) > 50:
					background.append(final_fit[r, c])
		"""

        mean, median, stddev = sigma_clipped_stats(final_fit)
        final_fit -= median

        #final_fit /= final_fit[50, 50]
        #final_fit *= qsodata_copy[50, 50]
        final_fit /= photonCount(
            50, 50, 2 * obj_table['PSF_FWHM'][obj_id - 1][pointer], final_fit)
        final_fit *= photonCount(
            50, 50, 2 * obj_table['PSF_FWHM'][obj_id - 1][pointer],
            qsodata_copy)

        print("%f, %f" % (np.max(qsodata_copy), np.max(final_fit)))

        # Final residue from subtraction of PSF from QSO

        residue = qsodata_copy - final_fit
        mean, median, stddev = sigma_clipped_stats(residue, sigma=3.0, iters=5)
        residue -= median

        try:
            fits.writeto('/data/marvels/billzhu/Experiment PSF Subtract/' +
                         color + '/' + str(index) + '-' + str(offset) +
                         '_SUB.fit',
                         residue,
                         qlist[0].header,
                         clobber=True)
            fits.writeto('/data/marvels/billzhu/Experiment PSF Cut/' + color +
                         '/' + str(index) + '-' + str(offset) + '_PSF.fit',
                         final_fit,
                         qlist[0].header,
                         clobber=True)

            print('\n')

            print("DONE TO BOTTOM")
        except:
            print('HEADER IS CORRUPT')
Ejemplo n.º 36
0
    # ===============================================================

    layermodel = None
    surfacemodel = None

    # Option 1: Use 1 V/km field:
    N1Vkm = True
    E1Vkm = True
    if testfield:
        en, ee = np.zeros((len(lat), len(lon)), dtype=npf), np.zeros(
            (len(lat), len(lon)), dtype=npf)
        if N1Vkm:
            en.fill(1.)
        if E1Vkm:
            ee.fill(1.)
        en_int = interpolate.interp2d(lon, lat, en)
        ee_int = interpolate.interp2d(lon, lat, ee)

    # Option 2 (-e): Use external field file:
    else:
        darray = np.loadtxt(efilepath, skiprows=0)
        # Reshape into usable array:
        nlat, nlon = len(lat), len(lon)
        ien, iee = 2, 5  # Indices of N and E field component (real parts only here)
        endata = np.reshape(darray[:, ien], (nlat, nlon), order='F')
        eedata = np.reshape(darray[:, iee], (nlat, nlon), order='F')

        # Interpolate E-field onto these points:
        en_int = interpolate.interp2d(lon, lat, endata)
        ee_int = interpolate.interp2d(lon, lat, eedata)
Ejemplo n.º 37
0
x = np.linspace(-6, 6, 11)
y = np.linspace(-6, 6, 11)

xx, yy = np.meshgrid(x, y)

z = f(xx, yy)

x_new = np.linspace(-6, 6, 20)
y_new = np.linspace(-6, 6, 20)

xx_new, yy_new = np.meshgrid(x_new, y_new)

z_true = f(xx_new, yy_new)

f_scipy = interpolate.interp2d(x, y, z, kind='cubic')

z_scipy = f_scipy(x_new, y_new)

bicubic_interpolation2(x, y, z,"my_interp")
import my_interp
z_new = np.zeros((x_new.size, y_new.size))
for my_n, my_x in enumerate(x_new):
    for my_m, my_y in enumerate(y_new):
        z_new[my_n,my_m] = my_interp.my_interp(my_x, my_y)

fig, ax = plt.subplots(2, 2, sharey=True, figsize=(16,12))

img0 = ax[0, 0].scatter(xx, yy, c=z, s=100)
ax[0, 0].set_title('original points')
fig.colorbar(img0, ax=ax[0, 0], orientation='vertical', shrink=1, pad=0.01)
Ejemplo n.º 38
0
def add_velocity_vectors(ax,
                         ds,
                         fn,
                         v_scl=3,
                         v_leglen=0.5,
                         nngrid=80,
                         zlev='top',
                         center=(.8, .05)):
    # v_scl: scale velocity vector (smaller to get longer arrows)
    # v_leglen: m/s for velocity vector legend
    xc = center[0]
    yc = center[1]
    # GET DATA
    G = zrfun.get_basic_info(fn, only_G=True)
    if zlev == 'top':
        u = ds['u'][0, -1, :, :].squeeze()
        v = ds['v'][0, -1, :, :].squeeze()
    elif zlev == 'bot':
        u = ds['u'][0, 0, :, :].squeeze()
        v = ds['v'][0, 0, :, :].squeeze()
    else:
        zfull_u = get_zfull(ds, fn, 'u')
        zfull_v = get_zfull(ds, fn, 'v')
        u = get_laym(ds, zfull_u, ds['mask_u'][:], 'u', zlev).squeeze()
        v = get_laym(ds, zfull_v, ds['mask_v'][:], 'v', zlev).squeeze()
    # ADD VELOCITY VECTORS
    # set masked values to 0
    ud = u.data
    ud[u.mask] = 0
    vd = v.data
    vd[v.mask] = 0
    # create interpolant
    import scipy.interpolate as intp
    ui = intp.interp2d(G['lon_u'][0, :], G['lat_u'][:, 0], ud)
    vi = intp.interp2d(G['lon_v'][0, :], G['lat_v'][:, 0], vd)
    # create regular grid
    aaa = ax.axis()
    daax = aaa[1] - aaa[0]
    daay = aaa[3] - aaa[2]
    axrat = np.cos(np.deg2rad(aaa[2])) * daax / daay
    x = np.linspace(aaa[0], aaa[1], int(round(nngrid * axrat)))
    y = np.linspace(aaa[2], aaa[3], int(nngrid))
    xx, yy = np.meshgrid(x, y)
    # interpolate to regular grid
    uu = ui(x, y)
    vv = vi(x, y)
    mask = uu != 0
    # plot velocity vectors
    ax.quiver(xx[mask],
              yy[mask],
              uu[mask],
              vv[mask],
              units='y',
              scale=v_scl,
              scale_units='y',
              color='k')
    ax.quiver([xc, xc], [yc, yc], [v_leglen, v_leglen], [v_leglen, v_leglen],
              units='y',
              scale=v_scl,
              scale_units='y',
              color='k',
              transform=ax.transAxes)
    ax.text(xc + .05,
            yc,
            str(v_leglen) + ' m/s',
            horizontalalignment='left',
            transform=ax.transAxes)
Ejemplo n.º 39
0
def load_data(stamp, burst, loc, meta, swath):
    '''
    This script calibrates and loads input SLC images.

    '''
    print('Reading...')
    time_1 = datetime.datetime.utcnow()
    
    if swath == 'IW1':
        str2 = '-004.xml'
        datastr = '-004.tiff'
    elif swath == 'IW2':
        str2 = '-005.xml'
        datastr = '-005.tiff'
    elif swath == 'IW3':
        str2 = '-006.xml'
        datastr = '-006.tiff'
    
    dataloc = glob.glob(loc + r'\measurement\*' + datastr)
    dataloc = dataloc[0]
    
    name = glob.glob(loc + r'\annotation\*' + str2)
    name = name[0]
    # Open element tree and retrieve parameters
    tree = ElementTree.parse(name)
    
    olp = tree.findall(".//imageAnnotation/imageInformation/numberOfSamples")
    mylist = [t.text for t in olp]
    no_pixels = int(mylist[0])
    olp = tree.findall(".//imageAnnotation/imageInformation/numberOfLines")
    mylist = [t.text for t in olp]
    no_lines = int(mylist[0])
    
    
    name = glob.glob(loc + r'\annotation\calibration\calibration*' + str2)
    name = name[0]
    # Open element tree and retrieve parameters
    tree = ElementTree.parse(name)
    # Load meta data in dictionary meta

    line = []
    olp = tree.findall(".//calibrationVectorList/calibrationVector")
    for ele in olp:
        i = ele.findall('line')
        linei = [t.text for t in i]
        line.append(int(linei[0]))
    y = np.asarray(line)
    
    olp = tree.findall(".//calibrationVectorList/calibrationVector/pixel")
    for t in olp:
        t3 = t.text
        t1 = t3.split()
        t2 = [float(t) for t in t1]
        x = np.asarray(t2)
    
    olp = tree.findall(".//calibrationVectorList/calibrationVector/sigmaNought")
    for i,t in enumerate(olp):
        t3 = t.text
        t1 = t3.split()
        t2 = [float(t) for t in t1]
        
        if i ==0:
            t_arr = np.asarray(t2)
        else:
            t_arr0 = t_arr
            t_arr1 = np.asarray(t2)
            t_arr = np.vstack([t_arr0,t_arr1])
    
    
    f = interpolate.interp2d(x, y, t_arr, kind='linear')
    xnew = np.arange(0, no_pixels, 1)
    ynew = np.arange(0, no_lines, 1)
    znew = f(xnew, ynew)
    
        
    ds = gdal.Open(dataloc)
    slc = np.array(ds.GetRasterBand(1).ReadAsArray())
      
    ints = np.abs(slc)
    phase = np.angle(slc)
    
    s0 = np.sqrt(ints**2 / (znew**2)) #https://sentinel.esa.int/web/sentinel/radiometric-calibration-of-level-1-products
    slc_new = s0 * np.exp(1j * phase)

    print('Saving.....')
        # ~~~~Save data~~~~~
    
    np.save(os.path.join(stamp, 'data_' + swath + '_slc.npy'), slc_new)
    time_2 = datetime.datetime.utcnow()
    diff_t = round((time_2 - time_1).total_seconds())
    print('Calibration is finished in    ' + str(diff_t) + '   seconds.')
    print('------------------------------------------------------------')
Ejemplo n.º 40
0
a_p = float(sys.arg[1])
m_p = float(sys.arg[2])
m_star = float(sys.arg[3])

R_H = a_p * (m_p / 3. * m_star)**{1 / 3.}

e_p = float(sys.arg[4])
e_sat = float(sys.arg[5])
sub = int(sys.arg[6])  # 0 = moon, 1 = submoon

if sub == 0:
    data = np.genfromtxt("Contour_moon.txt", delimiter=',', comments='#')
else:
    data = np.genfromtxt("Contour_submoon.txt", delimiter=',', comments='#')

X = data[:, 0]
Y = data[:, 1]
Z = data[:, 2]

xi = np.arange(0.0, 0.51, 0.01)
yi = np.arange(0.0, 0.51, 0.01)
zi = griddata((X, Y),
              Z, (xi[None, :], yi[:, None]),
              method='linear',
              fill_value=0)

f = interp2d(xi, yi, zi, kind='linear')

print("a_c = %1.3f AU" % (f(e_p, e_sat)[0] * R_H))
Ejemplo n.º 41
0
def beddata(DEM, thicknessmap, bedsmoothing=300):
    """Function to read in datasets provided by Huss and solve for bed topography
    
    Inputs: 'DEM' and 'thicknessmap' should be filenames, 
    'bedsmoothing' should be the radius (in m) of smoothing to apply to bed.  Default is 300m
    
    Outputs: xx, yy, zz arrays; 
    bedinterp, thickinterp, seinterp 2d functions;
    xbounds, ybounds values
    """

    SE = []
    H = []
    Z = []

    hdrs_s = []
    # Read and interpolate DEM
    with open(DEM, 'r') as f:
        #headarray = [ncols, nrows, xll, yll, cellsize, nodata_val]
        print 'Currently reading DEM'
        for num in xrange(0, 6, 1):
            headern = f.readline().split()  #read info in header
            headerval = float(headern[1])
            hdrs_s.append(headerval)
        ncols_s = int(hdrs_s[0])
        nrows_s = int(hdrs_s[1])
        xll_s = hdrs_s[2]
        yll_s = hdrs_s[3]
        delta_s = hdrs_s[4]

        lines = f.read().split(
            '\r\n')  #lines in Huss files end with \r\n rather than \n alone
        for n in xrange(
                0, (len(lines) - 1), 1
        ):  #leconte_dem file reads with empty line at end, need to ignore
            line = lines[n]
            splitup = line.split(
            )  #no splitter defined--will automatically see whitespace
            for ent in xrange(
                    0, len(splitup), 1
            ):  #every entry of DEM is surface elevation, first entry is tabbed
                SEval = float(splitup[ent])
                SE.append(SEval)
    SE = np.array(SE)
    se = np.reshape(SE, (-1, ncols_s))

    xs = []
    ys = []
    for i in xrange(0, ncols_s, 1):  #x values change by column
        xs.append(xll_s + i * delta_s)
    for j in xrange(0, nrows_s, 1):  #y values change by row
        ys.append(yll_s + j * delta_s)
    #ys = ys[::-1]
    seinterp = interpolate.interp2d(xs,
                                    ys,
                                    se,
                                    kind='linear',
                                    copy=True,
                                    bounds_error=False)  #interpolated DEM

    # Read and interpolate thickness map
    hdrs_h = []
    with open(thicknessmap, 'r') as f:
        print 'Currently reading ice thickness map'
        for num in xrange(0, 6, 1):
            headern = f.readline().split()  #read info in header
            headerval = float(headern[1])
            hdrs_h.append(headerval)
        ncols_h = int(hdrs_h[0])
        nrows_h = int(hdrs_h[1])
        xll_h = hdrs_h[2]
        if xll_h != xll_s:
            print 'Warning: DEM and thickness map grids start in different locations'
        yll_h = hdrs_h[3]
        delta_h = hdrs_h[4]

        lines = f.read().split(
            '\r\n')  #lines in Huss files end with \r\n rather than \n alone
        for n in xrange(
                0, (len(lines) - 1), 1
        ):  #leconte_thick file reads with empty line at end, need to ignore
            line = lines[n]
            splitup = line.split(
            )  #no splitter defined--will automatically see whitespace
            for ent in xrange(0, len(splitup), 1):
                Hval = float(splitup[ent])
                H.append(Hval)
    H = np.array(H)
    hh = np.reshape(H, (-1, ncols_h))

    xh = []
    yh = []
    for i in xrange(0, ncols_h, 1):  #x values change by column
        xh.append(xll_h + i * delta_h)
    for j in xrange(0, nrows_h, 1):  #y values change by row
        yh.append(yll_h + j * delta_h)
    #xh = xh[::-1]
    #yh = yh[::-1]
    thickinterp = interpolate.interp2d(xh,
                                       yh,
                                       hh,
                                       kind='linear',
                                       copy=True,
                                       bounds_error=False)

    #Find appropriate grid for interpolation; get bed
    xx = []
    yy = []
    ncols = max(ncols_s, ncols_h)
    nrows = max(nrows_s, nrows_h)
    if ncols == ncols_s:
        if nrows == nrows_s:
            print 'Finer grid is DEM'
            delta = delta_s
            xx = np.array(xs)
            yy = np.array(ys)
            yy = yy[::-1]
            hnew = thickinterp(xs, ys)
            zz = np.array(se) - np.array(hnew)
        else:
            print 'Error 1: grid sizes too different'
    if ncols == ncols_h:
        if nrows == nrows_h:
            print 'Finer grid is ice thickness'
            delta = delta_h
            xx = np.array(xh)
            yy = np.array(yh)
            #yy = yy[::-1]
            senew = seinterp(xh, yh)
            zz = np.array(senew) - np.array(hh)
        else:
            print 'Error 2: grid sizes too different'

    #print 'Reshaping y.  REMEMBER to check output graphically!'
    #yy = yy[::-1] #not sure why this should be...surely for positive yll, y should be increasing?  This makes the picture of Chenega correct...may need to check again

    #Smoothing bed
    if bedsmoothing == None:
        unsmoothZ = zz  #just return zz unsmoothed
    else:
        dsmooth = ceil(bedsmoothing / delta)  #smoothing
        zz = gaussian_filter(zz, dsmooth)  #smoothing the bed
    bedinterp = interpolate.interp2d(
        xx, yy, zz, kind='linear', copy=True,
        bounds_error=True)  #might need to do transpose of Z as in Columbia?

    #finding bounds
    xbounds = (min(xx), max(xx))
    ybounds = (min(yy), max(yy))

    return (xx, yy, zz, bedinterp, thickinterp, seinterp, xbounds, ybounds)
Ejemplo n.º 42
0
    q = np.zeros((TP, TP))
    #    q=np.ones((TP,TP))
    Sol_N_next = ADI(Sol_N, x, dx, right_um, bottom_um, top_um, mu, a, b, c, d,
                     TP, q)
    #for 2N
    N = N + N
    Sol_2N, x_ex, dx_ex, right_um_ex, bottom_um_ex, top_um_ex, mu_ex, a_ex, b_ex, c_ex, d_ex, TP_ex = Set_up(
        N, dt)
    q = np.zeros((TP_ex, TP_ex))
    #    q=np.ones((TP_ex,TP_ex))
    Sol_2N_next = ADI(Sol_2N, x_ex, dx_ex, right_um_ex, bottom_um_ex,
                      top_um_ex, mu_ex, a_ex, b_ex, c_ex, d_ex, TP_ex, q)
    # Interpolate the values from the 2N grid so the points match up to the same physical location
    #Interpolate the finer grid values to the coarser grid
    the_interloper = interpolate.interp2d(x_ex,
                                          x_ex,
                                          Sol_2N_next,
                                          kind='cubic')
    Sol_int = the_interloper(x, x)
    #find the biggest difference between the solutions
    Diff_Matrix = abs(Sol_N_next[1:-1, 1:-1] - Sol_int[1:-1, 1:-1])
    max_diff = Diff_Matrix.max()

#Doubling the number of grid points resulted in less than "CLOSE ENOUGH' maximum difference between the two solutions
#We will call this convereged and go back to the previous N value for the steady state solution
#The 2N grid will serve as our "Exact'" Solution
#So that the steady state solution will have N grid points, and the "Exact" solution will have 2N grid points.
#N-final is just for reference,
N_final = round(N / 2)
N_ex = N

# =============================================================================
Ejemplo n.º 43
0
 def __init__(self):
     self._atlas501 = interp2d(_vinfs_A5, _decls_A5, _data_A5, kind='linear', fill_value=0.1, copy=False)
     self._soyuzf = interp2d(_vinfs_SF, _decls_SF, _data_SF, kind='linear', fill_value=1e-3, copy=False)
Ejemplo n.º 44
0
def merge_and_cut(filename_low, filename_height, output_dir, start_zoom, end_zoom):
    if not os.path.exists(filename_low) or not os.path.exists(filename_height):
        return None
    data_set_low = gdal.Open(filename_low)
    if data_set_low is None:
        print('Read %s failed' % filename_low)
        return None
    data_set_height = gdal.Open(filename_height)
    if data_set_height is None:
        print('Read %s failed' % filename_height)
        return None
    band_low = data_set_low.GetRasterBand(1)
    if band_low is None:
        print('Read %s band failed' % filename_low)
        return None
    x_size_low, y_size_low = data_set_low.RasterXSize, data_set_low.RasterYSize
    x0_low, dx_low, _, y0_low, _, dy_low = data_set_low.GetGeoTransform()

    band_height = data_set_height.GetRasterBand(1)
    if band_height is None:
        print('Read %s band failed' % filename_height)
        return None
    x_size_height, y_size_height = data_set_height.RasterXSize, data_set_height.RasterYSize
    x0_height, dx_height, _, y0_height, _, dy_height = data_set_height.GetGeoTransform()

    min_lng_height = x0_height
    min_lat_height = y0_height
    max_lng_height = x0_height + x_size_height * dx_height
    max_lat_height = y0_height + y_size_height * dy_height
    min_lng_low = x0_low
    min_lat_low = y0_low
    max_lng_low = x0_low + x_size_low * dx_low
    max_lat_low = y0_low + y_size_low * dy_low
    x_offset = round((min_lng_height - min_lng_low) / dx_low)
    y_offset = round((min_lat_height - min_lat_low) / dy_low)
    x_size = round((max_lng_height - min_lng_height) / dx_low)
    y_size = round((max_lat_height - min_lat_height) / dy_low)

    bounds = get_tif_tile_bounds(filename_height, output_dir, start_zoom)
    if bounds == {}:
        return
    _, value = next(iter(bounds.items()))
    _zoom_size_low = round((value[2] - value[0]) / dx_low)
    buf_size = _zoom_size_low + 128     # 设置 buf 大小大于一块地形的 size,保证按块取数据时,块是完整的

    z_low_with_buf = band_low.ReadAsArray(x_offset - buf_size, y_offset - buf_size, x_size + buf_size * 2, y_size +
                                          buf_size * 2).astype('f4')
    # z_height = band_height.ReadAsArray(0, 0, x_size_height, y_size_height).astype('f4')

    for zoom in range(start_zoom, end_zoom + 1):
        ratio = 2 ** (zoom - start_zoom)
        dsize_low = ((x_size + buf_size * 2) * ratio, (y_size + buf_size * 2) * ratio)
        _z_low_with_buf = cv2.resize(src=z_low_with_buf, dsize=dsize_low, interpolation=cv2.INTER_LINEAR)
        dsize_height = (x_size * ratio, y_size * ratio)
        _z_height = cv2.resize(src=z_height, dsize=dsize_height, interpolation=cv2.INTER_CUBIC)
        z_height = band_height.ReadAsArray(0, 0, x_size_height, y_size_height, x_size * ratio, y_size * ratio).\
            astype('f4')
        _z_height = z_height
        bound_yx = get_data_bound(_z_height, 0.8)
        # 如果没有边界 则,不融合,直接采用低精度数据 cut
        if bound_yx.shape[0] != 0:
            bound_yx = bound_yx.astype('i4')
            _x = np.zeros(shape=(0, 1))     # x y z 添加边界值
            _y = np.zeros(shape=(0, 1))
            _z = np.zeros(shape=(0, 1))
            for _bound_yx in bound_yx:
                _bound_y_height = _bound_yx[0]
                _bound_x_height = _bound_yx[1]
                _bound_z_height = _z_height[_bound_y_height, _bound_x_height]
                _bound_y_low = _bound_yx[0] + buf_size * ratio
                _bound_x_low = _bound_yx[1] + buf_size * ratio
                _bound_z_low = _z_low_with_buf[_bound_y_low, _bound_x_low]
                _z_d = _bound_z_height - _bound_z_low
                _x = np.vstack((_x, _bound_x_low))
                _y = np.vstack((_y, _bound_y_low))
                _z = np.vstack((_z, _z_d))
            # x y z 添加边界值缓冲边界 0 值
            _xy = np.hstack((_x, _y))
            _m_point = MultiPoint(_xy)
            _zero_bound = _m_point.buffer(50)
            _zero_bound_xy = _zero_bound.exterior.coords.xy
            _zero_bound_x = np.around(np.array(_zero_bound_xy[0])).reshape(len(_zero_bound_xy[0]), -1)
            _zero_bound_y = np.around(np.array(_zero_bound_xy[1])).reshape(len(_zero_bound_xy[1]), -1)
            _zero_bound_z = np.zeros(shape=(_zero_bound_x.shape))
            _x = np.vstack((_x, _zero_bound_x))
            _y = np.vstack((_y, _zero_bound_y))
            _z = np.vstack((_z, _zero_bound_z))
            # x y z 添加数据边界 0 值
            for _x_edge in range(0, (x_size + buf_size * 2) * ratio):
                _x = np.vstack((_x, [_x_edge]))
                _y = np.vstack((_y, [0]))
                _x = np.vstack((_x, [_x_edge]))
                _y = np.vstack((_y, [(y_size + buf_size * 2) * ratio]))
                _z = np.vstack((_z, [[0], [0]]))
            for _y_edge in range(0, (y_size + buf_size * 2) * ratio):
                _y = np.vstack((_y, [_y_edge]))
                _x = np.vstack((_x, [0]))
                _y = np.vstack((_y, [_y_edge]))
                _x = np.vstack((_x, [(x_size + buf_size * 2) * ratio]))
                _z = np.vstack((_z, [[0], [0]]))

            # _xy = np.hstack((_x, _y))
            # grid = np.mgrid[0:(x_size + buf_size * 2) * ratio, 0:(y_size + buf_size * 2) * ratio]
            # _z_d_new = interpolate.griddata(_xy, _z, grid, method='linear')
            func = interpolate.interp2d(_x, _y, _z,  kind='linear')
            _x_new = np.arange(0, (x_size + buf_size * 2) * ratio)
            _y_new = np.arange(0, (y_size + buf_size * 2) * ratio)
            _z_d_new = func(_x_new, _y_new)

            _z_low_with_buf = _z_low_with_buf + _z_d_new

            for y in range(y_size * ratio):
                for x in range(x_size * ratio):
                    _z_height_v = _z_height[y][x]
                    y_low = y + buf_size * ratio
                    x_low = x + buf_size * ratio
                    _z_low_v = _z_low_with_buf[y_low][x_low]
                    if abs(_z_height_v - 0) > 0.001 and abs(_z_height_v - _z_low_v) > 0.001:
                        _z_low_with_buf[y_low][x_low] = _z_height_v
        # cut
        z_merged = _z_low_with_buf
        blc_bounds = get_tif_tile_bounds(filename_height, output_dir, zoom)
        for fname in blc_bounds:
            blc_bound = blc_bounds[fname]
            blc_x_min_low = round((blc_bound[0] - min_lng_low) / dx_low)
            blc_y_min_low = round((blc_bound[3] - min_lat_low) / dy_low)
            blc_x_max_low = round((blc_bound[2] - min_lng_low) / dx_low)
            blc_y_max_low = round((blc_bound[1] - min_lat_low) / dy_low)

            blc_x_offset_low = (blc_x_min_low - x_offset + buf_size) * ratio
            blc_y_offset_low = (blc_y_min_low - y_offset + buf_size) * ratio
            blc_x_size_low = (blc_x_max_low - blc_x_min_low) * ratio
            blc_y_size_low = (blc_y_max_low - blc_y_min_low) * ratio
            blc_z_low = z_merged[blc_y_offset_low:blc_y_offset_low + blc_y_size_low, blc_x_offset_low:blc_x_offset_low + blc_x_size_low]
            points_xyz = []
            z_low = np.array(blc_z_low)
            for x in range(blc_z_low.shape[1]):
                for y in range(blc_z_low.shape[0]):
                    point_xyz = [x, y, blc_z_low[y, x]]
                    points_xyz.append(point_xyz)
            points_xyz = np.array(points_xyz)
            points_xy = points_xyz[:, 0:2]
            tri = Delaunay(points_xy)
            index = tri.simplices
            points_xyz = (points_xyz + (blc_x_min_low, blc_y_min_low, 0)) * (dx_low, dy_low, 1) + (x0_low, y0_low, 0)
            write_terrain(fname, points_xyz, index)
Ejemplo n.º 45
0
newC = math.floor(ratioC * oldC)

# newImg = np.zeros((newR,newC))

stepR = (newR - 1) / oldR
startR = stepR / 2

stepC = (newC - 1) / oldC
startC = stepC / 2

# gridX, gridY = np.meshgrid(range(newR),range(newC))

meshVecR = np.arange(startR, newR, stepR)[:oldR]
meshVecC = np.arange(startC, newC, stepC)[:oldC]

# gridR, gridC = np.meshgrid(meshVecR, meshVecC)

# newImg = griddata(gridR, gridC, (gridX, gridY), method='cubic')
linImgFunc = interp2d(meshVecC, meshVecR, img, kind='linear')
linNewImg = linImgFunc(range(newC), range(newR))

cubImgFunc = interp2d(meshVecC, meshVecR, img, kind='cubic')
cubNewImg = cubImgFunc(range(newC), range(newR))

plt.figure()
plt.imshow(linNewImg, cmap="gray")
plt.figure()
plt.imshow(cubNewImg, cmap="gray")
plt.figure()
plt.imshow(np.abs(linNewImg - cubNewImg), cmap='gray')
Ejemplo n.º 46
0
    def velocity_conversion(self, two_dimensional=True):
        from scipy.interpolate import interp2d

        #create interpolant
        vp_interpolator = interp2d(self.P_table_axis, self.T_table_axis,
                                   self.vp_table)
        vs_interpolator = interp2d(self.P_table_axis, self.T_table_axis,
                                   self.vs_table)
        rho_interpolator = interp2d(self.P_table_axis, self.T_table_axis,
                                    self.rho_table)

        def get_vals_1d(self, gravity='constant'):
            '''
         get 1d profiles of pressure, Vp, Vs, and density
         '''
            self.P1d = np.zeros((self.npts_rad))
            self.vp1d = np.zeros((self.npts_rad))
            self.vs1d = np.zeros((self.npts_rad))
            self.rho1d = np.zeros((self.npts_rad))

            if gravity == 'constant':
                g = 9.8
            else:
                print "only constant gravity is currently implemented"

            for i in range(0, self.npts_rad):
                if self.T_adiabat[i] < 300:
                    T_here = 300.0
                else:
                    T_here = self.T_adiabat[i]

                self.vp1d[i] = vp_interpolator(self.P1d[i], T_here)
                self.vs1d[i] = vs_interpolator(self.P1d[i], T_here)
                self.rho1d[i] = rho_interpolator(self.P1d[i], T_here)
                weight_of_layer = self.rho1d[i] * g * self.dpr_km * 1000.0
                weight_of_layer *= 1e-5  #convert form Pa to bar

                if i + 1 < self.npts_rad:
                    self.P1d[i + 1] = self.P1d[i] + weight_of_layer

        def get_vals_2d(self):

            #initialize arrays
            self.vp_array = np.zeros((self.npts_rad, self.npts_theta))
            self.vs_array = np.zeros((self.npts_rad, self.npts_theta))
            self.rho_array = np.zeros((self.npts_rad, self.npts_theta))

            self.dvp_abs = np.zeros((self.npts_rad, self.npts_theta))
            self.dvs_abs = np.zeros((self.npts_rad, self.npts_theta))
            self.drho_abs = np.zeros((self.npts_rad, self.npts_theta))

            self.dvp_rel = np.zeros((self.npts_rad, self.npts_theta))
            self.dvs_rel = np.zeros((self.npts_rad, self.npts_theta))
            self.drho_rel = np.zeros((self.npts_rad, self.npts_theta))

            for i in range(0, self.npts_rad):
                for j in range(0, self.npts_theta):
                    #absolute values
                    self.vp_array[i,
                                  j] = vp_interpolator(self.P1d[i], self.T[i,
                                                                           j])
                    self.vs_array[i,
                                  j] = vs_interpolator(self.P1d[i], self.T[i,
                                                                           j])
                    self.rho_array[i, j] = rho_interpolator(
                        self.P1d[i], self.T[i, j])
                    #absolute perturbations
                    self.dvp_abs[i, j] = self.vp_array[i, j] - self.vp1d[i]
                    self.dvs_abs[i, j] = self.vs_array[i, j] - self.vs1d[i]
                    self.drho_abs[i, j] = self.rho_array[i, j] - self.rho1d[i]
                    self.drho_abs[i, j] /= 1000.0  #convert from kg/m3 to g/cm3
                    #percent perturbations
                    self.dvp_rel[i,
                                 j] = ((self.vp_array[i, j] - self.vp1d[i]) /
                                       self.vp1d[i]) * 100.0
                    self.dvs_rel[i,
                                 j] = ((self.vs_array[i, j] - self.vs1d[i]) /
                                       self.vs1d[i]) * 100.0
                    self.drho_rel[i, j] = (
                        (self.rho_array[i, j] - self.rho1d[i]) /
                        self.rho1d[i]) * 100.0

        def main(self, two_dimensional):
            get_vals_1d(self, gravity='constant')

            if two_dimensional == True:
                get_vals_2d(self)

        main(self, two_dimensional)
    def make_dataset(play,
                     event_frame,
                     metrica_attack,
                     metrica_defence,
                     bokeh_attack,
                     bokeh_defence,
                     field_dimen=(
                         106.,
                         68.,
                     ),
                     new_grid_size=500):

        params = mpc.default_model_params(3)

        event = events_df.loc[[(play, int(event_frame))]]
        tracking_frame = event['Start Frame'][0]

        att_frame = bokeh_attack.loc[(play, tracking_frame)]
        att_player_frame = att_frame[att_frame['player'] != "ball"]
        att_player_frame['Shirt Number'] = att_player_frame['player'].map(
            int).map(shirt_mapping[play]).fillna("")

        def_frame = bokeh_defence.loc[(play, tracking_frame)]
        def_player_frame = def_frame[def_frame['player'] != "ball"]
        def_player_frame['Shirt Number'] = def_player_frame['player'].map(
            int).map(shirt_mapping[play]).fillna("")

        ball_frame = att_frame[att_frame['player'] == "ball"]

        PPCF, xgrid, ygrid = pvm.lastrow_generate_pitch_control_for_event(
            play,
            event_frame,
            events_df,
            metrica_attack,
            metrica_defence,
            params,
            field_dimen=(
                106.,
                68.,
            ),
            n_grid_cells_x=50)
        PT = pvm.generate_relevance_at_event(play, event_frame, events_df,
                                             PPCF, params)
        PS = pvm.generate_scoring_opportunity(field_dimen=(
            106.,
            68.,
        ),
                                              n_grid_cells_x=50)
        PPV = pvm.generate_pitch_value(PPCF,
                                       PT,
                                       PS,
                                       field_dimen=(
                                           106.,
                                           68.,
                                       ),
                                       n_grid_cells_x=50)
        RPPV = pvm.generate_relative_pitch_value(play, event_frame, events_df,
                                                 metrica_attack, PPV, xgrid,
                                                 ygrid)

        xgrid_new = np.linspace(-field_dimen[0] / 2., field_dimen[0] / 2.,
                                new_grid_size)
        ygrid_new = np.linspace(-field_dimen[1] / 2., field_dimen[1] / 2.,
                                new_grid_size)

        PPCF_int = interpolate.interp2d(xgrid, ygrid, PPCF, kind='cubic')
        PPCF_new = PPCF_int(xgrid_new, ygrid_new)
        PPCF_dict = dict(image=[PPCF_new],
                         x=[xgrid.min()],
                         y=[ygrid.min()],
                         dw=[field_dimen[0]],
                         dh=[field_dimen[1]])
        PT_int = interpolate.interp2d(xgrid, ygrid, PT, kind='cubic')
        PT_new = PT_int(xgrid_new, ygrid_new)
        PT_dict = dict(image=[PT_new],
                       x=[xgrid.min()],
                       y=[ygrid.min()],
                       dw=[field_dimen[0]],
                       dh=[field_dimen[1]])
        PS_int = interpolate.interp2d(xgrid, ygrid, PS, kind='cubic')
        PS_new = PS_int(xgrid_new, ygrid_new)
        PS_dict = dict(image=[PS_new],
                       x=[xgrid.min()],
                       y=[ygrid.min()],
                       dw=[field_dimen[0]],
                       dh=[field_dimen[1]])
        PPV_int = interpolate.interp2d(xgrid, ygrid, PPV, kind='cubic')
        PPV_new = PPV_int(xgrid_new, ygrid_new)
        PPV_dict = dict(image=[PPV_new],
                        x=[xgrid.min()],
                        y=[ygrid.min()],
                        dw=[field_dimen[0]],
                        dh=[field_dimen[1]])
        RPPV_int = interpolate.interp2d(xgrid, ygrid, RPPV, kind='cubic')
        RPPV_new = RPPV_int(xgrid_new, ygrid_new)
        RPPV_dict = dict(image=[RPPV_new],
                         x=[xgrid.min()],
                         y=[ygrid.min()],
                         dw=[field_dimen[0]],
                         dh=[field_dimen[1]])

        event_src = ColumnDataSource(event)
        att_src = ColumnDataSource(att_player_frame)
        def_src = ColumnDataSource(def_player_frame)
        ball_src = ColumnDataSource(ball_frame)
        PPCF_src = ColumnDataSource(PPCF_dict)
        PT_src = ColumnDataSource(PT_dict)
        PS_src = ColumnDataSource(PS_dict)
        PPV_src = ColumnDataSource(PPV_dict)
        RPPV_src = ColumnDataSource(RPPV_dict)

        return event_src, att_src, def_src, ball_src, PPCF_src, PT_src, PS_src, PPV_src, RPPV_src, xgrid, ygrid
	ylabels = [r"$\beta$", r"$\delta_{p}$", r"$\delta_{m}$", r"$\delta_{p}$"]     
	ind = np.random.choice(range(results_rep_space.shape[0]), 10000)  	
	heatAxes = [(0,3),(0,5), (3,4), (3,5)]    
	k = 1
	for heatAxis in heatAxes:  
		i = heatAxis[0] 
		j = heatAxis[1]   
		x = results_rep_space[:, i]  
		y = results_rep_space[:, j]    
		z = results_rep_cost     
		x = x[ind] 
		y = y[ind] 
		z = z[ind]    
		
		#interpolates the data on a grid 
		f = interp2d(x,y,z, kind='linear')            
		xi = np.linspace(min(x), max(x), 150)    	
		yi = np.linspace(min(y), max(y), 150)   
		ZI = f(xi,yi)
		plt.subplot(2,2,k)   
		plt.xlabel(xlabels[k - 1]) 
		plt.ylabel(ylabels[k - 1])    
		
		XI, YI = np.meshgrid(xi, yi)     
		plt.pcolor(XI, YI, ZI, cmap=cm.jet_r, vmax=0, rasterized=True)  
		plt.xlim(min(xi), max(xi))
		plt.ylim(min(yi), max(yi))   			
		plt.colorbar()  
		
		k += 1 
	
def tableLookUpTwoImplicit(x_ave,
                           x_var,
                           p0,
                           p1,
                           filename='flameletTable.h5',
                           p0_name='ProgressVariable',
                           p1_name='ProgressVariableVariance'):

    with h5py.File(filename, 'r') as f:
        table = f['flameletTable']

        variable = list(f['variable'])
        x_ave_axis = np.array(f[table.dims[1].label])
        x_var_axis = np.array(f[table.dims[2].label])
        param_axis_0 = np.array(f[table.dims[3].label])
        param_axis_1 = np.array(f[table.dims[4].label])

        data = np.array(table)

    idx_p0 = variable.index(p0_name)
    idx_p1 = variable.index(p1_name)

    param_table = np.empty((2, ) + data.shape[3:])

    # interpolate with explicit index
    for i in range(param_axis_0.size):
        for j in range(param_axis_1.size):
            f = interpolate.interp2d(x_var_axis, x_ave_axis, data[idx_p0, :, :,
                                                                  i, j])
            param_table[0, i, j] = f(x_var, x_ave)

            f = interpolate.interp2d(x_var_axis, x_ave_axis, data[idx_p1, :, :,
                                                                  i, j])
            param_table[1, i, j] = f(x_var, x_ave)

    # interpolate with implicit index
    # inverse table
    table_inverse = np.empty((2, param_axis_0.size))
    for i in range(param_axis_0.size):
        f = interpolate.interp1d(param_table[1, i, :],
                                 param_table[0, i, :],
                                 bounds_error=False,
                                 fill_value=(param_table[0, i,
                                                         0], param_table[0, i,
                                                                         -1]))
        table_inverse[0, i] = f(p1)

        f = interpolate.interp1d(param_table[1, i, :],
                                 param_axis_1,
                                 bounds_error=False,
                                 fill_value=(param_axis_1[0],
                                             param_axis_1[-1]))
        table_inverse[1, i] = f(p1)

    f = interpolate.interp1d(table_inverse[0, :],
                             table_inverse[1, :],
                             bounds_error=False,
                             fill_value=(table_inverse[1,
                                                       0], table_inverse[1,
                                                                         -1]))
    param_1 = f(p0)

    f = interpolate.interp1d(table_inverse[0, :],
                             param_axis_0,
                             bounds_error=False,
                             fill_value=(param_axis_0[0], param_axis_0[-1]))
    param_0 = f(p0)

    # interpolate all variables
    var_table = np.empty((data.shape[0], ) + data.shape[3:])
    for k in range(data.shape[0]):
        for i in range(param_axis_0.size):
            for j in range(param_axis_1.size):
                f = interpolate.interp2d(x_var_axis, x_ave_axis, data[k, :, :,
                                                                      i, j])
                var_table[k, i, j] = f(x_var, x_ave)

    phi = np.zeros(var_table.shape[0])
    for k in range(var_table.shape[0]):
        f = interpolate.interp2d(param_axis_1, param_axis_0,
                                 var_table[k, :, :])
        phi[k] = f(param_0, param_1)

    return phi
Ejemplo n.º 50
0
def test_reconstruct_phase_nonstandard(lazy):
    """Testing reconstruction with non-standard output size for stacked images"""
    if lazy == True:
        pytest.skip("Dask array flags not supported")
    gc.collect()
    x2, z2, y2 = np.meshgrid(LS, np.array([0, 1]), LS)
    phase_ref2 = calc_phaseref(x2, y2, z2, img_size / 2.2, img_size / 2.2)
    holo2 = calc_holo(x2, y2, phase_ref2, FRINGE_SPACING, FRINGE_DIRECTION)
    ref2 = calc_holo(x2, y2, 0, FRINGE_SPACING, FRINGE_DIRECTION)
    holo_image2 = hs.signals.HologramImage(holo2)
    ref_image2 = hs.signals.HologramImage(ref2)
    del x2, z2, y2
    gc.collect()
    if lazy:
        ref_image2 = ref_image2.as_lazy()
        holo_image2 = holo_image2.as_lazy()

    sb_position2 = ref_image2.estimate_sideband_position(sb="upper")
    sb_position2_lower = ref_image2.estimate_sideband_position(sb="lower", )
    sb_position2_left = ref_image2.estimate_sideband_position(sb="left", )
    sb_position2_right = ref_image2.estimate_sideband_position(sb="right", )
    np.testing.assert_allclose(sb_position2, sb_position2_left)
    np.testing.assert_allclose(sb_position2_lower, sb_position2_right)

    sb_size2 = ref_image2.estimate_sideband_size(sb_position2)
    output_shape = (
        int(sb_size2.inav[0].data * 2),
        int(sb_size2.inav[0].data * 2),
    )

    wave_image2 = holo_image2.reconstruct_phase(
        reference=ref_image2,
        sb_position=sb_position2,
        sb_size=sb_size2,
        sb_smoothness=sb_size2 * 0.05,
        output_shape=output_shape,
    )
    # a. Reconstruction with parameters provided as ndarrays should be
    # identical to above:
    wave_image2a = holo_image2.reconstruct_phase(
        reference=ref_image2.data,
        sb_position=sb_position2.data,
        sb_size=sb_size2.data,
        sb_smoothness=sb_size2.data * 0.05,
        output_shape=output_shape,
    )
    np.testing.assert_allclose(wave_image2, wave_image2a)
    del wave_image2a
    gc.collect()
    # interpolate reconstructed phase to compare with the input (reference
    # phase):
    interp_x = np.arange(output_shape[0])
    phase_interp0 = interp2d(
        interp_x,
        interp_x,
        wave_image2.inav[0].unwrapped_phase().data,
        kind="cubic",
    )
    phase_new0 = phase_interp0(
        np.linspace(0, output_shape[0], img_size),
        np.linspace(0, output_shape[0], img_size),
    )

    phase_interp1 = interp2d(
        interp_x,
        interp_x,
        wave_image2.inav[1].unwrapped_phase().data,
        kind="cubic",
    )
    phase_new1 = phase_interp1(
        np.linspace(0, output_shape[0], img_size),
        np.linspace(0, output_shape[0], img_size),
    )

    X_START = int(img_size / 10)
    X_STOP = img_size - 1 - int(img_size / 10)
    phase_new_crop0 = phase_new0[X_START:X_STOP, X_START:X_STOP]
    phase_new_crop1 = phase_new1[X_START:X_STOP, X_START:X_STOP]
    phase_ref_crop0 = phase_ref2[0, X_START:X_STOP, X_START:X_STOP]
    phase_ref_crop1 = phase_ref2[1, X_START:X_STOP, X_START:X_STOP]
    np.testing.assert_allclose(phase_new_crop0, phase_ref_crop0, atol=0.05)
    np.testing.assert_allclose(phase_new_crop1, phase_ref_crop1, atol=0.04)
Ejemplo n.º 51
0
    def plot_results(self, file_name):
        import matplotlib.pyplot as plt
        ribs, shell_thick, max_stress, max_disp, weight = self.read_data_file(
            file_name, use_abaqus=True)
        # max_stress = max_stress_fixed
        n_rib = len(ribs)
        n_thick = len(shell_thick)
        opti_ribs = []
        opti_shell = []
        opti_weight = []
        rib_mat, shell_mat = np.meshgrid(ribs, shell_thick)
        # interpol weight
        f_weight = interpolate.interp2d(rib_mat,
                                        shell_mat,
                                        weight,
                                        kind='linear')

        plot1 = PlotHelper(['ribs', 'max stress'])
        for i in range(0, len(shell_thick)):
            stress = max_stress[i]
            # if np.min(stress) < max_shear_strength and np.max(stress) > max_shear_strength:
            #   optRibs = np.interp(max_shear_strength, stress, ribs)
            #   f = interp1d(stress, ribs, kind='linear')
            #   plot1.ax.plot([f(max_shear_strength)], [max_shear_strength], 'go')
            #   opti_ribs.append(f(max_shear_strength))
            #   opti_shell.append(shellThick[i])
            plot1.ax.plot(ribs,
                          max_stress[i],
                          label='shell= {:03f}'.format(shell_thick[i]))
        plot1.ax.plot(ribs,
                      np.full((len(ribs), 1), max_shear_strength),
                      'r--',
                      label='Limit-Load')
        plot1.finalize(legendNcol=2, tighten_layout=False)
        # plot1.show()

        plot2 = PlotHelper(['shellthickness in mm', 'max stress'])
        for i in range(0, len(ribs)):
            stress = max_stress[:, i]
            plot2.ax.plot(shell_thick,
                          stress,
                          label='ribs= {:f}'.format(ribs[i]))
            if np.min(stress) < max_shear_strength and np.max(
                    stress) > max_shear_strength:
                # optRibs = np.interp(max_shear_strength, stress, ribs)
                f = interp1d(stress, shell_thick, kind='linear')
                plot2.ax.plot([f(max_shear_strength)], [max_shear_strength],
                              'go')
                opti_ribs.append(ribs[i])
                opti_shell.append(f(max_shear_strength))
                opti_weight.append(f_weight(ribs[i], f(max_shear_strength))[0])
        plot2.ax.plot(shell_thick,
                      np.full((len(shell_thick), 1), max_shear_strength),
                      'r--',
                      label='Limit-Load')
        # plot2.ax.set_xlim((min([x * 1000 for x in shellThick]), max([x * 1000 for x in shellThick])))

        plot2.finalize(legendNcol=2)
        plot2.show()

        opti_min_index = opti_weight.index(min(opti_weight))
        print('opt wight {:03f}'.format(opti_weight[opti_min_index]))
        print('@ {:00f} ribs'.format(opti_ribs[opti_min_index]))
        print('@ {:05f} shell-thickness'.format(opti_shell[opti_min_index]))

        plot3d = PlotHelper(['ribs', 'shell thickness in m', 'mises stress'])
        max_stress[max_stress > 1.2 * max_shear_strength] = np.nan
        color_map = plt.cm.jet(weight / np.max(weight))
        surf = plot3d.ax.plot_surface(rib_mat,
                                      shell_mat,
                                      max_stress,
                                      facecolors=color_map,
                                      cstride=1,
                                      rstride=1)
        optiLine = plot3d.ax.plot(opti_ribs,
                                  opti_shell,
                                  max_shear_strength,
                                  'k--',
                                  label='Limit-Load')
        optiPoint = plot3d.ax.plot([opti_ribs[opti_min_index]],
                                   [opti_shell[opti_min_index]],
                                   max_shear_strength,
                                   'ro',
                                   label='glob. optimum')
        m = cm.ScalarMappable(cmap=cm.jet)
        m.set_array(weight)
        cbar = plt.colorbar(m)
        cbar.set_label('structure weight in kg', rotation=270)
        limit = np.full((n_thick, n_rib), max_shear_strength)
        plot3d.ax.plot_wireframe(rib_mat,
                                 shell_mat,
                                 limit,
                                 color='r',
                                 alpha=0.1)
        plot3d.ax.set_zlim3d(0, max_shear_strength)
        plot3d.finalize()
        plot3d.show()
Ejemplo n.º 52
0
def preprocesser(vals,
                 refine=2,
                 Rm_Outliers=False,
                 Filter=True,
                 Median=False,
                 Mean=True):

    # Determine spatial resolution
    resolution = vals.shape[0]

    if Rm_Outliers:
        # Identify and remove outliers
        outlier_buffer = 5

        vals_list = vals.reshape((resolution * resolution, ))
        vals_mins = heapq.nsmallest(outlier_buffer, vals_list)
        vals_maxes = heapq.nlargest(outlier_buffer, vals_list)

        # Cap max and min
        vals_min = np.max(vals_mins)
        vals_max = np.min(vals_maxes)

        # Trim outliers
        over = (vals > vals_max)
        under = (vals < vals_min)

        # Remove outliers
        vals[over] = vals_max
        vals[under] = vals_min

    else:
        vals_min = np.max(vals)
        vals_max = np.min(vals)

    if Filter:
        # Apply median/mean filter
        if Median:
            vals = median_filter(vals)
        if Mean:
            vals = mean_filter(vals)

    # Create grid
    start = 0.0
    end = 1.0
    x = np.linspace(start, end, resolution)
    y = np.linspace(start, end, resolution)

    [X, Y] = np.meshgrid(x, y)

    interp_vals = interp2d(x, y, vals, kind='cubic')

    # Create refined grid
    plot_start = 0.0
    plot_end = 1.0

    plot_x = np.linspace(plot_start, plot_end, refine * resolution)
    plot_y = np.linspace(plot_start, plot_end, refine * resolution)

    [plot_X, plot_Y] = np.meshgrid(plot_x, plot_y)

    vals_int_values = interp_vals(plot_x, plot_y)

    return vals_int_values, plot_X, plot_Y
Ejemplo n.º 53
0
v=[]
error = data['spd']   
#error = data['ame']
for mem in ['10']:
  for loc in error[mem].keys():
#    print('mem/loc',mem,loc,error[mem][loc])
    z = []
    for i,value in enumerate(error[mem][loc]):
      z.append(value)
    v.append(z)

mem = '10'
x = np.asarray([1.0, 1.01, 1.03, 1.05, 1.07, 1.09, 1.11, 1.13, 1.15, 1.17, 1.19])
y = np.arange(5,40.1,5)

f = interpolate.interp2d(x, y, v, kind='cubic')

xx = np.arange(1.0,1.191,0.01)
yy = np.arange(5,40.1,0.5)

xx = x
yy = y

X, Y = np.meshgrid(xx, yy)
Z = f(xx,yy)
#print(type(Z),type(X),type(Y))

fig, ax = plt.subplots()
SD = ax.contourf(X, Y, Z, 100, zorder=0, cmap='jet')
plt.colorbar(SD)
CS = ax.contour(X, Y, Z, 20, colors='black', zorder=1)
    def __init__(self):
        # paramsmeters of car
        self.Wheel_R = 0.287
        self.mass = 1449
        self.C_roll = 0.013
        self.density_air = 1.2
        self.area_frontal = 2.23
        self.G = 9.81
        self.C_d = 0.26
        # the factor of F_roll
        self.T_factor = 1

        # paramsmeters of transmission system
        # number of teeth
        self.Pgs_R = 78
        self.Pgs_S = 30
        # speed ratio from ring gear to wheel
        self.Pgs_K = 3.93

        # The optimal curve of engine
        self.Eng_pwr_opt_list = np.arange(0, 57, 1) * 1000
        #T_list = [0.0, 11.93662073189215, 23.8732414637843, 35.80986219567645, 47.7464829275686, 59.68310365946075, 71.6197243913529, 78.64126599834829, 84.88263631567752, 76.73541899073525, 82.3215222889114, 82.71044286665428, 84.25849928394459, 89.30996806595566, 83.03736161316279, 87.87696244337779, 88.31719385446216, 92.7645954021333, 98.22133630814113, 98.6068669156308, 97.94150344116636, 99.768770296412, 101.98277906859313, 104.09185851507847, 96.70173757482249, 105.16846459816874, 101.75479968170357, 103.54658948147409, 105.683914780389, 107.75470855248945, 109.34309067382122, 110.04765581818786, 110.7164821508837, 112.14476417151343, 113.92143294998826, 116.05047933784036, 117.73105379400477, 119.36620731892151, 120.95775674984046, 121.70672118791997, 121.64709026132127, 121.96920872463008, 121.90591385762197, 121.84562408815725, 121.7881303659721, 121.73324259153468, 121.68078751624131, 121.96112486933283, 121.58255599593066, 121.85300330473238, 121.80225236624644, 121.75353146529994, 121.70672118791995, 121.36995660245255, 121.90591385762195, 121.85877313300573, 121.81335052135952]
        self.W_list = [
            91.106186954104, 83.77580409572782, 83.77580409572782,
            83.77580409572782, 83.77580409572782, 83.77580409572782,
            83.77580409572782, 89.0117918517108, 94.24777960769379,
            117.28612573401894, 121.47491593880532, 132.9940890019679,
            142.4188669627373, 145.56045961632708, 168.59880574265222,
            170.69320084504542, 181.1651763570114, 183.25957145940458,
            183.25957145940458, 192.684349420174, 204.20352248333657,
            210.48670779051614, 215.72269554649912, 220.95868330248211,
            248.18581963359367, 237.71384412162766, 255.51620249196986,
            260.7521902479528, 264.9409804527392, 269.1297706575256,
            274.3657584135086, 281.69614127188476, 289.026524130261,
            294.262511886244, 298.4513020910303, 301.59289474462014,
            305.78168494940655, 309.9704751541929, 314.1592653589793,
            320.4424506661589, 328.8200310757317, 336.15041393410786,
            344.52799434368063, 352.90557475325346, 361.2831551628262,
            369.660735572399, 378.0383159819718, 385.368698840348,
            394.7934768011173, 402.12385965949346, 410.5014400690663,
            418.87902047863906, 427.2566008882119, 436.6813788489813,
            442.96456415616086, 451.3421445657336, 459.7197249753064
        ]
        self.Eng_pwr_func = interp1d(self.Eng_pwr_opt_list, self.W_list)

        Eng_spd_list = np.arange(0, 4501, 125) * (2 * math.pi) / 60
        Eng_spd_list = Eng_spd_list[np.newaxis, :]
        Eng_trq_list = np.arange(0, 111, 5) * (121 / 110)
        Eng_trq_list = Eng_trq_list[np.newaxis, :]
        data_path = 'Eng_bsfc_map.mat'
        data = scio.loadmat(data_path)
        Eng_bsfc_map = data['Eng_bsfc_map']
        self.Eng_trq_maxP = [
            -4.1757e-009, 6.2173e-006, -3.4870e-003, 9.1743e-001, 2.0158e+001
        ]
        Eng_fuel_map = Eng_bsfc_map * (Eng_spd_list.T *
                                       Eng_trq_list) / 3600 / 1000

        # fuel consumption (g)
        self.Eng_fuel_func = interp2d(Eng_trq_list, Eng_spd_list, Eng_fuel_map)

        # Motor 1
        # motor speed list (rad/s)
        Mot_spd_list = np.arange(-6000, 6001, 200) * (2 * math.pi) / 60
        # motor torque list (Nm)
        Mot_trq_list = np.arange(-400, 401, 10)

        # motor efficiency map
        data_path1 = 'Mot_eta_quarter.mat'
        data1 = scio.loadmat(data_path1)
        Mot_eta_quarter = data1['Mot_eta_quarter']
        Mot_eta_alltrqs = np.concatenate(
            ([np.fliplr(Mot_eta_quarter[:, 1:]), Mot_eta_quarter]), axis=1)
        Mot_eta_map = np.concatenate(
            ([np.flipud(Mot_eta_alltrqs[1:, :]), Mot_eta_alltrqs]))
        # motor efficiency
        self.Mot_eta_map_func = interp2d(Mot_trq_list, Mot_spd_list,
                                         Mot_eta_map)

        #  motor maximum torque
        Mot_trq_max_quarter = np.array([
            400, 400, 400, 400, 400, 400, 400, 347.200000000000,
            297.800000000000, 269.400000000000, 241, 221.800000000000,
            202.600000000000, 186.400000000000, 173.200000000000, 160, 148,
            136, 126.200000000000, 118.600000000000, 111, 105.800000000000,
            100.600000000000, 96.2000000000000, 92.6000000000000, 89,
            87.4000000000000, 85.8000000000000, 83.2000000000000,
            79.6000000000000, 76
        ])
        Mot_trq_max_quarter = Mot_trq_max_quarter[np.newaxis, :]
        Mot_trq_max_list = np.concatenate(
            (np.fliplr(Mot_trq_max_quarter[:, 1:]), Mot_trq_max_quarter),
            axis=1)
        # motor minimum torque
        Mot_trq_min_list = -Mot_trq_max_list
        self.Mot_trq_min_func = interp1d(Mot_spd_list,
                                         Mot_trq_min_list,
                                         kind='linear',
                                         fill_value='extrapolate')
        self.Mot_trq_max_func = interp1d(Mot_spd_list,
                                         Mot_trq_max_list,
                                         kind='linear',
                                         fill_value='extrapolate')

        # Generator (Motor 2)
        # generator speed list (rad/s)
        Gen_spd_list = np.arange(-10e3, 11e3, 1e3) * (2 * math.pi) / 60
        Gen_trq_list = np.arange(-75, 76, 5)

        # motor efficiency map
        Gen_eta_quarter = np.array(
            [[
                0.570000000000000, 0.570000000000000, 0.570000000000000,
                0.570000000000000, 0.570000000000000, 0.570000000000000,
                0.570000000000000, 0.570000000000000, 0.570000000000000,
                0.570000000000000, 0.570000000000000, 0.570000000000000,
                0.570000000000000, 0.570000000000000, 0.570000000000000,
                0.570000000000000
            ],
             [
                 0.570000000000000, 0.701190476190476, 0.832380952380952,
                 0.845500000000000, 0.845500000000000, 0.845500000000000,
                 0.845500000000000, 0.841181818181818, 0.832545454545455,
                 0.825204545454546, 0.820886363636364, 0.816136363636364,
                 0.807500000000000, 0.798863636363636, 0.794113636363636,
                 0.789795454545455
             ],
             [
                 0.570000000000000, 0.710238095238095, 0.850476190476190,
                 0.872272727272727, 0.880909090909091, 0.883500000000000,
                 0.883500000000000, 0.879181818181818, 0.870545454545455,
                 0.864500000000000, 0.864500000000000, 0.863636363636364,
                 0.855000000000000, 0.846363636363636, 0.841613636363636,
                 0.837295454545455
             ],
             [
                 0.570000000000000, 0.710238095238095, 0.850476190476190,
                 0.872272727272727, 0.880909090909091, 0.883500000000000,
                 0.883500000000000, 0.883500000000000, 0.883500000000000,
                 0.883500000000000, 0.883500000000000, 0.883500000000000,
                 0.883500000000000, 0.883500000000000, 0.875727272727273,
                 0.867090909090909
             ],
             [
                 0.570000000000000, 0.710238095238095, 0.850476190476190,
                 0.876159090909091, 0.889113636363636, 0.896022727272727,
                 0.900340909090909, 0.902500000000000, 0.902500000000000,
                 0.902500000000000, 0.902500000000000, 0.901636363636364,
                 0.893000000000000, 0.884363636363636, 0.883500000000000,
                 0.883500000000000
             ],
             [
                 0.570000000000000, 0.714761904761905, 0.859523809523810,
                 0.885659090909091, 0.898613636363636, 0.902500000000000,
                 0.902500000000000, 0.902500000000000, 0.902500000000000,
                 0.902500000000000, 0.902500000000000, 0.902500000000000,
                 0.902500000000000, 0.902500000000000, 0.894727272727273,
                 0.886090909090909
             ],
             [
                 0.570000000000000, 0.714761904761905, 0.859523809523810,
                 0.885659090909091, 0.898613636363636, 0.902500000000000,
                 0.902500000000000, 0.902500000000000, 0.902500000000000,
                 0.902500000000000, 0.902500000000000, 0.901636363636364,
                 0.893000000000000, 0.884363636363636, 0.883500000000000,
                 0.883500000000000
             ],
             [
                 0.570000000000000, 0.714761904761905, 0.859523809523810,
                 0.885659090909091, 0.898613636363636, 0.902500000000000,
                 0.902500000000000, 0.902500000000000, 0.902500000000000,
                 0.902500000000000, 0.902500000000000, 0.901636363636364,
                 0.893000000000000, 0.884363636363636, 0.883500000000000,
                 0.883500000000000
             ],
             [
                 0.570000000000000, 0.714761904761905, 0.859523809523810,
                 0.885659090909091, 0.898613636363636, 0.902500000000000,
                 0.902500000000000, 0.902500000000000, 0.902500000000000,
                 0.902500000000000, 0.902500000000000, 0.901636363636364,
                 0.893000000000000, 0.884363636363636, 0.883500000000000,
                 0.883500000000000
             ],
             [
                 0.570000000000000, 0.714761904761905, 0.859523809523810,
                 0.885659090909091, 0.898613636363636, 0.902500000000000,
                 0.902500000000000, 0.898181818181818, 0.889545454545454,
                 0.886090909090909, 0.894727272727273, 0.901636363636364,
                 0.893000000000000, 0.884363636363636, 0.883500000000000,
                 0.883500000000000
             ],
             [
                 0.570000000000000, 0.710238095238095, 0.850476190476190,
                 0.872272727272727, 0.880909090909091, 0.883500000000000,
                 0.883500000000000, 0.883500000000000, 0.883500000000000,
                 0.886090909090909, 0.894727272727273, 0.901636363636364,
                 0.893000000000000, 0.884363636363636, 0.883500000000000,
                 0.883500000000000
             ]])
        Gen_eta_alltrqs = np.concatenate(
            (Gen_eta_quarter[:, 1:], Gen_eta_quarter), axis=1)
        Gen_eta_map = np.concatenate(
            ([np.flipud(Gen_eta_alltrqs[1:, :]), Gen_eta_alltrqs]))
        # efficiency of the electric generator
        self.Gen_eta_map_func = interp2d(Gen_trq_list, Gen_spd_list,
                                         Gen_eta_map)

        # generator maxmium torque
        Gen_trq_max_half = np.array([
            76.7000000000000, 76.7000000000000, 70.6160000000000,
            46.0160000000000, 34.7320000000000, 26.6400000000000,
            21.2000000000000, 18.1160000000000, 16.2800000000000,
            13.4000000000000, 0
        ])
        Gen_trq_max_half = Gen_trq_max_half[np.newaxis, :]
        Gen_trq_max_list = np.concatenate(
            (np.fliplr(Gen_trq_max_half[:, 1:]), Gen_trq_max_half), axis=1)
        # generator minimum torque
        Gen_trq_min_list = -Gen_trq_max_list
        self.Gen_trq_min_func = interp1d(Gen_spd_list,
                                         Gen_trq_min_list,
                                         kind='linear',
                                         fill_value='extrapolate')
        self.Gen_trq_max_func = interp1d(Gen_spd_list,
                                         Gen_trq_max_list,
                                         kind='linear',
                                         fill_value='extrapolate')

        # Battery
        # published capacity of one battery cell
        Batt_Q_cell = 6.5
        # coulombs, battery package capacity
        self.Batt_Q = Batt_Q_cell * 3600
        # resistance and OCV list
        Batt_rint_dis_list = [
            0.7, 0.619244814, 0.443380117, 0.396994948, 0.370210379,
            0.359869599, 0.364414573, 0.357095093, 0.363394618, 0.386654377,
            0.4
        ]  # ohm
        Batt_rint_chg_list = [
            0.7, 0.623009741, 0.477267027, 0.404193372, 0.37640518,
            0.391748667, 0.365290105, 0.375071555, 0.382795632, 0.371566564,
            0.36
        ]  # ohm
        Batt_vol_list = [
            202, 209.3825073, 213.471405, 216.2673035, 218.9015961,
            220.4855042, 221.616806, 222.360199, 224.2510986, 227.8065948,
            237.293396
        ]  # V
        # resistance and OCV
        SOC_list = np.arange(0, 1.01, 0.1)
        self.Batt_vol_func = interp1d(SOC_list,
                                      Batt_vol_list,
                                      kind='linear',
                                      fill_value='extrapolate')
        self.Batt_rint_dis_list_func = interp1d(SOC_list,
                                                Batt_rint_dis_list,
                                                kind='linear',
                                                fill_value='extrapolate')
        self.Batt_rint_chg_list_func = interp1d(SOC_list,
                                                Batt_rint_chg_list,
                                                kind='linear',
                                                fill_value='extrapolate')

        #Battery current limitations
        self.Batt_I_max_dis = 196
        self.Batt_I_max_chg = 120
Ejemplo n.º 55
0
    def initialise_2D_scikit_fem(self):
        y_sol = self.mesh.edges["y"]
        len_y = len(y_sol)
        z_sol = self.mesh.edges["z"]
        len_z = len(z_sol)
        entries = np.empty((len_y, len_z, len(self.t_sol)))

        # Evaluate the base_variable index-by-index
        for idx in range(len(self.t_sol)):
            t = self.t_sol[idx]
            u = self.u_sol[:, idx]
            inputs = {name: inp[:, idx] for name, inp in self.inputs.items()}

            if self.known_evals:
                eval_and_known_evals = self.base_variable.evaluate(
                    t, u, inputs=inputs, known_evals=self.known_evals[t])
                entries[:, :, idx] = np.reshape(eval_and_known_evals[0],
                                                [len_y, len_z],
                                                order="F")
                self.known_evals[t] = eval_and_known_evals[1]
            else:
                entries[:, :, idx] = np.reshape(
                    self.base_variable.evaluate(t, u, inputs=inputs),
                    [len_y, len_z],
                    order="F",
                )

        # assign attributes for reference
        self.entries = entries
        self.dimensions = 2
        self.y_sol = y_sol
        self.z_sol = z_sol
        self.first_dimension = "y"
        self.second_dimension = "z"
        self.first_dim_pts = y_sol * self.get_spatial_scale(
            "y", "current collector")
        self.second_dim_pts = z_sol * self.get_spatial_scale(
            "z", "current collector")

        # set up interpolation
        if len(self.t_sol) == 1:
            # function of space only. Note the order of the points is the reverse
            # of what you'd expect
            interpolant = interp.interp2d(
                self.second_dim_pts,
                self.first_dim_pts,
                entries,
                kind="linear",
                fill_value=np.nan,
                bounds_error=False,
            )

            def interp_fun(input):
                return make_interp2D_fun(input, interpolant)

            self._interpolation_function = interp_fun
        else:
            # function of space and time.
            self._interpolation_function = interp.RegularGridInterpolator(
                (self.first_dim_pts, self.second_dim_pts, self.t_pts),
                entries,
                method="linear",
                fill_value=np.nan,
                bounds_error=False,
            )
Ejemplo n.º 56
0
plt.plot((a.grid.x - rin) / au, a.dusttemp[:, imid, 0, 0], label='RADMC-3D')
plt.plot(pinte_r - rin / au, pinte_mid_temp, label='MCFOST')
plt.xscale('log')
plt.yscale('log')
plt.xlabel(r'$r-r_{\mathrm{in}}$ [au]')
plt.ylabel(r'$T_d$ [K]')
plt.axis([0.00001, 400., 10, 2000.])
plt.legend(loc='lower left')
#plt.savefig('compare_tdust_midplane.png')
plt.show()

f = interpolate.interp1d(rc / au, np.linspace(0, nnr - 1, nnr))
ir02 = int(f([0.2])[0]) + 1
ir200 = int(f([200])[0])

f = interpolate.interp2d(thetac, rc / au, a.dusttemp[:, :, 0, 0])
rcyl02 = 0.2
zcyl02 = (math.pi / 2 - thetac) * rcyl02
rsph = np.sqrt(rcyl02**2 + zcyl02**2)
tsph = math.pi / 2 - np.arctan(zcyl02 / rcyl02)
tdust02 = np.zeros(nnt)
for iz in range(nnt):
    tdust02[iz] = f(tsph[iz], rsph[iz])
rcyl200 = 200
zcyl200 = (math.pi / 2 - thetac) * rcyl200
rsph = np.sqrt(rcyl200**2 + zcyl200**2)
tsph = math.pi / 2 - np.arctan(zcyl200 / rcyl200)
tdust200 = np.zeros(nnt)
for iz in range(nnt):
    tdust200[iz] = f(tsph[iz], rsph[iz])
Ejemplo n.º 57
0
    def initialise_2D(self):
        """
        Initialise a 2D object that depends on x and r, or x and z.
        """
        first_dim_nodes = self.mesh.nodes
        first_dim_edges = self.mesh.edges
        second_dim_nodes = self.base_variable.secondary_mesh.nodes
        second_dim_edges = self.base_variable.secondary_mesh.edges
        if self.base_eval.size // len(second_dim_nodes) == len(
                first_dim_nodes):
            first_dim_pts = first_dim_nodes
        elif self.base_eval.size // len(second_dim_nodes) == len(
                first_dim_edges):
            first_dim_pts = first_dim_edges

        second_dim_pts = second_dim_nodes
        first_dim_size = len(first_dim_pts)
        second_dim_size = len(second_dim_pts)
        entries = np.empty((first_dim_size, second_dim_size, len(self.t_sol)))

        # Evaluate the base_variable index-by-index
        for idx in range(len(self.t_sol)):
            t = self.t_sol[idx]
            u = self.u_sol[:, idx]
            inputs = {name: inp[:, idx] for name, inp in self.inputs.items()}
            if self.known_evals:
                eval_and_known_evals = self.base_variable.evaluate(
                    t, u, inputs=inputs, known_evals=self.known_evals[t])
                entries[:, :, idx] = np.reshape(
                    eval_and_known_evals[0],
                    [first_dim_size, second_dim_size],
                    order="F",
                )
                self.known_evals[t] = eval_and_known_evals[1]
            else:
                entries[:, :, idx] = np.reshape(
                    self.base_variable.evaluate(t, u, inputs=inputs),
                    [first_dim_size, second_dim_size],
                    order="F",
                )

        # add points outside first dimension domain for extrapolation to
        # boundaries
        extrap_space_first_dim_left = np.array(
            [2 * first_dim_pts[0] - first_dim_pts[1]])
        extrap_space_first_dim_right = np.array(
            [2 * first_dim_pts[-1] - first_dim_pts[-2]])
        first_dim_pts = np.concatenate([
            extrap_space_first_dim_left, first_dim_pts,
            extrap_space_first_dim_right
        ])
        extrap_entries_left = np.expand_dims(2 * entries[0] - entries[1],
                                             axis=0)
        extrap_entries_right = np.expand_dims(2 * entries[-1] - entries[-2],
                                              axis=0)
        entries_for_interp = np.concatenate(
            [extrap_entries_left, entries, extrap_entries_right], axis=0)

        # add points outside second dimension domain for extrapolation to
        # boundaries
        extrap_space_second_dim_left = np.array(
            [2 * second_dim_pts[0] - second_dim_pts[1]])
        extrap_space_second_dim_right = np.array(
            [2 * second_dim_pts[-1] - second_dim_pts[-2]])
        second_dim_pts = np.concatenate([
            extrap_space_second_dim_left,
            second_dim_pts,
            extrap_space_second_dim_right,
        ])
        extrap_entries_second_dim_left = np.expand_dims(
            2 * entries_for_interp[:, 0, :] - entries_for_interp[:, 1, :],
            axis=1)
        extrap_entries_second_dim_right = np.expand_dims(
            2 * entries_for_interp[:, -1, :] - entries_for_interp[:, -2, :],
            axis=1)
        entries_for_interp = np.concatenate(
            [
                extrap_entries_second_dim_left,
                entries_for_interp,
                extrap_entries_second_dim_right,
            ],
            axis=1,
        )

        # Process r-x or x-z
        if self.domain[0] in [
                "negative particle",
                "positive particle",
        ] and self.auxiliary_domains["secondary"][0] in [
                "negative electrode",
                "positive electrode",
        ]:
            self.first_dimension = "r"
            self.second_dimension = "x"
            self.r_sol = first_dim_pts
            self.x_sol = second_dim_pts
        elif (self.domain[0] in [
                "negative electrode",
                "separator",
                "positive electrode",
        ] and self.auxiliary_domains["secondary"] == ["current collector"]):
            self.first_dimension = "x"
            self.second_dimension = "z"
            self.x_sol = first_dim_pts
            self.z_sol = second_dim_pts
        else:
            raise pybamm.DomainError(
                "Cannot process 3D object with domain '{}' "
                "and auxiliary_domains '{}'".format(self.domain,
                                                    self.auxiliary_domains))

        # assign attributes for reference
        self.entries = entries
        self.dimensions = 2
        first_length_scale = self.get_spatial_scale(self.first_dimension,
                                                    self.domain[0])
        first_dim_pts_for_interp = first_dim_pts * first_length_scale

        second_length_scale = self.get_spatial_scale(
            self.second_dimension, self.auxiliary_domains["secondary"][0])
        second_dim_pts_for_interp = second_dim_pts * second_length_scale

        # Set pts to edges for nicer plotting
        self.first_dim_pts = first_dim_edges * first_length_scale
        self.second_dim_pts = second_dim_edges * second_length_scale

        # set up interpolation
        if len(self.t_sol) == 1:
            # function of space only. Note the order of the points is the reverse
            # of what you'd expect
            interpolant = interp.interp2d(
                second_dim_pts_for_interp,
                first_dim_pts_for_interp,
                entries_for_interp[:, :, 0],
                kind="linear",
                fill_value=np.nan,
                bounds_error=False,
            )

            def interp_fun(input):
                return make_interp2D_fun(input, interpolant)

            self._interpolation_function = interp_fun
        else:
            # function of space and time.
            self._interpolation_function = interp.RegularGridInterpolator(
                (first_dim_pts_for_interp, second_dim_pts_for_interp,
                 self.t_pts),
                entries_for_interp,
                method="linear",
                fill_value=np.nan,
                bounds_error=False,
            )
Ejemplo n.º 58
0
    def initialise_1D(self, fixed_t=False):
        len_space = self.base_eval.shape[0]
        entries = np.empty((len_space, len(self.t_sol)))

        # Evaluate the base_variable index-by-index
        for idx in range(len(self.t_sol)):
            t = self.t_sol[idx]
            u = self.u_sol[:, idx]
            inputs = {name: inp[:, idx] for name, inp in self.inputs.items()}
            if self.known_evals:
                eval_and_known_evals = self.base_variable.evaluate(
                    t, u, inputs=inputs, known_evals=self.known_evals[t])
                entries[:, idx] = eval_and_known_evals[0][:, 0]
                self.known_evals[t] = eval_and_known_evals[1]
            else:
                entries[:, idx] = self.base_variable.evaluate(t,
                                                              u,
                                                              inputs=inputs)[:,
                                                                             0]

        # Get node and edge values
        nodes = self.mesh.nodes
        edges = self.mesh.edges
        if entries.shape[0] == len(nodes):
            space = nodes
        elif entries.shape[0] == len(edges):
            space = edges

        # add points outside domain for extrapolation to boundaries
        extrap_space_left = np.array([2 * space[0] - space[1]])
        extrap_space_right = np.array([2 * space[-1] - space[-2]])
        space = np.concatenate([extrap_space_left, space, extrap_space_right])
        extrap_entries_left = 2 * entries[0] - entries[1]
        extrap_entries_right = 2 * entries[-1] - entries[-2]
        entries_for_interp = np.vstack(
            [extrap_entries_left, entries, extrap_entries_right])

        # assign attributes for reference (either x_sol or r_sol)
        self.entries = entries
        self.dimensions = 1
        if self.domain[0] in ["negative particle", "positive particle"]:
            self.first_dimension = "r"
            self.r_sol = space
        elif self.domain[0] in [
                "negative electrode",
                "separator",
                "positive electrode",
        ]:
            self.first_dimension = "x"
            self.x_sol = space
        elif self.domain == ["current collector"]:
            self.first_dimension = "z"
            self.z_sol = space
        else:
            self.first_dimension = "x"
            self.x_sol = space

        # assign attributes for reference
        length_scale = self.get_spatial_scale(self.first_dimension,
                                              self.domain[0])
        pts_for_interp = space * length_scale
        self.internal_boundaries = [
            bnd * length_scale for bnd in self.mesh.internal_boundaries
        ]

        # Set first_dim_pts to edges for nicer plotting
        self.first_dim_pts = edges * length_scale

        # set up interpolation
        if len(self.t_sol) == 1:
            # function of space only
            interpolant = interp.interp1d(
                pts_for_interp,
                entries_for_interp[:, 0],
                kind="linear",
                fill_value=np.nan,
                bounds_error=False,
            )

            def interp_fun(t, z):
                if isinstance(z, np.ndarray):
                    return interpolant(z)[:, np.newaxis]
                else:
                    return interpolant(z)

            self._interpolation_function = interp_fun
        else:
            # function of space and time. Note that the order of 't' and 'space'
            # is the reverse of what you'd expect
            self._interpolation_function = interp.interp2d(
                self.t_pts,
                pts_for_interp,
                entries_for_interp,
                kind="linear",
                fill_value=np.nan,
                bounds_error=False,
            )
Ejemplo n.º 59
0
def stn_interpolate(model_file_dic, df_stns):
    """Interpolate model forecast to stations.

    @Variables:
    model_file_list -- A list of model data.
    df_stns -- A pandas.DataFrame of national stations."""
    from scipy.interpolate import interp2d
    import numpy as np
    import pandas as pd
    from functools import reduce
    from collections import defaultdict
    # Get latlon from stations
    lats = df_stns['latitude']
    lons = df_stns['longitude']  # Spelling mistake
    ids = df_stns['id']
    stn_ids = df_stns['stationId']
    interp_results = defaultdict(lambda: list())
    df_results = dict()
    assert len(lats) == len(lons)
    # Loop over the file list, for each file, loop over a list of
    # **shortName, perturbationNumber** and do interpolation to each station.
    # short_name_list = ['tp', '2t', '2d']
    for model, model_file_list in model_file_dic.items():
        for model_file in model_file_list:
            grbmsg = pygrib.open(model_file)[1]
            # Unit conversion
            units_grbmsg = grbmsg['parameterUnits']
            short_name = 'PRCP'
            lat, lon, values = read_from_single_grbmsg(grbmsg)
            if units_grbmsg == 'm':
                values = values * 1000.
            elif units_grbmsg != 'kg m-2':
                print('Other kinds of precipitation units detected: {}'.format(
                    units_grbmsg))

            # Get validity datetime
            validity_datetime = "{:08d}{:02d}".format(grbmsg['validityDate'],
                                                      grbmsg['validityTime'])
            initial_datetime = "{:08d}{:02d}".format(grbmsg['dataDate'],
                                                     grbmsg['dataTime'])
            f = interp2d(lon, lat, values)  # bounds_error=True
            var_name = "".join([short_name, '.', model])
            # Do interpolation
            temp_interp_result = np.asarray(
                [f(lo, la)[0] for lo, la in zip(lons, lats)])
            temp_interp_result[temp_interp_result < 0.1] = 0.0
            interp_results[validity_datetime].append(
                pd.DataFrame({
                    var_name: temp_interp_result,
                    'stn_id': stn_ids
                }))
    for key_date in interp_results.keys():
        df_results[key_date] = reduce(
            lambda left, right: pd.merge(left, right, on='stn_id'),
            interp_results[key_date])
        # Add observation data to df_results according to key_date
        df_obs = get_station_data(key_date)
        df_results[key_date] = df_results[key_date].merge(
            df_obs[['datetime', 'stationId', 'PRE_24h']],
            left_on='stn_id',
            right_on='stationId')
        df_results[key_date] = df_results[key_date].merge(
            df_stns[['stationId', 'latitude', 'longitude']],
            left_on='stn_id',
            right_on='stationId',
            how='left')
        df_results[key_date]['time'] = key_date
    df_results = pd.concat([value for value in df_results.values()])
    df_results.merge(df_stns[['id', 'stationId']],
                     left_on='stn_id',
                     right_on='stationId')
    return df_results
Ejemplo n.º 60
0
class EVeh_model():
    Mass = 2.2135e+3
    Fterms = np.array([162.4046, 4.8429, 0.4936])
    _Spd_rpm = np.array([
        0, 500, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000,
        11000, 11900, 12400
    ])
    _Spd_radps = _Spd_rpm * np.pi / 30
    _Tq_Nm = np.array([
        -415.7, -405.0, -400, -350, -300, -250, -233, -225, -200, -175, -150,
        -125, -100, -75, -50, -25, -10, 0, 10, 25, 50, 75, 100, 125, 150, 175,
        200, 225, 233, 250, 300, 350, 400, 405.0, 415.7
    ])
    _Pw_W = np.array([[
        14351.2843432000, 14091.1418970700, 14587.1574276255, 15837.8561117835,
        16391.8315070421, 13341.4903214869, 12845.7226528034, 12930.9894360770,
        13286.9938053932, 16960.8265302376, 20637.3428820956, 24316.0446000527,
        27996.4335487945, 31309.8143708543, 33150.8639615047
    ],
                      [
                          13874.3406600000, 13608.9069996700, 14096.8387444255,
                          15319.9055559835, 15876.4913018421, 12980.5593338869,
                          12512.7762740034, 12604.2043740770, 12958.9388459932,
                          16534.9430116376, 20113.6307828956, 23694.5039416527,
                          27277.0643097945, 30502.3994328543, 32294.5347462824
                      ],
                      [
                          13651.4697800000, 13383.5635896700, 13867.7178644255,
                          15077.8725859835, 15635.6781218421, 12811.8999938869,
                          12357.1938540034, 12451.5010740770, 12805.6421359932,
                          16335.9320216376, 19868.9055028956, 23404.0643816527,
                          26940.9104597945, 30125.1027328543, 31894.3809073935
                      ],
                      [
                          11422.7609900000, 11130.1295296700, 11576.5090744255,
                          12657.5429159835, 13227.5462518421, 11125.3065838869,
                          10801.3696840034, 10924.4681140770, 11272.6751059932,
                          14345.8221316376, 17421.6527628956, 20499.6687816527,
                          23579.3719997945, 26352.1356928543, 27892.8424340602
                      ],
                      [
                          9194.05219800000, 8876.69546266998, 9285.30028242546,
                          10237.2132459835, 10819.4143818421, 9438.71317788691,
                          9245.54550600336, 9397.43514507695, 9739.70807199319,
                          12355.7122416376, 14974.4000128956, 17595.2731716527,
                          20217.8335397945, 22579.1686628543, 23891.3039762824
                      ],
                      [
                          6965.34340700000, 6623.26139666999, 6994.09149142546,
                          7816.88357698345, 8411.28251284211, 7752.11977188691,
                          7689.72133000336, 7870.40217807695, 8206.74103899319,
                          10365.6023516376, 12527.1472628956, 14690.8775716527,
                          16856.2950797945, 18806.2016328543, 19889.7655185047
                      ],
                      [
                          6207.58241800000, 5857.09381366999, 6215.08050242546,
                          6993.97148898345, 7592.51767784210, 7178.67801388691,
                          7160.74111100336, 7351.21096907695, 7685.53224799319,
                          9688.96499063756, 11695.0813328956, 13703.3830616527,
                          15713.3719997945, 17523.3928428543, 18529.2424451713
                      ],
                      [
                          5850.98901100000, 5496.54436366999, 5848.48709542546,
                          6606.71874198345, 7207.21657884210, 6908.82306888691,
                          6911.80924200336, 7106.88569407695, 7440.25752299319,
                          9370.54740863756, 11303.5208928956, 13238.6797716527,
                          15175.5258497945, 16919.7181128543, 17888.9962818380
                      ],
                      [
                          4599.89011000000, 4471.59930866999, 4796.94863442546,
                          5477.92753298345, 6003.15064484210, 6065.52636488691,
                          6133.89715500336, 6343.36921107695, 6673.77400599319,
                          8375.49246363756, 10079.8945168956, 11786.4819716527,
                          13494.7566197945, 15033.2345928543, 15888.2270451713
                      ],
                      [
                          3637.58241800000, 3588.74216566999, 3884.20138142546,
                          4495.40006098345, 4963.37042484210, 5222.22966188691,
                          5355.98506700336, 5579.85272707695, 5907.29048999319,
                          7380.43751863756, 8856.26814289557, 10334.2841616527,
                          11813.9873897945, 13146.7510828543, 13887.4578240602
                      ],
                      [
                          2933.07692300000, 2834.89601166999, 3096.72885342546,
                          3636.05940098345, 4053.59020584210, 4378.93295888691,
                          4578.07297900336, 4816.33624407695, 5140.80697299319,
                          6385.38257363756, 7632.64176889557, 8882.08636265270,
                          10133.2181547945, 11260.2675628543, 11886.6885901713
                      ],
                      [
                          2208.35164800000, 2177.31359466999, 2404.75083142546,
                          2876.71874198345, 3245.56822784210, 3535.63625488691,
                          3800.16089100336, 4052.81976007695, 4374.32345699319,
                          5390.32762863756, 6409.01539589557, 7429.88856065270,
                          8452.44892479447, 9373.78404685427, 9885.91935972688
                      ],
                      [
                          1618.90109900000, 1606.43447366999, 1793.54204042546,
                          2194.52093998345, 2517.10668884210, 2782.11977188691,
                          3022.24880300336, 3289.30327707695, 3607.83993999319,
                          4395.27268363756, 5185.38902189557, 5977.69075765270,
                          6771.67969379447, 7487.30052985427, 7885.15012828243
                      ],
                      [
                          1117.36263700000, 1112.47842966999, 1257.60797442546,
                          1581.33412698345, 1852.05174384210, 2094.09779388691,
                          2321.58946200336, 2525.78679307695, 2841.35642399319,
                          3400.21773863756, 3961.76264789557, 4525.49295565270,
                          5090.91046279447, 5600.81701385427, 5884.38089839354
                      ],
                      [
                          668.901098900000, 681.379528269985, 788.816765925456,
                          1036.93852198345, 1254.24954584210, 1460.69119988691,
                          1671.80924200336, 1858.42415607695, 2074.87290699319,
                          2405.16279363756, 2738.13627489557, 3073.29515365270,
                          3410.14123179447, 3714.33349785427, 3883.61166850466
                      ],
                      [
                          296.923076900000, 312.588319469985, 379.805776925455,
                          544.740719983452, 703.809985642103, 865.856035386906,
                          1055.21583590336, 1227.65492507695, 1408.05972099319,
                          1627.36059563756, 1849.34506589557, 2073.51493365270,
                          2299.37200179447, 2503.67415685427, 2617.45782139354
                      ],
                      [
                          107.252747300000, 129.621286469985, 180.245337425455,
                          307.268192483452, 433.040754942103, 573.108782686906,
                          746.094956703356, 908.314265876951, 1052.67510519319,
                          1266.70125463756, 1483.41099989557, 1702.30614265270,
                          1922.88848479447, 2122.44338785427, 2233.58969017132
                      ],
                      [
                          0, 57.4234842899851, 97.0585242054554,
                          224.191269383452, 336.667128542103, 467.504387086906,
                          645.655396303356, 803.588991076951, 997.290489793187,
                          1160.87707903756, 1327.14726389557, 1495.60284565270,
                          1665.74562779447, 1819.90492585427, 1905.83144761577
                      ],
                      [
                          107.252747300000, 147.643264469985, 197.827754925455,
                          326.169291383452, 462.601194442103, 602.339551886906,
                          789.721330403356, 940.182397676951, 1117.51027009319,
                          1289.99795763756, 1465.16924189557, 1642.52592265270,
                          1821.56980379447, 1983.74009085427, 2074.11716206021
                      ],
                      [
                          296.923076900000, 336.764143669985, 406.728853925455,
                          571.883577083452, 736.996798842103, 904.317573886906,
                          1086.97407760336, 1240.62195807695, 1423.33444599319,
                          1609.66828763756, 1798.68572489557, 1989.88856065270,
                          2182.77859479447, 2357.41042085427, 2454.71056928243
                      ],
                      [
                          668.901098900000, 716.324583169985, 827.058524225456,
                          1067.92753298345, 1278.31547984210, 1465.74614488691,
                          1652.02902300336, 1800.18239807695, 1986.30147899319,
                          2297.25070563756, 2610.88352789557, 2926.70174665270,
                          3244.20716579447, 3530.99283785427, 3690.60067850466
                      ],
                      [
                          1117.36263700000, 1157.75315466999, 1306.28929342546,
                          1618.47698398345, 1858.09569984210, 2054.53735388691,
                          2233.23781400336, 2375.23734307695, 2654.32345699319,
                          3215.05290363756, 3778.46594489557, 4344.06438465270,
                          4911.35002379447, 5422.93789285427, 5707.43584294910
                      ],
                      [
                          1618.90109900000, 1667.42348466999, 1858.04753542546,
                          2233.64181898345, 2499.96383184210, 2691.35054088691,
                          2866.42462700336, 3041.94063907695, 3557.73004999319,
                          4526.59136463756, 5498.13627489557, 6471.86658265270,
                          7447.28408879447, 8326.19063985427, 8814.75452439354
                      ],
                      [
                          2208.35164800000, 2258.30260466999, 2484.86072242546,
                          2921.11434598345, 3209.96383184210, 3405.85603588691,
                          3583.67737400336, 3708.64393607695, 4461.13664399319,
                          5838.12982663756, 7217.80660489557, 8599.66877965270,
                          9983.21815479447, 11229.4433828543, 11922.0731990602
                      ],
                      [
                          2933.07692300000, 2929.84106666999, 3193.21237042546,
                          3679.02643398345, 3990.84295284210, 4208.93295888691,
                          4399.06199000336, 4375.34723307695, 5364.54323699319,
                          7149.66828763756, 8937.47693389557, 10727.4709816527,
                          12519.1522197945, 14132.6961328543, 15029.3918851713
                      ],
                      [
                          3637.58241800000, 3708.96194566999, 4005.30028242546,
                          4532.43302798345, 4880.51328284210, 5127.28460688691,
                          5214.44660500336, 5042.05052907695, 6267.94983099319,
                          8461.20674963756, 10657.1472628956, 12855.2731716527,
                          15055.0862897945, 17035.9488828543, 18136.7105685047
                      ],
                      [
                          4599.89011000000, 4623.35755066999, 4949.58599642546,
                          5512.98247798345, 5897.76602984210, 6188.27361788691,
                          6029.83122000336, 5708.75382607695, 7171.35642399319,
                          9772.74521063756, 12376.8175928956, 14983.0753716527,
                          17591.0203497945, 19939.2016328543, 21244.0292573935
                      ],
                      [
                          5850.98901100000, 5661.92897866999, 6007.82775542546,
                          6596.16929098345, 7025.01877684210, 7249.26262888691,
                          6845.21583600336, 6375.45712307695, 8074.76301699319,
                          11084.2836716376, 14096.4879228956, 17110.8775716527,
                          20126.9544197945, 22842.4543728543, 24351.3479251713
                      ],
                      [
                          6207.58241800000, 6017.75315466999, 6368.04753542546,
                          6957.15830198345, 7399.52427184210, 7588.77911188691,
                          7106.13891300336, 6588.80217807695, 8363.85312699319,
                          11503.9759816376, 14646.7824328956, 17791.7742716527,
                          20938.4533197945, 23771.4952528543, 25345.6899051713
                      ],
                      [
                          6965.34340700000, 6773.87952866999, 7133.51456842546,
                          7724.25995098345, 8195.34844684210, 8310.25163988691,
                          7660.60045100336, 7042.16042007695, 8978.16961099319,
                          12395.8221316376, 15816.1582528956, 19238.6797716527,
                          22662.8884897945, 25745.7071228543, 27458.6666085047
                      ],
                      [
                          9194.05219800000, 8997.78062666998, 9384.88819442546,
                          9980.44126898345, 10536.0077918421, 10432.2296638869,
                          9291.36968200336, 8375.56701307695, 10784.9827959932,
                          15018.8990616376, 19255.4989128956, 23494.2841616527,
                          27734.7566197945, 31552.2126228543, 33673.3039807269
                      ],
                      [
                          11422.7609900000, 11221.6817296700, 11636.2618244255,
                          12236.6225859835, 12876.6671318421, 12554.2076838869,
                          10922.1389140034, 9708.97360607695, 12591.7959859932,
                          17641.9759816376, 22694.8395728956, 27749.8885616527,
                          32806.6247497945, 37358.7181128543, 39887.9413373935
                      ],
                      [
                          13651.4697800000, 13445.5828296700, 13887.6354444255,
                          14492.8039059835, 15217.3264718421, 14676.1857038869,
                          12552.9081440034, 11042.3802040770, 14398.6091759932,
                          20265.0529016376, 26134.1802328956, 32005.4929516527,
                          37878.4928797945, 43165.2236028543, 46102.5786940602
                      ],
                      [
                          13874.3406600000, 13667.9729396700, 14112.7728144255,
                          14718.4220359835, 15451.3924018421, 14888.3835038869,
                          12715.9850640034, 11175.7208640770, 14579.2904859932,
                          20527.3605916376, 26478.1142928956, 32431.0533916527,
                          38385.6796897945, 43745.8741528543, 46724.0424329491
                      ],
                      [
                          14351.2843432000, 14143.8877750700, 14594.5667862255,
                          15201.2448341835, 15952.2934920421, 15342.4867958869,
                          13064.9696728034, 11461.0698764770, 14965.9484893932,
                          21088.6990482376, 27214.1331812956, 33341.7527332527,
                          39471.0594631945, 44988.4663298543, 48053.9748341713
                      ]])
    PwLossAtVolt = interp2d(_Spd_radps, _Tq_Nm, _Pw_W)

    _Spd_rpm_mot = np.array([
        0, 510, 1020, 1530, 2040, 2550, 3060, 3570, 4080, 4467, 4591, 5101,
        5611, 6121, 6631, 7141, 7651, 8161, 8671, 9182, 9692, 10202, 10712,
        11222, 11732, 12140, 12400, 12500
    ])
    _Spd_radps_mot = _Spd_rpm_mot * np.pi / 30
    _Tq_Nm_mot = np.array([
        413.126736111111, 414.711805555556, 414.783854166667, 415,
        415.144097222222, 415.072048611111, 415, 414.783854166667,
        409.668402777778, 400.518229166667, 396.555555555556, 370.401909722222,
        340.429687500000, 312.402777777778, 287.113715277778, 264.418402777778,
        243.668402777778, 225.151909722222, 208.220486111111, 193.810763888889,
        180.914062500000, 170.034722222222, 160.164062500000, 151.518229166667,
        143.520833333333, 137.540798611111, 133.866319444444, 0
    ])
    MotTqLimAtVolt = interp1d(_Spd_radps_mot, _Tq_Nm_mot)
    Inertia = 16.4161
    M2WRatio = 9.4876
    WheelRadius = 0.3522
    Aux_load = 2000
    Rin_norm = 0.0872279723055434
    VOC_norm = 3.507459685926577e+02