Skip to content
Snippets Groups Projects
Commit 11ec10ed authored by Benedikt Schmitz's avatar Benedikt Schmitz
Browse files

Added a detailled workflow for the application with manual threshold values.

Minor comments and clarifications have been added.

 Zum Commit vorgemerkte Änderungen:
	geändert:       pyRES GUI.ipynb
parent 847c6549
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
# pyRES GUI
To evaluate a Stack needs the following steps:
* [Step 1: Define Laser and Target](#step1)
* [Step 2: Define used films](#step2)
* [Step 3: Define Stack](#step3)
* [Step 4: Functional Part](#step4)
* [Step 5: Display/Plot Results](#step5)
%% Cell type:code id: tags:
``` python
# Importing packages needed
from ElossFile import ElossFile
import matplotlib.pyplot as plt
import numpy as np
from Target import Target
from Laser import Laser
from RCFtype import RCFtype
from RCFImage import RCFImage
from Scanner import Scanner
from tifffile import tifffile
from RCFStack import RCFStack
from ElossFile import ElossFile
import fitfunctions
import tqdm
# modules for GUI elements:
from ipywidgets import Button
from tkinter import Tk, filedialog
from IPython.display import clear_output, display
```
%% Cell type:code id: tags:
``` python
# definition of select files function:
def select_files(b):
clear_output()
root = Tk()
# Hide the main window.
root.withdraw()
# Raise the root to the top of all windows.
root.call('wm', 'attributes', '.', '-topmost', True)
# List of selected files will be set button's file attribute.
b.files = filedialog.askopenfilename(multiple=True)
print(b.files) # Print the list of files selected.
```
%% Cell type:markdown id: tags:
### Step 1: Define Laser and Target <a class="anchor" id="step1"></a>
%% Cell type:code id: tags:
``` python
target1 = Target(thickness=10, distance=40, name="Quellschuss",typ='Thin Foil', material='Au')
print(target1.name)
laser1 = Laser(energy=29.6, pulseduration=650, focusdia=3.5, wavelenght=1.053, name="PHELIX_LIGHT", angle=0, contrast=0)
print(laser1.name)
```
%% Cell type:markdown id: tags:
### Step 2: Define used layers <a class="anchor" id="step2"></a>
There are batch to batch fluctuations for the films. Therefore several calibrations have to be done and the proper calibration file has to selected.
The important question at this point is, which calibration function is used. Two are available:
True: $$ \Xi(D)_i^T=D\frac{a_i}{c_i + D} $$
False: $$ \Xi(D)_i^F=D\frac{a_i + b_i D}{c_i + D} $$
This is done below:
%% Cell type:code id: tags:
``` python
## Selecti
# Set boolean true if b is set 0 as defined above.
boolean_b0 = True
## HD calibrations given:
# H2 = RCFtype.load_Cal_from_pickle(RCFtype,file_path='./calibrations/calib-files/calibration_CAL-2019-1_HD_LOT-01091801_film7.pkl')
# H2 = RCFtype.load_Cal_from_pickle(RCFtype,file_path='./calibrations/calib-files/calibration_CAL-2019-1_HD_LOT-12151402_film3.pkl')
H2 = RCFtype.load_Cal_from_pickle(RCFtype,file_path='./calibrations/calib-files/calibration_CAL-2019-1_HD_LOT-11171501_film4_b0.pkl')
## EBT3 calibrations given:
E3 = RCFtype.load_Cal_from_pickle(RCFtype,file_path='./calibrations/calib-files/calibration_CAL-2019-1_EBT_LOT-05191502_film1_b0.pkl')
# E3 = RCFtype.load_Cal_from_pickle(RCFtype,file_path='./calibrations/calib-files/calibration_CAL-2019-1_EBT_LOT-03161503_film2.pkl')
# E3 = RCFtype.load_Cal_from_pickle(RCFtype,file_path='./calibrations/calib-files/calibration_CAL-2019-1_EBT_LOT-07291902_film6.pkl')
# E3 = RCFtype.load_Cal_from_pickle(RCFtype,file_path='./calibrations/calib-files/calibration_CAL-2019-1_EBT_LOT-09121802_film8.pkl')
## The calibration belongs to a specific scanner:
# The selected layers have to be passed to a virtual scanner object:
scanner1 = Scanner(numberOfRCFtypes=0, name="coolscan")
# add RCF Types
scanner1.append_rcftypes_list(H2)
scanner1.append_rcftypes_list(E3)
# # remove RCF Type if necessary
# scanner1.remove_rcftypes_list(E3)
# scanner1.append_rcftypes_list(E3)
```
%% Cell type:markdown id: tags:
### Step 3: Define Stack <a class="anchor" id="step3"></a>
A stack is constituted of several individual layers and its responsefunction given by the corresponding energylossfiles (short elo).
Note: This should be automatised with a GUI.
%% Cell type:code id: tags:
``` python
UseGUI = True
# if file dialogue should be used or not:
if UseGUI == True:
# Elossfile for the specific active layers
# define buttons
ElossPath = Button(description="File select")
ElossPath.on_click(select_files)
display(ElossPath)
# hardcoded filepath:
elif UseGUI == False:
ElossPath = ["LIGHTShot/quellschuss_03_H2.csv",
"LIGHTShot/quellschuss_05_H2.csv",
"LIGHTShot/quellschuss_07_H2.csv",
"LIGHTShot/quellschuss_09_H2.csv",
"LIGHTShot/quellschuss_11_H2.csv",
"LIGHTShot/quellschuss_13_H2.csv",
"LIGHTShot/quellschuss_15_H2.csv",
"LIGHTShot/quellschuss_17_E3.csv",
"LIGHTShot/quellschuss_19_E3.csv",
"LIGHTShot/quellschuss_21_E3.csv",
"LIGHTShot/quellschuss_23_E3.csv",
"LIGHTShot/quellschuss_25_E3.csv",
"LIGHTShot/quellschuss_27_E3.csv"]
# List of used RCF Types in the order of occurence
RCFLayerList=[H2,H2,H2,H2,H2,H2,H2,E3,E3,E3,E3,E3,E3]
```
%% Cell type:code id: tags:
``` python
if UseGUI:
print(str(len(ElossPath.files))+' Eloss files imported.' )
```
%% Cell type:code id: tags:
``` python
# RCF Image scan read in and virtual variable
# if file dialogue should be used or not:
if UseGUI == True:
# Elossfile for the specific active layers
# define buttons
pathToImage = Button(description="File select")
pathToImage.on_click(select_files)
display(pathToImage)
# hardcoded filepath:
elif UseGUI == False:
pathToImage = ["LIGHTShot/quellschuss01.tif",
"LIGHTShot/quellschuss02.tif",
"LIGHTShot/quellschuss03.tif",
"LIGHTShot/quellschuss04.tif",
"LIGHTShot/quellschuss05.tif",
"LIGHTShot/quellschuss06.tif",
"LIGHTShot/quellschuss07.tif",
"LIGHTShot/quellschuss08.tif",
"LIGHTShot/quellschuss09.tif",
"LIGHTShot/quellschuss10.tif",
"LIGHTShot/quellschuss11.tif",
"LIGHTShot/quellschuss12.tif",
"LIGHTShot/quellschuss13.tif"]
```
%% Cell type:code id: tags:
``` python
if UseGUI:
print(str(len(ElossPath.files))+' images imported.' )
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
#if UseGUI:
#pathToImage = pathToImage.files
#ElossPath = ElossPath.files
if len(pathToImage) is not len(ElossPath):
print('Number of Eloss Files does not match the number of active layers!')
else:
#Allocate empty rcf image list:
rcf_images = []
# if it matches, one of the length can be taken to loop over:
for i in tqdm.tqdm(range(len(pathToImage))):
##### import Eloss:
elo_namebase = "elo"
for index, path in enumerate(ElossPath):
Eloss = ElossFile(name=elo_namebase+str(index), filepath=ElossPath[i])
##### import image:
# read in the image:
image = tifffile.imread(pathToImage[i])
# extract the tags from each tiff file:
with tifffile.TiffFile(pathToImage[i]) as tif:
tif_tags = {}
for tag in tif.pages[0].tags.values():
name, value = tag.name, tag.value
tif_tags[name] = value
# combine to RCFImage object:
RCFImageI = RCFImage(filename = "Quellschuss01", filepath="LIGHTShot/tina114_image1.csv",
width=tif_tags['ImageWidth'], height= tif_tags['ImageLength'], colortype="RGB",
XResolution=tif_tags['XResolution'][0],YResolution=tif_tags['YResolution'][0],
ResolutionUnit=tif_tags['ResolutionUnit'].name,
ImageArray = image, OpticalDensity=None, ImageMask=None, stdabwBG=None,
RCFType=RCFLayerList[i], elossfile=Eloss, scanner=scanner1)
# Append to list
rcf_images.append(RCFImageI)
# convert list to a numpy array
rcf_images = np.array(rcf_images)
```
%% Cell type:code id: tags:
``` python
# Remove pinhole if it exists
# RCFImage1.remove_pinhole()
# RCFImage2.remove_pinhole()
# RCFImage3.remove_pinhole()
# RCFImage4.remove_pinhole()
# RCFImage5.remove_pinhole()
# RCFImage6.remove_pinhole()
# RCFImage7.remove_pinhole()
# RCFImage8.remove_pinhole()
# RCFImage9.remove_pinhole()
# RCFImage10.remove_pinhole()
# RCFImage11.remove_pinhole()
# RCFImage12.remove_pinhole()
# RCFImage13.remove_pinhole()
```
%% Cell type:markdown id: tags:
### Step 4: Functional Part of RCF Evaluation <a class="anchor" id="step4"></a>
Substep layers:
1. Define which segmentation type is needed for which layer.
2. Define an array of objects.
3. Calculate segmentation for each iteration.
4. Create RCFStack object.
5. Deconvolution
%% Cell type:code id: tags:
``` python
# Substep 1:
# Assumption a pinhole penetrates all layers and therefore a simple boolean can be used to
# swich the correction on and off.
Pinhole_boolean = False
# The select list is used
select_list = [0,0,0,0,0,0,0,1,1,1,1,1,1]
select_list = [0,0,0,0,0,0,0,0,0,0,0,0,0]
# set 0 if HSV segmentation
# set 1 if MeV threshold
```
#select_list = [0,0,0,0,0,0,0,0,0,0,0,0,0]
select_list = [0,0,0,0,2,2,2,0,0,0,0,0,0]
# set 0 if HSV segmentation is used
# set 1 if MeV segmentation is used
# set 2 if MeV threshold is set
# if 2 is used, the threshold values have to be set
# it needs to have as many entries as "2"s are in the select list.
threshold_list = [1000,900,600]
%% Cell type:code id: tags:
``` python
# Substep 2:
# Loop over the rcf_images array and segment
for RCFIm in tqdm.tqdm(rcf_images):
select = select_list.pop(0)
cleanImageArray = RCFIm.counts2OD()
if Pinhole_boolean:
RCFIm.remove_pinhole()
RCFIm.OD2MeV(cleanImageArray)
if select == 0:
RCFIm.segmentation(RCFIm.ImageArray)
elif select == 1:
RCFIm.getAutomaticMaskValuefromMeV(RCFIm.MeV_map)
elif select == 2:
# set a manual value for the MeV Threshold
# RCFImage1.setMaskValue(RCFImage1.MeV_map,6900)
RCFIm.setMaskValue(RCFIm.MeV_map,threshold_list.pop(0))
RCFIm.cutAtValue(RCFIm.MeV_map, RCFIm.ErrMeVpx )
RCFIm.removeBackground()
```
%% Cell type:code id: tags:
``` python
# Plot the contours of the binary masks
# "hori_plots" defines the number of plots in the horizontal dimension
# it has to be smaller than the amount of layers used
if True:
hori_plots = 7
nrYplots = int(np.ceil(len(rcf_images)/hori_plots))
fig, axs = plt.subplots(nrYplots, hori_plots, figsize=(16,nrYplots*3))
# start horizontal position on the left:
hor_pos = 0
# start vertical postion on top:
ver_pos = 0
# Braqq peak values preallocated:
E = np.zeros(len(rcf_images))
E_error = np.zeros(len(rcf_images))
for i in range(len(rcf_images)):
# if horizontal positi is right, jump to next line:
if hor_pos == hori_plots-1:
ver_pos = ver_pos +1
# filling from left to right
hor_pos = i % hori_plots
pic_values = rcf_images[i].ImageArray/65355# *255
axs[ver_pos, hor_pos].imshow(pic_values[:,:,:])
axs[ver_pos, hor_pos].contour(rcf_images[i].ImageMask,colors='r')
axs[ver_pos, hor_pos].axis('off')
# enlarge thick title
axs[ver_pos, hor_pos].set_title('Layer '+str(i+1)+': '+rcf_images[i].RCFType.name.split()[0],
fontsize = 10, weight='bold')
# there are open axs that still have empty axis', this has to be dealt with
for i in range(hor_pos,hori_plots):
axs[ver_pos, i].axis('off')
```
%% Cell type:code id: tags:
``` python
# Substep 3:
## Create a RCFStack object
stack1 = RCFStack(numberOfRCFs = len(rcf_images),
rcf_images = rcf_images,
savepath="dummy",
laser_instance=laser1,
target_instance=target1,
scanner_instance=scanner1,
name ="Quellschuss")
## Create the corresponding ELO array for the stack
stack1.create_ELOarray()
```
%% Cell type:code id: tags:
``` python
# Substep 4:
## Deconvolution and fitting
## Step 1 is the definition of the models to be applied in this evaluation:
angle_fit = fitfunctions.parfun()
energy_fit = fitfunctions.expfun_fit()
# this functions are defined in the fitfunctions.py
print('Angle Fit selected: A(E) = ' + angle_fit.label)
print('Spectrum Fit selected: dN/dE (E) = ' + energy_fit[0].label)
```
%% Cell type:code id: tags:
``` python
if True:
# calculate the envelope
# stack1.plot_envelope_divergence(fitfunction=fitfunc, style="normalizeddiv")
stack1.plot_envelope_divergence(fitfunction=angle_fit, style="absolutediv")
# stack1.plot_envelope_divergence(fitfunction=fitfunc, style="particlesdiv")
# Attention: Invalid value encountered in sqrt is caused by the bootsstrapping for the error determination.
# Since enough resampling is done, this can be ignored.
```
%% Cell type:code id: tags:
``` python
## Step 1 is the fitting of the energyspectrum with simplefit
## at first and the proper deconvolution second.
## Step 2 is then the more detailed deconvolution
if True:
p1, p2 = stack1.simplefit(fit_model=energy_fit)
stack1.fitdeconv(p1, p2, 500,fit_model=energy_fit)
```
%% Cell type:code id: tags:
``` python
## Step 3 Linear energyspectrum deconvolution with the linear deconvolution
if True:
stack1.linear_deconv()
stack1.linear_deconv_with_uncertainties(nr_of_samples=60, Ec_Offset=2)
```
%% Cell type:code id: tags:
``` python
# All fit results are presented here
stack1.fit_results
```
%% Cell type:markdown id: tags:
### Step 5: Results Display <a class="anchor" id="step5"></a>
Several additional plots.
%% Cell type:code id: tags:
``` python
# Plot of the MeV Maps created during Evaluation.
if True:
hori_plots = 7
nrYplots = int(np.ceil(len(rcf_images)/hori_plots))
fig, axs = plt.subplots(nrYplots, hori_plots, figsize=(16,nrYplots*3))
# start horizontal position on the left:
hor_pos = 0
# start vertical postion on top:
ver_pos = 0
#nrYplots = int(np.ceil(len(rcf_images)/3))
#fig, axs = plt.subplots(nrYplots, 3, figsize=(12,nrYplots*4))
## start horizontal position on the left:
#hor_pos = 0
## start vertical postion on top:
#ver_pos = 0
for i in range(len(rcf_images)):
# if horizontal positi is right, jump to next line:
if hor_pos == hori_plots-1:
ver_pos = ver_pos +1
# filling from left to right
hor_pos = i % hori_plots
contour_value = [rcf_images[i].maskValue]
#values = rcf_images[i].MeV_map
values = rcf_images[i].MeV_map
# values = rcf_images[i].ImageMask
axs[ver_pos, hor_pos].imshow(values, cmap='tab20c')
axs[ver_pos, hor_pos].contour(rcf_images[i].ImageMask,colors='r')
axs[ver_pos, hor_pos].axis('off')
# enlarge thick title
axs[ver_pos, hor_pos].set_title('Layer '+str(i+1)+': '+rcf_images[i].RCFType.name.split()[0],
fontsize = 10, weight='bold')
# there are open axs that still have empty axis', this has to be dealt with
for i in range(hor_pos,hori_plots):
axs[ver_pos, i].axis('off')
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment