def auto_fitCube(self, image, verbose=0): x, y = [], [] xlist, ylist = [], [] max_rms = 0 xp, yp = 0, 0 diff = 0 max_diff = 0 s = numarray.shape(image) if s[0] > 100: # xlist=range(.25*s[0],.75*s[0]) xlist = range(s[0] / 4, 3 * s[0] / 4) else: xlist = range(s[0]) if s[1] > 100: # ylist=range(.25*s[1],.75*s[1],4) #later add the 4th pixel thing ylist = range(s[1] / 4, 3 * s[1] / 4, 4) else: ylist = range(s[1]) for i in xlist: for j in ylist: x, y = self.drill(image, i, j) rms = pylab.rms_flat(y) diff = abs(pylab.max(y) - rms) if (diff > max_diff): max_diff, xp, yp = diff, i, j # if rms>max_rms: # max_rms,xp,yp=rms,i,j # if verbose: print i,j,rms print 'optimum fit to [%d,%d] rms=%.6f' % (xp, yp, max_rms) XY, fwhm = self.fitCube2(xp, yp) return XY, fwhm
def auto_fitCube(self,image,verbose=0): x,y=[],[] xlist,ylist=[],[] max_rms=0 xp,yp=0,0 diff=0 max_diff=0 s=numarray.shape(image) if s[0]>100: # xlist=range(.25*s[0],.75*s[0]) xlist=range(s[0]/4,3*s[0]/4) else: xlist=range(s[0]) if s[1]>100: # ylist=range(.25*s[1],.75*s[1],4) #later add the 4th pixel thing ylist=range(s[1]/4,3*s[1]/4,4) else: ylist=range(s[1]) for i in xlist: for j in ylist: x,y=self.drill(image,i,j) rms=pylab.rms_flat(y) diff=abs(pylab.max(y)-rms) if(diff > max_diff): max_diff,xp,yp=diff,i,j # if rms>max_rms: # max_rms,xp,yp=rms,i,j # if verbose: print i,j,rms print 'optimum fit to [%d,%d] rms=%.6f'%(xp,yp,max_rms) XY,fwhm=self.fitCube2(xp,yp) return XY,fwhm
def plotedi(fn, saveplot=False, component=None): edi = MTedi.Edi() try: edi.readfile(fn) except: print '\n\tERROR - not a valid EDI file: {0}\n'.format(fn) sys.exit() # if saveplot is True: # import matplotlib # matplotlib.use('Agg') import pylab lo_comps = [] if component is not None: 'n' in component.lower() try: if 'n' in component.lower(): lo_comps.append('n') except: pass try: if 'e' in component.lower(): lo_comps.append('e') except: pass if len(lo_comps) == 0: lo_comps = ['n', 'e'] res_te = [] res_tm = [] phi_te = [] phi_tm = [] reserr_te = [] reserr_tm = [] phierr_te = [] phierr_tm = [] for r in edi.Z.resistivity: res_te.append(r[0, 1]) res_tm.append(r[1, 0]) for p in edi.Z.phase: phi_te.append(p[0, 1] % 90) phi_tm.append(p[1, 0] % 90) if pylab.np.mean(phi_te) > 90 and pylab.np.mean(phi_tm) > 90: phi_te = [i % 90 for i in phi_te] phi_tm = [i % 90 for i in phi_tm] for r in edi.Z.resistivity_err: reserr_te.append(r[0, 1]) reserr_tm.append(r[1, 0]) for p in edi.Z.phase_err: phierr_te.append(p[0, 1]) phierr_tm.append(p[1, 0]) periods = 1. / edi.freq resplotelement_xy = None resplotelement_yx = None axes = pylab.figure('EDI ' + fn) ax1 = pylab.subplot(211) if 'n' in lo_comps: resplotelement_xy = pylab.errorbar(periods, res_te, reserr_te, marker='x', c='b', fmt='x') if 'e' in lo_comps: resplotelement_yx = pylab.errorbar(periods, res_tm, reserr_tm, marker='x', c='r', fmt='x') pylab.xscale('log', nonposx='clip') pylab.yscale('log', nonposy='clip') minval = pylab.min(pylab.min(res_te, res_tm)) maxval = pylab.max(pylab.max(res_te, res_tm)) pylab.xlim(0.5 * pylab.min(periods), 2 * pylab.max(periods)) # ylim([0.1,100]) pylab.ylim([minval / 10, maxval * 10]) pylab.autoscale(False) pylab.ylabel(r' $\rho$ (in $\Omega m$)') pylab.setp(ax1.get_xticklabels(), visible=False) # share x only ax2 = pylab.subplot(212, sharex=ax1) pylab.autoscale(False) # ylim(-45,135) if 'n' in lo_comps: pylab.errorbar(periods, phi_te, phierr_te, marker='x', c='b', fmt='x') if 'e' in lo_comps: pylab.errorbar(periods, phi_tm, phierr_tm, marker='x', c='r', fmt='x') pylab.ylabel('Phase angle ($\degree$)') pylab.xlabel('Period (in s)') pylab.plot([pylab.xlim()[0], pylab.xlim()[1]], [45, 45], '-.', c='0.7') pylab.ylim([-0, 90]) ax1.legend([resplotelement_xy, resplotelement_yx], ['$E_{X}/B_Y$', '$E_Y/B_X$'], loc=2, ncol=1, numpoints=1, markerscale=0.8, frameon=True, labelspacing=0.3, prop={'size': 8}, fancybox=True, shadow=False) pylab.tight_layout() if saveplot is True: pylab.ioff() outfn = op.splitext(fn)[0] + '.png' pylab.savefig(outfn, bbox_inches='tight') pylab.close('all') pylab.ion() return outfn else: pylab.ion() pylab.show(block=True) return None
def main(): """ NAME foldtest.py DESCRIPTION does a fold test (Tauxe, 2007) on data INPUT FORMAT dec inc dip_direction dip SYNTAX foldtest.py [-h][-i][command line options] OPTIONS -h prints help message and quits -i for interactive parameter entry -f FILE OUTPUT Geographic: is an equal area projection of the input data in original coordinates Stratigraphic: is an equal area projection of the input data in tilt adjusted coordinates % Untilting: The dashed (red) curves are representative plots of maximum eigenvalue (tau_1) as a function of untilting The solid line is the cumulative distribution of the % Untilting required to maximize tau for all the bootstrapped data sets. The dashed vertical lines are 95% confidence bounds on the % untilting that yields the most clustered result (maximum tau_1). Command line: prints out the bootstrapped iterations and finally the confidence bounds on optimum untilting. If the 95% conf bounds include 0, then a pre-tilt magnetization is indicated If the 95% conf bounds include 100, then a post-tilt magnetization is indicated If the 95% conf bounds exclude both 0 and 100, syn-tilt magnetization is possible as is vertical axis rotation or other pathologies """ if '-h' in sys.argv: # check if help is needed print main.__doc__ sys.exit() # graceful quit if '-i' in sys.argv: # ask for filename file=raw_input("Enter file name with dec, inc dip_direction and dip data: ") f=open(file,'rU') data=f.readlines() elif '-f' in sys.argv: ind=sys.argv.index('-f') file=sys.argv[ind+1] f=open(file,'rU') data=f.readlines() else: print main.__doc__ sys.exit() # # get to work # PLTS={'geo':1,'strat':2,'taus':3,'ei':4} # make plot dictionary pmagplotlib.plot_init(PLTS['geo'],5,5) pmagplotlib.plot_init(PLTS['strat'],5,5) pmagplotlib.plot_init(PLTS['taus'],5,5) pmagplotlib.plot_init(PLTS['ei'],5,5) DIDDs= [] # set up list for dec inc dip_direction, dip nb=100 # number of bootstraps for line in data: # read in the data from standard input rec=line.split() # split each line on space to get records DIDDs.append([float(rec[0]),float(rec[1]),float(rec[2]),float(rec[3])]) pmagplotlib.plotEQ(PLTS['geo'],DIDDs,'Geographic') TCs,Ps,Taus,Es,Is=[],[],[],[],[] for k in range(len(DIDDs)): drot,irot=pmag.dotilt(DIDDs[k][0],DIDDs[k][1],DIDDs[k][2],DIDDs[k][3]) TCs.append([drot,irot,1.]) pmagplotlib.plotEQ(PLTS['strat'],TCs,'Stratigraphic') Percs=range(-10,110) for perc in Percs: tilt=0.01*perc TCs=[] for k in range(len(DIDDs)): drot,irot=pmag.dotilt(DIDDs[k][0],DIDDs[k][1],DIDDs[k][2],tilt*DIDDs[k][3]) TCs.append([drot,irot,1.]) ppars=pmag.doprinc(TCs) # get principal directions Taus.append(ppars['tau1']) Es.append(ppars["tau2"]/ppars["tau3"]) Is.append(ppars["inc"]) if int(10*(EI(ppars["inc"])))==int(10*Es[-1]): print EI(ppars["inc"]),Es[-1],perc Ps.append(perc) pylab.figure(num=PLTS['taus']) pylab.plot(Percs,Taus,'b-') pylab.figure(num=PLTS['ei']) pylab.plot(Es,Is,'b-') Is.sort() Eexp=[] for i in Is: Eexp.append(EI(i)) pylab.plot(Eexp,Is,'g-') Cdf,Untilt=[],[] print 'doing ',nb,' iterations...please be patient.....' for n in range(nb): # do bootstrap data sets - plot first 25 as dashed red line Es,Is=[],[] if n%50==0:print n Taus=[] # set up lists for taus PDs=pmag.pseudo(DIDDs) for perc in Percs: tilt=0.01*perc TCs=[] for k in range(len(PDs)): drot,irot=pmag.dotilt(PDs[k][0],PDs[k][1],PDs[k][2],tilt*PDs[k][3]) TCs.append([drot,irot,1.]) ppars=pmag.doprinc(TCs) # get principal directions Taus.append(ppars['tau1']) Es.append(ppars["tau2"]/ppars["tau3"]) Is.append(ppars["inc"]) if int(10*(EI(ppars["inc"])))==int(10*Es[-1]): Ps.append(perc) if n<25: pylab.figure(num=PLTS['taus']) pylab.plot(Percs,Taus,'r--') pylab.figure(num=PLTS['ei']) pylab.plot(Es,Is,'r--') Untilt.append(Percs[Taus.index(pylab.max(Taus))]) # tilt that gives maximum tau Cdf.append(float(n)/float(nb)) pylab.figure(num=PLTS['taus']) pylab.plot(Percs,Taus,'k') pylab.xlabel('% Untilting') pylab.ylabel('tau_1 (red), CDF (green)') Untilt.sort() # now for CDF of tilt of maximum tau Ps.sort() pylab.plot(Untilt,Cdf,'g') lower=int(.025*nb) upper=int(.975*nb) pylab.axvline(x=Untilt[lower],ymin=0,ymax=1,linewidth=1,linestyle='--') pylab.axvline(x=Untilt[upper],ymin=0,ymax=1,linewidth=1,linestyle='--') tit= '%i - %i %s'%(Untilt[lower],Untilt[upper],'Percent Unfolding') pylab.title(tit) print Ps[lower],Ps[upper] pmagplotlib.drawFIGS(PLTS) try: raw_input('Return to save all figures, cntl-d to quit\n') except EOFError: print "Good bye" sys.exit() files={} for key in PLTS.keys(): files[key]=('fold_'+'%s'%(key.strip()[:2])+'.svg') pmagplotlib.saveP(PLTS,files)
def multifit(lastcol,outdir,outpref,inputfile='input_fit.txt',doplot='yes'): ndataset=int(lastcol) if os.path.exists(inputfile) is False: reply=raw_input('I need an input file, do you want me to create it?(Y/n)') print reply if reply=='n': exit() else: print 'creating an input file' inputfile= create_input(inputfile) f=open(inputfile,'r') text=f.read() print text test = raw_input('Is it ok?(Y/n)') if test == 'n': print 'Please correct it and launch the program again' exit() #reading input parameters#################################################### Input_par=get_input(inputfile) pars = process_input(Input_par) filename=pars[0] t1=float(pars[1]) t2=float(pars[2]) range_par=pars[3] func=pars[4] name_const=pars[5] const_0=pars[6] name_par=pars[7] par_0=pars[8] xcol=pars[9] ycol=pars[10] normcol=pars[11] #yerr=pars[12] #input parameters read#################################################### g=open(filename,'r') title=g.readline() g.close() qs=title.split(' ') if doplot=='yes': Plab.ion() Plab.figure(1) axdata=Plab.axes() axdata.set_xlabel('t [sec]') axdata.set_ylabel('g^2(q,t)') ldata1,=axdata.semilogx((1,),(1,),'ko',label='all range') axdata.hold(True) ldata2,=axdata.semilogx((1,),(1,),'r^',label='fitting range') ldata3,=axdata.semilogx((1,),(1,),'k-',label='fit') axdata.legend(loc='lower left') Plab.draw() npars=len(name_par) parplot=zeros((ndataset-ycol,npars),dtype=float32) n=tuple(range(1,npars+1)) Plab.figure(2) ncols=(1+npars)/2 nrows=npars/ncols+npars%ncols ax=range(npars) lpars=range(npars) for k in range(npars): s=str(ncols)+str(nrows)+str(k+1) ax[k]=Plab.subplot(s) ax[k].set_xlabel('q [1/Ang]') ax[k].set_ylabel(name_par[k]) ax[k].set_title(name_par[k]) lpars[k],=ax[k].plot((1,),(1,),'ro-') Plab.draw() raw_input('Adjust positioning and size of figures, then press RETURN...') for i in range(ycol,ndataset): check=i-ycol print 'reading file ', filename, ' ...', 'col no. ', i+1 x,y,not_used=read_data(filename,xcol,i,normcol) print 'read' if range_par=='in': print 'including data in the range ', t1, ':', t2 if range_par=='out': print 'excluding data in the range ', t1, ':', t2 if range_par=='all': t1=Plab.min(x) t2=Plab.max(x) print 'using all x-range to fit:[',t1,'-',t2,']' xfit,yfit,not_used=fit_region(x,y,t1,t2,range_par) y_out,p,f= fitting(xfit,yfit,func,par_0,const_0) #writing results################################################# file_par_out=os.path.join(outdir,outpref+'_fitpar.dat') file_data_out=os.path.join(outdir,outpref+'_fitcol'+str(i+1)+'.dat') write_multi_par_out(check,name_par,p,t1,t2,filename,func,const_0,name_const,fileout=file_par_out,qval=qs[i+1],file_input=inputfile) ytheo=eval(f) mat=zeros((len(x),3),dtype=float32) mat[:,0]=x mat[:,1]=y mat[:,2]=ytheo fi=open(file_data_out,'w') fi.write('# x y fit') Plab.save(fi,mat) fi.close() print 'output written on files ', file_par_out,' and ', file_data_out #some plots##################################################### if doplot=='yes': Plab.figure(1) ldata1.set_data(x,y) ldata2.set_data(xfit,yfit) ldata3.set_data(x,ytheo) axdata.set_xlim(Plab.min(x),Plab.max(x)) axdata.set_ylim(Plab.min(y),Plab.max(y)) Plab.draw() q=qs[2:i+2] parplot[i-1,:]=p q=Plab.transpose(q) Plab.figure(2) for k in range(npars): lpars[k].set_data(q,parplot[:i,k]) xmin=float(q[0]) xmax=float(q[-1]) ax[k].set_xlim(0.9*xmin,1.1*xmax) ax[k].set_ylim(0.9*Plab.min(parplot[:i,k]),1.1*Plab.max(parplot[:i,k])) Plab.draw() if doplot=='yes': raw_input( "Press a RETURN to close figures...") Plab.close('all')
def plotcoh(fn, saveplot=False): data = np.loadtxt(fn) # if saveplot is True: # import matplotlib # matplotlib.use('Agg') import pylab periods = data[:, 0] if data.shape[1] != 99: # ipdb.set_trace() coh1 = data[:, 2] coh2 = data[:, 4] ax1 = pylab.figure('coherence') cohplotelement1 = None cohplotelement2 = None cohplotelement3 = None cohplotelement4 = None pylab.plot(periods, coh1) cohplotelement1 = pylab.scatter(periods, coh1, marker='x', c='b') pylab.plot(periods, coh2) cohplotelement2 = pylab.scatter(periods, coh2, marker='x', c='r') try: pylab.plot(periods, data[:, 6], 'g:') cohplotelement3 = pylab.scatter(periods, data[:, 6], marker='d', c='g') except: pass try: pylab.plot(periods, data[:, 8], 'y:') cohplotelement4 = pylab.scatter(periods, data[:, 8], marker='d', c='y') except: pass pylab.xscale('log', nonposx='clip') pylab.ylim([-.1, 1.1]) pylab.xlim(0.5 * pylab.min(periods), 2 * pylab.max(periods)) pylab.autoscale(False) pylab.xlabel('Period (in s)') pylab.ylabel('Coherence$^2$') eps = 0.05 if (cohplotelement3 is not None) and (cohplotelement4 is not None): ax1.legend([ cohplotelement1, cohplotelement2, cohplotelement3, cohplotelement4 ], ['$E_{X}$', '$E_{Y}$', '$B_{X}$', '$B_{Y}$'], loc=1, ncol=2, bbox_to_anchor=[1 - eps, 1 - eps], numpoints=1, markerscale=0.8, frameon=True, labelspacing=0.3, prop={'size': 9}, fancybox=True, shadow=False) else: ax1.legend([cohplotelement1, cohplotelement2], ['$E_{X}$', '$E_{Y}$'], loc=1, ncol=2, bbox_to_anchor=[1 - eps, 1 - eps], numpoints=1, markerscale=0.8, frameon=True, labelspacing=0.3, prop={'size': 9}, fancybox=True, shadow=False) if saveplot is True: pylab.ioff() outfn = op.splitext(fn)[0] + '.coh.png' pylab.savefig(outfn, bbox_inches='tight') pylab.close('all') pylab.ion() return outfn else: pylab.tight_layout() pylab.ion() pylab.show(block=True) return None