Exemplo n.º 1
0
def genShiftVectorFieldSpline(nx, ny, nsx, nsy, err_sx, err_sy, bbox=None):
    """interpolates shift vectors using smoothing splines"""
    wonky = findWonkyVectors(nx, ny, nsx, nsy, tol=2 * err_sx.mean())
    #wonky = findWonkyVectors(nx, ny, nsx, nsy, tol=100)
    good = wonky == 0

    print(('%d wonky vectors found and discarded' % wonky.sum()))

    if bbox:
        spx = SmoothBivariateSpline(nx[good],
                                    ny[good],
                                    nsx[good],
                                    1. / err_sx[good],
                                    bbox=bbox)
        spy = SmoothBivariateSpline(nx[good],
                                    ny[good],
                                    nsy[good],
                                    1. / err_sy[good],
                                    bbox=bbox)
    else:
        spx = SmoothBivariateSpline(nx[good], ny[good], nsx[good],
                                    1. / err_sx[good])
        spy = SmoothBivariateSpline(nx[good], ny[good], nsy[good],
                                    1. / err_sy[good])

    X, Y = np.meshgrid(np.arange(0, 512 * 70, 100),
                       np.arange(0, 256 * 70, 100))

    dx = spx.ev(X.ravel(), Y.ravel()).reshape(X.shape)
    dy = spy.ev(X.ravel(), Y.ravel()).reshape(X.shape)

    return (dx.T, dy.T, spx, spy, good)
Exemplo n.º 2
0
def df_fixer(df_path):
    """
    There are usually holes/blank spots toward the outside of the df. The
    extrapolation we do isn't totally necessary, but it makes the later
    deformation have cleaner edges and the background color is much easier to fix.
    """

    df = np.fromfile(df_path, dtype='float32', count=-1)
    df = df.reshape((256, 256, 3), order='F')
    df_R = df[:, :, 0]
    df_C = df[:, :, 1]
    # df_R += 1
    # df_C += 1

    # fill holes in df with spline interpolation/extrapolation
    [r1, c1] = np.where(df_R != -1)
    [rq, cq] = np.where(df_R == -1)
    splineR = SmoothBivariateSpline(r1, c1, df_R[r1, c1])
    df_R[rq, cq] = splineR.ev(rq, cq)

    [r1, c1] = np.where(df_C != -1)
    [rq, cq] = np.where(df_C == -1)
    splineC = SmoothBivariateSpline(r1, c1, df_C[r1, c1])
    df_C[rq, cq] = splineC.ev(rq, cq)
    return (df_R, df_C)
Exemplo n.º 3
0
def calc_sig_dist_spline(x,
                         y,
                         xref,
                         yref,
                         n_iter=5,
                         sig_clip=3,
                         plot=False,
                         smooth_fac=10000,
                         wx=None,
                         wy=None,
                         ret_bool=False):

    #now sigma clip
    sbool = np.ones(x.shape, dtype='bool')
    for i in range(n_iter):
        #import pdb; pdb.set_trace()
        tx = Spline(x[sbool],
                    y[sbool],
                    xref[sbool] - x[sbool],
                    s=smooth_fac,
                    w=wx[sbool])
        ty = Spline(x[sbool],
                    y[sbool],
                    yref[sbool] - y[sbool],
                    s=smooth_fac,
                    w=wy[sbool])
        xout = tx.ev(x, y)
        yout = ty.ev(x, y)
        dx = xref - xout - x
        dy = yref - yout - y
        xcen = np.mean(dx[sbool])
        xsig = np.std(dx[sbool])
        ycen = np.mean(dy[sbool])
        ysig = np.std(dy[sbool])
        sbool_temp = (dx > xcen - sig_clip * xsig) * (
            dx < xcen + sig_clip * xsig) * (dy > ycen - sig_clip * ysig) * (
                dy < ycen + sig_clip * ysig)
        if i != n_iter - 1:
            sbool = sbool_temp * sbool
        print 'trimmed ', len(sbool) - np.sum(sbool), '  stars'
        if plot:
            print 'number of residuals outside of -5,5', np.sum((dx > 5) +
                                                                (dx < -5) +
                                                                (dy < -5) +
                                                                (dy > 5))
            plt.figure(35)
            plt.subplot(121)
            plt.hist(dx, bins=100, range=(-5, 5))
            plt.title('X residual to fit')
            plt.subplot(122)
            plt.hist(dy, bins=100, range=(-5, 5))
            plt.title('Y residual to fit')
            plt.show()

    if not ret_bool:
        return tx, ty, dx, dy
    else:
        return tx, ty, dx, dy, sbool
    def model(x, y):

        spline = SmoothBivariateSpline(
            width, eqPonA, factor, kx=2, ky=1)

        result = spline.ev(x, y)

        return result
