Example #1
0
def nancorr2(x, y, w):
    '''nancorr2(x, y, w):
    input is master and slave complex images (tested for 1D only)
    w is the calculation window.
    '''
    import scipy
    scipy.pkgload('signal')

    w = array(w)
    cor = zeros(x.shape)
    Ex = empty(x.shape)
    Ey = empty(y.shape)
    for k, l in ((k, l) for k in range(x.shape[0]) for l in range(x.shape[1])):
        idx = [(kk, ll) for kk in range(k - w[0], k + w[0])
               for ll in range(l - w[1], l + w[1])]
        vidx = validIndex(x.shape, idx)
        Ex[k, l] = nonan(x[vidx[:, 0], vidx[:, 1]]).mean()
        Ey[k, l] = nonan(y[vidx[:, 0], vidx[:, 1]]).mean()

    corrFilter = ones(2 * w + 1)
    nfilt = corrFilter.size
    corrFilter = corrFilter / nfilt
    #Ex=scipy.signal.signaltools.correlate(x, corrFilter, mode='same')
    #Ey=scipy.signal.signaltools.correlate(y, corrFilter, mode='same')
    cor = scipy.signal.signaltools.correlate((x - Ex) * (y - Ey) / sqrt(
        (x - Ex)**2 * (y - Ey)**2),
                                             corrFilter,
                                             mode='same')
    return cor
Example #2
0
def nancorr2(x,y,w):
    '''nancorr2(x, y, w):
    input is master and slave complex images (tested for 1D only)
    w is the calculation window.
    '''        
    import scipy
    scipy.pkgload('signal')
    
    w=array(w);
    cor=zeros(x.shape)
    Ex=empty(x.shape)
    Ey=empty(y.shape)
    for k,l in ( (k,l) for k in range(x.shape[0]) for l in range(x.shape[1]) ):
        idx=[ (kk,ll) for kk in range(k-w[0],k+w[0]) for ll in range(l-w[1], l+w[1]) ]
        vidx=validIndex(x.shape, idx);
        Ex[k,l]=nonan(x[vidx[:,0],vidx[:,1]]).mean()
        Ey[k,l]=nonan(y[vidx[:,0],vidx[:,1]]).mean()
    

    corrFilter= ones(2*w+1)
    nfilt=corrFilter.size
    corrFilter=corrFilter/nfilt
    #Ex=scipy.signal.signaltools.correlate(x, corrFilter, mode='same')
    #Ey=scipy.signal.signaltools.correlate(y, corrFilter, mode='same')
    cor=scipy.signal.signaltools.correlate((x-Ex)*(y-Ey)/sqrt((x-Ex)**2*(y-Ey)**2), corrFilter, mode='same')
    return cor
Example #3
0
def r_squared(predictions, targets):
    """r_squared(predictions, targets)
  """
    import scipy
    scipy.pkgload('stats')
    slope, intercept, r_value, p_value, std_err = scipy.stats.linregress(
        predictions, targets)
    return r_value**2.
Example #4
0
def corr2(x,y,w):
    '''correlate(x, y, w):
    input is master and slave complex images (tested for 1D only)
    w is the calculation window.
    '''        
    import scipy
    scipy.pkgload('signal')
    
    cor=zeros(size(x))
    corrFilter= ones(w)
    nfilt=corrFilter.size
    corrFilter=corrFilter/nfilt
#    Em=scipy.ndimage.filters.correlate(m*conj(m),corrFilter,mode='nearest')
#    Es=scipy.ndimage.filters.correlate(s*conj(s),corrFilter,mode='nearest')
#    Ems=scipy.ndimage.filters.correlate(m*conj(s),corrFilter,mode='nearest')
    Ex=scipy.signal.signaltools.correlate(x, corrFilter, mode='same')
    Ey=scipy.signal.signaltools.correlate(y, corrFilter, mode='same')
    cor=scipy.signal.signaltools.correlate((x-Ex)*(y-Ey)/sqrt((x-Ex)**2*(y-Ey)**2), corrFilter, mode='same')
    #Vy=scipy.signal.signaltools.correlate((y-Ey)**2, corrFilter, mode='same')
    #cor=abs( (x-Ex)*(y-Ey) / sqrt(Vx*Vy) )
    return cor
