コード例 #1
0
ファイル: BoundaryConditions.py プロジェクト: archTk/pyNS
    def GetFlow(self):
        '''
        Calculating inlet flow (coefficients of the FFT  x(t)=A0+sum(2*Ck*exp(j*k*2*pi*f*t)))
        Timestep and period from SimulationContext are necessary.
        '''
        try:
            timestep = self.SimulationContext.Context['timestep']
        except KeyError:
            print "Error, Please set timestep in Simulation Context XML File"
            raise
        try:
            period = self.SimulationContext.Context['period']
        except KeyError:
            print "Error, Please set period in Simulation Context XML File"
            raise

        t = arange(0.0,period+timestep,timestep).reshape((1,ceil(period/timestep+1.0)))
        Cc = self.f_coeff*1.0/2.0*1e-6
        Flow = zeros((1, ceil(period/timestep+1.0)))
        for freq in arange(0,ceil(period/timestep+1.0)):
            Flow[0, freq] = self.A0_v
            for k in arange(0,self.f_coeff.shape[0]):
                Flow[0, freq] = Flow[0, freq]+real(2.0*complex(Cc[k,0],Cc[k,1])*exp(1j*(k+1)*2.0*pi*t[0,freq]/period))
        self.Flow = Flow
        return Flow
コード例 #2
0
ファイル: TestLPCImpl.py プロジェクト: drbenmorgan/lpcm
 def testNoisyLine1(self):
   x = map(lambda x: x + gauss(0,0.002), arange(-1,1,0.001))
   y = map(lambda x: x + gauss(0,0.002), arange(-1,1,0.001))
   z = map(lambda x: x + gauss(0,0.02), arange(-1,1,0.001))
   line = array(zip(x,y,z))
   lpc = LPCImpl(h = 0.2, mult = 2)
   lpc_curve = lpc.lpc(X = line)
コード例 #3
0
ファイル: twodim_base.py プロジェクト: 8848/Pymol-script-repo
def diagflat(v,k=0):
    """Return a 2D array whose k'th diagonal is a flattened v and all other
    elements are zero.

    Examples
    --------
      >>> diagflat([[1,2],[3,4]]])
      array([[1, 0, 0, 0],
             [0, 2, 0, 0],
             [0, 0, 3, 0],
             [0, 0, 0, 4]])

      >>> diagflat([1,2], 1)
      array([[0, 1, 0],
             [0, 0, 2],
             [0, 0, 0]])
    """
    try:
        wrap = v.__array_wrap__
    except AttributeError:
        wrap = None
    v = asarray(v).ravel()
    s = len(v)
    n = s + abs(k)
    res = zeros((n,n), v.dtype)
    if (k>=0):
        i = arange(0,n-k)
        fi = i+k+i*n
    else:
        i = arange(0,n+k)
        fi = i+(i-k)*n
    res.flat[fi] = v
    if not wrap:
        return res
    return wrap(res)
コード例 #4
0
ファイル: BoundaryConditions.py プロジェクト: archTk/pyNS
    def GetTimeFlow(self, el, time):
        '''
        Calculating inlet flow (coefficients of the FFT  x(t)=A0+sum(2*Ck*exp(j*k*2*pi*f*t)))
        for a specific time value.
        If signal is specified, flow is computed from time values.
        '''
        try:
            period = self.SimulationContext.Context['period']
        except KeyError:
            print "Error, Please set period in Simulation Context XML File"
            raise

        try:
            signal = self.InFlows[el]['signal']
            try:
                timestep = self.SimulationContext.Context['timestep']
            except KeyError:
                print "Error, Please set timestep in Simulation Context XML File"
                raise
            t = arange(0.0,period+timestep,timestep)
            t2 = list(t)
            Flow = float(signal[t2.index(time)])/6.0e7
            self.Flow = Flow
            return Flow
        except KeyError:
            f_coeff = self.InFlows[el]['f_coeff']
            A0 = self.InFlows[el]['A0']
            Cc = f_coeff*1.0/2.0*1e-6
            Flow = A0
            for k in arange(0,f_coeff.shape[0]):
                Flow += real(2.0*complex(Cc[k,0],Cc[k,1])*exp(1j*(k+1)*2.0*pi*time/period))
            self.Flow = Flow
            return Flow
コード例 #5
0
ファイル: TestLPCImpl.py プロジェクト: drbenmorgan/lpcm
 def testNoisyLine2(self):
   x = map(lambda x: x + gauss(0,0.005), arange(-1,1,0.005))
   y = map(lambda x: x + gauss(0,0.005), arange(-1,1,0.005))
   z = map(lambda x: x + gauss(0,0.005), arange(-1,1,0.005))
   line = array(zip(x,y,z))
   lpc = LPCImpl(h = 0.2, convergence_at = 0.001, mult = 2)
   lpc_curve = lpc.lpc(X = line) 
コード例 #6
0
ファイル: index_tricks.py プロジェクト: Benj1/numpy
 def __getitem__(self, key):
     try:
         size = []
         typ = int
         for k in range(len(key)):
             step = key[k].step
             start = key[k].start
             if start is None:
                 start = 0
             if step is None:
                 step = 1
             if isinstance(step, complex):
                 size.append(int(abs(step)))
                 typ = float
             else:
                 size.append(
                     int(math.ceil((key[k].stop - start)/(step*1.0))))
             if (isinstance(step, float) or
                     isinstance(start, float) or
                     isinstance(key[k].stop, float)):
                 typ = float
         if self.sparse:
             nn = [_nx.arange(_x, dtype=_t)
                     for _x, _t in zip(size, (typ,)*len(size))]
         else:
             nn = _nx.indices(size, typ)
         for k in range(len(size)):
             step = key[k].step
             start = key[k].start
             if start is None:
                 start = 0
             if step is None:
                 step = 1
             if isinstance(step, complex):
                 step = int(abs(step))
                 if step != 1:
                     step = (key[k].stop - start)/float(step-1)
             nn[k] = (nn[k]*step+start)
         if self.sparse:
             slobj = [_nx.newaxis]*len(size)
             for k in range(len(size)):
                 slobj[k] = slice(None, None)
                 nn[k] = nn[k][slobj]
                 slobj[k] = _nx.newaxis
         return nn
     except (IndexError, TypeError):
         step = key.step
         stop = key.stop
         start = key.start
         if start is None:
             start = 0
         if isinstance(step, complex):
             step = abs(step)
             length = int(step)
             if step != 1:
                 step = (key.stop-start)/float(step-1)
             stop = key.stop + step
             return _nx.arange(0, length, 1, float)*step + start
         else:
             return _nx.arange(start, stop, step)
コード例 #7
0
ファイル: LPCImplExamples.py プロジェクト: drbenmorgan/lpcm
def plot2():
  fig5 = plt.figure()
  x = map(lambda x: x + gauss(0,0.02)*(1-x*x), arange(-1,1,0.001))
  y = map(lambda x: x + gauss(0,0.02)*(1-x*x), arange(-1,1,0.001))
  z = map(lambda x: x + gauss(0,0.02)*(1-x*x), arange(-1,1,0.001))
  line = array(zip(x,y,z))
  lpc = LPCImpl(h = 0.05, mult = 2, it = 200, cross = False, scaled = False, convergence_at = 0.001)
  lpc_curve = lpc.lpc(X=line)
  ax = Axes3D(fig5)
  ax.set_title('testNoisyLine2')
  curve = lpc_curve[0]['save_xd']
  ax.scatter(x,y,z, c = 'red')
  ax.plot(curve[:,0],curve[:,1],curve[:,2])
  saveToPdf(fig5, '/tmp/testNoisyLine2.pdf')
  residuals_calc = LPCResiduals(line, tube_radius = 0.05, k = 10)
  residual_diags = residuals_calc.getPathResidualDiags(lpc_curve[0])
  fig6 = plt.figure()
  #plt.plot(lpc_curve[0]['lamb'][1:], residual_diags['line_seg_num_NN'], drawstyle = 'step', linestyle = '--')
  plt.plot(lpc_curve[0]['lamb'][1:], residual_diags['line_seg_mean_NN'])
  plt.plot(lpc_curve[0]['lamb'][1:], residual_diags['line_seg_std_NN'])
  saveToPdf(fig6, '/tmp/testNoisyLine2PathResiduals.pdf')
  coverage_graph = residuals_calc.getCoverageGraph(lpc_curve[0], arange(0.001, .102, 0.005))
  fig7 = plt.figure()
  plt.plot(coverage_graph[0],coverage_graph[1])
  saveToPdf(fig7, '/tmp/testNoisyLine2Coverage.pdf')
  residual_graph = residuals_calc.getGlobalResiduals(lpc_curve[0])
  fig8 = plt.figure()
  plt.plot(residual_graph[0], residual_graph[1])
  saveToPdf(fig8, '/tmp/testNoisyLine2Residuals.pdf')
  fig9 = plt.figure()
  plt.plot(range(len(lpc_curve[0]['lamb'])), lpc_curve[0]['lamb'])
  saveToPdf(fig9, '/tmp/testNoisyLine2PathLength.pdf')
