10 #include <QtCore/QDateTime>
11 #include <QtCore/QFile>
12 #include <QtCore/QFileInfo>
28 using tr1::placeholders::_1;
29 using tr1::placeholders::_2;
30 using tr1::placeholders::_3;
31 using tr1::placeholders::_4;
32 using tr1::placeholders::_5;
66 _filename = s.
value(
"OutputFilename",
"NotSet").toString().toStdString();
74 string updateType = s.
value(
"UpdateCalibrationType",
"cummulative").toString().toStdString();
77 _alpha = (2./(s.
value(
"NbrOfImages",200).toFloat()+1.));
80 if (updateType ==
"cummulative")
82 else if (updateType ==
"moving")
85 throw invalid_argument(
"pp330::loadSettings(): '" +
name() +
"' updateType '" +
86 updateType +
"' is unknown.");
95 const size_t imagesize(shape.first*shape.second);
119 ": generates the calibration data from images contained in '" +
132 "'(created '" + createdAt +
133 "') write '" + (
_write?
"true":
"false") +
134 "' train '" + (
_train?
"true":
"false") +
138 "' updateType '" + updateType +
141 "'. Condition is '" +
_condition->name() +
"'");
158 "': The given input filename '" + inname +
159 "' is a link to a non existing file. Skip loading the data!");
163 else if(!innameInfo.
exists())
166 "': The given input filename '" + inname +
167 "' does not exist. Skip loading the data!");
177 "' Load Darkcal data from file '" + inname +
"'");
178 ifstream in(inname.c_str(), ios::binary);
182 "' Could not open '" + inname +
"'. Skip loading the data.");
185 in.seekg(0,std::ios::end);
186 const size_t size(in.tellg() / 2 /
sizeof(double));
187 in.seekg(0,std::ios::beg);
188 vector<double> offsets(size);
189 in.read(reinterpret_cast<char*>(&offsets[0]), size*
sizeof(
double));
190 vector<double> noises(size);
191 in.read(reinterpret_cast<char*>(&noises[0]), size*
sizeof(
double));
195 if (size != sizeOfImage)
198 "' The size of the loaded data '" +
toString(size) +
"' in '" +
199 inname +
"' does not match the size of the input image '" +
200 toString(sizeOfImage) +
"'. Skip loading the data.");
205 copy(offsets.begin(),offsets.end(),meanbegin);
207 copy(noises.begin(),noises.end(),stdvbegin);
224 outname =
name() +
"_" + now.
toString(
"yyyyMMdd_HHmm").toStdString() +
".cal";
229 ofstream out(outname.c_str(), ios::binary);
231 throw invalid_argument(
"pp330::writeCalibration(): Error opening file '" +
237 vector<double> offsets(sizeOfImage);
240 copy(meanbegin,meanend,offsets.begin());
241 out.write(reinterpret_cast<char*>(&offsets[0]), offsets.size()*
sizeof(double));
243 vector<double> noises(sizeOfImage);
246 copy(stdvbegin,stdvend,noises.begin());
247 out.write(reinterpret_cast<char*>(&noises[0]), noises.size()*
sizeof(double));
257 string linkname(
name() +
".lnk");
260 throw runtime_error(
"pp330::writeCalibration: '" +
name() +
261 "' could not remove already existing link '" +
264 throw runtime_error(
"pp330::writeCalibration: '" +
name() +
265 "' could not create a link named '"+ linkname +
266 "' that points to the outputfile '" + outname +
"'");
295 "': The automatically determined boundaries for bad pixels based " +
296 "upon Noisemap are: low '" +
toString(stdvLowerBound) +
"' up '" +
313 "': The automatically determined boundaries for bad pixels based "+
314 "upon Offsetmap are: low '" +
toString(meanLowerBound) +
"' up '" +
322 for (
size_t iPix=0; iPix < sizeOfImage; ++iPix)
325 if (stdvBegin[iPix] < stdvLowerBound ||
326 stdvBegin[iPix] > stdvUpperBound)
328 if (meanBegin[iPix] < meanLowerBound ||
329 meanBegin[iPix] > meanUpperBound)
331 if (nValsBegin[iPix] < minpixels)
335 badPixBegin[iPix] = 1;
337 badPixBegin[iPix] = 0;
352 if(command ==
"startDarkcal")
355 "'starts collecting data for dark calibration");
366 const size_t sizeOfImage)
368 for(
size_t iPix(0); iPix < sizeOfImage; ++iPix)
370 const float mean(meanAr[iPix]);
371 const float stdv(stdvAr[iPix]);
372 const float pix(image[iPix]);
375 if(
_snr * stdv < pix - mean)
378 const float nVals(nValsAr[iPix] + 1);
379 const float delta(pix - mean);
380 const float newmean(mean + (delta / nVals));
381 const float M2(stdv*stdv * (nVals-2));
382 const float newM2(M2 + delta * (pix - mean) );
383 const float newstdv((nVals < 2) ? 0 : sqrt(newM2/(nVals-1)));
385 meanAr[iPix] = newmean;
386 stdvAr[iPix] = newstdv;
387 nValsAr[iPix] = nVals;
395 const size_t sizeOfImage)
397 for(
size_t iPix(0); iPix < sizeOfImage; ++iPix)
399 const float mean(meanAr[iPix]);
400 const float stdv(stdvAr[iPix]);
401 const float pix(image[iPix]);
402 const float nVals(nValsAr[iPix] + 1);
405 if(
_snr * stdv < pix - mean)
410 const float newstdv(sqrt(
_alpha*(pix - mean)*(pix - mean) + (1.f -
_alpha)*stdv*stdv));
412 meanAr[iPix] = newmean;
413 stdvAr[iPix] = newstdv;
414 nValsAr[iPix] = nVals;
421 const size_t sizeOfImage(image.
shape().first * image.
shape().second);
442 "' done collecting images for darkcalibration. Calculating maps");
444 for (
size_t iPix=0; iPix < sizeOfImage; ++iPix)
447 for (
size_t iStore=0; iStore <
_trainstorage.size(); ++iStore)
450 meanAr[iPix] = stat.
mean();
451 stdvAr[iPix] = stat.
stdv();
464 "' done calculating maps");
504 if (
_image->result().dim() != 2)
505 throw invalid_argument(
"pp331::loadSettings: '" +
name() +
"' input '" +
506 _image->name() +
"' is not a 2d histogram");
512 _filename = s.
value(
"Filename",
"out.cal").toString().toStdString();
515 s.
value(
"ADURangeHigh",0).toFloat());
521 if (
_isPnCCDNoCTE && (shape.first != 1024 || shape.second != 1024))
522 throw invalid_argument(
"pp331::loadSettings(): '" +
name() +
523 "' should be a pnCCD, but cols '" +
524 toString(shape.first) +
"' and rows '"
526 "' don't indicate a pnCCD");
537 ": generates the gain calibration from images contained in '" +
543 if (command ==
"startGain")
556 ofstream out(
_filename.c_str(), ios::binary);
558 throw invalid_argument(
"pp331::writeCalibration(): Error opening file '" +
561 out.write(reinterpret_cast<const char*>(&image.
front()),
_sizeOfImage*
sizeof(
float));
582 for (
size_t i(0); i <
_sizeOfImage; ++i, ++count, ++ave)
587 average += (*ave -
average)/counter;
597 for (
size_t i(0); i <
_sizeOfImage; ++i, ++gain, ++count, ++ave)
606 const size_t cols(image.
shape().first);
616 for (
size_t i(0);
pixel != ImageEnd; ++i, ++
pixel, ++gain, ++count, ++ave)
623 *ave += ((*pixel - *ave) / *count);
631 const size_t col (i % cols);
632 const size_t row (i / cols);
643 countcol += 512*1024;
647 const float currentgain(*gain);
648 const float currentcount(*count);
649 const float currentave(*ave);
650 for (
int ii=0; ii<512; ++ii)
652 *gaincol = currentgain;
655 *countcol = currentcount;
658 *avecol = currentave;
699 _filename = s.
value(
"Filename",
"out.cal").toString().toStdString();
702 s.
value(
"ADURangeUp",0).toFloat());
711 ": generates the hot pixel map from images contained in '" +
717 ifstream in(
_filename.c_str(), ios::binary);
721 "'. Skipping reading the hot pixels mask.");
724 in.seekg(0,std::ios::end);
725 const int valuesize(
sizeof(
mask_t));
726 const size_t size = in.tellg() / valuesize;
727 in.seekg(0,std::ios::beg);
728 vector<mask_t> hotpixmask(size);
729 in.read(reinterpret_cast<char*>(&hotpixmask.front()), size*valuesize);
733 const size_t sizeOfImage(result.
shape().first*result.
shape().second/2);
734 if (sizeOfImage != size)
737 toString(size) +
"' does not fit with size of image '" +
738 toString(sizeOfImage) +
"'. Skipping reading the hot pixels mask in '" +
742 copy(hotpixmask.begin(),hotpixmask.end(),result.
begin());
747 ofstream out(
_filename.c_str(), ios::binary);
749 throw invalid_argument(
"pp332::writeCalibration(): Error opening file '" +
753 const size_t sizeOfImage(result.
shape().first*result.
shape().second/2);
755 vector<mask_t>
mask(sizeOfImage);
756 copy(result.
begin(),result.
begin()+sizeOfImage,mask.begin());
757 out.write(reinterpret_cast<char*>(&mask.front()), sizeOfImage*
sizeof(
mask_t));
773 const size_t sizeOfImage(image.
shape().first * image.
shape().second);
779 for (;
pixel != ImageEnd; ++
pixel, ++count, ++hotpix)
837 string calctype(s.
value(
"CalculationType",
"mean").toString().toStdString());
838 if(calctype ==
"mean")
840 else if(calctype ==
"median")
843 throw invalid_argument(
"pp333::loadSettings() '" +
name() +
844 "': Calculation type '" + calctype +
"' is unkown.");
850 ": generates the common mode background level of '" +
851 _image->name() +
"' using calculation type '" + calctype +
852 "'. Condition is '" +
_condition->name() +
"'");
879 const size_t sizeOfImage(image.
shape().first * image.
shape().second);
880 const size_t parts(sizeOfImage /
_width);
883 for (
size_t part(0); part < parts; ++part)
888 const float commonmodeLevel(
_calcCommonmode(startPart_Image,endPart_Image));
893 fill(startPart_Res, endPart_Res, commonmodeLevel);
934 ": generates the common mode background level of '" +
935 _image->name() +
"' using either histogram or unbonded pixels"+
936 "'. Condition is '" +
_condition->name() +
"'");
945 const uint32_t nAsics(64);
946 const uint32_t nAsicsPerRow(2);
947 const uint32_t nColsAsic(194);
948 const uint32_t nRowsAsic(185);
949 const uint32_t nColsInput(nAsicsPerRow*nColsAsic);
950 const float low(-60);
952 const int32_t nBins(up-low);
955 typedef vector<double> hists_t;
956 hists_t hists(nAsics*nBins,0);
959 for (
int i(0); i < static_cast<int>(image.
datasize()); ++i)
964 if (std::abs(pixelval) < std::numeric_limits<result_t::value_t>::epsilon())
967 const uint16_t row(i/nColsInput);
969 const uint16_t colInRow(i%nColsInput);
971 const uint8_t asicOnChip(colInRow/nColsAsic);
973 const uint8_t chip(row/nRowsAsic);
975 const uint8_t asic(nAsicsPerRow*chip + asicOnChip);
977 const int32_t
bin(static_cast<int32_t>(nBins*(pixelval-low)/(up-low)));
979 if ((bin < 0) || (nBins <= bin))
982 hists[(asic*nBins) + bin] += 1;
986 hists_t histsCMVals(nAsics,0);
987 for (uint32_t asic(0); asic<nAsics; ++asic)
989 hists_t::const_iterator histStart(hists.begin()+(asic*nBins));
990 hists_t::const_iterator histEnd(histStart+nBins);
991 hists_t::const_iterator pToMax(
max_element(histStart,histEnd));
992 int bin(distance(histStart,pToMax));
995 histsCMVals[asic] = 1e6;
999 hists_t::const_iterator peakBegin(pToMax-
_width);
1000 hists_t::const_iterator peakEnd(pToMax+
_width+1);
1001 const double integral(accumulate(peakBegin,peakEnd,0.));
1003 bins.reserve(
_width*2+1);
1005 bins.push_back(low + (i*(up-low)/nBins));
1007 weights.reserve(_width*2+1);
1008 transform(peakBegin,peakEnd,bins.begin(),back_inserter(weights),
1009 multiplies<double>());
1010 const double weight(accumulate(weights.begin(),weights.end(),0.));
1011 const double com(weight/integral);
1013 histsCMVals[asic] =
com;
1017 hists_t unbondedPixCMVals(nAsics,0);
1018 const int sizeBetweenAsics(nColsAsic);
1019 const int sizeBetweenUnbondedPixels(3696);
1020 const int sizeBetweenChips(1566);
1022 const int nChips(32);
1025 for (
int chip=0; chip<nChips; ++chip)
1028 for (
int up=0; up<nUBP-1; ++up)
1031 unbondedPixCMVals[asic] += *pointer;
1032 pointer += sizeBetweenAsics;
1034 pointer += sizeBetweenUnbondedPixels;
1035 unbondedPixCMVals[asic+1] += *pointer;
1038 unbondedPixCMVals[asic] += *pointer;
1039 pointer += sizeBetweenAsics;
1041 unbondedPixCMVals[asic+1] += *pointer;
1042 pointer += sizeBetweenChips;
1045 for (uint32_t asic(0); asic < nAsics; ++asic)
1047 unbondedPixCMVals[asic] /=
static_cast<float>(nUBP);
1055 hists_t CMVals(nAsics,0);
1056 for (uint32_t asic(0); asic < nAsics; ++asic)
1058 CMVals[asic] = (fabs(unbondedPixCMVals[asic]-histsCMVals[asic]) <
_maxDist) ?
1059 histsCMVals[asic] : unbondedPixCMVals[asic];
1064 for (
int i(0); i < static_cast<int>(image.
datasize()); ++i)
1069 if (std::abs(pixelval) < std::numeric_limits<result_t::value_t>::epsilon())
1072 const uint16_t row(i/nColsInput);
1074 const uint16_t colInRow(i%nColsInput);
1076 const uint8_t asicOnChip(colInRow/nColsAsic);
1078 const uint8_t chip(row/nRowsAsic);
1080 const uint8_t asic(nAsicsPerRow*chip + asicOnChip);
1082 result[i] = CMVals[asic];
1088 for (uint32_t asic(0); asic < nAsics; ++asic)
1093 asic*image.
shape().first);
1095 hists_t::const_iterator histStart(hists.begin()+(asic*nBins));
1096 hists_t::const_iterator histEnd(histStart+nBins);
1097 res = copy(histStart,histEnd,res);
1099 *res = histsCMVals[asic];
1102 *res = unbondedPixCMVals[asic];
1105 *res = CMVals[asic];
CachedList::item_type result_t
define the results
storage_t::const_iterator const_iterator
a const iterator on the storage
bool _write
flag to tell whether the calibration should be written
size_t _aveOffset
offset to the average part
reference front()
retrieve reference to the first element
void appendRows(const storage_t &rows)
add row(s) to the result
float _autoNoiseSNR
the signal to noise ratio that determines the noise boundaries in case of automatically determining t...
Event to store all LCLS Data.
virtual void createHistList(result_t::shared_pointer result)
create result list.
char mask_t
define the output mask type
bool fuzzycompare(const T &first, const T &second)
fuzzy compare two floating point variables
pp332(const name_t &)
constructor.
const_iterator end() const
retrieve iterator to the end of storage
float _snr
the value above which outliers are removed from the distribution
pp333(const name_t &)
constructor.
std::vector< value_t > storage_t
the storage of this container
std::tr1::function< float(result_t::const_iterator, result_t::const_iterator)> _calcCommonmode
the function that calculates the commond mode level
std::string _filename
the filename that is used to save the calibration
determine the particle size by the distance between the first minima of the q average[Processor]
toString(const QString &format)
pp331(const name_t &)
constructor.
uint32_t _lastwritten
the time_t value of the last time the calibration was written
pp334(const name_t &)
constructor.
void movingUpdate(result_t::const_iterator image, result_t::iterator meanAr, result_t::iterator stdvAr, result_t::iterator nValsAr, const size_t sizeOfImage)
a moving exponential average and variance calculation
virtual void loadSettings(size_t)
load the settings of this pp
const name_t name() const
retrieve the name of this processor
void loadCalibration()
write the calibration data to file
float value_t
the values of this container
int _nFrames
the number of frames after which the gain map is calculted
setFile(const QString &file)
value_type mean()
retrieve the mean of the distribution without outliers
std::tr1::shared_ptr< self_type > shared_pointer
a shared pointer of this class
statistics calculator for a cummulative statistic, removes outliers
virtual void loadSettings(size_t)
load the settings of this pp
float _autoNoiseSNRStat
the signal to noise ratio that determines which values will be taken into account when automatically ...
pp330(const name_t &)
constructor.
std::pair< size_type, size_type > shape_t
define the shape of the result
bool _write
flag to tell whether the calibration should be written
float _NoiseLowerBound
the lower noise boundary when determining bad pixels
std::vector< result_t::shared_pointer > _trainstorage
the storage for the training images
shared_pointer _image
the raw image
float _maxADUVal
the maximum allowed adu value
size_t bin(const Axis< AxisPrecessionType > &xaxis, const ResultValueType &value)
calculate the index of the lineared array
things written only at end of run H5Dump ProcessorSummary size
virtual void processCommand(std::string command)
receive commands from the gui
size_t _countOffset
offset to the counts part
processors that do calibrations on pixel detector data
std::string _filename
the filename that is used to save the calibration
virtual void loadSettings(size_t)
load the settings of this pp
void writeCalibration()
write the calibration data to file
size_t _bPixBeginOffset
the offset to the first point of the bad pixels array in the result
float _snr
the signal to noise ratio in case one uses the mean calculator
int _updatePeriod
the period after which the data should be autosaved
size_t _stdvBeginOffset
the offset to the first point of the stdv array in the result
bool _train
flag telling whether training is needed
static void add(Level level, const std::string &line)
add a string to the log
const_iterator begin() const
retrieve a iterator for read access to beginning
virtual void process(const CASSEvent &, result_t &)
overwrite default behaviour don't do anything
size_t _minTrainImages
the minimum nbr of images necessary for training
count_type nbrPointsUsed()
retrieve the number of points used in the statistics
fromStdString(const std::string &str)
uint32_t _updateWritePeriod
the update time period in s
std::string _infilename
the filename that is used to load the calibration
virtual void process(const CASSEvent &, result_t &)
overwrite default behaviour don't do anything
ForwardIterator max_element(ForwardIterator first, ForwardIterator last)
provide own implementation of min_element to be able to compile
virtual void process(const CASSEvent &, result_t &)
overwrite default behaviour don't do anything
shared_pointer clone() const
create a copy of the result
int _counter
counter to count how many times this has been called
base class for processors.
virtual const result_t & result(const CASSEvent::id_t)
retrieve a result.
shared_pointer setupDependency(const std::string &depVarName, const name_t &name="")
setup the dependecy.
size_t _width
the number of times a pixel is high before masking it as hot pixel
float _constGain
the gain value that will be assinged to the pixel that one could not calculate the gain for ...
size_t _meanEndOffset
the offset to one beyond the last point of the mean array in the result
virtual void loadSettings(size_t)
load the settings of this pp
size_t _sizeOfImage
the size of the input image
float _minNbrPixels
minimum number of pixels in the trainig set that are part of the distribution
void calculateGainMap(result_t &gainmap)
write the calibration data to file
shared_pointer _image
the image to create the hotpixel map from
file contains declaration of classes and functions that help other processors to do their job...
size_t _counter
counter to count the total amount of images
void cummulativeUpdate(result_t::const_iterator image, result_t::iterator meanAr, result_t::iterator stdvAr, result_t::iterator nValsAr, const size_t sizeOfImage)
a cummulative average and variance calculation
void addDistribution(InputIterator first, InputIterator last)
add a number of dati to the distribution
QReadWriteLock lock
lock for locking operations on the data of the container
virtual void aboutToQuit()
write the calibrations before quitting
float meanCalc(result_t::const_iterator begin, result_t::const_iterator end)
function to calulate the common mode level as mean value
range_t _aduRange
the range of adu that indicates whether a pixel is hot
float _alpha
the alpha value for the moving average and stdv
void writeHotPixelMap()
write the calibration data to file
std::string toString(const Type &t)
convert any type to a string
shared_pointer _image
the image to create the hotpixel map from
bool _isPnCCDNoCTE
flag to tell whether its a pnCCD we are not interested in correction the cte
void loadCalibration()
write the calibration data to file
updateFunc_t _updateStatistics
the function that will update the statistics
size_t _nValBeginOffset
the offset to the first point of the counts array in the result
range_t _aduRange
the range of adu that indicates whether a pixel contains a photon
size_t _minPhotonCount
the number of photons that a pixel should have seen before calculating the gain
size_t _maxConsecutiveCount
the number of times a pixel is high before masking it as hot pixel
size_t _bPixEndOffset
the offset to one beyond the last point of the bad pixels array in the result
virtual void process(const CASSEvent &, result_t &)
overwrite default behaviour don't do anything
value(const QString &key, const QVariant &defaultValue=QVariant()
virtual void aboutToQuit()
write the calibrations before quitting
virtual void loadSettings(size_t)
load the settings of this pp
virtual void createHistList(result_t::shared_pointer result)
create the list of results
size_t _stdvEndOffset
the offset to one beyond the last point of the stdv array in the result
void addDatum(const value_type &datum)
add a datum to the container
storage_t::iterator iterator
a iterator on the storage
contains declarations of statistic calculators
float _OffsetLowerBound
the lower offset boundary when determining bad pixels
float _NoiseUpperBound
the upper noise boundary when determining bad pixels
noise and mask[Processor]
float _autoOffsetSNR
the signal to noise ratio that determines the offset boundaries in case of automatically determining ...
void setupGeneral()
general setup of the processor
file contains specialized class that do the settings for cass
link(const QString &linkName)
int _counter
counter to count how many times this has been called
bool _update
flag to tell whether the calibration should be updated after the training has completed.
virtual void processCommand(std::string command)
react on when the gui clients tell this to start the calibration
float medianCalc(result_t::const_iterator begin, result_t::const_iterator end)
function to calulate the common mode level via the median value
void writeCalibration()
write the calibration data to file
an accumulating processor
float _autoOffsetSNRStat
the signal to noise ratio that determines which values will be taken into account when automatically ...
size_t _gainOffset
offset to the gain part
result_t::shared_pointer _result
the result that accumulates the events
size_t _meanBeginOffset
the offset to the first point of the mean array in the result
virtual void process(const CASSEvent &, result_t &)
overwrite default behaviour don't do anything
float _maxDist
the maximum distance between the value of the unbonded pxiels and the hist
shared_pointer _condition
pointer to the processor that will contain the condition
int _nFrames
the number of frames after which the gain map is calculted
shape_t shape() const
return the shape of the result
bool setupCondition(bool defaultConditionType=true)
setup the condition.
std::string name_t
define the name type
bool _resetBadPixel
flag to tell when the bad pixel should be reset
contains a logger for cass
float _OffsetUpperBound
the upper offset boundary when determining bad pixels
int16_t pixel
define a pixel
float _width
the number of times a pixel is high before masking it as hot pixel
size_t _nValEndOffset
the offset to the first point of the counts array in the result
value_type stdv()
retrieve the standart deviation of the distribution
bool _write
flag to tell whether the calibration should be written
size_type datasize() const
return the size of the data as determined by the axis
std::string _filename
the filename that is used to save the calibration
beginGroup(const QString &prefix)
bool _checks
enable output that allow to check the parameters
shared_pointer _image
the raw image
virtual void aboutToQuit()
write the calibrations before quitting
void setBadPixMap()
set up the bad pixel map
void loadHotPixelMap()
write the calibration data to file
virtual const result_t & result(const CASSEvent::id_t eventid=0)
retrieve a result for a given id.
shared_pointer _image
the image to create the hotpixel map from