Esempio n. 1
0
def griddata(points, values, xi, method='linear', fill_value=np.nan, tol = 1e-6):
    """modified griddata plus tol arg"""
    points = _ndim_coords_from_arrays(points)

    if points.ndim < 2:
        ndim = points.ndim
    else:
        ndim = points.shape[-1]

    if ndim == 1 and method in ('nearest', 'linear', 'cubic'):
        from interpolate import interp1d
        points = points.ravel()
        if isinstance(xi, tuple):
            if len(xi) != 1:
                raise ValueError("invalid number of dimensions in xi")
            xi, = xi
        # Sort points/values together, necessary as input for interp1d
        idx = np.argsort(points)
        points = points[idx]
        values = values[idx]
        ip = interp1d(points, values, kind=method, axis=0, bounds_error=False,
                      fill_value=fill_value)
        return ip(xi)
    elif method == 'nearest':
        ip = NearestNDInterpolator(points, values)
        return ip(xi)
    elif method == 'linear':
        ip = LinearNDInterpolator(points, values, fill_value=fill_value)
        return ip(xi)
    elif method == 'cubic' and ndim == 2:
        ip = CloughTocher2DInterpolator(points, values, fill_value=fill_value, tol = tol)
        return ip(xi)
    else:
        raise ValueError("Unknown interpolation method %r for "
                         "%d dimensional data" % (method, ndim))
Esempio n. 2
0
    def __init__(self, name='nport1', nodes=('1', '0', '2', '0'), file="", freq=None):
	self.name = name
        self.nodes = nodes
	self.file = file
	self.data = touchstone.snp(self.file).read()
	x = []
        if freq:
	    for i in xrange(len(nodes)/2):
                row = []
                for j in xrange(len(nodes)/2):
	            freqs = self.data['freq']
		    sij = self.data['s%d%d'%(i+1,j+1)]
		    xsij = interp1d(freqs, sij)(freq)
	            row.append( xsij )
	        x.append(row)
        else:
 	    for i in xrange(len(nodes)/2):
                row = []
                for j in xrange(len(nodes)/2):
	            row.append( self.data['s%d%d'%(i+1,j+1)][0] )
                    freq = self.data['freq'][0]
	        x.append(row)
          
	self._ivcvs = []
	n1 = [newnode() for i in xrange(len(nodes)/2)]
	for i in xrange(len(nodes)/2):
	    self.append( Resistor(name=newname('r'), nodes=(nodes[i*2], n1[i]), r=-50) )	
	    n2 = [newnode() for _i in xrange(len(nodes)/2)] + [nodes[1]]
	    self.append( Resistor(name=newname('r'), nodes=(n1[i], n2[0]), r=100) )
	    for j in xrange(len(nodes)/2):
	        self.append( VCVSx(nodes=(n2[j], n2[j+1], n1[j], nodes[-1]), gain=x[i][j], freq=freq) )
		self._ivcvs.append( len(self)-1 )
Esempio n. 3
0
    def test_nd(self):
        """ Check the behavior when the inputs and outputs are multidimensional.
        """

        # Multidimensional input.
        interp10 = interp1d(self.x10, self.y10)
        assert_array_almost_equal(
            interp10(np.array([[3.4, 5.6], [2.4, 7.8]])),
            np.array([[3.4, 5.6], [2.4, 7.8]]),
        )

        # Multidimensional outputs.
        interp210 = interp1d(self.x10, self.y210)
        assert_array_almost_equal(
            interp210(1.5),
            np.array([[1.5], [11.5]]),
        )
        assert_array_almost_equal(
            interp210(np.array([1.5, 2.4])),
            np.array([[1.5, 2.4],
                      [11.5, 12.4]]),
        )
        
        interp102 = interp1d(self.x10, self.y102, axis=0)
        assert_array_almost_equal(
            interp102(1.5),
            np.array([[3.0, 4.0]]),
        )
        assert_array_almost_equal(
            interp102(np.array([1.5, 2.4])),
            np.array([[3.0, 4.0],
                      [4.8, 5.8]]),
        )

        # Both at the same time!
        x_new = np.array([[3.4, 5.6], [2.4, 7.8]])
        assert_array_almost_equal(
            interp210(x_new),
            np.array([[[3.4, 5.6], [2.4, 7.8]],
                      [[13.4, 15.6], [12.4, 17.8]]]),
        )
        assert_array_almost_equal(
            interp102(x_new),
            np.array([[[6.8, 7.8], [11.2, 12.2]],
                      [[4.8, 5.8], [15.6, 16.6]]]),
        )
