Beispiel #1
0
def p0_1s2():
    pl.clf()
    ourdat  = pl.loadtxt('1p0_1s2_J1.dat')
    ax1 = pl.axes()
    pl.figure(1, figsize=(8, 6), facecolor='white')
    # pl.plot(20.0, 4.7, 'gs', ms=7)
    # pl.plot(20.0, 1.4, 'bo', ms=7)
    label = '1p0' r'$\rightarrow$'  '1s2 ' '($\Delta J=1)$'
    # pl.plot(ourdat[:,0], ourdat[:,1], 'r--', ms=7,  label=label)
    pl.plot(ourdat[:,0], ourdat[:,2], 'b', ms=7, label=label)
    # pl.plot(ourdat[:,0], ourdat[:,3], 'g-.', ms=7)
    zatsdat = pl.loadtxt('../zats_figs/zats_1s2.dat')
    pl.plot(zatsdat[:,0], zatsdat[:,1], 'ro',)
    pl.plot(zatsdat[:,2], zatsdat[:,3], 'y*', ms=9, lw=5) # Hoshino
    pl.plot(zatsdat[:,4], zatsdat[:,5], 'mp', ms=7, lw=5) # Khakoo
    pl.plot(zatsdat[:,6], zatsdat[:,7], 'gs', ms=7, lw=5) # Filopivic
    pl.plot(zatsdat[:,8], zatsdat[:,9], 'cD', ms=9, lw=5) # Chutjian
    pl.legend(loc=1, frameon=False, scatterpoints=0)
    pl.xlim([12,35])
    # pl.ylim([0,5])
    pl.xlabel('Energy (eV)', fontsize=16)
    pl.ylabel('Cross section (MB)', fontsize=16)
    pl.savefig('1p0-1s2_J1_plot.eps')
    pl.show()
    return
Beispiel #2
0
def plot1(cursor):
    dage,dew,dmf,dM=gettable(cursor,cols='age,Ha_w,Massfrac,Mr',where='agn=0 AND Mr>-20 and Massfrac NOTNULL',table='sball')
    gage,gew,gmf,gM=gettable(cursor,cols='age,Ha_w,Massfrac,Mr',where='agn=0 AND Mr<-20 and Massfrac NOTNULL',table='sball')
    limit1x,limit1y=P.loadtxt('/home/tom/projekte/sdss/ages/mixred0',unpack=True)[:2]
    limit2x,limit2y=P.loadtxt('/home/tom/projekte/sdss/ages/mixblue0',unpack=True)[:2]

    ax1=P.subplot(1,2,1)
    P.title(r'$\mathrm{Dwarfs,}\,\, M_r > -20$')
    P.loglog(limit1x,limit1y,'--k',linewidth=2)
    P.loglog(limit2x,limit2y,'-k',linewidth=2)
    P.scatter(dage,dew*dcf,c=dmf,vmin=0,vmax=0.05,label='Age, M>-20',alpha=0.2,cmap=P.cm.OrRd,lw=1)
    P.xlabel(r'$\mathrm{Burst\, age}$')
    P.ylabel(r'$\mathrm{EW}(H\alpha)$')
    P.plot([1E6,1E10],[150,150],'k-.',lw=2)
    P.axis([4E6,2E9,55,9E2])

    P.subplot(1,2,2)
    P.title(r'$M_r < -20$')
    P.loglog(limit1x,limit1y,'--k',linewidth=2)
    P.loglog(limit2x,limit2y,'-k',linewidth=2)
    P.scatter(gage,gew*gcf,c=gmf,vmin=0,vmax=0.05,label='Age, M<-20',alpha=0.2,cmap=P.cm.OrRd,lw=1)
    P.xlabel(r'$\mathrm{Burst\, age}$')
    P.plot([1E6,1E10],[150,150],'k-.',lw=2)
    P.axis([4E6,2E9,55,9E2])
    P.setp(P.gca(),'yticklabels',[])
    P.subplots_adjust(wspace=0)
Beispiel #3
0
def p0_2p1():
    pl.clf()
    ourdat  = pl.loadtxt('1p0_2p1_J0.dat')
    ax1 = pl.axes()
    pl.figure(1, figsize=(8, 6), facecolor='white')
    # pl.plot(20.0, 5.0, 'gs', ms=7)
    # pl.plot(20.0, 5.2, 'bv', ms=7)
    # pl.plot(20.0, 2.7, 'bo', ms=7)
    label = '1p0' r'$\rightarrow$'  '2p1 ' '($\Delta J=0)$'
    # pl.plot(ourdat[:,0], ourdat[:,1], 'r--', ms=7,  label=label)
    pl.plot(ourdat[:,0], ourdat[:,2], 'b', ms=7, label=label)
    # pl.plot(ourdat[:,0], ourdat[:,3], 'g-.', ms=7)
    zatsdat = pl.loadtxt('../zats_figs/zats_2p1.dat')
    pl.plot(zatsdat[:,0], zatsdat[:,1]/10, 'ro',)
    pl.plot(zatsdat[:,2], zatsdat[:,3]/10, 'k^', ms=7, lw=5)
    pl.plot(zatsdat[:,4], zatsdat[:,5]/10, 'gs', ms=7, lw=5)
    pl.plot(zatsdat[:,6], zatsdat[:,7]/10, 'cD', ms=7, lw=5)
    pl.legend(loc=1, frameon=False, scatterpoints=0)
    pl.xlim([12,42])
    pl.ylim([0,15])
    pl.xlabel('Energy (eV)', fontsize=16)
    pl.ylabel('Cross section (MB)', fontsize=16)
    pl.savefig('1p0-2p1_J0_plot.eps')
    pl.show()
    return
Beispiel #4
0
def load_act(sym, source):
    ''' Load atomic collision transition file from mechanical quantum computations
        3 ascii input files:
        ael.dat: atomic energy levels in the mael.py format
        temp.dat: list of temperatures
        ups.dat: effective collision strengths
    '''
    path = '/home/tmerle/development/formato2/ad/ct/e/qm/'+SYM+'/'+source+'/'

    dumb = pl.loadtxt(path+'ael.dat', dtype='str')
    ael_list = [State(e=e, g=g, cfg=cfg, term=term, p=p, ref=ref) for e, g, cfg, term, p, ref in dumb]
    #[ael.print() for ael in ael_list]

    t_list = pl.loadtxt(path+'temp.dat', dtype='float')
    nt = len(t_list)

    dumb = pl.loadtxt(path+'ups.dat', dtype='float')
    
    l_list, u_list, ups_list = [], [], []

    for rec in dumb:
        l_list.append(int(rec[0]))
        u_list.append(int(rec[1]))
        ups_list.append(map(float, rec[2:]))            

    col_list = []

    for i, (l, u) in enumerate(zip(l_list, u_list)):
        #print(l, u, ups_list[i])
        col = Collision(type='QM', lower=ael_list[l-1], upper=ael_list[u-1], t_list=t_list, ups_list=ups_list[i], ref=source, kw='UPS_E')
        col_list.append(col)

    return col_list
Beispiel #5
0
def film1D(base, ext, debut, fin, vmin, vmax, dt = 0):
  """ displays the evolution in time of a 1-D solution
  Usage : film1D(base, ext, debut, fin, vmin, vmax)
          film1D(base, ext, debut, fin, vmin, vmax, dt)

  base : root of output files
  ext : extension of output files
  debut : start index
  fin : final index
  vmin, vmax : y-range
  
  Example : film1D("Un", ".dat", 0, 20, -0.1, 1.1)
         will display frames contained in Un0.dat, Un1.dat, ...
         until Un19.dat with y in [-0.1, 1.1]
  
  Put a dt different from 0, if the animation is too fast, so that the system
  will wait dt seconds between each display """
  V = pylab.loadtxt(base + str(debut) + ext)
  line, = pylab.plot(V[:,0], V[:,1]);
  pylab.axis(pylab.array([V[0, 0], V[V.shape[0]-1,0], vmin, vmax]));
  os.system('sleep ' +str(dt))
  for i in range(debut+1, fin):
    V = pylab.loadtxt(base + str(i) + ext)
    line.set_ydata(V[:,1])
    pylab.draw()
    os.system('sleep ' +str(dt))
Beispiel #6
0
	def load_csv(self,f):
		"""
		Loading data from a csv file. Uses pylab's load function. Seems much faster
		than scipy.io.read_array.
		"""
		varnm = f.readline().split(',')

		# what is the date variable's key if any, based on index passed as argument
		if self.date_key != '':
			try:
				rawdata = pylab.loadtxt(f, delimiter=',',converters={self.date_key:pylab.datestr2num})		# don't need to 'skiprows' here
			except ValueError:																				# if loading via pylab doesn't work use csv
				rawdata = self.load_csv_nf(f)	

				# converting the dates column to a date-number
				rawdata[self.date_key] = pylab.datestr2num(rawdata[self.date_key])

			self.date_key = varnm[self.date_key]
		else:
			try:
				rawdata = pylab.loadtxt(f, delimiter=',')														# don't need to 'skiprow' here
			except ValueError:																				# if loading via pylab doesn't work use csv
				rawdata = self.load_csv_nf(f)	

		# making sure that the variable names contain no leading or trailing spaces
		varnm = [i.strip() for i in varnm]

		# transforming the data into a dictionary
		if type(rawdata) == list:
			# if the csv module was used
			self.data = dict(zip(varnm,rawdata))
		else:
			# if the pylab.load module was used
			self.data = dict(zip(varnm,rawdata.T))
def main():  

   FILE1 = "./TO_PLOT.dat" 
   FILE2 = "./test.dat" 
   FILE3 = "./train.dat" 
   PATH_TO_OUTPUT = "./plot.png"


   f1 = pylab.loadtxt(FILE1,dtype = str, unpack=True)
   f2 = pylab.loadtxt(FILE2,dtype = str, unpack=True)
   f3 = pylab.loadtxt(FILE3,dtype = str, unpack=True)

   pylab.clf()
   pylab.cla()

   pylab.scatter(f1[0], f1[1], c=color[1], label='10-fold KNN')
   pylab.plot(f2[0], f2[1],  c=color[2], label='Test data')
   pylab.scatter(f3[0], f3[1],  c=color[3], label='Train data')

   pylab.ylabel('Acccuracy', fontsize=14)  
   pylab.xlabel('k', fontsize=14)       
   pylab.legend(loc=1, prop={'size':10})
   pylab.xlim(0.1,100)

		    
   pylab.savefig(PATH_TO_OUTPUT)
