jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
def interp2d_pairs(*args,**kwargs):
    """ Same interface as interp2d but the returned interpolant will evaluate its inputs as pairs of values.
    """
    # Internal function, that evaluates pairs of values, output has the same shape as input
    def interpolant(x,y,f):
        x,y = np.asarray(x), np.asarray(y)
        return (si.dfitpack.bispeu(f[0], f[1], f[2], f[3], f[4], x.ravel(), y.ravel())[0]).reshape(x.shape)
    # Wrapping the scipy interp2 function to call out interpolant instead
    return lambda x,y: interpolant(x,y,si.bisplev(*args,**kwargs))
//  [python]
def similarity(edge_image, mu, phi, sigma2, h, psi):
    height, width = edge_image.shape
    edge_distance = scipy.ndimage.distance_transform_edt(~edge_image)
    w = (mu + phi @ h).reshape(-1, 2)
    image_points = matrix_transform(w, psi.params)
    closest_distances = scipy.interpolate.interp2d(range(width), range(height), edge_distance)
    K = h.size
    noise = scipy.stats.multivariate_normal(mean=np.zeros(K), cov=np.eye(K))
    if noise.pdf(h.flatten()) == 0:
        print(h.flatten())
    noise = np.log(noise.pdf(h.flatten()))
    return -closest_distances(image_points[:, 0], image_points[:, 1]).sum() / sigma2
//  [python]
def similarity(edge_image, mu, phi, sigma2, h, psi):
    height, width = edge_image.shape
    edge_distance = scipy.ndimage.distance_transform_edt(~edge_image)
    w = (mu + phi @ h).reshape(-1, 2)
    image_points = matrix_transform(w, psi.params)
    x = np.arange(width)
    y = np.arange(height)
    xv, yv = np.meshgrid(x, y)
    closest_distances = scipy.interpolate.bisplev(xv, yv, edge_distance)
    K = h.size
    noise = scipy.stats.multivariate_normal(mean=np.zeros(K), cov=np.eye(K))
    if noise.pdf(h.flatten()) == 0:
        print(h.flatten())
    noise = np.log(noise.pdf(h.flatten()))
    return -closest_distances(image_points[:, 0], image_points[:, 1]).sum() / sigma2
//  [python]
def interpolate_RF(rf_map, deg_per_pnt):
    """Upsample an image

    Parameters
    ----------
    rf_map : np.ndarray
        Input image
    deg_per_pnt : numeric
        scale factor

    Returns
    -------
    interpolated : np.ndarray
        Upsampled image
    """

    x_pnts = np.shape(rf_map)[1]
    y_pnts = np.shape(rf_map)[0]

    x_coor = np.arange(
        -(x_pnts - 1) * deg_per_pnt / 2,
        (x_pnts + 1) * deg_per_pnt / 2,
        deg_per_pnt,
    )
    y_coor = np.arange(
        -(y_pnts - 1) * deg_per_pnt / 2,
        (y_pnts + 1) * deg_per_pnt / 2,
        deg_per_pnt,
    )

    x_interpolated = np.arange(
        -(x_pnts - 1) * deg_per_pnt / 2,
        deg_per_pnt / 2 + (x_pnts / 2 - 1) * deg_per_pnt + 1,
        1,
    )
    y_interpolated = np.arange(
        -(y_pnts - 1) * deg_per_pnt / 2,
        deg_per_pnt / 2 + (y_pnts / 2 - 1) * deg_per_pnt + 1,
        1,
    )

    interpolated = si.interp2d(x_coor, y_coor, rf_map)
    interpolated = interpolated(x_interpolated, y_interpolated)

    return interpolated
//  [python]
def interpolate_RF(rf_map, deg_per_pnt):
    """Upsample an image

    Parameters
    ----------
    rf_map : np.ndarray
        Input image
    deg_per_pnt : numeric
        scale factor

    Returns
    -------
    interpolated : np.ndarray
        Upsampled image
    """

    x_pnts = np.shape(rf_map)[1]
    y_pnts = np.shape(rf_map)[0]

    x_coor = np.arange(
        -(x_pnts - 1) * deg_per_pnt / 2,
        (x_pnts + 1) * deg_per_pnt / 2,
        deg_per_pnt,
    )
    y_coor = np.arange(
        -(y_pnts - 1) * deg_per_pnt / 2,
        (y_pnts + 1) * deg_per_pnt / 2,
        deg_per_pnt,
    )

    x_interpolated = np.arange(
        -(x_pnts - 1) * deg_per_pnt / 2,
        deg_per_pnt / 2 + (x_pnts / 2 - 1) * deg_per_pnt + 1,
        1,
    )
    y_interpolated = np.arange(
        -(y_pnts - 1) * deg_per_pnt / 2,
        deg_per_pnt / 2 + (y_pnts / 2 - 1) * deg_per_pnt + 1,
        1,
    )

    tck = si.bisplrep(x_coor, y_coor, rf_map)
    interpolated = si.bisplev(x_interpolated, y_interpolated, tck)

    return interpolated
//  [python]
def pcolormesh_plot_smooth(Fig,Ax,Key,Xdata,Ydata,Zdata,Limits,Tick_details):
    if not Tick_details:    Tick_details=[0]                                     #if Tick_details were not explicitly provided in PLOT_LIMITS then a default value is assumed 
    Xdata=[(pi/180)*float(i) for i in Xdata]
    Ydata=[float(i) for i in Ydata]    
    r, theta = np.meshgrid(Ydata, Xdata)        
    f = scipy.interpolate.interp2d(Ydata, Xdata, Zdata, kind='cubic')    
    Xdata_new=np.arange(min(Xdata), max(Xdata)+1.5*pi/180, 1.5*pi/180)                            
    Ydata_new=np.arange(min(Ydata), max(Ydata)+0.01, 0.01)    
    r_new,theta_new=np.meshgrid(Ydata_new, Xdata_new) 
    Zdata_new=f(Ydata_new,Xdata_new)      
    extension='neither'
    if Limits:
        v=(np.linspace(Limits[0],Limits[1],7,endpoint=True)).tolist()
        pcm=Ax.pcolormesh(theta_new,r_new,Zdata_new,cmap='jet',shading='gouraud',vmin=Limits[0],vmax=Limits[1])
#        cb=Fig.colorbar(pcm, ax=Ax, ticks=v, format=OOMFormatter(Tick_details[0], mathText=True),extend=extension)
    else:
        pcm=Ax.pcolormesh(theta_new,r_new,Zdata_new,cmap='jet',shading='gouraud')
#        cb=Fig.colorbar(pcm, ax=Ax, format=OOMFormatter(Tick_details[0], mathText=True),extend=extension)
    Ax.set_title(Key, fontsize=9,fontweight='bold',y=1.15)       #Shifting the subplot title to not overlap with the azimuth  value displayed    
    Ax.set_yticklabels([])
