Commit a2fb5eb6 authored by Nick Sauerwein's avatar Nick Sauerwein
Browse files

AnalysisTools added

parent 2abfc98f
{
"cells": [],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 2
}
from uncertainties import unumpy, ufloat
import matplotlib.pyplot as plt
import numpy as np
def make_statistic(xs ,ys, error_x):
from uncertainties import unumpy
arg = np.argsort(xs)
xs = xs[arg]
ys = ys[arg]
i = 0
x_mean = []
x_error = []
y_mean = []
y_error = []
n = []
ys_act = []
xs_act = []
x_act = 0
while i < len(xs):
x_act = (x_act * len(xs_act)+ xs[i])/(len(xs_act) + 1)
ys_act += [ys[i]]
xs_act += [xs[i]]
if i < len(xs) -1 and abs(xs[i+1] - x_act) < error_x:
i = i+1
else:
x_mean += [np.mean(xs_act)]
x_error += [np.std(xs_act, ddof = 1)/np.sqrt(len(xs_act))]
y_mean += [np.mean(ys_act)]
y_error += [np.std(ys_act, ddof = 1)/np.sqrt(len(xs_act))]
n += [len(xs_act)]
x_act = 0
ys_act = []
xs_act = []
i = i+1
return unumpy.uarray(x_mean, x_error), unumpy.uarray(y_mean, y_error), n
def errorplot(ux, uy):
plt.errorbar(unumpy.nominal_values(ux), unumpy.nominal_values(uy), xerr = unumpy.std_devs(ux),yerr = unumpy.std_devs(uy), fmt= '--o', elinewidth = 10, ecolor = 'y')
\ No newline at end of file
......@@ -7,8 +7,12 @@ import Globals as g
import matplotlib.pyplot as plt
def get_item_in_dict(dic, address):
for step in address:
dic = dic[step]
return dic
def print_dict(dictionary, ident = '', braces=1, plot = True):
""" Recursively prints nested dictionaries."""
......@@ -220,6 +224,39 @@ class IO:
datas += [data]
n += 1
return datas
def select(self, keys = [{}], kind = 'measure'):
#example of key: {'address': ['where', 'to', 'find', 'data'], 'value': [val, 'b', error]}
# 'b': bigger, 's': smaller, 'e': equals, in case of 'e' the error variable should be defined.
results = []
for filename in glob.iglob(self.path+kind+'*.npy'):
data = np.load(filename).item()
take = True
for key in keys:
try:
if key['value'][1] == 'b':
if key['value'][0] >= get_item_in_dict(data, key['address']):
take = False
print ('test')
if key['value'][1] == 's':
if key['value'][0] <= get_item_in_dict(data, key['address']):
take = False
if key['value'][1] == 'e':
if key['value'][0] - key['value'][2] <= get_item_in_dict(data, key['address']) or key['value'][0] + key['value'][2] >= get_item_in_dict(data, key['address']):
take = False
except:
take = False
if take:
results += [data]
return results
......
......@@ -63,9 +63,16 @@ def getposL():
def maaR(angle):
rev=-1
cmd("MAA0,"+str(int(angle*1000000))+","+str(rev)+",60000")
while cmd("GS0",output=True)[-2]!=str(3):
#while cmd("GS0",output=True)[-2]!=str(3):
#print(cmd("GS0",output=True)[-2])
time.sleep(0.3)
#time.sleep(0.1)
angle_ac = getposR()
#print (angle_ac)
while abs(angle_ac-angle)>0.01:
time.sleep(0.2)
angle_ac = getposR()
#print (angle_ac)
def mpaL(pos):
cmd("MPA1,"+str(int(pos*1000000))+",60000")
......
......@@ -33,6 +33,10 @@ z0: offset of z to fit blade edge
x0: offset of x to fit blade edge
ExposureTimeAbs: exposure time in us
TriggerMode: On/Off
Tomography: boolean
take_data: boolean
num_dir: Number of directions (ignored if Tomography = False)
num_av: Number of images at one angle (ignored if Tomography = False)
measurement file:
time: time (datetime object)
......@@ -43,7 +47,7 @@ im2: second image
class Interferometer:
#mendatory functions
def __init__(self, config):
def __init__(self, config, blade = None, delay = None):
#fixed variables
self.X_nozzle=1300
......@@ -56,10 +60,15 @@ class Interferometer:
self.set_config(config)
self.blade = blade
self.delay = delay
self.plot_server_im = None
self.plot_server_ph = None
def set_config(self,config):
self.take_data = config['take_data']
self.cam.properties['PixelFormat'] = 'Mono12'
self.cam.properties['ExposureTimeAbs']=config['ExposureTimeAbs']
self.cam.properties['TriggerMode']=config['TriggerMode']
self.xmin, self.xmax, self.zmin, self.zmax = (config['xmin'], config['xmax'],
......@@ -67,6 +76,9 @@ class Interferometer:
self.x0, self.z0 = (config['x0'], config['z0'])
self.set_frame(config['xmin'], config['xmax'],
config['zmin'], config['zmax'])
self.Tomography = config['Tomography']
self.num_dir = config['num_dir']
self.num_av = config['num_av']
def get_config(self):
config = {}
......@@ -74,21 +86,62 @@ class Interferometer:
config['TriggerMode'] = self.cam.properties['TriggerMode']
config['xmin'], config['xmax'],config['zmin'], config['zmax']= (self.xmin, self.xmax, self.zmin, self.zmax)
config['x0'], config['z0'] = (self.x0, self.z0)
config['Tomography'] = self.Tomography
config['num_dir'] = self.num_dir
config['num_av'] = self.num_av
config['take_data'] = self.take_data
return config
def measure(self):
import datetime
time = datetime.datetime.now()
D=[]
for img in self.cam.grab_images(2):
D.append(np.fliplr(img))
measurement = {'time': time,'im1': D[0], 'im2': D[1]}
return measurement
if self.Tomography == False or self.blade == None or self.delay == None:
D=[]
for img in self.cam.grab_images(2):
D.append(np.fliplr(img))
measurement = {'time': time,'im1': D[0], 'im2': D[1]}
return measurement
else:
blade_config0 = self.blade.get_config()
if self.take_data:
self.tomography_take_data(blade_config0)
self.run_tomography()
print ('bringing stage to original position')
self.blade.set_config(blade_config0)
print ('success')
measurement = {'time': time}
return measurement
def plot_measure(self, measurement, config = None):
if self.Tomography:
from IPython.display import Image, display
display(Image(filename='Devices/InterferometerTools/X_gpu.png'))
return 0
if config != None:
zmin = config['zmin']
zmax = config['zmax']
......@@ -118,7 +171,7 @@ class Interferometer:
self.plot_server_im.update(np.flipud(im1),extent=self.psize*np.array([0.,shape[1], 0., shape[0]])-np.array([z0, z0, x0,x0]))
alpha= self.Alpha(measurement['im1'],measurement['im2'])
alpha = self.Alpha(measurement['im1'],measurement['im2'])
self.plot_server_ph.update(np.flipud(alpha), extent=[zmin, zmax, xmin, xmax])
......@@ -152,6 +205,7 @@ class Interferometer:
cam.properties['AcquisitionFrameRateEnable']=False
cam.properties['AcquisitionFrameRateAbs']=100
cam.properties['GainRaw']=150
self.cam = cam
......@@ -175,4 +229,74 @@ class Interferometer:
alpha=-r.unwrap(Ds1[self.x1p:self.x2p,:],Ds2[self.x1p:self.x2p,:])[:,self.z1p:self.z2p]
return alpha
def tomography_take_data(self, blade_config0):
images_angles = []
blade_config1 = blade_config0.copy()
import time
for angle in -np.linspace(0,90,self.num_dir):
print ('Angle ',angle)
blade_config1['pos_R'] = blade_config0['pos_R'] + angle
print ('start movement')
self.blade.set_config(blade_config1)
print ('angle set')
Ds = []
for i in range(self.num_av):
time.sleep(0.5)
print ('Nummer ',i )
self.delay.measure()
D = []
for img in self.cam.grab_images(2):
D.append(np.fliplr(img))
Ds.append(D)
images_angle = np.mean(Ds, axis = 0).astype('uint16')
images_angles.append(images_angle)
np.save("Devices/InterferometerTools/images_angles.npy", images_angles)
def run_tomography(self):
from paramiko import SSHClient
from scp import SCPClient
import os
print ('send data')
client = SSHClient()
client.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
client.connect('kraftwerk.psi.ch', username='interferometerrunner', password='123_interferometer')
sftp = client.open_sftp()
sftp.put("/home/data/lwfaserver/Devices/InterferometerTools/images_angles.npy", "/home/interferometerrunner/Tomography/data/images_angles.npy")
print ('data transfered')
channel = client.invoke_shell()
stdin = channel.makefile('wb')
stdout = channel.makefile('rb')
stdin.write('''
load_cuda-8.0
load_arrayfire
cd /home/interferometerrunner/Tomography/
python tomography_steps.py
exit
''')
print ("Output : \n",stdout.read().decode("utf-8"))
print ('Copy result')
sftp.get("/home/interferometerrunner/Tomography/data/X_gpu.png", "/home/data/lwfaserver/Devices/InterferometerTools/X_gpu.png")
......@@ -78,12 +78,14 @@ class ParabolicMirror:
if output:
print ('FWHMxs: ',FWHMxs)
print ('maxints: ',maxints)
print ('mean(maxits): ',np.mean(maxints))
res = np.sqrt(np.array(FWHMxs)**2 + np.array(FWHMys)**2)/np.sqrt(2)*4096/np.array(maxints)*intmult
mean, error = np.mean(res), np.std(res, ddof = -1)
global reduce_int
if np.mean(maxints) > 4e3:
redurce_int = True
reduce_int = True
print ('will be attenuated')
if output:
print ('mean: ',mean,'error: ', error)
......@@ -138,7 +140,7 @@ class ParabolicMirror:
def after_it(res):
print ('###################')
print ('step done')
global reduce_int
global reduce_int, intmult
if reduce_int:
config_laser = laser.get_config()
config_laser['attenuation'] = config_laser['attenuation']/1.2
......
......@@ -348,8 +348,6 @@ def main(devices, io, parallel = False):
elif output_check.value:
dm.plot_measure(measurement, devices2measure,plot_config, 0.01)
plt.pause(0.001)
plt.draw_all(force = True)
print ('maximal possible rate: ',np.round(1/(time.time() -t),1))
if (1/rate_text.value - (time.time() -t) < 0):
......
This diff is collapsed.
......@@ -103,8 +103,8 @@ def plot_server_2d(connecim = None,connecext = None, config = {'xlabel' : '','yl
tools = 'pan,wheel_zoom,save,crosshair,resize,reset')
from bokeh.models.tools import BoxZoomTool
p.add_tools(BoxZoomTool(match_aspect = True))
p.plot_height = 400
p.plot_width = 400
p.plot_height = 480
p.plot_width = 480
if config['image']:
from bokeh.palettes import Greys256
palette = Greys256
......@@ -166,7 +166,7 @@ class Plot2DServer:
self.show()
def show(self):
open_window(self.url, width = 500)
open_window(self.url, width = 530)
def update(self,image ,extent):
self.connecext_ch.send(extent)
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment