Ejemplo n.º 1
0
def filtfilt(b, a, x):
    #For now only accepting 1d arrays
    ntaps = max(len(a), len(b))
    edge = ntaps * 3

    if x.ndim != 1:
        raise ValueError, "Filiflit is only accepting 1 dimension arrays."

    #x must be bigger than edge
    if x.size < edge:
        raise ValueError, "Input vector needs to be bigger than 3 * max(len(a),len(b)."

    if len(a) < ntaps:
        a = pylab.r_[a, zeros(len(b) - len(a))]

    if len(b) < ntaps:
        b = pylab.r_[b, zeros(len(a) - len(b))]

    zi = lfilter_zi(b, a)

    #Grow the signal to have edges for stabilizing
    #the filter with inverted replicas of the signal
    s = pylab.r_[2 * x[0] - x[edge:1:-1], x, 2 * x[-1] - x[-1:-edge:-1]]
    #in the case of one go we only need one of the extrems
    # both are needed for filtfilt

    (y, zf) = ss.lfilter(b, a, s, -1, zi * s[0])

    (y, zf) = ss.lfilter(b, a, pylab.flipud(y), -1, zi * y[-1])

    return pylab.flipud(y[edge - 1:-edge + 1])
Ejemplo n.º 2
0
    def pcolor(self, mode="mean", vmin=None, vmax=None):
        """

        If you loaded the pickle data sets with only mean and sigma, the D and
        pvalue mode cannot be used.

        """
        from pylab import clf, xticks, yticks, pcolor, colorbar, flipud, log10
        if mode == "mean":
            data = self.get_mean()
        elif mode == "sigma":
            data = self.get_sigma()
        elif mode == "D":
            data = self.get_ks()[0]
        elif mode == "pvalue":
            data = self.get_ks()[1]
        clf();

        if mode == "pvalue":
            pcolor(log10(flipud(data)), vmin=vmin, vmax=vmax);
        else:
            pcolor(flipud(data), vmin=vmin,vmax=vmax);

        colorbar()
        xticks([x+0.5 for x in range(0,8)], self.ligands, rotation=90)
        cellLines = self.cellLines[:]
        cellLines.reverse()
        yticks([x+0.5 for x in range(0,4)], cellLines, rotation=0)
Ejemplo n.º 3
0
def showVectorDisplacements():

    global testImage, croppedRefImage, u, v, valid, q1, umean, vmean, x, y, sxyVar, wxyVar, goodvectorsVar
    from scipy import where, compress, logical_and, median, logical_or, nan
    from pylab import resize, transpose, quiver, title, show, find, imshow, hist, figure, clf, draw, save, load, xlabel, ylabel, flipud

    mxy = 3
    wxy = int(wxyVar.get())
    sxy = int(sxyVar.get())
    goodvectors = float(goodvectorsVar.get())
    #process to find PIV-style displacements
    x, y, u, v, q1, valid = simplepiv(croppedRefImage, testImage, wxy, mxy,
                                      sxy)
    good = where(logical_and(q1 > goodvectors, valid > 0), True, False)
    umean = median(compress(good.flat, u.flat))
    vmean = median(compress(good.flat, v.flat))
    u = where(logical_or(q1 < goodvectors, valid < 0), 0, u)
    v = where(logical_or(q1 < goodvectors, valid < 0), 0, v)
    u = u - umean
    v = v - vmean
    save('vecx.out', x)
    save('vecy.out', y)
    save('vecu.out', u)
    save('vecv.out', v)
    save('vecq1.out', q1)
    save('vecvalid.out', valid)
    u = flipud(u)
    v = -flipud(v)
    quiver(x, y, u, v)
    title('Vector displacements')
    xlabel('Pixels')
    ylabel('Pixels')
    show()
    return
Ejemplo n.º 4
0
def filtfilt(b,a,x):
    #For now only accepting 1d arrays
    ntaps=max(len(a),len(b))
    edge=ntaps*3

    if x.ndim != 1:
        raise ValueError, "Filiflit is only accepting 1 dimension arrays."

    #x must be bigger than edge
    if x.size < edge:
        raise ValueError, "Input vector needs to be bigger than 3 * max(len(a),len(b)."

    if len(a) < ntaps:
        a=pylab.r_[a,zeros(len(b)-len(a))]

    if len(b) < ntaps:
        b=pylab.r_[b,zeros(len(a)-len(b))]

    zi=lfilter_zi(b,a)

    #Grow the signal to have edges for stabilizing 
    #the filter with inverted replicas of the signal
    s=pylab.r_[2*x[0]-x[edge:1:-1],x,2*x[-1]-x[-1:-edge:-1]]
    #in the case of one go we only need one of the extrems 
    # both are needed for filtfilt

    (y,zf)=ss.lfilter(b,a,s,-1,zi*s[0])

    (y,zf)=ss.lfilter(b,a,pylab.flipud(y),-1,zi*y[-1])

    return pylab.flipud(y[edge-1:-edge+1])
Ejemplo n.º 5
0
    def pcolor(self, mode="mean", vmin=None, vmax=None):
        """

        If you loaded the pickle data sets with only mean and sigma, the D and
        pvalue mode cannot be used.

        """
        from pylab import clf, xticks, yticks, pcolor, colorbar, flipud, log10
        if mode == "mean":
            data = self.get_mean()
        elif mode == "sigma":
            data = self.get_sigma()
        elif mode == "D":
            data = self.get_ks()[0]
        elif mode == "pvalue":
            data = self.get_ks()[1]
        clf();

        if mode == "pvalue":
            pcolor(log10(flipud(data)), vmin=vmin, vmax=vmax);
        else:
            pcolor(flipud(data), vmin=vmin,vmax=vmax);

        colorbar()
        xticks([x+0.5 for x in range(0,8)], self.ligands, rotation=90)
        cellLines = self.cellLines[:]
        cellLines.reverse()
        yticks([x+0.5 for x in range(0,4)], cellLines, rotation=0)
Ejemplo n.º 6
0
def fft_based(input_signal, filter_coefficients, boundary=0):
    """applied fft if the signal is too short to be splitted in windows
    Params :
        input_signal : the audio signal
        filter_coefficients : coefficients of the chirplet bank
        boundary : manage the bounds of the signal
    Returns :
        audio signal with application of fast Fourier transform
    """
    num_coeffs = filter_coefficients.size
    half_size = num_coeffs//2

    if boundary == 0:#ZERO PADDING
        input_signal = np.lib.pad(input_signal, (half_size, half_size), 'constant', constant_values=0)
        filter_coefficients = np.lib.pad(filter_coefficients, (0, input_signal.size-num_coeffs), 'constant', constant_values=0)
        newx = ifft(fft(input_signal)*fft(filter_coefficients))
        return newx[num_coeffs-1:-1]

    elif boundary == 1:#symmetric
        input_signal = concatenate([flipud(input_signal[:half_size]), input_signal, flipud(input_signal[half_size:])])
        filter_coefficients = np.lib.pad(filter_coefficients, (0, input_signal.size-num_coeffs), 'constant', constant_values=0)
        newx = ifft(fft(input_signal)*fft(filter_coefficients))
        return newx[num_coeffs-1:-1]

    else:#periodic
        return roll(ifft(fft(input_signal)*fft(filter_coefficients, input_signal.size)), -half_size).real
Ejemplo n.º 7
0
def postprocessCpData(data,geo,newxcount):
    x = data[:,0]
    y = geo[:,1]
    Cp = data[:,1]
 
    n = data.shape[0]
 
    # compute finite difference of x to classify points as upper and lower airfoil surface
    dx = pl.diff(x)
    dy = pl.diff(y)
    L = pl.sqrt(dx**2+dy**2)
    Tx = dx/L
    Ty = dy/L
    Nx = -Ty
    Ny = +Tx
    T = pl.array((Tx,Ty))
    T = T.transpose()
    N = pl.array((Nx,Ny))
    N = N.transpose()
 
    midx = (x[0:n-1]+x[1:n])/2.0
    midy = (y[0:n-1]+y[1:n])/2.0
    midcp = (Cp[0:n-1]+Cp[1:n])/2.0
 
    Tnode = pl.zeros( (n,2), pl.float64)
    Nnode = pl.zeros( (n,2), pl.float64)
    for i in range(1,n-1):
        Tnode[i,:] = bisector( T[i-1,:], T[i,:] )
        Nnode[i,:] = bisector( N[i-1,:], N[i,:] )
    Tnode[0,:] = bisector( T[0,:], T[-1,:] )
    Tnode[-1,:] = bisector( T[0,:], T[-1,:] )
    Nnode[0,:] = bisector( N[i-1,:], N[i,:] )
    Nnode[-1,:] = bisector( N[i-1,:], N[i,:] )
 
    # determine (safe) limits of x for interpolation
    xmin = min( min(x[dx<0]),min(x[dx>=0]) )
    xmax = max( max(x[dx<0]),max(x[dx>=0]) )
 
    # re-compute lower and upper Cp at new abscissae
    if ChebyshevSpacing:
        xnew = pl.linspace(pl.pi, 0, newxcount)
        xnew = (pl.cos(xnew)+1)/2.0
    else:
        xnew = pl.linspace(xmin, xmax, newxcount)
 
    newCpUpper = pl.interp(xnew, pl.flipud(x[dx<0]), pl.flipud(Cp[dx<0]))     
    newCpLower = pl.interp(xnew, x[dx>=0], Cp[dx>=0])
 
    return (x,y,Cp,L,T,N,midx,midy,midcp,Tnode,Nnode,xnew,newCpUpper,newCpLower)
Ejemplo n.º 8
0
    def plot(self):
        """
        
        .. plot::
            :include-source:
            :width: 80%
            
            from cellnopt.simulate import *
            from cellnopt.core import *
            pkn = cnodata("PKN-ToyPB.sif")
            midas = cnodata("MD-ToyPB.csv")
            s = boolean.BooleanSimulator(CNOGraph(pkn, midas))
            s.simulate(30)
            s.plot()
        """
        
        pylab.clf()

        data = numpy.array([self.data[x] for x in self.species if x in self.species])
        data = data.transpose()
        data = 1 - pylab.flipud(data)

        pylab.pcolor(data, vmin=0, vmax=1, edgecolors="k")
        pylab.xlabel("species"); 
        pylab.ylabel("Time (tick)");
        pylab.gray()

        pylab.xticks([0.5+x for x in range(0,30)], self.species, rotation=90)

        pylab.ylim([0, self.tick])
        pylab.xlim([0, len(self.species)])
Ejemplo n.º 9
0
    def __init_chirplet_filter_bank(self):
        """generate all the chirplets based on the attributes

        Returns :
            The bank of chirplets
        """
        num_chirps = self._num_octaves * self._num_chirps_by_octave

        #create a list of coefficients based on attributes
        lambdas = 2.0**(1 +
                        arange(num_chirps) / float(self._num_chirps_by_octave))

        #Low frequencies for a signal
        start_frequencies = (self._samplerate / lambdas) / 2.0

        #high frequencies for a signal
        end_frequencies = self._samplerate / lambdas

        durations = 2.0 * self._duration_longest_chirplet / flipud(lambdas)

        chirplets = list()
        for low_frequency, high_frequency, duration in zip(
                start_frequencies, end_frequencies, durations):
            chirplets.append(
                Chirplet(self._samplerate, low_frequency, high_frequency,
                         duration, self._polynome_degree))
        return chirplets