//  [python]
def pcolormesh_plot_smooth(Fig,Ax,Key,Xdata,Ydata,Zdata,Limits,Tick_details):
    if not Tick_details:    Tick_details=[0]                                     #if Tick_details were not explicitly provided in PLOT_LIMITS then a default value is assumed 
    Xdata=[(pi/180)*float(i) for i in Xdata]
    Ydata=[float(i) for i in Ydata]    
    r, theta = np.meshgrid(Ydata, Xdata)        
    tck = scipy.interpolate.bisplrep(Ydata, Xdata, Zdata, s=0)
    Xdata_new=np.arange(min(Xdata), max(Xdata)+1.5*pi/180, 1.5*pi/180)                            
    Ydata_new=np.arange(min(Ydata), max(Ydata)+0.01, 0.01)    
    r_new,theta_new=np.meshgrid(Ydata_new, Xdata_new) 
    Zdata_new=scipy.interpolate.bisplev(Ydata_new,Xdata_new,tck)      
    extension='neither'
    if Limits:
        v=(np.linspace(Limits[0],Limits[1],7,endpoint=True)).tolist()
        pcm=Ax.pcolormesh(theta_new,r_new,Zdata_new,cmap='jet',shading='gouraud',vmin=Limits[0],vmax=Limits[1])
#        cb=Fig.colorbar(pcm, ax=Ax, ticks=v, format=OOMFormatter(Tick_details[0], mathText=True),extend=extension)
    else:
        pcm=Ax.pcolormesh(theta_new,r_new,Zdata_new,cmap='jet',shading='gouraud')
#        cb=Fig.colorbar(pcm, ax=Ax, format=OOMFormatter(Tick_details[0], mathText=True),extend=extension)
    Ax.set_title(Key, fontsize=9,fontweight='bold',y=1.15)       #Shifting the subplot title to not overlap with the azimuth  value displayed    
    Ax.set_yticklabels([])
//  [python]
def getSlidingWindowVideo(I, dim, Tau, dT):
    N = I.shape[0] #Number of frames
    P = I.shape[1] #Number of pixels (possibly after PCA)
    pix = np.arange(P)
    NWindows = int(np.floor((N-dim*Tau)/dT))
    X = np.zeros((NWindows, dim*P))
    idx = np.arange(N)
    for i in range(NWindows):
        idxx = dT*i + Tau*np.arange(dim)
        start = int(np.floor(idxx[0]))
        end = int(np.ceil(idxx[-1]))
        f = scipy.interpolate.interp2d(pix, idx[start:end+1], I[idx[start:end+1], :], kind='linear')
        X[i, :] = f(pix, idxx).flatten()
    return X
//  [python]
def getSlidingWindowVideo(I, dim, Tau, dT):
    N = I.shape[0] #Number of frames
    P = I.shape[1] #Number of pixels (possibly after PCA)
    pix = np.arange(P)
    NWindows = int(np.floor((N-dim*Tau)/dT))
    X = np.zeros((NWindows, dim*P))
    idx = np.arange(N)
    for i in range(NWindows):
        idxx = dT*i + Tau*np.arange(dim)
        start = int(np.floor(idxx[0]))
        end = int(np.ceil(idxx[-1]))
        tck = scipy.interpolate.bisplrep(pix, idx[start:end+1], I[idx[start:end+1], :])
        X[i, :] = scipy.interpolate.bisplev(pix, idxx, tck).flatten()
    return X
//  [python]
def load_data_to_array(path_to_data):
    # Need customization
    # data: [N,6,121,T_MAX]
    # label: [N,]
    global T_MAX
    print('Loading data from ' + str(path_to_data))

    # Load data
    data = []
    label = []
    for data_root, data_dirs, data_files in os.walk(path_to_data):
        for data_file_name in data_files:

            file_path = os.path.join(data_root,data_file_name)
            try:
                # Data Selection
                label_1_name = data_file_name.split('_')[0]
                if label_1_name == 'fall':
                    label_1 = 1
                elif label_1_name == 'nonfall':
                    label_1 = 0
                else:
                    print('Wrong fall/nonfall prefix, skiping...')
                    continue

                data_1 = np.abs(scio.loadmat(file_path)[mat_file_key])  # [T,61]
                # Interpolation
                f = scipy.interpolate.interp2d(np.arange(0,data_1.shape[1]), np.arange(0,data_1.shape[0]), data_1)
                data_1 = f(np.linspace(0,data_1.shape[1],121), np.arange(0,data_1.shape[0]))    # [T,61] => [T,121]
                data_1 = np.expand_dims(data_1.transpose(), axis=0) # [T,121]=>[1,121,T]
                # Downsample
                data_1 = data_1[:,:,0::downsamp_ratio_for_stft] # [1,121,T]=>[1,121,t]

                # Skip nan
                if np.sum(np.isnan(data_1)):
                    print('Skipping ' + str(data_file_name))
                    continue

                # Normalization
                data_normed_1 = normalize_data(data_1)  # [6,121,t]

                # Update T_MAX
                if T_MAX < np.array(data_1).shape[2]:
                    T_MAX = np.array(data_1).shape[2]                
            except Exception as e:
                print(str(e))
                continue

            # Save List
            data.append(data_normed_1.tolist())
            label.append(label_1)

    # Zero-padding
    data = zero_padding(data, T_MAX)    # ([6,121,t1],...)=>[N,6,121,T]

    # Convert label to ndarray
    label = np.array(label)

    # data(ndarray): [N,6,121,T_MAX], label(ndarray): [N,]
    return data, label
//  [python]
def load_data_to_array(path_to_data):
    # Need customization
    # data: [N,6,121,T_MAX]
    # label: [N,]
    global T_MAX
    print('Loading data from ' + str(path_to_data))

    # Load data
    data = []
    label = []
    for data_root, data_dirs, data_files in os.walk(path_to_data):
        for data_file_name in data_files:

            file_path = os.path.join(data_root,data_file_name)
            try:
                # Data Selection
                label_1_name = data_file_name.split('_')[0]
                if label_1_name == 'fall':
                    label_1 = 1
                elif label_1_name == 'nonfall':
                    label_1 = 0
                else:
                    print('Wrong fall/nonfall prefix, skiping...')
                    continue

                data_1 = np.abs(scio.loadmat(file_path)[mat_file_key])  # [T,61]
                # Interpolation
                x = np.arange(0,data_1.shape[1])
                y = np.arange(0,data_1.shape[0])
                tck = scipy.interpolate.bisplrep(x, y, data_1)
                data_1 = scipy.interpolate.bisplev(np.linspace(0,data_1.shape[1],121), y, tck)    # [T,61] => [T,121]
                data_1 = np.expand_dims(data_1.transpose(), axis=0) # [T,121]=>[1,121,T]
                # Downsample
                data_1 = data_1[:,:,0::downsamp_ratio_for_stft] # [1,121,T]=>[1,121,t]

                # Skip nan
                if np.sum(np.isnan(data_1)):
                    print('Skipping ' + str(data_file_name))
                    continue

                # Normalization
                data_normed_1 = normalize_data(data_1)  # [6,121,t]

                # Update T_MAX
                if T_MAX < np.array(data_1).shape[2]:
                    T_MAX = np.array(data_1).shape[2]                
            except Exception as e:
                print(str(e))
                continue

            # Save List
            data.append(data_normed_1.tolist())
            label.append(label_1)

    # Zero-padding
    data = zero_padding(data, T_MAX)    # ([6,121,t1],...)=>[N,6,121,T]

    # Convert label to ndarray
    label = np.array(label)

    # data(ndarray): [N,6,121,T_MAX], label(ndarray): [N,]
    return data, label
//  [python]
def compute_multiplicity_grid_MZ(self, z_grid = None, logm_grid = None):
        r"""
        Attributes:
        -----------
        z_grid : array
            redshift grid
        logm_grid : array
            logm grid
        Returns:
        --------
        dN_dzdlogMdOmega : array
            tabulated multiplicity function over the redshift and logmass grid
        dzdlogMdOmega_interpolation : function
            interpolated function over the tabulated multiplicity grid
        """
        self.z_grid = z_grid
        self.logm_grid = logm_grid
        grid = np.zeros([len(self.logm_grid), len(self.z_grid)])
        for i, z in enumerate(self.z_grid):
            grid[:,i] = self.dndlog10M(self.logm_grid ,z) * self.dVdzdOmega(z)
        self.dN_dzdlogMdOmega = grid
        self.dNdzdlogMdOmega_interpolation = interpolate.interp2d(self.z_grid, 
                                                                self.logm_grid, 
                                                                self.dN_dzdlogMdOmega, 
                                                                kind='cubic')
//  [python]
def compute_multiplicity_grid_MZ(self, z_grid = None, logm_grid = None):
        r"""
        Attributes:
        -----------
        z_grid : array
            redshift grid
        logm_grid : array
            logm grid
        Returns:
        --------
        dN_dzdlogMdOmega : array
            tabulated multiplicity function over the redshift and logmass grid
        dzdlogMdOmega_interpolation : function
            interpolated function over the tabulated multiplicity grid
        """
        self.z_grid = z_grid
        self.logm_grid = logm_grid
        grid = np.zeros([len(self.logm_grid), len(self.z_grid)])
        for i, z in enumerate(self.z_grid):
            grid[:,i] = self.dndlog10M(self.logm_grid ,z) * self.dVdzdOmega(z)
        self.dN_dzdlogMdOmega = grid
        tck = interpolate.bisplev(self.z_grid, self.logm_grid, self.dN_dzdlogMdOmega)
        self.dNdzdlogMdOmega_interpolation = lambda z, logm: interpolate.bisplev(z, logm, tck)
//  [python]
def compute_halo_bias_grid_MZ(self, z_grid = None, logm_grid = None, halobias = None):
        r"""
        Attributes:
        -----------
        z_grid : array
            redshift grid
        logm_grid : array
            logm grid
        Returns:
        --------
        dN_dzdlogMdOmega : array
            tabulated multiplicity function over the redshift and logmass grid
        dzdlogMdOmega_interpolation : function
            interpolated function over the tabulated multiplicity grid
        """
        grid = np.zeros([len(self.logm_grid), len(self.z_grid)])
        self.halo_bias_model = halobias
        for i, z in enumerate(self.z_grid):
            hb = self.halo_bias_model.get_halo_bias(self.cosmo, 10**self.logm_grid, 1./(1. + z), mdef_other = self.massdef)
            grid[:,i] = hb
        self.halo_bias = grid
        self.halo_bias_interpolation = interpolate.interp2d(self.z_grid, 
                                                                self.logm_grid, 
                                                                self.halo_bias, 
                                                                kind='cubic')
//  [python]
def compute_halo_bias_grid_MZ(self, z_grid = None, logm_grid = None, halobias = None):
        r"""
        Attributes:
        -----------
        z_grid : array
            redshift grid
        logm_grid : array
            logm grid
        Returns:
        --------
        dN_dzdlogMdOmega : array
            tabulated multiplicity function over the redshift and logmass grid
        dzdlogMdOmega_interpolation : function
            interpolated function over the tabulated multiplicity grid
        """
        grid = np.zeros([len(self.logm_grid), len(self.z_grid)])
        self.halo_bias_model = halobias
        for i, z in enumerate(self.z_grid):
            hb = self.halo_bias_model.get_halo_bias(self.cosmo, 10**self.logm_grid, 1./(1. + z), mdef_other = self.massdef)
            grid[:,i] = hb
        self.halo_bias = grid
        tck = interpolate.bisplrep(self.z_grid, self.logm_grid, self.halo_bias, kx=3, ky=3)
        self.halo_bias_interpolation = lambda x, y: interpolate.bisplev(x, y, tck)
//  [python]
loni = np.linspace(lon.min(),lon.max(),lon.size)

ix,jx,kx = u.shape

ui = np.zeros(u.shape)
vi = np.zeros(v.shape)

for i in range(kx):
    interp_u = sp.interpolate.interp2d(lon,lat,u[:,:,i],kind='linear')
    ui[:,:,i] = interp_u(loni,lati)
    interp_v = sp.interpolate.interp2d(lon,lat,v[:,:,i],kind='linear')
    vi[:,:,i] = interp_v(loni,lati)
//  [python]
loni = np.linspace(lon.min(),lon.max(),lon.size)

ix,jx,kx = u.shape

ui = np.zeros(u.shape)
vi = np.zeros(v.shape)

for i in range(kx):
    interp_u = sp.interpolate.bisplev(lon,lat,u[:,:,i])
    ui[:,:,i] = interp_u(loni,lati)
    interp_v = sp.interpolate.bisplev(lon,lat,v[:,:,i])
    vi[:,:,i] = interp_v(loni,lati)
//  [python]
def interpolate_map_data(map_data_one_slice, nlat=30, nlon=30, \
                         dlat_interp=0.2, dlon_interp=0.2, lat_order='descend',\
                         lon_order='ascend'):
    '''
    Interpolate shear velocity values on a depth slice

    Input:
        map_data_one_slice is a dictionary that constains Vs, lat, and lon of a depth slice
        nlat is the total number of grid points along latitude
        nlon is the total number of grid points along longitude
        dlat_interp is the interpolation spacing along latitude
        dlon_interp is the interpolation spacing along longitude
        lat_order is the ordering of gird points in the latitude direction
        lon_order is the ordering of grid points in the longitude direction

    Output:
        map_data_one_slice_interpolated is a dictionary that constains interpolated Vs, lat, 
            and lon of the depth slice
    '''
    map_vs = map_data_one_slice['vs']
    map_lat = map_data_one_slice['lat']
    map_lon = map_data_one_slice['lon']
    z_list = np.zeros((nlat,nlon))
    for ilat in range(nlat):
        for ilon in range(nlon):
            index = ilat * nlon + ilon
            z_list[ilat][ilon] = map_vs[index]
    #
    x_temp = map_lon[0:nlon]
    y_temp = [map_lat[i*nlon] for i in range(nlat)]
    f = interpolate.interp2d(x_temp,y_temp,z_list,kind='cubic')
    if lon_order == 'ascend':
        lon_new = np.arange(min(x_temp),max(x_temp)+dlon_interp, dlon_interp)
    elif lon_order == 'descend':
        lon_new = np.arange(max(x_temp),min(x_temp)-dlon_interp, -dlon_interp)
    if lat_order == 'ascend':
        lat_new = np.arange(min(y_temp),max(y_temp)+dlat_interp, dlat_interp)
    elif lat_order == 'descend':
        lat_new = np.arange(max(y_temp),min(y_temp)-dlat_interp, -dlat_interp)
    z_new = f(lon_new,lat_new)
    map_data_one_slice_interpolated = {}
    map_data_one_slice_interpolated['vs'] = z_new
    map_data_one_slice_interpolated['lat'] = lat_new
    map_data_one_slice_interpolated['lon'] = lon_new
    return map_data_one_slice_interpolated
