Skip to content
Snippets Groups Projects
Commit 6d1aa45d authored by Mikhail Karnevskiy's avatar Mikhail Karnevskiy
Browse files

Add plotting constants of FCCD

parent b84511dc
No related branches found
No related tags found
1 merge request!132Feat: Add plotting constants of FCCD
......@@ -352,6 +352,20 @@ class HMType(Enum):
INSET_AXIS = 2
def get_range(data, scale):
"""
Get range, which includes most of the data points.
Range is calculated in units of median absolute deviations
:param data: numpy.array of data points
:param scale: range in units of median absolute deviations
:return:
"""
med = np.nanmedian(data)
mad = np.nanmedian(np.abs(data.flatten() - med))
return med - scale * mad, med + scale * mad
def hm_combine(data, fname=None, htype=None, **kwargs):
"""
Plot heatmap for calibration report
......
%% Cell type:markdown id: tags:
# Statistical analysis of calibration factors#
Author: Mikhail Karnevskiy, Steffen Hauf, Version 0.1
A description of the notebook.
%% Cell type:code id: tags:
``` python
cluster_profile = "noDB" # The ipcluster profile to use
start_date = "2019-01-30" # date to start investigation interval from
end_date = "2019-08-30" # date to end investigation interval at, can be "now"
nconstants = 10 # Number of time stamps to plot. If not 0, overcome start_date.
dclass="CCD" # Detector class
db_module = "fastCCD1" # detector entry in the DB to investigate
constants = ["Noise"]#, "Offset"] # constants to plot
gain_setting = [0,1,2,8] # gain stages
bias_voltage = [79] # Bias voltage
temperature = [235]#, 216, 245] # Operation temperature
integration_time = [1, 50] # Integration time
pixels_x=[1934]
pixels_y=[960]
max_time = 15
parameter_names = ['bias_voltage', 'integration_time', 'temperature',
'gain_setting', 'pixels_x', 'pixels_y'] # names of parameters
photon_energy = 9.2 # Photon energy of the beam
out_folder = "/gpfs/exfel/data/scratch/karnem/test_FCCD5/" # output folder
use_existing = "" # If not empty, constants stored in given folder will be used
cal_db_interface = "tcp://max-exfl016:8015#8025" # the database interface to use
cal_db_timeout = 180000 # timeout on caldb requests",
plot_range = 3 # range for plotting in units of median absolute deviations
```
%% Cell type:code id: tags:
``` python
import copy
import datetime
import dateutil.parser
import numpy as np
from operator import itemgetter
import os
import sys
import warnings
warnings.filterwarnings('ignore')
import h5py
import matplotlib
%matplotlib inline
from iCalibrationDB import Constants, Conditions, Detectors, ConstantMetaData
from cal_tools.tools import get_from_db, get_random_db_interface
from cal_tools.ana_tools import (save_dict_to_hdf5, load_data_from_hdf5,
combine_constants, HMType,
hm_combine, combine_lists, get_range)
```
%% Cell type:code id: tags:
``` python
# Prepare variables
spShape = (967, 10) # Shape of superpixel
parameters = [globals()[x] for x in parameter_names]
constantsDark = {'Noise': 'BadPixelsDark',
'Offset': 'BadPixelsDark'}
print('Bad pixels data: ', constantsDark)
# Define parameters in order to perform loop over time stamps
start = datetime.datetime.now() if start_date.upper() == "NOW" else dateutil.parser.parse(
start_date)
end = datetime.datetime.now() if end_date.upper() == "NOW" else dateutil.parser.parse(
end_date)
# Create output folder
os.makedirs(out_folder, exist_ok=True)
# Get getector conditions
det = getattr(Detectors, db_module)
dconstants = getattr(Constants, dclass)(det.detector_type)
print('CalDB Interface: {}'.format(cal_db_interface))
print('Start time at: ', start)
print('End time at: ', end)
```
%% Cell type:code id: tags:
``` python
parameter_list = combine_lists(*parameters, names = parameter_names)
print(parameter_list)
```
%% Cell type:code id: tags:
``` python
# Retrieve list of meta-data
constant_versions = []
constant_parameters = []
constantBP_versions = []
# Loop over constants
for c, const in enumerate(constants):
if use_existing != "":
break
# Loop over parameters
for pars in parameter_list:
if (const in ["Offset", "Noise", "SlopesPC"] or "DARK" in const.upper()):
dcond = Conditions.Dark
mcond = getattr(dcond, dclass)(**pars)
else:
dcond = Conditions.Illuminated
mcond = getattr(dcond, dclass)(**pars,
photon_energy=photon_energy)
print('Request: ', const, 'with paramters:', pars)
# Request Constant versions for given parameters and module
data = get_from_db(det,
getattr(dconstants,
const)(),
copy.deepcopy(mcond), None,
cal_db_interface,
creation_time=start,
verbosity=0,
timeout=cal_db_timeout,
meta_only=True,
version_info=True)
if not isinstance(data, list):
continue
data = sorted(data, key=itemgetter('begin_at'))
print('Number of retrieved constants: {}'.format(len(data)) )
if const in constantsDark:
# Request BP constant versions
dataBP = get_from_db(det,
getattr(dconstants,
constantsDark[const])(),
copy.deepcopy(mcond), None,
cal_db_interface,
creation_time=start,
verbosity=0,
timeout=cal_db_timeout,
meta_only=True,
version_info=True)
if not isinstance(data, list) or not isinstance(dataBP, list):
continue
print('Number of retrieved darks: {}'.format(len(dataBP)) )
found_BPmatch = False
for d in data:
# Match proper BP constant version
# and get constant version within
# requested time range
if d is None:
print('Time or data is not found!')
continue
dt = dateutil.parser.parse(d['begin_at'])
if (dt.replace(tzinfo=None) > end or
(nconstants==0 and dt.replace(tzinfo=None) < start)):
continue
if nconstants>0 and constant_parameters.count(pars)>nconstants-1:
break
closest_BP = None
closest_BPtime = None
for dBP in dataBP:
if dBP is None:
print("Bad pixels are not found!")
continue
dt = dateutil.parser.parse(d['begin_at'])
dBPt = dateutil.parser.parse(dBP['begin_at'])
if dt == dBPt:
found_BPmatch = True
else:
if np.abs(dBPt-dt).seconds < (max_time*60):
if closest_BP is None:
closest_BP = dBP
closest_BPtime = dBPt
else:
if np.abs(dBPt-dt) < np.abs(closest_BPtime-dt):
closest_BP = dBP
closest_BPtime = dBPt
if dataBP.index(dBP) == len(dataBP)-1:
if closest_BP:
dBP = closest_BP
dBPt = closest_BPtime
found_BPmatch = True
else:
print('Bad pixels are not found!')
if found_BPmatch:
print("Found constant {}: begin at {}".format(const, dt))
print("Found bad pixels at {}".format(dBPt))
constantBP_versions.append(dBP)
constant_versions.append(d)
constant_parameters.append(copy.deepcopy(pars))
found_BPmatch = False
break
else:
constant_versions += data
constant_parameters += [copy.deepcopy(pars)]*len(data)
# Remove dublications
constant_versions_tmp = []
constant_parameters_tmp = []
for i, x in enumerate(constant_versions):
if x not in constant_versions_tmp:
constant_versions_tmp.append(x)
constant_parameters_tmp.append(constant_parameters[i])
constant_versions=constant_versions_tmp
constant_parameters=constant_parameters_tmp
print('Number of stored constant versions is {}'.format(len(constant_versions)))
```
%% Cell type:code id: tags:
``` python
def get_rebined(a, rebin):
return a[:,:,0].reshape(
int(a.shape[0] / rebin[0]),
rebin[0],
int(a.shape[1] / rebin[1]),
rebin[1])
def modify_const(const, data, isBP = False):
return data
ret_constants = {}
constand_data = ConstantMetaData()
constant_BP = ConstantMetaData()
for i, constant_version in enumerate(constant_versions):
const = constant_version['data_set_name'].split('/')[-2]
qm = db_module
print("constant: {}, module {}".format(const,qm))
constand_data.retrieve_from_version_info(constant_version)
# Convert parameters to dict
dpar = {p.name: p.value for p in constand_data.detector_condition.parameters}
const = "{}_{}_{}_{}".format(const,
constant_parameters[i]['gain_setting'],
constant_parameters[i]['temperature'],
constant_parameters[i]['integration_time'])
if not const in ret_constants:
ret_constants[const] = {}
if not qm in ret_constants[const]:
ret_constants[const][qm] = []
cdata = constand_data.calibration_constant.data
ctime = constand_data.calibration_constant_version.begin_at
cdata = modify_const(const, cdata)
if len(constantBP_versions)>0:
constant_BP.retrieve_from_version_info(constantBP_versions[i])
cdataBP = constant_BP.calibration_constant.data
cdataBP = modify_const(const, cdataBP, True)
if cdataBP.shape != cdata.shape:
print('Wrong bad pixel shape! {}, expected {}'.format(cdataBP.shape, cdata.shape))
continue
# Apply bad pixel mask
cdataABP = np.copy(cdata)
cdataABP[cdataBP > 0] = np.nan
# Create superpixels for constants with BP applied
cdataABP = get_rebined(cdataABP, spShape)
toStoreBP = np.nanmean(cdataABP, axis=(1, 3))
toStoreBPStd = np.nanstd(cdataABP, axis=(1, 3))
# Prepare number of bad pixels per superpixels
cdataBP = get_rebined(cdataBP, spShape)
cdataNBP = np.nansum(cdataBP > 0, axis=(1, 3))
else:
toStoreBP = 0
toStoreBPStd = 0
cdataNBP = 0
# Create superpixels for constants without BP applied
cdata = get_rebined(cdata, spShape)
toStoreStd = np.nanstd(cdata, axis=(1, 3))
toStore = np.nanmean(cdata, axis=(1, 3))
# Convert parameters to dict
dpar = {p.name: p.value for p in constand_data.detector_condition.parameters}
print("Store values in dict", const, qm, ctime)
ret_constants[const][qm].append({'ctime': ctime,
'nBP': cdataNBP,
'dataBP': toStoreBP,
'dataBPStd': toStoreBPStd,
'data': toStore,
'dataStd': toStoreStd,
'mdata': dpar})
```
%% Cell type:code id: tags:
``` python
if use_existing == "":
print('Save data to /CalDBAna_{}_{}.h5'.format(dclass, db_module))
save_dict_to_hdf5(ret_constants,
'{}/CalDBAna_{}_{}.h5'.format(out_folder, dclass, db_module))
```
%% Cell type:code id: tags:
``` python
if use_existing == "":
fpath = '{}/CalDBAna_{}_*.h5'.format(out_folder, dclass)
else:
fpath = '{}/CalDBAna_{}_*.h5'.format(use_existing, dclass)
print('Load data from {}'.format(fpath))
ret_constants = load_data_from_hdf5(fpath)
```
%% Cell type:code id: tags:
``` python
# Parameters for plotting
keys = {
'Mean': ['data', '', 'Mean over pixels'],
'std': ['dataStd', '', '$\sigma$ over pixels'],
'MeanBP': ['dataBP', 'Good pixels only', 'Mean over pixels'],
'NBP': ['nBP', 'Fraction of BP', 'Fraction of BP'],
'stdBP': ['dataBPStd', 'Good pixels only', '$\sigma$ over pixels'],
'stdASIC': ['', '', '$\sigma$ over ASICs'],
'stdCell': ['', '', '$\sigma$ over Cells'],
}
```
%% Cell type:code id: tags:
``` python
print('Plot calibration constants')
# loop over constat type
for const, modules in ret_constants.items():
const, gain, temp, int_time = const.split("_")
print('Const: {}'.format(const))
# loop over modules
mod_data = {}
mod_data['stdASIC'] = []
mod_data['stdCell'] = []
mod_names = []
mod_times = []
# Loop over modules
for mod, data in modules.items():
print(mod)
ctimes = np.array(data["ctime"])
ctimes_ticks = [x.strftime('%y-%m-%d') for x in ctimes]
if ("mdata" in data):
cmdata = np.array(data["mdata"])
for i, tick in enumerate(ctimes_ticks):
ctimes_ticks[i] = ctimes_ticks[i] + \
', V={:1.0f}'.format(cmdata[i]['Sensor Temperature']) + \
', T={:1.0f}'.format(
cmdata[i]['Integration Time'])
sort_ind = np.argsort(ctimes_ticks)
ctimes_ticks = list(np.array(ctimes_ticks)[sort_ind])
# Create sorted by data dataset
rdata = {}
for key, item in keys.items():
if item[0] in data:
rdata[key] = np.array(data[item[0]])[sort_ind]
nTimes = rdata['Mean'].shape[0]
nPixels = rdata['Mean'].shape[1] * rdata['Mean'].shape[2]
nBins = nPixels
# Avoid to low values
if const in ["Noise", "Offset", "Noise-e"]:
rdata['Mean'][rdata['Mean'] < 0.1] = np.nan
if 'MeanBP' in rdata:
rdata['MeanBP'][rdata['MeanBP'] < 0.1] = np.nan
if 'NBP' in rdata:
rdata["NBP"] = rdata["NBP"] / spShape[0] / spShape[1] * 100
# Reshape: ASICs over cells for plotting
pdata = {}
for key in rdata:
if len(rdata[key].shape)<3:
continue
pdata[key] = rdata[key][:, :, :].reshape(nTimes, nBins).swapaxes(0, 1)
# Summary over ASICs
adata = {}
for key in rdata:
if len(rdata[key].shape)<3:
continue
adata[key] = np.nanmean(rdata[key], axis=(1, 2))
# Summary information over modules
for key in pdata:
if key not in mod_data:
mod_data[key] = []
mod_data[key].append(np.nanmean(pdata[key], axis=0))
mod_data['stdASIC'].append(np.nanstd(rdata['Mean'], axis=(1, 2)))
mod_names.append(mod)
mod_times.append(ctimes_ticks)
# Plotting
for key in pdata:
if len(pdata[key].shape)<2:
continue
if key == 'NBP':
unit = '[%]'
else:
unit = '[ADU]'
if const == 'Noise-e':
unit = '[$e^-$]'
title = '{}, module {}, gain {} {}'.format(
const, mod, gain, keys[key][1])
cb_label = '{}, {} {}'.format(const, keys[key][2], unit)
vmin,vmax = get_range(pdata[key][::-1].flatten(), plot_range)
hm_combine(pdata[key][::-1], htype=HMType.mro,
x_label='Creation Time', y_label='ASIC ID',
x_ticklabels=ctimes_ticks,
x_ticks=np.arange(len(ctimes_ticks))+0.3,
title=title, cb_label=cb_label,
vmin=vmin, vmax=vmax,
fname='{}/{}_{}_g{}_t{}_t{}_ASIC_{}.png'.format(
out_folder, const, mod.replace('_', ''), gain, temp, int_time, key),
pad=[0.125, 0.125, 0.12, 0.185])
```
......@@ -129,6 +129,12 @@ notebooks = {
"use function": "balance_sequences",
"cluster cores": 4},
},
"STATS_FROM_DB": {
"notebook": "notebooks/FastCCD/PlotFromCalDB_FastCCD_NBC.ipynb",
"concurrency": {"parameter": None,
"default concurrency": None,
"cluster cores": 1},
},
},
"JUNGFRAU": {
"DARK": {
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment