Beispiel #1
0
def plotIsoFreqNSimpedance(ax,freq,array,flag,par='abs',colorbar=True,colorNorm='SymLog',cLevel=True,contour=True):

    indUniFreq = np.where(freq==array['freq'])


    x, y = array['x'][indUniFreq],array['y'][indUniFreq]
    if par == 'abs':
        zPlot = np.abs(array[flag][indUniFreq])
        cmap = plt.get_cmap('OrRd_r')#seismic')
        level = np.logspace(0,-5,31)
        clevel = np.logspace(0,-4,5)
        plotNorm = colors.LogNorm()
    elif par == 'real':
        zPlot = np.real(array[flag][indUniFreq])
        cmap = plt.get_cmap('RdYlBu')
        if cLevel:
            level = np.concatenate((-np.logspace(0,-10,31),np.logspace(-10,0,31)))
            clevel = np.concatenate((-np.logspace(0,-8,5),np.logspace(-8,0,5)))
        else:
            level = np.linspace(zPlot.min(),zPlot.max(),100)
            clevel = np.linspace(zPlot.min(),zPlot.max(),10)
        if colorNorm=='SymLog':
            plotNorm = colors.SymLogNorm(1e-10,linscale=2)
        else:
            plotNorm = colors.Normalize()
    elif par == 'imag':
        zPlot = np.imag(array[flag][indUniFreq])
        cmap = plt.get_cmap('RdYlBu')
        level = np.concatenate((-np.logspace(0,-10,31),np.logspace(-10,0,31)))
        clevel = np.concatenate((-np.logspace(0,-8,5),np.logspace(-8,0,5)))
        plotNorm = colors.SymLogNorm(1e-10,linscale=2)
        if cLevel:
            level = np.concatenate((-np.logspace(0,-10,31),np.logspace(-10,0,31)))
            clevel = np.concatenate((-np.logspace(0,-8,5),np.logspace(-8,0,5)))
        else:
            level = np.linspace(zPlot.min(),zPlot.max(),100)
            clevel = np.linspace(zPlot.min(),zPlot.max(),10)
        if colorNorm=='SymLog':
            plotNorm = colors.SymLogNorm(1e-10,linscale=2)
        elif colorNorm=='Lin':
            plotNorm = colors.Normalize()
    if contour:
        cs = ax.tricontourf(x,y,zPlot,levels=level,cmap=cmap,norm=plotNorm)#,extend='both')
    else:
        uniX,uniY = np.unique(x),np.unique(y)
        X,Y = np.meshgrid(np.append(uniX-25,uniX[-1]+25),np.append(uniY-25,uniY[-1]+25))
        cs = ax.pcolor(X,Y,np.reshape(zPlot,(len(uniY),len(uniX))),cmap=cmap,norm=plotNorm)
    if colorbar:
        plt.colorbar(cs,cax=ax.cax,ticks=clevel,format='%1.2e')
        ax.set_title(flag+' '+par,fontsize=8)
    return cs
Beispiel #2
0
    def Fit(self,Source,X=None,function='line',Guess=numpy.ones(10),Show_Residuals=True,StartP=None,EndP=None,StartX=None,EndX=None,Show_Guess=False,Figure=None,Rendering=True,RAW_Data=True,Color='r',Show_Parameters=True,Number_of_points=1000.,Bounds=[[None,None]]*10,Model=False):
        """
        Source is the signal to fit
        X is the XScale
        function is the fitting function.
        Avaible functions are : line,
                                poly2,
                                poly3,
                                poly4,
                                gauss,
                                exp,
                                double_exp,
                                double_exp_xoffset,
                                sin,
                                hill,
                                sigmoid,
                                power,
                                beta
        p0 are the intitial guesses (default is a list of 1.)
        StartP and EndP are the start point and the End point of the fit (in points)
        StartX and EndX are the start point and the End point of the fit (in timescale units)
        """
        
        def find_indexes(Source,Min,Max):
        	c=abs(numpy.array(Source)-Min)
        	Min_index=list(c).index(min(c))
        	c=abs(numpy.array(Source)-Max)
        	Max_index=list(c).index(min(c))
        	return Min_index,Max_index    

        begin=X[0] #original begin and end points are stored here, so the final plot will be displayed in the original workspace
        end=X[-1]        
        if (StartP == None) and (StartX == None) :
            StartP=0
            StartX=0
        if (EndP == None) and (EndX == None) == None:
            EndP=len(Source)-1   
            EndX=len(Source)-1 
        
        if (StartP == None) or (EndP == None) :
            StartP,EndP=find_indexes(X,StartX,EndX) 
        else:
            StartX=X[StartP]
            EndX=X[EndP]


        Source=numpy.array(Source[StartP:EndP]) #if not using the whole range for the fit, truncated wave is created here
        X=numpy.array(X[StartP:EndP]) #if not using the whole range for the fit, truncated timescale is created here


    	# Data and Xscale
        Source = numpy.array(Source)
        if X==None or (len(Source) != len(X)):
            X = numpy.array(range(len(Source)))
            # create a set of Parameters

        Function=eval("self."+function) #the fitting function
        Formula=eval("self."+function.capitalize())[0] #the fitting formula
        Parameters_Names=eval("self."+function.capitalize())[1] ##list of the fitting parameters            
            



        for i,j in enumerate(Bounds):
            if Bounds[i][0] != None:
                Bounds[i][0]=numpy.float32(Bounds[i][0])
            if Bounds[i][1] != None:
                Bounds[i][1]=numpy.float32(Bounds[i][1])
        
        #print Bounds
        
        p0 = Parameters()

       
        # do fit, here with leastsq model
        if Model == False:
           
            for i,j in enumerate(Parameters_Names):
                #For each paramters, you can set value, min & max. i.e. p0.add('omega', value= 0.0, min=-numpy.pi/2., max=numpy.pi/2)
                if j != '0':
                    if Bounds[i][0] != None and Bounds[i][1]!=None:
                        p0.add(j,value=Guess[i],min=Bounds[i][0],max=Bounds[i][1])
                    elif Bounds[i][0] !=None and Bounds[i][1]==None:
                        p0.add(j,value=Guess[i],min=Bounds[i][0])     
                    elif Bounds[i][0] == None and Bounds[i][1] != None:
                        p0.add(j,value=Guess[i],max=Bounds[i][1])
                    else:
                        p0.add(j,value=Guess[i])            
            print 'Fitting in process ...'
            try:
                result = minimize(Function, p0, args=(X, Source))
                RenderingX=numpy.linspace(float(X[0]),float(X[-1]),num=Number_of_points)
                fit = Function(result.params,RenderingX) #Rendering, with Popt, the best fitting parameters
            except:
                print 'Fitting failed, try other parameters or constraints'
                return
            print 'Fitting performed between points ',StartP,' and ',EndP, ' (',len(X),' points)'
            print 'in units between: ',StartX,' and ',EndX
            print '######### FITTING RESULTS ############'
            print 'Parameters are :' 
            res=[]
            for i in list(result.params):
                print i, result.params[i].value  
                res.append(result.params[i].value)
            
        elif Model== True:
            for i,j in enumerate(Parameters_Names):
                if j != '0':
                    p0.add(j,value=Guess[i])             
            RenderingX=numpy.linspace(float(X[0]),float(X[-1]),num=Number_of_points)
            fit = Function(p0,RenderingX) #Rendering, with Popt, the best fitting parameters            