Example #5
0
def corr2(x, y, w):
    '''correlate(x, y, w):
    input is master and slave complex images (tested for 1D only)
    w is the calculation window.
    '''
    import scipy
    scipy.pkgload('signal')

    cor = zeros(size(x))
    corrFilter = ones(w)
    nfilt = corrFilter.size
    corrFilter = corrFilter / nfilt
    #    Em=scipy.ndimage.filters.correlate(m*conj(m),corrFilter,mode='nearest')
    #    Es=scipy.ndimage.filters.correlate(s*conj(s),corrFilter,mode='nearest')
    #    Ems=scipy.ndimage.filters.correlate(m*conj(s),corrFilter,mode='nearest')
    Ex = scipy.signal.signaltools.correlate(x, corrFilter, mode='same')
    Ey = scipy.signal.signaltools.correlate(y, corrFilter, mode='same')
    cor = scipy.signal.signaltools.correlate((x - Ex) * (y - Ey) / sqrt(
        (x - Ex)**2 * (y - Ey)**2),
                                             corrFilter,
                                             mode='same')
    #Vy=scipy.signal.signaltools.correlate((y-Ey)**2, corrFilter, mode='same')
    #cor=abs( (x-Ex)*(y-Ey) / sqrt(Vx*Vy) )
    return cor
Example #6
0
  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""

import time
import numpy as np
import scipy
if scipy.__version__[2] == 7:
    # scipy.pkgload('signal')
    scipy.pkgload('ndimage')
    scipy.pkgload('fftpack')
else:
    from scipy.fftpack import fftn, ifftn, fftshift, ifftshift
    from scipy import ndimage
    # from scipy import signal

# import reikna.cluda as cl
# from reikna.cluda import dtypes, any_api
# from reikna.fft import FFT
# from reikna.core import Annotation, Type, Transformation, Parameter
from pyfft.cl import Plan
import pyopencl as cl
import pyopencl.array as cl_array

Example #7
0
# Set your PYTHONSTARTUP environment variable to $HOME/.pythonrc.py
#
# inspired by:
# http://opag.ca/wiki/OpagCode/OpagSnippets

# Import Numpy and SciPy
try:
    import numpy as np
    import scipy as sp
    sp.pkgload()
except ImportError:
    pass

# Import PyQt4.Qt and PyQt4.Qwt5; initialize an application.
# Note: hides the builtins hex and oct.
try:
    from qt import *
    from Qwt5 import *
    from Qwt5.qplt import *
    application = QApplication([])
except ImportError:
    application = None

# Setup readline and history saving
from atexit import register
from os import path
import readline
import rlcompleter

# Set up a tab for completion; use a single space to indent Python code.
readline.parse_and_bind('tab: complete')
Example #8
0
from numpy import *
from helpers import virtualWarning
import scipy

scipy.pkgload('ndimage')
import pdb
from scipy.interpolate import interp1d


def regularize2d(x, y, z, n, nCut=(-1, -1)):
    """
    where x is has z.shape[0], y has z.shape[1] and form an an irregular mesh of z, 
    resample z on a regular mesh having dimensions given in n
    """
    assert z.ndim == 2, 'z must have only 2 dimensions!'
    xReg = linspace(x[0], x[nCut[0] - 1], n[0])
    yReg = linspace(y[0], y[nCut[1] - 1], n[1])

    zRegx = zeros((z[:nCut[0]].shape[0], n[1]))
    zReg = zeros(n)

    pol = lambda x_, z_, xi: interp1d(x_, z_, kind='cubic')(xi)

    for i in range(zRegx.shape[0]):
        zRegx[i] = pol(y, z[i], yReg)

    for j in range(zRegx.shape[1]):
        zReg[:, j] = pol(x[:nCut[0]], zRegx[:, j], xReg)

    return (xReg, yReg, zReg)
