def add_single_output(self,
                          target,
                          penalty=0.1,
                          basis=rbf.basis.phs2,
                          order=2):
        '''
		该函数是针对样本点y值是多维向量设计的,每次可以只添加y的一个维度,然后训练出针对该维度的专用RBF
		:param target:  目标值当前维度dim的向量, nx1, 其中n为训练样本点数目
		:param penalty:  惩罚系数0~1之间,如果惩罚系数越强,则多项式正则项的影响效果越强,如果p很大,则当
						当前的拟合网络退化成多项式回归
		:param basis:   选择当前RBF interpolant采用的RBF核函数类型
		:param order:   设置正则约束的多项式次数
		'''

        print(self.normalized_inputs.shape, target.shape)
        # 同样道理,需要对y输出值进行归一化处理
        #target_scaler = preprocessing.MinMaxScaler()
        target_scaler = preprocessing.StandardScaler()
        # 保证处理时的y向量是列向量,归一化是按照同列进行的
        target = target_scaler.fit_transform(target.reshape(-1, 1))

        net = RBFInterpolant(self.normalized_inputs,
                             target.reshape(-1),
                             penalty=penalty,
                             basis=basis,
                             order=order)

        self.rbf_nets.append((len(self.rbf_nets), target_scaler, net))
Beispiel #2
0
 def _get_acc_rbfi_(self, x, y, z):
     # returns the rbfi interpolator
     # using the user defined number of points, basis, and order
     dist, ids = self.grid._grid_evolved_kdtree_.query([x, y, z],
                                                       self.nclose)
     rbfi_x = RBFInterpolant(self.grid.evolved_grid[ids],
                             self.grid.evolved_acceleration_x[ids],
                             basis=self.basis,
                             order=self.order)
     rbfi_y = RBFInterpolant(self.grid.evolved_grid[ids],
                             self.grid.evolved_acceleration_y[ids],
                             basis=self.basis,
                             order=self.order)
     rbfi_z = RBFInterpolant(self.grid.evolved_grid[ids],
                             self.grid.evolved_acceleration_z[ids],
                             basis=self.basis,
                             order=self.order)
     return rbfi_x, rbfi_y, rbfi_z
Beispiel #3
0
 def _fit(self, X, F, data):
     #print(self.basis, self.order)
     self.model = RBFInterpolant(X,
                                 F,
                                 penalty=0.001,
                                 sigma=np.full(F.shape[0], 0.001),
                                 basis=self.basis,
                                 order=self.order)
     return self
Beispiel #4
0
    def _create_srf(self, obs_u, obs_v, xyz, **kwargs):

        # Create surface definitions
        u, v = np.meshgrid(obs_u, obs_v, indexing='ij')
        uv_obs = np.array([u.ravel(), v.ravel()]).T

        xsrf = RBFInterpolant(uv_obs, xyz[:, 0], **kwargs)
        ysrf = RBFInterpolant(uv_obs, xyz[:, 1], **kwargs)
        zsrf = RBFInterpolant(uv_obs, xyz[:, 2], **kwargs)

        usrf = RBFInterpolant(xyz, uv_obs[:, 0], **kwargs)
        vsrf = RBFInterpolant(xyz, uv_obs[:, 1], **kwargs)

        self._xsrf = xsrf
        self._ysrf = ysrf
        self._zsrf = zsrf
        self._usrf = usrf
        self._vsrf = vsrf
Beispiel #5
0
 def _get_pot_rbfi_(self, x, y, z):
     # returns the rbfi interpolator
     # using the user defined number of points, basis, and order
     dist, ids = self.grid._grid_evolved_kdtree_.query([x, y, z],
                                                       self.nclose)
     rbfi = RBFInterpolant(self.grid.evolved_grid[ids],
                           self.grid.evolved_potential[ids],
                           basis=self.basis,
                           order=self.order)
     return rbfi