#        if Show_Parameters == True:
#            for i in range(len(popt)):
#                if List[i][0] != '0':
#                    try:
#                        pyplot.text(begin+((end-begin)/10), max(fit)-(i+1)*abs((max(fit)-min(fit))/(10)), r"%s = {%s} +/- {%s}" % ((str(List[i][0])),str(float(popt[i])),str(float((pcov[i][i])**0.5))))# .format(popt[i], (pcov[i][i])**0.5))
#                    except:
#                        pyplot.text(begin+((end-begin)/10), max(fit)-(i+1)*abs((max(fit)-min(fit))/(10)),'test')

        #if Show_Error_Bars == True: to do
            #pyplot.errorbar(X, Source, yerr = y_sigma, fmt = 'o')    

        
#        if Show_Guess == True:
#            guess=Function(X,*p0)
#            G,=pyplot.plot(X, guess, label='Test data',marker='o',color='g') 
#            if RAW_Data == True:
#                pyplot.legend([S, G, F], ["Data", "initial guess", "Fit"], loc='best',fancybox=True)
#            else:
#                pyplot.legend([G, F], ["initial guess", "Fit"], loc='best',fancybox=True)
#        else:
#            if RAW_Data == True:
#                pyplot.legend([S, F], ["Data", "Fit"], loc='best',fancybox=True)
#            else:
#                pyplot.legend([F], ["Fit"], loc='best',fancybox=True)

        if Rendering == True:
            pyplot.rc('axes',fc='white')
            if Figure == None: #Creation of the figure. If Figure is not None, the fit is integrated in pre-existing figure
                fig=pyplot.figure(facecolor='white')
            else:
                fig = Figure   
                
            pyplot.title('Fitting completed')        
            if RAW_Data == True:
                S,=pyplot.plot(X, Source,color='b')
                
            try:
                if Show_Residuals == True:
                    final = Source + result.residual
                    pyplot.plot(X, final, 'r')
            except UnboundLocalError: #Should be only in the Plugin, at first launch.
                print 'No results'
                
            F,=pyplot.plot(RenderingX, fit, linestyle='--',color=Color)
            
            pyplot.xlim([begin,end])
            pyplot.grid(True) 
            pyplot.show()
            return fit,res,fig
        else:
            return fit