コード例 #8
0
ファイル: twodim_base.py プロジェクト: 8848/Pymol-script-repo
def tri(N, M=None, k=0, dtype=float):
    """ returns a N-by-M array where all the diagonals starting from
        lower left corner up to the k-th are all ones.
    """
    if M is None: M = N
    m = greater_equal(subtract.outer(arange(N), arange(M)),-k)
    return m.astype(dtype)
コード例 #9
0
ファイル: twodim_base.py プロジェクト: 8848/Pymol-script-repo
def diag(v, k=0):
    """ returns a copy of the the k-th diagonal if v is a 2-d array
        or returns a 2-d array with v as the k-th diagonal if v is a
        1-d array.
    """
    v = asarray(v)
    s = v.shape
    if len(s)==1:
        n = s[0]+abs(k)
        res = zeros((n,n), v.dtype)
        if (k>=0):
            i = arange(0,n-k)
            fi = i+k+i*n
        else:
            i = arange(0,n+k)
            fi = i+(i-k)*n
        res.flat[fi] = v
        return res
    elif len(s)==2:
        N1,N2 = s
        if k >= 0:
            M = min(N1,N2-k)
            i = arange(0,M)
            fi = i+k+i*N2
        else:
            M = min(N1+k,N2)
            i = arange(0,M)
            fi = i + (i-k)*N2
        return v.flat[fi]
    else:
        raise ValueError, "Input must be 1- or 2-d."
コード例 #10
0
ファイル: LPCImplExamples.py プロジェクト: drbenmorgan/lpcm
def helixHeteroscedasticDiags():
  #Parameterise a helix (no noise)
  fig5 = plt.figure()
  t = arange(-1,1,0.0005)
  x = map(lambda x: x + gauss(0,0.001 + 0.001*sin(2*pi*x)**2), (1 - t*t)*sin(4*pi*t))
  y = map(lambda x: x + gauss(0,0.001 + 0.001*sin(2*pi*x)**2), (1 - t*t)*cos(4*pi*t))
  z = map(lambda x: x + gauss(0,0.001 + 0.001*sin(2*pi*x)**2), t)
  line = array(zip(x,y,z))
  lpc = LPCImpl(h = 0.1, t0 = 0.1, mult = 1, it = 500, scaled = False, cross = False)
  lpc_curve = lpc.lpc(X=line)
  ax = Axes3D(fig5)
  ax.set_title('helixHeteroscedastic')
  curve = lpc_curve[0]['save_xd']
  ax.scatter(x,y,z, c = 'red')
  ax.plot(curve[:,0],curve[:,1],curve[:,2])
  saveToPdf(fig5, '/tmp/helixHeteroscedastic.pdf')
  residuals_calc = LPCResiduals(line, tube_radius = 0.2, k = 20)
  residual_diags = residuals_calc.getPathResidualDiags(lpc_curve[0])
  fig6 = plt.figure()
  #plt.plot(lpc_curve[0]['lamb'][1:], residual_diags['line_seg_num_NN'], drawstyle = 'step', linestyle = '--')
  plt.plot(lpc_curve[0]['lamb'][1:], residual_diags['line_seg_mean_NN'])
  plt.plot(lpc_curve[0]['lamb'][1:], residual_diags['line_seg_std_NN'])
  saveToPdf(fig6, '/tmp/helixHeteroscedasticPathResiduals.pdf')
  coverage_graph = residuals_calc.getCoverageGraph(lpc_curve[0], arange(0.01, .052, 0.01))
  fig7 = plt.figure()
  plt.plot(coverage_graph[0],coverage_graph[1])
  saveToPdf(fig7, '/tmp/helixHeteroscedasticCoverage.pdf')
  residual_graph = residuals_calc.getGlobalResiduals(lpc_curve[0])
  fig8 = plt.figure()
  plt.plot(residual_graph[0], residual_graph[1])
  saveToPdf(fig8, '/tmp/helixHeteroscedasticResiduals.pdf')
  fig9 = plt.figure()
  plt.plot(range(len(lpc_curve[0]['lamb'])), lpc_curve[0]['lamb'])
  saveToPdf(fig9, '/tmp/helixHeteroscedasticPathLength.pdf')
コード例 #11
0
def eye(N, M=None, k=0, dtype=float):
    """ eye returns a N-by-M 2-d array where the  k-th diagonal is all ones,
        and everything else is zeros.
    """
    if M is None: M = N
    m = equal(subtract.outer(arange(N), arange(M)),-k)
    if m.dtype != dtype:
        return m.astype(dtype)
コード例 #12
0
def diagflat(v, k=0):
    """
    Create a two-dimensional array with the flattened input as a diagonal.

    Parameters
    ----------
    v : array_like
        Input data, which is flattened and set as the `k`-th
        diagonal of the output.
    k : int, optional
        Diagonal to set; 0, the default, corresponds to the "main" diagonal,
        a positive (negative) `k` giving the number of the diagonal above
        (below) the main.

    Returns
    -------
    out : ndarray
        The 2-D output array.

    See Also
    --------
    diag : MATLAB work-alike for 1-D and 2-D arrays.
    diagonal : Return specified diagonals.
    trace : Sum along diagonals.

    Examples
    --------
    >>> np.diagflat([[1,2], [3,4]])
    array([[1, 0, 0, 0],
           [0, 2, 0, 0],
           [0, 0, 3, 0],
           [0, 0, 0, 4]])

    >>> np.diagflat([1,2], 1)
    array([[0, 1, 0],
           [0, 0, 2],
           [0, 0, 0]])

    """
    try:
        wrap = v.__array_wrap__
    except AttributeError:
        wrap = None
    v = asarray(v).ravel()
    s = len(v)
    n = s + abs(k)
    res = zeros((n, n), v.dtype)
    if k >= 0:
        i = arange(0, n - k, dtype=intp)
        fi = i + k + i * n
    else:
        i = arange(0, n + k, dtype=intp)
        fi = i + (i - k) * n
    res.flat[fi] = v
    if not wrap:
        return res
    return wrap(res)
コード例 #13
0
ファイル: twodim_base.py プロジェクト: RJSSimpson/numpy
def diagflat(v, k=0):
    """
    Create a two-dimensional array with the flattened input as a diagonal.

    Parameters
    ----------
    v : array_like
        Input data, which is flattened and set as the `k`-th
        diagonal of the output.
    k : int, optional
        Diagonal to set; 0, the default, corresponds to the "main" diagonal,
        a positive (negative) `k` giving the number of the diagonal above
        (below) the main.

    Returns
    -------
    out : ndarray
        The 2-D output array.

    See Also
    --------
    diag : MATLAB work-alike for 1-D and 2-D arrays.
    diagonal : Return specified diagonals.
    trace : Sum along diagonals.

    Examples
    --------
    >>> np.diagflat([[1,2], [3,4]])
    array([[1, 0, 0, 0],
           [0, 2, 0, 0],
           [0, 0, 3, 0],
           [0, 0, 0, 4]])

    >>> np.diagflat([1,2], 1)
    array([[0, 1, 0],
           [0, 0, 2],
           [0, 0, 0]])

    """
    try:
        wrap = v.__array_wrap__
    except AttributeError:
        wrap = None
    v = asarray(v).ravel()
    s = len(v)
    n = s + abs(k)
    res = zeros((n,n), v.dtype)
    if (k >= 0):
        i = arange(0,n-k)
        fi = i+k+i*n
    else:
        i = arange(0,n+k)
        fi = i+(i-k)*n
    res.flat[fi] = v
    if not wrap:
        return res
    return wrap(res)
