예제 #1
0
    def get_common_tangent(self, another_data, t0):
        """
        共通接線を探す
        """
        yp = None
        xi = pylab.linspace(0, 0.3, 10001)
        dxi = xi[1] - xi[0]
        close_t0 = xi[np.searchsorted(xi, t0)]

        y1 = pylab.stineman_interp(
            xi, self['comp1'], self['corrected_g'], yp)
        y2 = pylab.stineman_interp(
            xi, another_data['comp1'], another_data['corrected_g'], yp)

        def search_minimum(x):
            x1, x2 = x
            # print(y2[xi==x2])
            # print(y1[xi==x2])
            line = (y2[xi==x2]-y1[xi==x1])/(x2-x1)*(xi-x1) + y1[xi==x1]
            delta1 = y1 - line
            delta2 = y2 - line
            return (xi[delta1 == delta1.min()],
                    xi[delta2 == delta2.min()])
        a, b = xi[np.searchsorted(xi, close_t0-dxi)], xi[np.searchsorted(xi, close_t0+dxi)]
        print(a, b)
        print(xi[xi==a], xi[xi==b])
        for i in range(10):
            a, b = search_minimum((a, b))
            print(a, b)
        return a, b
예제 #2
0
 def get_t0(self, another_data, range=(0, 1)):
     """
     range 内の交点を探す
     なければ None を return
     """
     yp = None
     xi = pylab.linspace(range[0], range[-1], 10000)
     y1 = pylab.stineman_interp(xi, self['comp1'], self['collected_g'], yp)
     y2 = pylab.stineman_interp(
         xi, another_data['comp1'], another_data['collected_g'], yp)
     delta = y1 - y2
     # 最初に符号が反転する点を T0 とする
     return xi[np.where((delta[0] * delta) < 0)][0], y1[np.where((delta[0] * delta) < 0)][0]
def plot_one(filename, name, axes):
    field = 'Density'
    print "opening " + filename

    # open output and create ray
    pf = load(filename)
    ray = pf.h.ortho_ray(0, [0.5, 0.5])

    # first interpolate the exact solution onto the ray
    ray_exact = {
        'x':
        ray['x'],
        'Density':
        pylab.stineman_interp(ray['x'], exact['x'], exact['Density']),
        'x-velocity':
        pylab.stineman_interp(ray['x'], exact['x'], exact['x-velocity']),
        'Pressure':
        pylab.stineman_interp(ray['x'], exact['x'], exact['Pressure']),
        'InternalEnergy':
        pylab.stineman_interp(ray['x'], exact['x'], exact['InternalEnergy'])
    }

    # compute first order and max error norms
    delta = ray['dx'] * abs(ray[field] - ray_exact[field])
    norm = delta.sum()
    maxnorm = abs(ray[field] - ray_exact[field]).max()

    # rough computation of level for each point in ray (probably better way)
    level = -pylab.log(ray['dx'] / ray['dx'][0]) / pylab.log(2.0)

    # plot
    ax = pylab.axes(axes)
    pylab.axhline(0, color='k', linestyle='dotted')
    pylab.plot(exact['x'], exact[field], c='black', linewidth=(1, ))
    pylab.scatter(ray['x'], ray[field], c=level, s=8, linewidths=(0, ))

    # Set axis (clunky)
    pylab.axis([0, 0.999, 0, 1.1])  # for density
    if axes[1] < 0.5:
        pylab.xlabel('Position')
    else:
        ax.set_xticklabels([])
    if axes[0] < 0.1:
        pylab.ylabel(field)
    else:
        ax.set_yticklabels([])

    error_label(name, norm, maxnorm, 0.41, 1.0)
 def Stineman_interp_fit(x, y): #pylint: disable=C0103
     """
     データ補間曲線
     """
     yp = None #pylint: disable=C0103
     xi = pylab.linspace(x[0], x[-1], 100) #pylint: disable=E1101,C0103
     yi = pylab.stineman_interp(xi, x, y, yp) #pylint: disable=C0103
     return xi, yi
예제 #5
0
 def fit_interp(self, data_x, data_y, range=(0, 1), np=100):
     """
     range 内のデータを interpolate して出力
     """
     yp = None
     xi = pylab.linspace(range[0], range[-1], np)
     yi = pylab.stineman_interp(xi, data_x, data_y, yp)
     return xi, yi
예제 #6
0
def interpol(x, y, start=None, end=None, step=None, num=None, kind='lin'):
    from scipy import interpolate, exp, log10, linspace, logspace
    from pylab import stineman_interp
    from numpy import where
    # check if it is a linear vector or a log one
    if (x[1] - x[0]) * (1 - 0.01) <= x[2] - x[1] <= (x[1] - x[0]) * (1 + 0.01):
        scale = 'lin'
    else:
        scale = 'log'
    # set starting point of interpolation
    # if it is not given
    if start is None:
        start = x[0]
    # set ending point of interpolation
    # if it is not given
    if end is None:
        end = x[-1]

    # get stepsize / number of values of interpolation
    # if the x vector should be logarithmic
    if kind == 'log':
        if start <= 0.0: start = x[where(x > 0.0)[0][0]]
        if num is None:
            if scale == 'log':
                if step is None:
                    step = log10(x[2]) - log10(x[1])
                num = 1 + (log10(end) - log10(start)) / step
            else:
                if step is None:
                    step = x[2] - x[1]
                num = 1 + (end - start) / step
        x1 = 10**(linspace(log10(start), log10(end), num))
    # if the x vector should be linear
    else:  # linear
        if num is None:
            if scale == 'log':
                if start <= 0.0: start = x[where(x > 0.0)[0][0]]
                if step is None:
                    step = log10(x[2]) - log10(x[1])
                num = 1 + (log10(end) - log10(start)) / step
            else:
                if step is None:
                    step = x[2] - x[1]
                num = 1 + (end - start) / step
        x1 = linspace(start, end, num)

    # build a spline out of the x, y bvalues
    #~ spline_coeffs=interpolate.splrep(x,y,s=0)
    #~ # interpolate for new x vector
    #~ y1=interpolate.splev(x1,spline_coeffs,der=0)
    y2 = stineman_interp(x1, x, y)

    #~ y2 = interpolate.splev(x1, interpolate.splrep(x, y, k=3))
    #~ y2 = interpolate.interp1d(x,y)(x1)

    return x1, y2  #~, y2
예제 #7
0
### extract an ortho_ray (1D solution vector)
ray = pf.h.ortho_ray(0, [0.5, 0.5])


### define fields vector
fields = ('Density', 'x-velocity', 'InternalEnergy', 'Pressure' )

### read exact solution
exact = pylab.csv2rec( exact_solution_filename, delimiter=' ', names=('x', 'Density', 'x-velocity', 'Pressure', 'InternalEnergy') )


### calculate difference norm

# first interpolate the exact solution onto the ray
ray_exact = {'x': ray['x'], 
             'Density': pylab.stineman_interp(ray['x'],exact['x'],exact['Density']),
             'x-velocity': pylab.stineman_interp(ray['x'],exact['x'],exact['x-velocity']),
             'Pressure': pylab.stineman_interp(ray['x'],exact['x'],exact['Pressure']),
             'InternalEnergy': pylab.stineman_interp(ray['x'],exact['x'],exact['InternalEnergy'])}


# now calculate the norm (first order, since we're dealing with
# conservation laws)

norm = {}
maxnorm = {}
for f in fields:
    delta = ray['dx'] * abs( ray[f] - ray_exact[f] )
    norm[f] = delta.sum()
    maxnorm[f] = delta.max()
예제 #8
0
def touch():
    read_data = CVMCv1Parser.from_file('cv1.txt')
    d = read_data.data[0]['data']
    datax = d['comp1']
    dataz = d['F'] * 8.31 / 1000

    max_x = datax.max()
    min_x = datax.min()
    yp = None
    xi = pylab.linspace(min_x, max_x, 20)
    z1 = pylab.stineman_interp(xi, datax, dataz, yp)

    points = []
    for i, x in enumerate(xi):
        fig = pylab.figure()
        ax = fig.add_subplot(111)
        ax.plot(datax, dataz, '+')
        ax.plot(xi, z1, color='red', linewidth=2)

        ax.axvline(x, color='black', linewidth=1)
        Cursor(ax, vertOn=False, useblit=True, color='black', linewidth=1)
        try:
            p = pylab.ginput(n=1, timeout=2)
            while p == []:
                p = pylab.ginput(n=1, timeout=2)
            print(x, p[0][1])
        except KeyboardInterrupt:
            print("そのまま利用します")
            print(x, z1[i])
            p = [[x, z1[i]]]
        points.append(p[0][1])
        pylab.close()
    z2 = pylab.stineman_interp(datax, xi, points)
    delta = (z2 - dataz)**2
    sl = 5
    # pylab.plot(datax, delta[delta < sl])
    # pylab.show()

    ### interp
    # z3 = pylab.stineman_interp(
    #     xi, datax[delta < sl], dataz[delta < sl])
    # pylab.plot(datax, dataz, '+')
    # pylab.plot(xi, z3)
    # pylab.show()
    ### interp

    err = make_err_func(hex_free_end)
    opt = optimize.leastsq(err, [1, 1, 1, 1, 1, 1, 1],
                           args=(datax[delta<sl], dataz[delta<sl]))[0]
    xi2 = pylab.linspace(min_x, max_x, 200)
    fity = hex_free_end(opt, xi2)
    pylab.plot((datax/(datax+0.5))[::5], (dataz/(datax+0.5))[::5], '+')
    pylab.plot(xi2/(xi2+0.5), fity/(xi2+0.5), linewidth=2)
    print(xi2/(xi2+0.5))
    print(fity/(xi2+0.5))

    # pylab.plot(datax, dataz, '+')
    # pylab.plot(xi, fity, linewidth=2)

    pylab.show()

    lines = ''
    for x, z in zip(datax[::5], dataz[::5]):
        lines += '{0}\t{1}\n'.format(str(x/(x+0.5)), str(z/(x+0.5)))
    with open('data.txt', 'w') as wfile:
        wfile.write(lines)

    lines = ''
    for x, z in zip(xi2, fity):
        lines += '{0}\t{1}\n'.format(str(x/(x+0.5)), str(z/(x+0.5)))
    with open('fit.txt', 'w') as wfile:
        wfile.write(lines)