Ejemplo n.º 10
0
def getImages(filename,vname):
    file=NetCDF.NetCDFFile(filename,'r')
    vdata=file.variables[vname] 
    vsize=vdata.shape[0]
	# create empty files subdirectory for output images
    try:
        shutil.rmtree('colorbarImages')
    except:
        pass
    os.makedirs('colorbarImages')
	# go through the whole dataset and generate a color bar image for each step
    for i in range(vsize):
        varray = vdata[i,:,:,]
        data=pylab.flipud(varray)
        pylab.imshow(data, norm=LogNorm())
        imgNum = 'TimeStep_'+ str(i)	
    	if len(data[data>0])>0:
	    #make a new figure that contains the colorbar
    	    fig=pylab.figure(figsize=(2,5))
    	    ax1 = fig.add_axes([0.35, 0.03, 0.1, 0.9])
    	    vmin=data[data>0].min()
    	    vmax=data.max()
    	    norm = LogNorm(vmin,vmax)
	    #make the colorbar in log scale
    	    logFormatter=LogFormatter(10, labelOnlyBase=False)
    	    cb1 = ColorbarBase(ax1,norm=norm,format=logFormatter,spacing='proportional', orientation='vertical')
	    imgName='colorbarImages/%s.png' %imgNum
    	    fig.savefig(imgName, bbox_inches='tight')
Ejemplo n.º 11
0
def fft_smoothing(input_signal, sigma):
    """smooth the fast transform Fourier
    Params :
        input_signal : audio signal
        sigma : relative to the length of the output signal
    Returns :
        a shorter and smoother signal

    """
    size_signal = input_signal.size

    #shorten the signal
    new_size = int(floor(10.0 * size_signal * sigma))
    half_new_size = new_size // 2

    fftx = fft(input_signal)

    short_fftx = []
    for ele in fftx[:half_new_size]:
        short_fftx.append(ele)

    for ele in fftx[-half_new_size:]:
        short_fftx.append(ele)

    apodization_coefficients = generate_apodization_coeffs(
        half_new_size, sigma, size_signal)

    #apply the apodization coefficients
    short_fftx[:half_new_size] *= apodization_coefficients
    short_fftx[half_new_size:] *= flipud(apodization_coefficients)

    realifftxw = ifft(short_fftx).real
    return realifftxw
Ejemplo n.º 12
0
 def horizFlipCheckBoxChanged(self, event):
     self.horizFlip = self.ui.horizFlipCheckBox.isChecked()
     if hasattr(self, 'meas'):
         self.plotImage(pl.flipud(self.meas),
                        autoLevels=self.autolevels,
                        eqHist=self.equalizeHist,
                        scale=self.scale)
Ejemplo n.º 13
0
def showContours_v():

    global umean, vmean, modelgreylevelvar, goodvectorsVar, lowerLevelVar, upperLevelVar, tickvar, numcontourVar
    from scipy import zeros, where, logical_or, r_, argmin, shape, ravel, nan, compress, flipud
    from pylab import imshow, clf, title, save, load, figure, contourf, cm, hold, contour, xlabel, ylabel

    x = load('vecx.out.npy')
    y = load('vecy.out.npy')
    u = load('vecu.out.npy')
    v = load('vecv.out.npy')
    q1 = load('vecq1.out.npy')
    valid = load('vecvalid.out.npy')
    modelgreylevel = float(modelgreylevelVar.get())
    goodvectors = float(goodvectorsVar.get())
    v = where(logical_or(q1 < goodvectors, valid < 0), modelgreylevel, v)
    v = -flipud(v)
    lowerLevel = float(lowerLevelVar.get())
    upperLevel = float(upperLevelVar.get())
    numcontour = int(numcontourVar.get())
    tick = float(upperLevel - lowerLevel) / numcontour
    vv = r_[lowerLevel:upperLevel:tick]
    figure()
    contourf(x, y, v, vv, cmap=cm.gray)
    contourf(x, y, v, vv, cmap=cm.gray)
    xlabel('Pixels')
    ylabel('Pixels')
    return
Ejemplo n.º 14
0
    def solve(f1, f2, f3, f4, a, b, h, tol, max_steps):
        """
        uxx(x,yt) + uyy(x,y) = 0 on R = {(x,y): 0 <= x <= a, 0 <= y <= b},
        u(x,0) = f1(x), u(x,b) = f2(x) for 0 <= x <= a, u(0,y) = f3(y), u(a,y) = f4(y) for 0 <= y <= b,
        :param f1: u(x,0)
        :param f2: u(x,b)
        :param f3: u(0,y)
        :param f4: u(a,y)
        :param a: right boundary for x
        :param b: right boundary for y
        :param h: step
        :param tol: maximum delta
        :param max_steps: max count of steps
        :return: x - vector of x coordinates, y - vector of y coordinates, u - result (matrix of z coordinates)
        """

        # initialize parameters in u
        n = int(a / h) + 1
        m = int(b / h) + 1
        ave = (a * (f1(0) + f2(0)) + b * (f3(0) + f4(0))) / (2 * a + 2 * b)

        u = ave * pylab.ones((n, m))

        # boundary conditions
        u[0, :] = [f3(i * h) for i in range(0, m)]
        u[n - 1, :] = [f4(i * h) for i in range(0, m)]
        u[:, 0] = [f1(i * h) for i in range(0, n)]
        u[:, m - 1] = [f2(i * h) for i in range(0, n)]

        u[0, 0] = (u[0, 1] + u[1, 0]) / 2
        u[0, m - 1] = (u[0, m - 2] + u[1, m - 1]) / 2
        u[n - 1, 0] = (u[n - 2, 0] + u[n - 1, 1]) / 2
        u[n - 1, m - 1] = (u[n - 2, m - 1] + u[n - 1, m - 2]) / 2

        # The parameter of consistent method of relax
        w = 4 / (2 + math.sqrt(4 - (math.cos(math.pi /
                                             (n - 1)) + math.cos(math.pi /
                                                                 (m - 1)))**2))

        # Improved approximation operator purification throughout the lattice
        error = 1
        count = 0

        while error > tol and count <= max_steps:
            error = 0

            for j in range(1, m - 1):
                for i in range(1, n - 1):
                    relax = w * (u[i][j + 1] + u[i][j - 1] + u[i + 1][j] +
                                 u[i - 1, j] - 4 * u[i][j]) / 4
                    u[i, j] += relax
                    if error <= math.fabs(relax):
                        error = math.fabs(relax)
            count += 1

        x = [i * h for i in range(n)]
        y = [i * h for i in range(m)]
        u = pylab.flipud(pylab.transpose(u))
        return x, y, u
Ejemplo n.º 15
0
def MFarray_to_plotarray(mfarray, maskvalue, orientation, rcl):
    '''Create a 2d plotting array from a 3d modflow array.
    mfarray: a 3d modflow array
    maskvalue: the value to mask (e.g. hdry)
    orientation: 'layer' 'row' or 'column'
    rcl: the layer row or column
    '''
    rcl = rcl - 1
    nlay, nrow, ncol = shape(mfarray)
    if (orientation == 'layer'):
        Z = flipud(mfarray[rcl, :, :]).copy()
    elif (orientation == 'row'):
        Z = flipud(mfarray[:, rcl, :]).copy()
    elif (orientation == 'column'):
        Z = flipud(mfarray[:, :, rcl]).copy()
    Z = ma.masked_where(Z == maskvalue, Z)
    return Z
Ejemplo n.º 16
0
def MFarray_to_plotarray(mfarray,maskvalue,orientation,rcl):
    '''Create a 2d plotting array from a 3d modflow array.
    mfarray: a 3d modflow array
    maskvalue: the value to mask (e.g. hdry)
    orientation: 'layer' 'row' or 'column'
    rcl: the layer row or column
    '''
    rcl=rcl-1
    nlay,nrow,ncol=shape(mfarray)
    if(orientation=='layer'):
        Z=flipud(mfarray[rcl,:,:]).copy()
    elif(orientation=='row'):
        Z=flipud(mfarray[:,rcl,:]).copy()
    elif(orientation=='column'):
        Z=flipud(mfarray[:,:,rcl]).copy()
    Z=ma.masked_where(Z == maskvalue,Z)
    return Z
Ejemplo n.º 17
0
    def importfile(self,fname,params):
        # if even more sophisticated things are needed, just inherit THzTdData class
        #and override the importfile method
        #try to load the file with name fname
        #it should be possible to write this shorter
        try:
            #if no Y_col is specified            
            if params.has_key('Y_col'):
                #import it right away
                if params['dec_sep']=='.':
                    data=py.loadtxt(fname,
                                usecols=(params['time_col'],
                                         params['X_col'],
                                         params['Y_col']),
                                skiprows=params['skiprows'])
                                
                elif params['dec_sep']==',':
                    #if the decimal separator is , do a replacement
                    str2float=lambda val: float(val.replace(',','.'))
                    data=py.loadtxt(fname,
                                converters={params['time_col']:str2float,
                                            params['X_col']:str2float,
                                            params['Y_col']:str2float},
                                usecols=(params['time_col'],
                                         params['X_col'],
                                         params['Y_col']),
                                skiprows=params['skiprows'])                
            else:
                #import it right away
                if params['dec_sep']=='.':
                    data=py.loadtxt(fname,
                                usecols=(params['time_col'],
                                         params['X_col']),
                                skiprows=params['skiprows'])
                                
                elif params['dec_sep']==',':
                    #if the decimal separator is , do a replacement
                    str2float=lambda val: float(val.replace(',','.'))
                    data=py.loadtxt(fname,
                                converters={params['time_col']:str2float,
                                            params['X_col']:str2float},
                                usecols=(params['time_col'],
                                         params['X_col']),
                                skiprows=params['skiprows'])
                dummy_Y=py.zeros((data.shape[0],1))
                data=py.column_stack((data,dummy_Y))
        except IOError:
            print "File " + fname + " could not be loaded"
            sys.exit()

        #scale the timaaxis
        data[:,0]*=params['time_factor']
        
        #if the measurement was taken in negative time direction, flip the data
        if data[1,0]-data[0,0]<0:
            data=py.flipud(data)
     
        return data