コード例 #14
0
ファイル: index_tricks.py プロジェクト: phonx/FlipbookApp
 def __getitem__(self, key):
     try:
         size = []
         typ = int
         for k in range(len(key)):
             step = key[k].step
             start = key[k].start
             if start is None: start = 0
             if step is None: step = 1
             if isinstance(step, complex):
                 size.append(int(abs(step)))
                 typ = float
             else:
                 size.append(
                     int(math.ceil((key[k].stop - start) / (step * 1.0))))
             if isinstance(step, float) or \
                 isinstance(start, float) or \
                 isinstance(key[k].stop, float):
                 typ = float
         if self.sparse:
             nn = [
                 _nx.arange(_x, dtype=_t)
                 for _x, _t in zip(size, (typ, ) * len(size))
             ]
         else:
             nn = _nx.indices(size, typ)
         for k in range(len(size)):
             step = key[k].step
             start = key[k].start
             if start is None: start = 0
             if step is None: step = 1
             if isinstance(step, complex):
                 step = int(abs(step))
                 if step != 1:
                     step = (key[k].stop - start) / float(step - 1)
             nn[k] = (nn[k] * step + start)
         if self.sparse:
             slobj = [_nx.newaxis] * len(size)
             for k in range(len(size)):
                 slobj[k] = slice(None, None)
                 nn[k] = nn[k][slobj]
                 slobj[k] = _nx.newaxis
         return nn
     except (IndexError, TypeError):
         step = key.step
         stop = key.stop
         start = key.start
         if start is None: start = 0
         if isinstance(step, complex):
             step = abs(step)
             length = int(step)
             if step != 1:
                 step = (key.stop - start) / float(step - 1)
             stop = key.stop + step
             return _nx.arange(0, length, 1, float) * step + start
         else:
             return _nx.arange(start, stop, step)
コード例 #15
0
ファイル: twodim_base.py プロジェクト: zoccolan/eyetracker
def diag(v, k=0):
    """
    Extract a diagonal or construct a diagonal array.

    Parameters
    ----------
    v : array_like
        If `v` is a 2-dimensional array, return a copy of
        its `k`-th diagonal. If `v` is a 1-dimensional array,
        return a 2-dimensional array with `v` on the `k`-th diagonal.
    k : int, optional
        Diagonal in question.  The defaults is 0.

    Examples
    --------
    >>> x = np.arange(9).reshape((3,3))
    >>> x
    array([[0, 1, 2],
           [3, 4, 5],
           [6, 7, 8]])

    >>> np.diag(x)
    array([0, 4, 8])

    >>> np.diag(np.diag(x))
    array([[0, 0, 0],
           [0, 4, 0],
           [0, 0, 8]])

    """
    v = asarray(v)
    s = v.shape
    if len(s)==1:
        n = s[0]+abs(k)
        res = zeros((n,n), v.dtype)
        if (k>=0):
            i = arange(0,n-k)
            fi = i+k+i*n
        else:
            i = arange(0,n+k)
            fi = i+(i-k)*n
        res.flat[fi] = v
        return res
    elif len(s)==2:
        N1,N2 = s
        if k >= 0:
            M = min(N1,N2-k)
            i = arange(0,M)
            fi = i+k+i*N2
        else:
            M = min(N1+k,N2)
            i = arange(0,M)
            fi = i + (i-k)*N2
        return v.flat[fi]
    else:
        raise ValueError, "Input must be 1- or 2-d."
コード例 #16
0
def diag(v, k=0):
    """
    Extract a diagonal or construct a diagonal array.

    Parameters
    ----------
    v : array_like
        If `v` is a 2-dimensional array, return a copy of
        its `k`-th diagonal. If `v` is a 1-dimensional array,
        return a 2-dimensional array with `v` on the `k`-th diagonal.
    k : int, optional
        Diagonal in question.  The defaults is 0.

    Examples
    --------
    >>> x = np.arange(9).reshape((3,3))
    >>> x
    array([[0, 1, 2],
           [3, 4, 5],
           [6, 7, 8]])

    >>> np.diag(x)
    array([0, 4, 8])

    >>> np.diag(np.diag(x))
    array([[0, 0, 0],
           [0, 4, 0],
           [0, 0, 8]])

    """
    v = asarray(v)
    s = v.shape
    if len(s)==1:
        n = s[0]+abs(k)
        res = zeros((n,n), v.dtype)
        if (k>=0):
            i = arange(0,n-k)
            fi = i+k+i*n
        else:
            i = arange(0,n+k)
            fi = i+(i-k)*n
        res.flat[fi] = v
        return res
    elif len(s)==2:
        N1,N2 = s
        if k >= 0:
            M = min(N1,N2-k)
            i = arange(0,M)
            fi = i+k+i*N2
        else:
            M = min(N1+k,N2)
            i = arange(0,M)
            fi = i + (i-k)*N2
        return v.flat[fi]
    else:
        raise ValueError, "Input must be 1- or 2-d."
コード例 #17
0
ファイル: visualize.py プロジェクト: xrick/AlignmentDuration
def visualizeTransMatrix(matrix, titleName, phonemesNetwork):
    visualizeMatrix(matrix,  titleName)
    
    listPhonemeNames = []
    for phoneme in phonemesNetwork:
        listPhonemeNames.append(phoneme.ID)
    from numpy.core.numeric import arange
    plt.xticks(arange(len(listPhonemeNames)) , listPhonemeNames )
    plt.yticks(arange(len(listPhonemeNames)) , listPhonemeNames )
    plt.show()
コード例 #18
0
def diagflat(v, k=0):
    """
    Create a two-dimensional array with the flattened input as a diagonal.

    Parameters
    ----------
    v : array_like
        Input data, which is flattened and set as the `k`-th
        diagonal of the output.
    k : int, optional
        Diagonal to set.  The default is 0.

    Returns
    -------
    out : ndarray
        The 2-D output array.

    See Also
    --------
    diag : Matlab workalike for 1-D and 2-D arrays.
    diagonal : Return specified diagonals.
    trace : Sum along diagonals.

    Examples
    --------
    >>> np.diagflat([[1,2], [3,4]])
    array([[1, 0, 0, 0],
           [0, 2, 0, 0],
           [0, 0, 3, 0],
           [0, 0, 0, 4]])

    >>> np.diagflat([1,2], 1)
    array([[0, 1, 0],
           [0, 0, 2],
           [0, 0, 0]])

    """
    try:
        wrap = v.__array_wrap__
    except AttributeError:
        wrap = None
    v = asarray(v).ravel()
    s = len(v)
    n = s + abs(k)
    res = zeros((n, n), v.dtype)
    if (k >= 0):
        i = arange(0, n - k)
        fi = i + k + i * n
    else:
        i = arange(0, n + k)
        fi = i + (i - k) * n
    res.flat[fi] = v
    if not wrap:
        return res
    return wrap(res)