//  [python]
def interpolate_map_data(map_data_one_slice, nlat=30, nlon=30, \
                         dlat_interp=0.2, dlon_interp=0.2, lat_order='descend',\
                         lon_order='ascend'):
    '''
    Interpolate shear velocity values on a depth slice

    Input:
        map_data_one_slice is a dictionary that constains Vs, lat, and lon of a depth slice
        nlat is the total number of grid points along latitude
        nlon is the total number of grid points along longitude
        dlat_interp is the interpolation spacing along latitude
        dlon_interp is the interpolation spacing along longitude
        lat_order is the ordering of gird points in the latitude direction
        lon_order is the ordering of grid points in the longitude direction

    Output:
        map_data_one_slice_interpolated is a dictionary that constains interpolated Vs, lat, 
            and lon of the depth slice
    '''
    map_vs = map_data_one_slice['vs']
    map_lat = map_data_one_slice['lat']
    map_lon = map_data_one_slice['lon']
    z_list = np.zeros((nlat,nlon))
    for ilat in range(nlat):
        for ilon in range(nlon):
            index = ilat * nlon + ilon
            z_list[ilat][ilon] = map_vs[index]
    #
    x_temp = map_lon[0:nlon]
    y_temp = [map_lat[i*nlon] for i in range(nlat)]
    tck = interpolate.bisplrep(x_temp,y_temp,z_list,s=0)
    if lon_order == 'ascend':
        lon_new = np.arange(min(x_temp),max(x_temp)+dlon_interp, dlon_interp)
    elif lon_order == 'descend':
        lon_new = np.arange(max(x_temp),min(x_temp)-dlon_interp, -dlon_interp)
    if lat_order == 'ascend':
        lat_new = np.arange(min(y_temp),max(y_temp)+dlat_interp, dlat_interp)
    elif lat_order == 'descend':
        lat_new = np.arange(max(y_temp),min(y_temp)-dlat_interp, -dlat_interp)
    z_new = interpolate.bisplev(lon_new,lat_new,tck)
    map_data_one_slice_interpolated = {}
    map_data_one_slice_interpolated['vs'] = z_new
    map_data_one_slice_interpolated['lat'] = lat_new
    map_data_one_slice_interpolated['lon'] = lon_new
    return map_data_one_slice_interpolated
//  [python]
def test_interp2d(self):
        y, x = mgrid[0:2:20j, 0:pi:21j]
        z = sin(x+0.5*y)
        with suppress_warnings() as sup:
            sup.filter(DeprecationWarning)
            II = interp2d(x, y, z)
            assert_almost_equal(II(1.0, 2.0), sin(2.0), decimal=2)

            v, u = ogrid[0:2:24j, 0:pi:25j]
            assert_almost_equal(II(u.ravel(), v.ravel()),
                                sin(u+0.5*v), decimal=2)
//  [python]
def test_interp2d(self):
        y, x = mgrid[0:2:20j, 0:pi:21j]
        z = sin(x+0.5*y)
        with suppress_warnings() as sup:
            sup.filter(DeprecationWarning)
            II = bisplev(x, y, z)
            assert_almost_equal(II(1.0, 2.0), sin(2.0), decimal=2)

            v, u = ogrid[0:2:24j, 0:pi:25j]
            assert_almost_equal(II(u.ravel(), v.ravel()),
                                sin(u+0.5*v), decimal=2)
//  [python]
def test_interp2d_meshgrid_input(self):
        # Ticket #703
        x = linspace(0, 2, 16)
        y = linspace(0, pi, 21)
        z = sin(x[None, :] + y[:, None]/2.)
        with suppress_warnings() as sup:
            sup.filter(DeprecationWarning)
            II = interp2d(x, y, z)
            assert_almost_equal(II(1.0, 2.0), sin(2.0), decimal=2)
//  [python]
def test_interp2d_meshgrid_input(self):
        # Ticket #703
        x = linspace(0, 2, 16)
        y = linspace(0, pi, 21)
        z = sin(x[None, :] + y[:, None]/2.)
        with suppress_warnings() as sup:
            sup.filter(DeprecationWarning)
            II = bisplev(x, y, z)
            assert_almost_equal(II(1.0, 2.0), sin(2.0), decimal=2)
//  [python]
def compute_cdf_grid_ProxyZ(self, proxybin_edges = None, proxy_model = None, 
                                       z_grid = None, logm_grid = None):
        r"""
        Attributes:
        -----------
        lnLambda_bin: list of 2D arrays
            list of proxy bins
        proxy_model: object
            object from class with mass-proxy relation methods
            use of cumulative function
        Returns:
        --------
        cumulative_proxy_grid : array
            2D array of the proxy cumulative in proxy bins on a mass-redshift grid
        cumulative_proxy_grid_interp : array
            interpolation of the proxy cumulative in proxy bins
        """
        
        Proxy_bin = binning(proxybin_edges)

        
        cumulative_grid = []
        cumulative_grid_interp = []
        for proxy_bin in Proxy_bin:
            cdf = np.zeros([len(logm_grid), len(z_grid)])
            for i, z_value in enumerate(z_grid):
                cdf[:,i] = proxy_model.cdf(proxy_bin, z_value, logm_grid)
            cdf_interp = interpolate.interp2d(z_grid, 
                                            logm_grid, 
                                            cdf, 
                                            kind='cubic')
            cumulative_grid.append(cdf)
            cumulative_grid_interp.append(cdf_interp)
        self.cdf_proxy_grid = np.array(cumulative_grid)
        self.cdf_proxy_grid_interp = np.array(cumulative_grid_interp)
//  [python]
def compute_cdf_grid_ProxyZ(self, proxybin_edges = None, proxy_model = None, 
                                       z_grid = None, logm_grid = None):
        r"""
        Attributes:
        -----------
        lnLambda_bin: list of 2D arrays
            list of proxy bins
        proxy_model: object
            object from class with mass-proxy relation methods
            use of cumulative function
        Returns:
        --------
        cumulative_proxy_grid : array
            2D array of the proxy cumulative in proxy bins on a mass-redshift grid
        cumulative_proxy_grid_interp : array
            interpolation of the proxy cumulative in proxy bins
        """
        
        Proxy_bin = binning(proxybin_edges)

        
        cumulative_grid = []
        cumulative_grid_interp = []
        for proxy_bin in Proxy_bin:
            cdf = np.zeros([len(logm_grid), len(z_grid)])
            for i, z_value in enumerate(z_grid):
                cdf[:,i] = proxy_model.cdf(proxy_bin, z_value, logm_grid)
            tck = interpolate.bisplrep(z_grid, logm_grid, cdf)
            cdf_interp = lambda z, logm: interpolate.bisplev(z, logm, tck)
            cumulative_grid.append(cdf)
            cumulative_grid_interp.append(cdf_interp)
        self.cdf_proxy_grid = np.array(cumulative_grid)
        self.cdf_proxy_grid_interp = np.array(cumulative_grid_interp)
