Commit 1af4911f authored by root's avatar root
Browse files

camera binning

parent 2c006fdf
{
"cells": [],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 2
}
This diff is collapsed.
{
"cells": [],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 2
}
{
"cells": [],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 2
}
{
"cells": [],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 2
}
......@@ -47,4 +47,16 @@ def make_statistic(xs ,ys, error_x):
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
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')
def extract(measurements, list_of_ids):
m = measurements
for i in list_of_ids:
try:
m = np.array([measure[i] for measure in m])
except:
print ("possible ids are: ",[item[0] for item in m[0].items()])
assert (False)
return m
\ No newline at end of file
......@@ -126,7 +126,16 @@ def get_config(devices):
print (device_name,' config time: ',time.time() - t)
return config
def measure(devices, devices2measure = 'all'):
def meas(dev):
dn = type(dev).__name__
if hasattr(dev, 'measure'):
import time
tt = time.time()
d = dev.measure()
print (dn,' measure time: ',time.time() - tt)
return dn, d
def measure(devices, devices2measure = 'all', parallel = True):
time = str(datetime.datetime.now()).replace(':','-').replace(' ','_')
data = {'time': time}
......@@ -136,7 +145,16 @@ def measure(devices, devices2measure = 'all'):
if devices2measure == 'all':
devices2measure = devices
if parallel:
from joblib import Parallel, delayed
res = Parallel(n_jobs= 4, backend="threading")(delayed(meas)(device) for device in devices2measure)
for i in range(len(res)):
data['measure'][res[i][0]]= res[i][1]
return data
for device in devices2measure:
device_name = type(device).__name__
if hasattr(device, 'measure'):
......
......@@ -121,7 +121,7 @@ def movetoL(pos, direction):
def init():
cmd("SCLF0,500")#set close-loop frequency!!
cmd("SCLF1,500")
cmd("SCLF1,200")
#cmd("SCLS0,100000")
......
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 25 17:33:30 2017
@author: nicks
"""
from instruments.srs import SRSDG645
import quantities as pq
'''
config file:
jet_triggered: boolean, true if jet opens on fire
mode: 'one shot' or 'continuous'
rate: float, maximal possible rate (single shot) or rate of trigger (continuous)
t_sleep: time that the program sleeps until measurement finished
measurement file (n.a)
'''
class CameraDelay:
def __init__(self, config):
self.ddg = SRSDG645.open_tcpip('172.21.11.124',5025)
self.ddg.trigger_source = 3
self.jet = self.ddg.Output(self.ddg,3)
self.set_config(config)
def get_config(self):
config = {}
config['mode'] = self.getMode()
config['jet_triggered'] = self.getJet()
config['rate'] = self.getRate()
config['t_sleep'] = self.t_sleep
return config
def set_config(self, config):
self.setMode(config['mode'])
self.setJet(config['jet_triggered'])
self.setRate(config['rate'])
self.t_sleep = config['t_sleep']
def setMode(self, mode):
if mode == 'single shot':
self.ddg.trigger_source = 3
return
if mode == 'continuous':
self.ddg.trigger_source = 1
return
print ('mode: '+mode+' unknown')
raise
def getMode(self):
mode = {3: 'single shot', 1: 'continuous'}
return mode[self.ddg.trigger_source]
def setRate(self, rate):
self.ddg.holdoff = pq.sec*1/rate - pq.sec*1e-3
def getRate(self):
return 1/float(self.ddg.holdoff)
def singleMode(self):
self.ddg.trigger_source = 3
def setJet(self, On):
if On:
self.jet.level_amplitude = pq.volt*5
else:
self.jet.level_amplitude = pq.volt*0.51
def getJet(self):
if self.jet.level_amplitude == pq.volt*5:
return True
else:
return False
def measure(self):
import datetime
import time
from threading import Thread
def trigger():
time.sleep(self.t_sleep)
self.ddg.trigger()
t1 = Thread(target = trigger)
t1.start()
time = str(datetime.datetime.now()).replace(':','-').replace(' ','_')
measurement = {'time': time}
return measurement
import numpy as np
def binArray(data, axis, binstep, binsize, func=np.sum):
data = np.array(data)
dims = np.array(data.shape)
argdims = np.arange(data.ndim)
argdims[0], argdims[axis]= argdims[axis], argdims[0]
data = data.transpose(argdims)
data = [func(np.take(data,np.arange(int(i*binstep),int(i*binstep+binsize)),0),0) for i in np.arange(dims[axis]//binstep)]
data = np.array(data).transpose(argdims)
return data
\ No newline at end of file
......@@ -35,6 +35,7 @@ class FaradayCup:
return config
def measure(self):
sig_time, sig_uvolt = self.drs.readChannel(self.channel)
import datetime
time = datetime.datetime.now()
......
......@@ -10,7 +10,7 @@ import pypylon
import matplotlib.pyplot as plt
import Devices.InterferometerTools.routines as r
from Devices.CameraTools import binArray
# camera setup
......@@ -76,11 +76,16 @@ class Interferometer:
self.cam.properties['PixelFormat'] = 'Mono'+str(config['BitsOfImage'])
self.cam.properties['ExposureTimeAbs']=config['ExposureTimeAbs']
self.cam.properties['TriggerMode']=mode[config['TriggerMode']]
self.n_binning = config['binning']
self.xmin, self.xmax, self.zmin, self.zmax = (config['xmin'], config['xmax'],
config['zmin'], config['zmax'])
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']
......@@ -95,6 +100,8 @@ class Interferometer:
config['ExposureTimeAbs'] = self.cam.properties['ExposureTimeAbs']
config['TriggerMode'] = modei[self.cam.properties['TriggerMode']]
config['BitsOfImage'] = int(self.cam.properties['PixelFormat'][4:])
config['binning'] = self.n_binning
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
......@@ -106,7 +113,6 @@ class Interferometer:
config['shift'] = self.shift
config['live_preview'] = self.live_preview
return config
def measure(self):
......@@ -181,9 +187,15 @@ class Interferometer:
if self.plot_server_tomo == None:
self.plot_server_tomo = Plot2DServer({'title':'Tomography live', 'xlabel':'z [mm]', 'ylabel': 'x [mm]','image': True})
self.plot_server_tomo.update(np.flipud(measurement['reconstruction'][0, :,:]),extent=np.array([self.zmin, self.zmax, self.zmin, self.zmax]))
print(measurement['reconstruction'].shape[2]/2)
plt.plot(measurement['reconstruction'][0, measurement['reconstruction'].shape[1]//2,:])
im1 = binArray(measurement['reconstruction'][0, :,:], 0, self.n_binning, self.n_binning, np.sum)
im1 = binArray(im1, 1, self.n_binning, self.n_binning, np.sum)
self.plot_server_tomo.update(im1,extent=np.array([self.zmin, self.zmax, self.zmin, self.zmax]))
plt.figure()
[plt.plot(measurement['reconstruction'][0, measurement['reconstruction'].shape[1]//2 + int(y/ self.psize),:]) for y in np.linspace(0,4,8)]
plt.show()
......@@ -218,12 +230,18 @@ class Interferometer:
shape = measurement['im1'].shape
im1 = binArray(im1, 0, self.n_binning, self.n_binning, np.sum)
im1 = binArray(im1, 1, self.n_binning, self.n_binning, np.sum)
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'])
#self.plot_server_ph.update(np.flipud(alpha), extent=[zmin, zmax, xmin, xmax])
alpha = self.Alpha(measurement['im1'],measurement['im2'])
alpha = binArray(alpha, 0, self.n_binning, self.n_binning, np.sum)
alpha = binArray(alpha, 1, self.n_binning, self.n_binning, np.sum)
self.plot_server_ph.update(np.flipud(alpha), extent=[zmin, zmax, xmin, xmax])
def turn_off(self):
self.cam.close()
......@@ -260,8 +278,8 @@ class Interferometer:
self.cam = cam
def set_frame(self, xmin, xmax, zmin, zmax):
self.x1p=int((xmax + self.x0)/self.psize)
self.x2p=int((xmin + self.x0)/self.psize)
self.x2p=int((xmax + self.x0)/self.psize)
self.x1p=int((xmin + self.x0)/self.psize)
self.z1p=int((zmin + self.z0)/self.psize)
self.z2p=int((zmax + self.z0)/self.psize)
......@@ -276,6 +294,7 @@ class Interferometer:
Ds2=ndimage.filters.gaussian_filter(np.array(D2,dtype=float), [sigmax, sigmay], mode='nearest', truncate=2)
#calculate phase
alpha=-r.unwrap(Ds1[self.x1p:self.x2p,:],Ds2[self.x1p:self.x2p,:])[:,self.z1p:self.z2p]
return alpha
......@@ -351,7 +370,10 @@ def update_tomography(self, images_angles, angles_rad):
print ('about to update')
self.plot_server_tomo.update(np.flipud(res[0, :,:]),extent=np.array([self.zmin, self.zmax, self.zmin, self.zmax]))
im1 = binArray(res[0, :,:], 0, self.n_binning, self.n_binning, np.sum)
im1 = binArray(im1, 1, self.n_binning, self.n_binning, np.sum)
self.plot_server_tomo.update(im1,extent=np.array([self.zmin, self.zmax, self.zmin, self.zmax]))
print ('plot updated')
......
File mode changed from 100644 to 100755
......@@ -32,8 +32,8 @@ def calculate_phase(images_angles, Ly,center = 230, y_calib=200, slices=None, pl
alpha = correct_phase_jumps(alpha) #correct for phases larger than 2pi
#phase_e = lambda shiftt: np.mean(phase(alpha, alpha, shift=int(shiftt))[:,-y_calib:])**2
#from scipy import ndimage
#alpha = ndimage.filters.gaussian_filter(alpha,[0,5], mode="nearest", truncate=2)
from scipy import ndimage
alpha = ndimage.filters.gaussian_filter(alpha,[0,15], mode="nearest", truncate=2)
#shiftarr = np.linspace(shift - 100, shift + 100, 201)
#arg = np.argmin([phase_e(sh) for sh in shiftarr])
......@@ -66,7 +66,7 @@ def calculate_phase(images_angles, Ly,center = 230, y_calib=200, slices=None, pl
phase_l = phase_l[:,y_calib:-y_calib]
if idx == len(images_angles) -1 and plot_images:
if idx == 0 and plot_images:
plt.figure()
plt.title('ta')
plt.plot(phase_l[0,:])
......@@ -113,8 +113,9 @@ def reconstruct(images_angles, angles, Ly,slices = [1100], shift = 217, output =
#rot_center = tomopy.find_center(proj, angles, init = int(proj.shape[2]/2), ind=0, tol=0.5)
#print ('Center of rotation: ', rot_center, int(proj.shape[2]/2))
#np.save("Data/Interferometer/data.npy", {'projections': proj, 'angles': angles})
#print ('saved')
start = time.time()
recon = tomopy.recon(proj, angles, center=int(proj.shape[2]/2), algorithm='mlem', ncore = 8)
......
......@@ -50,11 +50,16 @@ class Laser:
def set_lin_comp(self, pos):
caput('F10HU-LMOT705:MOT.VAL', pos)
import time
time.sleep(2)
def get_lin_comp(self):
return caget('F10HU-LMOT705:MOT.VAL')
def measure(self):
import time
time.sleep(0.05)
import datetime
time = datetime.datetime.now()
sig_time, sig_uvolt = self.drs.readChannel(self.channel)
......
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 14 10:46:54 2016
@author: hermann_b
"""
import numpy as np
import pypylon
......@@ -11,6 +5,8 @@ import matplotlib.pyplot as plt
import Devices.InterferometerTools.routines as r
from Devices.CameraTools import binArray
# camera setup
......@@ -29,7 +25,6 @@ TriggerMode: On/Off
measurement file:
time: time (datetime object)
im1: first image
im2: second image
'''
mode = {False: 'Off', True: 'On'}
......@@ -54,6 +49,8 @@ class PlasmaCamHorizontal:
self.cam.properties['TriggerMode']=mode[config['TriggerMode']]
self.y0 = config['y0']
self.z0 = config['z0']
self.n_binning = config['binning']
self.calibrated = config['calibrated']
def get_config(self):
config = {}
......@@ -61,6 +58,8 @@ class PlasmaCamHorizontal:
config['TriggerMode'] = modei[self.cam.properties['TriggerMode']]
config['y0'] = self.y0
config['z0'] = self.z0
config['binning'] = self.n_binning
config['calibrated'] = self.calibrated
return config
def measure(self):
......@@ -69,11 +68,17 @@ class PlasmaCamHorizontal:
D=[]
if self.calibrated:
for img in self.cam.grab_images(2):
D.append(np.fliplr(img))
measurement = {'time': time,'im': D[0], 'im_c': D[1]}
return measurement
for img in self.cam.grab_images(1):
D.append(np.fliplr(img))
measurement = {'time': time,'im1': D[0]}
measurement = {'time': time,'im': D[0]}
return measurement
def plot_measure(self, measurement, config = None):
......@@ -84,9 +89,18 @@ class PlasmaCamHorizontal:
if self.plot_server_im == None:
self.plot_server_im = Plot2DServer({'title':'PlasmaCamHorizontal', 'xlabel':'z [mm]', 'ylabel': 'y [mm]', 'image': True})
im1 = measurement['im1']
im1 = measurement['im']
try:
im_c = measurement['im_c']
im1 = im1 - im_c
except:
print ('not calibrated')
shape = im1.shape
shape = measurement['im1'].shape
im1 = binArray(im1, 0, self.n_binning, self.n_binning, np.sum)
im1 = binArray(im1, 1, self.n_binning, self.n_binning, np.sum)
self.plot_server_im.update(np.flipud(im1),extent=self.psize*np.array([0.,shape[1], 0., shape[0]]) - np.array([self.z0, self.z0, self.y0, self.y0]))
......
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