コード例 #19
0
def tri(N, M=None, k=0, dtype=float, *, like=None):
    """
    An array with ones at and below the given diagonal and zeros elsewhere.

    Parameters
    ----------
    N : int
        Number of rows in the array.
    M : int, optional
        Number of columns in the array.
        By default, `M` is taken equal to `N`.
    k : int, optional
        The sub-diagonal at and below which the array is filled.
        `k` = 0 is the main diagonal, while `k` < 0 is below it,
        and `k` > 0 is above.  The default is 0.
    dtype : dtype, optional
        Data type of the returned array.  The default is float.
    ${ARRAY_FUNCTION_LIKE}

        .. versionadded:: 1.20.0

    Returns
    -------
    tri : ndarray of shape (N, M)
        Array with its lower triangle filled with ones and zero elsewhere;
        in other words ``T[i,j] == 1`` for ``j <= i + k``, 0 otherwise.

    Examples
    --------
    >>> np.tri(3, 5, 2, dtype=int)
    array([[1, 1, 1, 0, 0],
           [1, 1, 1, 1, 0],
           [1, 1, 1, 1, 1]])

    >>> np.tri(3, 5, -1)
    array([[0.,  0.,  0.,  0.,  0.],
           [1.,  0.,  0.,  0.,  0.],
           [1.,  1.,  0.,  0.,  0.]])

    """
    if like is not None:
        return _tri_with_like(N, M=M, k=k, dtype=dtype, like=like)

    if M is None:
        M = N

    m = greater_equal.outer(arange(N, dtype=_min_int(0, N)),
                            arange(-k, M - k, dtype=_min_int(-k, M - k)))

    # Avoid making a copy if the requested type is already bool
    m = m.astype(dtype, copy=False)

    return m
コード例 #20
0
ファイル: LPCImplExamples.py プロジェクト: drbenmorgan/lpcm
def plot1():
  fig1 = plt.figure()
  x = map(lambda x: x + gauss(0,0.005), arange(-1,1,0.005))
  y = map(lambda x: x + gauss(0,0.005), arange(-1,1,0.005))
  z = map(lambda x: x + gauss(0,0.005), arange(-1,1,0.005))
  line = array(zip(x,y,z))
  lpc = LPCImpl(h = 0.05, mult = 2, scaled = False)
  lpc_curve = lpc.lpc(X=line)
  ax = Axes3D(fig1)
  ax.set_title('testNoisyLine1')
  curve = lpc_curve[0]['save_xd']
  ax.scatter(curve[:,0],curve[:,1],curve[:,2],c = 'red')
  return fig1
コード例 #21
0
ファイル: function_base.py プロジェクト: alexxpan/python-art
def linspace(start, stop, num=50, endpoint=True, retstep=False):
    """Return evenly spaced numbers.

    Return num evenly spaced samples from start to stop.  If
    endpoint is True, the last sample is stop. If retstep is
    True then return (seq, step_value), where step_value used.

    :Parameters:
        start : {float}
            The value the sequence starts at.
        stop : {float}
            The value the sequence stops at. If ``endpoint`` is false, then
            this is not included in the sequence. Otherwise it is
            guaranteed to be the last value.
        num : {integer}
            Number of samples to generate. Default is 50.
        endpoint : {boolean}
            If true, ``stop`` is the last sample. Otherwise, it is not
            included. Default is true.
        retstep : {boolean}
            If true, return ``(samples, step)``, where ``step`` is the
            spacing used in generating the samples.

    :Returns:
        samples : {array}
            ``num`` equally spaced samples from the range [start, stop]
            or [start, stop).
        step : {float} (Only if ``retstep`` is true)
            Size of spacing between samples.

    :See Also:
        `arange` : Similiar to linspace, however, when used with
            a float endpoint, that endpoint may or may not be included.
        `logspace`
    """
    num = int(num)
    if num <= 0:
        return array([], float)
    if endpoint:
        if num == 1:
            return array([float(start)])
        step = (stop - start) / float((num - 1))
        y = _nx.arange(0, num) * step + start
        y[-1] = stop
    else:
        step = (stop - start) / float(num)
        y = _nx.arange(0, num) * step + start
    if retstep:
        return y, step
    else:
        return y
コード例 #22
0
ファイル: twodim_base.py プロジェクト: immerrr/numpy
def tri(N, M=None, k=0, dtype=float):
    """
    An array with ones at and below the given diagonal and zeros elsewhere.

    Parameters
    ----------
    N : int
        Number of rows in the array.
    M : int, optional
        Number of columns in the array.
        By default, `M` is taken equal to `N`.
    k : int, optional
        The sub-diagonal at and below which the array is filled.
        `k` = 0 is the main diagonal, while `k` < 0 is below it,
        and `k` > 0 is above.  The default is 0.
    dtype : dtype, optional
        Data type of the returned array.  The default is float.


    Returns
    -------
    tri : ndarray of shape (N, M)
        Array with its lower triangle filled with ones and zero elsewhere;
        in other words ``T[i,j] == 1`` for ``i <= j + k``, 0 otherwise.

    Examples
    --------
    >>> np.tri(3, 5, 2, dtype=int)
    array([[1, 1, 1, 0, 0],
           [1, 1, 1, 1, 0],
           [1, 1, 1, 1, 1]])

    >>> np.tri(3, 5, -1)
    array([[ 0.,  0.,  0.,  0.,  0.],
           [ 1.,  0.,  0.,  0.,  0.],
           [ 1.,  1.,  0.,  0.,  0.]])

    """
    if M is None:
        M = N

    m = greater_equal.outer(arange(N, dtype=_min_int(0, N)),
                            arange(-k, M-k, dtype=_min_int(-k, M - k)))

    # Avoid making a copy if the requested type is already bool
    if np_dtype(dtype) != np_dtype(bool):
        m = m.astype(dtype)

    return m
コード例 #23
0
ファイル: twodim_base.py プロジェクト: mbyt/numpy
def tri(N, M=None, k=0, dtype=float):
    """
    An array with ones at and below the given diagonal and zeros elsewhere.

    Parameters
    ----------
    N : int
        Number of rows in the array.
    M : int, optional
        Number of columns in the array.
        By default, `M` is taken equal to `N`.
    k : int, optional
        The sub-diagonal at and below which the array is filled.
        `k` = 0 is the main diagonal, while `k` < 0 is below it,
        and `k` > 0 is above.  The default is 0.
    dtype : dtype, optional
        Data type of the returned array.  The default is float.


    Returns
    -------
    tri : ndarray of shape (N, M)
        Array with its lower triangle filled with ones and zero elsewhere;
        in other words ``T[i,j] == 1`` for ``i <= j + k``, 0 otherwise.

    Examples
    --------
    >>> np.tri(3, 5, 2, dtype=int)
    array([[1, 1, 1, 0, 0],
           [1, 1, 1, 1, 0],
           [1, 1, 1, 1, 1]])

    >>> np.tri(3, 5, -1)
    array([[ 0.,  0.,  0.,  0.,  0.],
           [ 1.,  0.,  0.,  0.,  0.],
           [ 1.,  1.,  0.,  0.,  0.]])

    """
    if M is None:
        M = N

    m = greater_equal.outer(arange(N), arange(-k, M - k))

    # Avoid making a copy if the requested type is already bool
    if np_dtype(dtype) != np_dtype(bool):
        m = m.astype(dtype)

    return m
コード例 #24
0
ファイル: polynomial.py プロジェクト: lisarosalina/App
def polyint(p, m=1, k=None):
    """Return the mth analytical integral of the polynomial p.

    If k is None, then zero-valued constants of integration are used.
    otherwise, k should be a list of length m (or a scalar if m=1) to
    represent the constants of integration to use for each integration
    (starting with k[0])
    """
    m = int(m)
    if m < 0:
        raise ValueError, "Order of integral must be positive (see polyder)"
    if k is None:
        k = NX.zeros(m, float)
    k = atleast_1d(k)
    if len(k) == 1 and m > 1:
        k = k[0]*NX.ones(m, float)
    if len(k) < m:
        raise ValueError, \
              "k must be a scalar or a rank-1 array of length 1 or >m."
    if m == 0:
        return p
    else:
        truepoly = isinstance(p, poly1d)
        p = NX.asarray(p)
        y = NX.zeros(len(p)+1, float)
        y[:-1] = p*1.0/NX.arange(len(p), 0, -1)
        y[-1] = k[0]
        val = polyint(y, m-1, k=k[1:])
        if truepoly:
            val = poly1d(val)
        return val