Beispiel #3
0
def plotIsoFreqNSDiff(
    ax,
    freq,
    arrayList,
    flag,
    par="abs",
    colorbar=True,
    cLevel=True,
    mask=None,
    contourLine=True,
    useLog=False,
):

    indUniFreq0 = np.where(freq == arrayList[0]["freq"])
    indUniFreq1 = np.where(freq == arrayList[1]["freq"])
    seicmap = plt.get_cmap("RdYlBu")  # seismic')
    x, y = arrayList[0]["x"][indUniFreq0], arrayList[0]["y"][indUniFreq0]
    if par == "abs":
        if useLog:
            zPlot = (np.log10(np.abs(arrayList[0][flag][indUniFreq0])) -
                     np.log10(np.abs(arrayList[1][flag][indUniFreq1]))
                     ) / np.log10(np.abs(arrayList[1][flag][indUniFreq1]))
        else:
            zPlot = (np.abs(arrayList[0][flag][indUniFreq0]) -
                     np.abs(arrayList[1][flag][indUniFreq1])) / np.abs(
                         arrayList[1][flag][indUniFreq1])
        if mask:
            maskInd = np.logical_or(
                np.abs(arrayList[0][flag][indUniFreq0]) < 1e-3,
                np.abs(arrayList[1][flag][indUniFreq1]) < 1e-3,
            )
            zPlot = np.ma.array(zPlot)
            zPlot[maskInd] = mask
        if cLevel:
            level = np.arange(-200, 201, 10)
            clevel = np.arange(-200, 201, 25)
        else:
            level = np.linspace(zPlot.min(), zPlot.max(), 100)
            clevel = np.linspace(zPlot.min(), zPlot.max(), 10)
    elif par == "real":
        if useLog:
            zPlot = (
                np.log10(np.real(arrayList[0][flag][indUniFreq0])) -
                np.log10(np.real(arrayList[1][flag][indUniFreq1]))) / np.log10(
                    np.abs((np.real(arrayList[1][flag][indUniFreq1]))))
        else:
            zPlot = (np.real(arrayList[0][flag][indUniFreq0]) -
                     np.real(arrayList[1][flag][indUniFreq1])) / np.abs(
                         (np.real(arrayList[1][flag][indUniFreq1])))
        if mask:
            maskInd = np.logical_or(
                np.abs(np.real(arrayList[0][flag][indUniFreq0])) < 1e-3,
                np.abs(np.real(arrayList[1][flag][indUniFreq1])) < 1e-3,
            )
            zPlot = np.ma.array(zPlot)
            zPlot[maskInd] = mask
        if cLevel:
            level = np.arange(-200, 201, 10)
            clevel = np.arange(-200, 201, 25)
        else:
            level = np.linspace(zPlot.min(), zPlot.max(), 100)
            clevel = np.linspace(zPlot.min(), zPlot.max(), 10)
    elif par == "imag":
        if useLog:
            zPlot = (
                np.log10(np.imag(arrayList[0][flag][indUniFreq0])) -
                np.log10(np.imag(arrayList[1][flag][indUniFreq1]))) / np.log10(
                    np.abs((np.imag(arrayList[1][flag][indUniFreq1]))))
        else:
            zPlot = (np.imag(arrayList[0][flag][indUniFreq0]) -
                     np.imag(arrayList[1][flag][indUniFreq1])) / np.abs(
                         (np.imag(arrayList[1][flag][indUniFreq1])))
        if mask:
            maskInd = np.logical_or(
                np.abs(np.imag(arrayList[0][flag][indUniFreq0])) < 1e-3,
                np.abs(np.imag(arrayList[1][flag][indUniFreq1])) < 1e-3,
            )
            zPlot = np.ma.array(zPlot)
            zPlot[maskInd] = mask
        if cLevel:
            level = np.arange(-200, 201, 10)
            clevel = np.arange(-200, 201, 25)
        else:
            level = np.linspace(zPlot.min(), zPlot.max(), 100)
            clevel = np.linspace(zPlot.min(), zPlot.max(), 10)
    cs = ax.tricontourf(
        x, y, zPlot * 100, levels=level * 100, cmap=seicmap,
        extend="both")  # ,norm=colors.SymLogNorm(1e-2,linscale=2))
    if contourLine:
        csl = ax.tricontour(x, y, zPlot * 100, levels=clevel * 100, colors="k")
        plt.clabel(csl, fontsize=7, inline=1, fmt="%1.1e", inline_spacing=10)
    if colorbar:
        cb = plt.colorbar(cs, cax=ax.cax, ticks=clevel * 100, format="%1.1e")
        for t in cb.ax.get_yticklabels():
            t.set_rotation(60)
            t.set_fontsize(8)

    ax.set_title(flag + " " + par, fontsize=8)
Beispiel #4
0
def plotIsoFreqNSimpedance(
    ax,
    freq,
    array,
    flag,
    par="abs",
    colorbar=True,
    colorNorm="SymLog",
    cLevel=True,
    contour=True,
):

    indUniFreq = np.where(freq == array["freq"])

    x, y = array["x"][indUniFreq], array["y"][indUniFreq]
    if par == "abs":
        zPlot = np.abs(array[flag][indUniFreq])
        cmap = plt.get_cmap("OrRd_r")  # seismic')
        level = np.logspace(0, -5, 31)
        clevel = np.logspace(0, -4, 5)
        plotNorm = colors.LogNorm()
    elif par == "real":
        zPlot = np.real(array[flag][indUniFreq])
        cmap = plt.get_cmap("RdYlBu")
        if cLevel:
            level = np.concatenate(
                (-np.logspace(0, -10, 31), np.logspace(-10, 0, 31)))
            clevel = np.concatenate(
                (-np.logspace(0, -8, 5), np.logspace(-8, 0, 5)))
        else:
            level = np.linspace(zPlot.min(), zPlot.max(), 100)
            clevel = np.linspace(zPlot.min(), zPlot.max(), 10)
        if colorNorm == "SymLog":
            plotNorm = colors.SymLogNorm(1e-10, linscale=2)
        else:
            plotNorm = colors.Normalize()
    elif par == "imag":
        zPlot = np.imag(array[flag][indUniFreq])
        cmap = plt.get_cmap("RdYlBu")
        level = np.concatenate(
            (-np.logspace(0, -10, 31), np.logspace(-10, 0, 31)))
        clevel = np.concatenate((-np.logspace(0, -8, 5), np.logspace(-8, 0,
                                                                     5)))
        plotNorm = colors.SymLogNorm(1e-10, linscale=2)
        if cLevel:
            level = np.concatenate(
                (-np.logspace(0, -10, 31), np.logspace(-10, 0, 31)))
            clevel = np.concatenate(
                (-np.logspace(0, -8, 5), np.logspace(-8, 0, 5)))
        else:
            level = np.linspace(zPlot.min(), zPlot.max(), 100)
            clevel = np.linspace(zPlot.min(), zPlot.max(), 10)
        if colorNorm == "SymLog":
            plotNorm = colors.SymLogNorm(1e-10, linscale=2)
        elif colorNorm == "Lin":
            plotNorm = colors.Normalize()
    if contour:
        cs = ax.tricontourf(x,
                            y,
                            zPlot,
                            levels=level,
                            cmap=cmap,
                            norm=plotNorm)  # ,extend='both')
    else:
        uniX, uniY = np.unique(x), np.unique(y)
        X, Y = np.meshgrid(np.append(uniX - 25, uniX[-1] + 25),
                           np.append(uniY - 25, uniY[-1] + 25))
        cs = ax.pcolor(X,
                       Y,
                       np.reshape(zPlot, (len(uniY), len(uniX))),
                       cmap=cmap,
                       norm=plotNorm)
    if colorbar:
        plt.colorbar(cs, cax=ax.cax, ticks=clevel, format="%1.2e")
        ax.set_title(flag + " " + par, fontsize=8)
    return cs