//  [python]
def test_interp2d_linear(self):
        # Ticket #898
        a = np.zeros([5, 5])
        a[2, 2] = 1.0
        x = y = np.arange(5)
        with suppress_warnings() as sup:
            sup.filter(DeprecationWarning)
            b = interp2d(x, y, a, 'linear')
            assert_almost_equal(b(2.0, 1.5), np.array([0.5]), decimal=2)
            assert_almost_equal(b(2.0, 2.5), np.array([0.5]), decimal=2)
//  [python]
def test_interp2d_linear(self):
        # Ticket #898
        a = np.zeros([5, 5])
        a[2, 2] = 1.0
        x = y = np.arange(5)
        with suppress_warnings() as sup:
            sup.filter(DeprecationWarning)
            b = bisplev(x, y, a, dx=1, dy=1)
            assert_almost_equal(b(2.0, 1.5), np.array([0.5]), decimal=2)
            assert_almost_equal(b(2.0, 2.5), np.array([0.5]), decimal=2)
//  [python]
def test_interp2d_eval_unsorted(self):
        y, x = mgrid[0:2:20j, 0:pi:21j]
        z = sin(x + 0.5*y)
        with suppress_warnings() as sup:
            sup.filter(DeprecationWarning)
            func = interp2d(x, y, z)

            xe = np.array([3, 4, 5])
            ye = np.array([5.3, 7.1])
            assert_allclose(func(xe, ye), func(xe, ye[::-1]))

            assert_raises(ValueError, func, xe, ye[::-1], 0, 0, True)
//  [python]
def test_interp2d_eval_unsorted(self):
        y, x = mgrid[0:2:20j, 0:pi:21j]
        z = sin(x + 0.5*y)
        with suppress_warnings() as sup:
            sup.filter(DeprecationWarning)
            tck = splprep([x.ravel(), y.ravel(), z.ravel()], s=0)
            func = lambda x, y: bisplev(x, y, tck)

            xe = np.array([3, 4, 5])
            ye = np.array([5.3, 7.1])
            assert_allclose(func(xe, ye), func(xe, ye[::-1]))

            assert_raises(ValueError, func, xe, ye[::-1], 0, 0, True)
//  [python]
def test_interp2d_bounds(self):
        x = np.linspace(0, 1, 5)
        y = np.linspace(0, 2, 7)
        z = x[None, :]**2 + y[:, None]

        ix = np.linspace(-1, 3, 31)
        iy = np.linspace(-1, 3, 33)

        with suppress_warnings() as sup:
            sup.filter(DeprecationWarning)

            b = interp2d(x, y, z, bounds_error=True)
            assert_raises(ValueError, b, ix, iy)

            b = interp2d(x, y, z, fill_value=np.nan)
            iz = b(ix, iy)
            mx = (ix < 0) | (ix > 1)
            my = (iy < 0) | (iy > 2)
            assert_(np.isnan(iz[my, :]).all())
            assert_(np.isnan(iz[:, mx]).all())
            assert_(np.isfinite(iz[~my, :][:, ~mx]).all())
//  [python]
def test_interp2d_bounds(self):
        x = np.linspace(0, 1, 5)
        y = np.linspace(0, 2, 7)
        z = x[None, :]**2 + y[:, None]

        ix = np.linspace(-1, 3, 31)
        iy = np.linspace(-1, 3, 33)

        with suppress_warnings() as sup:
            sup.filter(DeprecationWarning)

            tck = bisplev(x, y, z)
            b = lambda x, y: bisplev(x, y, tck)
            assert_raises(ValueError, b, ix, iy)

            b = lambda x,y: bisplev(x, y, z, kx=1, ky=1, fill_value=np.nan)
            iz = b(ix, iy)
            mx = (ix < 0) | (ix > 1)
            my = (iy < 0) | (iy > 2)
            assert_(np.isnan(iz[my, :]).all())
            assert_(np.isnan(iz[:, mx]).all())
            assert_(np.isfinite(iz[~my, :][:, ~mx]).all())
//  [python]
def test_interp2d_meshgrid_input_unsorted(self):
        np.random.seed(1234)
        x = linspace(0, 2, 16)
        y = linspace(0, pi, 21)

        z = sin(x[None, :] + y[:, None] / 2.)
        with suppress_warnings() as sup:
            sup.filter(DeprecationWarning)
            ip1 = interp2d(x.copy(), y.copy(), z, kind='cubic')

            np.random.shuffle(x)
            z = sin(x[None, :] + y[:, None]/2.)
            ip2 = interp2d(x.copy(), y.copy(), z, kind='cubic')

            np.random.shuffle(x)
            np.random.shuffle(y)
            z = sin(x[None, :] + y[:, None] / 2.)
            ip3 = interp2d(x, y, z, kind='cubic')

            x = linspace(0, 2, 31)
            y = linspace(0, pi, 30)

            assert_equal(ip1(x, y), ip2(x, y))
            assert_equal(ip1(x, y), ip3(x, y))
//  [python]
def test_interp2d_meshgrid_input_unsorted(self):
        np.random.seed(1234)
        x = linspace(0, 2, 16)
        y = linspace(0, pi, 21)

        z = sin(x[None, :] + y[:, None] / 2.)
        with suppress_warnings() as sup:
            sup.filter(DeprecationWarning)
            tck = bisplrep(x, y, z, kx=3, ky=3)
            ip1 = lambda x, y: bisplev(x, y, tck)

            np.random.shuffle(x)
            z = sin(x[None, :] + y[:, None]/2.)
            tck = bisplrep(x, y, z, kx=3, ky=3)
            ip2 = lambda x, y: bisplev(x, y, tck)

            np.random.shuffle(x)
            np.random.shuffle(y)
            z = sin(x[None, :] + y[:, None] / 2.)
            tck = bisplrep(x, y, z, kx=3, ky=3)
            ip3 = lambda x, y: bisplev(x, y, tck)

            x = linspace(0, 2, 31)
            y = linspace(0, pi, 30)

            assert_equal(ip1(x, y), ip2(x, y))
            assert_equal(ip1(x, y), ip3(x, y))