Beispiel #8
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
Beispiel #9
0
def runAll(ScaleDensity, b, f, Particle, Scale):
    import pylab as p
    import shutil, subprocess
    
    path = "./outData/"
    savepath = "./plots/compare/"
    inifilename = "mybody.ini"

    filenameMine = "mass.dat"
    filenameRockstar = "halos_0.ascii"
    filenameAmiga = "amiga.dat"

    
    inifile = open(inifilename, 'r')
    tmpinifile = open(inifilename + ".tmp", "w")

    for line in inifile:
    
        if line[0:15] == "ScaleDensity = ":
            line = "ScaleDensity = "+ str(ScaleDensity)+"\n "
        if line[0:4] == "b = ":
            line = "b = " + str(b)+"\n " 
        if line[0:4] == "f = ":
            line = "f = " + str(f)+"\n "
        if line[0:21] == "LinkingLenghtScale = ":
            line = "LinkingLenghtScale = "+ str(Scale)+"\n "
        if line[0:20] == "NrParticlesDouble = ":
            line = "NrParticlesDouble = " + str(Particle)+"\n " 
            
        tmpinifile.write(line)
    
    inifile.close()
    tmpinifile.close()
    shutil.move(inifilename + ".tmp", inifilename)

    #Run my halofinder
    #print "Running for: " +"ScaleDensity="+ str(ScaleDensity) + " b=" + str(b) + " f="+str(f)
    subprocess.call(["mpirun","-n","2", "./main"])
    
    #Read data from files
    mineData = p.loadtxt(path + filenameMine)
    rockstarData = p.loadtxt(path + filenameRockstar)
    amigaData = p.loadtxt(path + filenameAmiga)

    sortedDataR = p.sort(rockstarData[:,2])[::-1]
    sortedData = p.sort(mineData)[::-1]
    sortedDataA = p.sort(amigaData[:,3])[::-1]


    p.figure()
    p.loglog(sortedData,range(1,len(sortedData)+1))
    p.loglog(sortedDataR,range(1,len(sortedDataR)+1))
    p.loglog(sortedDataA,range(1,len(sortedDataA)+1))
    p.xlabel("log(Mass) Msun")
    p.ylabel("log(Nr of halos with mass >= Mass)")
    p.legend(("mine","Rockstar","AMIGA"))
    name = "MassFunction_ScaleDensity="+ str(ScaleDensity) + "_b=" + str(b) + "_f="+str(f) + "_Scale=" +str(Scale) + "_Double="+str(double)
    p.savefig(savepath+name+".png")
Beispiel #10
0
    def on_bl_button(self,event):
        self.selectq_control.SetString(string='Streamwise (u) Velocity')
        self.selectq_control.num = 2
        self.blcall = True 
        self.bldraw = True
        self.on_update_button(event)
        self.blcall = False
        self.jcur = self.Bl_jplane.GetValue()
        gnum = self.qfile_control.manual_text2.GetValue()
        if (self.multgrd):      
            new_str1 = ''.join([self.qfile, '\n','qvalbl.txt', '\n', str(gnum), '\n', str(self.jcur) ,' ', 
                                str(self.jcur) ,' ', str(1), '\n' ,  str(1),' ',
                                str(self.nkind),' ',str(1), '\n' ,str(1) ,
                                ' ',str(1) ,' ', str(1), '\n',
                                str(2), '\n','n'])  
        else:
            new_str1 = ''.join([self.qfile, '\n','qvalbl.txt', '\n', str(self.jcur) ,' ', 
                                str(self.jcur) ,' ', str(1), '\n' ,  str(1),' ',
                                str(self.nkind),' ',str(1), '\n' ,str(1) ,
                                ' ',str(1) ,' ', str(1), '\n',
                                str(2), '\n','n'])  
            
        new_str2 = ''.join([self.grid, '\n',  str(gnum), '\n', 'cordsbl.txt', '\n', str(self.jcur) ,' ', 
                            str(self.jcur) ,' ', str(1), '\n' ,  str(1),' ',
                            str(self.nkind),' ', str(1), '\n' ,str(1) ,
                            ' ',str(1) ,' ', str(1)]) 
        p2 = subprocess.Popen(['getgridcords'], stdin=PIPE, stdout=PIPE)
        o2,e2 = p2.communicate(input=new_str2) 
        p1 = subprocess.Popen(['listplotvar'], stdin=PIPE, stdout=PIPE)
        o1,e1 = p1.communicate(input=new_str1)
        p3 = subprocess.Popen(['tail', '-n', '+7'], stdin=PIPE, stdout=PIPE)
        o3,e3 = p3.communicate(input=o1) 
        p4 = subprocess.Popen(['head', '-n', '-1'], stdin=PIPE, stdout=PIPE)
        o4,e4 = p4.communicate(input=o3) 

        self.file1 = pylab.loadtxt('qvalbl.txt')
        self.file2 = pylab.loadtxt('cordsbl.txt')
        
        os.remove('qvalbl.txt')
        os.remove('cordsbl.txt')
        
        tot = len(self.file1)
        u = [.5 for i in range(tot)]
        x = [.5 for i in range(tot)]
        y = [.5 for i in range(tot)]
        for k in range(0,tot):
            u[k] = float(self.file1[k][3])
            x[k] = float(self.file2[k][3])
            y[k] = float(self.file2[k][4])
        xoverc = round(x[0],5)
        self.x_over_c.SetLabel( ''.join(['x/c =   ', str(xoverc)]) )
        if (self.mom_norm.IsChecked()):
            self.update_bl_mom(x,y,u,(self.nkind-1),(self.jcur))
        else:
            self.update_bl_mom(x,y,u,(self.nkind-1),(self.jcur))
            self.update_bl(x,y,u,(self.nkind-1),(self.jcur))
Beispiel #11
0
def getData():
    
    # load the fitting data for X and y and return as elements of a tuple
    # X is a 100 by 10 matrix and y is a vector of length 100
    # Each corresponding row for X and y represents a single data sample

    X = pl.loadtxt('fittingdatap1_x.txt')
    y = pl.loadtxt('fittingdatap1_y.txt')

    return (X,y) 
def plot(experimento = None):
    path = '/home/rafaelbeirigo/ql/experiments/'
    
    ql = pl.loadtxt(path + experimento + "/QL/w.out")
    prql = pl.loadtxt(path + experimento + "/PRQL/w.out")

    pl.xlabel("Episodes")
    pl.ylabel("W")

    pl.plot(ql, label = 'Q-Learning')
    pl.plot(prql, label = 'PRQ-Learning prob')

    pl.legend(loc = 0)
Beispiel #13
0
def get_consts(kind):
    if kind == "hs":
        g1, g2 = 1.270042427, 1.922284066
        k_0, d_1, = -1.2540, 2.4001
        eta, Y_0, Y_1, Omega_1, Theta_1, H_A, H_B, Y_a4 = py.loadtxt('../tables/kn-layer-hs.txt').T
        Y_1 = 2*Y_1
        return g1, g2, k_0, d_1, eta, Y_0, H_A, Theta_1, 0.43, 0.078, 0.7
    elif kind == "bkw":
        g1, g2 = 1., 1.
        k_0, d_1 = -1.01619, 1.30272
        eta, Y_0 = py.loadtxt('../tables/kn-layer-bkw.txt').T
        H_A = Y_0 / 2
        return g1, g2, k_0, d_1, eta, Y_0, H_A, Theta_1, 0.345, 0.172
    else:
        raise "Invalid potential!"
Beispiel #14
0
 def read_data(cls, path):
     """
     AuxiliaryFiles中のデータ収集
     dictのリスト配列として収集する
     """
     comp_path = os.path.join(path, cls.base_dirc, cls.comp_file)
     comp = pylab.loadtxt(comp_path, comments='#')
     total = np.array([[sum(x) for x in comp]])
     frac = comp / total.T
     energy_path = os.path.join(path, cls.base_dirc, cls.energy_file)
     energy = pylab.loadtxt(energy_path, comments="#")
     energy = energy / total[:][0]
     data = [{'frac_atoms': list(x), 'energy': y}
             for x, y in zip(frac, energy)]
     return(data)
def plot():
    pl.xlabel("Episodes")
    pl.ylabel("W")

    pl.title("")

    prManu = pl.loadtxt("/home/rafaelbeirigo/ql/experiments/165/PRQL/W_avg_list_mean.out")
    prIPMU = pl.loadtxt("/home/rafaelbeirigo/ql/experiments/166/PRQL/W_avg_list_mean.out")
    ql = pl.loadtxt("/home/rafaelbeirigo/ql/experiments/165/QL/w.out")

    pl.plot(prManu, label="Manu")
    pl.plot(prIPMU, label="IPMU")
    pl.plot(ql, label="Q-Learning")

    leg_prop = matplotlib.font_manager.FontProperties(size=12)
    pl.legend(loc=4, prop=leg_prop)
Beispiel #16
0
def get_n(material,E=8):
    """
    "by LW 07/04/2011 function get the index of refraction from stored data file,
    index of refraction is a .dat file from http://henke.lbl.gov/optical_constants/getdb2.html 
    (energy range: 2-30keV,delete the header lines, name the file n_material.dat) 
    calling sequence: n=get_n(material,E) where n is the complex refractive index detlta-i*beta, E: X-ray energy in keV"
    """
    #get list_of supported materials from data file directory:
    xdatafiles = [ f for f in listdir(datapath) if isfile(join(datapath,f)) ]    
    name=[]
    for i in range(0, np.size(xdatafiles)):
        m=re.search('(?<=n_)\w+', xdatafiles[i])
        if m is not None:
            name.append(m.group(0))             
    
    E=np.array(E)
    if material in name:
        loadn=datapath+'n_'+material+'.dat'
        n=pl.loadtxt(loadn,comments='%')
        if np.min(E)>=np.min(n[:,0]/1000) and np.max(E)<=np.max(n[:,0]/1000):
            d=np.interp(E*1000,n[:,0],n[:,1])
            b=np.interp(E*1000,n[:,0],n[:,2])
            return d-1j*b
        else: print 'error: energy '+"%3.4f" %E +'[keV] out of range ('+"%3.4f" % np.min(n[:,0]/1000)+'=<E<='+"%3.4f" % np.max(n[:,0]/1000)+'keV)'
    elif material=='material?':
        print 'list of supported materials (based on data files in directory '+datapath+':'
        print name
    else: print 'error: non recognized material, please create index of refraction file first. Type "get_n?" for instructions; type get_n("material?") for list of supported materials'