Beispiel #5
0
def plotPsudoSectNSimpedance(
    ax,
    sectDict,
    array,
    flag,
    par="abs",
    colorbar=True,
    colorNorm="None",
    cLevel=None,
    contour=True,
):

    indSect = np.where(sectDict.values()[0] == array[sectDict.keys()[0]])

    # Define the plot axes
    if "x" in sectDict.keys()[0]:
        x = array["y"][indSect]
    else:
        x = array["x"][indSect]
    y = array["freq"][indSect]

    if par == "abs":
        zPlot = np.abs(array[flag][indSect])
        cmap = plt.get_cmap("OrRd_r")  # seismic')
        if cLevel:
            level = np.logspace(0, -5, 31, endpoint=True)
            clevel = np.logspace(0, -4, 5, endpoint=True)
        else:
            level = np.linspace(zPlot.min(), zPlot.max(), 100, endpoint=True)
            clevel = np.linspace(zPlot.min(), zPlot.max(), 10, endpoint=True)

    elif par == "ares":
        zPlot = np.abs(array[flag][indSect])**2 / (8 * np.pi**2 * 10**(-7) *
                                                   array["freq"][indSect])
        cmap = plt.get_cmap("RdYlBu")  # seismic)
        if cLevel:
            zMax = np.log10(cLevel[1])
            zMin = np.log10(cLevel[0])
        else:
            zMax = np.ceil(np.log10(np.abs(zPlot).max()))
            zMin = np.floor(np.log10(np.abs(zPlot).min()))
        level = np.logspace(zMin, zMax, (zMax - zMin) * 8 + 1, endpoint=True)
        clevel = np.logspace(zMin, zMax, (zMax - zMin) * 2 + 1, endpoint=True)
        plotNorm = colors.LogNorm()

    elif par == "aphs":
        zPlot = np.arctan2(array[flag][indSect].imag,
                           array[flag][indSect].real) * (180 / np.pi)
        cmap = plt.get_cmap("RdYlBu")  # seismic)
        if cLevel:
            zMax = cLevel[1]
            zMin = cLevel[0]
        else:
            zMax = np.ceil(zPlot).max()
            zMin = np.floor(zPlot).min()
        level = np.arange(zMin, zMax + 0.1, 1)
        clevel = np.arange(zMin, zMax + 0.1, 10)
        plotNorm = colors.Normalize()

    elif par == "real":
        zPlot = np.real(array[flag][indSect])
        cmap = plt.get_cmap("Spectral")  # ('RdYlBu')
        if cLevel:
            zMax = np.log10(cLevel[1])
            zMin = np.log10(cLevel[0])
        else:
            zMax = np.ceil(np.log10(np.abs(zPlot).max()))
            zMin = np.floor(np.log10(np.abs(zPlot).min()))
        level = np.concatenate((
            -np.logspace(
                zMax, zMin - 0.125, (zMax - zMin) * 8 + 1, endpoint=True),
            np.logspace(zMin - 0.125,
                        zMax, (zMax - zMin) * 8 + 1,
                        endpoint=True),
        ))
        clevel = np.concatenate((
            -np.logspace(zMax, zMin, (zMax - zMin) * 1 + 1, endpoint=True),
            np.logspace(zMin, zMax, (zMax - zMin) * 1 + 1, endpoint=True),
        ))
        plotNorm = colors.SymLogNorm(np.abs(level).min(), linscale=0.1)
    elif par == "imag":
        zPlot = np.imag(array[flag][indSect])
        cmap = plt.get_cmap("Spectral")  # ('RdYlBu')

        if cLevel:
            zMax = np.log10(cLevel[1])
            zMin = np.log10(cLevel[0])
        else:
            zMax = np.ceil(np.log10(np.abs(zPlot).max()))
            zMin = np.floor(np.log10(np.abs(zPlot).min()))
        level = np.concatenate((
            -np.logspace(
                zMax, zMin - 0.125, (zMax - zMin) * 8 + 1, endpoint=True),
            np.logspace(zMin - 0.125,
                        zMax, (zMax - zMin) * 8 + 1,
                        endpoint=True),
        ))
        clevel = np.concatenate((
            -np.logspace(zMax, zMin, (zMax - zMin) * 1 + 1, endpoint=True),
            np.logspace(zMin, zMax, (zMax - zMin) * 1 + 1, endpoint=True),
        ))
        plotNorm = colors.SymLogNorm(np.abs(level).min(), linscale=0.1)

    if colorNorm == "SymLog":
        plotNorm = colors.SymLogNorm(np.abs(level).min(), linscale=0.1)
    elif colorNorm == "Lin":
        plotNorm = colors.Normalize()
    elif colorNorm == "Log":
        plotNorm = colors.LogNorm()
    if contour:
        cs = ax.tricontourf(x,
                            y,
                            zPlot,
                            levels=level,
                            cmap=cmap,
                            norm=plotNorm)  # ,extend='both')
    else:
        uniX, uniY = np.unique(x), np.unique(y)
        X, Y = np.meshgrid(np.append(uniX - 25, uniX[-1] + 25),
                           np.append(uniY - 25, uniY[-1] + 25))
        cs = ax.pcolor(X,
                       Y,
                       np.reshape(zPlot, (len(uniY), len(uniX))),
                       cmap=cmap,
                       norm=plotNorm)
    if colorbar:
        csB = plt.colorbar(cs, cax=ax.cax, ticks=clevel, format="%1.2e")
        # csB.on_mappable_changed(cs)
        ax.set_title(flag + " " + par, fontsize=8)
        return cs, csB
    return cs, None