Exemplo n.º 5
0
def plot_interpolated_image(P, I, file_name='plots/img.png', pregrid=False, dim=50):

    plt.clf()
    
    print 'plotting columns of matrix, shape: ', I.shape
    if (I.ndim == 1):
        I = I[:, None]
        f = 1
    else:
        f = int(np.sqrt(I.shape[1]))

    for i in xrange(f**2):

        ax = plt.subplot(f,f,i+1)
        ax.xaxis.set_visible(False)
        ax.yaxis.set_visible(False)


        xlim = ylim = 0.9
        xi = np.linspace(-xlim, xlim, dim)
        yi = np.linspace(-ylim, ylim, dim)
        XI, YI = np.meshgrid(xi, yi)

        # grid the data.
        # contour the gridded data, plotting dots at the randomly spaced data points.

        if pregrid:
            # grid then spline smooth
            ZI = griddata((P[:, 0], P[:, 1]), I[:, i],
                          (xi[None, :], yi[:, None]),
                          method='linear',
                          fill_value=np.mean(I[:, i]))

            spline = SmoothBivariateSpline(XI.flatten(), YI.flatten(), ZI.flatten())

        else:
            spline = SmoothBivariateSpline(P[:, 0], P[:, 1], I[:, i])


        zi = spline.ev(XI.flatten(), YI.flatten())
        zi = np.reshape(zi, (dim,dim))

        # rbf = Rbf(XI, YI, zi, epsilon=1e-1)
        # zz = rbf(XI, YI)

        plt.imshow(zi, interpolation='nearest')

        #plt.contour(xi,yi,zi,10, linewidths=0.5,colors='k')
        #plt.contourf(xi,yi,zi,10, cmap=plt.cm.spectral)
        #ax.scatter(P[:,0], P[:,1], c='k', s=2, linewidths=0)
        #plt.xlim(-1, 1)
        #plt.ylim(-1, 1)

    plt.savefig(file_name)
Exemplo n.º 6
0
def genShiftVectorFieldSpline(nx,ny, nsx, nsy, err_sx, err_sy, bbox=None):
    '''interpolates shift vectors using smoothing splines'''
    wonky = findWonkyVectors(nx, ny, nsx, nsy, tol=2*err_sx.mean())
    #wonky = findWonkyVectors(nx, ny, nsx, nsy, tol=100)
    good = wonky == 0

    print(('%d wonky vectors found and discarded' % wonky.sum()))
    
    if bbox:
        spx = SmoothBivariateSpline(nx[good], ny[good], nsx[good], 1./err_sx[good], bbox=bbox)
        spy = SmoothBivariateSpline(nx[good], ny[good], nsy[good], 1./err_sy[good], bbox=bbox)
    else:
        spx = SmoothBivariateSpline(nx[good], ny[good], nsx[good], 1./err_sx[good])
        spy = SmoothBivariateSpline(nx[good], ny[good], nsy[good], 1./err_sy[good])

    X, Y = np.meshgrid(np.arange(0, 512*70, 100), np.arange(0, 256*70, 100))

    dx = spx.ev(X.ravel(),Y.ravel()).reshape(X.shape)
    dy = spy.ev(X.ravel(),Y.ravel()).reshape(X.shape)

    return (dx.T, dy.T, spx, spy, good)
Exemplo n.º 7
0
def spline_model(width_test, ratio_perim_area_test, width_data,
                 ratio_perim_area_data, factor_data):
    """Return the result of the spline model.

    The bounding box is chosen so as to allow extrapolation. The spline orders
    are two in the width direction and one in the perimeter/area direction. For
    justification on using this method for modelling electron insert factors
    see the *Methods: Bivariate spline model* section within
    <http://dx.doi.org/10.1016/j.ejmp.2015.11.002>.

    Parameters
    ----------
    width_test : np.ndarray
        The width point(s) which are to have the electron insert factor
        interpolated.
    ratio_perim_area_test : np.ndarray
        The perimeter/area which are to have the electron insert factor
        interpolated.

    width_data : np.ndarray
        The width data points for the relevant applicator, energy and ssd.
    ratio_perim_area_data : np.ndarray
        The perimeter/area data points for the relevant applicator, energy and
        ssd.
    factor_data : np.ndarray
        The insert factor data points for the relevant applicator, energy and
        ssd.

    Returns
    -------
    result : np.ndarray
        The interpolated electron insert factors for width_test and
        ratio_perim_area_test.

    """
    bbox = [
        np.min([np.min(width_data), np.min(width_test)]),
        np.max([np.max(width_data), np.max(width_test)]),
        np.min([np.min(ratio_perim_area_data),
                np.min(ratio_perim_area_test)]),
        np.max([np.max(ratio_perim_area_data),
                np.max(ratio_perim_area_test)])
    ]

    spline = SmoothBivariateSpline(width_data,
                                   ratio_perim_area_data,
                                   factor_data,
                                   kx=2,
                                   ky=1,
                                   bbox=bbox)

    return spline.ev(width_test, ratio_perim_area_test)
Exemplo n.º 8
0
    def model(x, y):
        bbox = [
            np.min([np.min(width), np.min(x)]),
            np.max([np.max(width), np.max(x)]),
            np.min([np.min(eqPonA), np.min(y)]),
            np.max([np.max(eqPonA), np.max(y)])]

        spline = SmoothBivariateSpline(
            width, eqPonA, factor, kx=2, ky=1, bbox=bbox)

        result = spline.ev(x, y)

        return result
Exemplo n.º 9
0
    def model(x, y):
        bbox = [
            np.min([np.min(width), np.min(x)]),
            np.max([np.max(width), np.max(x)]),
            np.min([np.min(eqPonA), np.min(y)]),
            np.max([np.max(eqPonA), np.max(y)])
        ]

        spline = SmoothBivariateSpline(width,
                                       eqPonA,
                                       factor,
                                       kx=2,
                                       ky=1,
                                       bbox=bbox)

        result = spline.ev(x, y)

        return result
Exemplo n.º 10
0
def spline_fit(x, y, z, evaluate=False, full_ccd=True, **interp_kwargs):
    """
        spline fit to unstructured 3d data using scipy SmoothBivariateSpline.
        return callable and function evaluated over the pixels.
        
        Parameters:
        -----------
            
            x, y, z: `array-like`
                data points to fit: f(x,y) = z
            
            evaluate: `bool`
                if True, evaluate the function over the pixels
            
            full_ccd: `bool`
                if you want to evaluate the model over a full CCD or 
                just a RC.
        
        Returns:
        --------
        
            spline function (+array)
    """
    # smooth spline fit
    spline = SmoothBivariateSpline(x, y, z, **interp_kwargs)

    # eval spline over the pixels
    if evaluate:
        xmin, ymin = 0, 0
        if full_ccd:
            xmin, ymin = -xsize, -ysize
        x_pix, y_pix = np.arange(xmin, xsize)[np.newaxis, ], np.arange(
            ymin, ysize)[:, np.newaxis]
        spline_arr = spline.ev(x_pix, y_pix)
        return spline, spline_arr
    else:
        return spline
Exemplo n.º 11
0
yinput = np.repeat(heights, noa)
zinput = data[:, plot_column, :].T.flatten()
# f = interp2d(x = xinput, y = yinput, z = zinput, kind='cubic')

# interpolate
f = SmoothBivariateSpline(x=xinput, y=yinput, z=zinput)

xnew = np.arange(min(x), max(x) + 0.5, 1)
ynew = np.arange(min(heights), max(heights), 1)

# znew = f(xnew, ynew)
znew = np.zeros((len(ynew), len(xnew)))

# evaluate interpolation function on new grid
j = 0
i = 0
for y in ynew:
    for x in xnew:
        znew[i, j] = f.ev(x, y)
        j += 1
    i += 1
    j = 0

plt.imshow(znew, interpolation='hamming', origin='lower')
#
plt.colorbar()
plt.title('Plasma Potential')
plt.xlabel('Angle')
plt.ylabel('Distance from target (mm)')
plt.show()
Exemplo n.º 12
0
# #
plt.axis('off')
fig.tight_layout()
plt.savefig('fit.pdf', transparent=True)