Beispiel #17
0
def get_ac(material,E=8):
    """
    by LW 10/03/2010
    function calculates the critical angle for total external reflection as a function of
    the material and the X-ray energy according to ac=sqrt(2*delta)
    index of refraction is a .dat file from http://henke.lbl.gov/optical_constants/getdb2.html
    (energy range: 2-30keV,delete the header % lines, name the file n_material.dat) % 
    calling sequence: ac=get_ac(material,E) where ac: critial angle in degrees, E [keV] (default: 8keV)
    type get_ac(\'materilal?\') to show list of supported materials"
    """
    
    #get list_of supported materials from data file directory:
    xdatafiles = [ f for f in listdir(datapath) if isfile(join(datapath,f)) ]    
    name=[]
    for i in range(0, np.size(xdatafiles)):
        m=re.search('(?<=n_)\w+', xdatafiles[i])
        if m is not None:
            name.append(m.group(0))             
    
    E=np.array(E)
    if material in name:
        loadn=datapath+'n_'+material+'.dat'
        n=pl.loadtxt(loadn,comments='%')
        if np.min(E)>=np.min(n[:,0]/1000) and np.max(E)<=np.max(n[:,0]/1000):
            d=np.interp(E*1000,n[:,0],n[:,1])
            return np.degrees(np.sqrt(2*d))
        else: print 'error: energy '+"%3.4f" %E +'[keV] out of range ('+"%3.4f" % np.min(n[:,0]/1000)+'=<E<='+"%3.4f" % np.max(n[:,0]/1000)+'keV)'
    elif material=='material?':
        print 'list of supported materials (based on data files in directory '+datapath+':'
        print name       
    else: print 'error: non recognized material, please create index of refraction file first. Type "get_ac?" for instructions; type get_ac("material?") for list of supported materials' 
Beispiel #18
0
def get_pinflux(current,Energy,thickness=300):
    """
    by LW 03/26/2015
    function to calculate photon flux from pin-diode measurement
    uses scattering cross section for Si from NIST -> PhElAbsCross_si.dat in database
    assumes Silicon as material as other materials would be pretty exotic
    calling sequence: get_pinflux(current,Energy,thickness=300)
    current: current [A]
    Energy: X-ray energy [keV]
    thickness: Si diode thickness [um]
    """
    # some conversions and contstants:
    rho_Si=2.329   # density of Si in g/cm^3!!!
    epsilon=3.66   # energy for creation of electron-hole pair in Si [eV]    
    thickness=thickness/1.0E4  #conversion to cm
    # read datafile with scattering cross section:
    loadn=datapath+'PhElAbsCross_Si.dat'
    crossdat=pl.loadtxt(loadn,comments='%')
    # check for energy range:
    xmin=min(crossdat[:,0])*1E3
    xmax=max(crossdat[:,0])*1E3
    Energy=np.array(Energy)*1.0
    current=np.array(current)*1.0
    if np.max(Energy) > xmax or np.min(Energy) <xmin:
        raise xfuncs_Exception(['X-ray energy out of range for cross section data. ',xmin,'<=Energy<=,',xmax,' [keV]'])
    # calculate photo current PER 1E10 ph/s:
    PhCur=1E10*crossdat[:,0]*1e3*1.6022e-16*(1-np.exp(-crossdat[:,1]*thickness*rho_Si))/epsilon
    PhCurint=np.interp(Energy,crossdat[:,0],PhCur)
    photon_flux=current/PhCurint*1E10
    print 'photo current for E= ',Energy,'keV: ',PhCurint*1E3,'mA/10^10ph/s'
    print 'flux for photo current ',current*1E3,'mA at E=',Energy,'keV: ',photon_flux,'ph/s'
    return photon_flux
Beispiel #19
0
def get_Es(gap,harmonic=[1,2,3,4,5],ID='CHX_IVU20_12202014'):
    """
    by LW 12/03/2014,
    function calculates the X-ray energies for a given undulator gap and set of harmonics
    based on magnetic measurement data in the database 
    type get_Es(gap [mm], harmonic [integer] (default=[1,2,3,4,5]), id (default:'CHX_IVU20_12202014'))
    harmonic can be a list of integers. Type get_Es(\"ID?\") for a list of available magnetic datasets
    """
    #get list_of available magnetic measurements from data file directory:
    xdatafiles = [ f for f in listdir(datapath) if isfile(join(datapath,f)) ]    
    name=[]
    for i in range(0, np.size(xdatafiles)):
        m=re.search('(?<=id_)\w+', xdatafiles[i])
        if m is not None:
            name.append(m.group(0))             
    if gap=='ID?':
        print 'list of available magnetic measurements (based on data files in directory '+datapath+':'
        print name
    else:
        for l in range(0, np.size(harmonic)):
            harm_check(harmonic)            
            if l==np.size(harmonic)-1:
                    gap=np.array(gap)
                    if ID in name:
                        loadn=datapath+'id_'+ID+'.dat'
                        magdat=pl.loadtxt(loadn,comments='%')
                        harmonic=np.array(harmonic)*1.0
                        if np.min(gap)>=np.min(magdat[:,0]) and np.max(gap)<=np.max(magdat[:,0]):
                            Es=np.interp(gap,magdat[:,0],magdat[:,2])
                            Eharmonics=np.array([harmonic,harmonic*Es])
                            return Eharmonics.T  
                        else: print 'error: gap '+"%3.4f" % gap +'[mm] out of range for gap ('+"%3.4f" % np.min(magdat[:,0])+'=<gap<='+"%3.4f" % np.max(magdat[:,0])+'mm), try higher/lower harmonic number.'
                    else: print 'error: non recognized magnetic data. Type get_gap(\'ID?\') for a list of available mangetic datasets.'
Beispiel #20
0
def get_gap(E,harmonic=3,ID='CHX_IVU20_12202014'):
    """    
    by LW 12/03/2014, function calculates the undulator gap for a requested energy
    and harmonic based on magnetic measurement data in the database 
    type get_gap(E [kev], harmonic [integer] (default=3), id (default+'CHX_IVU20_12202014')); 
    E can be an array of energies. Type get_gap\"ID?\") for a list of available magnetic datasets.
    """
    #get list_of available magnetic measurements from data file directory:
    xdatafiles = [ f for f in listdir(datapath) if isfile(join(datapath,f)) ]    
    name=[]
    for i in range(0, np.size(xdatafiles)):
        m=re.search('(?<=id_)\w+', xdatafiles[i])
        if m is not None:
            name.append(m.group(0))             

    if E=='ID?':
        print 'list of available magnetic measurements (based on data files in directory '+datapath+':'
        print name
    else:
        E=np.array(E)*1.0
        harm_check(harmonic)     
        if ID in name:
            loadn=datapath+'id_'+ID+'.dat'
            magdat=pl.loadtxt(loadn,comments='%')
            #harmonic=harmonic*1.0
            if np.min(E/harmonic)>=np.min(magdat[:,2]) and np.max(E/harmonic)<=np.max(magdat[:,2]):
                gap=np.interp(E/harmonic,magdat[:,2],magdat[:,0])
                return gap
            # this else should be a warning only and should return NaN    
            else: raise xfuncs_Exception ('error: energy '+"%3.4f" %E +'[keV] out of range for requested harmonic number, gap limit: ('+"%3.4f" % np.min(magdat[:,0])+'=<gap<='+"%3.4f" % np.max(magdat[:,0])+'mm), try using higher/lower harmonic number.')
        else: raise xfuncs_Exception('error: non recognized magnetic data. Type get_gap(\'ID?\') for a list of available mangetic datasets.')
Beispiel #21
0
def get_mu(material,E=8):
    """
    by LW 07/04/2011
    function gets the attenuation length from stored data file, 
    attenuation length is a .dat file from http://henke.lbl.gov/optical_constants/getdb2.html
    (energy range: 2-30keV,delete the header lines or comment with '%', name the file n_material.dat)
    calling sequence: mu=get_mu(material,E) where mu [MICRONS!!!] is the 1/e attenuation length, E: X-ray energy in keV'
    """
    #get list_of supported materials from data file directory:
    xdatafiles = [ f for f in listdir(datapath) if isfile(join(datapath,f)) ]    
    name=[]
    for i in range(0, np.size(xdatafiles)):
        mm=re.search('(?<=mu_)\w+', xdatafiles[i])
        if mm is not None:
            name.append(mm.group(0))             
    
    E=np.array(E)
    if material in name:
        loadn=datapath+'mu_'+material+'.dat'
        m=pl.loadtxt(loadn,comments='%')
        if np.min(E)>=np.min(m[:,0]/1000) and np.max(E)<=np.max(m[:,0]/1000):
            mu=np.interp(E*1000,m[:,0],m[:,1])
            return mu
        else: print 'error: energy '+"%3.4f" %E +'[keV] out of range ('+"%3.4f" % np.min(m[:,0]/1000)+'=<E<='+"%3.4f" % np.max(m[:,0]/1000)+'keV)'
    elif material=='material?':
        print 'list of supported materials (based on data files in directory '+datapath+':'
        print name
    else: print 'error: non recognized material, please create index of refraction file first. Type get_mu("?") for instructions; type get_n("material?") for list of supported materials'
    def getData(self):
        # check if a separator is a white space
        if is_empty(self.params.separator):
            _data = pl.loadtxt(self._file,
                              dtype=(str),
                              skiprows=self.headers_count,
                              unpack=True)
        else:
            _data = pl.loadtxt(self._file,
                              dtype=(str),
                              skiprows=self.headers_count,
                              unpack=True,
                              delimiter=self.params.separator)

        #some issues with preparing data, details in prepare_data_arrays func.
        return prepare_data_arrays(self._file, self.headers_count, _data)
