Commit c81fde478cab41c8449fd9423b8cb51ac9906e9c

Authored by bmarechal
1 parent 7fa40df51d
Exists in master

replace 4 spaces by tabs

Showing 2 changed files with 152 additions and 152 deletions Inline Diff

from scipy.optimize import curve_fit 1 1 from scipy.optimize import curve_fit
import csv, numpy, glob 2 2 import csv, numpy, glob
from scipy.special import erf 3 3 from scipy.special import erf
import matplotlib.pyplot as plt 4 4 import matplotlib.pyplot as plt
5 5
'''power function to optimize''' 6 6 '''power function to optimize'''
def P(x, Po, Pmax, xo, w): 7 7 def P(x, Po, Pmax, xo, w):
return Po+0.5*Pmax*(1.-erf(2.**0.5*(x-xo)/w)) 8 8 return Po+0.5*Pmax*(1.-erf(2.**0.5*(x-xo)/w))
9 9
10 10
'''load and fit beam section''' 11 11 '''load and fit beam section'''
files = glob.glob('*.dat') 12 12 files = glob.glob('*.dat')
files.sort() 13 13 files.sort()
data_waist = [] 14 14 data_waist = []
plt.close() 15 15 plt.close()
fig, p = plt.subplots(2, 1) 16 16 fig, p = plt.subplots(2, 1)
for f in files: 17 17 for f in files:
with open(f, 'r') as dest_f: 18 18 with open(f, 'r') as dest_f:
raw = csv.reader(dest_f, delimiter = '\t', quotechar = '"') 19 19 raw = csv.reader(dest_f, delimiter = '\t', quotechar = '"')
data = [value for value in raw] 20 20 data = [value for value in raw]
data = numpy.asarray(data, dtype = float) 21 21 data = numpy.asarray(data, dtype = float)
xmes = data[:,0] 22 22 xmes = data[:,0]
Pmes = data[:,1] 23 23 Pmes = data[:,1]
24 24
'''optimization with non-linear least squares method''' 25 25 '''optimization with non-linear least squares method'''
Ppopt, Pcov = curve_fit(P, xmes, Pmes) 26 26 Ppopt, Pcov = curve_fit(P, xmes, Pmes)
data_waist.append([int(f[-7:-4]), abs(Ppopt[3])]) 27 27 data_waist.append([int(f[-7:-4]), abs(Ppopt[3])])
28 28
'''plot''' 29 29 '''plot'''
p[0].plot(xmes, Pmes, 'o') 30 30 p[0].plot(xmes, Pmes, 'o')
p[0].plot(numpy.linspace(xmes[0], xmes[-1], 100), P(numpy.linspace(xmes[0], xmes[-1], 100), *Ppopt)) 31 31 p[0].plot(numpy.linspace(xmes[0], xmes[-1], 100), P(numpy.linspace(xmes[0], xmes[-1], 100), *Ppopt))
32 32
p[0].grid() 33 33 p[0].grid()
34 34
'''return waist(z) table''' 35 35 '''return waist(z) table'''
data_waist = numpy.asarray(data_waist, dtype = float) 36 36 data_waist = numpy.asarray(data_waist, dtype = float)
print(data_waist) 37 37 print(data_waist)
38 38
'''waist function to optimize''' 39 39 '''waist function to optimize'''
def W(z, w0, z0): 40 40 def W(z, w0, z0):
return w0*(1.+((z-z0)*1542e-6/(numpy.pi*w0**2))**2)**0.5 41 41 return w0*(1.+((z-z0)*1542e-6/(numpy.pi*w0**2))**2)**0.5
42 42
popt, cov = curve_fit(W, data_waist[:,0], data_waist[:,1]) 43 43 popt, cov = curve_fit(W, data_waist[:,0], data_waist[:,1])
print(popt[0], popt[1]) 44 44 print(popt[0], popt[1])
45 45
p[1].plot(data_waist[:,0], data_waist[:,1], 'bo') 46 46 p[1].plot(data_waist[:,0], data_waist[:,1], 'bo')
p[1].plot(data_waist[:,0], -data_waist[:,1], 'bo') 47 47 p[1].plot(data_waist[:,0], -data_waist[:,1], 'bo')
p[1].plot(numpy.linspace(data_waist[0,0], data_waist[-1,0], 100), W(numpy.linspace(data_waist[0,0], data_waist[-1,0], 100), *popt), 'r') 48 48 p[1].plot(numpy.linspace(data_waist[0,0], data_waist[-1,0], 100), W(numpy.linspace(data_waist[0,0], data_waist[-1,0], 100), *popt), 'r')
p[1].plot(numpy.linspace(data_waist[0,0], data_waist[-1,0], 100), -W(numpy.linspace(data_waist[0,0], data_waist[-1,0], 100), *popt), 'r') 49 49 p[1].plot(numpy.linspace(data_waist[0,0], data_waist[-1,0], 100), -W(numpy.linspace(data_waist[0,0], data_waist[-1,0], 100), *popt), 'r')
p[1].grid() 50 50 p[1].grid()
51 51
plt.show() 52 52 plt.show()
53 53
#!/usr/bin/env python 1 1 #!/usr/bin/env python
2 2
import argparse, time, os 3 3 import argparse, time, os
import matplotlib.pyplot as plt 4 4 import matplotlib.pyplot as plt
5 5
#============================================================================== 6 6 #==============================================================================
7 7
# Path 8 8 # Path
PATH = os.getcwd() 9 9 PATH = os.getcwd()
# File footer 10 10 # File footer
OFILENAME = '130' 11 11 OFILENAME = '130'
12 12
#============================================================================== 13 13 #==============================================================================
14 14
def parse(): 15 15 def parse():
""" 16 16 """
Specific parsing procedure for transfering data from Thorlabs PM100D. 17 17 Specific parsing procedure for transfering data from Thorlabs PM100D.
:returns: populated namespace (parser) 18 18 :returns: populated namespace (parser)
""" 19 19 """
parser = argparse.ArgumentParser(description = 'Acquire data from Thorlabs PM100D', 20 20 parser = argparse.ArgumentParser(description = 'Acquire data from Thorlabs PM100D',
epilog = 'Example: \'./pm100d.py -st 10 -o toto\' logs PM100D every 10 seconds to output file YYYYMMDD-HHMMSS-toto.dat') 21 21 epilog = 'Example: \'./pm100d.py -st 10 -o toto\' logs PM100D every 10 seconds to output file YYYYMMDD-HHMMSS-toto.dat')
22 22
parser.add_argument('-p', 23 23 parser.add_argument('-p',
action='store', 24 24 action='store',
dest='path', 25 25 dest='path',
default=PATH, 26 26 default=PATH,
help='Absolute path (default '+PATH+')') 27 27 help='Absolute path (default '+PATH+')')
28 28
parser.add_argument('-o', 29 29 parser.add_argument('-o',
action='store', 30 30 action='store',
dest='ofile', 31 31 dest='ofile',
default=OFILENAME, 32 32 default=OFILENAME,
help='Output data filename (default '+OFILENAME+')') 33 33 help='Output data filename (default '+OFILENAME+')')
34 34
args = parser.parse_args() 35 35 args = parser.parse_args()
return args 36 36 return args
37 37
#============================================================================== 38 38 #==============================================================================
39 39
class usbtmc: 40 40 class usbtmc:
def __init__(self, device): 41 41 def __init__(self, device):
self.device = device 42 42 self.device = device
self.FILE = os.open(device, os.O_RDWR) 43 43 self.FILE = os.open(device, os.O_RDWR)
44 44
def write(self, command): 45 45 def write(self, command):
os.write(self.FILE, command); 46 46 os.write(self.FILE, command);
47 47
def read(self, length = 4000): 48 48 def read(self, length = 4000):
return os.read(self.FILE, length) 49 49 return os.read(self.FILE, length)
50 50
def getName(self): 51 51 def getName(self):
self.write("*IDN?") 52 52 self.write("*IDN?")
return self.read(300) 53 53 return self.read(300)
54 54
def sendReset(self): 55 55 def sendReset(self):
self.write("*RST") 56 56 self.write("*RST")
57 57
#============================================================================== 58 58 #==============================================================================
59 59
class instrument: 60 60 class instrument:
"""Class to control a SCPI compatible instrument""" 61 61 """Class to control a SCPI compatible instrument"""
def __init__(self, device): 62 62 def __init__(self, device):
print 'Connecting to device %s...' %device 63 63 print 'Connecting to device %s...' %device
self.meas = usbtmc(device) 64 64 self.meas = usbtmc(device)
self.name = self.meas.getName() 65 65 self.name = self.meas.getName()
print self.name 66 66 print self.name
print ' --> Ok' 67 67 print ' --> Ok'
68 68
def write(self, command): 69 69 def write(self, command):
"""Send an arbitrary command directly to the scope""" 70 70 """Send an arbitrary command directly to the scope"""
self.meas.write(command) 71 71 self.meas.write(command)
72 72
def read(self, command): 73 73 def read(self, command):
"""Read an arbitrary amount of data directly from the scope""" 74 74 """Read an arbitrary amount of data directly from the scope"""
return self.meas.read(command) 75 75 return self.meas.read(command)
76 76
def reset(self): 77 77 def reset(self):
"""Reset the instrument""" 78 78 """Reset the instrument"""
self.meas.sendReset() 79 79 self.meas.sendReset()
80 80
def value(self): 81 81 def value(self):
self.write('MEAS?') 82 82 self.write('MEAS?')
return self.read(300) 83 83 return self.read(300)
84 84
#============================================================================== 85 85 #==============================================================================
86 86
def acqu_PM100D(instrument, path, ofile): 87 87 def acqu_PM100D(instrument, path, ofile):
88 88
t0 = time.time() 89 89 t0 = time.time()
filename = time.strftime("%Y%m%d-%H%M%S", time.gmtime(t0)) + '-' + ofile + '.dat' 90 90 filename = time.strftime("%Y%m%d-%H%M%S", time.gmtime(t0)) + '-' + ofile + '.dat'
print('Opening %s' %filename) 91 91 print('Opening %s' %filename)
data_file = open(filename, 'wr', 0) 92 92 data_file = open(filename, 'wr', 0)
dx = 0. 93 93 dx = 0.
94 94
xmes = [] 95 95 xmes = []
Pmes = [] 96 96 Pmes = []
plt.ion() 97 97 plt.ion()
fig = plt.figure() 98 98 fig = plt.figure()
ax1 = fig.add_subplot(111) 99 99 ax1 = fig.add_subplot(111)
line1, = ax1.plot(xmes, Pmes, 'o') 100 100 line1, = ax1.plot(xmes, Pmes, 'o')
101 101
# Infinite loop 102 102 # Infinite loop
while True: 103 103 while True:
try: 104 104 try:
keypressed = raw_input("Press Enter to continue...\n") 105 105 keypressed = raw_input("Press Enter to continue...\n")
106 106
if keypressed=='': 107 107 if keypressed=='':
# Power values 108 108 # Power values
sensors_values = instrument.value() 109 109 sensors_values = instrument.value()
sensors_values = sensors_values.replace('E', 'e') 110 110 sensors_values = sensors_values.replace('E', 'e')
string = "%f\t%s" % (dx , sensors_values) 111 111 string = "%f\t%s" % (dx , sensors_values)
data_file.write(string) # Write in a file 112 112 data_file.write(string) # Write in a file
print(string) 113 113 print(string)
114 114
xmes.append(dx) 115 115 xmes.append(dx)
Pmes.append(float(sensors_values)) 116 116 Pmes.append(float(sensors_values))
117 117
dx = dx + 0.05 118 118 dx = dx + 0.05
119 119
elif keypressed.isdigit(): 120 120 elif keypressed.isdigit():
print('Closing %s' %filename) 121 121 print('Closing %s' %filename)
data_file.close() 122 122 data_file.close()
t0 = time.time() 123 123 t0 = time.time()
filename = time.strftime("%Y%m%d-%H%M%S", time.gmtime(t0)) + '-' + keypressed + '.dat' 124 124 filename = time.strftime("%Y%m%d-%H%M%S", time.gmtime(t0)) + '-' + keypressed + '.dat'
print('Opening %s' %filename) 125 125 print('Opening %s' %filename)
data_file = open(filename, 'wr', 0) 126 126 data_file = open(filename, 'wr', 0)
dx = 0. 127 127 dx = 0.
128 128
xmes = [] 129 129 xmes = []
Pmes = [] 130 130 Pmes = []
line1, = ax1.plot(xmes, Pmes, 'o') 131 131 line1, = ax1.plot(xmes, Pmes, 'o')
132 132
else: 133 133 else:
raise KeyboardInterrupt 134 134 raise KeyboardInterrupt
135 135
136 136
line1.set_data(xmes, Pmes) 137 137 line1.set_data(xmes, Pmes)
ax1.relim() 138 138 ax1.relim()
ax1.autoscale_view() 139 139 ax1.autoscale_view()
fig.canvas.draw() 140 140 fig.canvas.draw()
141 141
except Exception as ex: 142 142 except Exception as ex:
print 'Exception during controler data reading: ' + str(ex) 143 143 print 'Exception during controler data reading: ' + str(ex)
144 144
except KeyboardInterrupt: 145 145 except KeyboardInterrupt:
print '\n --> Disconnected' 146 146 print '\n --> Disconnected'
data_file.close() 147 147 data_file.close()
148 148
# To stop the loop in a clean way 149 149 # To stop the loop in a clean way
break 150 150 break
151 151
#============================================================================== 152 152 #==============================================================================
153 153
def main(): 154 154 def main():
""" 155 155 """
Main script 156 156 Main script
""" 157 157 """
# Parse command line 158 158 # Parse command line
args = parse() 159 159 args = parse()
# path 160 160 # path
path = args.path 161 161 path = args.path
# Data output filename 162 162 # Data output filename
ofile = args.ofile 163 163 ofile = args.ofile
164 164
try: 165 165 try:
pm100 = instrument("/dev/usbtmc0") 166 166 pm100 = instrument("/dev/usbtmc0")
167 167
# acquisition with 2 sec. timeout 168 168 # acquisition with 2 sec. timeout
acqu_PM100D(pm100, path, ofile) 169 169 acqu_PM100D(pm100, path, ofile)
170 170
except Exception as ex: 171 171 except Exception as ex:
print 'Oups '+str(ex) 172 172 print 'Oups '+str(ex)
print 'Program ending\n' 173 173 print 'Program ending\n'
174 174
#============================================================================== 175 175 #==============================================================================
176 176
if __name__ == "__main__": 177 177 if __name__ == "__main__":
main() 178 178 main()
179 179