# plt.xlabel('Turbine Rating')
# plt.ylabel('Rotor Diameter')
# plt.title('Blade Mass')

#
# #
# # fig, ax = plt.subplots(nrows=1, ncols=2, subplot_kw={'projection': '3d'})
# # ax[0].plot_wireframe(X, Y, Z_Vrated, color='k')
# #
# # ax[1].plot_wireframe(X, Y, Z_smooth_Vrated, color='k')
# #
# # # for axes in ax:
# # #     # axes.set_zlim(-0.2,1)
# # #     axes.set_axis_off()
# #
# # fig.tight_layout()
# # plt.xlabel('Turbine Rating')
# # plt.ylabel('Rotor Diameter')
print len(w)
plt.show()

print interp_spline_blade_mass.get_coeffs()
print interp_spline_blade_mass.ev(0.5, 0.5, dx=0, dy=1)
print interp_spline_blade_mass.ev(0.5, 0.5, dx=1, dy=0)
print interp_spline_blade_mass.ev(0.5, 0.5, dx=1, dy=1)
Exemplo n.º 13
0
def implement_deform_timestep(sim, cells, t, p):
    """
    Implements the deformation of the tissue cluster based on divergence-free deformation
    calculated for cell centres.

    """
    # create a smooth bivariate spline to interpolate deformation data from cells:
    cellinterp_x = SmoothBivariateSpline(cells.cell_centres[:, 0],
                                         cells.cell_centres[:, 1],
                                         sim.d_cells_x,
                                         kx=4,
                                         ky=4)
    cellinterp_y = SmoothBivariateSpline(cells.cell_centres[:, 0],
                                         cells.cell_centres[:, 1],
                                         sim.d_cells_y,
                                         kx=4,
                                         ky=4)

    # calculate deformations wrt the ecm using the smooth bivariate spline:
    dxv = cellinterp_x.ev(cells.mem_verts[:, 0], cells.mem_verts[:, 1])
    dyv = cellinterp_y.ev(cells.mem_verts[:, 0], cells.mem_verts[:, 1])

    xv2 = cells.mem_verts[:, 0] + dxv
    yv2 = cells.mem_verts[:, 1] + dyv

    # calculate new cell centres:
    cell_cent_x = np.dot(cells.M_sum_mems, xv2 * cells.mem_sa) / cells.cell_sa
    cell_cent_y = np.dot(cells.M_sum_mems, yv2 * cells.mem_sa) / cells.cell_sa

    # smooth the vertices:
    # xv2 = sim.smooth_weight_mem*xv2 + cell_cent_x[cells.mem_to_cells]*sim.smooth_weight_o
    # yv2 = sim.smooth_weight_mem*yv2 + cell_cent_y[cells.mem_to_cells]*sim.smooth_weight_o

    # repackage the vertices:
    cell_verts2 = []

    for i, pts in enumerate(cells.cell_verts):
        vx = xv2[cells.cell_to_mems[i]]
        vy = yv2[cells.cell_to_mems[i]]

        pts2 = np.column_stack((vx, vy))
        cell_verts2.append(pts2)

    cells.cell_verts = np.asarray(cell_verts2)
    cells.cell_centres = np.column_stack((cell_cent_x, cell_cent_y))

    # # calculate deformations wrt the ecm using the smooth bivariate spline:
    # decm_x = cellinterp_x.ev(cells.ecm_verts_unique[:, 0], cells.ecm_verts_unique[:, 1])
    # decm_y = cellinterp_y.ev(cells.ecm_verts_unique[:, 0], cells.ecm_verts_unique[:, 1])
    #
    # # get the new ecm verts by applying the deformation:
    # ecm_x2 = cells.ecm_verts_unique[:, 0] + decm_x
    # ecm_y2 = cells.ecm_verts_unique[:, 1] + decm_y
    #
    # ecm_new = np.column_stack((ecm_x2, ecm_y2))
    #
    # # repackage new ecm vertices as cells.ecm_verts:
    # ecm_verts2 = []
    #
    # for inds in cells.inds2ecmVerts:
    #     ecm_verts2.append(ecm_new[inds])

    # cells.ecm_verts = np.asarray(ecm_verts2)

    # rebuild essential portions of the cell world:
    # cells.deformWorld(p, ecm_verts2)

    # write data to time-storage vectors:
    sim.cell_centres_time.append(cells.cell_centres[:])
    # sim.mem_mids_time.append(cells.mem_mids_flat[:])
    # sim.maskM_time.append(cells.maskM[:])
    # sim.mem_edges_time.append(cells.mem_edges_flat[:])
    sim.cell_verts_time.append(cells.cell_verts[:])