Ejemplo n.º 18
0
    def dependency_matrix(self, fontsize=12):
        r"""Return dependency matrix

        * :math:`D_{i,j}` = green ; species i is an activator of species j (only positive path)
        * :math:`D_{i,j}` = red   ; species i is an inhibitor of species j (only negative path)
        * :math:`D_{i,j}` = yellow; ambivalent (positive and negative paths connecting i and j)
        * :math:`D_{i,j}` = red   ; species i has no influence on j

        .. plot::
            :include-source:
            :width: 80%

            from cno import XCNOGraph, cnodata
            c = XCNOGraph(cnodata("PKN-ToyPB.sif"), cnodata("MD-ToyPB.csv"))
            c.dependency_matrix()

        """
        nodes = sorted(self.nodes())
        N = len(nodes)
        data = np.zeros((len(nodes), len(nodes)))
        for i,node1 in enumerate(nodes):
            paths = nx.shortest_path(self, node1)
            for j,node2 in enumerate(nodes):
                if node1 == node2:
                    data[i][j] = 0
                elif node2 not in paths.keys():
                    data[i][j] = 0
                else:
                    path = paths[node2]
                    links = [self.edge[path[ii]][path[ii+1]]["link"] for ii in range(0,len(path)-1)]
                    if len(np.unique(links)) == 2:
                        data[i][j] = 1  # yellow
                    elif "+" in links:
                        data[i][j] = 2  #green
                    elif "-" in links:
                        if links.count("-") % 2 ==0:
                            data[i][j] = 2
                        else:
                            data[i][j] = 3   #red

        nodeNames = [node.replace("_", "\_") for node in nodes]
        nodeNamesY = [node.replace("_", "\_") for node in nodes]

        norm = colors.Normalize(vmin=0, vmax=3)

        cmap = colors.ListedColormap([[0., 0, 0], [1,1,0],[.5, 1, 0.], [1., 0, 0.]])
        indices = [i for i, node in enumerate(nodes) 
                if "and" not in node or "+" in nodes]

        pylab.clf()
        pylab.pcolor(pylab.flipud(data[indices][:,indices]), edgecolors="w", 
                cmap=cmap, norm=norm);

        N = len(indices)

        nodeNames = np.array(nodeNames)[indices]
        nodeNamesY = np.array(nodeNamesY)[indices[::-1]]
Ejemplo n.º 19
0
def create_raster(lon, lat, variable, split, lon_split=None, left=None):
    if split:
        if left:
            lon = lon[:, 0:lon_split]
            lat = lat[:, 0:lon_split]
            variable = flipud(variable[:, 0:lon_split])
            tif_suffix = "_left.tif"
        else:
            lon_split += 1
            lon = lon[:, lon_split:-1]
            lat = lat[:, lon_split:-1]
            variable = flipud(variable[:, lon_split:-1])
            tif_suffix = "_right.tif"
    else:
        variable = flipud(variable)
        tif_suffix = ".tif"

    not_in_germany = ((lon > globals.min_lon) & (lon < globals.max_lon) &
                      (lat > globals.min_lat) &
                      (lat < globals.max_lat)).sum() == 0
    if not_in_germany:
        return

    # For each pixel I know it's latitude and longitude.
    # As you'll see below you only really need the coordinates of
    # one corner, and the resolution of the file.
    # That's (top left x, w-e pixel resolution, rotation (0 if North is up),
    #         top left y, rotation (0 if North is up), n-s pixel resolution)
    xmin, ymin, xmax, ymax = [lon.min(), lat.min(), lon.max(), lat.max()]
    nrows, ncols = np.shape(variable)
    xres = (xmax - xmin) / float(ncols)
    yres = (ymax - ymin) / float(nrows)
    geotransform = (xmin, xres, 0, ymax, 0, -yres)

    output_raster = gdal.GetDriverByName('GTiff').Create(
        os.path.join(root, file.replace(".nc", tif_suffix)), ncols, nrows, 1,
        gdal.GDT_Float32)  # Open the file
    output_raster.SetGeoTransform(geotransform)  # Specify its coordinates
    srs = osr.SpatialReference()  # Establish its coordinate encoding
    srs.ImportFromEPSG(4326)  # This one specifies WGS84 lat long.
    output_raster.SetProjection(
        srs.ExportToWkt())  # Exports the coordinate system to the file
    output_raster.GetRasterBand(1).WriteArray(
        variable)  # Writes my array to the raster
Ejemplo n.º 20
0
    def solve(f1, f2, f3, f4, a, b, h, tol, max_steps):
        """
        uxx(x,yt) + uyy(x,y) = 0 on R = {(x,y): 0 <= x <= a, 0 <= y <= b},
        u(x,0) = f1(x), u(x,b) = f2(x) for 0 <= x <= a, u(0,y) = f3(y), u(a,y) = f4(y) for 0 <= y <= b,
        :param f1: u(x,0)
        :param f2: u(x,b)
        :param f3: u(0,y)
        :param f4: u(a,y)
        :param a: right boundary for x
        :param b: right boundary for y
        :param h: step
        :param tol: maximum delta
        :param max_steps: max count of steps
        :return: x - vector of x coordinates, y - vector of y coordinates, u - result (matrix of z coordinates)
        """

        # initialize parameters in u
        n = int(a / h) + 1
        m = int(b / h) + 1
        ave = (a * (f1(0) + f2(0)) + b * (f3(0) + f4(0))) / (2 * a + 2 * b)

        u = ave * pylab.ones((n, m))

        # boundary conditions
        u[0, :] = [f3(i * h) for i in range(0, m)]
        u[n - 1, :] = [f4(i * h) for i in range(0, m)]
        u[:, 0] = [f1(i * h) for i in range(0, n)]
        u[:, m - 1] = [f2(i * h) for i in range(0, n)]

        u[0, 0] = (u[0, 1] + u[1, 0]) / 2
        u[0, m - 1] = (u[0, m - 2] + u[1, m - 1]) / 2
        u[n - 1, 0] = (u[n - 2, 0] + u[n - 1, 1]) / 2
        u[n - 1, m - 1] = (u[n - 2, m - 1] + u[n - 1, m - 2]) / 2

        # The parameter of consistent method of relax
        w = 4 / (2 + math.sqrt(4 - (math.cos(math.pi / (n - 1)) + math.cos(math.pi / (m - 1))) ** 2))

        # Improved approximation operator purification throughout the lattice
        error = 1
        count = 0

        while error > tol and count <= max_steps:
            error = 0

            for j in range(1, m - 1):
                for i in range(1, n - 1):
                    relax = w * (u[i][j + 1] + u[i][j - 1] + u[i + 1][j] + u[i - 1, j] - 4 * u[i][j]) / 4
                    u[i, j] += relax
                    if error <= math.fabs(relax):
                        error = math.fabs(relax)
            count += 1

        x = [i * h for i in range(n)]
        y = [i * h for i in range(m)]
        u = pylab.flipud(pylab.transpose(u))
        return x, y, u
def montage(I): 

    xdim, ydim, zdim = shape(I)
    nimages_x = int(ceil(sqrt(xdim)))
    nimages_y = int(ceil(sqrt(ydim)))
    nimages_z = int(ceil(sqrt(zdim)))
    Mx = zeros((nimages_x * zdim, nimages_x * ydim))
    My = zeros((nimages_y * zdim, nimages_y * xdim))
    Mz = zeros((nimages_z * ydim, nimages_z * xdim))
    
    # Sagittal (x)
    # switch i2 and i1 for loops to have the slice sequence
    # progress vertically rather than horizontally.
    xcount = 0
    for i1 in range(nimages_x):
        for i2 in range(nimages_x):
            xcount += 1
            if xcount < xdim:
                Mx[ i1*zdim : (i1+1)*zdim, i2*ydim : (i2+1)*ydim ] = rot90(I[xdim-xcount,::-1,:],1)
            else:
                break

    # Coronal (y)
    ycount = 0
    for i1 in range(nimages_y):
        for i2 in range(nimages_y):
            ycount += 1
            if ycount < ydim:
                My[ i1*zdim : (i1+1)*zdim, i2*xdim : (i2+1)*xdim ] = flipud(I[::-1,ydim-ycount,:].transpose())
            else:
                break

    # Horizontal (z)
    zcount = 0
    for i1 in range(nimages_z):
        for i2 in range(nimages_z):
            zcount += 1
            if zcount < zdim:
                Mz[ i1*ydim : (i1+1)*ydim, i2*xdim : (i2+1)*xdim ] = flipud(I[:,:,zdim-zcount].transpose())
            else:
                break

    return Mx, My, Mz, xdim, ydim, zdim, nimages_x, nimages_y, nimages_z
Ejemplo n.º 22
0
def histogram_u_v():

    from pylab import figure, hist, title, load, xlabel, ylabel
    from scipy import where, logical_or, flipud

    u = load('vecu.out.npy')
    v = load('vecv.out.npy')
    u = flipud(u)
    v = -flipud(v)
    figure()
    hist(u, 100)
    title('Frequency Distribution of horizontal displacements data')
    xlabel('Horizontal Displacement in Pixels')
    ylabel('Frequency')
    figure()
    hist(v, 100)
    title('Frequency Distribution of vertical displacements data')
    xlabel('Vertical Displacement in Pixels')
    ylabel('Frequency')
Ejemplo n.º 23
0
def test_colorbar():
    # Builtin colourmap "seismic" has the blue-white-red
    #   scale you want
    a = np.zeros((16, 16), dtype=np.float32)
    a[0, 0] = 1.0
    b = np.ones((16, 16), dtype=np.float32) * 0.5
    b[0, 0] = 1.0

    fig = plt.figure()
    plt.subplot(121, aspect='equal')
    # plt.pcolor(data, cmap=plt.cm.seismic, vmin=0, vmax=2)
    plt.pcolor(flipud(a), cmap='hot', vmin=0, vmax=1)
    plt.colorbar()

    plt.subplot(122, aspect='equal')
    plt.pcolor(flipud(b), cmap='hot', vmin=0, vmax=1)
    plt.colorbar()

    pp = PdfPages("test_colorbar.pdf")
    pp.savefig(fig)
    pp.close()
Ejemplo n.º 24
0
 def save_sonogram(
     self,
     replace=False,
     n_fft=settings.N_FFT,
     min_freq=settings.MIN_FREQ,
     max_freq=settings.MAX_FREQ,
     dpi=100,
     width=1000,
     height=350,
     max_framerate=settings.MAX_FRAMERATE,
 ):
     filename = self.get_sonogram_name()
     name = os.path.join(settings.SONOGRAM_DIR, filename)
     path = os.path.join(settings.MEDIA_ROOT, name)
     try:
         if not os.path.exists(path):
             replace = True
     except (ValueError, SuspiciousOperation, AttributeError):
         replace = True
     if replace:
         audio, framerate = self.get_audio(max_framerate=max_framerate)
         Pxx, freqs, bins, im = specgram(audio, NFFT=n_fft, Fs=framerate)
         f = where(logical_and(freqs > min_freq, freqs <= max_freq))[0]
         Pxx[where(Pxx > percentile(Pxx[f].flatten(), 99.99))] = percentile(Pxx[f].flatten(), 99.99)
         Pxx[where(Pxx < percentile(Pxx[f].flatten(), 0.01))] = percentile(Pxx[f].flatten(), 0.01)
         clf()
         fig = figure(figsize=(float(width) / dpi, float(height) / dpi), dpi=dpi)
         imshow(
             flipud(10 * log10(Pxx[f,])),
             extent=(bins[0], bins[-1], freqs[f][0], freqs[f][-1]),
             aspect="auto",
             cmap=cm.gray,
         )
         gca().set_ylabel("Frequency (Hz)")
         gca().set_xlabel("Time (s)")
         axis_pixels = gca().transData.transform(np.array((gca().get_xlim(), gca().get_ylim())).T)
         st, created = SonogramTransform.objects.get_or_create(
             n_fft=n_fft,
             framerate=framerate,
             min_freq=min_freq,
             max_freq=max_freq,
             duration=self.duration,
             width=width,
             height=height,
             dpi=dpi,
             top_px=max(axis_pixels[:, 1]),
             bottom_px=min(axis_pixels[:, 1]),
             left_px=min(axis_pixels[:, 0]),
             right_px=max(axis_pixels[:, 0]),
         )
         savefig(open(path, "wb"), format="jpg", dpi=dpi)
         sonogram, created = Sonogram.objects.get_or_create(snippet=self, transform=st, path=name)
         close()