예제 #9
0
파일: core.py 프로젝트: mikemt/pywafo-1
    def tospecdata(self, rate=None, method='fft', nugget=0.0, trunc=1e-5,
                   fast=True):
        '''
        Computes spectral density from the auto covariance function

        Parameters
        ----------
        rate = scalar, int
            1,2,4,8...2^r, interpolation rate for f (default 1)
        method : string
            interpolation method 'stineman', 'linear', 'cubic', 'fft'
        nugget : scalar, real
            nugget effect to ensure that round off errors do not result in
            negative spectral estimates. Good choice might be 10^-12.
        trunc : scalar, real
            truncates all spectral values where S/max(S) < trunc
                      0 <= trunc <1   This is to ensure that high frequency
                      noise is not added to the spectrum.  (default 1e-5)
        fast : bool
             if True : zero-pad to obtain power of 2 length ACF (default)
             otherwise  no zero-padding of ACF, slower but more accurate.

        Returns
        --------
        S : SpecData1D object
            spectral density

         NB! This routine requires that the covariance is evenly spaced
             starting from zero lag. Currently only capable of 1D matrices.

        Example:
        >>> import wafo.spectrum.models as sm
        >>> import numpy as np
        >>> import scipy.signal as st
        >>> import pylab
        >>> L = 129
        >>> t = np.linspace(0,75,L)
        >>> R = np.zeros(L)
        >>> win = st.parzen(41)
        >>> R[0:21] = win[20:41]
        >>> R0 = CovData1D(R,t)
        >>> S0 = R0.tospecdata()

        >>> Sj = sm.Jonswap()
        >>> S = Sj.tospecdata()
        >>> R2 = S.tocovdata()
        >>> S1 = R2.tospecdata()
        >>> abs(S1.data-S.data).max()

        >>> S1.plot('r-')
        >>> S.plot('b:')
        >>> pylab.show()

        >>> all(abs(S1.data-S.data)<1e-4)

        See also
        --------
        spec2cov
        datastructures
        '''

        dt = self.sampling_period()
        # dt = time-step between data points.

        acf, unused_ti = atleast_1d(self.data, self.args)

        if self.lagtype in 't':
            spectype = 'freq'
            ftype = 'w'
        else:
            spectype = 'k1d'
            ftype = 'k'

        if rate is None:
            rate = 1  # interpolation rate
        else:
            rate = 2 ** nextpow2(rate)  # make sure rate is a power of 2

        # add a nugget effect to ensure that round off errors
        # do not result in negative spectral estimates
        acf[0] = acf[0] + nugget
        n = acf.size
        # embedding a circulant vector and Fourier transform

        nfft = 2 ** nextpow2(2 * n - 2) if fast else 2 * n - 2

        if method == 'fft':
            nfft *= rate

        nf = nfft / 2  # number of frequencies
        acf = r_[acf, zeros(nfft - 2 * n + 2), acf[n - 2:0:-1]]

        Rper = (fft(acf, nfft).real).clip(0)  # periodogram
        RperMax = Rper.max()
        Rper = where(Rper < trunc * RperMax, 0, Rper)

        S = abs(Rper[0:(nf + 1)]) * dt / pi
        w = linspace(0, pi / dt, nf + 1)
        So = _wafospec.SpecData1D(S, w, type=spectype, freqtype=ftype)
        So.tr = self.tr
        So.h = self.h
        So.norm = self.norm

        if method != 'fft' and rate > 1:
            So.args = linspace(0, pi / dt, nf * rate)
            if method == 'stineman':
                So.data = stineman_interp(So.args, w, S)
            else:
                intfun = interpolate.interp1d(w, S, kind=method)
                So.data = intfun(So.args)
            So.data = So.data.clip(0)  # clip negative values to 0
        return So