コード例 #25
0
ファイル: LPCImplExamples.py プロジェクト: drbenmorgan/lpcm
def helixHeteroscedasticCrossingDemo():
  #Parameterise a helix (no noise)
  fig5 = plt.figure()
  t = arange(-1,1,0.001)
  x = map(lambda x: x + gauss(0,0.01 + 0.05*sin(8*pi*x)), (1 - t*t)*sin(4*pi*t))
  y = map(lambda x: x + gauss(0,0.01 + 0.05*sin(8*pi*x)), (1 - t*t)*cos(4*pi*t))
  z = map(lambda x: x + gauss(0,0.01 + 0.05*sin(8*pi*x)), t)
  line = array(zip(x,y,z))
  lpc = LPCImpl(h = 0.15, t0 = 0.1, mult = 2, it = 500, scaled = False)
  lpc_curve = lpc.lpc(line)
  ax = Axes3D(fig5)
  ax.set_title('helixHeteroscedasticWithCrossing')
  curve = lpc_curve[0]['save_xd']
  ax.scatter(x,y,z, c = 'red')
  ax.plot(curve[:,0],curve[:,1],curve[:,2])
  saveToPdf(fig5, '/tmp/helixHeteroscedasticWithCrossing.pdf')
  lpc.set_in_dict('cross', False, '_lpcParameters')
  fig6 = plt.figure()
  lpc_curve = lpc.lpc(X=line)
  ax = Axes3D(fig6)
  ax.set_title('helixHeteroscedasticWithoutCrossing')
  curve = lpc_curve[0]['save_xd']
  ax.scatter(x,y,z, c = 'red')
  ax.plot(curve[:,0],curve[:,1],curve[:,2])
  saveToPdf(fig6, '/tmp/helixHeteroscedasticWithoutCrossing.pdf')
コード例 #26
0
ファイル: LPCImplExamples.py プロジェクト: drbenmorgan/lpcm
def twoDisjointLinesWithMSClustering():
 
  t = arange(-1,1,0.002)
  x = map(lambda x: x + gauss(0,0.02)*(1-x*x), t)
  y = map(lambda x: x + gauss(0,0.02)*(1-x*x), t)
  z = map(lambda x: x + gauss(0,0.02)*(1-x*x), t)
  line1 = array(zip(x,y,z))
  line = vstack((line1, line1 + 3))
  lpc = LPCImpl(start_points_generator = lpcMeanShift(ms_h = 1), h = 0.05, mult = None, it = 200, cross = False, scaled = False, convergence_at = 0.001)
  lpc_curve = lpc.lpc(X=line)
  #Plot results
  fig = plt.figure()
  ax = Axes3D(fig)
  labels = lpc._startPointsGenerator._meanShift.labels_
  labels_unique = unique(labels)
  cluster_centers = lpc._startPointsGenerator._meanShift.cluster_centers_
  n_clusters = len(labels_unique)
  colors = cycle('bgrcmyk')
  for k, col in zip(range(n_clusters), colors):
    cluster_members = labels == k
    cluster_center = cluster_centers[k]
    ax.scatter(line[cluster_members, 0], line[cluster_members, 1], line[cluster_members, 2], c = col, alpha = 0.1)
    ax.scatter([cluster_center[0]], [cluster_center[1]], [cluster_center[2]], c = 'b', marker= '^')
    curve = lpc_curve[k]['save_xd']
    ax.plot(curve[:,0],curve[:,1],curve[:,2], c = col, linewidth = 3)
  plt.show()
コード例 #27
0
ファイル: zad2.py プロジェクト: slnowak/msi_byrski
def create_dataset():
    dataset = SupervisedDataSet(1, 1)

    for x in arange(0, 4*pi, pi/30):
        dataset.addSample(x, sin(x))

    return dataset
コード例 #28
0
ファイル: NetworkMesh.py プロジェクト: myousefi2016/pyNS
 def checkLinearConsistence(self):
     '''
     This method checks and fixes the correct proportion between the meshes of each edge.
     '''
     for edge in self.GraphEdgeToMesh.iterkeys():
         if edge.Side =='venous':
             meshes = self.GraphEdgeToMesh[edge]      
             startingMesh = meshes[0]
             startingRadius = self.ElementIdsToElements[str(startingMesh.keys()[0])].Radius[0]
             endingMesh = meshes[len(meshes)-1]
             endingRadius = self.ElementIdsToElements[str(endingMesh.keys()[0])].Radius[len(self.ElementIdsToElements[str(endingMesh.keys()[0])].Radius)-1]
             elLen = edge.Length['value']/len(meshes)
             self.dz = elLen/1.0e5
             z = arange(0.0,elLen,self.dz)
             dr = (endingRadius-startingRadius)/(len(meshes))
             for mesh in meshes:
                 if mesh == startingMesh:
                     r1 = startingRadius
                     r2 = r1+dr
                 elif mesh == endingMesh:     
                     r1 = r2
                     r2 = endingRadius
                 else: 
                     r1 = r2
                     r2+=dr
                 r_z = r1+((dr/elLen)*z)
                 self.ElementIdsToElements[str(mesh.keys()[0])].Radius = r_z
コード例 #29
0
def showAverageQValues(p, v, nEpisodes, path):
    '''Colorplot for the average QValues'''
    lrAgent = loadEpisodeVar(p, v, 0, path, 'lrAgent')
    ny, nx = shape(lrAgent.x)
    avgValues = zeros((ny, nx))
    for e in xrange(nEpisodes):
        if e != 0: lrAgent = loadEpisodeVar(p, v, e, path, 'lrAgent')
        avgValues += lrAgent.x


#      pdb.set_trace()
    avgValues = avgValues / nEpisodes
    figure()
    title('Average Q-values over the trials- p=' + str(p) + ' v=' + str(v))

    dlbd = lrAgent.lbd[1] - lrAgent.lbd[0]
    last = lrAgent.lbd[-1] + dlbd
    X = r_[
        lrAgent.lbd,
        last]  #watch out with this limit here "last" (pcolor doesn't show the last column)
    Y = arange(ny + 1)
    Z = avgValues
    pcolor(X, Y, Z)
    colorbar()
    axis([lrAgent.lbd[0], last, 0, ny + 1])
    xlabel('Learning rates')
    ylabel('Trials')