Esempio n. 4
0
 def update_figure(self):
     x = np.linspace(0, 10, 10)
     y = [random.randint(0, 10) for i in range(10)]
     xx = np.linspace(0, 10)
     f = interpolate.interp1d(x, y, 'quadratic')  # 产生插值曲线的函数
     yy = f(xx)
     self.axes.cla()
     self.axes.plot(x, y, 'o',xx,yy)
     self.draw()
Esempio n. 5
0
    def alter(self, freq):
	y = []
        n = len(self.nodes)/2
        freqs = self.data['freq']
	for i in xrange(n):
	    for j in xrange(n):
		sij = self.data['s%d%d'%(i+1,j+1)]
		xsij = interp1d(freqs, sij)(freq)
	        y.append( xsij )
        netlist = Netlist()
        for k, yi in zip(self._ivcvs, y):
	    netlist.extend( self[k].alter(yi, freq) )
        return netlist
Esempio n. 6
0
 def alter(self, freq):
     y = []
     n = len(self.nodes) / 2
     freqs = self.data['freq']
     for i in xrange(n):
         for j in xrange(n):
             sij = self.data['s%d%d' % (i + 1, j + 1)]
             xsij = interp1d(freqs, sij)(freq)
             y.append(xsij)
     netlist = Netlist()
     for k, yi in zip(self._ivcvs, y):
         netlist.extend(self[k].alter(yi, freq))
     return netlist
Esempio n. 7
0
    def test_bounds(self):
        """ Test that our handling of out-of-bounds input is correct.
        """

        extrap10 = interp1d(self.x10, self.y10, fill_value=self.fill_value,
            bounds_error=False)
        assert_array_equal(
            extrap10(11.2),
            np.array([self.fill_value]),
        )
        assert_array_equal(
            extrap10(-3.4),
            np.array([self.fill_value]),
        )
        assert_array_equal(
            extrap10._check_bounds(np.array([-1.0, 0.0, 5.0, 9.0, 11.0])),
            np.array([True, False, False, False, True]),
        )

        raises_bounds_error = interp1d(self.x10, self.y10, bounds_error=True)
        self.assertRaises(ValueError, raises_bounds_error, -1.0)
        self.assertRaises(ValueError, raises_bounds_error, 11.0)
        raises_bounds_error([0.0, 5.0, 9.0])
Esempio n. 8
0
 def alter(self, freq):
     x = []
     for i in xrange(len(self.nodes) / 2):
         row = []
         for j in xrange(len(self.nodes) / 2):
             freqs = self.data['freq']
             sij = self.data['s%d%d' % (i + 1, j + 1)]
             xsij = interp1d(freqs, sij)(freq)
             row.append(xsij)
         x.append(row)
     y = list(flatten(x))
     netlist = Netlist()
     for i, k in enumerate(self._ivcvs):
         netlist.append(self[k].alter(y[i], freq))
     return netlist
Esempio n. 9
0
    def alter(self, freq):
	x = []
	for i in xrange(len(self.nodes)/2):
	    row = []
	    for j in xrange(len(self.nodes)/2):
	        freqs = self.data['freq']
		sij = self.data['s%d%d'%(i+1,j+1)]
		xsij = interp1d(freqs, sij)(freq)
	        row.append( xsij )
	    x.append(row)
        y = list(flatten(x))
        netlist = Netlist()
        for i, k in enumerate(self._ivcvs):
	    netlist.append( self[k].alter(y[i], freq) )
        return netlist
Esempio n. 10
0
    def test_linear(self):
        """ Check the actual implementation of linear interpolation.
        """

        interp10 = interp1d(self.x10, self.y10)
        assert_array_almost_equal(
            interp10(self.x10),
            self.y10,
        )
        assert_array_almost_equal(
            interp10(1.2),
            np.array([1.2]),
        )
        assert_array_almost_equal(
            interp10([2.4, 5.6, 6.0]),
            np.array([2.4, 5.6, 6.0]),
        )