//  [python]
def calculate_AB_mag(time_steps, model_lambda, sim_flux, wave, trans):
    lambda_filter1 = [i for i in model_lambda if i > wave[0] and i < wave[len(wave)-1]]
    lambda_filter2 = N.append(wave[0], lambda_filter1)
    lambda_filter = N.append(lambda_filter2, wave[len(wave)-1])
    
    f = interpolate.interp2d(model_lambda, time_steps, sim_flux)
    flux_filter = (f(lambda_filter, time_steps))
    trans_filter = N.interp(lambda_filter, wave, trans)
    
    top = N.trapz((lambda_filter*flux_filter*trans_filter), lambda_filter, axis=1)
    bottom = N.trapz(trans_filter/lambda_filter, lambda_filter)
    
    m_ab = -2.41 - 2.5*N.log10(top/bottom)
    return m_ab
//  [python]
def calculate_AB_mag(time_steps, model_lambda, sim_flux, wave, trans):
    lambda_filter1 = [i for i in model_lambda if i > wave[0] and i < wave[len(wave)-1]]
    lambda_filter2 = N.append(wave[0], lambda_filter1)
    lambda_filter = N.append(lambda_filter2, wave[len(wave)-1])
    
    tck = interpolate.bisplrep(model_lambda, time_steps, sim_flux)
    flux_filter = interpolate.bisplev(lambda_filter, time_steps, tck)
    trans_filter = N.interp(lambda_filter, wave, trans)
    
    top = N.trapz((lambda_filter*flux_filter*trans_filter), lambda_filter, axis=1)
    bottom = N.trapz(trans_filter/lambda_filter, lambda_filter)
    
    m_ab = -2.41 - 2.5*N.log10(top/bottom)
    return m_ab
//  [python]
def gridData(self):
        nrad = 9
        npol = 7
        rgrid = np.arange(1, nrad + 1)
        pgrid = np.arange(1, npol + 1)
        rr, pp = np.meshgrid(rgrid, pgrid)
        print(pp.shape)
        rnew = np.arange(0.5, nrad + 0.51, 0.25)
        pnew = np.arange(0.5, npol + 0.51, 0.25)
        self.gdata = np.zeros((pnew.size, rnew.size, self.ftime.size))
        print('starting interpolation')
        for i in np.arange(self.ftime.size):
            if i != 0 and np.mod(i + 1, 100) == 0:
                print('  frame {} of {}'.format(i + 1, self.ftime.size))
            f = scipy.interpolate.interp2d(rr,
                                           pp,
                                           self.fdata[:, :, i].squeeze(),
                                           kind='linear')
            self.gdata[:, :, i] = f(rnew, pnew)
//  [python]
def gridData(self):
        nrad = 9
        npol = 7
        rgrid = np.arange(1, nrad + 1)
        pgrid = np.arange(1, npol + 1)
        rr, pp = np.meshgrid(rgrid, pgrid)
        print(pp.shape)
        rnew = np.arange(0.5, nrad + 0.51, 0.25)
        pnew = np.arange(0.5, npol + 0.51, 0.25)
        self.gdata = np.zeros((pnew.size, rnew.size, self.ftime.size))
        print('starting interpolation')
        for i in np.arange(self.ftime.size):
            if i != 0 and np.mod(i + 1, 100) == 0:
                print('  frame {} of {}'.format(i + 1, self.ftime.size))
            tck = scipy.interpolate.bisplev(rgrid, pgrid, self.fdata[:, :, i].squeeze())
            self.gdata[:, :, i] = scipy.interpolate.bisplev(rnew, pnew, tck)
//  [python]
def predict_z_height(pos_list, xy_location=None):
    '''Interpolate the z value at xy_location
 
    args:
    pos_list: a Position List containing at least 4 points
    xy_location: a tuple (x,y) containing the point in question
 
    returns: interpolated z height (float), interpolation function
    '''
    if len(pos_list) < 4:
        raise ValueError("Position List must have at least 4 values")
 
    f = scipy.interpolate.interp2d(
            [p.x for p in pos_list], 
            [p.y for p in pos_list], 
            [p.z for p in pos_list], 
            kind='cubic')
    
    if xy_location is None:
        return f
    return f(xy_location[0], xy_location[1]), f
//  [python]
def predict_z_height(pos_list, xy_location=None):
    '''Interpolate the z value at xy_location
 
    args:
    pos_list: a Position List containing at least 4 points
    xy_location: a tuple (x,y) containing the point in question
 
    returns: interpolated z height (float), interpolation function
    '''
    if len(pos_list) < 4:
        raise ValueError("Position List must have at least 4 values")
 
    x = [p.x for p in pos_list]
    y = [p.y for p in pos_list]
    z = [p.z for p in pos_list]
    
    tck = scipy.interpolate.bisplrep(x, y, z, kx=3, ky=3)
    
    if xy_location is None:
        return tck
    return scipy.interpolate.bisplev(xy_location[0], xy_location[1], tck), tck
//  [python]
def __init__(self, interp_kind='linear'):

        from scipy import interpolate

        x = [np.log10(1.e-3),np.log10(5e-3),np.log10(1e-2),np.log10(5e-2)]
        y = [0.1,0.2,0.3]
        a = [[2.01,0.81,0.56,0.27],[4.52,1.90,1.31,0.55],[8.16,3.20,2.19,0.95]]
        b = [[0.28,0.19,0.17,0.10],[0.62,0.28,0.21,0.13],[1.19,0.45,0.31,0.15]]
        d = [[1.12,0.86,0.74,0.60],[1.39,1.21,1.13,0.90],[1.52,1.39,1.32,1.13]]

        # define the interpolation functions
        self.fa = interpolate.interp2d(x, y, a, kind=interp_kind)
        self.fb = interpolate.interp2d(x, y, b, kind=interp_kind)
        self.fd = interpolate.interp2d(x, y, d, kind=interp_kind)
//  [python]
def __init__(self, interp_kind='linear'):

        from scipy import interpolate
        import numpy as np

        x = [np.log10(1.e-3),np.log10(5e-3),np.log10(1e-2),np.log10(5e-2)]
        y = [0.1,0.2,0.3]
        a = [[2.01,0.81,0.56,0.27],[4.52,1.90,1.31,0.55],[8.16,3.20,2.19,0.95]]
        b = [[0.28,0.19,0.17,0.10],[0.62,0.28,0.21,0.13],[1.19,0.45,0.31,0.15]]
        d = [[1.12,0.86,0.74,0.60],[1.39,1.21,1.13,0.90],[1.52,1.39,1.32,1.13]]

        tck_a = interpolate.bisplrep(x, y, a, kx=1, ky=1)
        tck_b = interpolate.bisplrep(x, y, b, kx=1, ky=1)
        tck_d = interpolate.bisplrep(x, y, d, kx=1, ky=1)

        self.fa = lambda x,y: interpolate.bisplev(x,y,tck_a)
        self.fb = lambda x,y: interpolate.bisplev(x,y,tck_b)
        self.fd = lambda x,y: interpolate.bisplev(x,y,tck_d)