Ejemplo n.º 25
0
 def save_sonogram(self, replace=False, n_fft=settings.N_FFT, \
     min_freq=settings.MIN_FREQ, \
     max_freq=settings.MAX_FREQ, \
     dpi=100,
     width=1000,
     height=350,
     max_framerate=settings.MAX_FRAMERATE):
     filename = self.get_sonogram_name()
     name = os.path.join(settings.SONOGRAM_DIR, filename)
     path = os.path.join(settings.MEDIA_ROOT, name)
     try:
         if not os.path.exists(path):
             replace = True
     except (ValueError, SuspiciousOperation, AttributeError):
         replace = True
     if replace:
         audio, framerate = self.get_audio(max_framerate=max_framerate)
         Pxx, freqs, bins, im = specgram(audio, NFFT=n_fft, Fs=framerate)
         f = where(logical_and(freqs > min_freq, freqs <= max_freq))[0]
         Pxx[where(Pxx > percentile(Pxx[f].flatten(), 99.99))] = percentile(
             Pxx[f].flatten(), 99.99)
         Pxx[where(Pxx < percentile(Pxx[f].flatten(), 0.01))] = percentile(
             Pxx[f].flatten(), 0.01)
         clf()
         fig = figure(figsize=(float(width) / dpi, float(height) / dpi),
                      dpi=dpi)
         imshow(flipud(10 * log10(Pxx[f, ])),
                extent=(bins[0], bins[-1], freqs[f][0], freqs[f][-1]),
                aspect='auto',
                cmap=cm.gray)
         gca().set_ylabel('Frequency (Hz)')
         gca().set_xlabel('Time (s)')
         axis_pixels = gca().transData.transform(
             np.array((gca().get_xlim(), gca().get_ylim())).T)
         st, created = SonogramTransform.objects.get_or_create(
             n_fft=n_fft,
             framerate=framerate,
             min_freq=min_freq,
             max_freq=max_freq,
             duration=self.duration,
             width=width,
             height=height,
             dpi=dpi,
             top_px=max(axis_pixels[:, 1]),
             bottom_px=min(axis_pixels[:, 1]),
             left_px=min(axis_pixels[:, 0]),
             right_px=max(axis_pixels[:, 0]),
         )
         savefig(open(path, 'wb'), format='jpg', dpi=dpi)
         sonogram, created = Sonogram.objects.get_or_create(snippet=self,
                                                            transform=st,
                                                            path=name)
         close()