def main():
    from optparse import OptionParser
    usage ="%prog -r data_file {-c col | -b} [-t title -w output.pdf]"
    parser = OptionParser(usage = usage)
    parser.add_option("-r", dest = "file",
                      help = "input data file")
    parser.add_option("-c", dest = "col", type=int,
                      help = "init time column of data file")
    parser.add_option("-b", dest = "binary", action="store_true", default=False,
                      help = "indicate if file format is python binary")
    parser.add_option("-t", dest = "title", default="Data",
                      help = "title of graph")
    parser.add_option("-w", dest = "out_file", default=None,
                      help = "output graph file")
    (options, args) = parser.parse_args()

    if not ((options.file and options.col) or
            (options.file and options.binary)):
        parser.print_help()
        exit()
    
    if options.binary:
        data = np.load(options.file)
    else:
        data = pylab.loadtxt(options.file,usecols=[col])
    m,s,t = compute_AT(data, title=options.title)
    print m, s, t
    if options.out_file:
        pylab.savefig(options.out_file)
def parse_gdat(filename):
    print('reading file')
    print(filename)
    #create a dictionary of obserables
    observableDict = defaultdict(list)
    data = []
    sind = 0
    #loop through all the seeds performed
    arraysize = []
    datatmp = pylab.loadtxt(filename)
    arraysize.append(numpy.size(datatmp,axis=0))
    observableDict[filename].append(datatmp)
    print(observableDict[filename])
    with open(filename, 'r') as f:
        observableNames = f.readline()
    observableNames = observableNames.split()
    #print(numpy.size(observableDict[f],axis=0))
    #print(numpy.size(observableDict[f],axis=1))
    #print(numpy.size(observableDict[f],axis=2))
    #now average the data for each seed
    #convert to a numpy array
    #print(data)
    #get the minimum size for data

    return observableDict,observableNames
Beispiel #25
0
def plot_1d(arguments):
    if isinstance(arguments,str):
        arguments = [arguments]
    if len(arguments) < 1:
        print "Need at least one data set"
        sys.exit(1)

    fig = pylab.figure(1)
    ax = fig.add_subplot(111)

    for f in arguments:
        try:
            data = pylab.loadtxt(f)
        except:
            print "Error %s is not a readable file.\n" % (f)
            sys.exit(1)

        #data = pylab.transpose(data)

        ax.plot(data,label=f)

    if len(arguments) > 1:
        ax.legend()

    return data
Beispiel #26
0
    def __init__(self, id, offline=False):
        self.id = id
        self.magSampleList = []
        self.count = 0
        self.filename = "./calibration/" + str(self.id) + ".cal"
        if offline:
            # load data from file
            #file = open("filename", mode='r')
            data = loadtxt(self.filename, skiprows=3, delimiter=',')

            for i in range(len(data)):
                x = data[i,0]
                y = data[i,1]
                z = data[i,2]

                mag = (x,y,z)

                self.magSampleList.append(mag)

        else:
            self.collectData = True
            self.c = CaptureThread(self.handleData)
            self.c.start()
            print "rotate device in all axes for 30 seconds..."
            #raw_input("Rotate device. Press ENTER when done...")
            sleep(10)
            print "20" + " (" + str(len(self.magSampleList)) + ")"
            sleep(10)
            print "10" + " (" + str(len(self.magSampleList)) + ")"
            sleep(10)
            print "Done" + " (" + str(len(self.magSampleList)) + ")"
            self.collectData = False
            self.c.stop = True

        self.processData()
def load_output(filename,number=-1):
   f = open(filename);

   mode = 0;
   sizeOfDataset = 0;
   for line in f.readlines():
      temp = line.strip();
      if temp == "":
         continue;
      if mode == 0:
         if temp[0] == '#':
            continue;
         else:
            mode = 1;
            sizeOfDataset = 1;
            continue;
      else:
         if temp[0] == '#':
            break;
         else:
            sizeOfDataset += 1;

   data = pylab.loadtxt(filename);
   data_parse = list();
#   if number != -1:
#      for i in range(number):
#         data_parse.append(data[i*sizeOfDataset:(i+1)*sizeOfDataset]);
#   else:
   for i in range(len(data)/sizeOfDataset):
      data_parse.append(data[i*sizeOfDataset:(i+1)*sizeOfDataset]);

   return data_parse;
 def plot(self):
     if self.lastPos<0:
         return
     canvas = self.findChild(FigureCanvas)
     timeLegend = self.findChild(QtGui.QLineEdit)
     axes = canvas.figure.gca()
     filename = '%s/postProcessing/%s/%s/%s'%(self.window().currentFolder,self.name,self.dirList[self.lastPos],self.archifield)
     data = pylab.loadtxt(filename)
     if len(data)>0:
         axes.clear()
         #@TODO
         #Fijarse que el sample guarda todos los datos de velocidad, y axis indica el eje de las abcisas
         if data.shape[1]>1:
             for ii in range(data.shape[1]-1):
                 label_ifield = self.ifield+self.labels[ii]
                 axes.plot(data[:,0],data[:,ii+1], color=self.colors[ii], label=label_ifield)
         else:
             axes.plot(data[:,0],data[:,1],'r',label='self.name')
             
         timeLegend.setText(self.dirList[self.lastPos])
         axes.set_title(self.name)
         axes.set_xlabel('distance')
         #axes.set_ylabel('|R|')
         axes.legend(loc=2, fontsize = 'small')
     canvas.draw()
Beispiel #29
0
def plot(filename, column, label):
    data = py.loadtxt(filename).T
    X, Y = data[0], data[column]
    mask = (X >= xmin) * (X <= xmax)
    X, Y = X[mask], corrector(Y[mask])
    aY, bY = np.min(Y), np.max(Y)
    pad = 7 if aY < 0 and -bY/aY < 10 else 0
    py.ylabel(r'$' + label + r'$', y=y_coord, labelpad=8-pad, rotation=0)
    py.plot(X, Y, '-', lw=1)
    py.xlabel(r'$\zeta$', labelpad=-5)
    py.xlim(xmin, xmax)
    ax = py.axes()
    ax.axhline(lw=.5, c='k', ls=':')
    specify_tics(np.min(Y), np.max(Y))
    if inside:
        print "Plot inside plot"
        ax = py.axes([.25, .45, .4, .4])
        mask = X <= float(sys.argv[7])
        py.plot(X[mask], Y[mask], '-', lw=1)
        ax.tick_params(axis='both', which='major', labelsize=8)
        ax.axhline(lw=.5, c='k', ls=':')
        ax.xaxis.set_major_locator(MultipleLocator(0.5))
        ax.yaxis.set_major_locator(LinearLocator(3))
        ymin, _, ymax = ax.get_yticks()
        if (ymax + ymin) < (ymax-ymin)/5:
            y = max(ymax, -ymin)
            py.ylim(-y, y)
def meanOfMeans():
    initialExperiment = 25
    finalExperiment = 35
    suffix = "piConc"
    experimentFolder = "170"

    rootDir = os.path.join("/", "home", "rafaelbeirigo", "ql", "experiments", experimentFolder)

    means = []
    meanFileName = "W_avg_list_mean.out"
    for experiment in range(initialExperiment, finalExperiment + 1):
        meanFilePath = os.path.join(rootDir, str(experiment), "PRQL", meanFileName)
        # open experiment the file that contains the "individual" mean
        # into a list
        mean = pl.loadtxt(meanFilePath)

        # this must be done because the function meanError.meanMultiDim()
        # needs each item in the mean list to be a list itself.
        mean = [[item] for item in mean]

        # append it to the list of means
        means.append(mean)

    # obtain the global mean considering the list of individual means
    globalMean = meanError.meanMultiDim(means)
    ## print globalMean

    # means2spreadsheet([globalMean])

    pl.savetxt(os.path.join(rootDir, "W_avg_list_mean." + suffix + ".out"), globalMean, fmt="%1.6f")

    return globalMean
Beispiel #31
0
import matplotlib.dates as dates
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
from scipy import interpolate

sys.path.append('/home/sakella/python_docs/myStuff/')
from read_netCDF import read_netCDF as get_field_netCDF_file

sys.path.append(
    '/discover/nobackup/sakella/processData/MERRA2_27June2013/before_1982/CMIP/'
)
from get_cmip_sst_sic import get_cmip_sst_sic as get_cmip_sst_sic
from write_cmip_daily import write_cmip_daily as write_cmip_daily

coastLineFile = '/discover/nobackup/sakella/Stuff/matlabStuff/coastLine.dat'
[x_coast, y_coast] = pylab.loadtxt(coastLineFile, unpack=True)
#-----------------------------------------------------------------
start_day = datetime(1982, 01, 01, 00, 0, 0)
end_day = datetime(1982, 12, 31, 00, 0, 0)

iDebug = 0
iPlot = 8  # produce a plot of raw 1x1 deg. CMIP data for a certain month.
iPlot_polar_stereo = 0  # plot SIC in [1]: stereo polar. [0]: latlon projection
#-----------------------------------------------------------------
cmip_data_path = '/discover/nobackup/sakella/processData/MERRA2_27June2013/before_1982/CMIP/data/360x180/'
cmip_sst_pre = 'amipbc_sst_360x180_'
cmip_sic_pre = 'amipbc_sic_360x180_'
cmip_file_suff = '.nc'
#
#MERRA-2 GRID: 1/4 deg
nlon_merra = 1440
Beispiel #32
0
import os
os.chdir(os.path.expanduser("~/Desktop/reflectivity/dynXRD/"))
import pyasf
import reflectivity
import sympy as sp
import pylab as pl

data = pl.loadtxt("test10.dat")
data[:,0] = pl.radians(data[:,0])
#pl.ion()

R = 3,0,0
thickness=1000
Energy=10000