Exemplo n.º 14
0
DME, IELCON = ass.DME(IBC, ne, elements)
KG = ass.matassem(IBC, mats, elements, nn, ne, neq, COORD, DME, IELCON)

RHSG = ass.loadasem(loads, IBC, neq, nl)

#%% SYSTEM SOLUTION
UG = np.linalg.solve(KG, RHSG)
if not (np.allclose(np.dot(KG, UG), RHSG)):
    print("The system is not in equilibrium!")

#%% POST-PROCCESSING
UC = pos.complete_disp(IBC, nodes, UG)
pos.plot_disp(UC, nodes, elements)

UU = pos.scatter(DME, UG, ne, neq, elements)
x = nodes[:, 1]
y = nodes[:, 2]
E_gauss, pts_gauss = pos.strainGLO(IELCON, UU, ne, COORD, elements)
E_int1 = SmoothBivariateSpline(pts_gauss[:, 0], pts_gauss[:, 1], E_gauss[:, 0])
E_int2 = SmoothBivariateSpline(pts_gauss[:, 0], pts_gauss[:, 1], E_gauss[:, 1])
E_int3 = SmoothBivariateSpline(pts_gauss[:, 0], pts_gauss[:, 1], E_gauss[:, 2])
E1 = E_int1.ev(x, y)
E2 = E_int2.ev(x, y)
E3 = E_int3.ev(x, y)
E_nodes = np.column_stack([E1, E2, E3])
pos.plot_strain(E_nodes, nodes, elements, plt_type="pcolor")
tri = pos.mesh2tri(nodes, elements)
plt.triplot(tri, color='k', alpha=0.3)

plt.show()
Exemplo n.º 15
0
UG = np.linalg.solve(KG, RHSG)
if not(np.allclose(np.dot(KG, UG), RHSG)):
    print("The system is not in equilibrium!")



#%% POST-PROCCESSING
UC = pos.complete_disp(IBC, nodes, UG)
pos.plot_disp(UC, nodes, elements)

UU = pos.scatter(DME, UG, ne, neq, elements)
x = nodes[:, 1]
y = nodes[:, 2]
E_gauss, pts_gauss = pos.strainGLO(IELCON, UU, ne, COORD, elements)
E_int1 = SmoothBivariateSpline(pts_gauss[:, 0], pts_gauss[:, 1],
                               E_gauss[:, 0])
E_int2 = SmoothBivariateSpline(pts_gauss[:, 0], pts_gauss[:, 1],
                               E_gauss[:, 1])
E_int3 = SmoothBivariateSpline(pts_gauss[:, 0], pts_gauss[:, 1],
                               E_gauss[:, 2])
E1 = E_int1.ev(x, y)
E2 = E_int2.ev(x, y)
E3 = E_int3.ev(x, y)
E_nodes = np.column_stack([E1, E2, E3])
pos.plot_strain(E_nodes, nodes, elements, plt_type="pcolor")
tri = pos.mesh2tri(nodes, elements)
plt.triplot(tri, color='k', alpha=0.3)

plt.show()

Exemplo n.º 16
0
    print('Splines (with linear extrapolation) : {} s per call'.format((s-t)/10/n_v))
    print( 'Max error : {}'.format(abs(out-true_vals).max()) )
    print( 'Mean error : {}'.format(abs(out-true_vals).mean()) )




    if d == 2:

        print('')

        from scipy.interpolate import SmoothBivariateSpline
        grid_x = grid[0,:]
        grid_y = grid[1,:]

        values = mvs.values[0,:]

        bs = SmoothBivariateSpline(grid_x, grid_y, values)

        t = time.time()
        for i in range(10):
            out = bs.ev(points[0,:], points[1,:])
        s = time.time()
        print('Splines (smooth splines from scipy) : {} s per call'.format((s-t)/10))
        print( 'Max error : {}'.format(abs(out-true_vals).max()) )
        print( 'Mean error : {}'.format(abs(out-true_vals).mean()) )