Example #9
0
from __future__ import division

# Import Numpy and SciPy
try:
    import numpy as np
    import scipy as sp
    sp.pkgload(#'cluster',
               'constants',
               'fftpack',
               'integrate',
               'interpolate',
               #'io',
               'linalg',
               'misc',
               'ndimage',
               'odr',
               'optimize',
               #'signal',
               #'sparse',
               #'spatial',
               'special',
               #'stats',
               #'stsci',
               #'weave',
               )
except ImportError:
    pass

# Import PyQt4.Qt and PyQt4.Qwt5; initialize an application.
# Note: hides the builtins hex and oct.
try:
Example #10
0
import os 
import scipy
scipy.pkgload('io')
from numpy import *
import numpy as np
import cPickle as pkl
import time
from pylab import *
from plotMacros import *
import mlabMacros as mlm

outputDir = "D:\\00PLASMA_DATA\\trellesTorch"
tName = 'trellesTorch_'
VAR = 'Th'
N = 500
compute = False
if compute:
	with open(os.path.join(outputDir,tName+VAR+'.pkl'),'rb') as f:
		D = pkl.load(f)

	y = D['y'][:N].copy()
	t = D['t'][:N].copy()
	del D

	yBar = np.mean(y,axis = 0)
	y-= yBar

	U,s,Vh = linalg.svd(y, full_matrices = False)
	with open(os.path.join(outputDir,tName+VAR+'_svd_%d.pkl'%N),'wb') as f:
		pkl.dump(dict(zip(['U','s','Vh'],[U,s,Vh])), f, -1)
else:
Example #11
0
#!/usr/bin/env python
import tables, scipy, optparse, os, sys
scipy.pkgload('io')

__revision__ = "$Id: h5tomat.py 3152 2006-09-29 10:26:22Z pauli $"

def main():
    parser = optparse.OptionParser(usage="%prog infile.h5 [outdir]")
    (options, args) = parser.parse_args()

    if len(args) < 1 or len(args) > 2:
        parser.error("Wrong number of arguments")

    infile = args[0]
    if len(args) > 1:
        outdir = args[1]
    else:
        outdir = os.path.splitext(infile)[0] + '.mat'

    f = None
    try:
        # Open
        
        try:
            f = tables.openFile(infile, 'r')
        except IOError, err:
            print err
            raise SystemExit(1)

        # Convert
Example #12
0
# Sets up history saving on exit.
def save_history(historyPath=historyPath, readline=readline):
    readline.write_history_file(historyPath)


register(save_history)

# Cleans up the global name
del register, path, readline, rlcompleter, historyPath, save_history

# Tries to import NumPy  and SciPy
try:
    import numpy as np
    import scipy as sp
    sp.pkgload()
except ImportError:
    pass

# Tries to import qt, Qwt4.iqt, Qwt4.Qwt and Qwt4.qplt
try:
    import qt
    import Qwt4.iqt
    import Qwt4.Qwt as qwt
    import Qwt4.qplt as qplt
except ImportError:
    pass

# Local Variables: ***
# mode: python ***
# End: ***
Example #13
0
  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""

# import numpy
import numpy as np
import scipy
if scipy.__version__[2] == 7:
    scipy.pkgload('signal')
    scipy.pkgload('ndimage')
    # scipy.pkgload('fftpack')
else:
    # from scipy.fftpack import fftn, ifftn, fftshift, ifftshift
    from scipy.ndimage.filters import gaussian_filter, gaussian_laplace, median_filter, laplace
    from scipy.signal import wiener
    from scipy import ndimage
    # from scipy import signal