//  [python]
def __PDF_int_F(u, T0, px):
    """Forward probabilitydistribution of electrons in tungsten with energy
    u * T0 and depth px [mg/cm2]
    u: fraction of initial electron energy (tube potensial)
    T0: initial energy (tube potensial)
    px: depth in tungsten
    """
    # interpolating Monte-Carlo data obtained from ref1 (paper1)
    f = inter.interp2d(CPF100_F_px, CPF100_u, CPF100_F, fill_value=None)
    return f(px, u) * __R_TW(T0) / __R_TW(100.)
//  [python]
def __PDF_int_F(u, T0, px):
    """Forward probabilitydistribution of electrons in tungsten with energy
    u * T0 and depth px [mg/cm2]
    u: fraction of initial electron energy (tube potensial)
    T0: initial energy (tube potensial)
    px: depth in tungsten
    """
    # interpolating Monte-Carlo data obtained from ref1 (paper1)
    f = interpolate.bisplev(CPF100_F_px, CPF100_u, CPF100_F)
    return f(px, u) * __R_TW(T0) / __R_TW(100.)
//  [python]
def line_params_2D(gridval1, gridval2, griddim1, griddim2, valuegrid):
    """
    Given a 2D grid of modeled line values - the amplitude, e.g. excitation temperature,
    and the optical depth, tau - return the model spectrum

    griddims contains the names of the axes and their values... it should have the same 
    number of entries as gridpars
    """

    if not scipyOK:
        raise ImportError("Scipy could not be imported, therefore interpolation is not available.")

    #matchpt1 = np.argmin( np.abs( gridval1 - griddim1[0,:] ))
    #matchpt2 = np.argmin( np.abs( gridval2 - griddim2[:,0] ))

    return scipy.ndimage.map_coordinates(valuegrid,np.array([[gridval2],[gridval1]]),order=1)

    interpgrid = scipy.interpolate.interp2d( 
            griddim1[ gridval1-5:gridval1+5, gridval2-5:gridval2+5].ravel(),
            griddim2[ gridval1-5:gridval1+5, gridval2-5:gridval2+5].ravel(),
            valuegrid[gridval1-5:gridval1+5, gridval2-5:gridval2+5].ravel())
    
    return interpgrid(gridval1,gridval2)
//  [python]
def line_params_2D(gridval1, gridval2, griddim1, griddim2, valuegrid):
    """
    Given a 2D grid of modeled line values - the amplitude, e.g. excitation temperature,
    and the optical depth, tau - return the model spectrum

    griddims contains the names of the axes and their values... it should have the same 
    number of entries as gridpars
    """

    if not scipyOK:
        raise ImportError("Scipy could not be imported, therefore interpolation is not available.")

    #matchpt1 = np.argmin( np.abs( gridval1 - griddim1[0,:] ))
    #matchpt2 = np.argmin( np.abs( gridval2 - griddim2[:,0] ))

    return scipy.ndimage.map_coordinates(valuegrid,np.array([[gridval2],[gridval1]]),order=1)

    tck = scipy.interpolate.bisplev(griddim1[ gridval1-5:gridval1+5, gridval2-5:gridval2+5].ravel(),
            griddim2[ gridval1-5:gridval1+5, gridval2-5:gridval2+5].ravel(),
            valuegrid[gridval1-5:gridval1+5, gridval2-5:gridval2+5].ravel())
    
    return tck(gridval1,gridval2)
//  [python]
def __PDF_int_M(u, T0, px):
    """Backward (scattered) probability distribution of electrons in tungsten
    with energy u * T0 and depth px [mg/cm2]
    u: fraction of initial electron energy (tube potensial)
    T0: initial energy (tube potensial)
    px: depth in tungsten
    """
    # interpolating Monte-Carlo data obtained from ref1 (paper1)
    f = inter.interp2d(CPF100_M_px, CPF100_u, CPF100_M, fill_value=None)
    return f(px, u) * __R_TW(T0) / __R_TW(100.)
//  [python]
def __PDF_int_M(u, T0, px):
    """Backward (scattered) probability distribution of electrons in tungsten
    with energy u * T0 and depth px [mg/cm2]
    u: fraction of initial electron energy (tube potensial)
    T0: initial energy (tube potensial)
    px: depth in tungsten
    """
    # interpolating Monte-Carlo data obtained from ref1 (paper1)
    f = bisplev(CPF100_M_px, CPF100_u, CPF100_M)
    return f(px, u) * __R_TW(T0) / __R_TW(100.)
//  [python]
def hawki_buildepsf(scifile, stars, pscale=0.06, size=69):
    
    oversampling = 0.106/pscale
    
    #read star positions
    strfile = ascii.read(stars)
    
    data = fits.open(scifile)[0].data
    nddata = NDData(data=data)
    
    strdata = psf.extract_stars(nddata, strfile, size=50)
    
    import matplotlib.pyplot as mp
    from astropy.visualization import simple_norm
    nrows = 5
    ncols = 5
    
    fig, ax = mp.subplots(nrows=nrows, ncols=ncols, figsize=(20,20), squeeze=True)
    ax = ax.ravel()
    for i in range(len(strdata)):
        norm = simple_norm(strdata[i], 'log', percent=99.)
        ax[i].imshow(strdata[i], norm=norm, origin='lower', cmap='viridis')
    
    mp.show()        
    
    epsf_builder = psf.EPSFBuilder(oversampling=2, shape=91, maxiters=20, progress_bar=True, smoothing_kernel='quadratic' )
    epsf, fitted_stars = epsf_builder(strdata)
    
    pos_oversamp = (np.arange(91)-45)*(0.106/2)
    pos_requested = (np.arange(size)-np.floor(size/2.))*pscale
    
    finterp = sinterp.interp2d(pos_oversamp, pos_oversamp, epsf.data, kind='linear')
    epsf_interp = finterp(pos_requested, pos_requested)
    epsf_interp[epsf_interp<0] = 0
        
    norm = simple_norm(epsf.data, 'log', percent=99.)
    mp.imshow(epsf.data, norm=norm, origin='lower', cmap='viridis')
    mp.show()
    mp.imshow(epsf_interp, norm=norm, origin='lower', cmap='viridis')
    mp.show()
    
    hduout = fits.PrimaryHDU(epsf_interp/np.nansum(epsf_interp))
    hduout.header['PSCALE' ] = pscale
    hduout.header['OVERSAMP'] = oversampling
    
    hduout.writeto('HAWKI_epsf.fits', overwrite=True)