Beispiel #6
0
def cross_validation(epsilon):
    groups = [range(i, len(y), k) for i in range(k)]
    error = 0.0
    for i in range(k):
        train = np.hstack([groups[j] for j in range(k) if j != i])
        test = groups[i]
        interp = RBFInterpolant(y[train],
                                d[train],
                                phi=phi,
                                order=degree,
                                eps=epsilon)
        error += ((interp(y[test]) - d[test])**2).sum()

    mse = error / len(y)
    return mse
Beispiel #7
0
    def _create_vol(self, obs_u, obs_v, obs_l, xyz, **kwargs):

        # Create volume definitions
        u, v, l = np.meshgrid(obs_u, obs_v, obs_l, indexing='ij')
        uvl_obs = np.array([u.ravel(), v.ravel(), l.ravel()]).T

        xvol = RBFInterpolant(uvl_obs, xyz[:, 0], **kwargs)
        yvol = RBFInterpolant(uvl_obs, xyz[:, 1], **kwargs)
        zvol = RBFInterpolant(uvl_obs, xyz[:, 2], **kwargs)

        uvol = RBFInterpolant(xyz, uvl_obs[:, 0], **kwargs)
        vvol = RBFInterpolant(xyz, uvl_obs[:, 1], **kwargs)
        lvol = RBFInterpolant(xyz, uvl_obs[:, 2], **kwargs)

        self._xvol = xvol
        self._yvol = yvol
        self._zvol = zvol
        self._uvol = uvol
        self._vvol = vvol
        self._lvol = lvol
Beispiel #8
0
    mse = error / len(y)
    return mse

# range of epsilon values to test
test_smoothings = 10**np.linspace(-4.0, 3.0, 1000)
mses = [cross_validation(s) for s in test_smoothings]

best_mse = np.min(mses)
best_smoothing = test_smoothings[np.argmin(mses)]
print('best smoothing parameter: %.2e (MSE=%.2e)' % (best_smoothing, best_mse))

interp = RBFInterpolant(
    y, d,
    phi=phi,
    order=degree,
    eps=epsilon,
    sigma=best_smoothing
    )