Ejemplo n.º 26
0
def mhd_four_pane_2d(P, extent=[0,1,0,1], do_quiver=True, cmap=None, **kwargs):

    from pylab import flipud, subplot, title, colorbar, cm, imshow, quiver, matplotlib
    from numpy import sqrt, linspace, meshgrid

    rho, pre   = P[:,:,0], P[:,:,1]
    vx, vy, vz = P[:,:,2], P[:,:,3], P[:,:,4]
    Bx, By, Bz = P[:,:,5], P[:,:,6], P[:,:,7]

    B2 = Bx**2 + By**2 + Bz**2
    v2 = vx**2 + vy**2 + vz**2
    W  = 1.0 / sqrt(1.0 - v2)

    if type(cmap) is str:
        from pickle import load
        cmap = load(open('rmhd/data/cmaps.pk'))[cmap]
    elif isinstance(cmap, matplotlib.colors.Colormap):
        pass
    else:
        cmap = cm.hot

    imargs = {'extent':extent, 'cmap':cmap, 'interpolation':'bilinear'}
    imargs.update(kwargs)

    tr = lambda x: flipud(x.T)

    subplot(2,2,1)
    imshow(tr(rho), **imargs)
    colorbar()
    title("Density")

    subplot(2,2,2)
    imshow(tr(pre), **imargs)
    colorbar()
    title("Pressure")

    subplot(2,2,3)
    imshow(tr(B2), **imargs)
    colorbar()
    title("Magnetic Pressure")

    subplot(2,2,4)
    imshow(tr(W), **imargs)
    colorbar()
    title("Lorentz Factor")

    if do_quiver:
        N = 10
        X,Y = meshgrid(linspace(extent[0],extent[1],W.shape[0]),
                       linspace(extent[2],extent[3],W.shape[1]))
        quiver(X[::N,::N], Y[::N,::N], Bx[::N,::N].T, By[::N,::N].T, color='y')

    """
Ejemplo n.º 27
0
def jetWoGn(reverse=False):
    """
    jetWoGn(reverse=False)
       - returning a colormap similar to cm.jet, but without green.
         if reverse=True, the map starts with red instead of blue.
    """
    m=18 # magic number, which works fine
    m0=pl.floor(m*0.0)
    m1=pl.floor(m*0.2)
    m2=pl.floor(m*0.2)
    m3=pl.floor(m/2)-m2-m1

    b_ = np.hstack( (0.4*np.arange(m1)/(m1-1.)+0.6, np.ones((m2+m3,)) ) )
    g_ = np.hstack( (np.zeros((m1,)),np.arange(m2)/(m2-1.),np.ones((m3,))) )
    r_ = np.hstack( (np.zeros((m1,)),np.zeros((m2,)),np.arange(m3)/(m3-1.)))

    r = np.hstack((r_,pl.flipud(b_)))
    g = np.hstack((g_,pl.flipud(g_)))
    b = np.hstack((b_,pl.flipud(r_)))

    if reverse:
        r = pl.flipud(r)
        g = pl.flipud(g)
        b = pl.flipud(b)

    ra = pl.linspace(0.0,1.0,m)

    cdict = {'red': zip(ra,r,r),
            'green': zip(ra,g,g),
            'blue': zip(ra,b,b)}

    return pl.matplotlib.colors.LinearSegmentedColormap('new_RdBl',cdict,256)
Ejemplo n.º 28
0
    def __call__(self,**params):
        p=ParamOverrides(self,params)

        for template in p.plot_template:

            for sheet in topo.sim.objects(Sheet).values():
                name=template.keys().pop(0)
                plot=make_template_plot(template,sheet.sheet_views,sheet.xdensity,sheet.bounds,p.normalize,name=template[name])
                if plot:
                    bitmap=plot.bitmap
                    pylab.figure(figsize=(5,5))
                    isint=pylab.isinteractive() # Temporarily make non-interactive for plotting
                    pylab.ioff()                                         # Turn interactive mode off

                    pylab.imshow(bitmap.image,origin='lower',interpolation='nearest')
                    pylab.axis('off')

                    for (t,pref,sel,c) in p.overlay:
                        v = pylab.flipud(sheet.sheet_views[pref].view()[0])

                        if (t=='contours'):
                            pylab.contour(v,[sel,sel],colors=c,linewidths=2)

                        if (t=='arrows'):
                            s = pylab.flipud(sheet.sheet_views[sel].view()[0])
                            scale=int(pylab.ceil(log10(len(v))))
                            X=pylab.array([x for x in xrange(len(v)/scale)])
                            v_sc=pylab.zeros((len(v)/scale,len(v)/scale))
                            s_sc=pylab.zeros((len(v)/scale,len(v)/scale))
                            for i in X:
                                for j in X:
                                    v_sc[i][j]=v[scale*i][scale*j]
                                    s_sc[i][j]=s[scale*i][scale*j]
                            pylab.quiver(scale*X,scale*X,-cos(2*pi*v_sc)*s_sc,-sin(2*pi*v_sc)*s_sc,color=c,edgecolors=c,minshaft=3,linewidths=1)

                    p.title='%s overlaid with %s at time %s' %(plot.name,pref,topo.sim.timestr())
                    if isint: pylab.ion()
                    p.filename_suffix="_"+sheet.name
                    self._generate_figure(p)
Ejemplo n.º 29
0
    def plot_adjacency_matrix(self, fontsize=12, **kargs):
        """Plots adjacency matrix

        :param kargs: optional arguments accepted by pylab.pcolor

        From the following graph, 

        .. plot::
            :width: 70%

            from cno import XCNOGraph, cnodata
            c = XCNOGraph(cnodata("PKN-ToyMMB.sif"), cnodata("MD-ToyMMB.csv"))
            c.plot()

        The adjacency matrix can be created as follows:

        .. plot::
            :width: 70%
            :include-source:

            from cno import XCNOGraph, cnodata
            c = XCNOGraph(cnodata("PKN-ToyMMB.sif"), cnodata("MD-ToyMMB.csv"))
            c.plot_adjacency_matrix()

        """
        nodeNames = sorted(self.nodes())
        nodeNamesY = sorted(self.nodes())

        nodeNamesY.reverse()
        N = len(nodeNames)

        data = self.adjacency_matrix(nodelist=nodeNames)
        # This is now a sparse matrix (networkx 1.9).
        try:
            data = data.todense()
        except:
            pass

        pylab.pcolor(pylab.flipud(pylab.array(data)), edgecolors="k", **kargs)
        pylab.axis([0, N, 0, N])
        pylab.xticks([0.5+x for x in pylab.arange(N)], nodeNames, rotation=90,
                      fontsize=fontsize)
        pylab.yticks([0.5+x for x in pylab.arange(N)], nodeNamesY, rotation=0,
                      fontsize=fontsize)
        try:pylab.tight_layout()
        except:pass
Ejemplo n.º 30
0
def retrieve_shakemap(event, shake_map_type):
   import pylab

   if shake_map_type not in SHAKEMAPS:
      raise ShakemapNotFound("Use one of %s shakemap types" % SHAKEMAPS.keys())

   eqid = event["Eqid"]
   rfile = httputil.RemoteFile(SHAKEMAPS[shake_map_type] % eqid)
   rfile.update()
   
   fhandle = open(rfile.filename, "r")
   head = fhandle.read(300)
   fhandle.close()

   if head.find("File Not Found (404)") >= 0:
      raise ShakemapNotAvailable("Shakemap not available for this event !")

   img = pylab.imread(rfile.filename)
   pylab.imshow(pylab.flipud(img))
   pylab.show()
Ejemplo n.º 31
0
 def loadImage(self, file):
     if file in self.dictFileImage:
         return self.dictFileImage[file];
     else:
         id     = self.totalImages;
         pixels = pylab.flipud(pylab.imread(file));            
         
         # SIFT features
         partName, partDot, partExt = file.rpartition('.');
         keyFile = ''.join(partName + partDot + "key"); 
         pgmFile = ''.join(partName + partDot + "pgm");
         if os.path.exists(pgmFile) == False:
             #pylab.imsave(pgmFile, pixels);
             if len(pixels.shape) == 2:
                 pilImage = Image.fromarray(pixels, 'L');                    
             else:
                 h = pixels.shape[0];
                 w = pixels.shape[1];                    
                 pixelsGray = np.matrix(np.zeros((h, w)), dtype=np.uint8);                    
                 for i in range(h):
                     for j in range(w):
                         pixelsGray[i, j] = (np.mean(pixels[i, j])).astype(np.uint8);
                 pilImage = Image.fromarray(pixelsGray, 'L');
             pilImage.save(pgmFile);
             
         if os.path.exists(keyFile) == False:            
             sift.process_image(pgmFile, keyFile);
             
         loc, des  = sift.read_features_from_file(keyFile);
         #im.features = [Feature(im.id, des[i], loc[i]) for i in range(len(des))];
         #print "Total features: ", len(im.features)
         
         im = ImageObject(id, pixels, loc, des);
         
         # add to dictionary
         self.dictFileImage[file]    = im;
         self.dictIdImage[im.id]     = im;
         # increase total images
         self.totalImages += 1;
         #print "Total images: ", self.totalImages;
         return im;
Ejemplo n.º 32
0
def retrieve_shakemap(event, shake_map_type):
    import pylab

    if shake_map_type not in SHAKEMAPS:
        raise ShakemapNotFound("Use one of %s shakemap types" %
                               SHAKEMAPS.keys())

    eqid = event["Eqid"]
    rfile = httputil.RemoteFile(SHAKEMAPS[shake_map_type] % eqid)
    rfile.update()

    fhandle = open(rfile.filename, "r")
    head = fhandle.read(300)
    fhandle.close()

    if head.find("File Not Found (404)") >= 0:
        raise ShakemapNotAvailable("Shakemap not available for this event !")

    img = pylab.imread(rfile.filename)
    pylab.imshow(pylab.flipud(img))
    pylab.show()
Ejemplo n.º 33
0
def hyd_four_pane_2d(P, extent=[0,1,0,1], do_quiver=True, cmap=None, **kwargs):

    from pylab import flipud, subplot, title, colorbar, cm, imshow, quiver, matplotlib
    from numpy import sqrt, linspace, meshgrid

    rho, pre   = P[:,:,0], P[:,:,1]
    vx, vy, vz = P[:,:,2], P[:,:,3], P[:,:,4]

    if type(cmap) is str:
        from pickle import load
        cmap = load(open('rmhd/data/cmaps.pk'))[cmap]
    elif isinstance(cmap, matplotlib.colors.Colormap):
        pass
    else:
        cmap = cm.hot

    imargs = {'extent':extent, 'cmap':cmap, 'interpolation':'bilinear'}
    imargs.update(kwargs)

    tr = lambda x: flipud(x.T)

    subplot(2,2,1)
    imshow(tr(rho), **imargs)
    colorbar()
    title("Density")

    subplot(2,2,2)
    imshow(tr(pre), **imargs)
    colorbar()
    title("Pressure")

    subplot(2,2,3)
    imshow(tr(vx), **imargs)
    colorbar()
    title("X-Velocity")

    subplot(2,2,4)
    imshow(tr(vy), **imargs)
    colorbar()
    title("Y-Velocity")
Ejemplo n.º 34
0
def qimplot(image=None, rmin=-2, rmax=2, cmap='gray'):
    """
    qimplot: Quick Image Plot
    Plots image in grayscale. Colorscale is from rmin*RMS to rmax*RMS.
    Defaults:
        rmin = -2
        rmax = +2
        cmap = 'gray'
            Can be any of the usual cmap values, e.g. 'YlOrRd' or 'jet'
    """
    logger = logging.getLogger('QIMPLOT')
    logger.info("Quick Image Plot")
    if image is None:
        logger.critical("Please provide input image!")
    pl.figure(figsize=(10, 10))
    fits = miriad('fits')
    if not os.path.exists(image):
        logger.critical(image + " not found!")
        sys.exit(0)
    fits.in_ = image
    fits.out = image + '.fits'
    fits.op = 'xyout'
    fits.go(rmfiles=True)
    imheader = pyfits.open(image + '.fits')
    imdata = imheader[0].data
    rms = pl.rms_flat(imdata[0, 0, :, :])
    logger.info('RMS = ' + "{:2.2}".format(rms))
    logger.info("Plotting from " + str(rmin) + "*RMS to " + str(rmax) +
                str("*RMS"))
    pl.imshow(pl.flipud(imdata[0, 0, :, :]),
              cmap=cmap,
              vmin=rmin * rms,
              vmax=rmax * rms)
    pl.colorbar()
    pl.xticks(())
    pl.yticks(())
Ejemplo n.º 35
0
def jetWoGn(reverse=False):
    """
    jetWoGn(reverse=False)
       - returning a colormap similar to cm.jet, but without green.
         if reverse=True, the map starts with red instead of blue.
    """
    m = 18  # magic number, which works fine
    m0 = pylab.floor(m * 0.0)
    m1 = pylab.floor(m * 0.2)
    m2 = pylab.floor(m * 0.2)
    m3 = pylab.floor(m / 2) - m2 - m1

    b_ = pylab.hstack(
        (0.4 * pylab.arange(m1) / (m1 - 1.) + 0.6, pylab.ones((m2 + m3, ))))
    g_ = pylab.hstack((pylab.zeros(
        (m1, )), pylab.arange(m2) / (m2 - 1.), pylab.ones((m3, ))))
    r_ = pylab.hstack((pylab.zeros((m1, )), pylab.zeros(
        (m2, )), pylab.arange(m3) / (m3 - 1.)))

    r = pylab.hstack((r_, pylab.flipud(b_)))
    g = pylab.hstack((g_, pylab.flipud(g_)))
    b = pylab.hstack((b_, pylab.flipud(r_)))

    if reverse:
        r = pylab.flipud(r)
        g = pylab.flipud(g)
        b = pylab.flipud(b)

    ra = pylab.linspace(0.0, 1.0, m)

    cdict = {
        'red': zip(ra, r, r),
        'green': zip(ra, g, g),
        'blue': zip(ra, b, b)
    }

    return LinearSegmentedColormap('new_RdBl', cdict, 256)
Ejemplo n.º 36
0
def plot_topo_file(topoplotdata):
    """
    Read in a topo or bathy file and produce a pcolor map.
    """

    deprecation_msg = "This function is being deprecated in favor of the " + \
                      "Topography class in clawpack.geoclaw.topotools and " + \
                      "plotting tools associated with it."
    warnings.filterwarnings('default', category=DeprecationWarning)
    warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2)
    warnings.resetwarnings()

    import os
    import pylab
    from clawpack.clawutil.data import ClawData

    fname = topoplotdata.fname
    topotype = topoplotdata.topotype
    if topoplotdata.climits:
        # deprecated option
        cmin = topoplotdata.climits[0]
        cmax = topoplotdata.climits[1]
    else:
        cmin = topoplotdata.cmin
        cmax = topoplotdata.cmax
    figno = topoplotdata.figno
    addcolorbar = topoplotdata.addcolorbar
    addcontour = topoplotdata.addcontour
    contour_levels = topoplotdata.contour_levels
    xlimits = topoplotdata.xlimits
    ylimits = topoplotdata.ylimits
    coarsen = topoplotdata.coarsen
    imshow = topoplotdata.imshow
    gridedges_show = topoplotdata.gridedges_show
    neg_cmap = topoplotdata.neg_cmap
    pos_cmap = topoplotdata.pos_cmap
    cmap = topoplotdata.cmap
    print_fname = topoplotdata.print_fname

    if neg_cmap is None:
        neg_cmap = colormaps.make_colormap({
            cmin: [0.3, 0.2, 0.1],
            0: [0.95, 0.9, 0.7]
        })
    if pos_cmap is None:
        pos_cmap = colormaps.make_colormap({
            0: [.5, .7, 0],
            cmax: [.2, .5, .2]
        })
    if cmap is None:
        cmap = colormaps.make_colormap({
            -1: [0.3, 0.2, 0.1],
            -0.00001: [0.95, 0.9, 0.7],
            0.00001: [.5, .7, 0],
            1: [.2, .5, .2]
        })
        #cmap = colormaps.make_colormap({-1:[0,0,1],0:[1,1,1],1:[1,0,0]})

    if abs(topotype) == 1:

        X, Y, topo = topotools.topofile2griddata(fname, topotype)
        topo = pylab.flipud(topo)
        Y = pylab.flipud(Y)
        x = X[0, :]
        y = Y[:, 0]
        xllcorner = x[0]
        yllcorner = y[0]
        cellsize = x[1] - x[0]

    elif abs(topotype) == 3:

        file = open(fname, 'r')
        lines = file.readlines()
        ncols = int(lines[0].split()[0])
        nrows = int(lines[1].split()[0])
        xllcorner = float(lines[2].split()[0])
        yllcorner = float(lines[3].split()[0])
        cellsize = float(lines[4].split()[0])
        NODATA_value = int(lines[5].split()[0])

        print("Loading file ", fname)
        print("   nrows = %i, ncols = %i" % (nrows, ncols))
        topo = pylab.loadtxt(fname, skiprows=6, dtype=float)
        print("   Done loading")

        if 0:
            topo = []
            for i in range(nrows):
                topo.append(pylab.array(lines[6 + i], ))
            print('+++ topo = ', topo)
            topo = pylab.array(topo)

        topo = pylab.flipud(topo)

        x = pylab.linspace(xllcorner, xllcorner + ncols * cellsize, ncols)
        y = pylab.linspace(yllcorner, yllcorner + nrows * cellsize, nrows)
        print("Shape of x, y, topo: ", x.shape, y.shape, topo.shape)

    else:
        raise Exception("*** Only topotypes 1 and 3 supported so far")

    if coarsen > 1:
        topo = topo[slice(0, nrows, coarsen), slice(0, ncols, coarsen)]
        x = x[slice(0, ncols, coarsen)]
        y = y[slice(0, nrows, coarsen)]
        print("Shapes after coarsening: ", x.shape, y.shape, topo.shape)

    if topotype < 0:
        topo = -topo

    if figno:
        pylab.figure(figno)

    if topoplotdata.imshow:
        color_norm = Normalize(cmin, cmax, clip=True)
        xylimits = (x[0], x[-1], y[0], y[-1])
        #pylab.imshow(pylab.flipud(topo.T), extent=xylimits, \
        pylab.imshow(pylab.flipud(topo), extent=xylimits, \
                cmap=cmap, interpolation='nearest', \
                norm=color_norm)
        #pylab.clim([cmin,cmax])
        if addcolorbar:
            pylab.colorbar()
    else:
        neg_topo = ma.masked_where(topo > 0., topo)
        all_masked = (ma.count(neg_topo) == 0)
        if not all_masked:
            pylab.pcolormesh(x, y, neg_topo, cmap=neg_cmap)
            pylab.clim([cmin, 0])
            if addcolorbar:
                pylab.colorbar()

        pos_topo = ma.masked_where(topo < 0., topo)
        all_masked = (ma.count(pos_topo) == 0)
        if not all_masked:
            pylab.pcolormesh(x, y, pos_topo, cmap=pos_cmap)
            pylab.clim([0, cmax])
    if addcolorbar:
        pylab.colorbar()

    pylab.axis('scaled')

    if addcontour:
        pylab.contour(x, y, topo, levels=contour_levels, colors='k')

    patchedges_show = True
    if patchedges_show:
        pylab.plot([x[0], x[-1]], [y[0], y[0]], 'k')
        pylab.plot([x[0], x[-1]], [y[-1], y[-1]], 'k')
        pylab.plot([x[0], x[0]], [y[0], y[-1]], 'k')
        pylab.plot([x[-1], x[-1]], [y[0], y[-1]], 'k')

    if print_fname:
        fname2 = os.path.splitext(fname)[0]
        pylab.text(xllcorner + cellsize,
                   yllcorner + cellsize,
                   fname2,
                   color='m')

    topodata = ClawData()
    topodata.x = x
    topodata.y = y
    topodata.topo = topo

    return topodata
Ejemplo n.º 37
0
import sys, os
import pylab
sys.path.append('../../datatools')
import dart  # from the directory above

gaugeno = 43412
fname = '43412_5day-03132011.txt'
t1fit = 16500.
t2fit = 18000.
t1out = 16800
t2out = 17500.
degree = 15

fname_notide = os.path.splitext(fname)[0] + '_notide.txt'
t,eta = dart.plotdart(fname)    
t = pylab.flipud(t)
eta = pylab.flipud(eta)

c,t_notide,eta_notide = dart.fit_tide_poly(t,eta,degree,t1fit,t2fit, t1out,t2out)

# Time of quake:  05:48:15 UTC on March 12, 2011
# Convert to minutes after start of March:
t_quake = 11*24*60 + 5*60 + 48 + 15/60.  
#print "Time of quake = %7.2f minutes after start of March" % t_quake

t_sec = (t_notide-t_quake)*60.
d = pylab.vstack([t_sec,eta_notide]).T
pylab.savetxt(fname_notide,d)
print "Created file ",fname_notide

#dart.plot_postquake(t_notide,eta_notide,t_quake,gaugeno)
Ejemplo n.º 38
0
from PIL import Image
import pylab as p


# This should work for any photo, but greyscale is probably better
F=Image.open('MDP.jpg').convert('L')
arr=p.flipud(p.array(F))

NY,NX=arr.shape
x=p.arange(NX)
y=p.arange(NY)

p.gray()

X,Y=p.meshgrid(x,y)



def plot(sx,sy,n,**kwargs):

    print range(*sx.indices(NX))

    arr_n=p.array([[p.mean(arr[x:x+n,y:y+n]) for x in range(*sx.indices(NY))]
                   for y in range(*sy.indices(NX))])

    print arr_n

    p.pcolormesh(X[sx,sy],Y[sx,sy],arr_n.T,vmin=0,vmax=255,**kwargs)


# offsets to make specifying the "refined" areas easier
Ejemplo n.º 39
0
def makePalindrome(num, even):
    dec = decomp(num)
    if even:
        return fuse(r_[dec, flipud(dec)])
    else:
        return fuse(r_[dec, flipud(dec[:-1])])
Ejemplo n.º 40
0
    def startAcq(self):
        """
        Function called when pressing the Start button. Will launch the
        integration loop and stay going as long as no stopping action has 
        happened (pressing Stop button, closing the window, changed integration
        time).
        """
        self.ui.stopBut.setEnabled(True)
        self.ui.startBut.setEnabled(False)
        camId = self.ui.cameraID.value()

        try:
            with StarlightCCD(camId) as self.ccd:
                self.meas = pl.zeros((self.ccd.ccdParams['height'],
                                      self.ccd.ccdParams['width']))
                i = 0

                # flags for the event loop
                startThread = True  # needs to start a new acquisition
                self.plotMeas = False  # needs to plot the acquisition (acq finished)
                self.acquire = True  # CCD should be acquiring

                # wait for a loop to finish
                while self.acquiring:
                    pass

                self.acquiring = True  # the event loop below is active

                # acquisition event loop
                while self.acquire:
                    if startThread:
                        ccdThread = ExposureThread(
                            self.ccd,
                            self.exposureTime,
                            ilAcq=self.ilAcq,
                            ilCorrDoubleExpo=self.ilDoubleExpo)
                        ccdThread.start()
                        startThread = False
                        if self.capture and self.exposureTime > 1:
                            self.captureStartSound.play()
                            #print 'start sound'

                    if not ccdThread.is_alive():  # acquisition finished
                        self.plotMeas = True
                        startThread = True

                    if self.plotMeas:
                        self.meas = ccdThread.ccd.pixels.transpose()

                        if self.ccd.ccdParams[
                                'isInterlaced'] and not self.ilAcq:  ##not self.ilAcq and
                            self.scale = (1, 2)
                        else:
                            self.scale = (1, 1)

                        # flip image according to user specification
                        #    note that due to pyqtgraph behaviour, the array
                        #    columns are the rows in the displayed image
                        if self.horizFlip:
                            self.meas = pl.flipud(self.meas)
                        if self.vertFlip:
                            self.meas = pl.fliplr(self.meas)

                        # plot image preview
                        self.plotImage(self.meas,
                                       autoLevels=self.autolevels,
                                       eqHist=self.equalizeHist,
                                       scale=self.scale)

                        if self.capture:
                            self.captureStopSound.play()
                            #print 'stop sound'
                            break  # will stop and record file in self.stop()
                        else:
                            self.plotMeas = False  # go for another acquisition

                    if ccdThread.ccd.completionPercentage == 100 or i % 100 == 0:
                        self.ui.progressBar.setValue(
                            ccdThread.ccd.completionPercentage)
                    self.displayStats()
                    # process events to catch a stop push and refresh image preview
                    self.app.processEvents()

                    i = i + 1

                #self.ui.progressBar.setValue(0)
                ccdThread.stop()
                while ccdThread.is_alive():  # wait before closing device
                    pass
                self.acquiring = False

        except IndexError:
            self.ui.modelName.setText('No device')
            self.ccd = None
        finally:
            self.stop(userStop=False)
Ejemplo n.º 41
0
import warnings
warnings.filterwarnings('ignore')

import numpy
import pylab

data = numpy.loadtxt('/tmp/input.txt')

pylab.figure(figsize=(6, 6))
pylab.xlabel('Destination Node')
pylab.ylabel('Source Node')
pylab.title('Adjacency Matrix')
pylab.pcolor(pylab.flipud(data), cmap=pylab.get_cmap('binary'))
pylab.xlim(0, len(data))
pylab.ylim(0, len(data))

pylab.savefig('/tmp/output.png')
Ejemplo n.º 42
0
from PIL import Image
import cv2
import time
import pylab as pl
from scipy.misc import imresize, imfilter
import turtle

counter = 1

img = pl.flipud(pl.imread("inputImages/%05d.jpg" % counter))
levels = 8
size = 2**levels

img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

turtle.setup(img.shape[1], img.shape[0])
img = imfilter(imresize(img, (size, size)), 'blur')

turtle.setworldcoordinates(0, 0, size, -size)
turtle.tracer(1000, 0)

time.sleep(.5)

# hilbert curve turtle code stolen from
# falko's python example on stackoverflow
# https://codegolf.stackexchange.com/questions/36374/redraw-an-image-with-just-one-closed-curve


# define recursive hilbert curve
def hilbert(level, angle=90):
    global img
Ejemplo n.º 43
0
def plot_topo(topoplotdata):
    """
    Plot topo data as specified by topoplotdata.
    """

    import os
    import pylab

    if topoplotdata.Z is None:
        topoplodata = read_topo(topoplotdata)
        
    x = topoplotdata.x
    y = topoplotdata.y
    topo = topoplotdata.Z
    X = topoplotdata.X
    Y = topoplotdata.Y
    xllcorner = x[0]
    yllcorner = y[0]
    cellsize = x[1]-x[0]
    
    
    fname = topoplotdata.fname 
    
    topotype = topoplotdata.topotype
    if topoplotdata.climits:
        # deprecated option
        cmin = topoplotdata.climits[0]
        cmax = topoplotdata.climits[1]
    else:
        cmin = topoplotdata.cmin
        cmax = topoplotdata.cmax
    figno = topoplotdata.figno
    addcolorbar = topoplotdata.addcolorbar
    addcontour = topoplotdata.addcontour
    contour_levels = topoplotdata.contour_levels
    xlimits = topoplotdata.xlimits
    ylimits = topoplotdata.ylimits
    coarsen = topoplotdata.coarsen
    imshow = topoplotdata.imshow
    gridedges_show = topoplotdata.gridedges_show
    neg_cmap = topoplotdata.neg_cmap
    pos_cmap = topoplotdata.pos_cmap
    cmap = topoplotdata.cmap
    clf = topoplotdata.clf
    print_fname = topoplotdata.print_fname



    if neg_cmap is None:
        neg_cmap = colormaps.make_colormap({cmin:[0.3,0.2,0.1],
                                                -0.00001:[0.95,0.9,0.7],
                                                0.00001:[.5,.7,0]})
    if pos_cmap is None:
        pos_cmap = colormaps.make_colormap({ -0.00001:[0.95,0.9,0.7],
                                     0.00001:[.5,.7,0],
                                        cmax:[.2,.5,.2]})
    if cmap is None:
        cmap = colormaps.make_colormap({cmin:[0.3,0.2,0.1],
                                           -0.00001:[0.95,0.9,0.7],
                                           0.00001:[.5,.7,0],
                                           cmax:[.2,.5,.2]})
        #cmap = colormaps.make_colormap({-1:[0,0,1],0:[1,1,1],1:[1,0,0]})
        
    #-------------
    if 0:
        if abs(topotype) == 1:

            X,Y,topo = topotools.topofile2griddata(fname, topotype)
            topo = pylab.flipud(topo)
            Y = pylab.flipud(Y)
            x = X[0,:]
            y = Y[:,0]
            xllcorner = x[0]
            yllcorner = y[0]
            cellsize = x[1]-x[0]


        elif abs(topotype) == 3:

            file = open(fname, 'r')
            lines = file.readlines()
            ncols = int(lines[0].split()[0])
            nrows = int(lines[1].split()[0])
            xllcorner = float(lines[2].split()[0])
            yllcorner = float(lines[3].split()[0])
            cellsize = float(lines[4].split()[0])
            NODATA_value = int(lines[5].split()[0])

            print "Loading file ",fname
            print "   nrows = %i, ncols = %i" % (nrows,ncols)
            topo = pylab.loadtxt(fname,skiprows=6,dtype=float)
            print "   Done loading"

            if 0:
                topo = []
                for i in range(nrows):
                    topo.append(pylab.array(lines[6+i],))
                print '+++ topo = ',topo
                topo = pylab.array(topo)

            topo = pylab.flipud(topo)

            x = pylab.linspace(xllcorner, xllcorner+ncols*cellsize, ncols)
            y = pylab.linspace(yllcorner, yllcorner+nrows*cellsize, nrows)
            print "Shape of x, y, topo: ", x.shape, y.shape, topo.shape

        else:
            raise Exception("*** Only topotypes 1 and 3 supported so far")
        
        if topotype < 0:
            topo = -topo
        
    
    #------------------

    ncols,nrows = topo.shape
    #import pdb; pdb.set_trace()
    
    if coarsen > 1:
        topo = topo[slice(0,nrows,coarsen), slice(0,ncols,coarsen)]
        X = X[slice(0,nrows,coarsen), slice(0,ncols,coarsen)]
        Y = Y[slice(0,nrows,coarsen), slice(0,ncols,coarsen)]
        x = x[slice(0,ncols,coarsen)]
        y = y[slice(0,nrows,coarsen)]
        print "Shapes after coarsening: ", x.shape, y.shape, topo.shape


    if figno:
        pylab.figure(figno)
    if clf:
        pylab.clf()

    if topoplotdata.imshow:
            color_norm = Normalize(cmin,cmax,clip=True)
            xylimits = (x[0],x[-1],y[0],y[-1])
            #pylab.imshow(pylab.flipud(topo.T), extent=xylimits, \
            pylab.imshow(topo, extent=xylimits, \
                    cmap=cmap, interpolation='nearest', \
                    norm=color_norm)
            #pylab.clim([cmin,cmax])
            if addcolorbar:
                pylab.colorbar(shrink=0.5)
    else:
        neg_topo = ma.masked_where(topo>0., topo)
        all_masked = (ma.count(neg_topo) == 0)
        if not all_masked:
            pylab.pcolormesh(X,Y,neg_topo,cmap=neg_cmap)
            pylab.clim([cmin,0])
            if addcolorbar:
                pylab.colorbar(shrink=0.5)

        pos_topo = ma.masked_where(topo<0., topo)
        all_masked = (ma.count(pos_topo) == 0)
        if not all_masked:
            pylab.pcolormesh(X,Y,pos_topo,cmap=pos_cmap)
            pylab.clim([0,cmax])
        if addcolorbar:
            pylab.colorbar(shrink=0.5)

    pylab.axis('scaled')


    if addcontour:
        pylab.contour(X,Y,topo,levels=contour_levels,colors='k')

    patchedges_show = True
    if patchedges_show:
        pylab.plot([x[0],x[-1]],[y[0],y[0]],'k')
        pylab.plot([x[0],x[-1]],[y[-1],y[-1]],'k')
        pylab.plot([x[0],x[0]],[y[0],y[-1]],'k')
        pylab.plot([x[-1],x[-1]],[y[0],y[-1]],'k')

    if print_fname:
        fname2 = os.path.splitext(fname)[0]
        pylab.text(xllcorner+cellsize, yllcorner+cellsize, fname2, color='m')

    topodata = object()
    topodata.x = x
    topodata.y = y
    topodata.topo = topo

    return topodata
Ejemplo n.º 44
0
import pylab as pl
from scipy.misc import imresize, imfilter
import turtle

# load image
img = pl.flipud(pl.imread("face.png"))

# setup turtle
levels = 8
size = 2**levels
turtle.setup(img.shape[1] * 4.2, img.shape[0] * 4.2)
turtle.setworldcoordinates(0, 0, size, -size)
turtle.tracer(1000, 0)

# resize and blur image
img = imfilter(imresize(img, (size, size)), 'blur')


# define recursive hilbert curve
def hilbert(level, angle=90):
    if level == 0:
        return
    if level == 1 and img[-turtle.pos()[1], turtle.pos()[0]] > 128:
        turtle.forward(2**level - 1)
    else:
        turtle.right(angle)
        hilbert(level - 1, -angle)
        turtle.forward(1)
        turtle.left(angle)
        hilbert(level - 1, angle)
        turtle.forward(1)
Ejemplo n.º 45
0
def plot_topo_file(topoplotdata):
    """
    Read in a topo or bathy file and produce a pcolor map.
    """

    import os
    import pylab
    from pyclaw.data import Data

    fname = topoplotdata.fname
    topotype = getattr(topoplotdata, 'topotype', 3)
    cmap = getattr(topoplotdata, 'cmap', bathy3_colormap)
    climits = getattr(topoplotdata, 'climits', [-50, 50])
    figno = getattr(topoplotdata, 'figno', 200)
    addcolorbar = getattr(topoplotdata, 'addcolorbar', True)
    addcontour = getattr(topoplotdata, 'addcontour', False)
    contour_levels = getattr(topoplotdata, 'contour_levels', [0, 0])
    xlimits = getattr(topoplotdata, 'xlimits', None)
    ylimits = getattr(topoplotdata, 'ylimits', None)
    coarsen = getattr(topoplotdata, 'coarsen', 1)

    if abs(topotype) != 3:
        print "*** Only topotype = 3, -3 implemented so far."
        return

    file = open(fname, 'r')
    lines = file.readlines()
    ncols = int(lines[0].split()[0])
    nrows = int(lines[1].split()[0])
    xllcorner = float(lines[2].split()[0])
    yllcorner = float(lines[3].split()[0])
    cellsize = float(lines[4].split()[0])
    NODATA_value = int(lines[5].split()[0])

    print "Loading file ", fname
    print "   nrows = %i, ncols = %i" % (nrows, ncols)
    topo = pylab.loadtxt(fname, skiprows=6, dtype=float)
    print "   Done loading"

    if 0:
        topo = []
        for i in range(nrows):
            topo.append(pylab.array(lines[6 + i], ))
        print '+++ topo = ', topo
        topo = pylab.array(topo)

    topo = pylab.flipud(topo)
    if topotype < 0:
        topo = -topo

    x = pylab.linspace(xllcorner, xllcorner + ncols * cellsize, ncols)
    y = pylab.linspace(yllcorner, yllcorner + nrows * cellsize, nrows)
    print "Shape of x, y, topo: ", x.shape, y.shape, topo.shape

    if coarsen > 1:
        topo = topo[slice(0, nrows, coarsen), slice(0, ncols, coarsen)]
        x = x[slice(0, ncols, coarsen)]
        y = y[slice(0, nrows, coarsen)]
        print "Shapes after coarsening: ", x.shape, y.shape, topo.shape

    #import pdb; pdb.set_trace()

    if figno:
        pylab.figure(figno)

    pylab.pcolor(x, y, topo, cmap=cmap)
    pylab.clim(climits)
    pylab.axis('scaled')

    if addcolorbar:
        pylab.colorbar()

    if addcontour:
        pylab.contour(x, y, topo, levels=contour_levels, colors='k')

    gridedges_show = True
    if gridedges_show:
        pylab.plot([x[0], x[-1]], [y[0], y[0]], 'k')
        pylab.plot([x[0], x[-1]], [y[-1], y[-1]], 'k')
        pylab.plot([x[0], x[0]], [y[0], y[-1]], 'k')
        pylab.plot([x[-1], x[-1]], [y[0], y[-1]], 'k')

    fname2 = os.path.splitext(fname)[0]
    pylab.text(xllcorner + cellsize, yllcorner + cellsize, fname2, color='m')

    topodata = Data()
    topodata.x = x
    topodata.y = y
    topodata.topo = topo

    return topodata
Ejemplo n.º 46
0
def plot_topo_file(topoplotdata):
    """
    Read in a topo or bathy file and produce a pcolor map.
    """

    import os
    import pylab
    from pyclaw.data import Data

    fname = topoplotdata.fname
    topotype = topoplotdata.topotype
    if topoplotdata.climits:
        # deprecated option
        cmin = topoplotdata.climits[0]
        cmax = topoplotdata.climits[1]
    else:
        cmin = topoplotdata.cmin
        cmax = topoplotdata.cmax
    figno = topoplotdata.figno
    addcolorbar = topoplotdata.addcolorbar
    addcontour = topoplotdata.addcontour
    contour_levels = topoplotdata.contour_levels
    xlimits = topoplotdata.xlimits
    ylimits = topoplotdata.ylimits
    coarsen = topoplotdata.coarsen
    imshow = topoplotdata.imshow
    gridedges_show = topoplotdata.gridedges_show
    cmap = topoplotdata.cmap
    print_fname = topoplotdata.print_fname

    if cmap is None:
        cmap = colormaps.make_colormap({
            cmin: [0.3, 0.2, 0.1],
            0: [0.95, 0.9, 0.7],
            .01: [.5, .7, 0],
            cmax: [.2, .5, .2]
        })

    if abs(topotype) == 1:

        X, Y, topo = topotools.topofile2griddata(fname, topotype)
        topo = pylab.flipud(topo)
        Y = pylab.flipud(Y)
        x = X[0, :]
        y = Y[:, 0]
        xllcorner = x[0]
        yllcorner = y[0]
        cellsize = x[1] - x[0]

    elif abs(topotype) == 3:

        file = open(fname, 'r')
        lines = file.readlines()
        ncols = int(lines[0].split()[0])
        nrows = int(lines[1].split()[0])
        xllcorner = float(lines[2].split()[0])
        yllcorner = float(lines[3].split()[0])
        cellsize = float(lines[4].split()[0])
        NODATA_value = int(lines[5].split()[0])

        print "Loading file ", fname
        print "   nrows = %i, ncols = %i" % (nrows, ncols)
        topo = pylab.loadtxt(fname, skiprows=6, dtype=float)
        print "   Done loading"

        if 0:
            topo = []
            for i in range(nrows):
                topo.append(pylab.array(lines[6 + i], ))
            print '+++ topo = ', topo
            topo = pylab.array(topo)

        topo = pylab.flipud(topo)

        x = pylab.linspace(xllcorner, xllcorner + ncols * cellsize, ncols)
        y = pylab.linspace(yllcorner, yllcorner + nrows * cellsize, nrows)
        print "Shape of x, y, topo: ", x.shape, y.shape, topo.shape

    else:
        raise Exception("*** Only topotypes 1 and 3 supported so far")

    if coarsen > 1:
        topo = topo[slice(0, nrows, coarsen), slice(0, ncols, coarsen)]
        x = x[slice(0, ncols, coarsen)]
        y = y[slice(0, nrows, coarsen)]
        print "Shapes after coarsening: ", x.shape, y.shape, topo.shape

    if topotype < 0:
        topo = -topo

    if figno:
        pylab.figure(figno)

    if topoplotdata.imshow:
        color_norm = Normalize(cmin, cmax, clip=True)
        xylimits = (x[0], x[-1], y[0], y[-1])
        #pylab.imshow(pylab.flipud(topo.T), extent=xylimits, \
        pylab.imshow(pylab.flipud(topo), extent=xylimits, \
                cmap=cmap, interpolation='nearest', \
                norm=color_norm)
    else:
        pylab.pcolor(x, y, topo, cmap=cmap)
        pylab.clim([cmin, cmax])
    pylab.axis('scaled')

    if addcolorbar:
        pylab.colorbar()

    if addcontour:
        pylab.contour(x, y, topo, levels=contour_levels, colors='k')

    if gridedges_show:
        pylab.plot([x[0], x[-1]], [y[0], y[0]], 'k')
        pylab.plot([x[0], x[-1]], [y[-1], y[-1]], 'k')
        pylab.plot([x[0], x[0]], [y[0], y[-1]], 'k')
        pylab.plot([x[-1], x[-1]], [y[0], y[-1]], 'k')

    if print_fname:
        fname2 = os.path.splitext(fname)[0]
        pylab.text(xllcorner + cellsize,
                   yllcorner + cellsize,
                   fname2,
                   color='m')

    topodata = Data()
    topodata.x = x
    topodata.y = y
    topodata.topo = topo

    return topodata
Ejemplo n.º 47
0
def plot_topo_file(topoplotdata):
    """
    Read in a topo or bathy file and produce a pcolor map.
    """

    import os
    import pylab
    from pyclaw.data import Data

    fname = topoplotdata.fname
    topotype = topoplotdata.topotype
    if topoplotdata.climits:
        # deprecated option
        cmin = topoplotdata.climits[0]
        cmax = topoplotdata.climits[1]
    else:
        cmin = topoplotdata.cmin
        cmax = topoplotdata.cmax
    figno = topoplotdata.figno
    addcolorbar = topoplotdata.addcolorbar
    addcontour = topoplotdata.addcontour
    contour_levels = topoplotdata.contour_levels
    xlimits = topoplotdata.xlimits
    ylimits = topoplotdata.ylimits
    coarsen = topoplotdata.coarsen
    imshow = topoplotdata.imshow
    gridedges_show = topoplotdata.gridedges_show
    neg_cmap = topoplotdata.neg_cmap
    pos_cmap = topoplotdata.pos_cmap
    print_fname = topoplotdata.print_fname


    if neg_cmap is None:
        neg_cmap = colormaps.make_colormap({cmin:[0.3,0.2,0.1],
                                                0:[0.95,0.9,0.7]})
    if pos_cmap is None:
        pos_cmap = colormaps.make_colormap({    0:[.5,.7,0],
                                              cmax:[.2,.5,.2]})

    if abs(topotype) == 1:

        X,Y,topo = topotools.topofile2griddata(fname, topotype)
        topo = pylab.flipud(topo)
        Y = pylab.flipud(Y)
        x = X[0,:]
        y = Y[:,0]
        xllcorner = x[0]
        yllcorner = y[0]
        cellsize = x[1]-x[0]


    elif abs(topotype) == 3:

        file = open(fname, 'r')
        lines = file.readlines()
        ncols = int(lines[0].split()[0])
        nrows = int(lines[1].split()[0])
        xllcorner = float(lines[2].split()[0])
        yllcorner = float(lines[3].split()[0])
        cellsize = float(lines[4].split()[0])
        NODATA_value = int(lines[5].split()[0])

        print "Loading file ",fname
        print "   nrows = %i, ncols = %i" % (nrows,ncols)
        topo = pylab.loadtxt(fname,skiprows=6,dtype=float)
        print "   Done loading"

        if 0:
            topo = []
            for i in range(nrows):
                topo.append(pylab.array(lines[6+i],))
            print '+++ topo = ',topo
            topo = pylab.array(topo)

        topo = pylab.flipud(topo)

        x = pylab.linspace(xllcorner, xllcorner+ncols*cellsize, ncols)
        y = pylab.linspace(yllcorner, yllcorner+nrows*cellsize, nrows)
        print "Shape of x, y, topo: ", x.shape, y.shape, topo.shape

    else:
        raise Exception("*** Only topotypes 1 and 3 supported so far")


    if coarsen > 1:
        topo = topo[slice(0,nrows,coarsen), slice(0,ncols,coarsen)]
        x = x[slice(0,ncols,coarsen)]
        y = y[slice(0,nrows,coarsen)]
        print "Shapes after coarsening: ", x.shape, y.shape, topo.shape


    if topotype < 0:
        topo = -topo

    if figno:
        pylab.figure(figno)

    if topoplotdata.imshow:
            color_norm = Normalize(cmin,cmax,clip=True)
            xylimits = (x[0],x[-1],y[0],y[-1])
            #pylab.imshow(pylab.flipud(topo.T), extent=xylimits, \
            pylab.imshow(pylab.flipud(topo), extent=xylimits, \
                    cmap=cmap, interpolation='nearest', \
                    norm=color_norm)
    else:
        neg_topo = ma.masked_where(topo>0., topo)
        all_masked = (ma.count(neg_topo) == 0)
        if not all_masked:
            pylab.pcolormesh(x,y,neg_topo,cmap=neg_cmap)
            pylab.clim([cmin,0])
            if addcolorbar:
                pylab.colorbar()

        pos_topo = ma.masked_where(topo<0., topo)
        all_masked = (ma.count(pos_topo) == 0)
        if not all_masked:
            pylab.pcolormesh(x,y,pos_topo,cmap=pos_cmap)
            pylab.clim([0,cmax])
            if addcolorbar:
                pylab.colorbar()

    pylab.axis('scaled')


    if addcontour:
        pylab.contour(x,y,topo,levels=contour_levels,colors='k')

    if gridedges_show:
        pylab.plot([x[0],x[-1]],[y[0],y[0]],'k')
        pylab.plot([x[0],x[-1]],[y[-1],y[-1]],'k')
        pylab.plot([x[0],x[0]],[y[0],y[-1]],'k')
        pylab.plot([x[-1],x[-1]],[y[0],y[-1]],'k')

    if print_fname:
        fname2 = os.path.splitext(fname)[0]
        pylab.text(xllcorner+cellsize, yllcorner+cellsize, fname2, color='m')

    topodata = Data()
    topodata.x = x
    topodata.y = y
    topodata.topo = topo

    return topodata
Ejemplo n.º 48
0
import pylab as pl
from scipy.misc import imresize, imfilter
import turtle

# load image
img = pl.flipud(pl.imread(".ily.png"))
a=turtle.Turtle()
s=turtle.Screen()
s.setup(400,400)
s.delay(5000)
# setup turtle
levels = 8
size = 2**levels
turtle.setup(img.shape[1] * 4.2, img.shape[0] * 4.2)
turtle.setworldcoordinates(0, 0, size, -size)
turtle.tracer(1000, 0)

# resize and blur image
img = imfilter(imresize(img, (size, size)), 'blur')

# define recursive hilbert curve
def hilbert(level, angle = 90):
    if level == 0:
        return
    if level == 1 and img[-turtle.pos()[1], turtle.pos()[0]] > 128:
        turtle.forward(2**level - 1)
    else:
        turtle.right(angle)
        hilbert(level - 1, -angle)
        turtle.forward(1)
        turtle.left(angle)
Ejemplo n.º 49
0
 if doBGcorrect:
     for l in xrange(data.shape[1]):
         indf = data[:,l] < (pl.median(data[:,l]))
         poly = rt.PolynomialFit(channels, data[:,l], indf=indf)
         data[:,l] -= poly
 data /= mon
 if "3d" in colname and not saveonly:
     if "-log" in colname:
         imdata = pl.log(data)
         ind = pl.isfinite(imdata)
     else:
         imdata = data
         ind = slice(None)
     vmin[j] = 0#min(vmin[j], imdata[ind].min())
     vmax[j] = max(vmax[j], imdata[ind].max())
     thisax.imshow(pl.flipud(imdata), aspect="auto",
                      vmin=vmin[j], vmax=vmax[j],
                      extent=(x[0], x[-1], 0, data.shape[0]-1))
     thisax.set_title("#%i:  %s"%(i, scan.command()))
     thisax.grid(False)
 elif "2d" in colname:
     if "roi" in colname:
         imax = data.sum(1).argmax()
         ind = slice(imax - nint, imax + nint)
         print("Channels in roi: %i...%i"%(imax - nint, imax + nint))
     elif "sum" in colname:
         ind = slice(None)
     if not saveonly:
         thisax.plot(x, data[ind].sum(0), style, 
                        label="#%i:  %s"%(i, scan.command()))
         lblax = thisax
Ejemplo n.º 50
0
def build_fft(input_signal,
              filter_coefficients,
              threshold_windows=6,
              boundary=0):
    """generate fast transform fourier by windows
    Params :
        input_signal : the audio signal
        filter_coefficients : coefficients of the chirplet bank
        threshold_windows : calcul the size of the windows
        boundary : manage the bounds of the signal
    Returns :
        fast Fourier transform applied by windows to the audio signal

    """
    num_coeffs = filter_coefficients.size
    #print(n,boundary,M)
    half_size = num_coeffs // 2
    signal_size = input_signal.size
    #power of 2 to apply fast fourier transform
    windows_size = 2**ceil(log2(num_coeffs * (threshold_windows + 1)))
    number_of_windows = floor(signal_size // windows_size)

    if number_of_windows == 0:
        return fft_based(input_signal, filter_coefficients, boundary)

    windowed_fft = empty_like(input_signal)
    #pad with 0 to have a size in a power of 2
    windows_size = int(windows_size)

    zeropadding = np.lib.pad(filter_coefficients,
                             (0, windows_size - num_coeffs),
                             'constant',
                             constant_values=0)

    h_fft = fft(zeropadding)

    #to browse the whole signal
    current_pos = 0

    #apply fft to a part of the signal. This part has a size which is a power
    #of 2
    if boundary == 0:  #ZERO PADDING

        #window is half padded with since it's focused on the first half
        window = input_signal[current_pos:current_pos + windows_size -
                              half_size]
        zeropaddedwindow = np.lib.pad(window, (len(h_fft) - len(window), 0),
                                      'constant',
                                      constant_values=0)
        x_fft = fft(zeropaddedwindow)

    elif boundary == 1:  #SYMMETRIC
        window = concatenate([
            flipud(input_signal[:half_size]),
            input_signal[current_pos:current_pos + windows_size - half_size]
        ])
        x_fft = fft(window)

    else:
        x_fft = fft(input_signal[:windows_size])

    windowed_fft[:windows_size - num_coeffs] = (ifft(
        x_fft * h_fft)[num_coeffs - 1:-1]).real

    current_pos += windows_size - num_coeffs - half_size
    #apply fast fourier transofm to each windows
    while current_pos + windows_size - half_size <= signal_size:

        x_fft = fft(input_signal[current_pos - half_size:current_pos +
                                 windows_size - half_size])
        #Suppress the warning, work on the real/imagina
        windowed_fft[current_pos:current_pos + windows_size -
                     num_coeffs] = (ifft(x_fft * h_fft)[num_coeffs -
                                                        1:-1]).real
        current_pos += windows_size - num_coeffs
    # print(countloop)
    #apply fast fourier transform to the rest of the signal
    if windows_size - (signal_size - current_pos + half_size) < half_size:

        window = input_signal[current_pos - half_size:]
        zeropaddedwindow = np.lib.pad(
            window,
            (0, int(windows_size - (signal_size - current_pos + half_size))),
            'constant',
            constant_values=0)
        x_fft = fft(zeropaddedwindow)
        windowed_fft[current_pos:] = roll(ifft(
            x_fft * h_fft), half_size)[half_size:half_size +
                                       windowed_fft.size - current_pos].real
        windowed_fft[-half_size:] = convolve(input_signal[-num_coeffs:],
                                             filter_coefficients,
                                             'same')[-half_size:]
    else:

        window = input_signal[current_pos - half_size:]
        zeropaddedwindow = np.lib.pad(
            window,
            (0, int(windows_size - (signal_size - current_pos + half_size))),
            'constant',
            constant_values=0)
        x_fft = fft(zeropaddedwindow)
        windowed_fft[current_pos:] = ifft(
            x_fft * h_fft)[num_coeffs - 1:num_coeffs + windowed_fft.size -
                           current_pos - 1].real

    return windowed_fft