Beispiel #6
0
    def Fit(self,
            Source,
            X=None,
            function='line',
            Guess=numpy.ones(10),
            Show_Residuals=True,
            StartP=None,
            EndP=None,
            StartX=None,
            EndX=None,
            Show_Guess=False,
            Figure=None,
            Rendering=True,
            RAW_Data=True,
            Color='r',
            Show_Parameters=True,
            Number_of_points=1000.,
            Bounds=[[None, None]] * 10,
            Model=False):
        """
        Source is the signal to fit
        X is the XScale
        function is the fitting function.
        Avaible functions are : line,
                                poly2,
                                poly3,
                                poly4,
                                gauss,
                                exp,
                                double_exp,
                                double_exp_xoffset,
                                sin,
                                hill,
                                sigmoid,
                                power,
                                beta
        p0 are the intitial guesses (default is a list of 1.)
        StartP and EndP are the start point and the End point of the fit (in points)
        StartX and EndX are the start point and the End point of the fit (in timescale units)
        """
        def find_indexes(Source, Min, Max):
            c = abs(numpy.array(Source) - Min)
            Min_index = list(c).index(min(c))
            c = abs(numpy.array(Source) - Max)
            Max_index = list(c).index(min(c))
            return Min_index, Max_index

        begin = X[
            0]  #original begin and end points are stored here, so the final plot will be displayed in the original workspace
        end = X[-1]
        if (StartP == None) and (StartX == None):
            StartP = 0
            StartX = 0
        if (EndP == None) and (EndX == None) == None:
            EndP = len(Source) - 1
            EndX = len(Source) - 1

        if (StartP == None) or (EndP == None):
            StartP, EndP = find_indexes(X, StartX, EndX)
        else:
            StartX = X[StartP]
            EndX = X[EndP]

        Source = numpy.array(
            Source[StartP:EndP]
        )  #if not using the whole range for the fit, truncated wave is created here
        X = numpy.array(
            X[StartP:EndP]
        )  #if not using the whole range for the fit, truncated timescale is created here

        # Data and Xscale
        Source = numpy.array(Source)
        if X == None or (len(Source) != len(X)):
            X = numpy.array(range(len(Source)))
            # create a set of Parameters

        Function = eval("self." + function)  #the fitting function
        Formula = eval("self." +
                       function.capitalize())[0]  #the fitting formula
        Parameters_Names = eval("self." + function.capitalize())[
            1]  ##list of the fitting parameters

        for i, j in enumerate(Bounds):
            if Bounds[i][0] != None:
                Bounds[i][0] = numpy.float32(Bounds[i][0])
            if Bounds[i][1] != None:
                Bounds[i][1] = numpy.float32(Bounds[i][1])

        #print Bounds

        p0 = Parameters()

        # do fit, here with leastsq model
        if Model == False:

            for i, j in enumerate(Parameters_Names):
                #For each paramters, you can set value, min & max. i.e. p0.add('omega', value= 0.0, min=-numpy.pi/2., max=numpy.pi/2)
                if j != '0':
                    if Bounds[i][0] != None and Bounds[i][1] != None:
                        p0.add(j,
                               value=Guess[i],
                               min=Bounds[i][0],
                               max=Bounds[i][1])
                    elif Bounds[i][0] != None and Bounds[i][1] == None:
                        p0.add(j, value=Guess[i], min=Bounds[i][0])
                    elif Bounds[i][0] == None and Bounds[i][1] != None:
                        p0.add(j, value=Guess[i], max=Bounds[i][1])
                    else:
                        p0.add(j, value=Guess[i])
            print 'Fitting in process ...'
            try:
                result = minimize(Function, p0, args=(X, Source))
                RenderingX = numpy.linspace(float(X[0]),
                                            float(X[-1]),
                                            num=Number_of_points)
                fit = Function(
                    result.params, RenderingX
                )  #Rendering, with Popt, the best fitting parameters
            except:
                print 'Fitting failed, try other parameters or constraints'
                return
            print 'Fitting performed between points ', StartP, ' and ', EndP, ' (', len(
                X), ' points)'
            print 'in units between: ', StartX, ' and ', EndX
            print '######### FITTING RESULTS ############'
            print 'Parameters are :'
            res = []
            for i in list(result.params):
                print i, result.params[i].value
                res.append(result.params[i].value)

        elif Model == True:
            for i, j in enumerate(Parameters_Names):
                if j != '0':
                    p0.add(j, value=Guess[i])
            RenderingX = numpy.linspace(float(X[0]),
                                        float(X[-1]),
                                        num=Number_of_points)
            fit = Function(
                p0,
                RenderingX)  #Rendering, with Popt, the best fitting parameters

#        if Show_Parameters == True:
#            for i in range(len(popt)):
#                if List[i][0] != '0':
#                    try:
#                        pyplot.text(begin+((end-begin)/10), max(fit)-(i+1)*abs((max(fit)-min(fit))/(10)), r"%s = {%s} +/- {%s}" % ((str(List[i][0])),str(float(popt[i])),str(float((pcov[i][i])**0.5))))# .format(popt[i], (pcov[i][i])**0.5))
#                    except:
#                        pyplot.text(begin+((end-begin)/10), max(fit)-(i+1)*abs((max(fit)-min(fit))/(10)),'test')

#if Show_Error_Bars == True: to do
#pyplot.errorbar(X, Source, yerr = y_sigma, fmt = 'o')

#        if Show_Guess == True:
#            guess=Function(X,*p0)
#            G,=pyplot.plot(X, guess, label='Test data',marker='o',color='g')
#            if RAW_Data == True:
#                pyplot.legend([S, G, F], ["Data", "initial guess", "Fit"], loc='best',fancybox=True)
#            else:
#                pyplot.legend([G, F], ["initial guess", "Fit"], loc='best',fancybox=True)
#        else:
#            if RAW_Data == True:
#                pyplot.legend([S, F], ["Data", "Fit"], loc='best',fancybox=True)
#            else:
#                pyplot.legend([F], ["Fit"], loc='best',fancybox=True)

        if Rendering == True:
            pyplot.rc('axes', fc='white')
            if Figure == None:  #Creation of the figure. If Figure is not None, the fit is integrated in pre-existing figure
                fig = pyplot.figure(facecolor='white')
            else:
                fig = Figure

            pyplot.title('Fitting completed')
            if RAW_Data == True:
                S, = pyplot.plot(X, Source, color='b')

            try:
                if Show_Residuals == True:
                    final = Source + result.residual
                    pyplot.plot(X, final, 'r')
            except UnboundLocalError:  #Should be only in the Plugin, at first launch.
                print 'No results'

            F, = pyplot.plot(RenderingX, fit, linestyle='--', color=Color)

            pyplot.xlim([begin, end])
            pyplot.grid(True)
            pyplot.show()
            return fit, res, fig
        else:
            return fit