예제 #10
0
파일: core.py 프로젝트: Bobfrat/pywafo
    def tospecdata(self,
                   rate=None,
                   method='fft',
                   nugget=0.0,
                   trunc=1e-5,
                   fast=True):
        '''
        Computes spectral density from the auto covariance function

        Parameters
        ----------
        rate = scalar, int
            1,2,4,8...2^r, interpolation rate for f (default 1)
        method : string
            interpolation method 'stineman', 'linear', 'cubic', 'fft'
        nugget : scalar, real
            nugget effect to ensure that round off errors do not result in
            negative spectral estimates. Good choice might be 10^-12.
        trunc : scalar, real
            truncates all spectral values where S/max(S) < trunc
                      0 <= trunc <1   This is to ensure that high frequency
                      noise is not added to the spectrum.  (default 1e-5)
        fast : bool
             if True : zero-pad to obtain power of 2 length ACF (default)
             otherwise  no zero-padding of ACF, slower but more accurate.

        Returns
        --------
        S : SpecData1D object
            spectral density

         NB! This routine requires that the covariance is evenly spaced
             starting from zero lag. Currently only capable of 1D matrices.

        Example:
        >>> import wafo.spectrum.models as sm
        >>> import numpy as np
        >>> import scipy.signal as st
        >>> import pylab
        >>> L = 129
        >>> t = np.linspace(0,75,L)
        >>> R = np.zeros(L)
        >>> win = st.parzen(41)
        >>> R[0:21] = win[20:41]
        >>> R0 = CovData1D(R,t)
        >>> S0 = R0.tospecdata()

        >>> Sj = sm.Jonswap()
        >>> S = Sj.tospecdata()
        >>> R2 = S.tocovdata()
        >>> S1 = R2.tospecdata()
        >>> abs(S1.data-S.data).max() < 1e-4
        True

        S1.plot('r-')
        S.plot('b:')
        pylab.show()

        See also
        --------
        spec2cov
        datastructures
        '''

        dt = self.sampling_period()
        # dt = time-step between data points.

        acf, unused_ti = atleast_1d(self.data, self.args)

        if self.lagtype in 't':
            spectype = 'freq'
            ftype = 'w'
        else:
            spectype = 'k1d'
            ftype = 'k'

        if rate is None:
            rate = 1  # interpolation rate
        else:
            rate = 2**nextpow2(rate)  # make sure rate is a power of 2

        # add a nugget effect to ensure that round off errors
        # do not result in negative spectral estimates
        acf[0] = acf[0] + nugget
        n = acf.size
        # embedding a circulant vector and Fourier transform

        nfft = 2**nextpow2(2 * n - 2) if fast else 2 * n - 2

        if method == 'fft':
            nfft *= rate

        nf = nfft / 2  # number of frequencies
        acf = r_[acf, zeros(nfft - 2 * n + 2), acf[n - 2:0:-1]]

        Rper = (fft(acf, nfft).real).clip(0)  # periodogram
        RperMax = Rper.max()
        Rper = where(Rper < trunc * RperMax, 0, Rper)

        S = abs(Rper[0:(nf + 1)]) * dt / pi
        w = linspace(0, pi / dt, nf + 1)
        So = _wafospec.SpecData1D(S, w, type=spectype, freqtype=ftype)
        So.tr = self.tr
        So.h = self.h
        So.norm = self.norm

        if method != 'fft' and rate > 1:
            So.args = linspace(0, pi / dt, nf * rate)
            if method == 'stineman':
                So.data = stineman_interp(So.args, w, S)
            else:
                intfun = interpolate.interp1d(w, S, kind=method)
                So.data = intfun(So.args)
            So.data = So.data.clip(0)  # clip negative values to 0
        return So
예제 #11
0
 def Stineman_interp_fit(self, x, y):
     yp = None
     xi = pylab.linspace(x[0], x[-1], 100)
     yi = pylab.stineman_interp(xi, x, y, yp)
     return xi, yi
예제 #12
0
from pylab import figure, show, nx, linspace, stineman_interp
x = linspace(0,2*nx.pi,20);
y = nx.sin(x); yp = None 
xi = linspace(x[0],x[-1],100);
yi = stineman_interp(xi,x,y,yp);

fig = figure()
ax = fig.add_subplot(111)
ax.plot(x,y,'ro',xi,yi,'-b.')
show()

예제 #13
0
from pylab import figure, show, nx, linspace, stineman_interp
x = linspace(0, 2 * nx.pi, 20)
y = nx.sin(x)
yp = None
xi = linspace(x[0], x[-1], 100)
yi = stineman_interp(xi, x, y, yp)

fig = figure()
ax = fig.add_subplot(111)
ax.plot(x, y, 'ro', xi, yi, '-b.')
show()