#struct = pyasf.unit_cell("1521772")
struct = pyasf.unit_cell("cif/LiNbO3_28294.cif") #Li Nb O3
Sub=reflectivity.Substrate(struct)
#v_par=sp.Matrix([0,0,1])
psi=sp.pi/2
v_perp=sp.Matrix([0,1,0])
#Sub.calc_orientation(v_par, v_perp)
Sub.calc_orientation_from_angle(psi, v_perp)
layer1=reflectivity.Epitaxial_Layer(struct, thickness)
#layer1.calc_orientation(v_par, v_perp)\
layer1.calc_orientation_from_angle(psi, v_perp)
crystal=reflectivity.Sample(Sub, layer1)
crystal.set_Miller(R)
crystal.calc_g0_gH(Energy)
thBragg= float(layer1.calc_Bragg_angle(Energy).subs(layer1.structure.subs).evalf())
angle=pl.linspace(0.995, 1.005,501)*thBragg
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import pylab
import numpy
import matplotlib.pyplot as plt

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
filename = 'gummel_0.0.out'
#HEADER: V(base) V(collector) V(emitter) I(base) I(collector) I(emitter)
data = pylab.loadtxt(filename)
vbe = data[:, 0] - data[:, 2]
ic = data[:, 4]
ib = data[:, 3]
beta = ic / ib
l1 = ax1.semilogy(vbe, beta, "-*", label=r"$\beta$", color="black")
l2 = ax2.semilogy(vbe, ic, "-+", label=r"$I_c$")
l3 = ax2.semilogy(vbe, ib, "-.", label=r"$I_b$")
lns = l1 + l2 + l3
ax1.legend(l1 + l2 + l3, (r"$\beta$", r"$I_c$", r"$I_b$"), loc="upper left")
#pylab.title("Title of Plot")
ax1.set_xlabel(r"$V_{be}$ (V)")
ax2.set_ylabel(r"A/cm")
#ax2.set_ylabel(r"A/cm")
#pylab.ylabel("Y Axis Label")
pylab.savefig('gummel.pdf')
Beispiel #34
0
    "grav_mesh", "cooling", "sourceterms", "count"
]

SUBTYPES = [
    "none", "density", "gradient", "force", "grav", "external_grav", "tend",
    "xv", "rho", "gpart", "multipole", "spart", "count"
]

SIDS = [
    "(-1,-1,-1)", "(-1,-1, 0)", "(-1,-1, 1)", "(-1, 0,-1)", "(-1, 0, 0)",
    "(-1, 0, 1)", "(-1, 1,-1)", "(-1, 1, 0)", "(-1, 1, 1)", "( 0,-1,-1)",
    "( 0,-1, 0)", "( 0,-1, 1)", "( 0, 0,-1)"
]

#  Read input.
data = pl.loadtxt(infile)
full_step = data[0, :]

#  Do we have an MPI file?
full_step = data[0, :]
if full_step.size == 13:
    print "# MPI mode"
    mpimode = True
    nranks = int(max(data[:, 0])) + 1
    print "# Number of ranks:", nranks
    rankcol = 0
    threadscol = 1
    taskcol = 2
    subtaskcol = 3
    ticcol = 5
    toccol = 6
Beispiel #35
0
import numpy as np
import matplotlib.pyplot as plt
import pylab
import sys

d1 = pylab.loadtxt("5MW_Blade_Property.txt", skiprows=2)
d2 = np.zeros(11)
for i in range(0, 11):
    d1[i, 3] = d1[i, 3] * 1.04536
    d2[i] = d1[i, 9] + d1[i, 10]

f = open('5MW_Blade_F3.inp', 'w')
for i in range(0, 11):
    (f.write('%14.5E' % d1[i, 0]), f.write('%14.5E' % d1[i, 3]),
     f.write('%14.5E' % d1[i, 10]), f.write('%14.5E' % d1[i, 9]),
     f.write('%14.5E' % 0), f.write('%14.5E' % d1[i, 14]),
     f.write('%14.5E' % 0), f.write('%14.5E' % d1[i, 7]),
     f.write('%14.5E' % d1[i, 5]), f.write('%14.5E' % d1[i, 4]),
     f.write('%14.5E' % 0), f.write('%14.5E' % 0), f.write('%14.5E' % 0),
     f.write('%14.5E' % d1[i, 6]), f.write('%14.5E' % d1[i, 7]),
     f.write('%14.5E' % d1[i, 7]), f.write('%14.5E' % 0),
     f.write('%14.5E' % 0), f.write('%14.5E' % 0), f.write('\n'))
f.close()
Beispiel #36
0
rcParams[
    'mathtext.default'] = 'regular'  # match the font used for regular text

gasGamma = 1.4

# read data
d = gkedata.GkeData("s3-dg-euler-pos_q_1.h5")
dgDat = gkedgbasis.GkeDgLobatto1DPolyOrder1Basis(d)
X, rho = dgDat.project(0)
X, rhou = dgDat.project(1)
X, Er = dgDat.project(4)

u = rhou / rho
pr = (gasGamma - 1) * (Er - 0.5 * rho * u * u)

ex_density = pylab.loadtxt("s18-euler-shock-exact-density.txt")
ex_velocity = pylab.loadtxt("s18-euler-shock-exact-velocity.txt")
ex_pressure = pylab.loadtxt("s18-euler-shock-exact-pressure.txt")
ex_ie = pylab.loadtxt("s18-euler-shock-exact-internal-energy.txt")

pylab.figure(1)
pylab.subplot(2, 2, 1)
pylab.plot(X, rho, 'k-')
pylab.plot(ex_density[:, 0], ex_density[:, 1], 'r-')
pylab.axis('tight')
pylab.ylabel("Density")

pylab.subplot(2, 2, 2)
pylab.plot(X, u, 'k-')
pylab.plot(ex_velocity[:, 0], ex_velocity[:, 1], 'r-')
pylab.axis('tight')
Beispiel #37
0
# pycombina is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with pycombina. If not, see <http://www.gnu.org/licenses/>.

import numpy as np
import pylab as pl

from pycombina import BinApprox, CombinaBnB, CombinaMILP, CombinaSUR

pl.close("all")

data = pl.loadtxt("data/mmlotka_nt_12000_400.csv", delimiter=" ", skiprows=1)

dN = 8

t = data[::dN, 0]
b_rel = data[:-1:dN, 3:]

max_switches = [5, 2, 3]

binapprox = BinApprox(t = t, b_rel = b_rel, binary_threshold = 1e-3, \
        off_state_included = True)
binapprox.set_n_max_switches(n_max_switches=max_switches)

#binapprox.set_valid_controls_for_interval((0, 2), [1,0,0])
#binapprox.set_valid_control_transitions(0, [1,0,1])
#binapprox.set_min_up_times([2.0, 2.0, 2.0])
Beispiel #38
0
from uncertainties import ufloat
import math
import numpy
import numpy
import pylab
from scipy.optimize import curve_fit
import math
import scipy.stats

import uncertainties 

def linear(x, a, b):
	return a*x+b


Vl, Vce, dVl, dVce = pylab.loadtxt('/home/federico/Laboratorio3/relazione3/dati2.txt', unpack=True)


Rb = 46700 
dRb = 400
Rl = 977
dRl = 8

Ic = (Vl)/Rl
dIc = Ic*((dVl/Vl)**2+(dRl/Rl)**2)**0.5


pylab.figure(2)
pylab.title('I_c vs V_be')
pylab.xlabel('V_ce (V)')
pylab.ylabel('I_c (mA)')
'script per calcolo apertura numerica di una fibra ottica'

import pylab as py
from lab import fit_curve

files = ['borcapFOLAN3.txt', 'borcapFOMAN4.txt']

py.figure(1).set_tight_layout(True)
py.clf()
NA_prima = py.ones(len(files))
NA_dopo = py.ones(len(files))
NA_m = py.ones(len(files))

for i in range(len(files)):
    filename = files[i]
    ang, P = py.loadtxt(filename, unpack=True)
    dang = py.ones(len(ang)) * 0.5
    dP = P * 0.03

    Pmax = max(P)
    P5 = Pmax * 0.05  #P al 5% di P_max

    #trovo l'indice corrispondente a P_max così da avere il massimo in 0
    m = 0
    while P[m] < Pmax:
        m = m + 1
    ang = ang - ang[m]

    ##faccio il grafico
    py.figure(1)
    py.subplot(2, 1, i + 1)