Esempio n. 11
0
def griddata(points, values, xi, method='linear', fill_value=np.nan, tol=1e-6):
    """modified griddata plus tol arg"""
    points = _ndim_coords_from_arrays(points)

    if points.ndim < 2:
        ndim = points.ndim
    else:
        ndim = points.shape[-1]

    if ndim == 1 and method in ('nearest', 'linear', 'cubic'):
        from interpolate import interp1d
        points = points.ravel()
        if isinstance(xi, tuple):
            if len(xi) != 1:
                raise ValueError("invalid number of dimensions in xi")
            xi, = xi
        # Sort points/values together, necessary as input for interp1d
        idx = np.argsort(points)
        points = points[idx]
        values = values[idx]
        ip = interp1d(points,
                      values,
                      kind=method,
                      axis=0,
                      bounds_error=False,
                      fill_value=fill_value)
        return ip(xi)
    elif method == 'nearest':
        ip = NearestNDInterpolator(points, values)
        return ip(xi)
    elif method == 'linear':
        ip = LinearNDInterpolator(points, values, fill_value=fill_value)
        return ip(xi)
    elif method == 'cubic' and ndim == 2:
        ip = CloughTocher2DInterpolator(points,
                                        values,
                                        fill_value=fill_value,
                                        tol=tol)
        return ip(xi)
    else:
        raise ValueError("Unknown interpolation method %r for "
                         "%d dimensional data" % (method, ndim))
Esempio n. 12
0
    def __init__(self,
                 name='nport1',
                 nodes=('1', '0', '2', '0'),
                 file="",
                 freq=None):
        self.name = name
        self.nodes = nodes
        self.file = file
        self.data = touchstone.snp(self.file).read()
        x = []
        if freq:
            for i in xrange(len(nodes) / 2):
                row = []
                for j in xrange(len(nodes) / 2):
                    freqs = self.data['freq']
                    sij = self.data['s%d%d' % (i + 1, j + 1)]
                    xsij = interp1d(freqs, sij)(freq)
                    row.append(xsij)
                x.append(row)
        else:
            for i in xrange(len(nodes) / 2):
                row = []
                for j in xrange(len(nodes) / 2):
                    row.append(self.data['s%d%d' % (i + 1, j + 1)][0])
                    freq = self.data['freq'][0]
                x.append(row)

        self._ivcvs = []
        n1 = [newnode() for i in xrange(len(nodes) / 2)]
        for i in xrange(len(nodes) / 2):
            self.append(
                Resistor(name=newname('r'), nodes=(nodes[i * 2], n1[i]),
                         r=-50))
            n2 = [newnode() for _i in xrange(len(nodes) / 2)] + [nodes[1]]
            self.append(
                Resistor(name=newname('r'), nodes=(n1[i], n2[0]), r=100))
            for j in xrange(len(nodes) / 2):
                self.append(
                    VCVSx(nodes=(n2[j], n2[j + 1], n1[j], nodes[-1]),
                          gain=x[i][j],
                          freq=freq))
                self._ivcvs.append(len(self) - 1)