Beispiel #7
0
def plotIsoFreqNStipper(ax,
                        freq,
                        array,
                        flag,
                        par='abs',
                        colorbar=True,
                        colorNorm='SymLog',
                        cLevel=True,
                        contour=True):

    indUniFreq = np.where(freq == array['freq'])

    x, y = array['x'][indUniFreq], array['y'][indUniFreq]
    if par == 'abs':
        cmap = plt.get_cmap('OrRd_r')  #seismic')
        zPlot = np.abs(array[flag][indUniFreq])
        if cLevel:
            level = np.logspace(-4, 0, 33)
            clevel = np.logspace(-4, 0, 5)
        else:
            level = np.linspace(zPlot.min(), zPlot.max(), 100)
            clevel = np.linspace(zPlot.min(), zPlot.max(), 10)
        if colorNorm == 'SymLog':
            plotNorm = colors.LogNorm()
        else:
            plotNorm = colors.Normalize()
    elif par == 'real':
        cmap = plt.get_cmap('RdYlBu')
        zPlot = np.real(array[flag][indUniFreq])
        if cLevel:
            level = np.concatenate(
                (-np.logspace(0, -4, 33), np.logspace(-4, 0, 33)))
            clevel = np.concatenate(
                (-np.logspace(0, -4, 5), np.logspace(-4, 0, 5)))
        else:
            level = np.linspace(zPlot.min(), zPlot.max(), 100)
            clevel = np.linspace(zPlot.min(), zPlot.max(), 10)
        if colorNorm == 'SymLog':
            plotNorm = colors.SymLogNorm(1e-4, linscale=2)
        else:
            plotNorm = colors.Normalize()
    elif par == 'imag':
        cmap = plt.get_cmap('RdYlBu')
        zPlot = np.imag(array[flag][indUniFreq])
        if cLevel:
            level = np.concatenate(
                (-np.logspace(0, -4, 33), np.logspace(-4, 0, 33)))
            clevel = np.concatenate(
                (-np.logspace(0, -4, 5), np.logspace(-4, 0, 5)))
        else:
            level = np.linspace(zPlot.min(), zPlot.max(), 100)
            clevel = np.linspace(zPlot.min(), zPlot.max(), 10)
        if colorNorm == 'SymLog':
            plotNorm = colors.SymLogNorm(1e-4, linscale=2)
        else:
            plotNorm = colors.Normalize()
    if contour:
        cs = ax.tricontourf(x,
                            y,
                            zPlot,
                            levels=level,
                            cmap=cmap,
                            norm=plotNorm)  #,extend='both')
    else:
        uniX, uniY = np.unique(x), np.unique(y)
        X, Y = np.meshgrid(np.append(uniX - 25, uniX[-1] + 25),
                           np.append(uniY - 25, uniY[-1] + 25))
        cs = ax.pcolor(X,
                       Y,
                       np.reshape(zPlot, (len(uniY), len(uniX))),
                       levels=level,
                       cmap=cmap,
                       norm=plotNorm,
                       edgecolors='k',
                       linewidths=0.5)
    if colorbar:
        plt.colorbar(cs, cax=ax.cax, ticks=clevel, format='%1.2e')
    ax.set_title(flag + ' ' + par, fontsize=8)