//  [python]
def hawki_buildepsf(scifile, stars, pscale=0.06, size=69):
    
    oversampling = 0.106/pscale
    
    #read star positions
    strfile = ascii.read(stars)
    
    data = fits.open(scifile)[0].data
    nddata = NDData(data=data)
    
    strdata = psf.extract_stars(nddata, strfile, size=50)
    
    import matplotlib.pyplot as mp
    from astropy.visualization import simple_norm
    nrows = 5
    ncols = 5
    
    fig, ax = mp.subplots(nrows=nrows, ncols=ncols, figsize=(20,20), squeeze=True)
    ax = ax.ravel()
    for i in range(len(strdata)):
        norm = simple_norm(strdata[i], 'log', percent=99.)
        ax[i].imshow(strdata[i], norm=norm, origin='lower', cmap='viridis')
    
    mp.show()        
    
    epsf_builder = psf.EPSFBuilder(oversampling=2, shape=91, maxiters=20, progress_bar=True, smoothing_kernel='quadratic' )
    epsf, fitted_stars = epsf_builder(strdata)
    
    pos_oversamp = (np.arange(91)-45)*(0.106/2)
    pos_requested = (np.arange(size)-np.floor(size/2.))*pscale
    
    from scipy.interpolate import bisplev, bisplrep
    tck = bisplrep(pos_oversamp, pos_oversamp, epsf.data)
    epsf_interp = bisplev(pos_requested, pos_requested, tck)
    epsf_interp[epsf_interp<0] = 0
        
    norm = simple_norm(epsf.data, 'log', percent=99.)
    mp.imshow(epsf.data, norm=norm, origin='lower', cmap='viridis')
    mp.show()
    mp.imshow(epsf_interp, norm=norm, origin='lower', cmap='viridis')
    mp.show()
    
    hduout = fits.PrimaryHDU(epsf_interp/np.nansum(epsf_interp))
    hduout.header['PSCALE' ] = pscale
    hduout.header['OVERSAMP'] = oversampling
    
    hduout.writeto('HAWKI_epsf.fits', overwrite=True)
//  [python]
def calc_bivariate_qq(libbgmg, zgrid, pdf):
    zgrid_fine = np.arange(-25, 25.00001, 0.005)   # project to a finer grid
    pdf_fine=scipy.interpolate.interp2d(zgrid, zgrid, pdf)(zgrid_fine, zgrid_fine)
    pthresh_vec = [1, 0.1, 0.01, 0.001]
    zthresh_vec = -scipy.stats.norm.ppf(np.array(pthresh_vec)/2)

    zvec1=libbgmg.zvec1
    zvec2=libbgmg.zvec2

    # Regular grid (vertical axis of the QQ plots)
    hv_z = np.linspace(0, np.min([np.max(np.abs(np.concatenate((zvec1, zvec2)))), 38.0]), 1000)
    hv_logp = -np.log10(2*scipy.stats.norm.cdf(-hv_z))

    result = []
    for zthresh, pthresh in zip(zthresh_vec, pthresh_vec):
        mask = abs(zvec2)>=zthresh
        data_logpvec = calc_qq_data(zvec1[mask], libbgmg.weights[mask], hv_logp)

        pd_cond = np.sum(pdf_fine[abs(zgrid_fine) >= zthresh, :], axis=0)
        pd_cond = pd_cond / np.sum(pd_cond) / (zgrid_fine[1]-zgrid_fine[0])
        model_logpvec = calc_qq_model(zgrid_fine, pd_cond, hv_z)

        title = 'T1|T2|{}'.format(pthresh)
        result.append({'hv_logp': hv_logp, 'data_logpvec': data_logpvec, 'model_logpvec': model_logpvec,
                       'n_snps': int(np.sum(mask)), 'sum_data_weights': float(np.sum(libbgmg.weights[mask])), 'title' : title})

    for zthresh in zthresh_vec:
        mask = abs(zvec1)>=zthresh
        data_logpvec = calc_qq_data(zvec2[mask], libbgmg.weights[mask], hv_logp)

        pd_cond = np.sum(pdf_fine[:, abs(zgrid_fine) >= zthresh], axis=1)
        pd_cond = pd_cond / np.sum(pd_cond) / (zgrid_fine[1]-zgrid_fine[0])
        model_logpvec = calc_qq_model(zgrid_fine, pd_cond, hv_z)

        title = 'T2|T1|{}'.format(pthresh)
        result.append({'hv_logp': hv_logp, 'data_logpvec': data_logpvec, 'model_logpvec': model_logpvec,
                       'n_snps': int(np.sum(mask)), 'sum_data_weights': float(np.sum(libbgmg.weights[mask])), 'title' : title})
    return result
//  [python]
def calc_bivariate_qq(libbgmg, zgrid, pdf):
    zgrid_fine = np.arange(-25, 25.00001, 0.005)   # project to a finer grid
    pdf_fine = scipy.interpolate.bisplev(zgrid, zgrid, pdf, zgrid_fine, zgrid_fine)
    pthresh_vec = [1, 0.1, 0.01, 0.001]
    zthresh_vec = -scipy.stats.norm.ppf(np.array(pthresh_vec)/2)

    zvec1=libbgmg.zvec1
    zvec2=libbgmg.zvec2

    # Regular grid (vertical axis of the QQ plots)
    hv_z = np.linspace(0, np.min([np.max(np.abs(np.concatenate((zvec1, zvec2)))), 38.0]), 1000)
    hv_logp = -np.log10(2*scipy.stats.norm.cdf(-hv_z))

    result = []
    for zthresh, pthresh in zip(zthresh_vec, pthresh_vec):
        mask = abs(zvec2)>=zthresh
        data_logpvec = calc_qq_data(zvec1[mask], libbgmg.weights[mask], hv_logp)

        pd_cond = np.sum(pdf_fine[abs(zgrid_fine) >= zthresh, :], axis=0)
        pd_cond = pd_cond / np.sum(pd_cond) / (zgrid_fine[1]-zgrid_fine[0])
        model_logpvec = calc_qq_model(zgrid_fine, pd_cond, hv_z)

        title = 'T1|T2|{}'.format(pthresh)
        result.append({'hv_logp': hv_logp, 'data_logpvec': data_logpvec, 'model_logpvec': model_logpvec,
                       'n_snps': int(np.sum(mask)), 'sum_data_weights': float(np.sum(libbgmg.weights[mask])), 'title' : title})

    for zthresh in zthresh_vec:
        mask = abs(zvec1)>=zthresh
        data_logpvec = calc_qq_data(zvec2[mask], libbgmg.weights[mask], hv_logp)

        pd_cond = np.sum(pdf_fine[:, abs(zgrid_fine) >= zthresh], axis=1)
        pd_cond = pd_cond / np.sum(pd_cond) / (zgrid_fine[1]-zgrid_fine[0])
        model_logpvec = calc_qq_model(zgrid_fine, pd_cond, hv_z)

        title = 'T2|T1|{}'.format(pthresh)
        result.append({'hv_logp': hv_logp, 'data_logpvec': data_logpvec, 'model_logpvec': model_logpvec,
                       'n_snps': int(np.sum(mask)), 'sum_data_weights': float(np.sum(libbgmg.weights[mask])), 'title' : title})
    return result
//  [python]
def get_interp_slice_posts(x, y, vals, slice_shape):
    
    slice_vals = np.zeros(slice_shape)
    
    # interpolator 
    f = scipy.interpolate.interp2d(x, y, vals)

    # evaluate interpolator on the mesh
    xgrid = np.arange(slice_shape[0])
    ygrid = np.arange(slice_shape[1])
    yy,xx = np.meshgrid(ygrid,xgrid)
    xx = np.ravel(xx)
    yy = np.ravel(yy)
    
    for i in range(len(xx)):
        slice_vals[xx[i], yy[i]] = f(xx[i], yy[i])

    return slice_vals