def plot():
    experimento = '/home/rafaelbeirigo/ql/experiments/'

    pi0 = pl.loadtxt(experimento + "/67/PRQL/w.out")
    pi1 = pl.loadtxt(experimento + "/68/PRQL/w.out")
    pi2 = pl.loadtxt(experimento + "/69/PRQL/w.out")
    pi3 = pl.loadtxt(experimento + "/70/PRQL/w.out")
    pi4 = pl.loadtxt(experimento + "/71/PRQL/w.out")
    pi5 = pl.loadtxt(experimento + "/72/PRQL/w.out")
    pi6 = pl.loadtxt(experimento + "/73/PRQL/w.out")
    pi7 = pl.loadtxt(experimento + "/74/PRQL/w.out")
    pi8 = pl.loadtxt(experimento + "/75/PRQL/w.out")
    pi9 = pl.loadtxt(experimento + "/76/PRQL/w.out")
    pi10 = pl.loadtxt(experimento + "/77/PRQL/w.out")

    ql = pl.loadtxt(experimento + "/56/QL/w.out")

    pl.xlabel("Episodes")
    pl.ylabel("W")

    intervalo = 15
    incremento = 50

    intervalo_pi10 = intervalo
    intervalo += incremento
    intervalo_pi9 = intervalo
    intervalo += incremento
    intervalo_pi8 = intervalo
    intervalo += incremento
    intervalo_pi7 = intervalo
    intervalo += incremento
    intervalo_pi6 = intervalo
    intervalo += incremento
    intervalo_pi5 = intervalo
    intervalo += incremento
    intervalo_pi4 = intervalo
    intervalo += incremento
    intervalo_pi3 = intervalo
    intervalo += incremento
    intervalo_pi2 = intervalo
    intervalo += incremento
    intervalo_pi1 = intervalo
    intervalo += incremento
    intervalo_pi0 = intervalo_pi10
    intervalo_ql = intervalo_pi10

    x_pi10 = pl.mgrid[:pi10.shape[0]:intervalo_pi10]
    x_pi9 = pl.mgrid[:pi7.shape[0]:intervalo_pi9]
    x_pi8 = pl.mgrid[:pi7.shape[0]:intervalo_pi8]
    x_pi7 = pl.mgrid[:pi7.shape[0]:intervalo_pi7]
    x_pi6 = pl.mgrid[:pi7.shape[0]:intervalo_pi6]
    x_pi5 = pl.mgrid[:pi7.shape[0]:intervalo_pi5]
    x_pi4 = pl.mgrid[:pi7.shape[0]:intervalo_pi4]
    x_pi3 = pl.mgrid[:pi7.shape[0]:intervalo_pi3]
    x_pi2 = pl.mgrid[:pi7.shape[0]:intervalo_pi2]
    x_pi1 = pl.mgrid[:pi7.shape[0]:intervalo_pi1]
    x_pi0 = pl.mgrid[:pi0.shape[0]:intervalo_pi0]
    x_ql = pl.mgrid[:ql.shape[0]:intervalo_ql]

    pl.plot(x_ql, ql[::intervalo_ql], 'o', label='Q-Learning')
    pl.plot(x_pi10, pi10[::intervalo_pi10], '*')
    pl.plot(x_pi9, pi9[::intervalo_pi9], '*')
    pl.plot(x_pi8, pi8[::intervalo_pi8], '*')
    pl.plot(x_pi7, pi7[::intervalo_pi7], '*')
    pl.plot(x_pi6, pi6[::intervalo_pi6], '*')
    pl.plot(x_pi5, pi5[::intervalo_pi5], '*')
    pl.plot(x_pi4, pi4[::intervalo_pi4], '*')
    pl.plot(x_pi3, pi3[::intervalo_pi3], '*')
    pl.plot(x_pi2, pi2[::intervalo_pi2], '*')
    pl.plot(x_pi1, pi1[::intervalo_pi1], '*')

    # plota linhas ate o final (com esses intervalos as vezes falta ponto no final)
    pl.plot(pi10, linestyle='-', label='Otima: 100% Pessima:   0%', color='g')
    pl.plot(pi9, linestyle='-', label='Otima:  90% Pessima:  10%')
    pl.plot(pi8, linestyle='-', label='Otima:  80% Pessima:  20%')
    pl.plot(pi7, linestyle='-', label='Otima:  70% Pessima:  30%')
    pl.plot(pi6, linestyle='-', label='Otima:  60% Pessima:  40%')
    pl.plot(pi5, linestyle='-', label='Otima:  50% Pessima:  50%')
    pl.plot(pi4, linestyle='-', label='Otima:  40% Pessima:  60%')
    pl.plot(pi3, linestyle='-', label='Otima:  30% Pessima:  70%')
    pl.plot(pi2, linestyle='-', label='Otima:  20% Pessima:  80%')
    pl.plot(pi1, linestyle='-', label='Otima:  10% Pessima:  90%')
    pl.plot(pi0, linestyle='-', label='Otima:   0% Pessima: 100%', color='r')

    leg_prop = matplotlib.font_manager.FontProperties(size=12)
    pl.legend(loc=4, prop=leg_prop)
Beispiel #41
0
#-------------------------------------------------------------------------------

if __name__ == '__main___':
    """
    """

    #parameters=lumfunc.parameters['C','alpha','Smin','Smax']

    #Testing all functionality
    #c=pylab.loadtxt('chain_2d_banana.txt')
    #contour(c,[0,1], labels=['1', '2'], col=('#3bf940','#059a09'),line=True)

    # Run as e.g.
    contour_plot.contourTri(
        pylab.loadtxt('chains-4-all-10deg-130812/1-post_equal_weights.dat'),
        line=True,
        outfile='chains-4-all-10deg-130812/test.png',
        col=('red', 'blue'),
        labels=lumfunc.parameters,
        ranges=lumfunc.plotRanges,
        truth=lumfunc.plotTruth,
        reconstruct=(lumfunc.medianArray(lumfunc.bins), lumfunc.ksNoisy),
        autoscale=False,
        title='title')

    #contour_plot.contourTri(pylab.loadtxt('chains-3-fixSmin-10deg-130812/1-post_equal_weights.dat'),line=True,outfile='test.png',col=('red','blue'),labels=lumfunc.parameters)

    #import pymultinest
    #a=pymultinest.Analyzer(len(lumfunc.parameters),'chains-4-all-mm-10deg-130815/1-')
    #s=a.get_stats()
xlo, xup = 0.0, 2*math.pi
ylo, yup = -6, 6
nx, ny = 64, 64

X = pylab.linspace(0, 2*math.pi, nx+1)
Y = pylab.linspace(-6, 6, ny+1)

dx = (xup-xlo)/nx
dy = (yup-ylo)/ny

Xc = pylab.linspace(xlo+0.5*dx, xup-0.5*dx, nx)
Yc = pylab.linspace(ylo+0.5*dy, yup-0.5*dy, ny)

tEnd = 10.0
nFrame = 4

T = pylab.linspace(0, tEnd, nFrame+1)

fig = pylab.figure(3)
numDenHist = pylab.loadtxt("s143-vlasov-free-stream_numDensInCell")
pylab.plot(numDenHist[:,0], numDenHist[:,1], 'k-')
# exact solution at selected points
Tex = pylab.linspace(0, tEnd, 20)
nEx = numDenHist[0,1]*pylab.exp(-0.5*Tex**2)
pylab.plot(Tex, nEx, 'ro')
pylab.xlabel('Time [s]')
pylab.ylabel('Number Density')
pylab.savefig('s143-vlasov-free-stream_numDensInCell.pdf')
pylab.close()
Beispiel #43
0
def lassoW():
    return pl.loadtxt('lasso_true_w.txt')
Beispiel #44
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
Beispiel #45
0
    'en_vs_rho_k10.dat', 'pidle_vs_rho_k10.dat', 'ploss_vs_rho_k10.dat',
    'en_vs_rho_k40.dat', 'pidle_vs_rho_k40.dat', 'ploss_vs_rho_k40.dat'
]

figure = 0

pylab.rc('font', **{'family': 'sans-serif', 'sans-serif': ['Helvetica']})

os.chdir(os.path.dirname(os.path.realpath(__file__)) + "/..")
call(["make", "distclean"])
call(["make"])
call(["./sim", "-t 10000", "-c 1000000", "-l 12000", "-r 0.25,0.95"])

pylab.figure(++figure)
pylab.clf()
data, label = pylab.loadtxt(filelist[0], delimiter=','), r'K=$\infty$'
pylab.plot(data[:, 0], data[:, 1], label=label)
pylab.title(r"$E[N]$ vs $\rho$")
pylab.xlabel(r"Utilization of the buffer")
pylab.ylabel(r"Average \# of packets in the buffer")
pylab.legend()
pylab.savefig(filelist[0].rsplit('.', 1)[0] + ".png")

pylab.figure(++figure)
pylab.clf()
data, label = pylab.loadtxt(filelist[0], delimiter=','), r'K=$\infty$'
pylab.plot(data[:, 0], data[:, 1], label=label)
pylab.title(r"$P_{idle}$ vs $\rho$")
pylab.xlabel(r"Utilization of the buffer")
pylab.ylabel(r"Proportion of time the system is idle")
pylab.legend()
Beispiel #46
0
#!/usr/bin/env python

#need this to run without xserver
import matplotlib
matplotlib.use('Agg')

import math
import matplotlib.pyplot as pyplot
import numpy
import pylab

hardsphereR = 3.03420 / 2 / 10  # from Clark et al, in nm

newdata = pylab.loadtxt('figs/single-rod-in-water.dat')
hugdata = pylab.loadtxt('figs/hughes-single-rod-in-water.dat')
rnew = newdata[:, 0] - hardsphereR
rhug = hugdata[:, 0] - hardsphereR
newbrokenHB = newdata[:, 2]
hugbrokenHB = hugdata[:, 2]
p1, = pylab.plot(rnew, newbrokenHB / 2, color='#990022', linestyle='-')  #'r-')
p2, = pylab.plot(rhug, hugbrokenHB / 2, color='#220099',
                 linestyle='--')  #'k--')

#plot properties
pyplot.ylabel('Broken bonds per nm')
pyplot.xlabel('Radius of rod (nm)')
pyplot.xlim(0, 1.5)
pyplot.ylim(0, 10)
pyplot.legend([p2, p1], ["Hughes, et al", "This work"], loc=2)
pyplot.savefig('figs/single-rod-broken-HB.pdf')
Beispiel #47
0
def getData(name):
    data = pl.loadtxt(name)
    # Returns column matrices
    X = data[0:1].T
    Y = data[1:2].T
    return X, Y
Beispiel #48
0
import math
import numpy
import numpy
import pylab
from scipy.optimize import curve_fit
import math
import scipy.stats
import uncertainties 
from uncertainties import unumpy

def linear(x, a, b):
	return a*(x-b)**2

INPUT = "/home/federico/Laboratorio3/relazione5/datiParabola.txt"

Vd, dVd, Vgs, dVgs = pylab.loadtxt(INPUT, unpack=True)

R_1 = ufloat(0.994*1000, 0.008*1000)
R_2 = ufloat(1.954*1000, 0.016*1000)
V_1 = ufloat(15.01, 0.08)
V_2 = ufloat(-15.11, 0.08)

#Nelle visualizzazioni devo introdurre gli errori

V_GS = unumpy.uarray(Vgs, dVgs)
V_D = unumpy.uarray(Vd, dVd)

I_D = V_D/R_1
I_D = 1000*I_D

pylab.rc('font',size=13)
Beispiel #49
0
    'family': 'sans-serif',
    'color': 'black',
    'weight': 'normal',
    'size': 16,
}
fig_size = plt.rcParams["figure.figsize"]
fig_size[0] = 12
fig_size[1] = 5
plt.rcParams["figure.figsize"] = fig_size

# step size (constant value)
DT05 = 0.05
DT01 = 0.01
DT001 = 0.001
# load data
y2 = pylab.loadtxt(sys.argv[1] + "_001.txt")
y3 = pylab.loadtxt(sys.argv[1] + "_01.txt")
y4 = pylab.loadtxt(sys.argv[1] + "_05.txt")
y5 = pylab.loadtxt(sys.argv[1] + "_PID.txt")