Beispiel #8
0
def plotIsoFreqNSDiff(ax,freq,arrayList,flag,par='abs',colorbar=True,cLevel=True,mask=None,contourLine=True,useLog=False):

    indUniFreq0 = np.where(freq==arrayList[0]['freq'])
    indUniFreq1 = np.where(freq==arrayList[1]['freq'])
    seicmap = plt.get_cmap('RdYlBu')#seismic')
    x, y = arrayList[0]['x'][indUniFreq0],arrayList[0]['y'][indUniFreq0]
    if par == 'abs':
        if useLog:
            zPlot = (np.log10(np.abs(arrayList[0][flag][indUniFreq0])) - np.log10(np.abs(arrayList[1][flag][indUniFreq1])))/np.log10(np.abs(arrayList[1][flag][indUniFreq1]))
        else:
            zPlot = (np.abs(arrayList[0][flag][indUniFreq0]) - np.abs(arrayList[1][flag][indUniFreq1]))/np.abs(arrayList[1][flag][indUniFreq1])
        if mask:
            maskInd = np.logical_or(np.abs(arrayList[0][flag][indUniFreq0])< 1e-3,np.abs(arrayList[1][flag][indUniFreq1]) < 1e-3)
            zPlot = np.ma.array(zPlot)
            zPlot[maskInd] = mask
        if cLevel:
            level = np.arange(-200,201,10)
            clevel = np.arange(-200,201,25)
        else:
            level = np.linspace(zPlot.min(),zPlot.max(),100)
            clevel = np.linspace(zPlot.min(),zPlot.max(),10)
    elif par == 'real':
        if useLog:
            zPlot = (np.log10(np.real(arrayList[0][flag][indUniFreq0])) -np.log10(np.real(arrayList[1][flag][indUniFreq1])))/np.log10(np.abs((np.real(arrayList[1][flag][indUniFreq1]))))
        else:
            zPlot = (np.real(arrayList[0][flag][indUniFreq0]) -np.real(arrayList[1][flag][indUniFreq1]))/np.abs((np.real(arrayList[1][flag][indUniFreq1])))
        if mask:
            maskInd = np.logical_or(np.abs(np.real(arrayList[0][flag][indUniFreq0])) < 1e-3,np.abs(np.real(arrayList[1][flag][indUniFreq1])) < 1e-3)
            zPlot = np.ma.array(zPlot)
            zPlot[maskInd] = mask
        if cLevel:
            level = np.arange(-200,201,10)
            clevel = np.arange(-200,201,25)
        else:
            level = np.linspace(zPlot.min(),zPlot.max(),100)
            clevel = np.linspace(zPlot.min(),zPlot.max(),10)
    elif par == 'imag':
        if useLog:
            zPlot = (np.log10(np.imag(arrayList[0][flag][indUniFreq0])) -np.log10(np.imag(arrayList[1][flag][indUniFreq1])))/np.log10(np.abs((np.imag(arrayList[1][flag][indUniFreq1]))))
        else:
            zPlot = (np.imag(arrayList[0][flag][indUniFreq0]) -np.imag(arrayList[1][flag][indUniFreq1]))/np.abs((np.imag(arrayList[1][flag][indUniFreq1])))
        if mask:
            maskInd = np.logical_or(np.abs(np.imag(arrayList[0][flag][indUniFreq0])) < 1e-3,np.abs(np.imag(arrayList[1][flag][indUniFreq1])) < 1e-3)
            zPlot = np.ma.array(zPlot)
            zPlot[maskInd] = mask
        if cLevel:
            level = np.arange(-200,201,10)
            clevel = np.arange(-200,201,25)
        else:
            level = np.linspace(zPlot.min(),zPlot.max(),100)
            clevel = np.linspace(zPlot.min(),zPlot.max(),10)
    cs = ax.tricontourf(x,y,zPlot*100,levels=level*100,cmap=seicmap,extend='both') #,norm=colors.SymLogNorm(1e-2,linscale=2))
    if contourLine:
        csl = ax.tricontour(x,y,zPlot*100,levels=clevel*100,colors='k')
        plt.clabel(csl, fontsize=7, inline=1,fmt='%1.1e',inline_spacing=10)
    if colorbar:
        cb = plt.colorbar(cs,cax=ax.cax,ticks=clevel*100,format='%1.1e')
        for t in cb.ax.get_yticklabels():
            t.set_rotation(60)
            t.set_fontsize(8)

    ax.set_title(flag+' '+par,fontsize=8)
Beispiel #9
0
def plotPsudoSectNSimpedance(ax,sectDict,array,flag,par='abs',colorbar=True,colorNorm='None',cLevel=None,contour=True):

    indSect = np.where(sectDict.values()[0]==array[sectDict.keys()[0]])

    # Define the plot axes
    if 'x' in sectDict.keys()[0]:
        x = array['y'][indSect]
    else:
        x = array['x'][indSect]
    y = array['freq'][indSect]

    if par == 'abs':
        zPlot = np.abs(array[flag][indSect])
        cmap = plt.get_cmap('OrRd_r')#seismic')
        if cLevel:
            level = np.logspace(0,-5,31,endpoint=True)
            clevel = np.logspace(0,-4,5,endpoint=True)
        else:
            level = np.linspace(zPlot.min(),zPlot.max(),100,endpoint=True)
            clevel = np.linspace(zPlot.min(),zPlot.max(),10,endpoint=True)

    elif par == 'ares':
        zPlot = np.abs(array[flag][indSect])**2/(8*np.pi**2*10**(-7)*array['freq'][indSect])
        cmap = plt.get_cmap('RdYlBu')#seismic)
        if cLevel:
            zMax = np.log10(cLevel[1])
            zMin = np.log10(cLevel[0])
        else:
            zMax = (np.ceil(np.log10(np.abs(zPlot).max())))
            zMin = (np.floor(np.log10(np.abs(zPlot).min())))
        level = np.logspace(zMin,zMax,(zMax-zMin)*8+1,endpoint=True)
        clevel = np.logspace(zMin,zMax,(zMax-zMin)*2+1,endpoint=True)
        plotNorm = colors.LogNorm()

    elif par == 'aphs':
        zPlot = np.arctan2(array[flag][indSect].imag,array[flag][indSect].real)*(180/np.pi)
        cmap = plt.get_cmap('RdYlBu')#seismic)
        if cLevel:
            zMax = cLevel[1]
            zMin = cLevel[0]
        else:
            zMax = (np.ceil(zPlot).max())
            zMin = (np.floor(zPlot).min())
        level = np.arange(zMin,zMax+.1,1)
        clevel = np.arange(zMin,zMax+.1,10)
        plotNorm = colors.Normalize()

    elif par == 'real':
        zPlot = np.real(array[flag][indSect])
        cmap = plt.get_cmap('Spectral') #('RdYlBu')
        if cLevel:
            zMax = np.log10(cLevel[1])
            zMin = np.log10(cLevel[0])
        else:
            zMax = (np.ceil(np.log10(np.abs(zPlot).max())))
            zMin = (np.floor(np.log10(np.abs(zPlot).min())))
        level = np.concatenate((-np.logspace(zMax,zMin-.125,(zMax-zMin)*8+1,endpoint=True),np.logspace(zMin-.125,zMax,(zMax-zMin)*8+1,endpoint=True)))
        clevel = np.concatenate((-np.logspace(zMax,zMin,(zMax-zMin)*1+1,endpoint=True),np.logspace(zMin,zMax,(zMax-zMin)*1+1,endpoint=True)))
        plotNorm = colors.SymLogNorm(np.abs(level).min(),linscale=0.1)
    elif par == 'imag':
        zPlot = np.imag(array[flag][indSect])
        cmap = plt.get_cmap('Spectral') #('RdYlBu')

        if cLevel:
            zMax = np.log10(cLevel[1])
            zMin = np.log10(cLevel[0])
        else:
            zMax = (np.ceil(np.log10(np.abs(zPlot).max())))
            zMin = (np.floor(np.log10(np.abs(zPlot).min())))
        level = np.concatenate((-np.logspace(zMax,zMin-.125,(zMax-zMin)*8+1,endpoint=True),np.logspace(zMin-.125,zMax,(zMax-zMin)*8+1,endpoint=True)))
        clevel = np.concatenate((-np.logspace(zMax,zMin,(zMax-zMin)*1+1,endpoint=True),np.logspace(zMin,zMax,(zMax-zMin)*1+1,endpoint=True)))
        plotNorm = colors.SymLogNorm(np.abs(level).min(),linscale=0.1)

    if colorNorm=='SymLog':
        plotNorm = colors.SymLogNorm(np.abs(level).min(),linscale=0.1)
    elif colorNorm=='Lin':
        plotNorm = colors.Normalize()
    elif colorNorm=='Log':
        plotNorm = colors.LogNorm()
    if contour:
        cs = ax.tricontourf(x,y,zPlot,levels=level,cmap=cmap,norm=plotNorm)#,extend='both')
    else:
        uniX,uniY = np.unique(x),np.unique(y)
        X,Y = np.meshgrid(np.append(uniX-25,uniX[-1]+25),np.append(uniY-25,uniY[-1]+25))
        cs = ax.pcolor(X,Y,np.reshape(zPlot,(len(uniY),len(uniX))),cmap=cmap,norm=plotNorm)
    if colorbar:
        csB = plt.colorbar(cs,cax=ax.cax,ticks=clevel,format='%1.2e')
        # csB.on_mappable_changed(cs)
        ax.set_title(flag+' '+par,fontsize=8)
        return cs, csB
    return cs,None