def cplxgaussian_filter(real_input,
                        imag_input,
                        sigma=0.707,
                        order_=0,
                        mode_='nearest',
from __future__ import division

# Import Numpy and SciPy
try:
    import numpy as np
    import scipy as sp
    sp.pkgload(  #'cluster',
        'constants',
        'fftpack',
        'integrate',
        'interpolate',
        #'io',
        'linalg',
        'misc',
        'ndimage',
        'odr',
        'optimize',
        #'signal',
        #'sparse',
        #'spatial',
        'special',
        #'stats',
        #'stsci',
        #'weave',
    )
except ImportError:
    pass

# Import PyQt4.Qt and PyQt4.Qwt5; initialize an application.
# Note: hides the builtins hex and oct.
try:
Example #15
0
                If not 0, Delta is assumed to have the same temperature
                dependence as in bulk.
    omega_D     Debye temperature [Kelvin]
                Needed only if Delta is T-dependent.
    n_E         Number of energy discretization points [Default=500]

The progam then prints the corresponding temperature-dependence of
supercurrent.
"""
from __future__ import division
import usadel1 as u
import sys
import re
import scipy as S
import traceback
S.pkgload('integrate', 'optimize')

__revision__ = "$Id: singlewire.py 3152 2006-09-29 10:26:22Z pauli $"

ec = 1.60217733e-19
"""Electron charge       ec = 1.60217733e-19             [C]"""
Rgas = 8.31451
"""Ideal gas constant    R = 8.31451                     [J / K * mol]"""
N_A = 6.0221367e23
"""Avogadro's number     N_A = 6.0221367e23              [1]"""
k_B = Rgas / N_A
"""Boltzmann's constant  k_B = Rgas/N_A = 1.380658e-23   [J / K]"""
EulerGamma = 0.577215664901532860606512090083
"""Euler's Gamma"""

Example #16
0
Ben Herbst - U. Stellenbosch.
Fernando Perez - U. Colorado, Boulder."""

# Required packages

# Std lib
import os

# Third-party
import pylab as P
import numpy as N
import scipy as S

# Scipy has a special loading mechanism to import multiple subpackages into
# its own namespace for convenience
S.pkgload('linalg')

# Classes and functions begin
def imshow2(m1,m2,labels=(None,None)):
    """Display two images side by side.

    Returns the created figure instance."""

    fig = P.figure()
    ax1 = [0.025,0.1,0.45,0.775]
    ax2 = [0.525,0.1,0.45,0.775]
    for m,ax_coord,label in [(m1,ax1,labels[0]),(m2,ax2,labels[1])]:
        ax = fig.add_axes(ax_coord)
        ax.imshow(m,cmap=P.cm.gray)
        if label:
            ax.set_xlabel(label)
Example #17
0
#define some helpers for python 
import numpy as np
from numpy import *
rfft = fft.rfft
irfft = fft.irfft
fftshift = fft.fftshift
import scipy
scipy.pkgload()
import pdb

def ngrid(X):
    """
    like meshgrid for n dimensions
    X is an n-tuple of e.g. (x,y,z) points to arrange in mesh
    """
    G = ones((len(X),)+tuple([x.shape[0] for x in X]))
    for i in range(len(X)):
        sly = []
        for j in range(len(X)):
            if j==i:
                sly+= [slice(None)]
            else:
                sly+=[newaxis]    
                
        G[i] *=  X[i][sly]
    return G

def grid2idx(g):
    idx = zeros_like(g[0])
    rg = array(g.shape)[1:]
    gPrime = array([g[i]-amin(g[i]) for i in range(g.shape[0])])
Example #18
0
import numpy as np
from numpy import *
import scipy
scipy.pkgload('weave')
from scipy import weave
import cPickle as pkl
import time
import pdb
from pylab import *
import particle as part
import sensor as sens
import particleModelEnsemble as pmEns
from plotMacros import *
import mlabMacros as mlm
from interpolators import zerothOrderInterpolator

def alignArrays(master, slave, tol):
    """
    match each element of master to the nearest element of slave within a distance tol of 
    the master element. elements of master that are not matched are discarded
    
    return the matched 
    """
    
    
    mIdx = []
    sIdx = []
    J = 0
    
    for i in range(master.shape[0]):
        theMin = -1