t05 = np.linspace(0, y4.size * DT05, y4.size)
t01 = np.linspace(0, y3.size * DT01, y3.size)
t001 = np.linspace(0, y2.size * DT001, y2.size)

# setup the figure
fig = plt.figure()

for i in range(0, y5.size):
    if y5[i] < 0:
        y5[i] = y5[i] * -1
#print "%d" % y3.size
Beispiel #50
0
# System

x = ca.MX.sym("x", 2)
p = ca.MX.sym("p", 1)
u = ca.MX.sym("u", 1)

# f = ca.vertcat([x[1], p[0]/(m*(L**2))*(u-x[0]) - g/L * pl.sin(x[0])])
f = ca.vertcat([x[1], p[0]/(m*(L**2))*(u-x[0]) - g/L * x[0]])

phi = x

odesys = pecas.systems.ExplODE(x = x, u = u, p = p, f = f, phi = phi)
odesys.show_system_information(showEquations = True)

data = pl.loadtxt('data_pendulum.txt')
tu = data[:500, 0]
numeas = data[:500, 1]
wmeas = data[:500, 2]
yN = pl.array([numeas,wmeas])
N = tu.size
uN = [psi] * (N-1)

wv = pl.ones(yN.shape)

lsqpe_sim = pecas.LSq( \
    system = odesys, tu = tu, \
    uN = uN, \
    pinit = 1, \
    xinit = yN, 
    # linear_solver = "ma97", \
Beispiel #51
0
fiendex_forandring = []
fiendey_forandring = []
ROMVESEN = pygame.transform.scale(ROMVESEN, (60, 60))

for i in range(fiende_nummer):
    fiendeImg.append(ROMVESEN)
    fiendex.append(random.randint(0, bredde - 40))
    fiendey.append(random.randint(50, 150))
    fiendex_forandring.append(fiende_fart)
    fiendey_forandring.append(40)

#Score og level
score_value = 0
level_nå = 0

high_score = str(int(loadtxt("./assets/poeng.txt")))


def fiende(x, y, i):
    vindu.blit(fiendeImg[i], (x, y))


def spiller(x, y):
    vindu.blit(SPILLER, (x, y))


def skyt_laser(x, y):
    global lasertid
    lasertid = "fire"
    vindu.blit(SPILLERLASER, (x, y + 10))
Beispiel #52
0
# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""
import pylab as p
p.close('all')
data = p.loadtxt('caustic_18.11.04_L2.1.txt', skiprows=1)
x    = data[:,0]/100
u    = data[:,1]/1000
v    = data[:,2]/1000
el   = data[:,3]


p.figure(figsize=(8, 4.5))
p.plot(x,u,'r.', label='u-radius')
p.plot(x,v,'b.', label='v-radius')
p.title('Beam Profile at Fiber Tip', fontsize=18)
p.xlabel('Distance From Center of Iris2 [m]', fontsize=14)
p.ylabel('Beam Diameter [mm]', fontsize=14 )
p.legend(fontsize=14)


p.figure()
p.plot(x, el, 'b.')
Beispiel #53
0
#Code taken from https://stackoverflow.com/a/48979692

import matplotlib.pyplot as plt
import pylab
from matplotlib.collections import PatchCollection

#These numbers should match simulation.c
NTIMESTEPS=300
NPOINTS=100

#Load our data.
data=pylab.loadtxt("out.txt")

#10 second video at 30 fps = 300 frames
for timestep in range(NTIMESTEPS):
    plt.close('all')
    fig, axes = plt.subplots(figsize=(5,5))
    #adding the Circles to the plot using a PatchCollection is much faster.
    patches=[]

    #Grab the correct datapoints from the file and add them as circles.
    for i in range(NPOINTS):
        index=timestep*NPOINTS+i;
        patches.append(plt.Circle((data[index,2],data[index,3]),0.15))

    axes.add_collection(PatchCollection(patches, alpha=0.95))
    axes.set_xlim(-1,10)
    axes.set_ylim(-1,10)
    axes.set_xlabel("x (m)")
    axes.set_ylabel("y (m)")
    axes.set_title("t=%.2f seconds" % data[timestep*NPOINTS,0])
Beispiel #54
0
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.lines as lines

# setup font
font =  {'family' : 'sans-serif',
         'color'  : 'black',
         'weight' : 'normal',
         'size'   : 16,
        }

# step size (constant value)
DT = 0.001

# load data
y = pylab.loadtxt("./track_sinusoidal.torque")
t = np.linspace(0,y[:,0].size*DT,y[:,0].size)

# setup the figure
fig = plt.figure()

# plot data
plt.plot(t,y[:,1],'k' ,label='PD control torque (joint 1)')
plt.plot(t,y[:,0],'r' ,label='inverse dynamics torque (joint 1)')

# add titles, labels, and legend
plt.title('Motor torques for PD control vs. inverse dynamics control for track sinusoidal task', fontdict=font)
plt.xlabel('Time', fontdict=font)
plt.ylabel('Torque', fontdict=font)
plt.legend(loc=4, shadow=True)
def main():

    # PHYSICS AND MACHINE PARAMETERS.
    intensity = 4.5e11  # Number of particles (protons) per bunch.
    charge = e  # Charge of a proton.
    mass = m_p  # Mass of a proton.

    sigma_z = 0.0936851405476  # Bunch length (RMS) [m].
    gamma = 4263.15613303  # Relativistic gamma.
    alpha_0 = 0.0003225  # Momentum compaction factor.
    eta = alpha_0 - 1. / gamma**2  # Slippage factor.
    gamma_t = 1. / np.sqrt(alpha_0)  # Transition gamma.

    p0 = np.sqrt(gamma**2 - 1) * mass * c  # Momentum.

    Q_s = 0.00234243399047  # Synchrotron tune.
    Q_x = 64.31  # Betatron tune (horizontal).
    Q_y = 59.32  # Betatron tune (vertical).

    C = 26658.883  # Ring circumference [m].
    R = C / (2. * np.pi)  # Ring radius [m].

    alpha_x = 0.
    alpha_y = 0.

    Qp_x = 0.  # Horizontal chromaticity.
    Qp_y = 0.  # Vertical chromaticity.

    beta_x = 65.9756337546  # Horizontal beta function [m].
    beta_y = 71.5255058456  # Vertical beta function [m].
    beta_z = eta * R / Q_s  # Longitudinal beta function [m].

    epsn_x = 2.0  # Horizontal emittance [um].
    epsn_y = 2.0  # Vertical emittance [um].
    epsn_z = 4. * np.pi * sigma_z**2 * p0 / (beta_z * e)

    # SIMULATION PARAMETERS.
    n_macroparticles = 20000  # Number of macroparticles per bunch (go to 1e6).
    n_turns = 5  # Number of turn (set to 2e5 later)

    # ==============================================================================================
    # GENERATE BUNCH AND CREATE VARIOUS SLICINGS.
    # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    # Create bunch (matched) and apply initial kicks.
    bunch = Particles.as_gaussian(n_macroparticles,
                                  charge,
                                  gamma,
                                  intensity,
                                  mass,
                                  alpha_x,
                                  beta_x,
                                  epsn_x,
                                  alpha_y,
                                  beta_y,
                                  epsn_y,
                                  beta_z,
                                  epsn_z,
                                  generator_seed=10)

    # Import bunch from file.
    bunch.x = np.loadtxt('./initBunch/x.dat')
    bunch.y = np.loadtxt('./initBunch/y.dat')
    bunch.z = np.loadtxt('./initBunch/z.dat')
    bunch.xp = np.loadtxt('./initBunch/xp.dat')
    bunch.yp = np.loadtxt('./initBunch/yp.dat')
    bunch.dp = np.loadtxt('./initBunch/dp.dat')

    # SLICINGS
    n_slices_for_wakes = 20
    slices_for_wakes = Slicer(n_slices_for_wakes,
                              nsigmaz=3,
                              mode='const_space')
    slices_for_wakes.update_slices(bunch)

    # ==============================================================================================
    # SET UP SYNCHROTRON AND BETATRON MOTION.
    # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    n_segments = 1  # Number of segments per turn.
    s = np.arange(0, n_segments + 1) * C / n_segments

    # BETATRON
    # Loop on number of segments and create the TransverseSegmentMap for each segment.
    alpha_x *= np.ones(n_segments)
    beta_x *= np.ones(n_segments)
    D_x = np.zeros(n_segments)
    alpha_y *= np.ones(n_segments)
    beta_y *= np.ones(n_segments)
    D_y = np.zeros(n_segments)

    transverse_map = TransverseMap(s, alpha_x, beta_x, D_x, alpha_y, beta_y,
                                   D_y, Q_x, Q_y)

    # SYNCHROTRON
    cavity = LinearMap(C, alpha_0, Q_s, (slices_for_wakes, ))

    # ==============================================================================================
    # SET UP WAKE FIELDS USING RESONATOR MODEL.
    # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    R_shunt = 10e6
    frequency = 2e9
    Q = 0.9
    Yokoya_X1 = 0.5
    Yokoya_Y1 = 0.5
    Yokoya_X2 = 0.5
    Yokoya_Y2 = 0.5
    Yokoya_Z = 0
    wakes = Wakes.resonator(R_shunt, frequency, Q, Yokoya_X1, Yokoya_Y1,
                            Yokoya_X2, Yokoya_Y2, Yokoya_Z, slices_for_wakes)

    # ==============================================================================================
    # SET UP ACCELERATOR MAP AND START TRACKING
    # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    # Accelerator map.
    map_ = [transverse_map[0]] + [cavity]
    wakes = [wakes]

    f, (ax1, ax2, ax3, ax4) = plt.subplots(4, sharex=True)

    # Read data from files created with old PyHT version.
    # (where wakes were benchmarked against HT -> see pres. M. Schenk, 22.07.2014, HTWG Meeting).
    dipX_kick_old_version = plt.loadtxt(
        './resultsOldPyHT/kicks_dipX_resonator.dat')
    dipY_kick_old_version = plt.loadtxt(
        './resultsOldPyHT/kicks_dipY_resonator.dat')
    quadX_kick_old_version = plt.loadtxt(
        './resultsOldPyHT/kicks_quadX_resonator.dat')
    quadY_kick_old_version = plt.loadtxt(
        './resultsOldPyHT/kicks_quadY_resonator.dat')

    # For new PyHT version.
    dipX_kick = np.zeros(n_macroparticles)
    dipY_kick = np.zeros(n_macroparticles)
    quadX_kick = np.zeros(n_macroparticles)
    quadY_kick = np.zeros(n_macroparticles)

    # Start tracking.
    for i in range(n_turns):
        t0 = time.clock()

        for m in map_:
            m.track(bunch)

        if i == 4:
            # Dip kicks.
            xp_old = np.zeros(n_macroparticles)
            xp_old[:] = bunch.xp
            wakes[0].wake_kicks[0].apply(bunch, slices_for_wakes)
            dipX_kick[:] = bunch.xp - xp_old

            yp_old = np.zeros(n_macroparticles)
            yp_old[:] = bunch.yp
            wakes[0].wake_kicks[2].apply(bunch, slices_for_wakes)
            dipY_kick[:] = bunch.yp - yp_old

            # Quad kicks.
            wakes[0].wake_kicks[1].apply(bunch, slices_for_wakes)
            quadX_kick[:] = bunch.xp - xp_old

            wakes[0].wake_kicks[3].apply(bunch, slices_for_wakes)
            quadY_kick[:] = bunch.yp - yp_old

            # Compare results for old and new versions.
            ax1.plot(dipX_kick, c='r', label='new version')
            ax1.plot(dipX_kick_old_version,
                     'b',
                     linestyle='dashed',
                     label='old version')
            ax1.set_ylabel('dipX kick')
            handles, labels = ax1.get_legend_handles_labels()
            ax1.legend(handles, labels)

            ax2.plot(dipY_kick, c='r', label='new version')
            ax2.plot(dipY_kick_old_version,
                     c='b',
                     linestyle='dashed',
                     label='old version')
            ax2.set_ylabel('dipY kick')
            handles, labels = ax2.get_legend_handles_labels()
            ax2.legend(handles, labels)

            ax3.plot(quadX_kick, c='r', label='new version')
            ax3.plot(quadX_kick_old_version,
                     c='b',
                     linestyle='dashed',
                     label='old version')
            ax3.set_ylabel('quadX kick')
            handles, labels = ax3.get_legend_handles_labels()
            ax3.legend(handles, labels)

            ax4.plot(quadY_kick, c='r', label='new version')
            ax4.plot(quadY_kick_old_version,
                     c='b',
                     linestyle='dashed',
                     label='old version')
            ax4.set_ylabel('quadY kick')
            ax4.set_xlabel('particle no.')
            handles, labels = ax4.get_legend_handles_labels()
            ax4.legend(handles, labels)

        else:
            wakes[0].track(bunch)

        print 'turn', i

    plt.show()
Beispiel #56
0
import pylab
import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import matplotlib as mplt

###CARICA

print('\n\n\nCARICA\n\n\n')

x, y = pylab.loadtxt(
    r'C:\Users\Satellite\Desktop\Università 2\Laboratorio 2\_ESAME\lab2 Giulio\esercitazione 4\dati\DatiCond1_C.txt',
    unpack=True)  #file Arduino:prima colonna tempo,seconda voltaggio
# ATTENZIONE ALLE UNITA' DI MIAURA
dx = 4 / 1000
dy = np.array([1] * len(y))
x = x / 1000


#Funzione carica
def carica(x, q, t):
    return q * (1 - np.exp(-x / t))


init = (1023, 15)  #q è il max valore in digit di delta V (1023), t è tau=RC
#UNITA' DI MISURAAAAA

pylab.figure(0)  #Serve per vedere se gli init sono giusti
pylab.errorbar(x, y, dy, dx, linestyle='', color='black', marker='.')
xx = np.linspace(min(x), max(x), 2000)
pylab.plot(xx, carica(xx, *init), color='red')
import pylab
import tables
import math

dat = pylab.loadtxt("fdtd-convergence.dat")
dx = dat[:,0]
err75 = dat[:,1]
err150 = dat[:,2]

fig = pylab.figure(1)
pylab.loglog(dx, err75, 'r-')
pylab.loglog(dx, err75, 'ro')
pylab.loglog(dx, err150, 'k-')
pylab.loglog(dx, err150, 'ko')
pylab.xlabel("Grid spacing")
pylab.ylabel("Average error")
pylab.axis('tight')
pylab.title('Error for wave-propagation scheme')
pylab.show()
pylab.savefig("tm-wave-convergence.png")

print "Order of convergence t=75"
for i in range(1, dx.shape[0]):
    od = (pylab.log(err75[i]) - pylab.log(err75[i-1]))/(pylab.log(dx[i]) - pylab.log(dx[i-1]))
    print od

print "Order of convergence t=150"
for i in range(1, dx.shape[0]):
    od = (pylab.log(err150[i]) - pylab.log(err150[i-1]))/(pylab.log(dx[i]) - pylab.log(dx[i-1]))
    print od
from pylab import plot, show
from numpy import linspace, sin, cos
from pylab import loadtxt
from pylab import plot, show, xlim, ylim
x = linspace(0, 10, 100)
y = sin(x)
ylim(-1.1, 1.1)
g = cos(x)
plot(x, y)
plot(x, g)
show()

a = open("grafic.txt", "w")
for i in range(len(x)):
    a.write("%.2f%.2f\n" % (x[i], y[i]))
a.close()

b = loadtxt("grafic.txt", float)
print(b[:0])
print(b[:1])
Beispiel #59
0
@author: loredp
"""

import sklearn.linear_model as skls
import lassoData
import pylab as pl
import functions as fun
import matplotlib.pyplot as plt
import numpy as np

train = lassoData.lassoTrainData()
val = lassoData.lassoValData()
test = lassoData.lassoTestData()

true_w = pl.loadtxt('lasso_true_w.txt')  #True value for the data

#Step 1: transform data

X = train[0]
Y = train[1]

(Xc, Yc) = fun.center_data(X, Y)

alpha = 0.2
fig = plt.figure()
fig.add_subplot(121)
w1 = fun.compare(X, Y, M=12, alpha=alpha, basis=fun.basis_sin)
plt.bar(range(13), w1[0], color='teal')
plt.title('LASSO')
fig.add_subplot(122)
def load_video_info(video_path):
    """
    Loads all the relevant information for the video in the given path:
    the list of image files (cell array of strings), initial position
    (1x2), target size (1x2), whether to resize the video to half
    (boolean), and the ground truth information for precision calculations
    (Nx2, for N frames). The ordering of coordinates is always [y, x].

    The path to the video is returned, since it may change if the images
    are located in a sub-folder (as is the default for MILTrack's videos).
    """

    # load ground truth from text file (MILTrack's format)
    text_files = glob.glob(os.path.join(video_path, "*_gt.txt"))
    assert text_files, \
        "No initial position and ground truth (*_gt.txt) to load."

    first_file_path = os.path.join(video_path, text_files[0])
    #f = open(first_file_path, "r")
    #ground_truth = textscan(f, '%f,%f,%f,%f') # [x, y, width, height]
    #ground_truth = cat(2, ground_truth{:})
    ground_truth = pylab.loadtxt(first_file_path, delimiter=",")
    #f.close()

    # set initial position and size
    first_ground_truth = ground_truth[0, :]
    # target_sz contains height, width
    target_sz = pylab.array([first_ground_truth[3], first_ground_truth[2]])
    # pos contains y, x center
    pos = [first_ground_truth[1], first_ground_truth[0]] \
        + pylab.floor(target_sz / 2)

    #try:
    if True:
        # interpolate missing annotations
        # 4 out of each 5 frames is filled with zeros
        for i in range(4):  # x, y, width, height
            xp = range(0, ground_truth.shape[0], 5)
            fp = ground_truth[xp, i]
            x = range(ground_truth.shape[0])
            ground_truth[:, i] = pylab.interp(x, xp, fp)
        # store positions instead of boxes
        ground_truth = ground_truth[:, [1, 0]] + ground_truth[:, [3, 2]] / 2
    #except Exception as e:
    else:
        print("Failed to gather ground truth data")
        #print("Error", e)
        # ok, wrong format or we just don't have ground truth data.
        ground_truth = []

    # list all frames. first, try MILTrack's format, where the initial and
    # final frame numbers are stored in a text file. if it doesn't work,
    # try to load all png/jpg files in the folder.

    text_files = glob.glob(os.path.join(video_path, "*_frames.txt"))
    if text_files:
        first_file_path = os.path.join(video_path, text_files[0])
        #f = open(first_file_path, "r")
        #frames = textscan(f, '%f,%f')
        frames = pylab.loadtxt(first_file_path, delimiter=",", dtype=int)
        #f.close()

        # see if they are in the 'imgs' subfolder or not
        test1_path_to_img = os.path.join(video_path,
                                         "imgs/img%05i.png" % frames[0])
        test2_path_to_img = os.path.join(video_path, "img%05i.png" % frames[0])
        if os.path.exists(test1_path_to_img):
            video_path = os.path.join(video_path, "imgs/")
        elif os.path.exists(test2_path_to_img):
            video_path = video_path  # no need for change
        else:
            raise Exception("Failed to find the png images")

        # list the files
        img_files = [
            "img%05i.png" % i for i in range(frames[0], frames[1] + 1)
        ]
        #img_files = num2str((frames{1} : frames{2})', 'img%05i.png')
        #img_files = cellstr(img_files);
    else:
        # no text file, just list all images
        img_files = glob.glob(os.path.join(video_path, "*.png"))
        if len(img_files) == 0:
            img_files = glob.glob(os.path.join(video_path, "*.jpg"))

        assert len(img_files), "Failed to find png or jpg images"

        img_files.sort()

    # if the target is too large, use a lower resolution
    # no need for so much detail
    if pylab.sqrt(pylab.prod(target_sz)) >= 100:
        pos = pylab.floor(pos / 2)
        target_sz = pylab.floor(target_sz / 2)
        resize_image = True
    else:
        resize_image = False

    ret = [img_files, pos, target_sz, resize_image, ground_truth, video_path]
    return ret