コード例 #30
0
def calcTheoreticalLWCProfile(cloudTop,cloudBase,zInc,betaStatic,cloudBaseTemp,lowestMeasuredLWC,lowestMeasuredAlt,omega):    
    LWCs = []
    alts = []
    Zs = []
    logZs = []
    deltaZ = cloudTop - cloudBase       # Absolute Wolkendicke
    
    # Ermittelung der Grenzschichten zwischen den 3 Layern:
    boundary1 = 0.   # Höhe der Grenze zwischen Layer1 und Layer2 (untere und mittlere Schicht)
    boundary2 = 0.   # Höhe der Grenze zwischen Layer2 und Layer3 (mittlere und obere Schicht)
    
    if deltaZ >= 166.67: boundary1 = deltaZ * 0.3 + cloudBase  # boundary1 entspricht 30% der Nebeldicke
    else: boundary1 = 50. + cloudBase                          # boundary1 entspricht 50m über Nebeluntergrenze
    
    if deltaZ >= 500.00: boundary2 = cloudTop - 75.  # boundary2 entspricht 75m unter Nebelobergrenze
    else: boundary2 = cloudTop - deltaZ * 0.15       # boundary2 entspricht 15% von der Gesamtdicke unter Nebelobergrenze = 85% der Nebeldicke
    
    # Anpassung von beta (Eq. 4.44):
    beta = betaStatic * cloudTop / 1000.
    
    # Bestimmung des LWC-Wertes bei 0m Höhe
    # Annahme: Zwischen Boden und niedrigstem LWC-Messpunkt ist der LWC-Gradient subadiabatisch mit beta = betaStatic
    l_LWC_adiab = adiabaticLWC(-lowestMeasuredAlt,cloudBaseTemp)
    l_LWC = (1-beta) * l_LWC_adiab + lowestMeasuredLWC
    
    # Inkrementieren durch das Profil:
    for alt in arange(cloudBase,cloudTop+zInc,zInc):
        # Festlegen von Variablen (u.a. betaCurrent) je nach Schicht:
        betaCurrent = 0.
        
        # Wenn wir uns im unteren Layer befinden:
        if alt <= boundary1:
            betaCurrent = beta * ((alt - cloudBase) / (boundary1 - cloudBase))
            LWC_adiab = adiabaticLWC(alt-cloudBase,cloudBaseTemp)
            LWC = (1-betaCurrent) * LWC_adiab + l_LWC # Eq. 4.43 (ohne Weg über mixing ratio), + l_LWC für Rechtsverschiebung
            
        # Wenn wir uns im mittleren Layer befinden:
        if (alt <= boundary2) and (alt > boundary1):
            betaCurrent = beta
            LWC_adiab = adiabaticLWC(alt-cloudBase,cloudBaseTemp)
            LWC = (1-betaCurrent) * LWC_adiab + l_LWC  # Eq. 4.43 (ohne Weg über mixing ratio), + l_LWC für Rechtsverschiebung
            
        # Wenn wir uns im oberen Layer befinden:
        if alt > boundary2:
            # Hier soll der LWC einfach nur linear abnehmen. D.h. es wird eine Gerade gebildet zwischen
            # 0 (Obergrenze) und LWC-Wert @ boundary2 und für die jeweilige Höhe der entsprechende Wert berechnet:
            LWC = (alt-cloudTop) / ((boundary2 - cloudTop) / ((1-beta) * adiabaticLWC(boundary2-cloudBase,cloudBaseTemp) + l_LWC)) # + l_LWC für Rechtsverschiebung
        
        Z = LWC/omega
        if Z>0:
            logZ = 10*(math.log10(Z))
        else:
            logZ = -999.
        LWCs.append(LWC)
        Zs.append(Z)
        alts.append(alt)
        logZs.append(logZ)

    finalList = zip(alts,LWCs,Zs,logZs)  
    return finalList
コード例 #31
0
ファイル: plots.py プロジェクト: martin1/thesis
def plot_price_volume(buy_prices, buy_volumes, sell_prices, sell_volumes, show_intersections=False):
    
    intersect_x = None
    intersect_y = None
    
    for i in range(0, len(buy_prices)):
        
        x_buy = [r for r in buy_volumes[i]]
        y_buy = [r for r in buy_prices[i]]
        x_sell = [r for r in sell_volumes[i]]
        y_sell = [r for r in sell_prices[i]]
        f_buy = lambda x: interp(x, x_buy, y_buy)
        f_sell = lambda x: interp(x, x_sell, y_sell)
        
        if show_intersections == True:
   
            intersect_x, intersect_y = get_intersection_point(x_buy, y_buy, x_sell, y_sell, time=str(times[i]))
            plt.plot(intersect_x, intersect_y, 'ko')
            
        plt.plot(x_buy, f_buy(x_buy), 'k-', label='Demand Curve')#, linewidth=0.2, markersize=0.1)
        plt.plot(x_sell, f_sell(x_sell), 'k--', label='Supply Curve')
        #plt.annotate(str(intersect_x[0])+ ' | ' + str(intersect_y[0]), xy=(intersect_x, intersect_y),
        #             xytext=(intersect_x-3000, intersect_y-100))
        #plt.plot(41500, 80.16, 'ro')
    plt.xlabel("MWh")
    plt.ylabel("EUR/MWh")
    plt.legend(loc='best')
    plt.ylim(-200, 2000)
    plt.yticks(arange(-200, 2000, 200.0))
    plt.grid(axis='y')
    plt.autoscale()
    plt.show()
コード例 #32
0
def diag_indices(n, ndim=2):
    """Return the indices to access the main diagonal of an array.

    This returns a tuple of indices that can be used to access the main
    diagonal of an array with ndim (>=2) dimensions and shape (n,n,...,n).  For
    ndim=2 this is the usual diagonal, for ndim>2 this is the set of indices
    to access A[i,i,...,i] for i=[0..n-1].

    Parameters
    ----------
    n : int
      The size, along each dimension, of the arrays for which the returned
      indices can be used.

    ndim : int, optional
      The number of dimensions.

    Notes
    -----
    .. versionadded:: 1.4.0

    See also
    --------
    diag_indices_from

    Examples
    --------
    Create a set of indices to access the diagonal of a (4,4) array:
    >>> di = diag_indices(4)

    >>> a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
    >>> a
    array([[ 1,  2,  3,  4],
           [ 5,  6,  7,  8],
           [ 9, 10, 11, 12],
           [13, 14, 15, 16]])
    >>> a[di] = 100
    >>> a
    array([[100,   2,   3,   4],
           [  5, 100,   7,   8],
           [  9,  10, 100,  12],
           [ 13,  14,  15, 100]])

    Now, we create indices to manipulate a 3-d array:
    >>> d3 = diag_indices(2,3)

    And use it to set the diagonal of a zeros array to 1:
    >>> a = zeros((2,2,2),int)
    >>> a[d3] = 1
    >>> a
    array([[[1, 0],
            [0, 0]],

           [[0, 0],
            [0, 1]]])

    """
    idx = arange(n)
    return (idx, ) * ndim
コード例 #33
0
def diag_indices(n, ndim=2):
    """Return the indices to access the main diagonal of an array.

    This returns a tuple of indices that can be used to access the main
    diagonal of an array with ndim (>=2) dimensions and shape (n,n,...,n).  For
    ndim=2 this is the usual diagonal, for ndim>2 this is the set of indices
    to access A[i,i,...,i] for i=[0..n-1].

    Parameters
    ----------
    n : int
      The size, along each dimension, of the arrays for which the returned
      indices can be used.

    ndim : int, optional
      The number of dimensions.

    Notes
    -----
    .. versionadded:: 1.4.0

    See also
    --------
    diag_indices_from

    Examples
    --------
    Create a set of indices to access the diagonal of a (4,4) array:
    >>> di = diag_indices(4)

    >>> a = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]])
    >>> a
    array([[ 1,  2,  3,  4],
           [ 5,  6,  7,  8],
           [ 9, 10, 11, 12],
           [13, 14, 15, 16]])
    >>> a[di] = 100
    >>> a
    array([[100,   2,   3,   4],
           [  5, 100,   7,   8],
           [  9,  10, 100,  12],
           [ 13,  14,  15, 100]])

    Now, we create indices to manipulate a 3-d array:
    >>> d3 = diag_indices(2,3)

    And use it to set the diagonal of a zeros array to 1:
    >>> a = zeros((2,2,2),int)
    >>> a[d3] = 1
    >>> a
    array([[[1, 0],
            [0, 0]],

           [[0, 0],
            [0, 1]]])

    """
    idx = arange(n)
    return (idx,) * ndim
コード例 #34
0
ファイル: function_base.py プロジェクト: alexxpan/python-art
def kaiser(M, beta):
    """kaiser(M, beta) returns a Kaiser window of length M with shape parameter
    beta.
    """
    from numpy.dual import i0
    n = arange(0, M)
    alpha = (M - 1) / 2.0
    return i0(beta * sqrt(1 - ((n - alpha) / alpha)**2.0)) / i0(beta)
コード例 #35
0
def kaiser(M,beta):
    """kaiser(M, beta) returns a Kaiser window of length M with shape parameter
    beta.
    """
    from numpy.dual import i0
    n = arange(0,M)
    alpha = (M-1)/2.0
    return i0(beta * sqrt(1-((n-alpha)/alpha)**2.0))/i0(beta)
コード例 #36
0
 def test_an_example_a(self):
     a = arange(15).reshape(3,5)
     self.assertEqual(a.shape, (3,5))
     self.assertEqual(a.ndim, 2)
     self.assertEqual(a.dtype.name, 'int64')
     self.assertEqual(a.itemsize, 8) # 64/8
     self.assertEqual(a.size, 15)
     self.assertEqual(type(a), numpy.ndarray)