Esempio n. 13
0
def griddata(points, values, xi, method='linear', fill_value=np.nan):
    """
    Interpolate unstructured N-dimensional data.

    .. versionadded:: 0.9

    Parameters
    ----------
    points : ndarray of floats, shape (npoints, ndims)
        Data point coordinates. Can either be a ndarray of
        size (npoints, ndim), or a tuple of `ndim` arrays.
    values : ndarray of float or complex, shape (npoints, ...)
        Data values.
    xi : ndarray of float, shape (..., ndim)
        Points where to interpolate data at.

    method : {'linear', 'nearest', 'cubic'}, optional
        Method of interpolation. One of

        - ``nearest``: return the value at the data point closest to
          the point of interpolation.  See `NearestNDInterpolator` for
          more details.

        - ``linear``: tesselate the input point set to n-dimensional
          simplices, and interpolate linearly on each simplex.  See
          `LinearNDInterpolator` for more details.

        - ``cubic`` (1-D): return the value detemined from a cubic
          spline.

        - ``cubic`` (2-D): return the value determined from a
          piecewise cubic, continuously differentiable (C1), and
          approximately curvature-minimizing polynomial surface. See
          `CloughTocher2DInterpolator` for more details.

    fill_value : float, optional
        Value used to fill in for requested points outside of the
        convex hull of the input points.  If not provided, then the
        default is ``nan``. This option has no effect for the
        'nearest' method.


    Examples
    --------

    Suppose we want to interpolate the 2-D function

    >>> def func(x, y):
    >>>     return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2

    on a grid in [0, 1]x[0, 1]

    >>> grid_x, grid_y = np.mgrid[0:1:100j, 0:1:200j]

    but we only know its values at 1000 data points:

    >>> points = np.random.rand(1000, 2)
    >>> values = func(points[:,0], points[:,1])

    This can be done with `griddata` -- below we try out all of the
    interpolation methods:

    >>> from scipy.interpolate import griddata
    >>> grid_z0 = griddata(points, values, (grid_x, grid_y), method='nearest')
    >>> grid_z1 = griddata(points, values, (grid_x, grid_y), method='linear')
    >>> grid_z2 = griddata(points, values, (grid_x, grid_y), method='cubic')

    One can see that the exact result is reproduced by all of the
    methods to some degree, but for this smooth function the piecewise
    cubic interpolant gives the best results:

    >>> import matplotlib.pyplot as plt
    >>> plt.subplot(221)
    >>> plt.imshow(func(grid_x, grid_y).T, extent=(0,1,0,1), origin='lower')
    >>> plt.plot(points[:,0], points[:,1], 'k.', ms=1)
    >>> plt.title('Original')
    >>> plt.subplot(222)
    >>> plt.imshow(grid_z0.T, extent=(0,1,0,1), origin='lower')
    >>> plt.title('Nearest')
    >>> plt.subplot(223)
    >>> plt.imshow(grid_z1.T, extent=(0,1,0,1), origin='lower')
    >>> plt.title('Linear')
    >>> plt.subplot(224)
    >>> plt.imshow(grid_z2.T, extent=(0,1,0,1), origin='lower')
    >>> plt.title('Cubic')
    >>> plt.gcf().set_size_inches(6, 6)
    >>> plt.show()

    """

    points = _ndim_coords_from_arrays(points)

    if points.ndim < 2:
        ndim = points.ndim
    else:
        ndim = points.shape[-1]

    if ndim == 1 and method in ('nearest', 'linear', 'cubic'):
        from interpolate import interp1d
        points = points.ravel()
        if isinstance(xi, tuple):
            if len(xi) != 1:
                raise ValueError("invalid number of dimensions in xi")
            xi, = xi
        # Sort points/values together, necessary as input for interp1d
        idx = np.argsort(points)
        points = points[idx]
        values = values[idx]
        ip = interp1d(points,
                      values,
                      kind=method,
                      axis=0,
                      bounds_error=False,
                      fill_value=fill_value)
        return ip(xi)
    elif method == 'nearest':
        ip = NearestNDInterpolator(points, values)
        return ip(xi)
    elif method == 'linear':
        ip = LinearNDInterpolator(points, values, fill_value=fill_value)
        return ip(xi)
    elif method == 'cubic' and ndim == 2:
        ip = CloughTocher2DInterpolator(points, values, fill_value=fill_value)
        return ip(xi)
    else:
        raise ValueError("Unknown interpolation method %r for "
                         "%d dimensional data" % (method, ndim))