Beispiel #10
0
#!/usr/bin/python3

from matplotlib import pyplot, numpy
from math import pi, e

SAMPLES_N = 80
ARG_MAX = 2 * pi

arguments = list(numpy.linspace(0, ARG_MAX, SAMPLES_N + 1))

y = []
for x in arguments:
    y.append(e ** (1j * x))
y = numpy.array(y)

# Flat unit circle plot
figure = pyplot.figure()
ax = figure.add_subplot(121, xlabel="Re", ylabel="Im", title="Unit circle")
ax.scatter(y.real, y.imag, numpy.linspace(0, ARG_MAX, SAMPLES_N + 1) * 3)
ax.grid(True)

# 3D helix plot
ax2 = figure.add_subplot(122, projection='3d', xlabel="Re", ylabel="θ", zlabel="Im", title="Complex exponential")
ax2.plot(y.real, arguments, y.imag)

pyplot.show()
    print(supervivientes)
    while (i < maximo):
        r1 = random.randint(0, 3)
        r2 = random.randint(0, 3)
    return otraGeneracion


def f(x):
    return (-50 * x * x) + 500 * x


def f_dev(x):
    return (-100 * x) + 500


sample = np.linspace(-50, 100, num=30)
mutacion = 25
rangoSupervivencia = 4
poblacionInicial = generarPoblacion(8, 20, -10)
i = 1
index = -1
while (i < 50):
    j = 0
    r = 0
    print("Generacion " + str(i))
    print(poblacionInicial[0])

    for x in poblacionInicial[0]:
        res = f_dev(x)
        poblacionInicial[1].append(res)
Beispiel #12
0
#!/usr/bin/python3

#Exercise 1.4 in Owen's "Practical Signal Processing"

from matplotlib import pyplot, numpy, colors
from math import pi, e, radians

#Unit circle
SAMPLES_N = 160
ARG_MAX = 2 * pi
t = list(numpy.linspace(0, ARG_MAX, SAMPLES_N + 1))
y = list(map(lambda x: e**(1j * x), t))
y = numpy.array(y)

#Handles and labels for the legend
labels = [r'$e^{j\theta}$', 'Series A', 'Series B', 'Series C']
handles = []

#Plot circle
FIG_SIZE = 8  # Side of a square
fig, ax = pyplot.subplots(figsize=(FIG_SIZE, FIG_SIZE))
handles += ax.plot(y.real, y.imag)
ax.set(xlabel="Re", ylabel="Im", title="Unit circle")

#Series of measurement data
data = [[12, 15, 13, 9, 16], [358, 1, 359, 355, 2], [210, 290, 10, 90, 170]]

#Let measurements 'degrade'
weights = [5, 4, 3, 2, 1]

#Averaging results
Beispiel #13
0
from matplotlib import numpy as np
from matplotlib import pyplot as plt
import scipy.optimize as opt

def twoD_Gaussian((x, y), amplitude, xo, yo, sigma_x, sigma_y, theta, offset):
    xo = float(xo)
    yo = float(yo)    
    a = (np.cos(theta)**2)/(2*sigma_x**2) + (np.sin(theta)**2)/(2*sigma_y**2)
    b = -(np.sin(2*theta))/(4*sigma_x**2) + (np.sin(2*theta))/(4*sigma_y**2)
    c = (np.sin(theta)**2)/(2*sigma_x**2) + (np.cos(theta)**2)/(2*sigma_y**2)
    g = offset + amplitude*np.exp( - (a*((x-xo)**2) + 2*b*(x-xo)*(y-yo) 
                            + c*((y-yo)**2)))
    return g.ravel()

# Create x and y indices
x = np.linspace(0, 200, 201)
y = np.linspace(0, 200, 201)
x, y = np.meshgrid(x, y)

#create data
data = twoD_Gaussian((x, y), 3, 100, 100, 20, 40, 0, 10)

# plot twoD_Gaussian data generated above
plt.figure()
plt.imshow(data.reshape(201, 201))
plt.colorbar()

# add some noise to the data and try to fit the data generated beforehand
initial_guess = (3,100,100,20,40,0,10)

data_noisy = data + 0.2*np.random.normal(size=data.shape)