コード例 #37
0
ファイル: tabu.py プロジェクト: homerobse/adaptiverl
 def __init__(self, agent):
     self.agent = agent
     self.lbdAllowed = zeros(self.agent.nLr, int)
     self.ngbhdSize = 2
     self.banThreshold = 8
     self.banNumber = 20
     self.sigma = 0.25**2
     self.neighborhood = arange(2 * self.ngbhdSize + 1)
コード例 #38
0
ファイル: InverseWomersley.py プロジェクト: myousefi2016/pyNS
    def GetTaoFromQ(self, el):
        '''
        Computing wall shear stress in terms of the flow rate,
        using inverse womersley method of Cezeaux et al.1997
        '''
        self.radius = mean(el.Radius)
        self.Res = el.R
        self.length = el.Length
        self.Name = el.Name

        #WOMERSLEY NUMBER
        self.alpha = self.radius * sqrt(
            (2.0 * pi * self.density) / (self.tPeriod * self.viscosity))

        #FOURIER SIGNAL
        k = len(self.signal)
        n = 0
        while n < (self.nHarmonics):
            An = 0
            Bn = 0
            for i in arange(k):
                An += self.signal[i] * cos(
                    n * (2.0 * pi / self.tPeriod) * self.dt * self.nSteps[i])
                Bn += self.signal[i] * sin(
                    n * (2.0 * pi / self.tPeriod) * self.dt * self.nSteps[i])
            An = An * (2.0 / k)
            Bn = Bn * (2.0 / k)
            self.fourierModes.append(complex(An, Bn))
            n += 1

        self.Steps = linspace(0, self.tPeriod, self.samples)
        self.WssSignal = []
        self.Tauplot = []

        for step in self.Steps:
            self.tao = -self.fourierModes[0].real * 2.0

            k = 1
            while k < self.nHarmonics:
                cI = complex(0., 1.)
                cA = (self.alpha * pow((1.0 * k), 0.5)) * pow(cI, 1.5)
                c1 = 2.0 * jn(1, cA)
                c0 = cA * jn(0, cA)
                cT = complex(0, -2.0 * pi * k * self.t / self.tPeriod)
                '''tao computation'''
                taoNum = self.alpha**2 * cI**3 * jn(1, cA)
                taoDen = c0 - c1
                taoFract = taoNum / taoDen
                cTao = self.fourierModes[k] * exp(cT) * taoFract
                self.tao += cTao.real
                k += 1

            self.tao *= -(self.viscosity / (self.radius**3 * pi))
            self.Tauplot.append(self.tao * 10)  #dynes/cm2
            self.WssSignal.append(self.tao)
            self.t += self.dtPlot

        return self.WssSignal  #Pascal
コード例 #39
0
def hamming(M):
    """hamming(M) returns the M-point Hamming window.
    """
    if M < 1:
        return array([])
    if M == 1:
        return ones(1,float)
    n = arange(0,M)
    return 0.54-0.46*cos(2.0*pi*n/(M-1))
コード例 #40
0
ファイル: InverseWomersley.py プロジェクト: myousefi2016/pyNS
 def SetFlowSignal(self, el, flowsig):
     '''
     Setting Flow Signal for specific mesh
     '''
     for sig in flowsig:
         self.signal.append(float(sig))  #flow in m3/s
     self.nSteps = arange(0, len(self.signal), 1)
     self.dt = self.tPeriod / (len(self.nSteps) - 1)
     self.dtPlot = self.tPeriod / self.samples
コード例 #41
0
ファイル: InverseWomersley.py プロジェクト: archTk/pyNS
 def SetFlowSignal(self, el, flowsig):
     '''
     Setting Flow Signal for specific mesh
     '''
     for sig in flowsig:
         self.signal.append(float(sig)) #flow in m3/s
     self.nSteps = arange(0,len(self.signal),1)
     self.dt = self.tPeriod/(len(self.nSteps)-1)
     self.dtPlot = self.tPeriod/self.samples
コード例 #42
0
ファイル: function_base.py プロジェクト: alexxpan/python-art
def hamming(M):
    """hamming(M) returns the M-point Hamming window.
    """
    if M < 1:
        return array([])
    if M == 1:
        return ones(1, float)
    n = arange(0, M)
    return 0.54 - 0.46 * cos(2.0 * pi * n / (M - 1))
コード例 #43
0
ファイル: function_base.py プロジェクト: jacr6/radicalspam
def bartlett(M):
    """bartlett(M) returns the M-point Bartlett window.
    """
    if M < 1:
        return array([])
    if M == 1:
        return ones(1, float)
    n = arange(0,M)
    return where(less_equal(n,(M-1)/2.0),2.0*n/(M-1),2.0-2.0*n/(M-1))
コード例 #44
0
 def __init__(self, *args, **kwds):
     NumpyTestCase.__init__(self, *args, **kwds)
     self.data = numeric.arange(25)
     self.maskeddata = MaskedArray(self.data)
     self.maskeddata[10] = masked
     self.func_pairs = [
         (MF.mov_average, MA.mean),
         (MF.mov_median, mstats.mmedian),
         ((lambda x, span : MF.mov_stddev(x, span, bias=True)), MA.std)]
コード例 #45
0
ファイル: function_base.py プロジェクト: jacr6/radicalspam
def blackman(M):
    """blackman(M) returns the M-point Blackman window.
    """
    if M < 1:
        return array([])
    if M == 1:
        return ones(1, float)
    n = arange(0,M)
    return 0.42-0.5*cos(2.0*pi*n/(M-1)) + 0.08*cos(4.0*pi*n/(M-1))
コード例 #46
0
ファイル: twodim_base.py プロジェクト: alexxpan/python-art
def diagflat(v, k=0):
    try:
        wrap = v.__array_wrap__
    except AttributeError:
        wrap = None
    v = asarray(v).ravel()
    s = len(v)
    n = s + abs(k)
    res = zeros((n, n), v.dtype)
    if (k >= 0):
        i = arange(0, n - k)
        fi = i + k + i * n
    else:
        i = arange(0, n + k)
        fi = i + (i - k) * n
    res.flat[fi] = v
    if not wrap:
        return res
    return wrap(res)
コード例 #47
0
def eye(N, M=None, k=0, dtype=float):
    """
    Return a 2-D array with ones on the diagonal and zeros elsewhere.

    Parameters
    ----------
    N : int
      Number of rows in the output.
    M : int, optional
      Number of columns in the output. If None, defaults to `N`.
    k : int, optional
      Index of the diagonal: 0 refers to the main diagonal, a positive value
      refers to an upper diagonal, and a negative value to a lower diagonal.
    dtype : dtype, optional
      Data-type of the returned array.

    Returns
    -------
    I : ndarray (N,M)
      An array where all elements are equal to zero, except for the `k`-th
      diagonal, whose values are equal to one.

    See Also
    --------
    diag : Return a diagonal 2-D array using a 1-D array specified by the user.

    Examples
    --------
    >>> np.eye(2, dtype=int)
    array([[1, 0],
           [0, 1]])
    >>> np.eye(3, k=1)
    array([[ 0.,  1.,  0.],
           [ 0.,  0.,  1.],
           [ 0.,  0.,  0.]])

    """
    if M is None: M = N
    m = equal(subtract.outer(arange(N), arange(M)),-k)
    if m.dtype != dtype:
        m = m.astype(dtype)
    return m