Esempio n. 14
0
def griddata(points, values, xi, method='linear', fill_value=np.nan):
    """
    Interpolate unstructured N-dimensional data.

    .. versionadded:: 0.9

    Parameters
    ----------
    points : ndarray of floats, shape (npoints, ndims)
        Data point coordinates. Can either be a ndarray of
        size (npoints, ndim), or a tuple of `ndim` arrays.
    values : ndarray of float or complex, shape (npoints, ...)
        Data values.
    xi : ndarray of float, shape (..., ndim)
        Points where to interpolate data at.

    method : {'linear', 'nearest', 'cubic'}, optional
        Method of interpolation. One of

        - ``nearest``: return the value at the data point closest to
          the point of interpolation.  See `NearestNDInterpolator` for
          more details.

        - ``linear``: tesselate the input point set to n-dimensional
          simplices, and interpolate linearly on each simplex.  See
          `LinearNDInterpolator` for more details.

        - ``cubic`` (1-D): return the value determined from a cubic
          spline.

        - ``cubic`` (2-D): return the value determined from a
          piecewise cubic, continuously differentiable (C1), and
          approximately curvature-minimizing polynomial surface. See
          `CloughTocher2DInterpolator` for more details.

    fill_value : float, optional
        Value used to fill in for requested points outside of the
        convex hull of the input points.  If not provided, then the
        default is ``nan``. This option has no effect for the
        'nearest' method.


    Examples
    --------

    Suppose we want to interpolate the 2-D function

    >>> def func(x, y):
    >>>     return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2

    on a grid in [0, 1]x[0, 1]

    >>> grid_x, grid_y = np.mgrid[0:1:100j, 0:1:200j]

    but we only know its values at 1000 data points:

    >>> points = np.random.rand(1000, 2)
    >>> values = func(points[:,0], points[:,1])

    This can be done with `griddata` -- below we try out all of the
    interpolation methods:

    >>> from scipy.interpolate import griddata
    >>> grid_z0 = griddata(points, values, (grid_x, grid_y), method='nearest')
    >>> grid_z1 = griddata(points, values, (grid_x, grid_y), method='linear')
    >>> grid_z2 = griddata(points, values, (grid_x, grid_y), method='cubic')

    One can see that the exact result is reproduced by all of the
    methods to some degree, but for this smooth function the piecewise
    cubic interpolant gives the best results:

    >>> import matplotlib.pyplot as plt
    >>> plt.subplot(221)
    >>> plt.imshow(func(grid_x, grid_y).T, extent=(0,1,0,1), origin='lower')
    >>> plt.plot(points[:,0], points[:,1], 'k.', ms=1)
    >>> plt.title('Original')
    >>> plt.subplot(222)
    >>> plt.imshow(grid_z0.T, extent=(0,1,0,1), origin='lower')
    >>> plt.title('Nearest')
    >>> plt.subplot(223)
    >>> plt.imshow(grid_z1.T, extent=(0,1,0,1), origin='lower')
    >>> plt.title('Linear')
    >>> plt.subplot(224)
    >>> plt.imshow(grid_z2.T, extent=(0,1,0,1), origin='lower')
    >>> plt.title('Cubic')
    >>> plt.gcf().set_size_inches(6, 6)
    >>> plt.show()

    """

    points = _ndim_coords_from_arrays(points)

    if points.ndim < 2:
        ndim = points.ndim
    else:
        ndim = points.shape[-1]

    if ndim == 1 and method in ('nearest', 'linear', 'cubic'):
        from interpolate import interp1d
        points = points.ravel()
        if isinstance(xi, tuple):
            if len(xi) != 1:
                raise ValueError("invalid number of dimensions in xi")
            xi, = xi
        # Sort points/values together, necessary as input for interp1d
        idx = np.argsort(points)
        points = points[idx]
        values = values[idx]
        ip = interp1d(points, values, kind=method, axis=0, bounds_error=False,
                      fill_value=fill_value)
        return ip(xi)
    elif method == 'nearest':
        ip = NearestNDInterpolator(points, values)
        return ip(xi)
    elif method == 'linear':
        ip = LinearNDInterpolator(points, values, fill_value=fill_value)
        return ip(xi)
    elif method == 'cubic' and ndim == 2:
        ip = CloughTocher2DInterpolator(points, values, fill_value=fill_value)
        return ip(xi)
    else:
        raise ValueError("Unknown interpolation method %r for "
                         "%d dimensional data" % (method, ndim))