fig, ax = plt.subplots()
ax.loglog(test_smoothings, mses, 'k-')
ax.grid(ls=':', color='k')
ax.set_xlabel(r'$\lambda$')
ax.set_ylabel('cross validation MSE')
ax.plot(best_smoothing, best_mse, 'ko')
ax.text(
    best_smoothing,
    best_mse,
    '(%.2e, %.2e)' % (best_smoothing, best_mse),
    va='top'
Beispiel #9
0
    term4 = -0.2 * np.exp(-(9 * x1 - 4)**2 - (9 * x2 - 7)**2)
    y = term1 + term2 + term3 + term4
    return y


# the observations and their locations for interpolation
xobs = np.random.uniform(0.0, 1.0, (500, 2))
yobs = frankes_test_function(xobs)

# the locations where we evaluate the interpolants
xitp = np.mgrid[0:1:200j, 0:1:200j].reshape(2, -1).T

# the true function which we want the interpolants to reproduce
true_soln = frankes_test_function(xitp)

yitp = RBFInterpolant(xobs, yobs, phi='phs3', order=1)(xitp)

fig, ax = plt.subplots(1, 2, figsize=(9, 3.5))
ax[0].set_title('RBFInterpolant')
p = ax[0].tripcolor(xitp[:, 0], xitp[:, 1], yitp)
ax[0].scatter(xobs[:, 0], xobs[:, 1], c='k', s=3)
ax[0].set_xlim(0, 1)
ax[0].set_ylim(0, 1)
ax[0].set_aspect('equal')
ax[0].grid(ls=':', color='k')
fig.colorbar(p, ax=ax[0])
ax[1].set_title('|error|')
p = ax[1].tripcolor(xitp[:, 0], xitp[:, 1], np.abs(yitp - true_soln))
ax[1].set_xlim(0, 1)
ax[1].set_ylim(0, 1)
ax[1].set_aspect('equal')
Beispiel #10
0
phi_obs = np.random.uniform(0.0, np.pi, nobs)
# get the cartesian coordinates for the observation points
cart_obs = spherical_to_cartesian(theta_obs, phi_obs)
# get the latent function at the observation points
val_obs = true_function(theta_obs, phi_obs)
# make a grid of interpolation points in spherical coordinates
theta_itp, phi_itp = np.meshgrid(np.linspace(0.0, 2 * np.pi, 100),
                                 np.linspace(0.0, np.pi, 100))
theta_itp = theta_itp.flatten()
phi_itp = phi_itp.flatten()
# get the catesian coordinates for the interpolation points
cart_itp = spherical_to_cartesian(theta_itp, phi_itp)
# create an RBF interpolant from the cartesian observation points. I
# am just use the default `RBFInterpolant` parameters here, nothing
# special.
I = RBFInterpolant(cart_obs, val_obs)
# evaluate the interpolant on the interpolation points
val_itp = I(cart_itp)

## PLOTTING

# plot the true function in spherical coordinates
val_true = true_function(theta_itp, phi_itp)
plt.figure(1)
plt.title('True function')
p = plt.tripcolor(theta_itp, phi_itp, val_true, cmap='viridis')
plt.colorbar(p)
plt.xlabel('theta (azimuthal angle)')
plt.ylabel('phi (polar angle)')
plt.xlim(0, 2 * np.pi)
plt.ylim(0, np.pi)
Beispiel #11
0
#!/usr/bin/env python
# This script demonstrates how to use RBFs for 2-D interpolation
import numpy as np
from rbf.interpolate import RBFInterpolant
import matplotlib.pyplot as plt
np.random.seed(1)

# create noisy data
x_obs = np.random.random((100, 2))  # observation points
u_obs = np.sin(2 * np.pi * x_obs[:, 0]) * np.cos(2 * np.pi * x_obs[:, 1])
u_obs += np.random.normal(0.0, 0.2, 100)

# create smoothed interpolant
I = RBFInterpolant(x_obs, u_obs, penalty=0.001)

# create interpolation points
x_itp = np.random.random((10000, 2))
u_itp = I(x_itp)

plt.tripcolor(x_itp[:, 0], x_itp[:, 1], u_itp, vmin=-1.1, vmax=1.1)
plt.scatter(x_obs[:, 0], x_obs[:, 1], s=100, c=u_obs, vmin=-1.1, vmax=1.1)
plt.xlim((0.05, 0.95))
plt.ylim((0.05, 0.95))
plt.colorbar()
plt.tight_layout()
plt.show()
Beispiel #12
0
Aitp = rbf.basis.phs3(xitp, x)

# evaluate the interpolant at the interpolation points
uitp1 = Aitp.dot(coeff)

### METHOD 2, use RBFInterpolant ###
from rbf.interpolate import RBFInterpolant

# This command will produce an identical interpolant to the one
# created above
# I = RBFInterpolant(x,u,basis=phs3,order=-1)

# The default values for basis and order are phs3 and 0, where the
# latter means that a constant term is added to the interpolation
# function. This tends to produce much better results
I = RBFInterpolant(x, u)
uitp2 = I(xitp)

# plot the results
fig, ax = plt.subplots(figsize=(6, 4))
ax.plot(x[:, 0], u, 'ko')
ax.plot(xitp[:, 0], uitp1, 'r-')
ax.plot(xitp[:, 0], uitp2, 'b-')
ax.plot(xitp[:, 0], np.sin(xitp[:, 0]), 'k--')
ax.legend([
    'observation points', 'interpolant, order=-1', 'interpolant, order=1',
    'true solution'
],
          loc=2,
          frameon=False)
fig.tight_layout()
Beispiel #13
0
''' 
In this example we generate synthetic scattered data with added noise 
and then fit it with a smoothed interpolant. See rbf.filter for 
smoothing large data sets.
'''
import numpy as np
from rbf.interpolate import RBFInterpolant
import matplotlib.pyplot as plt
np.random.seed(1)

x_obs = np.random.random((100, 2))  # observation points
u_obs = np.sin(2 * np.pi * x_obs[:, 0]) * np.cos(
    2 * np.pi * x_obs[:, 1])  # signal
u_obs += np.random.normal(0.0, 0.2, 100)  # add noise to signal
I = RBFInterpolant(x_obs, u_obs, penalty=0.001)  # instantiate Interpolant
vals = np.linspace(0, 1, 200)
x_itp = np.reshape(np.meshgrid(vals, vals), (2, 200 * 200)).T  # interp points
u_itp = I(x_itp)  # evaluate the interpolant

# plot the results
plt.tripcolor(x_itp[:, 0],
              x_itp[:, 1],
              u_itp,
              vmin=-1.1,
              vmax=1.1,
              cmap='viridis')
plt.scatter(x_obs[:, 0],
            x_obs[:, 1],
            s=100,
            c=u_obs,
            vmin=-1.1,
Beispiel #14
0
if 'viridis' in vars(cm):
    plt.rcParams['image.cmap'] = 'viridis'

np.random.seed(1)

# create 20 2-D observation points
x = np.random.random((100, 2))
# find the function value at the observation points
u = np.sin(2 * np.pi * x[:, 0]) * np.cos(2 * np.pi * x[:, 1])
u += np.random.normal(0.0, 0.1, 100)
# create interpolation points
a = np.linspace(0, 1, 100)
x1itp, x2itp = np.meshgrid(a, a)
xitp = np.array([x1itp.ravel(), x2itp.ravel()]).T
# form interpolant
I = RBFInterpolant(x, u, penalty=0.001)
# evaluate the interpolant
uitp = I(xitp)
# evaluate the x derivative of the interpolant
dxitp = I(xitp, diff=(1, 0))

# find the true values
utrue = np.sin(2 * np.pi * xitp[:, 0]) * np.cos(2 * np.pi * xitp[:, 1])
dxtrue = 2 * np.pi * np.cos(2 * np.pi * xitp[:, 0]) * np.cos(
    2 * np.pi * xitp[:, 1])

# plot the results
fig, ax = plt.subplots(2, 2)
p = ax[0, 0].tripcolor(xitp[:, 0], xitp[:, 1], uitp)
ax[0, 0].scatter(x[:, 0], x[:, 1], c=u, s=100, clim=p.get_clim())
fig.colorbar(p, ax=ax[0, 0])
Beispiel #15
0
this example is equivalent to a thin plate spline.
'''
import numpy as np
from rbf.interpolate import RBFInterpolant
import rbf.basis
import matplotlib.pyplot as plt
np.random.seed(1)

basis = rbf.basis.phs2
order = 1

x_obs = np.random.random((100, 2))  # observation points
u_obs = np.sin(2 * np.pi * x_obs[:, 0]) * np.cos(
    2 * np.pi * x_obs[:, 1])  # signal
u_obs += np.random.normal(0.0, 0.2, 100)  # add noise to signal
I = RBFInterpolant(x_obs, u_obs, sigma=0.1, basis=basis, order=order)
vals = np.linspace(0, 1, 200)
x_itp = np.reshape(np.meshgrid(vals, vals), (2, 200 * 200)).T  # interp points
u_itp = I(x_itp)  # evaluate the interpolant
# plot the results
plt.tripcolor(x_itp[:, 0],
              x_itp[:, 1],
              u_itp,
              vmin=-1.1,
              vmax=1.1,
              cmap='viridis')
plt.scatter(x_obs[:, 0],
            x_obs[:, 1],
            s=100,
            c=u_obs,
            vmin=-1.1,
Beispiel #16
0
and then fit it with a smoothed RBF interpolant. The interpolant in
this example is equivalent to a thin plate spline.
'''
import numpy as np
from rbf.interpolate import RBFInterpolant
import rbf.basis
import matplotlib.pyplot as plt
np.random.seed(1)

basis = rbf.basis.phs2
order = 1

x_obs = np.random.random((100,2)) # observation points
u_obs = np.sin(2*np.pi*x_obs[:,0])*np.cos(2*np.pi*x_obs[:,1]) # signal
u_obs += np.random.normal(0.0,0.2,100) # add noise to signal
I = RBFInterpolant(x_obs,u_obs,penalty=0.1,basis=basis,order=order)
vals = np.linspace(0,1,200)
x_itp = np.reshape(np.meshgrid(vals,vals),(2,200*200)).T # interp points
u_itp = I(x_itp) # evaluate the interpolant
# plot the results
plt.tripcolor(x_itp[:,0],x_itp[:,1],u_itp,vmin=-1.1,vmax=1.1,cmap='viridis')
plt.scatter(x_obs[:,0],x_obs[:,1],s=100,c=u_obs,vmin=-1.1,vmax=1.1,
            cmap='viridis',edgecolor='k')
plt.xlim((0.05,0.95))
plt.ylim((0.05,0.95))
plt.colorbar()
plt.tight_layout()
plt.savefig('../figures/interpolate.a.png')
plt.show()

Beispiel #17
0
print('obs_v size: %s' % str(obs_v.size))
obs_l = np.linspace(0., 1., num=10)

u, v, l = np.meshgrid(obs_u, obs_v, obs_l, indexing='ij')
xyz = test_surface(u, v, l).reshape(3, u.size)
uvl_obs = np.array([u.ravel(), v.ravel(), l.ravel()]).T

print('u shape: %s' % str(u.shape))
print('xyz shape: %s' % str(xyz.shape))
print('uvl_obs shape: %s' % str(uvl_obs.shape))

basis = rbf.basis.phs2
order = 1

print('creating xsrf...')
xsrf = RBFInterpolant(uvl_obs, xyz[0], penalty=0.1, basis=basis, order=order)
print('creating ysrf...')
ysrf = RBFInterpolant(uvl_obs, xyz[1], penalty=0.1, basis=basis, order=order)
print('creating zsrf...')
zsrf = RBFInterpolant(uvl_obs, xyz[2], penalty=0.1, basis=basis, order=order)

spatial_resolution = 25.  # um
du = old_div((1.01 * np.pi - (-0.016 * np.pi)), max_u * spatial_resolution)
dv = old_div((1.425 * np.pi - (-0.23 * np.pi)), max_v * spatial_resolution)
su = np.arange(-0.016 * np.pi, 1.01 * np.pi, du)
sv = np.arange(-0.23 * np.pi, 1.425 * np.pi, dv)
sl = np.linspace(0., 1., num=10)

u, v, l = np.meshgrid(su, sv, sl)
uvl_s = np.array([u.ravel(), v.ravel(), l.ravel()]).T
Beispiel #18
0
def make_distance_interpolant(comm,
                              geometry_config,
                              make_volume,
                              resolution=[30, 30, 10],
                              nsample=1000):
    from rbf.interpolate import RBFInterpolant

    rank = comm.rank

    layer_extents = geometry_config['Parametric Surface']['Layer Extents']
    (extent_u, extent_v, extent_l) = get_total_extents(layer_extents)

    rotate = geometry_config['Parametric Surface']['Rotation']
    origin = geometry_config['Parametric Surface']['Origin']

    min_u, max_u = extent_u
    min_v, max_v = extent_v
    min_l, max_l = extent_l

    ## This parameter is used to expand the range of L and avoid
    ## situations where the endpoints of L end up outside of the range
    ## of the distance interpolant
    safety = 0.01

    ip_volume = None
    if rank == 0:
        logger.info('Creating volume: min_l = %f max_l = %f...' %
                    (min_l, max_l))
        ip_volume = make_volume((min_u - safety, max_u + safety), \
                                (min_v - safety, max_v + safety), \
                                (min_l - safety, max_l + safety), \
                                resolution=resolution, rotate=rotate)

    ip_volume = comm.bcast(ip_volume, root=0)

    interp_sigma = 0.01
    interp_basis = rbf.basis.ga
    interp_order = 1

    if rank == 0:
        logger.info('Computing reference distances...')

    vol_dist = get_volume_distances(ip_volume,
                                    origin_spec=origin,
                                    nsample=nsample,
                                    comm=comm)
    (origin_ranges, obs_uvl, dist_u, dist_v) = vol_dist

    if rank == 0:
        logger.info('Done computing reference distances...')

    sendcounts = np.array(comm.gather(len(obs_uvl), root=0))
    displs = np.concatenate([np.asarray([0]), np.cumsum(sendcounts)[:-1]])

    obs_uvs = None
    dist_us = None
    dist_vs = None
    if rank == 0:
        obs_uvs = np.zeros((np.sum(sendcounts), 3), dtype=np.float32)
        dist_us = np.zeros(np.sum(sendcounts), dtype=np.float32)
        dist_vs = np.zeros(np.sum(sendcounts), dtype=np.float32)

    uvl_datatype = MPI.FLOAT.Create_contiguous(3).Commit()
    comm.Gatherv(sendbuf=obs_uvl,
                 recvbuf=(obs_uvs, sendcounts, displs, uvl_datatype),
                 root=0)
    uvl_datatype.Free()
    comm.Gatherv(sendbuf=dist_u,
                 recvbuf=(dist_us, sendcounts, displs, MPI.FLOAT),
                 root=0)
    comm.Gatherv(sendbuf=dist_v,
                 recvbuf=(dist_vs, sendcounts, displs, MPI.FLOAT),
                 root=0)

    ip_dist_u = None
    ip_dist_v = None
    if rank == 0:
        logger.info('Computing U volume distance interpolants...')
        ip_dist_u = RBFInterpolant(obs_uvs, dist_us, order=interp_order, phi=interp_basis, \
                                   sigma=interp_sigma)
        logger.info('Computing V volume distance interpolants...')
        ip_dist_v = RBFInterpolant(obs_uvs, dist_vs, order=interp_order, phi=interp_basis, \
                                   sigma=interp_sigma)

    origin_ranges = comm.bcast(origin_ranges, root=0)
    ip_dist_u = comm.bcast(ip_dist_u, root=0)
    ip_dist_v = comm.bcast(ip_dist_v, root=0)

    return origin_ranges, ip_dist_u, ip_dist_v
Beispiel #19
0
                                eps=epsilon)
        error += ((interp(y[test]) - d[test])**2).sum()

    mse = error / len(y)
    return mse


# range of epsilon values to test
test_epsilons = 10**np.linspace(-0.5, 2.5, 1000)
mses = [cross_validation(eps) for eps in test_epsilons]

best_mse = np.min(mses)
best_epsilon = test_epsilons[np.argmin(mses)]
print('best epsilon: %.2e (MSE=%.2e)' % (best_epsilon, best_mse))

interp = RBFInterpolant(y, d, phi=phi, order=degree, eps=best_epsilon)

fig, ax = plt.subplots()
ax.loglog(test_epsilons, mses, 'k-')
ax.grid(ls=':', color='k')
ax.set_xlabel(r'$\epsilon$')
ax.set_ylabel('cross validation MSE')
ax.plot(best_epsilon, best_mse, 'ko')
ax.text(best_epsilon,
        best_mse,
        '(%.2e, %.2e)' % (best_epsilon, best_mse),
        va='top')
fig.tight_layout()

fig, axs = plt.subplots(2, 1, figsize=(6, 8))
p = axs[0].tripcolor(x[:, 0], x[:, 1], interp(x))