コード例 #48
0
def tri(N, M=None, k=0, dtype=float):
    """
    Construct an array filled with ones at and below the given diagonal.

    Parameters
    ----------
    N : int
        Number of rows in the array.
    M : int, optional
        Number of columns in the array.
        By default, `M` is taken equal to `N`.
    k : int, optional
        The sub-diagonal below which the array is filled.
        `k` = 0 is the main diagonal, while `k` < 0 is below it,
        and `k` > 0 is above.  The default is 0.
    dtype : dtype, optional
        Data type of the returned array.  The default is float.

    Returns
    -------
    T : (N,M) ndarray
        Array with a lower triangle filled with ones, in other words
        ``T[i,j] == 1`` for ``i <= j + k``.

    Examples
    --------
    >>> np.tri(3, 5, 2, dtype=int)
    array([[1, 1, 1, 0, 0],
           [1, 1, 1, 1, 0],
           [1, 1, 1, 1, 1]])

    >>> np.tri(3, 5, -1)
    array([[ 0.,  0.,  0.,  0.,  0.],
           [ 1.,  0.,  0.,  0.,  0.],
           [ 1.,  1.,  0.,  0.,  0.]])

    """
    if M is None: M = N
    m = greater_equal(subtract.outer(arange(N), arange(M)),-k)
    return m.astype(dtype)
コード例 #49
0
ファイル: geometry.py プロジェクト: qenops/dOptimize
def mvpolyval1d(p, val, axis=0):
    # ToDo: need to switch to Horner's method
    # why would we ever need to do this?
    truepoly = isinstance(p, poly2d)
    p = NX.asarray(p)
    o = p.shape[axis]
    o = np.reshape(np.power(val,NX.arange(o, 0, -1)-1),(-1,1))
    o = o if axis == 0 else o.T
    p = p * o
    y = np.sum(p,axis-1)
    if truepoly:
        y = poly1d(y)
    return y
コード例 #50
0
ファイル: function_base.py プロジェクト: jacr6/radicalspam
def linspace(start, stop, num=50, endpoint=True, retstep=False):
    """Return evenly spaced numbers.

    Return num evenly spaced samples from start to stop.  If
    endpoint is True, the last sample is stop. If retstep is
    True then return the step value used.
    """
    num = int(num)
    if num <= 0:
        return array([], float)
    if endpoint:
        if num == 1:
            return array([float(start)])
        step = (stop-start)/float((num-1))
        y = _nx.arange(0, num) * step + start
        y[-1] = stop
    else:
        step = (stop-start)/float(num)
        y = _nx.arange(0, num) * step + start
    if retstep:
        return y, step
    else:
        return y
コード例 #51
0
    def visualize_trans_probs(self, lyricsWithModels, fromFrame, toFrame,
                              from_phoneme, to_phoneme):
        '''
        forced alignment: considers only previous state in desicion
        '''

        lenObs = numpy.shape(self.B_map)[1]
        tmpOnsetProbArray = numpy.zeros(
            (to_phoneme - from_phoneme + 1, lenObs))

        # viterbi loop
        #         for t in xrange(1,lenObs):
        for t in xrange(fromFrame, toFrame):
            self.logger.debug("at time {} out of {}".format(t, lenObs))

            if ParametersAlgo.WITH_ORACLE_ONSETS == -1:
                whichMatrix = -1  # last matrix with no onset
            else:
                # distance of how many frames from closest onset
                onsetDist, _ = getDistFromEvent(self.noteOnsets, t)
                whichMatrix = min(ParametersAlgo.ONSET_SIGMA_IN_FRAMES + 1,
                                  onsetDist)
                self.logger.debug("which Matrix: " + str(whichMatrix))

            for j in xrange(from_phoneme, to_phoneme + 1):
                if j > 0:
                    a = self.transMatrices[whichMatrix][j - 1, j]
                    tmpOnsetProbArray[j - from_phoneme,
                                      t] = a  # because of indexing

#             visualizeMatrix(tmpOnsetProbArray, 'titleName')

        matplotlib.rcParams['figure.figsize'] = (20, 8)
        visualizeMatrix(tmpOnsetProbArray[:, fromFrame:toFrame], '')

        ###### add vertical legend names
        statesNetworkNames = []
        for i in range(from_phoneme, to_phoneme + 1):
            stateWithDur = lyricsWithModels.statesNetwork[i]
            stateWithDurPrev = lyricsWithModels.statesNetwork[i - 1]
            statesNetworkNames.append("{} -> {}".format(
                stateWithDurPrev.phoneme.ID, stateWithDur.phoneme.ID))

        import matplotlib.pyplot as plt
        from numpy.core.numeric import arange
        plt.yticks(arange(len(statesNetworkNames)), statesNetworkNames)
        plt.show()
コード例 #52
0
ファイル: polynomial.py プロジェクト: lisarosalina/App
def polyder(p, m=1):
    """Return the mth derivative of the polynomial p.
    """
    m = int(m)
    truepoly = isinstance(p, poly1d)
    p = NX.asarray(p)
    n = len(p)-1
    y = p[:-1] * NX.arange(n, 0, -1)
    if m < 0:
        raise ValueError, "Order of derivative must be positive (see polyint)"
    if m == 0:
        return p
    else:
        val = polyder(y, m-1)
        if truepoly:
            val = poly1d(val)
        return val
コード例 #53
0
ファイル: dataset.py プロジェクト: pirenea-irap/sofa
    def hann(self, signal, half=False):
        """
        Apply a Hann windowing on raw signal, before FFT.

        """
        points = len(signal)

        # Hanning from Herschel (half window)"""
        # hann = 0.5 * (1.0 + cos ((PI*i) / channels))"""
        if half:
            iarr = num.arange(points) * math.pi / points
            iarr = 0.5 + 0.5 * math.cos(iarr)
        # Hanning from numpy (full window)"""
        else:
            iarr = np.hanning(points)
        hann = signal * iarr

        return hann
コード例 #54
0
def boxplotProbabilities(prob,nv, lbdMean):
   '''
   DEFINITION: makes a boxplot of the mean (within an episode) learning rates for different probabilities and a given volatility  
   INPUTS:
   prob: probabilities array
   nv: given volatility (you have to know what the indexes in lbdMean mean in terms of volatility e.g. 1 would mean volatility .005 if the simulation was done with vol=[.001 .005])
   TODO - think of a way of how not to depend on knowing beforehand of how the simulation was done 
   lbdMean: array with the mean chosen learning rate in an episode. lbdMean is indexed [p,v,e]
   '''
   l=[]
   for p in xrange(len(prob)):
      l.append(lbdMean[p,nv,:])
   figure()
   boxplot(l)
   pylab.xticks(range(1,len(prob)+1), prob)
   xlabel('Reward probability')
   ylabel('Average learning rate lambda')
   title('Average learning rates distributions for v='+str(vol[nv]))
   plot(arange(0,5),'x')
コード例 #55
0
def showQValues2(lrAgent, spFactor=1):
    '''Colorplot for the QValues'''
    figure()
    title('Q-values over the trials')
    dlbd = lrAgent.lbd[1] - lrAgent.lbd[0]
    ny, nx = shape(lrAgent.x)
    last = lrAgent.lbd[-1] + dlbd
    X = r_[
        lrAgent.lbd,
        last]  #watch out with this limit here "last" (pcolor doesn't show the last column)
    Y = arange(ny / spFactor + 1)

    sample = array([i % spFactor == 0 for i in xrange(ny)])
    Z = lrAgent.x[sample]
    pcolor(X, Y, Z)
    colorbar()
    axis([lrAgent.lbd[0], last, 0, ny / spFactor + 1])
    xlabel('Learning rates')
    ylabel('Trials')
コード例 #56
0
def _make_along_axis_idx(arr_shape, indices, axis):
    # compute dimensions to iterate over
    if not _nx.issubdtype(indices.dtype, _nx.integer):
        raise IndexError("`indices` must be an integer array")
    if len(arr_shape) != indices.ndim:
        raise ValueError("`indices` and `arr` must have the same number of dimensions")
    shape_ones = (1,) * indices.ndim
    dest_dims = list(range(axis)) + [None] + list(range(axis + 1, indices.ndim))

    # build a fancy index, consisting of orthogonal aranges, with the
    # requested index inserted at the right location
    fancy_index = []
    for dim, n in zip(dest_dims, arr_shape):
        if dim is None:
            fancy_index.append(indices)
        else:
            ind_shape = shape_ones[:dim] + (-1,) + shape_ones[dim + 1 :]
            fancy_index.append(_nx.arange(n).reshape(ind_shape))

    return tuple(fancy_index)