Esempio n. 15
0
    def test_validation(self):
        """ Make sure that appropriate exceptions are raised when invalid values
        are given to the constructor.
        """

        # These should all work. 
        interp1d(self.x10, self.y10, kind='linear')
        interp1d(self.x10, self.y10, kind='cubic')
        interp1d(self.x10, self.y10, kind='slinear')
        interp1d(self.x10, self.y10, kind='quadratic')
        interp1d(self.x10, self.y10, kind='zero')
        interp1d(self.x10, self.y10, kind=0)
        interp1d(self.x10, self.y10, kind=1)
        interp1d(self.x10, self.y10, kind=2)
        interp1d(self.x10, self.y10, kind=3)                

        # x array must be 1D.
        self.assertRaises(ValueError, interp1d, self.x25, self.y10)

        # y array cannot be a scalar.
        self.assertRaises(ValueError, interp1d, self.x10, np.array(0))

        # Check for x and y arrays having the same length.
        self.assertRaises(ValueError, interp1d, self.x10, self.y2)
        self.assertRaises(ValueError, interp1d, self.x2, self.y10)
        self.assertRaises(ValueError, interp1d, self.x10, self.y102)
        interp1d(self.x10, self.y210)
        interp1d(self.x10, self.y102, axis=0)

        # Check for x and y having at least 1 element.
        self.assertRaises(ValueError, interp1d, self.x1, self.y10)
        self.assertRaises(ValueError, interp1d, self.x10, self.y1)
        self.assertRaises(ValueError, interp1d, self.x1, self.y1)
Esempio n. 16
0
tanData = op('tangents').rows()
resolution = op('res')[0]

points = [[float(x[0].val), float(x[1].val)] for x in posData]
tangents = [[float(x[0].val), float(x[1].val)] for x in tanData]
points = np.asarray(points)
tangents = np.asarray(tangents)

# Interpolate with different tangent lengths, but equal direction.
tangents = np.dot(tangents, np.eye(2))
samples = curve.sampleCubicSplinesWithDerivative(points, tangents, resolution)

# equispaced x
x = samples[:, 0]
y = samples[:, 1]
f = interpolate.interp1d(x, y)
x_new = np.linspace(np.min(x), np.max(x), x.shape[0])
y_new = f(x_new)

table = op('equispaced_x')
table.clear(keepFirstRow=True)
table.appendRows(y_new)

# original
"""
table = op('original')
table.clear(keepFirstRow = True)
table.appendRows(samples)
"""

# equispaced x and y
Esempio n. 17
0
    for ntest in range(ntests):
        # draw the data
        x = torch.rand(D, N, device='cuda') * 10000
        x = x.sort(dim=1)[0]

        y = torch.linspace(0, 1000, D * N).to('cuda').view(D, -1)
        y -= y[:, 0, None]

        xnew = torch.rand(Dnew, P, device='cuda') * 10000

        print('Solving %d interpolation problems: '
              'each with %d observations and %d desired values' % (D, N, P))

        # launching the cuda version
        t0 = time.time()
        yq_gpu = interp1d(x, y, xnew, yq_gpu, cuda=True)
        t1 = time.time()

        # putting everything back to CPU before calling the CPU version
        x = x.to('cpu')
        y = y.to('cpu')
        xnew = xnew.to('cpu')

        # calling the cpu version
        t0_cpu = time.time()
        yq_cpu = interp1d(x, y, xnew, yq_cpu, cuda=False)
        t1_cpu = time.time()

        # compute the difference between both
        error = torch.norm(yq_cpu -
                           yq_gpu.to('cpu')) / torch.norm(yq_cpu) * 100.
Esempio n. 18
0
    def test_init(self):
        """ Check that the attributes are initialized appropriately by the
        constructor.
        """

        self.assert_(interp1d(self.x10, self.y10).copy)
        self.assert_(not interp1d(self.x10, self.y10, copy=False).copy)
        self.assert_(interp1d(self.x10, self.y10).bounds_error)
        self.assert_(not interp1d(self.x10, self.y10, bounds_error=False).bounds_error)
        self.assert_(np.isnan(interp1d(self.x10, self.y10).fill_value))
        self.assertEqual(
            interp1d(self.x10, self.y10, fill_value=3.0).fill_value, 
            3.0,
        )
        self.assertEqual(
            interp1d(self.x10, self.y10).axis,
            0,
        )
        self.assertEqual(
            interp1d(self.x10, self.y210).axis,
            1,
        )
        self.assertEqual(
            interp1d(self.x10, self.y102, axis=0).axis,
            0,
        )
        assert_array_equal(
            interp1d(self.x10, self.y10).x,
            self.x10,
        )
        assert_array_equal(
            interp1d(self.x10, self.y10).y,
            self.y10,
        )
        assert_array_equal(
            interp1d(self.x10, self.y210).y,
            self.y210,
        )