From 623b1de8a0e4571249da44c5fd5ee2c0eb80827e Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Mon, 24 Jan 2022 11:19:38 +0100 Subject: [PATCH 1/2] added f suffix --- slsDetectorCalibration/interpolations/etaInterpolationBase.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/slsDetectorCalibration/interpolations/etaInterpolationBase.h b/slsDetectorCalibration/interpolations/etaInterpolationBase.h index 0882c8f23..56250510c 100644 --- a/slsDetectorCalibration/interpolations/etaInterpolationBase.h +++ b/slsDetectorCalibration/interpolations/etaInterpolationBase.h @@ -274,10 +274,10 @@ float *gethhx() for (int ii=0; iitot_eta*2.){ + } else if(ftest[ibx+iby*nSubPixelsX]>tot_eta*2.f){ etah[ii]=2; nbad++; } else From c554bbb2d3d4d936b88a323a99d4868ad8276af1 Mon Sep 17 00:00:00 2001 From: Erik Frojdh Date: Mon, 24 Jan 2022 11:26:56 +0100 Subject: [PATCH 2/2] formatted slsDetectorCalibration --- slsDetectorCalibration/MovingStat.h | 297 ++- slsDetectorCalibration/RunningStat.h | 76 +- slsDetectorCalibration/Stat.h | 62 +- slsDetectorCalibration/analogDetector.h | 2281 +++++++++-------- slsDetectorCalibration/circularFifo.h | 195 +- .../commonModeSubtraction.h | 141 +- .../commonModeSubtractionNew.h | 223 +- .../dataStructures/Mythen3_01_jctbData.h | 227 +- .../dataStructures/Mythen3_02_jctbData.h | 229 +- .../dataStructures/adcSar2_jctbData.h | 94 +- .../dataStructures/chiptestBoardData.h | 142 +- .../dataStructures/deserializer.h | 385 +-- .../gotthardDoubleModuleDataNew.h | 255 +- .../dataStructures/gotthardShortModuleData.h | 176 +- .../dataStructures/imageZmq16bit.h | 187 +- .../dataStructures/imageZmq32bit.h | 187 +- .../jungfrauHighZSingleChipData.h | 399 ++- .../dataStructures/moench02CtbData.h | 288 +-- .../dataStructures/moench03CtbData.h | 261 +- .../dataStructures/moench03T1CtbData.h | 262 +- .../moench03T1ReceiverDataNew.h | 640 ++--- .../moench03T1ReceiverDataNewRect.h | 536 ++-- .../dataStructures/moench03T1ReorderedData.h | 313 ++- .../dataStructures/moench03T1ZmqData.h | 467 ++-- .../dataStructures/moench03T1ZmqDataNew.h | 585 ++--- .../dataStructures/moench03TCtbData.h | 298 +-- .../moench04CtbReceiver10GbData.h | 539 ++-- .../dataStructures/moench04CtbReceiverData.h | 531 ++-- .../dataStructures/moench04CtbZmq10GbData.h | 704 ++--- .../dataStructures/moench04CtbZmqData.h | 465 ++-- .../dataStructures/slsDetectorData.h | 649 ++--- .../dataStructures/slsReceiverData.h | 397 +-- slsDetectorCalibration/energyCalibration.cpp | 1246 +++++---- slsDetectorCalibration/energyCalibration.h | 683 ++--- slsDetectorCalibration/ghostSummation.h | 82 +- .../interpolatingDetector.h | 436 ++-- .../interpolations/eta2InterpolationBase.h | 713 +++--- .../interpolations/eta3InterpolationBase.h | 468 ++-- .../etaInterpolationAdaptiveBins.h | 481 ++-- .../interpolations/etaInterpolationBase.h | 693 +++-- .../etaInterpolationCleverAdaptiveBins.h | 496 ++-- .../interpolations/etaInterpolationGlobal.h | 135 +- .../interpolations/etaInterpolationPosXY.h | 325 +-- .../etaInterpolationRandomBins.h | 634 +++-- .../interpolations/etaVEL/EtaVEL.cpp | 1198 +++++---- .../interpolations/etaVEL/EtaVEL.h | 227 +- .../etaVEL/etaVELInterpolation.cpp | 204 +- .../etaVEL/etaVELInterpolation.h | 80 +- .../interpolations/linearInterpolation.h | 383 ++- .../interpolations/noInterpolation.h | 144 +- .../interpolations/slsInterpolation.h | 1070 ++++---- .../jungfrauClusterFinder.cpp | 243 +- .../jungfrauInterpolation.cpp | 355 +-- .../jungfrauPhotonCounter.cpp | 668 +++-- .../jungfrauZmqProcess.cpp | 1643 ++++++------ slsDetectorCalibration/moench03CommonMode.h | 85 +- .../moench03GhostSummation.h | 98 +- slsDetectorCalibration/moenchCommonMode.h | 24 +- .../moench03ClusterFinder.cpp | 312 ++- .../moench03Interpolation.cpp | 355 +-- .../moench03NoInterpolation.cpp | 258 +- .../moenchExecutables/moenchPhotonCounter.cpp | 668 +++-- .../moenchExecutables/moenchZmqProcess.cpp | 1588 ++++++------ .../multiThreadedAnalogDetector.h | 1130 ++++---- .../multiThreadedCountingDetector.h | 53 +- .../multiThreadedInterpolatingDetector.h | 168 +- slsDetectorCalibration/pedestalSubtraction.h | 83 +- slsDetectorCalibration/singlePhotonDetector.h | 1207 ++++----- slsDetectorCalibration/single_photon_hit.h | 458 ++-- slsDetectorCalibration/tiffIO.cpp | 123 +- slsDetectorCalibration/tiffIO.h | 39 +- slsReceiverSoftware/src/Listener.h | 3 +- slsSupportLib/include/sls/file_utils.h | 6 +- slsSupportLib/include/sls/versionAPI.h | 18 +- slsSupportLib/src/file_utils.cpp | 13 +- slsSupportLib/src/md5.c | 98 +- slsSupportLib/tests/test-network_utils.cpp | 3 +- 77 files changed, 15998 insertions(+), 15890 deletions(-) diff --git a/slsDetectorCalibration/MovingStat.h b/slsDetectorCalibration/MovingStat.h index d069cc6d0..a183d34e2 100644 --- a/slsDetectorCalibration/MovingStat.h +++ b/slsDetectorCalibration/MovingStat.h @@ -1,167 +1,158 @@ // SPDX-License-Identifier: LGPL-3.0-or-other // Copyright (C) 2021 Contributors to the SLS Detector Package #ifndef MOVINGSTAT_H -#define MOVINGSTAT_H +#define MOVINGSTAT_H #include +class MovingStat { -class MovingStat - { + /** @short approximated moving average structure */ + public: + /** constructor + \param nn number of samples parameter to be used + */ + MovingStat(int nn) : n(nn), m_n(0), m_newM(0), m_newM2(0) {} + // void setPointers(double *me, double *va) {mean=me; var=va;} + /** + clears the moving average number of samples parameter, mean and standard + deviation + */ + void Clear() { + m_n = 0; + m_newM = 0; + m_newM2 = 0; + } - /** @short approximated moving average structure */ - public: - - - /** constructor - \param nn number of samples parameter to be used - */ - MovingStat(int nn) : n(nn), m_n(0), m_newM(0),m_newM2(0) {} - // void setPointers(double *me, double *va) {mean=me; var=va;} - /** - clears the moving average number of samples parameter, mean and standard deviation - */ - void Clear() - { - m_n = 0; - m_newM=0; - m_newM2=0; - } - - /** - clears the moving average number of samples parameter, mean and standard deviation - */ - void Set(double val, double rms=0, int m=-1) - { - if (m>=0) m_n = m; else m_n = n; - m_newM=val*m_n; - SetRMS(rms); - // cout << "set " << val << " " << m << " " << m_n << " " << m_newM << endl; - } - /** - clears the moving average number of samples parameter, mean and standard deviation - */ - void SetRMS(double rms) - { - if (rms<=0) { - if (m_n>0) - m_newM2=m_newM*m_newM/m_n; - else - m_newM2=0; - //m_n=0; - } else { - if (m_n>0) { - m_newM2=(m_n*rms*rms+m_newM*m_newM/m_n); - } else { - m_newM2=(m_n*rms*rms+m_newM*m_newM/n); - m_n=0; - } - } - } - - /** sets number of samples parameter - \param i number of samples parameter to be set - */ - - int SetN(int i) {if (i>=1) n=i; return n;}; - - /** - gets number of samples parameter - \returns actual number of samples parameter - */ - int GetN() {return m_n;}; - - /** calculates the moving average i.e. adds if number of elements is lower than number of samples parameter, pushes otherwise - \param x value to calculate the moving average - */ - inline void Calc(double x) { - if (m_n= 0) + m_n = m; + else + m_n = n; + m_newM = val * m_n; + SetRMS(rms); + // cout << "set " << val << " " << m << " " << m_n << " " << m_newM << + // endl; + } + /** + clears the moving average number of samples parameter, mean and standard + deviation + */ + void SetRMS(double rms) { + if (rms <= 0) { + if (m_n > 0) + m_newM2 = m_newM * m_newM / m_n; + else + m_newM2 = 0; + // m_n=0; + } else { + if (m_n > 0) { + m_newM2 = (m_n * rms * rms + m_newM * m_newM / m_n); + } else { + m_newM2 = (m_n * rms * rms + m_newM * m_newM / n); + m_n = 0; } - - } - - - inline void Push(double x) - { - /** adds the element to the accumulated average and squared mean, while subtracting the current value of the average and squared average - \param x value to push - */ - if (m_n == 0) - { - m_newM = x; - m_newM2 = x*x; - m_n++; - } - else { - m_newM = m_newM + x - m_newM/m_n; - m_newM2 = m_newM2 + x*x - m_newM2/m_n; - } - - } - - /** returns the current number of elements of the moving average - \returns returns the current number of elements of the moving average - */ - int NumDataValues() const - { - return m_n; - } - /** returns the mean, 0 if no elements are inside - \returns returns the mean - */ - inline double Mean() const - { - // cout << "get " << m_n << " " << m_newM << " " << m_newM/m_n << endl; - - - return (m_n > 0) ? m_newM/m_n : 0.0; } + } - /** returns the squared mean, 0 if no elements are inside - \returns returns the squared average - */ - double M2() const - { - return ( (m_n > 1) ? m_newM2/m_n : 0.0 ); - } + /** sets number of samples parameter + \param i number of samples parameter to be set + */ - /** returns the variance, 0 if no elements are inside - \returns returns the variance - */ - inline double Variance() const - { - return (m_n > 0) ? m_newM2/m_n-m_newM/m_n*m_newM/m_n : 0.0; - } - - /** returns the standard deviation, 0 if no elements are inside - \returns returns the standard deviation - */ - inline double StandardDeviation() const - { - - return sqrt(Variance());// - } - - private: - int n; /**< number of samples parameter */ - int m_n; /**< current number of elements */ - double m_newM; /**< accumulated average */ - double m_newM2; /**< accumulated squared average */ + int SetN(int i) { + if (i >= 1) + n = i; + return n; }; + + /** + gets number of samples parameter + \returns actual number of samples parameter + */ + int GetN() { return m_n; }; + + /** calculates the moving average i.e. adds if number of elements is lower + than number of samples parameter, pushes otherwise \param x value to + calculate the moving average + */ + inline void Calc(double x) { + if (m_n < n) + Add(x); + else + Push(x); + } + /** adds the element to the accumulated average and standard deviation + \param x value to add + */ + inline void Add(double x) { + m_n++; + + if (m_n == 1) { + m_newM = x; + m_newM2 = x * x; + } else { + m_newM = m_newM + x; + m_newM2 = m_newM2 + x * x; + } + } + + inline void Push(double x) { + /** adds the element to the accumulated average and squared mean, while + subtracting the current value of the average and squared average + \param x value to push + */ + if (m_n == 0) { + m_newM = x; + m_newM2 = x * x; + m_n++; + } else { + m_newM = m_newM + x - m_newM / m_n; + m_newM2 = m_newM2 + x * x - m_newM2 / m_n; + } + } + + /** returns the current number of elements of the moving average + \returns returns the current number of elements of the moving average + */ + int NumDataValues() const { return m_n; } + /** returns the mean, 0 if no elements are inside + \returns returns the mean + */ + inline double Mean() const { + // cout << "get " << m_n << " " << m_newM << " " << m_newM/m_n << + // endl; + + return (m_n > 0) ? m_newM / m_n : 0.0; + } + + /** returns the squared mean, 0 if no elements are inside + \returns returns the squared average + */ + double M2() const { return ((m_n > 1) ? m_newM2 / m_n : 0.0); } + + /** returns the variance, 0 if no elements are inside + \returns returns the variance + */ + inline double Variance() const { + return (m_n > 0) ? m_newM2 / m_n - m_newM / m_n * m_newM / m_n : 0.0; + } + + /** returns the standard deviation, 0 if no elements are inside + \returns returns the standard deviation + */ + inline double StandardDeviation() const { + + return sqrt(Variance()); // + } + + private: + int n; /**< number of samples parameter */ + int m_n; /**< current number of elements */ + double m_newM; /**< accumulated average */ + double m_newM2; /**< accumulated squared average */ +}; #endif diff --git a/slsDetectorCalibration/RunningStat.h b/slsDetectorCalibration/RunningStat.h index aca704097..39d447321 100644 --- a/slsDetectorCalibration/RunningStat.h +++ b/slsDetectorCalibration/RunningStat.h @@ -1,57 +1,37 @@ // SPDX-License-Identifier: LGPL-3.0-or-other // Copyright (C) 2021 Contributors to the SLS Detector Package - class RunningStat - { - public: - RunningStat() : m_n(0) {} +class RunningStat { + public: + RunningStat() : m_n(0) {} - void Clear() - { - m_n = 0; + void Clear() { m_n = 0; } + + void Push(double x) { + m_n++; + + // See Knuth TAOCP vol 2, 3rd edition, page 232 + if (m_n == 1) { + m_oldM = m_newM = x; + m_oldS = 0.0; + } else { + m_newM = m_oldM + (x - m_oldM) / m_n; + m_newS = m_oldS + (x - m_oldM) * (x - m_newM); + + // set up for next iteration + m_oldM = m_newM; + m_oldS = m_newS; } + } - void Push(double x) - { - m_n++; + int NumDataValues() const { return m_n; } - // See Knuth TAOCP vol 2, 3rd edition, page 232 - if (m_n == 1) - { - m_oldM = m_newM = x; - m_oldS = 0.0; - } - else - { - m_newM = m_oldM + (x - m_oldM)/m_n; - m_newS = m_oldS + (x - m_oldM)*(x - m_newM); - - // set up for next iteration - m_oldM = m_newM; - m_oldS = m_newS; - } - } + double Mean() const { return (m_n > 0) ? m_newM : 0.0; } - int NumDataValues() const - { - return m_n; - } + double Variance() const { return ((m_n > 1) ? m_newS / (m_n - 1) : 0.0); } - double Mean() const - { - return (m_n > 0) ? m_newM : 0.0; - } + double StandardDeviation() const { return sqrt(Variance()); } - double Variance() const - { - return ( (m_n > 1) ? m_newS/(m_n - 1) : 0.0 ); - } - - double StandardDeviation() const - { - return sqrt( Variance() ); - } - - private: - int m_n; - double m_oldM, m_newM, m_oldS, m_newS; - }; + private: + int m_n; + double m_oldM, m_newM, m_oldS, m_newS; +}; diff --git a/slsDetectorCalibration/Stat.h b/slsDetectorCalibration/Stat.h index 6521aa933..877d6a13a 100644 --- a/slsDetectorCalibration/Stat.h +++ b/slsDetectorCalibration/Stat.h @@ -1,47 +1,33 @@ // SPDX-License-Identifier: LGPL-3.0-or-other // Copyright (C) 2021 Contributors to the SLS Detector Package -class Stat - { +class Stat { public: - - Stat() : n(0), m(0.), m2(0.) {} - - void Clear() - { - n = 0; - m=0; - m2=0; + Stat() : n(0), m(0.), m2(0.) {} + + void Clear() { + n = 0; + m = 0; + m2 = 0; } - - void Push(double x) - { - - m+=x; - m2+=x*x; - n++; - } - int NumDataValues() const - { - return n; - } + void Push(double x) { - double Mean() const - { - return (n > 0) ? m/n : 0.0; - } + m += x; + m2 += x * x; + n++; + } - double Variance() const - { - return ( (n >0 ) ? (m2/n-m*m/(n*n)) : 0.0 ); - } + int NumDataValues() const { return n; } - double StandardDeviation() const - { - return sqrt( Variance() ); - } + double Mean() const { return (n > 0) ? m / n : 0.0; } - private: - int n; - double m, m2; - }; + double Variance() const { + return ((n > 0) ? (m2 / n - m * m / (n * n)) : 0.0); + } + + double StandardDeviation() const { return sqrt(Variance()); } + + private: + int n; + double m, m2; +}; diff --git a/slsDetectorCalibration/analogDetector.h b/slsDetectorCalibration/analogDetector.h index c80ab60be..9453172fa 100644 --- a/slsDetectorCalibration/analogDetector.h +++ b/slsDetectorCalibration/analogDetector.h @@ -1,483 +1,506 @@ // SPDX-License-Identifier: LGPL-3.0-or-other // Copyright (C) 2021 Contributors to the SLS Detector Package #ifndef ANALOGDETECTOR_H -#define ANALOGDETECTOR_H +#define ANALOGDETECTOR_H //#include -#include -#include "slsDetectorData.h" -#include "pedestalSubtraction.h" #include "commonModeSubtractionNew.h" #include "ghostSummation.h" -#include "tiffIO.h" +#include "pedestalSubtraction.h" +#include "slsDetectorData.h" #include "slsInterpolation.h" - +#include "tiffIO.h" +#include #ifdef ROOTSPECTRUM -#include -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include #endif using namespace std; #ifndef FRAMEMODE_DEF #define FRAMEMODE_DEF -/** -enum to define the flags of the data set, which are needed to seect the type of processing it should undergo: frame, pedestal, flat +/** +enum to define the flags of the data set, which are needed to seect the type of +processing it should undergo: frame, pedestal, flat */ enum frameMode { eFrame, ePedestal, eFlat, eRaw }; -/** +/** enum to define the detector mode */ enum detectorMode { eAnalog, ePhotonCounting, eInterpolating }; #endif - template class analogDetector { - /** @short class to perform pedestal subtraction etc. for an analog detector */ + /** @short class to perform pedestal subtraction etc. for an analog detector + */ - public: + public: + /** - - - /** - - Constructor (no error checking if datasize and offsets are compatible!) - \param d detector data structure to be used - if null it is assumed that the data are in ordered ip=iy*nx+ix - \param sign is the sign of the data - \param nped number of samples for pedestal averaging - \param cm common mode subtraction algorithm, if any. Defaults to NULL i.e. none - \param nnx detector size in x - must be specified if no data structure is defined, otherwise defaults to the size of the data structure. - \param nny detector size in y - must be specified if no data structure is defined, otherwise defaults to the size of the data structure. - \param gm pointer to tha gain map matrix + Constructor (no error checking if datasize and offsets are compatible!) + \param d detector data structure to be used - if null it is assumed that + the data are in ordered ip=iy*nx+ix \param sign is the sign of the data + \param nped number of samples for pedestal averaging + \param cm common mode subtraction algorithm, if any. Defaults to NULL + i.e. none \param nnx detector size in x - must be specified if no data + structure is defined, otherwise defaults to the size of the data + structure. \param nny detector size in y - must be specified if no data + structure is defined, otherwise defaults to the size of the data + structure. \param gm pointer to tha gain map matrix - */ - - - analogDetector(slsDetectorData *d, int sign=1, - commonModeSubtraction *cm=NULL, int nped=1000, int nnx=-1, int nny=-1, double *gm=NULL, ghostSummation *gs=NULL) : det(d), nx(nnx), ny(nny), stat(NULL), cmSub(cm), dataSign(sign), iframe(-1), gmap(gm), ghSum(gs), id(0) { - - if (det) - det->getDetectorSize(nx,ny); - - stat=new pedestalSubtraction*[ny]; - /* pedMean=new double*[ny]; */ - /* pedVariance=new double*[ny]; */ - for (int i=0; idet; - nx=orig->nx; - ny=orig->ny; - dataSign=orig->dataSign; - iframe=orig->iframe; - gmap=orig->gmap; - // cmSub=orig->cmSub; - id=orig->id; - xmin=orig->xmin; - xmax=orig->xmax; - ymin=orig->ymin; - ymax=orig->ymax; - thr=orig->thr; - // nSigma=orig->nSigma; - fMode=orig->fMode; - myFile=orig->myFile; - - - stat=new pedestalSubtraction*[ny]; - /* pedMean=new double*[ny]; */ - /* pedVariance=new double*[ny]; */ - for (int i=0; iSetNPedestals(); - //cout << nped << " " << orig->getPedestal(ix,iy) << orig->getPedestalRMS(ix,iy) << endl; - for (iy=0; iygetPedestal(ix,iy),orig->getPedestalRMS(ix,iy),orig->GetNPedestals(ix,iy)); - /* if (ix==50 && iy==50) */ - /* cout << "clone ped " << " " << ix << " " << iy << " " << getPedestal(ix,iy) << " " << getPedestalRMS(ix,iy)<< " " << GetNPedestals(ix,iy) << endl; */ - } - } - image=new int[nx*ny]; -#ifdef ROOTSPECTRUM - hs=(TH2F*)(orig->hs)->Clone();//new TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); -#ifdef ROOTCLUST - hs3=(TH2F*)(orig->hs3)->Clone();//new TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); - hs5=(TH2F*)(orig->hs5)->Clone();//new TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); - hs7=(TH2F*)(orig->hs7)->Clone();//new TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); - hs9=(TH2F*)(orig->hs9)->Clone();//new TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); -#endif -#endif - if (orig->cmSub) { - cmSub=(orig->cmSub)->Clone(); - cout <<"cloning cm" << endl; - } - else cmSub=NULL; - if (orig->ghSum) { - ghSum=(orig->ghSum)->Clone(); - cout <<"cloning gs" << endl; - } - else ghSum=NULL; - } - - - /** - clone. Must be virtual! - \returns a clone of the original analog detector - */ - virtual analogDetector *Clone() { - return new analogDetector(this); - } - - /** - Gives an id to the structure. For debugging purposes in case of multithreading. - \param i is to be set - \returns current id - */ - int setId(int i){id=i; return id;}; - - /** - Returns id of the structure. For debugging purposes in case of multithreading. - \returns current id - */ - int getId() {return id; }; - /** - Returns data size of the detector data structure - \returns data size of the detector data structurein bytes - */ - int getDataSize(){return det->getDataSize();}; - /** - Returns data size of the detector image matrix - \param nnx reference to image size in x - \param nny reference to image size in y - \param nns reference to number of subpixels for interpolating detector, will always be 1 in this case - \returns number of pixels of the detector image - */ - virtual int getImageSize(int &nnx, int &nny, int &nnsx, int &nnsy){nnx=nx; nny=ny; nnsx=1; nnsy=1; return nx*ny;}; - /** - Returns data size of the detector image matrix - \param nnx reference to pixel size in x - \param nny reference to pixel size in y - \returns number of pixels of the detector image - */ - virtual int getDetectorSize(int &nnx, int &nny){nnx=nx; nny=ny; return nx*ny;}; - - /** - set gain map - \param gm pointer to gain map matrix to be set - NULL unsets - \returns pointer to current gain map - */ - double *setGainMap(double *gm) {gmap=gm; return gmap;}; - - /** - return gain map - \returns pointer to current gain map - */ - double *getGainMap() {return gmap;}; - /** - reads a 32 bit tiff file of the size of the detector and sets its values as gain map for the detector. If file does not exist returns NULL, but does not change gainmap compared to previous settings. - \param imgname complete name of the file containing the gain map data - \returns pointer to current gain map is file reading succeeded, NULL is file reading didn't work. - */ - double *readGainMap(const char * imgname) { - uint32_t nnx, nny; - float *gm=ReadFromTiff( imgname, nny, nnx); - if (gm) { - if (gmap) delete [] gmap; - gmap=new double[nnx*nny]; - for (iy=0; iyClear(); -#ifdef ROOTSPECTRUM - hs->Reset(); -#ifdef ROOTCLUST - hs3->Reset();//new TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); - hs5->Reset();//new TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); - hs7->Reset();//new TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); - hs9->Reset();//new TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); -#endif -#endif - }; - - /** resets the commonModeSubtraction and increases the frame index */ - virtual void newFrame(){iframe++; if (cmSub) cmSub->newFrame(); det->newFrame();}; - - /** resets the commonModeSubtraction and increases the frame index */ - virtual void newFrame(char *data){ - iframe++; - if (cmSub) cmSub->newFrame(); - det->newFrame(); - // det->getData(data); - calcGhost(data); - // cout << getId() << " Calc ghost " << getGhost(15,15) << endl; - }; - - - /** sets the commonModeSubtraction algorithm to be used - \param cm commonModeSubtraction algorithm to be used (NULL unsets) - \returns pointer to the actual common mode subtraction algorithm */ - commonModeSubtraction *setCommonModeSubtraction(commonModeSubtraction *cm) {cmSub=cm; return cmSub;}; -/** - gets the commonModeSubtraction algorithm to be used - \returns pointer to the actual common mode subtraction algorithm + + analogDetector(slsDetectorData *d, int sign = 1, + commonModeSubtraction *cm = NULL, int nped = 1000, + int nnx = -1, int nny = -1, double *gm = NULL, + ghostSummation *gs = NULL) + : det(d), nx(nnx), ny(nny), stat(NULL), cmSub(cm), dataSign(sign), + iframe(-1), gmap(gm), ghSum(gs), id(0) { + + if (det) + det->getDetectorSize(nx, ny); + + stat = new pedestalSubtraction *[ny]; + /* pedMean=new double*[ny]; */ + /* pedVariance=new double*[ny]; */ + for (int i = 0; i < ny; i++) { + stat[i] = new pedestalSubtraction[nx]; + /* pedMean[i]=new double[nx]; */ + /* pedVariance[i]=new double[nx]; */ + for (ix = 0; ix < nx; ++ix) { + stat[i][ix].SetNPedestals(nped); + /* stat[i][ix].setPointers(&(pedMean[iy][ix]),&(pedVariance[iy][ix])); + */ + } + } + image = new int[nx * ny]; + xmin = 0; + xmax = nx; + ymin = 0; + ymax = ny; + fMode = ePedestal; + thr = 0; + myFile = NULL; +#ifdef ROOTSPECTRUM + hs = new TH2F("hs", "hs", 2000, -100, 10000, nx * ny, -0.5, + nx * ny - 0.5); +#ifdef ROOTCLUST + hs3 = new TH2F("hs3", "hs3", 2000, -100, 3 * 3 * 10000, nx * ny, -0.5, + nx * ny - 0.5); + hs5 = new TH2F("hs5", "hs5", 2000, -100, 5 * 5 * 10000, nx * ny, -0.5, + nx * ny - 0.5); + hs7 = new TH2F("hs7", "hs7", 2000, -100, 7 * 7 * 10000, nx * ny, -0.5, + nx * ny - 0.5); + hs9 = new TH2F("hs9", "hs9", 2000, -100, 9 * 9 * 10000, nx * ny, -0.5, + nx * ny - 0.5); +#endif +#endif + }; + /** + destructor. Deletes the pdestalSubtraction array and the image */ - commonModeSubtraction *getCommonModeSubtraction() {return cmSub;}; + virtual ~analogDetector() { + for (int i = 0; i < ny; i++) { + delete[] stat[i]; + /* delete [] pedMean[i]; */ + /* delete [] pedVariance[i]; */ + }; + /* delete [] pedMean; */ + /* delete [] pedVariance; */ + delete[] stat; + delete[] image; +#ifdef ROOTSPECTRUM + delete hs; +#ifdef ROOTCLUST + delete hs3; + delete hs5; + delete hs7; + delete hs9; +#endif +#endif + }; + /** + constructor cloning another analog detector + \param orig analog Detector structure to be cloned + */ + analogDetector(analogDetector *orig) { + /* copy construction from orig*/ + det = orig->det; + nx = orig->nx; + ny = orig->ny; + dataSign = orig->dataSign; + iframe = orig->iframe; + gmap = orig->gmap; + // cmSub=orig->cmSub; + id = orig->id; + xmin = orig->xmin; + xmax = orig->xmax; + ymin = orig->ymin; + ymax = orig->ymax; + thr = orig->thr; + // nSigma=orig->nSigma; + fMode = orig->fMode; + myFile = orig->myFile; - ghostSummation *getGhostSummation(){return ghSum;}; - ghostSummation *setGhostSummation(ghostSummation *gs){ghSum=gs; return ghSum;}; + stat = new pedestalSubtraction *[ny]; + /* pedMean=new double*[ny]; */ + /* pedVariance=new double*[ny]; */ + for (int i = 0; i < ny; i++) { + stat[i] = new pedestalSubtraction[nx]; + /* pedMean[i]=new double[nx]; */ + /* pedVariance[i]=new double[nx]; */ + } + int nped = orig->SetNPedestals(); + // cout << nped << " " << orig->getPedestal(ix,iy) << + // orig->getPedestalRMS(ix,iy) << endl; + for (iy = 0; iy < ny; ++iy) { + for (ix = 0; ix < nx; ++ix) { + // stat[iy][ix].setPointers(&(pedMean[iy][ix]),&(pedVariance[iy][ix])); + stat[iy][ix].SetNPedestals(nped); + setPedestal(ix, iy, orig->getPedestal(ix, iy), + orig->getPedestalRMS(ix, iy), + orig->GetNPedestals(ix, iy)); + /* if (ix==50 && iy==50) */ + /* cout << "clone ped " << " " << ix << " " << iy << " " << + * getPedestal(ix,iy) << " " << getPedestalRMS(ix,iy)<< " " << + * GetNPedestals(ix,iy) << endl; */ + } + } + image = new int[nx * ny]; +#ifdef ROOTSPECTRUM + hs = + (TH2F *)(orig->hs) + ->Clone(); // new + // TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); +#ifdef ROOTCLUST + hs3 = + (TH2F *)(orig->hs3) + ->Clone(); // new + // TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); + hs5 = + (TH2F *)(orig->hs5) + ->Clone(); // new + // TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); + hs7 = + (TH2F *)(orig->hs7) + ->Clone(); // new + // TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); + hs9 = + (TH2F *)(orig->hs9) + ->Clone(); // new + // TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); +#endif +#endif + if (orig->cmSub) { + cmSub = (orig->cmSub)->Clone(); + cout << "cloning cm" << endl; + } else + cmSub = NULL; + if (orig->ghSum) { + ghSum = (orig->ghSum)->Clone(); + cout << "cloning gs" << endl; + } else + ghSum = NULL; + } + /** + clone. Must be virtual! + \returns a clone of the original analog detector + */ + virtual analogDetector *Clone() { return new analogDetector(this); } + + /** + Gives an id to the structure. For debugging purposes in case of + multithreading. \param i is to be set \returns current id + */ + int setId(int i) { + id = i; + return id; + }; + + /** + Returns id of the structure. For debugging purposes in case of + multithreading. \returns current id + */ + int getId() { return id; }; + /** + Returns data size of the detector data structure + \returns data size of the detector data structurein bytes + */ + int getDataSize() { return det->getDataSize(); }; + /** + Returns data size of the detector image matrix + \param nnx reference to image size in x + \param nny reference to image size in y + \param nns reference to number of subpixels for interpolating detector, + will always be 1 in this case \returns number of pixels of the detector + image + */ + virtual int getImageSize(int &nnx, int &nny, int &nnsx, int &nnsy) { + nnx = nx; + nny = ny; + nnsx = 1; + nnsy = 1; + return nx * ny; + }; + /** + Returns data size of the detector image matrix + \param nnx reference to pixel size in x + \param nny reference to pixel size in y + \returns number of pixels of the detector image + */ + virtual int getDetectorSize(int &nnx, int &nny) { + nnx = nx; + nny = ny; + return nx * ny; + }; + + /** + set gain map + \param gm pointer to gain map matrix to be set - NULL unsets + \returns pointer to current gain map + */ + double *setGainMap(double *gm) { + gmap = gm; + return gmap; + }; + + /** + return gain map + \returns pointer to current gain map + */ + double *getGainMap() { return gmap; }; + /** + reads a 32 bit tiff file of the size of the detector and sets its values + as gain map for the detector. If file does not exist returns NULL, but + does not change gainmap compared to previous settings. \param imgname + complete name of the file containing the gain map data \returns pointer + to current gain map is file reading succeeded, NULL is file reading + didn't work. + */ + double *readGainMap(const char *imgname) { + uint32_t nnx, nny; + float *gm = ReadFromTiff(imgname, nny, nnx); + if (gm) { + if (gmap) + delete[] gmap; + gmap = new double[nnx * nny]; + for (iy = 0; iy < nny; ++iy) { + for (ix = 0; ix < nnx; ++ix) { + gmap[iy * nnx + ix] = gm[iy * nnx + ix]; + // cout << gmap[iy*nnx+ix] << " " ; + } + } + return gmap; + } + return NULL; + } + /** + writes a 32 bit tiff file of the size of the detector and contaning the + gain map value, if any. If file doesn'e exist or gainmap is undefined, + does not do anything. \param imgname complete name of the file to be + written \returns NULL if file writing didn't succeed, else a pointer + */ + void *writeGainMap(const char *imgname) { + float *gm = NULL; + void *ret; + if (gmap) { + gm = new float[nx * ny]; + for (iy = 0; iy < ny; ++iy) { + for (ix = 0; ix < nx; ++ix) { + gm[iy * nx + ix] = gmap[iy * nx + ix]; + } + } + ret = WriteToTiff(gm, imgname, ny, nx); + delete[] gm; + } + return ret; + } + + /** resets the pedestalSubtraction array, the commonModeSubtraction and the + * image data*/ + + virtual void newDataSet() { + iframe = -1; + for (iy = 0; iy < ny; ++iy) + for (ix = 0; ix < nx; ++ix) { + stat[iy][ix].Clear(); + image[iy * nx + ix] = 0; + } + if (cmSub) + cmSub->Clear(); +#ifdef ROOTSPECTRUM + hs->Reset(); +#ifdef ROOTCLUST + hs3->Reset(); // new + // TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); + hs5->Reset(); // new + // TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); + hs7->Reset(); // new + // TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); + hs9->Reset(); // new + // TH2F("hs","hs",(orig->hs)-getNbins,-500,9500,nx*ny,-0.5,nx*ny-0.5); +#endif +#endif + }; + + /** resets the commonModeSubtraction and increases the frame index */ + virtual void newFrame() { + iframe++; + if (cmSub) + cmSub->newFrame(); + det->newFrame(); + }; + + /** resets the commonModeSubtraction and increases the frame index */ + virtual void newFrame(char *data) { + iframe++; + if (cmSub) + cmSub->newFrame(); + det->newFrame(); + // det->getData(data); + calcGhost(data); + // cout << getId() << " Calc ghost " << getGhost(15,15) << endl; + }; + + /** sets the commonModeSubtraction algorithm to be used + \param cm commonModeSubtraction algorithm to be used (NULL unsets) + \returns pointer to the actual common mode subtraction algorithm + */ + commonModeSubtraction *setCommonModeSubtraction(commonModeSubtraction *cm) { + cmSub = cm; + return cmSub; + }; + /** + gets the commonModeSubtraction algorithm to be used + \returns pointer to the actual common mode subtraction algorithm + */ + commonModeSubtraction *getCommonModeSubtraction() { return cmSub; }; + + ghostSummation *getGhostSummation() { return ghSum; }; + ghostSummation *setGhostSummation(ghostSummation *gs) { + ghSum = gs; + return ghSum; + }; /** sets the sign of the data \param sign 1 means positive values for photons, -1 negative, 0 gets \returns current sign for the data */ - int setDataSign(int sign=0) {if (sign==1 || sign==-1) dataSign=sign; return dataSign;}; + int setDataSign(int sign = 0) { + if (sign == 1 || sign == -1) + dataSign = sign; + return dataSign; + }; - /** adds value to pedestal (and common mode) for the given pixel \param val value to be added \param ix pixel x coordinate \param iy pixel y coordinate - \param cm 1 adds the value to common mod, 0 skips it. Defaults to 0. - not properly implemented + \param cm 1 adds the value to common mod, 0 skips it. Defaults to 0. - + not properly implemented */ - virtual void addToPedestal(double val, int ix, int iy, int cm=0){ - if (ix>=0 && ix=0 && iy0) { - val-= getCommonMode(ix, iy); - } - // cout << val << " " ; - val+=getGhost(ix,iy); - // cout << val ; - // cout << endl; - stat[iy][ix].addToPedestal(val); - /* if (cmSub && cm>0) { */ - /* if (det) if (det->isGood(ix, iy)==0) return; */ - /* cmSub->addToCommonMode(val, ix, iy); */ - /* }; */ - }; + virtual void addToPedestal(double val, int ix, int iy, int cm = 0) { + if (ix >= 0 && ix < nx && iy >= 0 && iy < ny) { + + // cout << val << " " ; + if (cmSub && cm > 0) { + val -= getCommonMode(ix, iy); + } + // cout << val << " " ; + val += getGhost(ix, iy); + // cout << val ; + // cout << endl; + stat[iy][ix].addToPedestal(val); + /* if (cmSub && cm>0) { */ + /* if (det) if (det->isGood(ix, iy)==0) return; */ + /* cmSub->addToCommonMode(val, ix, iy); */ + /* }; */ + }; } - + double getCommonMode(int ix, int iy) { - if (cmSub) { - return cmSub->getCommonMode(ix, iy); - } - return 0; + if (cmSub) { + return cmSub->getCommonMode(ix, iy); + } + return 0; } + virtual void addToCommonMode(char *data) { + // cout << "+"<< getId() << endl; + if (cmSub) { + // cout << "*" << endl; + for (iy = ymin; iy < ymax; ++iy) { + for (ix = xmin; ix < xmax; ++ix) { + // if (getNumpedestals(ix,iy)>0) + // if (det->isGood(ix,iy)) { + addToCommonMode(data, ix, iy); + // cout << ":"; + // } + } + } + // cout << "cm " << getCommonMode(0,0) << " " << getCommonMode(1,0) + // << endl; + } + } - virtual void addToCommonMode(char *data){ - // cout << "+"<< getId() << endl; - if (cmSub) { - //cout << "*" << endl; - for (iy=ymin; iy0) - // if (det->isGood(ix,iy)) { - addToCommonMode(data, ix, iy); - // cout << ":"; - // } - } - } - //cout << "cm " << getCommonMode(0,0) << " " << getCommonMode(1,0) << endl; - } - } - - virtual void addToCommonMode(char *data, int ix, int iy=0){ - // cout <<"."; - if (cmSub) { - //cout <<":"; - if (det) if (det->isGood(ix, iy)==0) return; - if (getNumpedestals(ix,iy)>0){ - double val; - if (det) { - /* if (det->getChannel(data, ix, iy)>=0x3fff) */ - /* cout << ix << " " << iy << " " << det->getChannel(data, ix, iy) <getValue(data, ix, iy)-getPedestal(ix,iy,0)); - } else - val= (((double*)data)[iy*nx+ix]-getPedestal(ix,iy)); - val+=getGhost(ix,iy); - - cmSub->addToCommonMode(val, ix, iy); - //cout << ":"; - } - } - } - /** - gets pedestal (and common mode) - \param ix pixel x coordinate - \param iy pixel y coordinate - \param cm 0 (default) without common mode subtraction, 1 with common mode subtraction (if defined) - \returns pedestal value - */ - virtual double getPedestal (int ix, int iy, int cm=0){ - if (ix>=0 && ix=0 && iy0) { - return stat[iy][ix].getPedestal()+getCommonMode(ix,iy); - //return pedMean[iy][ix]+getCommonMode(ix,iy); - } - //return pedMean[iy][ix]; - return stat[iy][ix].getPedestal(); - } else return -1; - }; - + virtual void addToCommonMode(char *data, int ix, int iy = 0) { + // cout <<"."; + if (cmSub) { + // cout <<":"; + if (det) + if (det->isGood(ix, iy) == 0) + return; + if (getNumpedestals(ix, iy) > 0) { + double val; + if (det) { + /* if (det->getChannel(data, ix, iy)>=0x3fff) */ + /* cout << ix << " " << iy << " " << det->getChannel(data, + * ix, iy) <getValue(data, ix, iy) - + getPedestal(ix, iy, 0)); + } else + val = + (((double *)data)[iy * nx + ix] - getPedestal(ix, iy)); + val += getGhost(ix, iy); + cmSub->addToCommonMode(val, ix, iy); + // cout << ":"; + } + } + } /** - gets pedestal rms (i.e. noise) - \param ix pixel x coordinate - \param iy pixel y coordinate - \returns pedestal rms - */ - virtual double getPedestalRMS(int ix, int iy){ - double g=1; - if (ix>=0 && ix=0 && iy=0 && ix=0 && iy= 0 && ix < nx && iy >= 0 && iy < ny) { + if (cmSub && cm > 0) { + return stat[iy][ix].getPedestal() + getCommonMode(ix, iy); + // return pedMean[iy][ix]+getCommonMode(ix,iy); + } + // return pedMean[iy][ix]; + return stat[iy][ix].getPedestal(); + } else + return -1; }; /** @@ -486,63 +509,99 @@ template class analogDetector { \param iy pixel y coordinate \returns pedestal rms */ - virtual double* getPedestalRMS(double *ped=NULL){ - if (ped==NULL) { - ped=new double[nx*ny]; - } - for (iy=0; iy= 0 && ix < nx && iy >= 0 && iy < ny) { + if (gmap) { + g = gmap[iy * nx + ix]; + if (g == 0) + g = -1.; + } + // return sqrt(pedVariance[iy][ix])/g; + return stat[iy][ix].getPedestalRMS() / g; // divide by gain? + } + return -1; }; + virtual int getNumpedestals(int ix, int iy) { + if (ix >= 0 && ix < nx && iy >= 0 && iy < ny) + return stat[iy][ix].getNumpedestals(); + return -1; + }; + /** + gets pedestal (and common mode) + \param ix pixel x coordinate + \param iy pixel y coordinate + \param cm 0 (default) without common mode subtraction, 1 with common mode + subtraction (if defined) \returns pedestal value + */ + virtual double *getPedestal(double *ped) { + if (ped == NULL) { + ped = new double[nx * ny]; + } + for (iy = 0; iy < ny; ++iy) { + for (ix = 0; ix < nx; ++ix) { + ped[iy * nx + ix] = stat[iy][ix].getPedestal(); + // cout << ped[iy*nx+ix] << " " ; + } + } + return ped; + }; + /** + gets pedestal rms (i.e. noise) + \param ix pixel x coordinate + \param iy pixel y coordinate + \returns pedestal rms + */ + virtual double *getPedestalRMS(double *ped = NULL) { + if (ped == NULL) { + ped = new double[nx * ny]; + } + for (iy = 0; iy < ny; ++iy) { + for (ix = 0; ix < nx; ++ix) { + ped[iy * nx + ix] = stat[iy][ix].getPedestalRMS(); + } + } + return ped; + }; - - - - - - - - - - /** sets pedestal \param ix pixel x coordinate \param iy pixel y coordinate \param val value to set \param rms rms to be set if any, defaults to 0 - \param m number of pedestal samples to be set or the moving stat structure is any, defaults to 0 + \param m number of pedestal samples to be set or the moving stat + structure is any, defaults to 0 */ - virtual void setPedestal(int ix, int iy, double val, double rms=0, int m=-1){if (ix>=0 && ix=0 && iy= 0 && ix < nx && iy >= 0 && iy < ny) + stat[iy][ix].setPedestal(val, rms, m); + }; + + /** + sets pedestal + \param ix pixel x coordinate + \param iy pixel y coordinate + \param val value to set + \param rms rms to be set if any, defaults to 0 + \param m number of pedestal samples to be set or the moving stat + structure is any, defaults to 0 + */ + virtual void setPedestal(double *ped, double *rms = NULL, int m = -1) { + double rr = 0; + for (iy = ymin; iy < ymax; ++iy) { + for (ix = xmin; ix < xmax; ++ix) { + if (rms) + rr = rms[iy * nx + ix]; + stat[iy][ix].setPedestal(ped[iy * nx + ix], rr, m); + // cout << ix << " " << iy << " " << ped[iy*nx+ix] << " " << + // stat[iy][ix].getPedestal() << endl; + }; + }; } - - - - /** sets pedestal rms @@ -550,754 +609,774 @@ template class analogDetector { \param iy pixel y coordinate \param rms value to set */ - virtual void setPedestalRMS(int ix, int iy, double rms=0){if (ix>=0 && ix=0 && iy= 0 && ix < nx && iy >= 0 && iy < ny) + stat[iy][ix].setPedestalRMS(rms); + }; /** sets pedestal rms for all pixels \param rms pointer to array of pedestal rms */ - virtual void setPedestalRMS(double *rms){ - for (iy=ymin; iycalcGhost(data, ix, iy); - } - -}; - virtual void calcGhost(char *data){if (ghSum) { - ghSum->calcGhost(data); - - // cout << getId() << " @ " << ghSum->getXTalk() << " " << ghSum->getGhost(15,15) << endl; - } - + virtual void calcGhost(char *data, int ix, int iy = 1) { + if (ghSum) { + ghSum->calcGhost(data, ix, iy); + } + }; -}; + virtual void calcGhost(char *data) { + if (ghSum) { + ghSum->calcGhost(data); + // cout << getId() << " @ " << ghSum->getXTalk() << " " << + // ghSum->getGhost(15,15) << endl; + } + }; - virtual double getGhost(int ix, int iy) {if (ghSum) return ghSum->getGhost(ix, iy); return 0;}; + virtual double getGhost(int ix, int iy) { + if (ghSum) + return ghSum->getGhost(ix, iy); + return 0; + }; - /** - write 32bit tiff file with detector image data - \param imgname file name to be written - \returns NULL if file writing didn't succed, otherwise a pointer - */ - virtual void *writeImage(const char * imgname) { - float *gm=NULL; - void *ret; + /** + write 32bit tiff file with detector image data + \param imgname file name to be written + \returns NULL if file writing didn't succed, otherwise a pointer + */ + virtual void *writeImage(const char *imgname) { + float *gm = NULL; + void *ret; #ifdef ROOTSPECTRUM - TH2F *hmap=new TH2F("hmap","hmap",nx, -0.5,nx-0.5, ny, -0.5, ny-0.5); + TH2F *hmap = + new TH2F("hmap", "hmap", nx, -0.5, nx - 0.5, ny, -0.5, ny - 0.5); #endif - gm=new float[nx*ny]; - for (iy=0; iySetBinContent(ix+1, iy+1,image[iy*nx+ix]); + hmap->SetBinContent(ix + 1, iy + 1, image[iy * nx + ix]); #endif - } - } - ret=WriteToTiff(gm, imgname, ny, nx); - delete [] gm; + } + } + ret = WriteToTiff(gm, imgname, ny, nx); + delete[] gm; #ifdef ROOTSPECTRUM - char rootfn[10000]; - sprintf(rootfn,"%s.root",imgname); - TFile *f=new TFile(rootfn,"RECREATE"); - hs->Write("hs"); + char rootfn[10000]; + sprintf(rootfn, "%s.root", imgname); + TFile *f = new TFile(rootfn, "RECREATE"); + hs->Write("hs"); #ifdef ROOTCLUST - hs3->Write("hs3"); - hs5->Write("hs5"); - hs7->Write("hs7"); - hs9->Write("hs9"); -#endif - hmap->Write("hmap"); - + hs3->Write("hs3"); + hs5->Write("hs5"); + hs7->Write("hs7"); + hs9->Write("hs9"); +#endif + hmap->Write("hmap"); - f->Close(); - delete f; - delete hmap; + f->Close(); + delete f; + delete hmap; #endif - return ret; - } -#ifdef ROOTSPECTRUM - TH2F *getSpectrum(){return hs;}; -#endif - /** - write 32bit tiff file containing the pedestals - \param imgname file name to be written - \returns NULL if file writing didn't succed, otherwise a pointer - */ - - virtual void *writePedestals(const char * imgname) { - float *gm=NULL; - void *ret; - gm=new float[nx*ny]; -#ifdef ROOTSPECTRUM - - TH2F *hmap=new TH2F("hmap","hmap",nx, -0.5,nx-0.5, ny, -0.5, ny-0.5); - -#endif - for (iy=0; iygetCommonMode(); */ - /* else */ - gm[iy*nx+ix]=stat[iy][ix].getPedestal(); -#ifdef ROOTSPECTRUM - hmap->SetBinContent(ix+1, iy+1,gm[iy*nx+ix]); -#endif - } + return ret; } - ret=WriteToTiff(gm, imgname, ny, nx); - delete [] gm; - #ifdef ROOTSPECTRUM - char rootfn[10000]; - sprintf(rootfn,"%s.root",imgname); - TFile *f=new TFile(rootfn,"RECREATE"); - hs->Write("hs"); + TH2F *getSpectrum() { return hs; }; +#endif + /** + write 32bit tiff file containing the pedestals + \param imgname file name to be written + \returns NULL if file writing didn't succed, otherwise a pointer + */ + + virtual void *writePedestals(const char *imgname) { + float *gm = NULL; + void *ret; + gm = new float[nx * ny]; +#ifdef ROOTSPECTRUM + + TH2F *hmap = + new TH2F("hmap", "hmap", nx, -0.5, nx - 0.5, ny, -0.5, ny - 0.5); + +#endif + for (iy = 0; iy < ny; ++iy) { + for (ix = 0; ix < nx; ++ix) { + /* if (cmSub) */ + /* gm[iy*nx+ix]=stat[iy][ix].getPedestal()-cmSub->getCommonMode(); + */ + /* else */ + gm[iy * nx + ix] = stat[iy][ix].getPedestal(); +#ifdef ROOTSPECTRUM + hmap->SetBinContent(ix + 1, iy + 1, gm[iy * nx + ix]); +#endif + } + } + ret = WriteToTiff(gm, imgname, ny, nx); + delete[] gm; + +#ifdef ROOTSPECTRUM + char rootfn[10000]; + sprintf(rootfn, "%s.root", imgname); + TFile *f = new TFile(rootfn, "RECREATE"); + hs->Write("hs"); #ifdef ROOTCLUST - hs3->Write("hs3"); - hs5->Write("hs5"); - hs7->Write("hs7"); - hs9->Write("hs9"); + hs3->Write("hs3"); + hs5->Write("hs5"); + hs7->Write("hs7"); + hs9->Write("hs9"); #endif - hmap->Write("hmap"); - f->Close(); - delete f; - delete hmap; + hmap->Write("hmap"); + f->Close(); + delete f; + delete hmap; #endif - return ret; - } - - /** - read 32bit tiff file containing the pedestals - \param imgname file name to be read - \returns 0 if file reading didn't succed, otherwise 1 - */ - int readPedestals(const char * imgname) { - uint32_t nnx, nny; - float *gm=ReadFromTiff( imgname, nny, nnx); - if (nnx>nx) nnx=nx; - if (nny>ny) nny=ny; - - - - if (gm) { - for (iy=0; iynx) nnx=nx; - if (nny>ny) nny=ny; - + /** + read 32bit tiff file containing the pedestals + \param imgname file name to be read + \returns 0 if file reading didn't succed, otherwise 1 + */ + int readPedestals(const char *imgname) { + uint32_t nnx, nny; + float *gm = ReadFromTiff(imgname, nny, nnx); + if (nnx > nx) + nnx = nx; + if (nny > ny) + nny = ny; - if (gm) { - for (iy=0; iy nx) + nnx = nx; + if (nny > ny) + nny = ny; + + if (gm) { + for (iy = 0; iy < nny; ++iy) { + for (ix = 0; ix < nnx; ++ix) { + image[iy * nx + ix] = gm[iy * nx + ix]; + } + } + delete[] gm; + return 1; + } + return 0; + } + /** returns pointer to image data \returns pointer to image data - */ - virtual int *getImage(){return image;}; - /** - write 32bit tiff file containing the pedestals RMS - \param imgname file name to be written - \returns NULL if file writing didn't succed, otherwise a pointer */ - void *writePedestalRMS(const char * imgname) { - float *gm=NULL; - void *ret; - gm=new float[nx*ny]; - for (iy=0; iynx) nnx=nx; - if (nny>ny) nny=ny; - if (gm) { - for (iy=0; iy nx) + nnx = nx; + if (nny > ny) + nny = ny; + if (gm) { + for (iy = 0; iy < nny; ++iy) { + for (ix = 0; ix < nnx; ++ix) { + stat[iy][ix].setPedestalRMS(gm[iy * nx + ix]); + } + } + delete[] gm; + return 1; + } + return 0; } - return 0; - } - - + /** + Adds all the data for each pixels in the selected region of interest to + the pedestal \param data pointer to the data + */ + virtual void addToPedestal(char *data, int cm = 0) { + // cout << "add to pedestal " << endl; + newFrame(data); - /** - Adds all the data for each pixels in the selected region of interest to the pedestal - \param data pointer to the data - */ + // calcGhost(data); - - virtual void addToPedestal(char *data, int cm=0) { - - // cout << "add to pedestal " << endl; - newFrame(data); - - //calcGhost(data); + if (cmSub && cm) { + // cout <<","; + addToCommonMode(data); + } - - if (cmSub && cm) { - // cout <<","; - addToCommonMode(data); - } - - //cout << xmin << " " << xmax << endl; - // cout << ymin << " " << ymax << endl; - for (iy=ymin; iyisGood(ix,iy)) { - // addToPedestal(data,ix,iy,1); - addToPedestal(data,ix,iy,cm); - /* if (ix==50 && iy==50) */ - /* cout<< "*ped* " << id << " " << ix << " " << iy << " " << det->getChannel(data,ix,iy) << " " << stat[iy][ix].getPedestal() << " " << stat[iy][ix].getPedestalRMS() <<" " << stat[iy][ix]. GetNPedestals() << endl; */ - //if (ix==10 && iy==10) - // cout <isGood(ix, iy)) { + // addToPedestal(data,ix,iy,1); + addToPedestal(data, ix, iy, cm); + /* if (ix==50 && iy==50) */ + /* cout<< "*ped* " << id << " " << ix << " " << iy << " " + * << det->getChannel(data,ix,iy) << " " << + * stat[iy][ix].getPedestal() << " " << + * stat[iy][ix].getPedestalRMS() <<" " << stat[iy][ix]. + * GetNPedestals() << endl; */ + // if (ix==10 && iy==10) + // cout <= 0 && xmi <= nx) + xmin = xmi; + if (xma >= 0 && xma <= nx) + xmax = xma; + if (xmax < xmin) { + xmi = xmin; + xmin = xmax; + xmax = xmi; + } - - /** - Sets region of interest in which data should be processed - \param xmi minimum x. if -1 or out of range remains unchanged - \param xma maximum x. if -1 or out of range remains unchanged - \param ymi minimum y. if -1 or out of range remains unchanged - \param yma maximum y. if -1 or out of range remains unchanged - */ - - void setROI(int xmi=-1, int xma=-1, int ymi=-1, int yma=-1) { - if (xmi>=0 && xmi<=nx) xmin=xmi; - if (xma>=0 && xma<=nx) xmax=xma; - if (xmax=0 && ymi<=ny) ymin=ymi; - if (yma>=0 && yma<=ny) ymax=yma; - if (ymax= 0 && ymi <= ny) + ymin = ymi; + if (yma >= 0 && yma <= ny) + ymax = yma; + if (ymax < ymin) { + ymi = ymin; + ymin = ymax; + ymax = ymi; + } #ifdef ROOTSPECTRUM - delete hs; - hs=new TH2F("hs","hs",2000,-100,10000,(xmax-xmin)*(ymax-ymin),-0.5,(xmax-xmin)*(ymax-ymin)-0.5); + delete hs; + hs = new TH2F("hs", "hs", 2000, -100, 10000, + (xmax - xmin) * (ymax - ymin), -0.5, + (xmax - xmin) * (ymax - ymin) - 0.5); #ifdef ROOTCLUST - delete hs3; - hs3=new TH2F("hs3","hs3",2000,-100,3*3*10000,(xmax-xmin)*(ymax-ymin),-0.5,(xmax-xmin)*(ymax-ymin)-0.5); - delete hs5; - hs5=new TH2F("hs5","hs5",2000,-100,5*5*10000,(xmax-xmin)*(ymax-ymin),-0.5,(xmax-xmin)*(ymax-ymin)-0.5); - delete hs7; - hs7=new TH2F("hs7","hs7",2000,-100,7*7*10000,(xmax-xmin)*(ymax-ymin),-0.5,(xmax-xmin)*(ymax-ymin)-0.5); - delete hs9; - hs9=new TH2F("hs9","hs9",2000,-100,9*9*10000,(xmax-xmin)*(ymax-ymin),-0.5,(xmax-xmin)*(ymax-ymin)-0.5); + delete hs3; + hs3 = new TH2F("hs3", "hs3", 2000, -100, 3 * 3 * 10000, + (xmax - xmin) * (ymax - ymin), -0.5, + (xmax - xmin) * (ymax - ymin) - 0.5); + delete hs5; + hs5 = new TH2F("hs5", "hs5", 2000, -100, 5 * 5 * 10000, + (xmax - xmin) * (ymax - ymin), -0.5, + (xmax - xmin) * (ymax - ymin) - 0.5); + delete hs7; + hs7 = new TH2F("hs7", "hs7", 2000, -100, 7 * 7 * 10000, + (xmax - xmin) * (ymax - ymin), -0.5, + (xmax - xmin) * (ymax - ymin) - 0.5); + delete hs9; + hs9 = new TH2F("hs9", "hs9", 2000, -100, 9 * 9 * 10000, + (xmax - xmin) * (ymax - ymin), -0.5, + (xmax - xmin) * (ymax - ymin) - 0.5); #endif #endif - }; - /** - Gets region of interest in which data are processed - \param xmi reference to minimum x. - \param xma reference to maximum x. - \param ymi reference to minimum y. - \param yma reference to maximum y. - */ + /** + Gets region of interest in which data are processed + \param xmi reference to minimum x. + \param xma reference to maximum x. + \param ymi reference to minimum y. + \param yma reference to maximum y. + */ - void getROI(int &xmi, int &xma, int &ymi, int &yma) {xmi=xmin; xma=xmax; ymi=ymin; yma=ymax;}; - - - - - /** - Adds all the data for the selected pixel to the pedestal - \param data pointer to the data - \param ix pixel x coordinate - \param iy pixel y coordinate - */ - - - virtual void addToPedestal(char *data, int ix, int iy, int cm=0) { - - - double val; - if (ix>=0 && ix=0 && iygetValue(data, ix, iy); - else - val=((double*)data)[iy*nx+ix]; - // cout << val << endl; - /* if (ix==10 && iy==10) */ - /* cout << ix << " " << iy << " " << val ; */ - /* if (ix==100 && iy==100) */ - /* cout << ix << " " << iy << " " << val; */ - addToPedestal(val,ix,iy); - // cout << val << endl; - /* if (ix==10 && iy==10) */ - /* cout <<" " << getPedestal(ix,iy)<< endl; */ - /* if (ix==100 && iy==100) */ - /* cout << " " << getPedestal(ix,iy)<< endl; */ - } - return ; - + void getROI(int &xmi, int &xma, int &ymi, int &yma) { + xmi = xmin; + xma = xmax; + ymi = ymin; + yma = ymax; }; - - - /** - Subtracts pedestal from the data array in the region of interest - \param data pointer to the data - \param val pointer where the pedestal subtracted data should be added. If NULL, the internal image is used - \returns pointer to the pedestal subtracted data - */ - // virtual int *subtractPedestal(char *data, int *val=NULL) { - - virtual int *subtractPedestal(char *data, int *val=NULL, int cm=0) { - - newFrame(data); - - if (val==NULL) - val=image;//new double[nx*ny]; - - //calcGhost(data); - for (iy=ymin; iyisGood(ix,iy)) - val[iy*nx+ix]+=subtractPedestal(data, ix, iy,cm); - } - } - return val; + /** + Adds all the data for the selected pixel to the pedestal + \param data pointer to the data + \param ix pixel x coordinate + \param iy pixel y coordinate + */ + + virtual void addToPedestal(char *data, int ix, int iy, int cm = 0) { + + double val; + if (ix >= 0 && ix < nx && iy >= 0 && iy < ny) { + + if (det) + val = dataSign * det->getValue(data, ix, iy); + else + val = ((double *)data)[iy * nx + ix]; + // cout << val << endl; + /* if (ix==10 && iy==10) */ + /* cout << ix << " " << iy << " " << val ; */ + /* if (ix==100 && iy==100) */ + /* cout << ix << " " << iy << " " << val; */ + addToPedestal(val, ix, iy); + // cout << val << endl; + /* if (ix==10 && iy==10) */ + /* cout <<" " << getPedestal(ix,iy)<< endl; */ + /* if (ix==100 && iy==100) */ + /* cout << " " << getPedestal(ix,iy)<< endl; */ + } + return; }; - + /** + Subtracts pedestal from the data array in the region of interest + \param data pointer to the data + \param val pointer where the pedestal subtracted data should be added. + If NULL, the internal image is used \returns pointer to the pedestal + subtracted data + */ + // virtual int *subtractPedestal(char *data, int *val=NULL) { + virtual int *subtractPedestal(char *data, int *val = NULL, int cm = 0) { - /** - Subtracts pedestal from the data for a selected pixel - \param data pointer to the data - \param ix pixel x coordinate - \param iy pixel y coordinate - \returns pedestal subtracted value - */ + newFrame(data); + if (val == NULL) + val = image; // new double[nx*ny]; + // calcGhost(data); - virtual double subtractPedestal(char *data, int ix, int iy=0, int cm=0) { - double g=1.; - double val =0; - if (ix>=0 && ix=0 && iyisGood(ix, iy)) + val[iy * nx + ix] += subtractPedestal(data, ix, iy, cm); + } + } + return val; + }; - if (det) { - /* if (det->getChannel(data, ix, iy)>=0x3fff) */ - /* cout << ix << " " << iy << " " << det->getChannel(data, ix, iy) <getValue(data, ix, iy)-getPedestal(ix,iy,cm))/g; - } else - val= (((double*)data)[iy*nx+ix]-getPedestal(ix,iy))/g; - - //if (val>=0.5*thr) - // cout << val << " " << (dataSign*det->getValue(data, ix, iy)-getPedestal(ix,iy,cm)) << " " << g << " "; + /** + Subtracts pedestal from the data for a selected pixel + \param data pointer to the data + \param ix pixel x coordinate + \param iy pixel y coordinate + \returns pedestal subtracted value + */ - val+=getGhost(ix,iy)/g; + virtual double subtractPedestal(char *data, int ix, int iy = 0, + int cm = 0) { + double g = 1.; + double val = 0; + if (ix >= 0 && ix < nx && iy >= 0 && iy < ny) { + if (gmap) { + g = gmap[iy * nx + ix]; + if (g == 0) + g = -1.; + } + + if (det) { + /* if (det->getChannel(data, ix, iy)>=0x3fff) */ + /* cout << ix << " " << iy << " " << det->getChannel(data, ix, + * iy) <getValue(data, ix, iy) - + getPedestal(ix, iy, cm)) / + g; + } else + val = + (((double *)data)[iy * nx + ix] - getPedestal(ix, iy)) / g; + + // if (val>=0.5*thr) + // cout << val << " " << (dataSign*det->getValue(data, ix, + // iy)-getPedestal(ix,iy,cm)) << " " << g << " "; + + val += getGhost(ix, iy) / g; #ifdef ROOTSPECTRUM - hs->Fill(val,(iy-ymin)*(xmax-xmin)+(ix-xmin)); + hs->Fill(val, (iy - ymin) * (xmax - xmin) + (ix - xmin)); #ifdef ROOTCLUST - double v3=0,v5=0,v7=0,v9=0; - for (int iix=-4; iix<5; i++ix) - for (int iiy=-4; iiy<5; i++iy) { - if (det) - val= (dataSign*det->getValue(data, ix+iix, iy+iiy)-getPedestal(ix+iix,iy+iiy,cm))/g; - else - val= (((double*)data)[(iy+iiy)*nx+ix+iix]-getPedestal(ix+iix,iy+iiy,cm))/g; - - if (iix>-4 && iiy>-4 && iix<4 && iiy<4) { - if (iix>-3 && iiy>-3 && iix<3 && iiy<3){ - if (iix>-2 && iiy>-2 && iix<2 && iiy<2){ - v3+=val; - } - v5+=val; - } - v7+=val; - } - v9+=val; - } - hs3->Fill(v3,(iy-ymin)*(xmax-xmin)+(ix-xmin)); - hs5->Fill(v5,(iy-ymin)*(xmax-xmin)+(ix-xmin)); - hs7->Fill(v7,(iy-ymin)*(xmax-xmin)+(ix-xmin)); - hs9->Fill(v9,(iy-ymin)*(xmax-xmin)+(ix-xmin)); + double v3 = 0, v5 = 0, v7 = 0, v9 = 0; + for (int iix = -4; iix < 5; i++ ix) + for (int iiy = -4; iiy < 5; i++ iy) { + if (det) + val = (dataSign * + det->getValue(data, ix + iix, iy + iiy) - + getPedestal(ix + iix, iy + iiy, cm)) / + g; + else + val = (((double *)data)[(iy + iiy) * nx + ix + iix] - + getPedestal(ix + iix, iy + iiy, cm)) / + g; + + if (iix > -4 && iiy > -4 && iix < 4 && iiy < 4) { + if (iix > -3 && iiy > -3 && iix < 3 && iiy < 3) { + if (iix > -2 && iiy > -2 && iix < 2 && iiy < 2) { + v3 += val; + } + v5 += val; + } + v7 += val; + } + v9 += val; + } + hs3->Fill(v3, (iy - ymin) * (xmax - xmin) + (ix - xmin)); + hs5->Fill(v5, (iy - ymin) * (xmax - xmin) + (ix - xmin)); + hs7->Fill(v7, (iy - ymin) * (xmax - xmin) + (ix - xmin)); + hs9->Fill(v9, (iy - ymin) * (xmax - xmin) + (ix - xmin)); #endif #endif - return val; - } - return val; - }; - + return val; + } + return val; + }; - /** - sets threshold value for conversion into number of photons - \param t threshold to be set - \returns threshold value - */ - double setThreshold(double t){thr=t; return thr;}; - - /** - gets threshold value for conversion into number of photons - \returns threshold value - */ - double getThreshold(){return thr;}; - /** - converts the data into number of photons for the selected pixel - \param data pointer to the data - \param ix pixel x coordinate - \param iy pixel y coordinate - \returns converted number of photons. If no threshold is set, returns gain converted pedestal subtracted data. - */ + /** + sets threshold value for conversion into number of photons + \param t threshold to be set + \returns threshold value + */ + double setThreshold(double t) { + thr = t; + return thr; + }; - int convertToPhotons(char *data, int ix, int iy=0) { - int nph=0; - double v; - if (ix>=0 && ix=0 && iyFill(v,(iy-ymin)*(xmax-xmin)+(ix-xmin)); */ -/* #endif */ - if (thr>0) { - v+=0.5*thr; - nph=v/thr; - - /* if (ix ==10 && iy<20) */ - /* cout << det->getValue(data,ix,iy) << " " << stat[iy][ix].getPedestal() << " " << getCommonMode(ix,iy) << " " << getPedestal(ix,iy,0)<< " " << getPedestal(ix,iy,1) << endl; */ - // cout << subtractPedestal(data,ix,iy,0) << " " << subtractPedestal(data,ix,iy,1) << " " << nph << endl; - if (nph>0) { - //cout << " " << nph << endl; - return nph; - } - return 0; - } - return v; - } - return 0; - }; - - /** - converts the data into number of photons for all pixels - \param data pointer to the data - \param nph pointer where the photons should added. If NULL,the internal image is used - \returns pointer to array containing the number of photons + /** + gets threshold value for conversion into number of photons + \returns threshold value + */ + double getThreshold() { return thr; }; + /** + converts the data into number of photons for the selected pixel + \param data pointer to the data + \param ix pixel x coordinate + \param iy pixel y coordinate + \returns converted number of photons. If no threshold is set, returns gain + converted pedestal subtracted data. */ - virtual int *getNPhotons(char *data, int *nph=NULL) { - - //double val; - if (nph==NULL) - nph=image; - - newFrame(data); - /* cout << fMode << endl; */ - - /* switch(fMode) { */ - /* case eRaw: */ - /* cout << "raw" << endl; */ - /* break; */ - /* default: */ - /* cout << "analog" << endl; */ - /* } */ - //calcGhost(data); - addToCommonMode(data); - for (iy=ymin; iygetChannel(data,ix,iy); - break; - default: - if (det->isGood(ix,iy)) - nph[iy*nx+ix]+=convertToPhotons(data, ix, iy); - } - } - } - return nph; - - } - /** - clears the image array - + int convertToPhotons(char *data, int ix, int iy = 0) { + int nph = 0; + double v; + if (ix >= 0 && ix < nx && iy >= 0 && iy < ny) { + v = subtractPedestal(data, ix, iy, 1); + /* // cout << v << " " ; */ + /* #ifdef ROOTSPECTRUM */ + /* // cout << (iy-ymin)*(xmax-xmin)+(ix-xmin) << endl; */ + /* hs->Fill(v,(iy-ymin)*(xmax-xmin)+(ix-xmin)); */ + /* #endif */ + if (thr > 0) { + v += 0.5 * thr; + nph = v / thr; + + /* if (ix ==10 && iy<20) */ + /* cout << det->getValue(data,ix,iy) << " " << + * stat[iy][ix].getPedestal() << " " << getCommonMode(ix,iy) << + * " " << getPedestal(ix,iy,0)<< " " << getPedestal(ix,iy,1) << + * endl; */ + // cout << subtractPedestal(data,ix,iy,0) << " " << + // subtractPedestal(data,ix,iy,1) << " " << nph << endl; + if (nph > 0) { + // cout << " " << nph << endl; + return nph; + } + return 0; + } + return v; + } + return 0; + }; + + /** + converts the data into number of photons for all pixels + \param data pointer to the data + \param nph pointer where the photons should added. If NULL,the internal + image is used \returns pointer to array containing the number of photons */ - virtual void clearImage(){ - for (iy=0; iygetChannel(data, ix, iy); + break; + default: + if (det->isGood(ix, iy)) + nph[iy * nx + ix] += convertToPhotons(data, ix, iy); + } + } + } + return nph; + } + + /** + clears the image array + + */ + virtual void clearImage() { + for (iy = 0; iy < ny; ++iy) { + for (ix = 0; ix < nx; ++ix) { + image[iy * nx + ix] = 0; + } + } #ifdef ROOTSPECTRUM - //cout << "reset histogram " << endl; - if (hs) - hs->Reset(); + // cout << "reset histogram " << endl; + if (hs) + hs->Reset(); #ifdef ROOTCLUST - if (hs3) - hs3->Reset(); - if (hs5) - hs5->Reset(); - if (hs7) - hs7->Reset(); - if (hs9) - hs9->Reset(); + if (hs3) + hs3->Reset(); + if (hs5) + hs5->Reset(); + if (hs7) + hs7->Reset(); + if (hs9) + hs9->Reset(); #endif - //cout << "done " << endl; + // cout << "done " << endl; #endif - }; + }; /** sets/gets number of samples for moving average pedestal calculation - \param i number of samples to be set (0 or negative gets) - \returns actual number of samples + \param i number of samples to be set (0 or negative gets) + \returns actual number of samples */ - int SetNPedestals(int i=-1) { - int ix=0, iy=0; - if (i>0) - for (iy=0; iy 0) + for (iy = 0; iy < ny; ++iy) + for (ix = 0; ix < nx; ++ix) + stat[iy][ix].SetNPedestals(i); + return stat[0][0].SetNPedestals(); }; - /** gets number of samples for moving average pedestal calculation - \returns actual number of samples - */ + /** gets number of samples for moving average pedestal calculation + \returns actual number of samples + */ int GetNPedestals(int ix, int iy) { - if (ix>=0 && ix=0 && iy= 0 && ix < nx && iy >= 0 && iy < ny) + return stat[iy][ix].GetNPedestals(); + else + return -1; }; - - /** calculates the sum of photons in the specified region of interest. - \param data pointer to the data - \param xmi minimum x for the calculation. If -1 the minimum x of the predefined region of interest is used - \param xma maximum x for the calculation. If -1 the maximum x of the predefined region of interest is used - \param ymi minimum y for the calculation. If -1 the minimum y of the predefined region of interest is used - \param yma maximum y for the calculation. If -1 the maximum y of the predefined region of interest is used - - \returns total number of photons in - */ - virtual int getTotalNumberOfPhotons(char *data, int xmi=-1, int xma=-1, int ymi=-1, int yma=-1) { - int val=0; - if (xmi<0) xmi=xmin; - if (xma<0) xma=xmax; - if (ymi<0) ymi=ymin; - if (yma<0) yma=ymax; - - newFrame(data); - //calcGhost(data); - addToCommonMode(data); - for (iy=ymi; iyisGood(ix,iy)) { - if (ix>=0 && ix=0 && iyisGood(ix, iy)) { + if (ix >= 0 && ix < nx && iy >= 0 && iy < ny) + val += convertToPhotons(data, ix, iy); + } + + return val; }; + /** + calculates the image converted into number of photons. If the frame mode + is pedestal, it also it to the pdedestal subtraction. \param data pointer + to the data to be processed \param val pointer of the data to be added + to. If NULL, the internal image will be used \param pointer to the + processed data \returns + */ - /** - calculates the image converted into number of photons. If the frame mode is pedestal, it also it to the pdedestal subtraction. - \param data pointer to the data to be processed - \param val pointer of the data to be added to. If NULL, the internal image will be used - \param pointer to the processed data - \returns - */ - - virtual void processData(char *data,int *val=NULL) { - switch(fMode) { - case ePedestal: - //cout << "analog ped " << endl; - addToPedestal(data,1); - break; - default: - //cout << "analog frame" << endl; - //subtractPedestal(data); - analogDetector::getNPhotons(data); - } + virtual void processData(char *data, int *val = NULL) { + switch (fMode) { + case ePedestal: + // cout << "analog ped " << endl; + addToPedestal(data, 1); + break; + default: + // cout << "analog frame" << endl; + // subtractPedestal(data); + analogDetector::getNPhotons(data); + } }; // virtual char *getInterpolation(){return NULL;}; - /** sets the current frame mode for the detector - \param f frame mode to be set - - \returns current frame mode - */ - frameMode setFrameMode(frameMode f) {fMode=f; return fMode;}; - - /** gets the current frame mode for the detector - \returns current frame mode - */ - frameMode getFrameMode() {return fMode;}; - + /** sets the current frame mode for the detector + \param f frame mode to be set - - //enum detectorMode { eAnalog, ePhotonCounting, eInterpolating }; - /** sets the current detector mode for the detector - \param f detector mode to be set - \returns current detector mode - */ - detectorMode setDetectorMode(detectorMode f) {dMode=f; return dMode;}; - - /** gets the current detector mode for the detector - \returns current detector mode - */ - detectorMode getDetectorMode() {return dMode;}; - - -/** sets file pointer where to write the clusters to - \param f file pointer - \returns current file pointer -*/ -FILE *setFilePointer(FILE *f){myFile=f; return myFile;}; - -/** gets file pointer where to write the clusters to - \returns current file pointer -*/ -FILE *getFilePointer(){return myFile;}; - - - - - - - - virtual slsInterpolation *getInterpolation(){ - return NULL; + \returns current frame mode + */ + frameMode setFrameMode(frameMode f) { + fMode = f; + return fMode; }; - - virtual slsInterpolation *setInterpolation(slsInterpolation *ii){return NULL;} + /** gets the current frame mode for the detector + \returns current frame mode + */ + frameMode getFrameMode() { return fMode; }; + // enum detectorMode { eAnalog, ePhotonCounting, eInterpolating }; + /** sets the current detector mode for the detector + \param f detector mode to be set + \returns current detector mode + */ + detectorMode setDetectorMode(detectorMode f) { + dMode = f; + return dMode; + }; - - virtual double setNSigma(double n) {return 0;}; - virtual void setEnergyRange(double emi, double ema) {;}; + /** gets the current detector mode for the detector + \returns current detector mode + */ + detectorMode getDetectorMode() { return dMode; }; + /** sets file pointer where to write the clusters to + \param f file pointer + \returns current file pointer + */ + FILE *setFilePointer(FILE *f) { + myFile = f; + return myFile; + }; + /** gets file pointer where to write the clusters to + \returns current file pointer + */ + FILE *getFilePointer() { return myFile; }; + virtual slsInterpolation *getInterpolation() { return NULL; }; + virtual slsInterpolation *setInterpolation(slsInterpolation *ii) { + return NULL; + } + virtual double setNSigma(double n) { return 0; }; + virtual void setEnergyRange(double emi, double ema) { ; }; - - - protected: - + protected: slsDetectorData *det; /**< slsDetectorData to be used */ - int nx; /**< Size of the detector in x direction */ - int ny; /**< Size of the detector in y direction */ - pedestalSubtraction **stat; /**< pedestalSubtraction class */ + int nx; /**< Size of the detector in x direction */ + int ny; /**< Size of the detector in y direction */ + pedestalSubtraction **stat; /**< pedestalSubtraction class */ /* double **pedMean; /\**< pedestalSubtraction class *\/ */ /* double **pedVariance; /\**< pedestalSubtraction class *\/ */ - commonModeSubtraction *cmSub;/**< commonModeSubtraction class */ - int dataSign; /**< sign of the data i.e. 1 if photon is positive, -1 if negative */ - int iframe; /**< frame number (not from file but incremented within the dataset every time newFrame is called */ + commonModeSubtraction *cmSub; /**< commonModeSubtraction class */ + int dataSign; /**< sign of the data i.e. 1 if photon is positive, -1 if + negative */ + int iframe; /**< frame number (not from file but incremented within the + dataset every time newFrame is called */ double *gmap; - ghostSummation *ghSum;/**< ghostSummation class */ + ghostSummation *ghSum; /**< ghostSummation class */ int *image; int id; - //int xmin, xmax, ymin, ymax; int xmin; /**< minimum x of the region of interest */ + // int xmin, xmax, ymin, ymax; int xmin; /**< minimum x of the region of + // interest */ int xmin; /**< minimum x of the region of interest */ int xmax; /**< maximum x of the region of interest */ - int ymin;/**< minimum y of the region of interest */ - int ymax;/**< maximum y of the region of interest */ - double thr; /**< threshold to be used for conversion into number of photons */ - // int nSigma; /**< number of sigma to be used for conversion into number of photons if threshold is undefined */ - frameMode fMode; /**< current detector frame mode */ + int ymin; /**< minimum y of the region of interest */ + int ymax; /**< maximum y of the region of interest */ + double + thr; /**< threshold to be used for conversion into number of photons */ + // int nSigma; /**< number of sigma to be used for conversion into number + // of photons if threshold is undefined */ + frameMode fMode; /**< current detector frame mode */ detectorMode dMode; /**< current detector frame mode */ - FILE *myFile; /**< file pointer to write to */ + FILE *myFile; /**< file pointer to write to */ int ix, iy; #ifdef ROOTSPECTRUM TH2F *hs; diff --git a/slsDetectorCalibration/circularFifo.h b/slsDetectorCalibration/circularFifo.h index cf373d279..c92199315 100644 --- a/slsDetectorCalibration/circularFifo.h +++ b/slsDetectorCalibration/circularFifo.h @@ -1,88 +1,78 @@ // SPDX-License-Identifier: LGPL-3.0-or-other // Copyright (C) 2021 Contributors to the SLS Detector Package #pragma once -/* CircularFifo.h -* Code & platform dependent issues with it was originally -* published at http://www.kjellkod.cc/threadsafecircularqueue -* 2009-11-02 -* @author Kjell Hedstr�m, hedstrom@kjellkod.cc -* modified by the sls detetor group -* */ +/* CircularFifo.h + * Code & platform dependent issues with it was originally + * published at http://www.kjellkod.cc/threadsafecircularqueue + * 2009-11-02 + * @author Kjell Hedstr�m, hedstrom@kjellkod.cc + * modified by the sls detetor group + * */ //#include "sls_receiver_defs.h" +#include #include #include -#include - -typedef double double32_t; -typedef float float32_t; -typedef int int32_t; - +typedef double double32_t; +typedef float float32_t; +typedef int int32_t; /** Circular Fifo (a.k.a. Circular Buffer) -* Thread safe for one reader, and one writer */ -template -class CircularFifo { -public: + * Thread safe for one reader, and one writer */ +template class CircularFifo { + public: + CircularFifo(unsigned int Size) : tail(0), head(0) { + Capacity = Size + 1; + array.resize(Capacity); + sem_init(&data_mutex, 0, 0); + sem_init(&free_mutex, 0, Size); + } + virtual ~CircularFifo() { + sem_destroy(&data_mutex); + sem_destroy(&free_mutex); + } - CircularFifo(unsigned int Size) : tail(0), head(0){ - Capacity = Size + 1; - array.resize(Capacity); - sem_init(&data_mutex,0,0); - sem_init(&free_mutex,0,Size); - } - virtual ~CircularFifo() { - sem_destroy(&data_mutex); - sem_destroy(&free_mutex); - } + bool push(Element *&item_, bool no_block = false); + bool pop(Element *&item_, bool no_block = false); - bool push(Element*& item_, bool no_block=false); - bool pop(Element*& item_, bool no_block=false); + bool isEmpty() const; + bool isFull() const; - bool isEmpty() const; - bool isFull() const; + int getDataValue() const; + int getFreeValue() const; - int getDataValue() const; - int getFreeValue() const; - -private: - std::vector array; - unsigned int tail; // input index - unsigned int head; // output index - unsigned int Capacity; - mutable sem_t data_mutex; - mutable sem_t free_mutex; - unsigned int increment(unsigned int idx_) const; + private: + std::vector array; + unsigned int tail; // input index + unsigned int head; // output index + unsigned int Capacity; + mutable sem_t data_mutex; + mutable sem_t free_mutex; + unsigned int increment(unsigned int idx_) const; }; -template -int CircularFifo::getDataValue() const -{ - int value; - sem_getvalue(&data_mutex, &value); - return value; +template int CircularFifo::getDataValue() const { + int value; + sem_getvalue(&data_mutex, &value); + return value; } -template -int CircularFifo::getFreeValue() const -{ +template int CircularFifo::getFreeValue() const { int value; sem_getvalue(&free_mutex, &value); return value; } - /** Producer only: Adds item to the circular queue. -* If queue is full at 'push' operation no update/overwrite -* will happen, it is up to the caller to handle this case -* -* \param item_ copy by reference the input item -* \param no_block if true, return immediately if fifo is full -* \return whether operation was successful or not */ -template -bool CircularFifo::push(Element*& item_, bool no_block) -{ + * If queue is full at 'push' operation no update/overwrite + * will happen, it is up to the caller to handle this case + * + * \param item_ copy by reference the input item + * \param no_block if true, return immediately if fifo is full + * \return whether operation was successful or not */ +template +bool CircularFifo::push(Element *&item_, bool no_block) { // check for fifo full if (no_block && isFull()) return false; @@ -95,64 +85,57 @@ bool CircularFifo::push(Element*& item_, bool no_block) } /** Consumer only: Removes and returns item from the queue -* If queue is empty at 'pop' operation no retrieve will happen -* It is up to the caller to handle this case -* -* \param item_ return by reference the wanted item -* \param no_block if true, return immediately if fifo is full -* \return whether operation was successful or not */ -template -bool CircularFifo::pop(Element*& item_, bool no_block) -{ + * If queue is empty at 'pop' operation no retrieve will happen + * It is up to the caller to handle this case + * + * \param item_ return by reference the wanted item + * \param no_block if true, return immediately if fifo is full + * \return whether operation was successful or not */ +template +bool CircularFifo::pop(Element *&item_, bool no_block) { // check for fifo empty if (no_block && isEmpty()) return false; - sem_wait(&data_mutex); - item_ = array[head]; - head = increment(head); - sem_post(&free_mutex); - return true; + sem_wait(&data_mutex); + item_ = array[head]; + head = increment(head); + sem_post(&free_mutex); + return true; } /** Useful for testinng and Consumer check of status - * Remember that the 'empty' status can change quickly - * as the Procuder adds more items. - * - * \return true if circular buffer is empty */ -template -bool CircularFifo::isEmpty() const -{ + * Remember that the 'empty' status can change quickly + * as the Procuder adds more items. + * + * \return true if circular buffer is empty */ +template bool CircularFifo::isEmpty() const { return (getDataValue() == 0); } /** Useful for testing and Producer check of status - * Remember that the 'full' status can change quickly - * as the Consumer catches up. - * - * \return true if circular buffer is full. */ -template -bool CircularFifo::isFull() const -{ + * Remember that the 'full' status can change quickly + * as the Consumer catches up. + * + * \return true if circular buffer is full. */ +template bool CircularFifo::isFull() const { return (getFreeValue() == 0); } /** Increment helper function for index of the circular queue -* index is inremented or wrapped -* -* \param idx_ the index to the incremented/wrapped -* \return new value for the index */ -template -unsigned int CircularFifo::increment(unsigned int idx_) const -{ - // increment or wrap - // ================= - // index++; - // if(index == array.lenght) -> index = 0; - // - //or as written below: - // index = (index+1) % array.length - idx_ = (idx_+1) % Capacity; - return idx_; + * index is inremented or wrapped + * + * \param idx_ the index to the incremented/wrapped + * \return new value for the index */ +template +unsigned int CircularFifo::increment(unsigned int idx_) const { + // increment or wrap + // ================= + // index++; + // if(index == array.lenght) -> index = 0; + // + // or as written below: + // index = (index+1) % array.length + idx_ = (idx_ + 1) % Capacity; + return idx_; } - diff --git a/slsDetectorCalibration/commonModeSubtraction.h b/slsDetectorCalibration/commonModeSubtraction.h index 3ab9f896f..b01498d69 100644 --- a/slsDetectorCalibration/commonModeSubtraction.h +++ b/slsDetectorCalibration/commonModeSubtraction.h @@ -5,80 +5,95 @@ #include "MovingStat.h" - - - class commonModeSubtraction { - /** @short class to calculate the common mode of the pedestals based on an approximated moving average*/ + /** @short class to calculate the common mode of the pedestals based on an + * approximated moving average*/ - public: - - /** constructor - \param nn number of samples for the moving average to calculate the average common mode - \param iroi number of regions on which one can calculate the common mode separately. Defaults to 1 i.e. whole detector + public: + /** constructor + \param nn number of samples for the moving average to calculate the + average common mode \param iroi number of regions on which one can + calculate the common mode separately. Defaults to 1 i.e. whole detector - */ - commonModeSubtraction(int nn=1000, int iroi=1) : cmStat(NULL), cmPed(NULL), nCm(NULL), nROI(iroi) {cmStat=new MovingStat[nROI]; for (int i=0; i0) cmStat[i].Calc(cmPed[i]/nCm[i]); - nCm[i]=0; - cmPed[i]=0; - }}; - - /** adds the pixel to the sum of pedestals -- virtual func must be overloaded to define the regions of interest - \param val value to add - \param ix pixel x coordinate - \param iy pixel y coordinate */ - virtual void addToCommonMode(double val, int ix=0, int iy=0) { - (void) ix; (void) iy; - - //if (isc>=0 && isc 0) + cmStat[i].Calc(cmPed[i] / nCm[i]); + nCm[i] = 0; + cmPed[i] = 0; + } + }; + + /** adds the pixel to the sum of pedestals -- virtual func must be + overloaded to define the regions of interest \param val value to add + \param ix pixel x coordinate + \param iy pixel y coordinate */ - virtual double getCommonMode(int ix=0, int iy=0) { - (void) ix; (void) iy; - if (nCm[0]>0) return cmPed[0]/nCm[0]-cmStat[0].Mean(); - return 0;}; - + virtual void addToCommonMode(double val, int ix = 0, int iy = 0) { + (void)ix; + (void)iy; + // if (isc>=0 && isc 0) + return cmPed[0] / nCm[0] - cmStat[0].Mean(); + return 0; + }; - - protected: - MovingStat *cmStat; /**getNRoi(), cs->nsigma); */ /* } */ - + virtual commonModeSubtraction *Clone() { - return new commonModeSubtraction(this->nROI, this->nsigma); + return new commonModeSubtraction(this->nROI, this->nsigma); } - /** clears the moving average and the sum of pedestals calculation - virtual func*/ - virtual void Clear(){ - for (int i=0; i0) cmStat[i].Calc(cmPed[i]/nCm[i]); - nCm[i]=0; - mean[i]=0; - mean2[i]=0; - }}; - - /** adds the pixel to the sum of pedestals -- virtual func must be overloaded to define the regions of interest - \param val value to add - \param ix pixel x coordinate - \param iy pixel y coordinate - */ - virtual void addToCommonMode(double val, int ix=0, int iy=0) { - - int iroi=getROI(ix,iy); - // if (iroi==0) val=100; - // else val=-100; - // if (isc>=0 && isc=0 && iroi0) - return mean[iroi]/nCm[iroi]; - } - return 0; - }; - - /** gets the common mode i.e. the difference between the current average sum of pedestals mode and the average pedestal - \param ix pixel x coordinate - \param iy pixel y coordinate - \return the difference between the current average sum of pedestals and the average pedestal - */ - virtual double getCommonModeRMS(int ix=0, int iy=0) { - int iroi=getROI(ix,iy); - if (iroi>=0 && iroi0) - return sqrt(mean2[iroi]/nCm[iroi]-(mean[iroi]/nCm[iroi])*(mean[iroi]/nCm[iroi])); - } - return 0; + /** adds the average of pedestals to the moving average and reinitializes + * the calculation of the sum of pedestals for all ROIs. - virtual func*/ + virtual void newFrame() { + // cout << "Reset CM" << endl; + for (int i = 0; i < nROI; i++) { + // if (nCm[i]>0) cmStat[i].Calc(cmPed[i]/nCm[i]); + nCm[i] = 0; + mean[i] = 0; + mean2[i] = 0; + } }; - /** - gets the common mode ROI for pixel ix, iy -should be overloaded! + /** adds the pixel to the sum of pedestals -- virtual func must be + overloaded to define the regions of interest \param val value to add + \param ix pixel x coordinate + \param iy pixel y coordinate + */ + virtual void addToCommonMode(double val, int ix = 0, int iy = 0) { + + int iroi = getROI(ix, iy); + // if (iroi==0) val=100; + // else val=-100; + // if (isc>=0 && isc= 0 && iroi < nROI) { + if (nCm[iroi] > 0) + return mean[iroi] / nCm[iroi]; + } + return 0; + }; + + /** gets the common mode i.e. the difference between the current average sum + of pedestals mode and the average pedestal \param ix pixel x coordinate + \param iy pixel y coordinate + \return the difference between the current average sum of pedestals and + the average pedestal + */ + virtual double getCommonModeRMS(int ix = 0, int iy = 0) { + int iroi = getROI(ix, iy); + if (iroi >= 0 && iroi < nROI) { + if (nCm[iroi] > 0) + return sqrt(mean2[iroi] / nCm[iroi] - + (mean[iroi] / nCm[iroi]) * + (mean[iroi] / nCm[iroi])); + } + return 0; + }; + + /** + gets the common mode ROI for pixel ix, iy -should be overloaded! */ - virtual int getROI(int ix, int iy){ (void) ix; (void) iy; return 0;}; - int getNRoi(){return nROI;}; - - protected: - double *mean; /** { + public: + mythen3_01_jctbData(int nch = 64 * 3, int dr = 24, int off = 5) + : slsDetectorData(64 * 3, 1, dr * 8 * nch, NULL, + NULL, NULL), + dynamicRange(dr), serialOffset(off), frameNumber(0), + numberOfCounters(nch){}; - public: - mythen3_01_jctbData( int nch=64*3,int dr=24, int off=5): slsDetectorData(64*3,1,dr*8*nch,NULL,NULL,NULL), dynamicRange(dr), serialOffset(off), frameNumber(0), numberOfCounters(nch) {}; + virtual void getPixel(int ip, int &x, int &y) { + x = -1; + y = -1; + }; - virtual void getPixel(int ip, int &x, int &y) {x=-1; y=-1;}; - - virtual short unsigned int getChannel(char *data, int ix, int iy=0) { - int ret=-1; - short unsigned int *val=mythen03_frame(data,dynamicRange,numberOfCounters,serialOffset); - if (ix>=0 && ix= 0 && ix < numberOfCounters) + ret = val[ix]; + delete[] val; + return ret; + }; + + virtual int getFrameNumber(char *buff) { return frameNumber; }; + + virtual char *findNextFrame(char *data, int &ndata, int dsize) { + ndata = dsize; + return data; } - return data; - } - - virtual short unsigned int **getData(char *ptr, int dsize=-1) { - short unsigned int **val; - val=new short unsigned int*[1]; - val[0]=mythen03_frame(ptr,dynamicRange,nx,serialOffset); - return val; - - } - - virtual short unsigned int* mythen03_frame(char *ptr, int dr=24, int nch=64*3, int off=5) { - // off=0; - //int iarg; - int64_t word, *wp; - short unsigned int* val=new short unsigned int[nch]; - int bit[64]; - int nb=2; - int ioff=0; - int idr=0; - int ib=0; - int iw=0; - int ii=0; - bit[0]=19; - bit[1]=8; - idr=0; - for (ib=0; ib=0) frameNumber=f; return frameNumber; }; - virtual int setDynamicRange(int d=-1) {if (d>0 && d<=24) dynamicRange=d; return dynamicRange;}; - virtual int setSerialOffset(int d=-1) {if (d>=0) serialOffset=d; return serialOffset;}; - virtual int setNumberOfCounters(int d=-1) {if (d>=0) numberOfCounters=d; return numberOfCounters;}; - + virtual short unsigned int *mythen03_frame(char *ptr, int dr = 24, + int nch = 64 * 3, int off = 5) { + // off=0; + // int iarg; + int64_t word, *wp; + short unsigned int *val = new short unsigned int[nch]; + int bit[64]; + int nb = 2; + int ioff = 0; + int idr = 0; + int ib = 0; + int iw = 0; + int ii = 0; + bit[0] = 19; + bit[1] = 8; + idr = 0; + for (ib = 0; ib < nch; ib++) { + val[ib] = 0; + } + wp = (int64_t *)ptr; - private: - - int dynamicRange; - int serialOffset; - int frameNumber; - int numberOfCounters; - - + for (iw = 0; iw < nch / nb; iw) { + word = *wp; + ; + if (ioff < off) { + ioff++; + cout << "*"; + } else { + if (idr < 16) { + for (ib = 0; ib < nb; ib++) { + if (word & (1 << bit[ib])) { + cout << "+"; + val[iw + nch / nb * (ib)] |= (1 << idr); + } else { + cout << "-"; + } + } // end for() + } + idr++; + + if (idr == dr) { + idr = 0; + // cout << dec << " " << iw << " " << val[iw] << " " << + // val[iw+nch/2] << endl; + cout << dec << iw << endl; + iw++; + } // end if() + + } // end else() + wp += 1; + ii++; + } // end for + + cout << "M3.01 Decoded " << ii << " samples" << endl; + cout << "M3.01 Should be " << nch / nb * dr + off << " samples" << endl; + + return val; + } + + virtual int setFrameNumber(int f = 0) { + if (f >= 0) + frameNumber = f; + return frameNumber; + }; + virtual int setDynamicRange(int d = -1) { + if (d > 0 && d <= 24) + dynamicRange = d; + return dynamicRange; + }; + virtual int setSerialOffset(int d = -1) { + if (d >= 0) + serialOffset = d; + return serialOffset; + }; + virtual int setNumberOfCounters(int d = -1) { + if (d >= 0) + numberOfCounters = d; + return numberOfCounters; + }; + + private: + int dynamicRange; + int serialOffset; + int frameNumber; + int numberOfCounters; }; #endif diff --git a/slsDetectorCalibration/dataStructures/Mythen3_02_jctbData.h b/slsDetectorCalibration/dataStructures/Mythen3_02_jctbData.h index deca0d9e5..b9cdd1534 100644 --- a/slsDetectorCalibration/dataStructures/Mythen3_02_jctbData.h +++ b/slsDetectorCalibration/dataStructures/Mythen3_02_jctbData.h @@ -3,130 +3,131 @@ #ifndef MYTHEN302JCTBDATA_H #define MYTHEN302JCTBDATA_H - #include "Mythen3_01_jctbData.h" -//class mythen3_02_jctbData : public slsDetectorData { +// class mythen3_02_jctbData : public slsDetectorData { class mythen3_02_jctbData : public mythen3_01_jctbData { + public: + mythen3_02_jctbData(int nch = 64 * 3, int dr = 24, int off = 5) + : mythen3_01_jctbData(nch, dr, off) + // slsDetectorData(64*3,1,dr*8*nch,NULL,NULL,NULL), dynamicRange(dr), + // serialOffset(off), frameNumber(0), numberOfCounters(nch) + {}; - public: - mythen3_02_jctbData( int nch=64*3,int dr=24, int off=5): mythen3_01_jctbData( nch,dr, off) - //slsDetectorData(64*3,1,dr*8*nch,NULL,NULL,NULL), dynamicRange(dr), serialOffset(off), frameNumber(0), numberOfCounters(nch) - {}; + /* virtual void getPixel(int ip, int &x, int &y) {x=-1; y=-1;}; */ - /* virtual void getPixel(int ip, int &x, int &y) {x=-1; y=-1;}; */ - - /* virtual short unsigned int getChannel(char *data, int ix, int iy=0) { */ - /* int ret=-1; */ - /* short unsigned int *val=mythen03_frame(data,dynamicRange,numberOfCounters,serialOffset); */ - /* if (ix>=0 && ix=0 && ix=0) frameNumber=f; return frameNumber; }; */ - /* virtual int setDynamicRange(int d=-1) {if (d>0 && d<=24) dynamicRange=d; return dynamicRange;}; */ - /* virtual int setSerialOffset(int d=-1) {if (d>=0) serialOffset=d; return serialOffset;}; */ - /* virtual int setNumberOfCounters(int d=-1) {if (d>=0) numberOfCounters=d; return numberOfCounters;}; */ - - - /* private: */ - - /* int dynamicRange; */ - /* int serialOffset; */ - /* int frameNumber; */ - /* int numberOfCounters; */ - - + /* virtual int setFrameNumber(int f=0) {if (f>=0) frameNumber=f; return + * frameNumber; }; */ + /* virtual int setDynamicRange(int d=-1) {if (d>0 && d<=24) dynamicRange=d; + * return dynamicRange;}; */ + /* virtual int setSerialOffset(int d=-1) {if (d>=0) serialOffset=d; return + * serialOffset;}; */ + /* virtual int setNumberOfCounters(int d=-1) {if (d>=0) numberOfCounters=d; + * return numberOfCounters;}; */ + /* private: */ + /* int dynamicRange; */ + /* int serialOffset; */ + /* int frameNumber; */ + /* int numberOfCounters; */ }; #endif diff --git a/slsDetectorCalibration/dataStructures/adcSar2_jctbData.h b/slsDetectorCalibration/dataStructures/adcSar2_jctbData.h index f7dfae566..456f2f9d7 100644 --- a/slsDetectorCalibration/dataStructures/adcSar2_jctbData.h +++ b/slsDetectorCalibration/dataStructures/adcSar2_jctbData.h @@ -3,63 +3,63 @@ #ifndef ADCSAR2_JCTBDATA_H #define ADCSAR2_JCTBDATA_H - class adcSar2_jctbData : public slsDetectorData { + public: + adcSar2_jctbData(int nsamples = 1000) + : slsDetectorData(nsamples, 1, nsamples * 8, NULL, + NULL, NULL){}; - public: - adcSar2_jctbData(int nsamples=1000): slsDetectorData(nsamples,1,nsamples*8,NULL,NULL,NULL){}; + virtual void getPixel(int ip, int &x, int &y) { + x = ip / 8; + y = 1; + }; - virtual void getPixel(int ip, int &x, int &y) {x=ip/8; y=1;}; - - virtual short unsigned int getChannel(char *data, int ix, int iy=0) { - int adcvalue=0; - int vv1= *((int16_t*) (data+8*ix)); - int vv2= *((int16_t*) (data+8*ix+2)); - for (int jj=0;jj<8;jj++){ - adcvalue=adcvalue+ (((vv1>>(jj*2)) & 0x1)<<(jj)); + virtual short unsigned int getChannel(char *data, int ix, int iy = 0) { + int adcvalue = 0; + int vv1 = *((int16_t *)(data + 8 * ix)); + int vv2 = *((int16_t *)(data + 8 * ix + 2)); + for (int jj = 0; jj < 8; jj++) { + adcvalue = adcvalue + (((vv1 >> (jj * 2)) & 0x1) << (jj)); + } + for (int jj = 0; jj < 4; jj++) { + adcvalue = adcvalue + (((vv2 >> (jj * 2)) & 0x1) << (jj + 8)); + } + return adcvalue; + }; + + virtual int getFrameNumber(char *buff) { return frameNumber; }; + + virtual char *findNextFrame(char *data, int &ndata, int dsize) { + ndata = dsize; + return data; } - for (int jj=0;jj<4;jj++){ - adcvalue=adcvalue+ (((vv2>>(jj*2)) & 0x1)<<(jj+8)); + + virtual char *readNextFrame(ifstream &filebin) { + char *data = NULL; + if (filebin.is_open()) { + data = new char[dataSize]; + filebin.read(data, dataSize); + } + return data; } - return adcvalue; - }; - - virtual int getFrameNumber(char *buff) {return frameNumber;}; - - virtual char *findNextFrame(char *data, int &ndata, int dsize) { - ndata=dsize; - return data; - } - - virtual char *readNextFrame(ifstream &filebin) { - char *data=NULL; - if (filebin.is_open()) { - data=new char[dataSize]; - filebin.read(data,dataSize); - } - return data; - } - - /* virtual int **getData(char *ptr, int dsize=-1) { */ - /* int **val; */ - /* val=new int*[1]; */ - /* val[0]=mythen03_frame(ptr,dynamicRange,nx,serialOffset); */ - /* return val; */ - - /* } */ - + /* virtual int **getData(char *ptr, int dsize=-1) { */ + /* int **val; */ + /* val=new int*[1]; */ + /* val[0]=mythen03_frame(ptr,dynamicRange,nx,serialOffset); */ + /* return val; */ - virtual int setFrameNumber(int f=0) {if (f>=0) frameNumber=f; return frameNumber; }; - - private: - - int frameNumber; - - + /* } */ + virtual int setFrameNumber(int f = 0) { + if (f >= 0) + frameNumber = f; + return frameNumber; + }; + private: + int frameNumber; }; #endif diff --git a/slsDetectorCalibration/dataStructures/chiptestBoardData.h b/slsDetectorCalibration/dataStructures/chiptestBoardData.h index c6019a9eb..8ef08d943 100644 --- a/slsDetectorCalibration/dataStructures/chiptestBoardData.h +++ b/slsDetectorCalibration/dataStructures/chiptestBoardData.h @@ -7,85 +7,97 @@ class chiptestBoardData : public slsDetectorData { + public: + /** + chiptestBoard data structure. Works for data acquired using the + chiptestBoard. Inherits and implements slsDetectorData. - public: + Constructor (no error checking if datasize and offsets are compatible!) + \param npx number of pixels in the x direction + \param npy number of pixels in the y direction (1 for strips) + \param nadc number of adcs + \param offset offset at the beginning of the pattern + \param dMap array of size nx*ny storing the pointers to the data in the + dataset (as offset) \param dMask Array of size nx*ny storing the polarity of + the data in the dataset (should be 0 if no inversion is required, 0xffffffff + is inversion is required) \param dROI Array of size nx*ny. The elements are + 1s if the channel is good or in the ROI, 0 is bad or out of the ROI. NULL + (default) means all 1s. - /** - chiptestBoard data structure. Works for data acquired using the chiptestBoard. - Inherits and implements slsDetectorData. + */ + chiptestBoardData(int npx, int npy, int nadc, int offset, int **dMap = NULL, + uint16_t **dMask = NULL, int **dROI = NULL) + : slsDetectorData(npx, npy, nadc * (npx * npy) + offset, dMap, + dMask, dROI), + nAdc(nadc), offSize(offset), + iframe(0){}; // should be? nadc*(npx*npy+offset) - Constructor (no error checking if datasize and offsets are compatible!) - \param npx number of pixels in the x direction - \param npy number of pixels in the y direction (1 for strips) - \param nadc number of adcs - \param offset offset at the beginning of the pattern - \param dMap array of size nx*ny storing the pointers to the data in the dataset (as offset) - \param dMask Array of size nx*ny storing the polarity of the data in the dataset (should be 0 if no inversion is required, 0xffffffff is inversion is required) - \param dROI Array of size nx*ny. The elements are 1s if the channel is good or in the ROI, 0 is bad or out of the ROI. NULL (default) means all 1s. + /** - */ - chiptestBoardData(int npx, int npy, int nadc, int offset, int **dMap=NULL, uint16_t **dMask=NULL, int **dROI=NULL): slsDetectorData(npx, npy, nadc*(npx*npy)+offset, dMap, dMask, dROI), nAdc(nadc), offSize(offset), iframe(0) {}; // should be? nadc*(npx*npy+offset) + Returns the frame number for the given dataset. Virtual func: works for + slsDetectorReceiver data (also for each packet), but can be overloaded. + \param buff pointer to the dataset + \returns frame number - - - /** + */ - Returns the frame number for the given dataset. Virtual func: works for slsDetectorReceiver data (also for each packet), but can be overloaded. - \param buff pointer to the dataset - \returns frame number + virtual int getFrameNumber(char *buff) { + (void)buff; + return iframe; + }; - */ + /** - virtual int getFrameNumber(char *buff){(void)buff; return iframe;}; + Loops over a memory slot until a complete frame is found (i.e. all packets + 0 to nPackets, same frame number). Can be overloaded for different kind of + detectors! \param data pointer to the memory to be analyzed \param ndata + size of frame returned \param dsize size of the memory slot to be analyzed + \returns always return the pointer to data (no frame loss!) + */ - - /** + virtual char *findNextFrame(char *data, int &ndata, int dsize) { + ndata = dsize; + setDataSize(dsize); + return data; + }; - Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). Can be overloaded for different kind of detectors! - \param data pointer to the memory to be analyzed - \param ndata size of frame returned - \param dsize size of the memory slot to be analyzed - \returns always return the pointer to data (no frame loss!) - */ + /** + Loops over a file stream until a complete frame is found (i.e. all packets + 0 to nPackets, same frame number). Can be overloaded for different kind of + detectors! \param filebin input file stream (binary) \returns pointer to + the first packet of the last good frame, NULL if no frame is found or last + frame is incomplete + */ - virtual char *findNextFrame(char *data, int &ndata, int dsize) {ndata=dsize;setDataSize(dsize); return data;}; + virtual char *readNextFrame(ifstream &filebin) { - /** - Loops over a file stream until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). Can be overloaded for different kind of detectors! - \param filebin input file stream (binary) - \returns pointer to the first packet of the last good frame, NULL if no frame is found or last frame is incomplete - */ + int afifo_length = 0; + uint16_t *afifo_cont; - virtual char *readNextFrame(ifstream &filebin) { - - int afifo_length=0; - uint16_t *afifo_cont; - - if (filebin.is_open()) { - if (filebin.read((char*)&afifo_length,sizeof(uint32_t))) { - setDataSize(afifo_length*nAdc*sizeof(uint16_t)); - afifo_cont=new uint16_t[afifo_length*nAdc]; - if (filebin.read((char*)afifo_cont,afifo_length*sizeof(uint16_t)*nAdc)) { - iframe++; - return (char*)afifo_cont; - } else { - delete [] afifo_cont; - return NULL; - } - } else { - return NULL; - } - } - return NULL; - }; - - private: - const int nAdc; /** #include "slsDetectorData.h" +#include class deserializer : public slsDetectorData { + public: + deserializer(std::vector dbl, int nch = 64 * 3, int dr = 24, + int off = 2) + : slsDetectorData(nch, 1, nch * dr * 8 + off * 8, NULL, NULL, + NULL), + dynamicRange(dr), serialOffset(off), frameNumber(0), + numberOfCounters(nch), dbitlist(dbl){}; - public: + deserializer(std::vector dbl, int nch, int dr, int off, int ds) + : slsDetectorData(nch, 1, ds, NULL, NULL, NULL), dynamicRange(dr), + serialOffset(off), frameNumber(0), numberOfCounters(nch), + dbitlist(dbl){}; + virtual void getPixel(int ip, int &x, int &y) { + x = -1; + y = -1; + }; - deserializer( std::vector dbl, int nch=64*3,int dr=24, int off=2): slsDetectorData(nch,1,nch*dr*8+off*8,NULL,NULL,NULL), dynamicRange(dr), serialOffset(off), frameNumber(0), numberOfCounters(nch), dbitlist(dbl) {}; + virtual int getChannel(char *data, int ix, int iy = 0) { + int ret = -1; + if (ix >= 0 && ix < numberOfCounters) { + int *val = deserializeAll(data, dbitlist, dynamicRange, + numberOfCounters, serialOffset); + ret = val[ix]; + delete[] val; + } + return ret; + }; - deserializer( std::vector dbl, int nch,int dr, int off, int ds): slsDetectorData(nch,1,ds,NULL,NULL,NULL), dynamicRange(dr), serialOffset(off), frameNumber(0), numberOfCounters(nch), dbitlist(dbl) {}; + virtual int getFrameNumber(char *buff) { return frameNumber; }; - virtual void getPixel(int ip, int &x, int &y) {x=-1; y=-1;}; - - virtual int getChannel(char *data, int ix, int iy=0) { - int ret=-1; - if (ix>=0 && ix dbl, int dr=24, int nch=64*3, int off=5) { - // off=0; - //int iarg; + virtual int **getData(char *ptr, int dsize = -1) { + int **val; + val = new int *[1]; + val[0] = deserializeAll(ptr, dbitlist, dynamicRange, nx, serialOffset); + return val; + } + static int *deserializeAll(char *ptr, std::vector dbl, int dr = 24, + int nch = 64 * 3, int off = 5) { + // off=0; + // int iarg; - cout <<"** deserializer: " << endl; - cout << "** Number of chans:\t" << nch << endl; - cout << "** Serial Offset:\t" << off << endl; - cout << "** Dynamic range:\t" << dr << endl; - int64_t word, *wp, ww,one=1, bit ; - int* val=new int[nch]; - int ioff=0; - int idr=0; - int ib=0; - int iw=0; - int ii=0; - int ich; - int nb=dbl.size(); - idr=0; - for (ib=0; ib1060) */ - /* cout << iw << " " << idr << " " << ib << " " << bit << " " << ich << " " << val[ich] << " ** " ; */ - bit=dbl[ib]; - ww=one<1060) */ - /* cout << val[ich] << " " << hex << word << " " << ww << " " << (word&(ww)) << dec < dbl, int dr=24, int nch=64*3, int off=5) { - // off=0; - //int iarg; - // int64_t word; - int* val=new int[nch]; - //int ioff=0; - int idr=0; - int ib=0; - int iw=0; - int ii=0; - int ich; - int nb=dbl.size(); - int bit; - char *dval; + for (ib = 0; ib < nb; ib++) { + cout << dbl[ib] << " "; + } + cout << endl; - idr=0; - for (ib=0; ib1060) */ - /* cout << iw << " " << idr << " " << ib << " " << bit << " " << ich << " " << val[ich] << " ** " ; */ - bit=dbl[ib]; - //ioff=off; - idr=0; - for (iw=0; iw<(nch*dr/nb)/8; iw++) { - val[ich]|=(*dval)<=dr) { - idr=0; - ich++; - } - } - ii++; - // ib++; - }//end for - - - return val; - } + for (iw = 0; iw < nw; iw) { + word = *wp; + ; + if (ioff < off) { + ioff++; + // cout <<"*"; + } else { + // if (idr<16) { + // ib=0; + // cout << hex << "*************" << word << endl; + for (ib = 0; ib < nb; ib++) { + // for (const auto &bit : dbl) { + ich = iw + nch * ib / nb; + /* if (ich>1060) */ + /* cout << iw << " " << idr << " " << ib << " " << bit << " + * " << ich << " " << val[ich] << " ** " ; */ + bit = dbl[ib]; + ww = one << bit; + if (word & (ww) && ich < nch) { + // cout << "+" ; + val[ich] |= (1 << idr); + } + /* if (ich>1060) */ + /* cout << val[ich] << " " << hex << word << " " << ww << + * " " << (word&(ww)) << dec <=0) frameNumber=f; return frameNumber; }; - virtual int setDynamicRange(int d=-1) {if (d>0 && d<=24) dynamicRange=d; return dynamicRange;}; - virtual int setSerialOffset(int d=-1) {if (d>=0) serialOffset=d; return serialOffset;}; - virtual int setNumberOfCounters(int d=-1) {if (d>=0) numberOfCounters=d; return numberOfCounters;}; - virtual std::vector setDBitList(std::vector dbl) {dbitlist=dbl; return dbitlist;}; - virtual std::vector getDBitList() {return dbitlist;}; - - - private: - - int dynamicRange; - int serialOffset; - int frameNumber; - int numberOfCounters; - std::vector dbitlist; - + idr++; + } - + if (idr == dr) { + idr = 0; + // cout << dec << " " << iw << " " << val[iw] << " " << + // val[iw+nch/2] << endl; + // cout < dbl, int dr = 24, + int nch = 64 * 3, int off = 5) { + // off=0; + // int iarg; + // int64_t word; + int *val = new int[nch]; + // int ioff=0; + int idr = 0; + int ib = 0; + int iw = 0; + int ii = 0; + int ich; + int nb = dbl.size(); + int bit; + char *dval; + + idr = 0; + for (ib = 0; ib < nch; ib++) { + val[ib] = 0; + } + dval = ptr; + + ib = 0; + ich = 0; + for (ib = 0; ib < nb; ib++) { + // for (const auto &bit : dbl) { + + /* if (ich>1060) */ + /* cout << iw << " " << idr << " " << ib << " " << bit << " " << ich + * << " " << val[ich] << " ** " ; */ + bit = dbl[ib]; + // ioff=off; + idr = 0; + for (iw = 0; iw < (nch * dr / nb) / 8; iw++) { + val[ich] |= (*dval) << idr; + idr += 8; + dval++; + if (idr >= dr) { + idr = 0; + ich++; + } + } + ii++; + // ib++; + } // end for + + return val; + } + + virtual int setFrameNumber(int f = 0) { + if (f >= 0) + frameNumber = f; + return frameNumber; + }; + virtual int setDynamicRange(int d = -1) { + if (d > 0 && d <= 24) + dynamicRange = d; + return dynamicRange; + }; + virtual int setSerialOffset(int d = -1) { + if (d >= 0) + serialOffset = d; + return serialOffset; + }; + virtual int setNumberOfCounters(int d = -1) { + if (d >= 0) + numberOfCounters = d; + return numberOfCounters; + }; + virtual std::vector setDBitList(std::vector dbl) { + dbitlist = dbl; + return dbitlist; + }; + virtual std::vector getDBitList() { return dbitlist; }; + + private: + int dynamicRange; + int serialOffset; + int frameNumber; + int numberOfCounters; + std::vector dbitlist; }; #endif diff --git a/slsDetectorCalibration/dataStructures/gotthardDoubleModuleDataNew.h b/slsDetectorCalibration/dataStructures/gotthardDoubleModuleDataNew.h index 657728724..7e3a33930 100644 --- a/slsDetectorCalibration/dataStructures/gotthardDoubleModuleDataNew.h +++ b/slsDetectorCalibration/dataStructures/gotthardDoubleModuleDataNew.h @@ -1,174 +1,155 @@ // SPDX-License-Identifier: LGPL-3.0-or-other // Copyright (C) 2021 Contributors to the SLS Detector Package #ifndef GOTTHARD2MODULEDATANEW_H -#define GOTTHARD2MODULEDATANEW_H +#define GOTTHARD2MODULEDATANEW_H #include "gotthardModuleDataNew.h" - - - - - - - class gotthardDoubleModuleDataNew : public slsDetectorData { - private: - const int nModules; - const int offset; - int iframe; - + private: + const int nModules; + const int offset; + int iframe; -public: + public: + /** + Implements the slsReceiverData structure for the gotthard read out by a module + i.e. using the slsReceiver (1x1280 pixels, 2 packets 1286 large etc.) \param c + crosstalk parameter for the output buffer + */ + gotthardDoubleModuleDataNew(int off = 24 * 2, int nmod = 2) + : slsDetectorData(1280 * nmod, 1, nmod * (1280 * 2 + off)), + nModules(nmod), offset(off), iframe(0) { - /** - Implements the slsReceiverData structure for the gotthard read out by a module i.e. using the slsReceiver - (1x1280 pixels, 2 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer - - */ - - - gotthardDoubleModuleDataNew(int off=24*2, int nmod=2): slsDetectorData(1280*nmod, 1, nmod*(1280*2+off)), nModules(nmod), offset(off),iframe(0) { - - - - #ifdef BCHIP074_BCHIP075 - cout << "This is a bchip074-bchip075 system " << endl; + cout << "This is a bchip074-bchip075 system " << endl; #endif + uint16_t **dMask; + int **dMap; + int ix, iy; + int ypixels = 1; + int xpixels = 1280 * nmod; + int imod, ipix; + dMask = new uint16_t *[1]; + dMap = new int *[1]; + dMap[0] = new int[1280 * nmod]; + dMask[0] = new uint16_t[1280 * nmod]; - uint16_t **dMask; - int **dMap; - int ix, iy; - int ypixels=1; - int xpixels=1280*nmod; - int imod, ipix; - dMask=new uint16_t*[1]; - dMap=new int*[1]; - dMap[0] = new int[1280*nmod]; - dMask[0] = new uint16_t[1280*nmod]; - - for(int ix=0; ix=128*4 && ibad<128*5) || (ibad>=9*128 && ibad<10*128) || (ibad>=(1280+128*4) && ibad=(1280+128*6))) - dataROIMask[0][ix]=0; + int ibad = ix / 2 + 1280 * imod; + if ((ibad >= 128 * 4 && ibad < 128 * 5) || + (ibad >= 9 * 128 && ibad < 10 * 128) || + (ibad >= (1280 + 128 * 4) && ibad < ibad >= (1280 + 128 * 6))) + dataROIMask[0][ix] = 0; #endif - } + } - setDataMap(dMap); - setDataMask(dMask); + setDataMap(dMap); + setDataMask(dMask); + }; - }; + /** + Returns the frame number for the given dataset. + \param buff pointer to the dataset + \returns frame number - /** + */ - Returns the frame number for the given dataset. - \param buff pointer to the dataset - \returns frame number + int getFrameNumber(char *buff) { + if (offset >= sizeof(sls_detector_header)) + return ((sls_detector_header *)buff)->frameNumber; + return iframe; + }; //*((int*)(buff+5))&0xffffff;}; - */ + /** + gets the packets number (last packet is labelled with 0 and is replaced with + 40) \param buff pointer to the memory \returns packet number + */ - int getFrameNumber(char *buff){if (offset>=sizeof(sls_detector_header)) return ((sls_detector_header*)buff)->frameNumber; return iframe;};//*((int*)(buff+5))&0xffffff;}; + int getPacketNumber(char *buff) { + if (offset >= sizeof(sls_detector_header)) + return ((sls_detector_header *)buff)->packetNumber; + }; - + /** - /** - gets the packets number (last packet is labelled with 0 and is replaced with 40) - \param buff pointer to the memory - \returns packet number + Loops over a memory slot until a complete frame is found (i.e. all + packets 0 to nPackets, same frame number). purely virtual func \param + data pointer to the memory to be analyzed \param ndata reference to the + amount of data found for the frame, in case the frame is incomplete at + the end of the memory slot \param dsize size of the memory slot to be + analyzed \returns pointer to the beginning of the last good frame (might + be incomplete if ndata smaller than dataSize), or NULL if no frame is + found - */ + */ + virtual char *findNextFrame(char *data, int &ndata, int dsize) { + if (dsize < dataSize) + ndata = dsize; + else + ndata = dataSize; + return data; + } - int getPacketNumber(char *buff){if (offset>=sizeof(sls_detector_header))return ((sls_detector_header*)buff)->packetNumber;}; + virtual char *readNextFrame(ifstream &filebin) { + int ff = -1, np = -1; + return readNextFrame(filebin, ff, np); + }; + virtual char *readNextFrame(ifstream &filebin, int &ff) { + int np = -1; + return readNextFrame(filebin, ff, np); + }; + virtual char *readNextFrame(ifstream &filebin, int &ff, int &np) { + char *data = new char[dataSize]; + char *d = readNextFrame(filebin, ff, np, data); + if (d == NULL) { + delete[] data; + data = NULL; + } + return data; + } + virtual char *readNextFrame(ifstream &filebin, int &ff, int &np, + char *data) { + char *retval = 0; + int nd; + int fnum = -1; + np = 0; + int pn; - /** - - Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func - \param data pointer to the memory to be analyzed - \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot - \param dsize size of the memory slot to be analyzed - \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found - - */ - virtual char *findNextFrame(char *data, int &ndata, int dsize){ - if (dsize=0) - fnum=ff; - - if (filebin.is_open()) { - if (filebin.read(data, dataSize) ){ - ff=getFrameNumber(data); - np=getPacketNumber(data); - return data; - } - } - return NULL; - - - - }; - - - + // cout << dataSize << endl; + if (ff >= 0) + fnum = ff; + if (filebin.is_open()) { + if (filebin.read(data, dataSize)) { + ff = getFrameNumber(data); + np = getPacketNumber(data); + return data; + } + } + return NULL; + }; }; - - - - #endif diff --git a/slsDetectorCalibration/dataStructures/gotthardShortModuleData.h b/slsDetectorCalibration/dataStructures/gotthardShortModuleData.h index a546140d2..533f56ddd 100644 --- a/slsDetectorCalibration/dataStructures/gotthardShortModuleData.h +++ b/slsDetectorCalibration/dataStructures/gotthardShortModuleData.h @@ -1,129 +1,105 @@ // SPDX-License-Identifier: LGPL-3.0-or-other // Copyright (C) 2021 Contributors to the SLS Detector Package #ifndef GOTTHARDSHORTMODULEDATA_H -#define GOTTHARDSHORTMODULEDATA_H +#define GOTTHARDSHORTMODULEDATA_H #include "slsReceiverData.h" - - - - - class gotthardShortModuleData : public slsReceiverData { -public: + public: + /** + Implements the slsReceiverData structure for the gotthard short read out by a + module i.e. using the slsReceiver (1x256 pixels, 1 packet 256 large etc.) + \param c crosstalk parameter for the output buffer + */ + gotthardShortModuleData(double c = 0) + : slsReceiverData(xpixels, ypixels, npackets, buffersize), + xtalk(c) { + uint16_t **dMask; + int **dMap; + int ix, iy; + int offset = 2; - /** - Implements the slsReceiverData structure for the gotthard short read out by a module i.e. using the slsReceiver - (1x256 pixels, 1 packet 256 large etc.) - \param c crosstalk parameter for the output buffer + dMask = new uint16_t *[ypixels]; + dMap = new int *[ypixels]; + for (int i = 0; i < ypixels; i++) { + dMap[i] = new int[xpixels]; + dMask[i] = new uint16_t[xpixels]; + } - */ + for (ix = 0; ix < ypixels; ++ix) + for (iy = 0; iy < xpixels; ++iy) + dMask[ix][iy] = 0x0; + for (ix = 0; ix < ypixels; ++ix) + for (iy = 0; iy < xpixels; ++iy) { + dMap[ix][iy] = offset; + offset++; + } - gotthardShortModuleData(double c=0): slsReceiverData(xpixels, ypixels, npackets, buffersize), xtalk(c){ + setDataMap(dMap); + setDataMask(dMask); + }; - uint16_t **dMask; - int **dMap; - int ix, iy; - int offset = 2; + /** - dMask=new uint16_t*[ypixels]; - dMap=new int*[ypixels]; - for (int i = 0; i < ypixels; i++) { - dMap[i] = new int[xpixels]; - dMask[i] = new uint16_t[xpixels]; - } + Returns the frame number for the given dataset. + \param buff pointer to the dataset + \returns frame number - for(ix=0; ix::getValue(data, ix, iy); + else + return slsDetectorData::getValue(data, ix, iy) - + xtalk * + slsDetectorData::getValue(data, ix - 1, iy); + }; - int getFrameNumber(char *buff){ - return (*(int*)buff); - }; + /** sets the output buffer crosstalk correction parameter + \param c output buffer crosstalk correction parameter to be set + \returns current value for the output buffer crosstalk correction parameter + */ + double setXTalk(double c) { + xtalk = c; + return xtalk; + } + /** gets the output buffer crosstalk parameter + \returns current value for the output buffer crosstalk correction parameter + */ + double getXTalk() { return xtalk; } - /** - gets the packets number (last packet is labelled with 0 and is replaced with 40) - \param buff pointer to the memory - \returns packet number - - */ - - int getPacketNumber(char *buff){ - return 1; - }; - - - /** - returns the pixel value as double correcting for the output buffer crosstalk - \param data pointer to the memory - \param ix coordinate in the x direction - \param iy coordinate in the y direction - \returns channel value as double - - */ - double getValue(char *data, int ix, int iy=0) { - //check how it is for gotthard - if (xtalk==0) - return slsDetectorData::getValue(data, ix, iy); - else - return slsDetectorData::getValue(data, ix, iy)-xtalk*slsDetectorData::getValue(data, ix-1, iy); - }; - - - - /** sets the output buffer crosstalk correction parameter - \param c output buffer crosstalk correction parameter to be set - \returns current value for the output buffer crosstalk correction parameter - - */ - double setXTalk(double c) {xtalk=c; return xtalk;} - - - /** gets the output buffer crosstalk parameter - \returns current value for the output buffer crosstalk correction parameter - */ - double getXTalk() {return xtalk;} - - - - - - - -private: - - double xtalk; /** { - - private: - - // int iframe; - public: + private: + // int iframe; + public: + /** + Implements the slsReceiverData structure for the moench02 prototype read + out by a module i.e. using the slsReceiver (160x160 pixels, 40 packets + 1286 large etc.) \param c crosstalk parameter for the output buffer + */ + // moench03T1ZmqDataNew(int ns=5000): slsDetectorData(400, 400, + // ns*32*2+sizeof(int)), nSamples(ns), offset(sizeof(int)), xtalk(0.00021) { + imageZmq16bit(int nnx = 400, int nny = 400) + : slsDetectorData(nnx, nny, 2 * nnx * nny) { + cout << "* " << nx << " " << ny << endl; + int is = 0; + for (int row = 0; row < ny; row++) { + for (int col = 0; col < nx; col++) { + dataMap[row][col] = is * 2; + is++; + } + } + }; + virtual double getValue(char *data, int ix, int iy = 0) { - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer + cout << ix << " " << ix << dataMap[iy][ix] << 2 * nx * ny << " " + << endl; + uint16_t val = getChannel(data, ix, iy) & 0x3fff; + return val; + }; - */ - // moench03T1ZmqDataNew(int ns=5000): slsDetectorData(400, 400, ns*32*2+sizeof(int)), nSamples(ns), offset(sizeof(int)), xtalk(0.00021) { - imageZmq16bit(int nnx=400, int nny=400): slsDetectorData(nnx, nny, 2*nnx*nny) { - cout << "* " << nx << " " << ny << endl; - int is=0; - for (int row=0; row=0) + // fnum=ff; + if (filebin.is_open()) { + if (filebin.read(data, 2 * nx * ny)) { + // iframe++; + // ff=iframe; + return data; + } + } + return NULL; + }; - int getFrameNumber(char *buff){return *((int*)buff);};//*((int*)(buff+5))&0xffffff;}; + virtual char *findNextFrame(char *data, int &ndata, int dsize) { + if (dsize < 2 * nx * ny) + ndata = dsize; + else + ndata = 2 * nx * ny; + return data; + } - - int getPacketNumber(char *buff){return 0;}//((*(((int*)(buff+4))))&0xff)+1;}; - - virtual char *readNextFrame(ifstream &filebin) { - int ff=-1, np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int &ff) { - int np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np) { - char *data=new char[2*nx*ny]; - char *d=readNextFrame(filebin, ff, np, data); - if (d==NULL) {delete [] data; data=NULL;} - return data; - } - - - - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np, char *data) { - //char *retval=0; - // int nd; - //int fnum = -1; - np=0; - // int pn; - - - // if (ff>=0) - // fnum=ff; - - if (filebin.is_open()) { - if (filebin.read(data, 2*nx*ny) ){ - // iframe++; - //ff=iframe; - return data; - } - } - return NULL; - - - - }; - - - - virtual char *findNextFrame(char *data, int &ndata, int dsize){ - if (dsize<2*nx*ny) ndata=dsize; - else ndata=2*nx*ny; - return data; - - } - - - - - - - // virtual int setFrameNumber(int ff){iframe=ff}; - - - - - - - - - - -int getPacketNumber(int x, int y) {return 0;}; + // virtual int setFrameNumber(int ff){iframe=ff}; + int getPacketNumber(int x, int y) { return 0; }; }; - - - #endif diff --git a/slsDetectorCalibration/dataStructures/imageZmq32bit.h b/slsDetectorCalibration/dataStructures/imageZmq32bit.h index c5240c35c..5d915ee41 100644 --- a/slsDetectorCalibration/dataStructures/imageZmq32bit.h +++ b/slsDetectorCalibration/dataStructures/imageZmq32bit.h @@ -1,127 +1,102 @@ // SPDX-License-Identifier: LGPL-3.0-or-other // Copyright (C) 2021 Contributors to the SLS Detector Package #ifndef IMAGEZMQ32BIT_H -#define IMAGEZMQ32BIT_H +#define IMAGEZMQ32BIT_H #include "slsDetectorData.h" - class imageZmq32bit : public slsDetectorData { - - private: - - // int iframe; - public: + private: + // int iframe; + public: + /** + Implements the slsReceiverData structure for the moench02 prototype read + out by a module i.e. using the slsReceiver (160x160 pixels, 40 packets + 1286 large etc.) \param c crosstalk parameter for the output buffer + */ + // moench03T1ZmqDataNew(int ns=5000): slsDetectorData(400, 400, + // ns*32*2+sizeof(int)), nSamples(ns), offset(sizeof(int)), xtalk(0.00021) { + imageZmq32bit(int nnx = 400, int nny = 400) + : slsDetectorData(nnx, nny, sizeof(uint32_t) * nnx * nny) { + cout << "* " << nx << " " << ny << endl; + int is = 0; + for (int row = 0; row < ny; row++) { + for (int col = 0; col < nx; col++) { + dataMap[row][col] = is * sizeof(uint32_t); + is++; + } + } + }; + /* virtual double getValue(char *data, int ix, int iy=0) { */ - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer + /* //cout << ix << " " << ix << dataMap[iy][ix] << 2*nx*ny << " "<< endl; + */ + /* uint16_t val=getChannel(data, ix, iy); */ + /* return val; */ + /* }; */ - */ - // moench03T1ZmqDataNew(int ns=5000): slsDetectorData(400, 400, ns*32*2+sizeof(int)), nSamples(ns), offset(sizeof(int)), xtalk(0.00021) { - imageZmq32bit(int nnx=400, int nny=400): slsDetectorData(nnx, nny, sizeof(uint32_t)*nnx*nny) { - cout << "* " << nx << " " << ny << endl; - int is=0; - for (int row=0; row=0) + // fnum=ff; + if (filebin.is_open()) { + if (filebin.read(data, 2 * nx * ny)) { + // iframe++; + // ff=iframe; + return data; + } + } + return NULL; + }; - int getFrameNumber(char *buff){return *((int*)buff);};//*((int*)(buff+5))&0xffffff;}; + virtual char *findNextFrame(char *data, int &ndata, int dsize) { + if (dsize < 2 * nx * ny) + ndata = dsize; + else + ndata = 2 * nx * ny; + return data; + } - - int getPacketNumber(char *buff){return 0;}//((*(((int*)(buff+4))))&0xff)+1;}; - - virtual char *readNextFrame(ifstream &filebin) { - int ff=-1, np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int &ff) { - int np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np) { - char *data=new char[2*nx*ny]; - char *d=readNextFrame(filebin, ff, np, data); - if (d==NULL) {delete [] data; data=NULL;} - return data; - } - - - - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np, char *data) { - //char *retval=0; - // int nd; - //int fnum = -1; - np=0; - // int pn; - - - // if (ff>=0) - // fnum=ff; - - if (filebin.is_open()) { - if (filebin.read(data, 2*nx*ny) ){ - // iframe++; - //ff=iframe; - return data; - } - } - return NULL; - - - - }; - - - - virtual char *findNextFrame(char *data, int &ndata, int dsize){ - if (dsize<2*nx*ny) ndata=dsize; - else ndata=2*nx*ny; - return data; - - } - - - - - - - // virtual int setFrameNumber(int ff){iframe=ff}; - - - - - - - - - - -int getPacketNumber(int x, int y) {return 0;}; + // virtual int setFrameNumber(int ff){iframe=ff}; + int getPacketNumber(int x, int y) { return 0; }; }; - - - #endif diff --git a/slsDetectorCalibration/dataStructures/jungfrauHighZSingleChipData.h b/slsDetectorCalibration/dataStructures/jungfrauHighZSingleChipData.h index 7983c34e4..0b6a8afa6 100644 --- a/slsDetectorCalibration/dataStructures/jungfrauHighZSingleChipData.h +++ b/slsDetectorCalibration/dataStructures/jungfrauHighZSingleChipData.h @@ -1,240 +1,239 @@ // SPDX-License-Identifier: LGPL-3.0-or-other // Copyright (C) 2021 Contributors to the SLS Detector Package #ifndef JUNGFRAUHIGHZSINGLECHIPDATA_H -#define JUNGFRAUHIGHZSINGLECHIPDATA_H +#define JUNGFRAUHIGHZSINGLECHIPDATA_H #include "slsDetectorData.h" //#define VERSION_V2 - /** - @short structure for a Detector Packet or Image Header - @li frameNumber is the frame number - @li expLength is the subframe number (32 bit eiger) or real time exposure time in 100ns (others) - @li packetNumber is the packet number - @li bunchId is the bunch id from beamline - @li timestamp is the time stamp with 10 MHz clock - @li modId is the unique module id (unique even for left, right, top, bottom) - @li xCoord is the x coordinate in the complete detector system - @li yCoord is the y coordinate in the complete detector system - @li zCoord is the z coordinate in the complete detector system - @li debug is for debugging purposes - @li roundRNumber is the round robin set number - @li detType is the detector type see :: detectorType - @li version is the version number of this structure format - */ - typedef struct { - uint64_t bunchNumber; /**< is the frame number */ - uint64_t pre; /**< something */ - - } jf_header; - - +/** + @short structure for a Detector Packet or Image Header + @li frameNumber is the frame number + @li expLength is the subframe number (32 bit eiger) or real time exposure + time in 100ns (others) + @li packetNumber is the packet number + @li bunchId is the bunch id from beamline + @li timestamp is the time stamp with 10 MHz clock + @li modId is the unique module id (unique even for left, right, top, bottom) + @li xCoord is the x coordinate in the complete detector system + @li yCoord is the y coordinate in the complete detector system + @li zCoord is the z coordinate in the complete detector system + @li debug is for debugging purposes + @li roundRNumber is the round robin set number + @li detType is the detector type see :: detectorType + @li version is the version number of this structure format +*/ +typedef struct { + uint64_t bunchNumber; /**< is the frame number */ + uint64_t pre; /**< something */ +} jf_header; class jungfrauHighZSingleChipData : public slsDetectorData { - - private: - - int iframe; - public: - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer - */ - jungfrauHighZSingleChipData(): slsDetectorData(256, 256, 256*256*2+sizeof(jf_header)) { + private: + int iframe; + public: + /** + Implements the slsReceiverData structure for the moench02 prototype read + out by a module i.e. using the slsReceiver (160x160 pixels, 40 packets + 1286 large etc.) \param c crosstalk parameter for the output buffer - for (int ix=0; ix<256; ix++) { - for (int iy=0; iy<256; iy++) { - dataMap[iy][ix]=sizeof(jf_header)+(256*iy+ix)*2; + */ + jungfrauHighZSingleChipData() + : slsDetectorData(256, 256, + 256 * 256 * 2 + sizeof(jf_header)) { + + for (int ix = 0; ix < 256; ix++) { + for (int iy = 0; iy < 256; iy++) { + dataMap[iy][ix] = sizeof(jf_header) + (256 * iy + ix) * 2; #ifdef HIGHZ - dataMask[iy][ix]=0x3fff; + dataMask[iy][ix] = 0x3fff; #endif - } - } - - iframe=0; - // cout << "data struct created" << endl; - }; - + } + } - - /** - Returns the value of the selected channel for the given dataset as double. - \param data pointer to the dataset (including headers etc) - \param ix pixel number in the x direction - \param iy pixel number in the y direction - \returns data for the selected channel, with inversion if required as double + iframe = 0; + // cout << "data struct created" << endl; + }; - */ - virtual double getValue(char *data, int ix, int iy=0) { - - uint16_t val=getChannel(data, ix, iy)&0x3fff; - return val; - }; + /** + Returns the value of the selected channel for the given dataset as + double. \param data pointer to the dataset (including headers etc) \param + ix pixel number in the x direction \param iy pixel number in the y + direction \returns data for the selected channel, with inversion if + required as double - + */ + virtual double getValue(char *data, int ix, int iy = 0) { - /* virtual void calcGhost(char *data, int ix, int iy) { */ - /* double val=0; */ - /* ghost[iy][ix]=0; */ - - /* } */ + uint16_t val = getChannel(data, ix, iy) & 0x3fff; + return val; + }; + + /* virtual void calcGhost(char *data, int ix, int iy) { */ + /* double val=0; */ + /* ghost[iy][ix]=0; */ + + /* } */ + + /* virtual void calcGhost(char *data) { */ + /* for (int ix=0; ix<25; ix++){ */ + /* for (int iy=0; iy<200; iy++) { */ + /* calcGhost(data, ix,iy); */ + /* } */ + /* } */ + /* // cout << "*" << endl; */ + /* } */ + + /* double getGhost(int ix, int iy) { */ + /* return 0; */ + /* }; */ + + /** + + Returns the frame number for the given dataset. Purely virtual func. + \param buff pointer to the dataset + \returns frame number + + */ + + /* class jfrau_packet_header_t { */ + /* public: */ + /* unsigned char reserved[4]; */ + /* unsigned char packetNumber[1]; */ + /* unsigned char frameNumber[3]; */ + /* unsigned char bunchid[8]; */ + /* }; */ + + int getFrameNumber(char *buff) { + return ((jf_header *)buff)->bunchNumber; + }; //*((int*)(buff+5))&0xffffff;}; + + /** + + Returns the packet number for the given dataset. purely virtual func + \param buff pointer to the dataset + \returns packet number number - /* virtual void calcGhost(char *data) { */ - /* for (int ix=0; ix<25; ix++){ */ - /* for (int iy=0; iy<200; iy++) { */ - /* calcGhost(data, ix,iy); */ - /* } */ - /* } */ - /* // cout << "*" << endl; */ - /* } */ + */ + int getPacketNumber(char *buff) { + return 0; + } //((*(((int*)(buff+4))))&0xff)+1;}; + /* /\** */ - /* double getGhost(int ix, int iy) { */ - /* return 0; */ - /* }; */ + /* Loops over a memory slot until a complete frame is found (i.e. all + * packets 0 to nPackets, same frame number). purely virtual func */ + /* \param data pointer to the memory to be analyzed */ + /* \param ndata reference to the amount of data found for the frame, in + * case the frame is incomplete at the end of the memory slot */ + /* \param dsize size of the memory slot to be analyzed */ + /* \returns pointer to the beginning of the last good frame (might be + * incomplete if ndata smaller than dataSize), or NULL if no frame is found + */ - /** + /* *\/ */ + /* virtual char *findNextFrame(char *data, int &ndata, int + * dsize){ndata=dsize; setDataSize(dsize); return data;}; */ - Returns the frame number for the given dataset. Purely virtual func. - \param buff pointer to the dataset - \returns frame number + /* /\** */ - */ + /* Loops over a file stream until a complete frame is found (i.e. all + * packets 0 to nPackets, same frame number). Can be overloaded for + * different kind of detectors! */ + /* \param filebin input file stream (binary) */ + /* \returns pointer to the begin of the last good frame, NULL if no + * frame is found or last frame is incomplete */ -/* class jfrau_packet_header_t { */ -/* public: */ -/* unsigned char reserved[4]; */ -/* unsigned char packetNumber[1]; */ -/* unsigned char frameNumber[3]; */ -/* unsigned char bunchid[8]; */ -/* }; */ + /* *\/ */ + /* virtual char *readNextFrame(ifstream &filebin){ */ + /* // int afifo_length=0; */ + /* uint16_t *afifo_cont; */ + /* int ib=0; */ + /* if (filebin.is_open()) { */ + /* afifo_cont=new uint16_t[dataSize/2]; */ + /* while (filebin.read(((char*)afifo_cont)+ib,2)) { */ + /* ib+=2; */ + /* if (ib==dataSize) break; */ + /* } */ + /* if (ib>0) { */ + /* iframe++; */ + /* // cout << ib << "-" << endl; */ + /* return (char*)afifo_cont; */ + /* } else { */ + /* delete [] afifo_cont; */ + /* return NULL; */ + /* } */ + /* } */ + /* return NULL; */ + /* }; */ + virtual char *readNextFrame(ifstream &filebin) { + int ff = -1, np = -1; + return readNextFrame(filebin, ff, np); + }; + virtual char *readNextFrame(ifstream &filebin, int &ff) { + int np = -1; + return readNextFrame(filebin, ff, np); + }; - int getFrameNumber(char *buff){return ((jf_header*)buff)->bunchNumber;};//*((int*)(buff+5))&0xffffff;}; + virtual char *readNextFrame(ifstream &filebin, int &ff, int &np) { + char *data = new char[dataSize]; + char *d = readNextFrame(filebin, ff, np, data); + if (d == NULL) { + delete[] data; + data = NULL; + } + return data; + } - /** + virtual char *readNextFrame(ifstream &filebin, int &ff, int &np, + char *data) { + char *retval = 0; + int nd; + int fnum = -1; + np = 0; + int pn; - Returns the packet number for the given dataset. purely virtual func - \param buff pointer to the dataset - \returns packet number number + // cout << dataSize << endl; + if (ff >= 0) + fnum = ff; + if (filebin.is_open()) { + if (filebin.read(data, dataSize)) { + ff = getFrameNumber(data); + np = getPacketNumber(data); + return data; + } + } + return NULL; + }; + /** - */ - int getPacketNumber(char *buff){return 0;}//((*(((int*)(buff+4))))&0xff)+1;}; + Loops over a memory slot until a complete frame is found (i.e. all + packets 0 to nPackets, same frame number). purely virtual func \param + data pointer to the memory to be analyzed \param ndata reference to the + amount of data found for the frame, in case the frame is incomplete at + the end of the memory slot \param dsize size of the memory slot to be + analyzed \returns pointer to the beginning of the last good frame (might + be incomplete if ndata smaller than dataSize), or NULL if no frame is + found -/* /\** */ - -/* Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func */ -/* \param data pointer to the memory to be analyzed */ -/* \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot */ -/* \param dsize size of the memory slot to be analyzed */ -/* \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found */ - -/* *\/ */ -/* virtual char *findNextFrame(char *data, int &ndata, int dsize){ndata=dsize; setDataSize(dsize); return data;}; */ - - -/* /\** */ - -/* Loops over a file stream until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). Can be overloaded for different kind of detectors! */ -/* \param filebin input file stream (binary) */ -/* \returns pointer to the begin of the last good frame, NULL if no frame is found or last frame is incomplete */ - -/* *\/ */ -/* virtual char *readNextFrame(ifstream &filebin){ */ -/* // int afifo_length=0; */ -/* uint16_t *afifo_cont; */ -/* int ib=0; */ -/* if (filebin.is_open()) { */ -/* afifo_cont=new uint16_t[dataSize/2]; */ -/* while (filebin.read(((char*)afifo_cont)+ib,2)) { */ -/* ib+=2; */ -/* if (ib==dataSize) break; */ -/* } */ -/* if (ib>0) { */ -/* iframe++; */ -/* // cout << ib << "-" << endl; */ -/* return (char*)afifo_cont; */ -/* } else { */ -/* delete [] afifo_cont; */ -/* return NULL; */ -/* } */ -/* } */ -/* return NULL; */ -/* }; */ - - - virtual char *readNextFrame(ifstream &filebin) { - int ff=-1, np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int &ff) { - int np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np) { - char *data=new char[dataSize]; - char *d=readNextFrame(filebin, ff, np, data); - if (d==NULL) {delete [] data; data=NULL;} - return data; - } - - - - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np, char *data) { - char *retval=0; - int nd; - int fnum = -1; - np=0; - int pn; - - // cout << dataSize << endl; - if (ff>=0) - fnum=ff; - - if (filebin.is_open()) { - if (filebin.read(data, dataSize) ){ - ff=getFrameNumber(data); - np=getPacketNumber(data); - return data; - } - } - return NULL; - }; - - - - /** - - Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func - \param data pointer to the memory to be analyzed - \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot - \param dsize size of the memory slot to be analyzed - \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found - - */ - virtual char *findNextFrame(char *data, int &ndata, int dsize){ - if (dsize { - private: - - int iframe; - // int *xmap, *ymap; - int nadc; - int sc_width; - int sc_height; + private: + int iframe; + // int *xmap, *ymap; + int nadc; + int sc_width; + int sc_height; - int maplength; + int maplength; + public: + /** + Implements the slsReceiverData structure for the moench02 prototype read + out by a module i.e. using the slsReceiver (160x160 pixels, 40 packets + 1286 large etc.) \param c crosstalk parameter for the output buffer + */ - public: + moench02CtbData(int ns = 6400) + : slsDetectorData(160, 160, ns * 2 * 32, NULL, NULL), + nadc(32), sc_width(40), sc_height(160) { + int adc_off[4] = {40, 0, 120, 80}; + int adc_nr[4] = {8, 10, 20, 22}; + int row, col; + int isample; + int iadc, iiadc; + int ix, iy; + maplength = this->getDataSize() / 2; + // cout << maplength << endl; + for (iiadc = 0; iiadc < 4; iiadc++) { - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer + iadc = adc_nr[iiadc]; + // cout << iiadc << endl; + for (int i = 0; i < sc_width * sc_height; i++) { - */ - + col = adc_off[iiadc] + (i % sc_width); + row = i / sc_width; + dataMap[row][col] = (32 * i + iadc) * 2; + if (dataMap[row][col] < 0 || dataMap[row][col] >= dataSize) { + cout << "Error: pointer " << dataMap[row][col] + << " out of range " << endl; + } + } + } - moench02CtbData(int ns=6400): slsDetectorData(160, 160, ns*2*32, NULL, NULL) , nadc(32), sc_width(40), sc_height(160) { - - - int adc_off[4]={40,0,120,80}; - int adc_nr[4]={8,10,20,22}; - int row, col; - - int isample; - int iadc, iiadc; - int ix, iy; - maplength=this->getDataSize()/2; - //cout << maplength << endl; - - for (iiadc=0; iiadc<4; iiadc++) { - - iadc=adc_nr[iiadc]; - //cout << iiadc << endl; - for (int i=0; i=dataSize) { - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - } - - } - } - - for (int i=0; i=0){ - xmap[i]=adc_off[iadc]+ix; - ymap[i]=iy; - }else{ - xmap[i]=-1; - ymap[i]=-1; - } - } - iframe=0; - cout << "data struct created" << endl; - }; - - void getPixel(int ip, int &x, int &y) { - if(ip>=0 && ip0) { - iframe++; - //cout << ib/2 << "-" << endl; - //for (int i=0; i= 0) { + xmap[i] = adc_off[iadc] + ix; + ymap[i] = iy; + } else { + xmap[i] = -1; + ymap[i] = -1; + } + } + iframe = 0; + cout << "data struct created" << endl; }; + void getPixel(int ip, int &x, int &y) { + if (ip >= 0 && ip < maplength) { + x = xmap[ip]; + y = ymap[ip]; + } /*else{ + cerr<<"WRONG ARRAY LENGTH"< 0) { + iframe++; + // cout << ib/2 << "-" << endl; + // for (int i=0; i { - private: - - int iframe; - int nadc; - int sc_width; - int sc_height; - public: + private: + int iframe; + int nadc; + int sc_width; + int sc_height; + public: + /** + Implements the slsReceiverData structure for the moench02 prototype read + out by a module i.e. using the slsReceiver (160x160 pixels, 40 packets + 1286 large etc.) \param c crosstalk parameter for the output buffer + */ + moench03CtbData(int ns = 5000) + : slsDetectorData(400, 400, ns * 2 * 32, NULL, NULL), + nadc(32), sc_width(25), sc_height(200) { - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer + int row, col; - */ - + int isample; + int iadc; + int ix, iy; - moench03CtbData(int ns=5000): slsDetectorData(400, 400, ns*2*32, NULL, NULL) , nadc(32), sc_width(25), sc_height(200) { + int adc_nr[32] = {200, 225, 250, 275, 300, 325, 350, 375, 0, 25, 50, + 75, 100, 125, 150, 175, 175, 150, 125, 100, 75, 50, + 25, 0, 375, 350, 325, 300, 275, 250, 225, 200}; - - int row, col; + /* int adc_nr[32]={300,325,350,375,300,325,350,375, \ */ + /* 200,225,250,275,200,225,250,275,\ */ + /* 100,125,150,175,100,125,150,175,\ */ + /* 0,25,50,75,0,25,50,75}; */ - int isample; - int iadc; - int ix, iy; + for (iadc = 0; iadc < nadc; iadc++) { + for (int i = 0; i < sc_width * sc_height; i++) { + col = adc_nr[iadc] + (i % sc_width); + if (iadc < 16) { + row = 199 - i / sc_width; + } else { + row = 200 + i / sc_width; + } + dataMap[row][col] = (nadc * i + iadc) * 2; + if (dataMap[row][col] < 0 || dataMap[row][col] >= 2 * 400 * 400) + cout << "Error: pointer " << dataMap[row][col] + << " out of range " << endl; + } + } + for (int i = 0; i < nx * ny; i++) { + isample = i / nadc; + iadc = i % nadc; + ix = isample % sc_width; + iy = isample / sc_width; + if (iadc < (nadc / 2)) { + xmap[i] = adc_nr[iadc] + ix; + ymap[i] = ny / 2 - 1 - iy; + } else { + xmap[i] = adc_nr[iadc] + ix; + ymap[i] = ny / 2 + iy; + } + } - int adc_nr[32]={200,225,250,275,300,325,350,375,\ - 0,25,50,75,100,125,150,175,\ - 175,150,125,100,75,50,25,0,\ - 375,350,325,300,275,250,225,200}; - - /* int adc_nr[32]={300,325,350,375,300,325,350,375, \ */ - /* 200,225,250,275,200,225,250,275,\ */ - /* 100,125,150,175,100,125,150,175,\ */ - /* 0,25,50,75,0,25,50,75}; */ - - - for (iadc=0; iadc=2*400*400) - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - - } - } - for (int i=0; i0) { - iframe++; - // cout << ib << "-" << endl; - return (char*)afifo_cont; - } else { - delete [] afifo_cont; - return NULL; - } - } - return NULL; + iframe = 0; + // cout << "data struct created" << endl; }; + /** - + Returns the frame number for the given dataset. Purely virtual func. + \param buff pointer to the dataset + \returns frame number + */ + + virtual int getFrameNumber(char *buff) { + (void)buff; + return iframe; + }; + + /** + + Returns the packet number for the given dataset. purely virtual func + \param buff pointer to the dataset + \returns packet number number + + + virtual int getPacketNumber(char *buff)=0; + + */ + + /** + + Loops over a memory slot until a complete frame is found (i.e. all packets + 0 to nPackets, same frame number). purely virtual func \param data pointer + to the memory to be analyzed \param ndata reference to the amount of data + found for the frame, in case the frame is incomplete at the end of the + memory slot \param dsize size of the memory slot to be analyzed \returns + pointer to the beginning of the last good frame (might be incomplete if + ndata smaller than dataSize), or NULL if no frame is found + + */ + virtual char *findNextFrame(char *data, int &ndata, int dsize) { + ndata = dsize; + setDataSize(dsize); + return data; + }; + + /** + + Loops over a file stream until a complete frame is found (i.e. all packets + 0 to nPackets, same frame number). Can be overloaded for different kind of + detectors! \param filebin input file stream (binary) \returns pointer to + the begin of the last good frame, NULL if no frame is found or last frame + is incomplete + + */ + virtual char *readNextFrame(ifstream &filebin) { + // int afifo_length=0; + uint16_t *afifo_cont; + int ib = 0; + if (filebin.is_open()) { + afifo_cont = new uint16_t[dataSize / 2]; + while (filebin.read(((char *)afifo_cont) + ib, 2)) { + ib += 2; + if (ib == dataSize) + break; + } + if (ib > 0) { + iframe++; + // cout << ib << "-" << endl; + return (char *)afifo_cont; + } else { + delete[] afifo_cont; + return NULL; + } + } + return NULL; + }; }; - - #endif diff --git a/slsDetectorCalibration/dataStructures/moench03T1CtbData.h b/slsDetectorCalibration/dataStructures/moench03T1CtbData.h index 6a4e31e0f..65f2d540c 100644 --- a/slsDetectorCalibration/dataStructures/moench03T1CtbData.h +++ b/slsDetectorCalibration/dataStructures/moench03T1CtbData.h @@ -1,160 +1,146 @@ // SPDX-License-Identifier: LGPL-3.0-or-other // Copyright (C) 2021 Contributors to the SLS Detector Package #ifndef MOENCH03T1CTBDATA_H -#define MOENCH03T1CTBDATA_H +#define MOENCH03T1CTBDATA_H #include "slsDetectorData.h" - - class moench03T1CtbData : public slsDetectorData { - private: - - int iframe; - int nadc; - int sc_width; - int sc_height; - public: + private: + int iframe; + int nadc; + int sc_width; + int sc_height; + public: + /** + Implements the slsReceiverData structure for the moench02 prototype read + out by a module i.e. using the slsReceiver (160x160 pixels, 40 packets + 1286 large etc.) \param c crosstalk parameter for the output buffer + */ + moench03T1CtbData(int ns = 5000) + : slsDetectorData(400, 400, ns * 2 * 32, NULL, NULL), + nadc(32), sc_width(25), sc_height(200) { - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer + int adc_nr[32] = {300, 325, 350, 375, 300, 325, 350, 375, 200, 225, 250, + 275, 200, 225, 250, 275, 100, 125, 150, 175, 100, 125, + 150, 175, 0, 25, 50, 75, 0, 25, 50, 75}; - */ - + int row, col; - moench03T1CtbData(int ns=5000): slsDetectorData(400, 400, ns*2*32, NULL, NULL) , nadc(32), sc_width(25), sc_height(200) { + int isample; + int iadc; + int ix, iy; + for (iadc = 0; iadc < nadc; iadc++) { + for (int i = 0; i < sc_width * sc_height; i++) { + col = adc_nr[iadc] + (i % sc_width); + if (iadc < 16) { + row = 199 - i / sc_width; + } else { + row = 200 + i / sc_width; + } + dataMap[row][col] = (nadc * i + iadc) * 2; + if (dataMap[row][col] < 0 || dataMap[row][col] >= 2 * 400 * 400) + cout << "Error: pointer " << dataMap[row][col] + << " out of range " << endl; + } + } + int adc4; + for (int i = 0; i < nx * ny; i++) { + isample = i / nadc; + iadc = i % nadc; + ix = isample % sc_width; + iy = isample / sc_width; + adc4 = (int)iadc / 4; + // if (iadc<(nadc/2)) { + if (adc4 % 2 == 0) { + xmap[i] = adc_nr[iadc] + ix; + ymap[i] = ny / 2 - 1 - iy; + } else { + xmap[i] = adc_nr[iadc] + ix; + ymap[i] = ny / 2 + iy; + } + } - int adc_nr[32]={300,325,350,375,300,325,350,375, \ - 200,225,250,275,200,225,250,275,\ - 100,125,150,175,100,125,150,175,\ - 0,25,50,75,0,25,50,75}; - - int row, col; - - int isample; - int iadc; - int ix, iy; - - - - - - for (iadc=0; iadc=2*400*400) - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - - } - } - int adc4; - for (int i=0; i0) { - iframe++; - // cout << ib << "-" << endl; - return (char*)afifo_cont; - } else { - delete [] afifo_cont; - return NULL; - } - } - return NULL; + iframe = 0; + // cout << "data struct created" << endl; }; + /** - + Returns the frame number for the given dataset. Purely virtual func. + \param buff pointer to the dataset + \returns frame number + */ + + virtual int getFrameNumber(char *buff) { + (void)buff; + return iframe; + }; + + /** + + Returns the packet number for the given dataset. purely virtual func + \param buff pointer to the dataset + \returns packet number number + + + virtual int getPacketNumber(char *buff)=0; + + */ + + /** + + Loops over a memory slot until a complete frame is found (i.e. all packets + 0 to nPackets, same frame number). purely virtual func \param data pointer + to the memory to be analyzed \param ndata reference to the amount of data + found for the frame, in case the frame is incomplete at the end of the + memory slot \param dsize size of the memory slot to be analyzed \returns + pointer to the beginning of the last good frame (might be incomplete if + ndata smaller than dataSize), or NULL if no frame is found + + */ + virtual char *findNextFrame(char *data, int &ndata, int dsize) { + ndata = dsize; + setDataSize(dsize); + return data; + }; + + /** + + Loops over a file stream until a complete frame is found (i.e. all packets + 0 to nPackets, same frame number). Can be overloaded for different kind of + detectors! \param filebin input file stream (binary) \returns pointer to + the begin of the last good frame, NULL if no frame is found or last frame + is incomplete + + */ + virtual char *readNextFrame(ifstream &filebin) { + // int afifo_length=0; + uint16_t *afifo_cont; + int ib = 0; + if (filebin.is_open()) { + afifo_cont = new uint16_t[dataSize / 2]; + while (filebin.read(((char *)afifo_cont) + ib, 2)) { + ib += 2; + if (ib == dataSize) + break; + } + if (ib > 0) { + iframe++; + // cout << ib << "-" << endl; + return (char *)afifo_cont; + } else { + delete[] afifo_cont; + return NULL; + } + } + return NULL; + }; }; - - #endif diff --git a/slsDetectorCalibration/dataStructures/moench03T1ReceiverDataNew.h b/slsDetectorCalibration/dataStructures/moench03T1ReceiverDataNew.h index 47a681156..17a9f5a45 100644 --- a/slsDetectorCalibration/dataStructures/moench03T1ReceiverDataNew.h +++ b/slsDetectorCalibration/dataStructures/moench03T1ReceiverDataNew.h @@ -1,366 +1,366 @@ // SPDX-License-Identifier: LGPL-3.0-or-other // Copyright (C) 2021 Contributors to the SLS Detector Package #ifndef MOENCH03T1RECDATANEW_H -#define MOENCH03T1RECDATANEW_H +#define MOENCH03T1RECDATANEW_H #include "slsDetectorData.h" //#define VERSION_V2 - /** - @short structure for a Detector Packet or Image Header - @li frameNumber is the frame number - @li expLength is the subframe number (32 bit eiger) or real time exposure time in 100ns (others) - @li packetNumber is the packet number - @li bunchId is the bunch id from beamline - @li timestamp is the time stamp with 10 MHz clock - @li modId is the unique module id (unique even for left, right, top, bottom) - @li xCoord is the x coordinate in the complete detector system - @li yCoord is the y coordinate in the complete detector system - @li zCoord is the z coordinate in the complete detector system - @li debug is for debugging purposes - @li roundRNumber is the round robin set number - @li detType is the detector type see :: detectorType - @li version is the version number of this structure format - */ - typedef struct { - uint64_t frameNumber; /**< is the frame number */ - uint32_t expLength; /**< is the subframe number (32 bit eiger) or real time exposure time in 100ns (others) */ - uint32_t packetNumber; /**< is the packet number */ - uint64_t bunchId; /**< is the bunch id from beamline */ - uint64_t timestamp; /**< is the time stamp with 10 MHz clock */ - uint16_t modId; /**< is the unique module id (unique even for left, right, top, bottom) */ - uint16_t xCoord; /**< is the x coordinate in the complete detector system */ - uint16_t yCoord; /**< is the y coordinate in the complete detector system */ - uint16_t zCoord; /**< is the z coordinate in the complete detector system */ - uint32_t debug; /**< is for debugging purposes */ - uint16_t roundRNumber; /**< is the round robin set number */ - uint8_t detType; /**< is the detector type see :: detectorType */ - uint8_t version; /**< is the version number of this structure format */ +/** + @short structure for a Detector Packet or Image Header + @li frameNumber is the frame number + @li expLength is the subframe number (32 bit eiger) or real time exposure + time in 100ns (others) + @li packetNumber is the packet number + @li bunchId is the bunch id from beamline + @li timestamp is the time stamp with 10 MHz clock + @li modId is the unique module id (unique even for left, right, top, bottom) + @li xCoord is the x coordinate in the complete detector system + @li yCoord is the y coordinate in the complete detector system + @li zCoord is the z coordinate in the complete detector system + @li debug is for debugging purposes + @li roundRNumber is the round robin set number + @li detType is the detector type see :: detectorType + @li version is the version number of this structure format +*/ +typedef struct { + uint64_t frameNumber; /**< is the frame number */ + uint32_t expLength; /**< is the subframe number (32 bit eiger) or real time + exposure time in 100ns (others) */ + uint32_t packetNumber; /**< is the packet number */ + uint64_t bunchId; /**< is the bunch id from beamline */ + uint64_t timestamp; /**< is the time stamp with 10 MHz clock */ + uint16_t modId; /**< is the unique module id (unique even for left, right, + top, bottom) */ + uint16_t xCoord; /**< is the x coordinate in the complete detector system */ + uint16_t yCoord; /**< is the y coordinate in the complete detector system */ + uint16_t zCoord; /**< is the z coordinate in the complete detector system */ + uint32_t debug; /**< is for debugging purposes */ + uint16_t roundRNumber; /**< is the round robin set number */ + uint8_t detType; /**< is the detector type see :: detectorType */ + uint8_t version; /**< is the version number of this structure format */ #ifndef VERSION_V1 - uint64_t packetCaught[8]; /**< is the version number of this structure format */ + uint64_t + packetCaught[8]; /**< is the version number of this structure format */ #endif - } sls_detector_header; - - - +} sls_detector_header; class moench03T1ReceiverDataNew : public slsDetectorData { - - private: - - int iframe; - int nadc; - int sc_width; - int sc_height; - const int nSamples; - double ghost[200][25]; + private: + int iframe; + int nadc; + int sc_width; + int sc_height; + const int nSamples; - public: + double ghost[200][25]; + public: + /** + Implements the slsReceiverData structure for the moench02 prototype read + out by a module i.e. using the slsReceiver (160x160 pixels, 40 packets + 1286 large etc.) \param c crosstalk parameter for the output buffer + */ + moench03T1ReceiverDataNew(int ns = 5000) + : slsDetectorData(400, 400, + ns * 2 * 32 + sizeof(sls_detector_header)), + nSamples(ns) { + int nadc = 32; + int sc_width = 25; + int sc_height = 200; - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer + int adc_nr[32] = {300, 325, 350, 375, 300, 325, 350, 375, 200, 225, 250, + 275, 200, 225, 250, 275, 100, 125, 150, 175, 100, 125, + 150, 175, 0, 25, 50, 75, 0, 25, 50, 75}; - */ - moench03T1ReceiverDataNew(int ns=5000): slsDetectorData(400, 400, ns*2*32+sizeof(sls_detector_header)), nSamples(ns) { + int row, col; - int nadc=32; - int sc_width=25; - int sc_height=200; + int isample; + int iadc; + int ix, iy; - int adc_nr[32]={300,325,350,375,300,325,350,375, \ - 200,225,250,275,200,225,250,275,\ - 100,125,150,175,100,125,150,175,\ - 0,25,50,75,0,25,50,75}; + int npackets = 40; + int i; + int adc4(0); - int row, col; + for (int ip = 0; ip < npackets; ip++) { + for (int is = 0; is < 128; is++) { - int isample; - int iadc; - int ix, iy; - - int npackets=40; - int i; - int adc4(0); - - for (int ip=0; ip=nSamples*2*32) - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - } - } - } + if (dataMap[row][col] < 0 || + dataMap[row][col] >= nSamples * 2 * 32) + cout << "Error: pointer " << dataMap[row][col] + << " out of range " << endl; + } + } + } + } + // double ghost[200][25]; + + for (int ix = 0; ix < 25; ix++) + for (int iy = 0; iy < 200; iy++) + ghost[iy][ix] = 0.; + + int ipacket; + int ibyte; + int ii = 0; + for (ibyte = 0; ibyte < sizeof(sls_detector_header) / 2; ibyte++) { + xmap[ibyte] = -1; + ymap[ibyte] = -1; + } + int off = sizeof(sls_detector_header) / 2; + for (ipacket = 0; ipacket < npackets; ipacket++) { + for (ibyte = 0; ibyte < 8192 / 2; ibyte++) { + i = ipacket * 8208 / 2 + ibyte; + isample = ii / nadc; + if (isample < nSamples) { + iadc = ii % nadc; + adc4 = (int)iadc / 4; + ix = isample % sc_width; + iy = isample / sc_width; + if (adc4 % 2 == 0) { + xmap[i + off] = adc_nr[iadc] + ix; + ymap[i + off] = ny / 2 - 1 - iy; + } else { + xmap[i + off] = adc_nr[iadc] + ix; + ymap[i + off] = ny / 2 + iy; + } + } + ii++; + // } + } + } + + iframe = 0; + // cout << "data struct created" << endl; + }; + + /** + Returns the value of the selected channel for the given dataset as + double. \param data pointer to the dataset (including headers etc) \param + ix pixel number in the x direction \param iy pixel number in the y + direction \returns data for the selected channel, with inversion if + required as double + + */ + virtual double getValue(char *data, int ix, int iy = 0) { + /* cout << " x "<< ix << " y"<< iy << " val " << getChannel(data, ix, + * iy)<< endl;*/ + /* double val=0, vout=getChannel(data, ix, iy); */ + /* int x1=ix%25; */ + /* for (int ix=0; ix<16; ix++) { */ + /* for (int ii=0; ii<2; ii++) { */ + /* val+=getChannel(data,x1+25*ix,iy); */ + /* val+=getChannel(data,x1+25*ix,399-iy); */ + /* } */ + /* } */ + /* vout+=0.0008*val-6224; */ + /* return vout; //(double)getChannel(data, ix, iy); + */ + uint16_t val = getChannel(data, ix, iy) & 0x3fff; + return val; + }; + + virtual void calcGhost(char *data, int ix, int iy) { + double val = 0; + /* for (int ix=0; ix<25; ix++){ */ + /* for (int iy=0; iy<200; iy++) { */ + val = 0; + // cout << "** "; + for (int isc = 0; isc < 16; isc++) { + // for (int ii=0; ii<2; ii++) { + val += getChannel(data, ix + 25 * isc, iy); + // cout << "(" << isc << "," << val << " " ; + val += getChannel(data, ix + 25 * isc, 399 - iy); + // cout << val << " " ; + // } + } + ghost[iy][ix] = val; //-6224; + // cout << " --"<< endl; + /* } */ + /* } */ + // cout << "*" << endl; } - // double ghost[200][25]; - for (int ix=0; ix<25; ix++) - for (int iy=0; iy<200; iy++) - ghost[iy][ix]=0.; - - int ipacket; - int ibyte; - int ii=0; - for (ibyte=0; ibyteframeNumber; + }; //*((int*)(buff+5))&0xffffff;}; + + /** + + Returns the packet number for the given dataset. purely virtual func + \param buff pointer to the dataset + \returns packet number number + + + + */ + int getPacketNumber(char *buff) { + return ((sls_detector_header *)buff)->packetNumber; + } //((*(((int*)(buff+4))))&0xff)+1;}; + + /* /\** */ + + /* Loops over a memory slot until a complete frame is found (i.e. all + * packets 0 to nPackets, same frame number). purely virtual func */ + /* \param data pointer to the memory to be analyzed */ + /* \param ndata reference to the amount of data found for the frame, in + * case the frame is incomplete at the end of the memory slot */ + /* \param dsize size of the memory slot to be analyzed */ + /* \returns pointer to the beginning of the last good frame (might be + * incomplete if ndata smaller than dataSize), or NULL if no frame is found */ - uint16_t val=getChannel(data, ix, iy)&0x3fff; - return val; - }; - + /* *\/ */ + /* virtual char *findNextFrame(char *data, int &ndata, int + * dsize){ndata=dsize; setDataSize(dsize); return data;}; */ - virtual void calcGhost(char *data, int ix, int iy) { - double val=0; - /* for (int ix=0; ix<25; ix++){ */ - /* for (int iy=0; iy<200; iy++) { */ - val=0; - // cout << "** "; - for (int isc=0; isc<16; isc++) { - // for (int ii=0; ii<2; ii++) { - val+=getChannel(data,ix+25*isc,iy); - // cout << "(" << isc << "," << val << " " ; - val+=getChannel(data,ix+25*isc,399-iy); - // cout << val << " " ; - // } - } - ghost[iy][ix]=val;//-6224; - // cout << " --"<< endl; - /* } */ - /* } */ - // cout << "*" << endl; - - } + /* /\** */ + /* Loops over a file stream until a complete frame is found (i.e. all + * packets 0 to nPackets, same frame number). Can be overloaded for + * different kind of detectors! */ + /* \param filebin input file stream (binary) */ + /* \returns pointer to the begin of the last good frame, NULL if no + * frame is found or last frame is incomplete */ + /* *\/ */ + /* virtual char *readNextFrame(ifstream &filebin){ */ + /* // int afifo_length=0; */ + /* uint16_t *afifo_cont; */ + /* int ib=0; */ + /* if (filebin.is_open()) { */ + /* afifo_cont=new uint16_t[dataSize/2]; */ + /* while (filebin.read(((char*)afifo_cont)+ib,2)) { */ + /* ib+=2; */ + /* if (ib==dataSize) break; */ + /* } */ + /* if (ib>0) { */ + /* iframe++; */ + /* // cout << ib << "-" << endl; */ + /* return (char*)afifo_cont; */ + /* } else { */ + /* delete [] afifo_cont; */ + /* return NULL; */ + /* } */ + /* } */ + /* return NULL; */ + /* }; */ - virtual void calcGhost(char *data) { - for (int ix=0; ix<25; ix++){ - for (int iy=0; iy<200; iy++) { - calcGhost(data, ix,iy); - } + virtual char *readNextFrame(ifstream &filebin) { + int ff = -1, np = -1; + return readNextFrame(filebin, ff, np); + }; + + virtual char *readNextFrame(ifstream &filebin, int &ff) { + int np = -1; + return readNextFrame(filebin, ff, np); + }; + + virtual char *readNextFrame(ifstream &filebin, int &ff, int &np) { + char *data = new char[dataSize]; + char *d = readNextFrame(filebin, ff, np, data); + if (d == NULL) { + delete[] data; + data = NULL; + } + return data; } - // cout << "*" << endl; - } + virtual char *readNextFrame(ifstream &filebin, int &ff, int &np, + char *data) { + char *retval = 0; + int nd; + int fnum = -1; + np = 0; + int pn; - double getGhost(int ix, int iy) { - if (iy<200) return ghost[iy][ix%25]; - if (iy<400) return ghost[399-iy][ix%25]; - return 0; - }; + // cout << dataSize << endl; + if (ff >= 0) + fnum = ff; - /** + if (filebin.is_open()) { + if (filebin.read(data, dataSize)) { + ff = getFrameNumber(data); + np = getPacketNumber(data); + return data; + } + } + return NULL; + }; - Returns the frame number for the given dataset. Purely virtual func. - \param buff pointer to the dataset - \returns frame number + /** - */ + Loops over a memory slot until a complete frame is found (i.e. all + packets 0 to nPackets, same frame number). purely virtual func \param + data pointer to the memory to be analyzed \param ndata reference to the + amount of data found for the frame, in case the frame is incomplete at + the end of the memory slot \param dsize size of the memory slot to be + analyzed \returns pointer to the beginning of the last good frame (might + be incomplete if ndata smaller than dataSize), or NULL if no frame is + found -/* class jfrau_packet_header_t { */ -/* public: */ -/* unsigned char reserved[4]; */ -/* unsigned char packetNumber[1]; */ -/* unsigned char frameNumber[3]; */ -/* unsigned char bunchid[8]; */ -/* }; */ - - - - int getFrameNumber(char *buff){return ((sls_detector_header*)buff)->frameNumber;};//*((int*)(buff+5))&0xffffff;}; - - /** - - Returns the packet number for the given dataset. purely virtual func - \param buff pointer to the dataset - \returns packet number number - - - - */ - int getPacketNumber(char *buff){return ((sls_detector_header*)buff)->packetNumber;}//((*(((int*)(buff+4))))&0xff)+1;}; - -/* /\** */ - -/* Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func */ -/* \param data pointer to the memory to be analyzed */ -/* \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot */ -/* \param dsize size of the memory slot to be analyzed */ -/* \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found */ - -/* *\/ */ -/* virtual char *findNextFrame(char *data, int &ndata, int dsize){ndata=dsize; setDataSize(dsize); return data;}; */ - - -/* /\** */ - -/* Loops over a file stream until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). Can be overloaded for different kind of detectors! */ -/* \param filebin input file stream (binary) */ -/* \returns pointer to the begin of the last good frame, NULL if no frame is found or last frame is incomplete */ - -/* *\/ */ -/* virtual char *readNextFrame(ifstream &filebin){ */ -/* // int afifo_length=0; */ -/* uint16_t *afifo_cont; */ -/* int ib=0; */ -/* if (filebin.is_open()) { */ -/* afifo_cont=new uint16_t[dataSize/2]; */ -/* while (filebin.read(((char*)afifo_cont)+ib,2)) { */ -/* ib+=2; */ -/* if (ib==dataSize) break; */ -/* } */ -/* if (ib>0) { */ -/* iframe++; */ -/* // cout << ib << "-" << endl; */ -/* return (char*)afifo_cont; */ -/* } else { */ -/* delete [] afifo_cont; */ -/* return NULL; */ -/* } */ -/* } */ -/* return NULL; */ -/* }; */ - - - virtual char *readNextFrame(ifstream &filebin) { - int ff=-1, np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int &ff) { - int np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np) { - char *data=new char[dataSize]; - char *d=readNextFrame(filebin, ff, np, data); - if (d==NULL) {delete [] data; data=NULL;} - return data; - } - - - - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np, char *data) { - char *retval=0; - int nd; - int fnum = -1; - np=0; - int pn; - - // cout << dataSize << endl; - if (ff>=0) - fnum=ff; - - if (filebin.is_open()) { - if (filebin.read(data, dataSize) ){ - ff=getFrameNumber(data); - np=getPacketNumber(data); - return data; - } - } - return NULL; - - - - }; - - - - /** - - Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func - \param data pointer to the memory to be analyzed - \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot - \param dsize size of the memory slot to be analyzed - \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found - - */ - virtual char *findNextFrame(char *data, int &ndata, int dsize){ - if (dsize { - - private: - - int iframe; - int nadc; - int sc_width; - int sc_height; - const int nSamples; + private: + int iframe; + int nadc; + int sc_width; + int sc_height; + const int nSamples; - public: + public: + /** + Implements the slsReceiverData structure for the moench02 prototype read + out by a module i.e. using the slsReceiver (160x160 pixels, 40 packets + 1286 large etc.) \param c crosstalk parameter for the output buffer - - - - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer - - */ + */ #ifdef HOR - moench03T1ReceiverDataNew(int ns=5000): slsDetectorData(800, 200, ns*2*32+sizeof(sls_detector_header)), nSamples(ns) { + moench03T1ReceiverDataNew(int ns = 5000) + : slsDetectorData(800, 200, + ns * 2 * 32 + sizeof(sls_detector_header)), + nSamples(ns) { #endif #ifdef VERT - moench03T1ReceiverDataNew(int ns=5000): slsDetectorData(200, 800, ns*2*32+sizeof(sls_detector_header)), nSamples(ns) { + moench03T1ReceiverDataNew(int ns = 5000) + : slsDetectorData( + 200, 800, ns * 2 * 32 + sizeof(sls_detector_header)), + nSamples(ns) { #endif - int nadc=32; - int sc_width=25; - int sc_height=200; + int nadc = 32; + int sc_width = 25; + int sc_height = 200; - int adc_nr[32]={300,325,350,375,300,325,350,375, \ - 200,225,250,275,200,225,250,275,\ - 100,125,150,175,100,125,150,175,\ - 0,25,50,75,0,25,50,75}; + int adc_nr[32] = {300, 325, 350, 375, 300, 325, 350, 375, + 200, 225, 250, 275, 200, 225, 250, 275, + 100, 125, 150, 175, 100, 125, 150, 175, + 0, 25, 50, 75, 0, 25, 50, 75}; - int row, col; + int row, col; - int isample; - int iadc; - int ix, iy; - - int npackets=40; - int i; - int adc4(0); - int pix; + int isample; + int iadc; + int ix, iy; + int npackets = 40; + int i; + int adc4(0); + int pix; - int off=0; + int off = 0; #ifdef OFF_1 - off=1; + off = 1; #endif - cout << "This is a MOENCH with rectangular pixels!" << endl; + cout << "This is a MOENCH with rectangular pixels!" << endl; - for (int ip=0; ip=nSamples*2*32+sizeof(sls_detector_header)) - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - ix=col; - iy=row; + for (iadc = 0; iadc < nadc; iadc++) { + i = 128 * ip + is; + adc4 = (int)iadc / 4; + if (i < sc_width * sc_height) { + // for (int i=0; i= nSamples * 2 * 32 + + sizeof(sls_detector_header)) + cout << "Error: pointer " << dataMap[row][col] + << " out of range " << endl; + ix = col; + iy = row; #ifdef HOR - if (row%2==off) { - ix=2*col; - iy=row/2; - } else { - ix=2*col+1; - iy=row/2; - } + if (row % 2 == off) { + ix = 2 * col; + iy = row / 2; + } else { + ix = 2 * col + 1; + iy = row / 2; + } #endif #ifdef VERT - if (col%2==off) { - ix=col/2; - iy=row*2+1; - } else { - ix=col/2; - iy=row*2; - } + if (col % 2 == off) { + ix = col / 2; + iy = row * 2 + 1; + } else { + ix = col / 2; + iy = row * 2; + } #endif - dataMap[iy][ix]=pix; - } - } - } - } + dataMap[iy][ix] = pix; + } + } + } + } - /* int ipacket; */ - /* int ibyte; */ - /* int ii=0; */ - /* for (ibyte=0; ibyteframeNumber; + }; //*((int*)(buff+5))&0xffffff;}; + + /** + + Returns the packet number for the given dataset. purely virtual func + \param buff pointer to the dataset + \returns packet number number - int getFrameNumber(char *buff){return ((sls_detector_header*)buff)->frameNumber;};//*((int*)(buff+5))&0xffffff;}; + */ + int getPacketNumber(char *buff) { + return ((sls_detector_header *)buff)->packetNumber; + } //((*(((int*)(buff+4))))&0xff)+1;}; - /** + /* /\** */ - Returns the packet number for the given dataset. purely virtual func - \param buff pointer to the dataset - \returns packet number number + /* Loops over a memory slot until a complete frame is found (i.e. + * all packets 0 to nPackets, same frame number). purely virtual func */ + /* \param data pointer to the memory to be analyzed */ + /* \param ndata reference to the amount of data found for the + * frame, in case the frame is incomplete at the end of the memory slot + */ + /* \param dsize size of the memory slot to be analyzed */ + /* \returns pointer to the beginning of the last good frame (might + * be incomplete if ndata smaller than dataSize), or NULL if no frame is + * found */ + /* *\/ */ + /* virtual char *findNextFrame(char *data, int &ndata, int + * dsize){ndata=dsize; setDataSize(dsize); return data;}; */ + /* /\** */ - */ - int getPacketNumber(char *buff){return ((sls_detector_header*)buff)->packetNumber;}//((*(((int*)(buff+4))))&0xff)+1;}; + /* Loops over a file stream until a complete frame is found (i.e. + * all packets 0 to nPackets, same frame number). Can be overloaded for + * different kind of detectors! */ + /* \param filebin input file stream (binary) */ + /* \returns pointer to the begin of the last good frame, NULL if no + * frame is found or last frame is incomplete */ -/* /\** */ + /* *\/ */ + /* virtual char *readNextFrame(ifstream &filebin){ */ + /* // int afifo_length=0; */ + /* uint16_t *afifo_cont; */ + /* int ib=0; */ + /* if (filebin.is_open()) { */ + /* afifo_cont=new uint16_t[dataSize/2]; */ + /* while (filebin.read(((char*)afifo_cont)+ib,2)) { */ + /* ib+=2; */ + /* if (ib==dataSize) break; */ + /* } */ + /* if (ib>0) { */ + /* iframe++; */ + /* // cout << ib << "-" << endl; */ + /* return (char*)afifo_cont; */ + /* } else { */ + /* delete [] afifo_cont; */ + /* return NULL; */ + /* } */ + /* } */ + /* return NULL; */ + /* }; */ -/* Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func */ -/* \param data pointer to the memory to be analyzed */ -/* \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot */ -/* \param dsize size of the memory slot to be analyzed */ -/* \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found */ + virtual char *readNextFrame(ifstream & filebin) { + int ff = -1, np = -1; + return readNextFrame(filebin, ff, np); + }; -/* *\/ */ -/* virtual char *findNextFrame(char *data, int &ndata, int dsize){ndata=dsize; setDataSize(dsize); return data;}; */ + virtual char *readNextFrame(ifstream & filebin, int &ff) { + int np = -1; + return readNextFrame(filebin, ff, np); + }; + virtual char *readNextFrame(ifstream & filebin, int &ff, int &np) { + char *data = new char[dataSize]; + char *d = readNextFrame(filebin, ff, np, data); + if (d == NULL) { + delete[] data; + data = NULL; + } + return data; + } -/* /\** */ + virtual char *readNextFrame(ifstream & filebin, int &ff, int &np, + char *data) { + char *retval = 0; + int nd; + int fnum = -1; + np = 0; + int pn; -/* Loops over a file stream until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). Can be overloaded for different kind of detectors! */ -/* \param filebin input file stream (binary) */ -/* \returns pointer to the begin of the last good frame, NULL if no frame is found or last frame is incomplete */ + // cout << dataSize << endl; + if (ff >= 0) + fnum = ff; -/* *\/ */ -/* virtual char *readNextFrame(ifstream &filebin){ */ -/* // int afifo_length=0; */ -/* uint16_t *afifo_cont; */ -/* int ib=0; */ -/* if (filebin.is_open()) { */ -/* afifo_cont=new uint16_t[dataSize/2]; */ -/* while (filebin.read(((char*)afifo_cont)+ib,2)) { */ -/* ib+=2; */ -/* if (ib==dataSize) break; */ -/* } */ -/* if (ib>0) { */ -/* iframe++; */ -/* // cout << ib << "-" << endl; */ -/* return (char*)afifo_cont; */ -/* } else { */ -/* delete [] afifo_cont; */ -/* return NULL; */ -/* } */ -/* } */ -/* return NULL; */ -/* }; */ + if (filebin.is_open()) { + if (filebin.read(data, dataSize)) { + ff = getFrameNumber(data); + np = getPacketNumber(data); + return data; + } + } + return NULL; + }; + /** - virtual char *readNextFrame(ifstream &filebin) { - int ff=-1, np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int &ff) { - int np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np) { - char *data=new char[dataSize]; - char *d=readNextFrame(filebin, ff, np, data); - if (d==NULL) {delete [] data; data=NULL;} - return data; - } - - - - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np, char *data) { - char *retval=0; - int nd; - int fnum = -1; - np=0; - int pn; - - // cout << dataSize << endl; - if (ff>=0) - fnum=ff; - - if (filebin.is_open()) { - if (filebin.read(data, dataSize) ){ - ff=getFrameNumber(data); - np=getPacketNumber(data); - return data; - } - } - return NULL; - - - - }; - - - - /** - - Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func - \param data pointer to the memory to be analyzed - \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot - \param dsize size of the memory slot to be analyzed - \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found - - */ - virtual char *findNextFrame(char *data, int &ndata, int dsize){ - if (dsize { - - private: - - public: + private: + public: + /** + Implements the slsReceiverData structure for the moench02 prototype read + out by a module i.e. using the slsReceiver (160x160 pixels, 40 packets + 1286 large etc.) \param c crosstalk parameter for the output buffer + fwrite(&ff, 8, 1,of);//write detector frame number + fwrite(&ifr, 8, 1,of);//write datset frame number + fwrite(data,2,NX*NY,of);//write reordered data + */ + moench03T1ReorderedData() + : slsDetectorData(400, 400, 2 * 400 * 400 + 2 * 8) { + for (int iy = 0; iy < 400; iy++) + for (int ix = 0; ix < 400; ix++) + dataMap[iy][ix] = 2 * 8 + 2 * (iy * 400 + ix); + int ibyte; + for (ibyte = 0; ibyte < 8; ibyte++) { + xmap[ibyte] = -1; + ymap[ibyte] = -1; + } + for (ibyte = 0; ibyte < 400 * 400; ibyte++) { + xmap[ibyte + 8] = ibyte % 400; + ymap[ibyte + 8] = ibyte / 400; + } - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer + // cout << "data struct created" << endl; + }; - fwrite(&ff, 8, 1,of);//write detector frame number - fwrite(&ifr, 8, 1,of);//write datset frame number - fwrite(data,2,NX*NY,of);//write reordered data - */ - moench03T1ReorderedData(): slsDetectorData(400, 400, 2*400*400+2*8) { - for (int iy=0; iy<400; iy++) - for (int ix=0; ix<400; ix++) - dataMap[iy][ix]=2*8+2*(iy*400+ix); - - int ibyte; - for (ibyte=0; ibyte<8; ibyte++){ - xmap[ibyte]=-1; - ymap[ibyte]=-1; + /** + + Returns the frame number for the given dataset. Purely virtual func. + \param buff pointer to the dataset + \returns frame number + + */ + + /* class jfrau_packet_header_t { */ + /* public: */ + /* unsigned char reserved[4]; */ + /* unsigned char packetNumber[1]; */ + /* unsigned char frameNumber[3]; */ + /* unsigned char bunchid[8]; */ + /* }; */ + + int getFrameNumber(char *buff) { return *((int *)buff); }; + + /* /\** */ + + /* Loops over a memory slot until a complete frame is found (i.e. all + * packets 0 to nPackets, same frame number). purely virtual func */ + /* \param data pointer to the memory to be analyzed */ + /* \param ndata reference to the amount of data found for the frame, in + * case the frame is incomplete at the end of the memory slot */ + /* \param dsize size of the memory slot to be analyzed */ + /* \returns pointer to the beginning of the last good frame (might be + * incomplete if ndata smaller than dataSize), or NULL if no frame is found + */ + + /* *\/ */ + /* virtual char *findNextFrame(char *data, int &ndata, int + * dsize){ndata=dsize; setDataSize(dsize); return data;}; */ + + /* /\** */ + + /* Loops over a file stream until a complete frame is found (i.e. all + * packets 0 to nPackets, same frame number). Can be overloaded for + * different kind of detectors! */ + /* \param filebin input file stream (binary) */ + /* \returns pointer to the begin of the last good frame, NULL if no + * frame is found or last frame is incomplete */ + + /* *\/ */ + /* virtual char *readNextFrame(ifstream &filebin){ */ + /* // int afifo_length=0; */ + /* uint16_t *afifo_cont; */ + /* int ib=0; */ + /* if (filebin.is_open()) { */ + /* afifo_cont=new uint16_t[dataSize/2]; */ + /* while (filebin.read(((char*)afifo_cont)+ib,2)) { */ + /* ib+=2; */ + /* if (ib==dataSize) break; */ + /* } */ + /* if (ib>0) { */ + /* iframe++; */ + /* // cout << ib << "-" << endl; */ + /* return (char*)afifo_cont; */ + /* } else { */ + /* delete [] afifo_cont; */ + /* return NULL; */ + /* } */ + /* } */ + /* return NULL; */ + /* }; */ + + virtual char *readNextFrame(ifstream &filebin) { + int ff = -1, np = -1; + return readNextFrame(filebin, ff, np); + }; + + virtual char *readNextFrame(ifstream &filebin, int &ff) { + int np = -1; + return readNextFrame(filebin, ff, np); + }; + + virtual char *readNextFrame(ifstream &filebin, int &ff, int &np) { + char *data = new char[dataSize]; + char *d = readNextFrame(filebin, ff, np, data); + if (d == NULL) { + delete[] data; + data = NULL; + } + return data; } - for (ibyte=0; ibyte<400*400; ibyte++){ - xmap[ibyte+8]=ibyte%400; - ymap[ibyte+8]=ibyte/400; + + virtual char *readNextFrame(ifstream &filebin, int &ff, int &np, + char *data) { + char *retval = 0; + int nd; + int fnum = -1; + np = 0; + int pn; + + if (ff >= 0) + fnum = ff; + + if (filebin.is_open()) { + if (filebin.read(data, dataSize)) { + ff = getFrameNumber(data); + np = 40; + return data; + } + } + return NULL; + }; + + /** + + Loops over a memory slot until a complete frame is found (i.e. all + packets 0 to nPackets, same frame number). purely virtual func \param + data pointer to the memory to be analyzed \param ndata reference to the + amount of data found for the frame, in case the frame is incomplete at + the end of the memory slot \param dsize size of the memory slot to be + analyzed \returns pointer to the beginning of the last good frame (might + be incomplete if ndata smaller than dataSize), or NULL if no frame is + found + + */ + virtual char *findNextFrame(char *data, int &ndata, int dsize) { + if (dsize < dataSize) + ndata = dsize; + else + ndata = dataSize; + return data; } - - // cout << "data struct created" << endl; - }; - - - - /** - - Returns the frame number for the given dataset. Purely virtual func. - \param buff pointer to the dataset - \returns frame number - - */ - -/* class jfrau_packet_header_t { */ -/* public: */ -/* unsigned char reserved[4]; */ -/* unsigned char packetNumber[1]; */ -/* unsigned char frameNumber[3]; */ -/* unsigned char bunchid[8]; */ -/* }; */ - - - - int getFrameNumber(char *buff){return *((int*)buff);}; - -/* /\** */ - -/* Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func */ -/* \param data pointer to the memory to be analyzed */ -/* \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot */ -/* \param dsize size of the memory slot to be analyzed */ -/* \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found */ - -/* *\/ */ -/* virtual char *findNextFrame(char *data, int &ndata, int dsize){ndata=dsize; setDataSize(dsize); return data;}; */ - - -/* /\** */ - -/* Loops over a file stream until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). Can be overloaded for different kind of detectors! */ -/* \param filebin input file stream (binary) */ -/* \returns pointer to the begin of the last good frame, NULL if no frame is found or last frame is incomplete */ - -/* *\/ */ -/* virtual char *readNextFrame(ifstream &filebin){ */ -/* // int afifo_length=0; */ -/* uint16_t *afifo_cont; */ -/* int ib=0; */ -/* if (filebin.is_open()) { */ -/* afifo_cont=new uint16_t[dataSize/2]; */ -/* while (filebin.read(((char*)afifo_cont)+ib,2)) { */ -/* ib+=2; */ -/* if (ib==dataSize) break; */ -/* } */ -/* if (ib>0) { */ -/* iframe++; */ -/* // cout << ib << "-" << endl; */ -/* return (char*)afifo_cont; */ -/* } else { */ -/* delete [] afifo_cont; */ -/* return NULL; */ -/* } */ -/* } */ -/* return NULL; */ -/* }; */ - - - virtual char *readNextFrame(ifstream &filebin) { - int ff=-1, np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int &ff) { - int np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np) { - char *data=new char[dataSize]; - char *d=readNextFrame(filebin, ff, np, data); - if (d==NULL) {delete [] data; data=NULL;} - return data; - } - - - - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np, char *data) { - char *retval=0; - int nd; - int fnum = -1; - np=0; - int pn; - - if (ff>=0) - fnum=ff; - - if (filebin.is_open()) { - if (filebin.read(data, dataSize) ){ - ff=getFrameNumber(data); - np=40; - return data; - } - } - return NULL; - - - - }; - - - - /** - - Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func - \param data pointer to the memory to be analyzed - \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot - \param dsize size of the memory slot to be analyzed - \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found - - */ - virtual char *findNextFrame(char *data, int &ndata, int dsize){ - if (dsize { - - private: - - int iframe; - int nadc; - int sc_width; - int sc_height; - const int nPackets; /**(400, 400, ps * npackets), packetSize(ps), + nPackets(npackets) { + + int nadc = 32; + int sc_width = 25; + int sc_height = 200; + + int adc_nr[32] = {300, 325, 350, 375, 300, 325, 350, 375, 200, 225, 250, + 275, 200, 225, 250, 275, 100, 125, 150, 175, 100, 125, + 150, 175, 0, 25, 50, 75, 0, 25, 50, 75}; + + int row, col; + + int isample; + int iadc; + int ix, iy; + + // int npackets=40; + int i; + int adc4(0); + + for (int ip = 0; ip < npackets; ip++) { + for (int is = 0; is < 128; is++) { + + for (iadc = 0; iadc < nadc; iadc++) { + i = 128 * ip + is; + adc4 = (int)iadc / 4; + if (i < sc_width * sc_height) { + // for (int i=0; i= 8192 * 40) + cout << "Error: pointer " << dataMap[row][col] + << " out of range " << endl; + } + } + } + } + + int ipacket; + int ibyte; + int ii = 0; + for (int ipacket = 0; ipacket < npackets; ipacket++) { + for (int ibyte = 0; ibyte < 8192 / 2; ibyte++) { + i = ipacket * 8208 / 2 + ibyte; + /* if (ibyte<8) { */ + /* //header! */ + /* xmap[i]=-1; */ + /* ymap[i]=-1; */ + /* } else { */ + // ii=ibyte+128*32*ipacket; + isample = ii / nadc; + iadc = ii % nadc; + adc4 = (int)iadc / 4; + ix = isample % sc_width; + iy = isample / sc_width; + if (adc4 % 2 == 0) { + xmap[i] = adc_nr[iadc] + ix; + ymap[i] = ny / 2 - 1 - iy; + } else { + xmap[i] = adc_nr[iadc] + ix; + ymap[i] = ny / 2 + iy; + } + + ii++; + // } + } + } + + iframe = 0; + // cout << "data struct created" << endl; + }; + + /** + + Returns the frame number for the given dataset. Purely virtual func. + \param buff pointer to the dataset + \returns frame number + + */ + + /* class jfrau_packet_header_t { */ + /* public: */ + /* unsigned char reserved[4]; */ + /* unsigned char packetNumber[1]; */ + /* unsigned char frameNumber[3]; */ + /* unsigned char bunchid[8]; */ + /* }; */ + + int getFrameNumber(char *buff) { + return iframe; + }; //*((int*)(buff+5))&0xffffff;}; + + /** + + Returns the packet number for the given dataset. purely virtual func + \param buff pointer to the dataset + \returns packet number number + */ + int getPacketNumber(char *buff) { + return 0; + } //((*(((int*)(buff+4))))&0xff)+1;}; - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer + /* /\** */ - */ - moench03T1ZmqData(int npackets=40, int ps=8192): slsDetectorData(400, 400, ps*npackets), packetSize(ps), nPackets(npackets) { + /* Loops over a memory slot until a complete frame is found (i.e. all + * packets 0 to nPackets, same frame number). purely virtual func */ + /* \param data pointer to the memory to be analyzed */ + /* \param ndata reference to the amount of data found for the frame, in + * case the frame is incomplete at the end of the memory slot */ + /* \param dsize size of the memory slot to be analyzed */ + /* \returns pointer to the beginning of the last good frame (might be + * incomplete if ndata smaller than dataSize), or NULL if no frame is found + */ - int nadc=32; - int sc_width=25; - int sc_height=200; + /* *\/ */ + /* virtual char *findNextFrame(char *data, int &ndata, int + * dsize){ndata=dsize; setDataSize(dsize); return data;}; */ - int adc_nr[32]={300,325,350,375,300,325,350,375, \ - 200,225,250,275,200,225,250,275,\ - 100,125,150,175,100,125,150,175,\ - 0,25,50,75,0,25,50,75}; + /* /\** */ - int row, col; + /* Loops over a file stream until a complete frame is found (i.e. all + * packets 0 to nPackets, same frame number). Can be overloaded for + * different kind of detectors! */ + /* \param filebin input file stream (binary) */ + /* \returns pointer to the begin of the last good frame, NULL if no + * frame is found or last frame is incomplete */ - int isample; - int iadc; - int ix, iy; - - // int npackets=40; - int i; - int adc4(0); + /* *\/ */ + /* virtual char *readNextFrame(ifstream &filebin){ */ + /* // int afifo_length=0; */ + /* uint16_t *afifo_cont; */ + /* int ib=0; */ + /* if (filebin.is_open()) { */ + /* afifo_cont=new uint16_t[dataSize/2]; */ + /* while (filebin.read(((char*)afifo_cont)+ib,2)) { */ + /* ib+=2; */ + /* if (ib==dataSize) break; */ + /* } */ + /* if (ib>0) { */ + /* iframe++; */ + /* // cout << ib << "-" << endl; */ + /* return (char*)afifo_cont; */ + /* } else { */ + /* delete [] afifo_cont; */ + /* return NULL; */ + /* } */ + /* } */ + /* return NULL; */ + /* }; */ - for (int ip=0; ip=8192*40) - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - } - } - } + virtual char *readNextFrame(ifstream &filebin, int &ff) { + int np = -1; + return readNextFrame(filebin, ff, np); + }; + + virtual char *readNextFrame(ifstream &filebin, int &ff, int &np) { + char *data = new char[packetSize * nPackets]; + char *d = readNextFrame(filebin, ff, np, data); + if (d == NULL) { + delete[] data; + data = NULL; + } + return data; } - int ipacket; - int ibyte; - int ii=0; - for (int ipacket=0; ipacket= 0) + fnum = ff; + + if (filebin.is_open()) { + if (filebin.read(data, packetSize * nPackets)) { + iframe++; + ff = iframe; + return data; + } + } + return NULL; + }; + + /** + + Loops over a memory slot until a complete frame is found (i.e. all + packets 0 to nPackets, same frame number). purely virtual func \param + data pointer to the memory to be analyzed \param ndata reference to the + amount of data found for the frame, in case the frame is incomplete at + the end of the memory slot \param dsize size of the memory slot to be + analyzed \returns pointer to the beginning of the last good frame (might + be incomplete if ndata smaller than dataSize), or NULL if no frame is + found + + */ + virtual char *findNextFrame(char *data, int &ndata, int dsize) { + if (dsize < packetSize * nPackets) + ndata = dsize; + else + ndata = packetSize * nPackets; + return data; } - - - - - iframe=0; - // cout << "data struct created" << endl; - }; - - - - /** - - Returns the frame number for the given dataset. Purely virtual func. - \param buff pointer to the dataset - \returns frame number - - */ - -/* class jfrau_packet_header_t { */ -/* public: */ -/* unsigned char reserved[4]; */ -/* unsigned char packetNumber[1]; */ -/* unsigned char frameNumber[3]; */ -/* unsigned char bunchid[8]; */ -/* }; */ - - - - int getFrameNumber(char *buff){return iframe;};//*((int*)(buff+5))&0xffffff;}; - - /** - - Returns the packet number for the given dataset. purely virtual func - \param buff pointer to the dataset - \returns packet number number - - - - */ - int getPacketNumber(char *buff){return 0;}//((*(((int*)(buff+4))))&0xff)+1;}; - -/* /\** */ - -/* Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func */ -/* \param data pointer to the memory to be analyzed */ -/* \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot */ -/* \param dsize size of the memory slot to be analyzed */ -/* \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found */ - -/* *\/ */ -/* virtual char *findNextFrame(char *data, int &ndata, int dsize){ndata=dsize; setDataSize(dsize); return data;}; */ - - -/* /\** */ - -/* Loops over a file stream until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). Can be overloaded for different kind of detectors! */ -/* \param filebin input file stream (binary) */ -/* \returns pointer to the begin of the last good frame, NULL if no frame is found or last frame is incomplete */ - -/* *\/ */ -/* virtual char *readNextFrame(ifstream &filebin){ */ -/* // int afifo_length=0; */ -/* uint16_t *afifo_cont; */ -/* int ib=0; */ -/* if (filebin.is_open()) { */ -/* afifo_cont=new uint16_t[dataSize/2]; */ -/* while (filebin.read(((char*)afifo_cont)+ib,2)) { */ -/* ib+=2; */ -/* if (ib==dataSize) break; */ -/* } */ -/* if (ib>0) { */ -/* iframe++; */ -/* // cout << ib << "-" << endl; */ -/* return (char*)afifo_cont; */ -/* } else { */ -/* delete [] afifo_cont; */ -/* return NULL; */ -/* } */ -/* } */ -/* return NULL; */ -/* }; */ - - - virtual char *readNextFrame(ifstream &filebin) { - int ff=-1, np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int &ff) { - int np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np) { - char *data=new char[packetSize*nPackets]; - char *d=readNextFrame(filebin, ff, np, data); - if (d==NULL) {delete [] data; data=NULL;} - return data; - } - - - - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np, char *data) { - char *retval=0; - int nd; - int fnum = -1; - np=0; - int pn; - - - if (ff>=0) - fnum=ff; - - if (filebin.is_open()) { - if (filebin.read(data, packetSize*nPackets) ){ - iframe++; - ff=iframe; - return data; - } - } - return NULL; - - - - }; - - - - /** - - Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func - \param data pointer to the memory to be analyzed - \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot - \param dsize size of the memory slot to be analyzed - \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found - - */ - virtual char *findNextFrame(char *data, int &ndata, int dsize){ - if (dsize { - - private: - - // int iframe; - int nadc; - int sc_width; - int sc_height; - const int nSamples; - const int offset; + private: + // int iframe; + int nadc; + int sc_width; + int sc_height; + const int nSamples; + const int offset; + double ghost[200][25]; + double xtalk; - double ghost[200][25]; - double xtalk; + public: + /** + Implements the slsReceiverData structure for the moench02 prototype read + out by a module i.e. using the slsReceiver (160x160 pixels, 40 packets + 1286 large etc.) \param c crosstalk parameter for the output buffer - public: + */ + // moench03T1ZmqDataNew(int ns=5000): slsDetectorData(400, 400, + // ns*32*2+sizeof(int)), nSamples(ns), offset(sizeof(int)), xtalk(0.00021) { + moench03T1ZmqDataNew(int ns = 5000, int oo = 2 * 2) + : slsDetectorData(400, 400, ns * 32 * 2 + oo), nSamples(ns), + offset(oo), xtalk(0.00021) { + cout << "M0.3" << endl; + int nadc = 32; + int sc_width = 25; + int sc_height = 200; + int adc_nr[32] = {300, 325, 350, 375, 300, 325, 350, 375, 200, 225, 250, + 275, 200, 225, 250, 275, 100, 125, 150, 175, 100, 125, + 150, 175, 0, 25, 50, 75, 0, 25, 50, 75}; + /* int adc_nr[32]={350,375,150,175,350,375,150,175, \ + 300,325,100,125,300,325,100,125,\ + 250,275,50,75,250,275,50,75,\ + 200,225,0,25,200,225,0,25}; + */ + int row, col; + int isample; + int iadc; + int ix, iy; - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer + // int npackets=40; + int i; + int adc4(0); - */ - // moench03T1ZmqDataNew(int ns=5000): slsDetectorData(400, 400, ns*32*2+sizeof(int)), nSamples(ns), offset(sizeof(int)), xtalk(0.00021) { - moench03T1ZmqDataNew(int ns=5000, int oo=2*2): slsDetectorData(400, 400, ns*32*2+oo), nSamples(ns), offset(oo), xtalk(0.00021) { - cout << "M0.3" << endl; - int nadc=32; - int sc_width=25; - int sc_height=200; - - int adc_nr[32]={300,325,350,375,300,325,350,375, \ - 200,225,250,275,200,225,250,275,\ - 100,125,150,175,100,125,150,175,\ - 0,25,50,75,0,25,50,75}; - - /* int adc_nr[32]={350,375,150,175,350,375,150,175, \ - 300,325,100,125,300,325,100,125,\ - 250,275,50,75,250,275,50,75,\ - 200,225,0,25,200,225,0,25}; - */ - int row, col; - - int isample; - int iadc; - int ix, iy; - - //int npackets=40; - int i; - int adc4(0); - - //for (int ip=0; ip=dataSize) - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - } - } - } - // } + // for (int ip=0; ip= dataSize) + cout << "Error: pointer " << dataMap[row][col] + << " out of range " << endl; + } + } + } + // } - - int ii=0; - - for (i=0; i< dataSize; i++) { - if (i0) { */ + /* iframe++; */ + /* // cout << ib << "-" << endl; */ + /* return (char*)afifo_cont; */ + /* } else { */ + /* delete [] afifo_cont; */ + /* return NULL; */ + /* } */ + /* } */ + /* return NULL; */ + /* }; */ -/* Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func */ -/* \param data pointer to the memory to be analyzed */ -/* \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot */ -/* \param dsize size of the memory slot to be analyzed */ -/* \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found */ + virtual char *readNextFrame(ifstream &filebin) { + int ff = -1, np = -1; + return readNextFrame(filebin, ff, np); + }; -/* *\/ */ -/* virtual char *findNextFrame(char *data, int &ndata, int dsize){ndata=dsize; setDataSize(dsize); return data;}; */ + virtual char *readNextFrame(ifstream &filebin, int &ff) { + int np = -1; + return readNextFrame(filebin, ff, np); + }; + virtual char *readNextFrame(ifstream &filebin, int &ff, int &np) { + char *data = new char[32 * 2 * nSamples]; + char *d = readNextFrame(filebin, ff, np, data); + if (d == NULL) { + delete[] data; + data = NULL; + } + return data; + } -/* /\** */ + virtual char *readNextFrame(ifstream &filebin, int &ff, int &np, + char *data) { + // char *retval=0; + // int nd; + // int fnum = -1; + np = 0; + // int pn; -/* Loops over a file stream until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). Can be overloaded for different kind of detectors! */ -/* \param filebin input file stream (binary) */ -/* \returns pointer to the begin of the last good frame, NULL if no frame is found or last frame is incomplete */ + // if (ff>=0) + // fnum=ff; -/* *\/ */ -/* virtual char *readNextFrame(ifstream &filebin){ */ -/* // int afifo_length=0; */ -/* uint16_t *afifo_cont; */ -/* int ib=0; */ -/* if (filebin.is_open()) { */ -/* afifo_cont=new uint16_t[dataSize/2]; */ -/* while (filebin.read(((char*)afifo_cont)+ib,2)) { */ -/* ib+=2; */ -/* if (ib==dataSize) break; */ -/* } */ -/* if (ib>0) { */ -/* iframe++; */ -/* // cout << ib << "-" << endl; */ -/* return (char*)afifo_cont; */ -/* } else { */ -/* delete [] afifo_cont; */ -/* return NULL; */ -/* } */ -/* } */ -/* return NULL; */ -/* }; */ + if (filebin.is_open()) { + if (filebin.read(data, 32 * 2 * nSamples)) { + // iframe++; + // ff=iframe; + return data; + } + } + return NULL; + }; + /** - virtual char *readNextFrame(ifstream &filebin) { - int ff=-1, np=-1; - return readNextFrame(filebin, ff, np); - }; + Loops over a memory slot until a complete frame is found (i.e. all + packets 0 to nPackets, same frame number). purely virtual func \param + data pointer to the memory to be analyzed \param ndata reference to the + amount of data found for the frame, in case the frame is incomplete at + the end of the memory slot \param dsize size of the memory slot to be + analyzed \returns pointer to the beginning of the last good frame (might + be incomplete if ndata smaller than dataSize), or NULL if no frame is + found - virtual char *readNextFrame(ifstream &filebin, int &ff) { - int np=-1; - return readNextFrame(filebin, ff, np); - }; + */ + virtual char *findNextFrame(char *data, int &ndata, int dsize) { + if (dsize < 32 * 2 * nSamples) + ndata = dsize; + else + ndata = 32 * 2 * nSamples; + return data; + } - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np) { - char *data=new char[32*2*nSamples]; - char *d=readNextFrame(filebin, ff, np, data); - if (d==NULL) {delete [] data; data=NULL;} - return data; - } - - - - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np, char *data) { - //char *retval=0; - // int nd; - //int fnum = -1; - np=0; - // int pn; - - - // if (ff>=0) - // fnum=ff; - - if (filebin.is_open()) { - if (filebin.read(data, 32*2*nSamples) ){ - // iframe++; - //ff=iframe; - return data; - } - } - return NULL; - - - - }; - - - - /** - - Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func - \param data pointer to the memory to be analyzed - \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot - \param dsize size of the memory slot to be analyzed - \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found - - */ - virtual char *findNextFrame(char *data, int &ndata, int dsize){ - if (dsize<32*2*nSamples) ndata=dsize; - else ndata=32*2*nSamples; - return data; - - } - - - - - - - // virtual int setFrameNumber(int ff){iframe=ff}; - - - - - - - - - - -int getPacketNumber(int x, int y) {return 0;}; + // virtual int setFrameNumber(int ff){iframe=ff}; + int getPacketNumber(int x, int y) { return 0; }; }; - - - #endif diff --git a/slsDetectorCalibration/dataStructures/moench03TCtbData.h b/slsDetectorCalibration/dataStructures/moench03TCtbData.h index 71caf17d3..bdf5b74e3 100644 --- a/slsDetectorCalibration/dataStructures/moench03TCtbData.h +++ b/slsDetectorCalibration/dataStructures/moench03TCtbData.h @@ -1,182 +1,166 @@ // SPDX-License-Identifier: LGPL-3.0-or-other // Copyright (C) 2021 Contributors to the SLS Detector Package #ifndef MOENCH03TCTBDATA_H -#define MOENCH03TCTBDATA_H +#define MOENCH03TCTBDATA_H #include "slsDetectorData.h" - - class moench03TCtbData : public slsDetectorData { - private: - - int iframe; - int nadc; - int sc_width; - int sc_height; - public: + private: + int iframe; + int nadc; + int sc_width; + int sc_height; + public: + /** + Implements the slsReceiverData structure for the moench02 prototype read + out by a module i.e. using the slsReceiver (160x160 pixels, 40 packets + 1286 large etc.) \param c crosstalk parameter for the output buffer + */ + moench03TCtbData(int ns = 5000) + : slsDetectorData(400, 400, ns * 2 * 32, NULL, NULL), + nadc(32), sc_width(25), sc_height(200) { - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer + int row, col; - */ - + int isample; + int iadc; + int ix, iy; - moench03TCtbData(int ns=5000): slsDetectorData(400, 400, ns*2*32, NULL, NULL) , nadc(32), sc_width(25), sc_height(200) { + int adc_nr[32] = {300, 325, 350, 375, 300, 325, 350, 375, 200, 225, 250, + 275, 200, 225, 250, 275, 100, 125, 150, 175, 100, 125, + 150, 175, 0, 25, 50, 75, 0, 25, 50, 75}; - - int row, col; + /* int adc_nr[32]={200,225,250,275,300,325,350,375,\ */ + /* 0,25,50,75,100,125,150,175,\ */ + /* 175,150,125,100,75,50,25,0,\ */ + /* 375,350,325,300,275,250,225,200}; */ - int isample; - int iadc; - int ix, iy; + for (iadc = 0; iadc < nadc; iadc++) { + for (int i = 0; i < sc_width * sc_height; i++) { + col = adc_nr[iadc] + (i % sc_width); + if (iadc < 16) { + row = 199 - i / sc_width; + } else { + row = 200 + i / sc_width; + } + dataMap[row][col] = (nadc * i + iadc) * 2; + if (dataMap[row][col] < 0 || dataMap[row][col] >= 2 * 400 * 400) + cout << "Error: pointer " << dataMap[row][col] + << " out of range " << endl; + } + } + int adc4; + for (int i = 0; i < nx * ny; i++) { + isample = i / nadc; + iadc = i % nadc; + ix = isample % sc_width; + iy = isample / sc_width; + adc4 = (int)iadc / 4; + // if (iadc<(nadc/2)) { + if (adc4 % 2 == 0) { + xmap[i] = adc_nr[iadc] + ix; + ymap[i] = ny / 2 - 1 - iy; + } else { + xmap[i] = adc_nr[iadc] + ix; + ymap[i] = ny / 2 + iy; + } + } - + /* for (int i=0; i=2*400*400) - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - - } - } - int adc4; - for (int i=0; i0) { - iframe++; - // cout << ib << "-" << endl; - return (char*)afifo_cont; - } else { - delete [] afifo_cont; - return NULL; - } - } - return NULL; + iframe = 0; + // cout << "data struct created" << endl; }; + /** - + Returns the frame number for the given dataset. Purely virtual func. + \param buff pointer to the dataset + \returns frame number + */ + + virtual int getFrameNumber(char *buff) { + (void)buff; + return iframe; + }; + + /** + + Returns the packet number for the given dataset. purely virtual func + \param buff pointer to the dataset + \returns packet number number + + + virtual int getPacketNumber(char *buff)=0; + + */ + + /** + + Loops over a memory slot until a complete frame is found (i.e. all packets + 0 to nPackets, same frame number). purely virtual func \param data pointer + to the memory to be analyzed \param ndata reference to the amount of data + found for the frame, in case the frame is incomplete at the end of the + memory slot \param dsize size of the memory slot to be analyzed \returns + pointer to the beginning of the last good frame (might be incomplete if + ndata smaller than dataSize), or NULL if no frame is found + + */ + virtual char *findNextFrame(char *data, int &ndata, int dsize) { + ndata = dsize; + setDataSize(dsize); + return data; + }; + + /** + + Loops over a file stream until a complete frame is found (i.e. all packets + 0 to nPackets, same frame number). Can be overloaded for different kind of + detectors! \param filebin input file stream (binary) \returns pointer to + the begin of the last good frame, NULL if no frame is found or last frame + is incomplete + + */ + virtual char *readNextFrame(ifstream &filebin) { + // int afifo_length=0; + uint16_t *afifo_cont; + int ib = 0; + if (filebin.is_open()) { + afifo_cont = new uint16_t[dataSize / 2]; + while (filebin.read(((char *)afifo_cont) + ib, 2)) { + ib += 2; + if (ib == dataSize) + break; + } + if (ib > 0) { + iframe++; + // cout << ib << "-" << endl; + return (char *)afifo_cont; + } else { + delete[] afifo_cont; + return NULL; + } + } + return NULL; + }; }; - - #endif diff --git a/slsDetectorCalibration/dataStructures/moench04CtbReceiver10GbData.h b/slsDetectorCalibration/dataStructures/moench04CtbReceiver10GbData.h index 556246699..1c8bb4c5d 100644 --- a/slsDetectorCalibration/dataStructures/moench04CtbReceiver10GbData.h +++ b/slsDetectorCalibration/dataStructures/moench04CtbReceiver10GbData.h @@ -1,296 +1,301 @@ // SPDX-License-Identifier: LGPL-3.0-or-other // Copyright (C) 2021 Contributors to the SLS Detector Package #ifndef MOENCH04REC10GBDATA_H -#define MOENCH04REC10GBDATA_H +#define MOENCH04REC10GBDATA_H #include "slsDetectorData.h" //#define VERSION_V2 - /** - @short structure for a Detector Packet or Image Header - @li frameNumber is the frame number - @li expLength is the subframe number (32 bit eiger) or real time exposure time in 100ns (others) - @li packetNumber is the packet number - @li bunchId is the bunch id from beamline - @li timestamp is the time stamp with 10 MHz clock - @li modId is the unique module id (unique even for left, right, top, bottom) - @li xCoord is the x coordinate in the complete detector system - @li yCoord is the y coordinate in the complete detector system - @li zCoord is the z coordinate in the complete detector system - @li debug is for debugging purposes - @li roundRNumber is the round robin set number - @li detType is the detector type see :: detectorType - @li version is the version number of this structure format - */ - typedef struct { - uint64_t frameNumber; /**< is the frame number */ - uint32_t expLength; /**< is the subframe number (32 bit eiger) or real time exposure time in 100ns (others) */ - uint32_t packetNumber; /**< is the packet number */ - uint64_t bunchId; /**< is the bunch id from beamline */ - uint64_t timestamp; /**< is the time stamp with 10 MHz clock */ - uint16_t modId; /**< is the unique module id (unique even for left, right, top, bottom) */ - uint16_t xCoord; /**< is the x coordinate in the complete detector system */ - uint16_t yCoord; /**< is the y coordinate in the complete detector system */ - uint16_t zCoord; /**< is the z coordinate in the complete detector system */ - uint32_t debug; /**< is for debugging purposes */ - uint16_t roundRNumber; /**< is the round robin set number */ - uint8_t detType; /**< is the detector type see :: detectorType */ - uint8_t version; /**< is the version number of this structure format */ - uint64_t packetCaught[8]; /**< is the version number of this structure format */ - - } sls_detector_header; - - +/** + @short structure for a Detector Packet or Image Header + @li frameNumber is the frame number + @li expLength is the subframe number (32 bit eiger) or real time exposure + time in 100ns (others) + @li packetNumber is the packet number + @li bunchId is the bunch id from beamline + @li timestamp is the time stamp with 10 MHz clock + @li modId is the unique module id (unique even for left, right, top, bottom) + @li xCoord is the x coordinate in the complete detector system + @li yCoord is the y coordinate in the complete detector system + @li zCoord is the z coordinate in the complete detector system + @li debug is for debugging purposes + @li roundRNumber is the round robin set number + @li detType is the detector type see :: detectorType + @li version is the version number of this structure format +*/ +typedef struct { + uint64_t frameNumber; /**< is the frame number */ + uint32_t expLength; /**< is the subframe number (32 bit eiger) or real time + exposure time in 100ns (others) */ + uint32_t packetNumber; /**< is the packet number */ + uint64_t bunchId; /**< is the bunch id from beamline */ + uint64_t timestamp; /**< is the time stamp with 10 MHz clock */ + uint16_t modId; /**< is the unique module id (unique even for left, right, + top, bottom) */ + uint16_t xCoord; /**< is the x coordinate in the complete detector system */ + uint16_t yCoord; /**< is the y coordinate in the complete detector system */ + uint16_t zCoord; /**< is the z coordinate in the complete detector system */ + uint32_t debug; /**< is for debugging purposes */ + uint16_t roundRNumber; /**< is the round robin set number */ + uint8_t detType; /**< is the detector type see :: detectorType */ + uint8_t version; /**< is the version number of this structure format */ + uint64_t + packetCaught[8]; /**< is the version number of this structure format */ +} sls_detector_header; class moench04CtbReceiver10GbData : public slsDetectorData { - - private: - - int iframe; - int nadc; - int sc_width; - int sc_height; - const int aSamples; - const int dSamples; + private: + int iframe; + int nadc; + int sc_width; + int sc_height; + const int aSamples; + const int dSamples; - public: + public: + /** + Implements the slsReceiverData structure for the moench02 prototype read + out by a module i.e. using the slsReceiver (160x160 pixels, 40 packets + 1286 large etc.) \param c crosstalk parameter for the output buffer + + */ + moench04CtbReceiver10GbData(int nas = 5000, int nds = 0) + : slsDetectorData( + 400, 400, nas * 2 * 32 + sizeof(sls_detector_header) + nds * 8), + aSamples(nas), dSamples(nds) { + + int nadc = 32; + int sc_width = 25; + int sc_height = 200; + + int adc_nr[32] = {9, 8, 11, 10, 13, 12, 15, 14, 1, 0, 3, + 2, 5, 4, 7, 6, 23, 22, 21, 20, 19, 18, + 17, 16, 31, 30, 29, 28, 27, 26, 25, 24}; + + int row, col; + + int isample; + int iadc; + int ix, iy; + + int npackets = 40; + int i; + int adc4(0); + + for (int ip = 0; ip < npackets; ip++) { + for (int is = 0; is < 128; is++) { + + for (iadc = 0; iadc < nadc; iadc++) { + i = 128 * ip + is; + adc4 = (int)iadc / 4; + if (i < sc_width * sc_height) { + // for (int i=0; i 0) { + row = 199 - i / sc_width; + } else { + row = 200 + i / sc_width; + } + if (nds > 0) + dataMap[row][col] = + sizeof(sls_detector_header) + + ((nadc + 4) * i + iadc) * 2; //+16*(ip+1); + else + dataMap[row][col] = + sizeof(sls_detector_header) + + (nadc * i + iadc) * 2; //+16*(ip+1); + if (dataMap[row][col] < 0 || + dataMap[row][col] >= aSamples * 2 * 32) + cout << "Error: pointer " << dataMap[row][col] + << " out of range " << endl; + } + } + } + } + + int ipacket; + int ibyte; + int ii = 0; + for (ibyte = 0; ibyte < sizeof(sls_detector_header) / 2; ibyte++) { + xmap[ibyte] = -1; + ymap[ibyte] = -1; + } + /* int off=sizeof(sls_detector_header)/2; */ + + /* for (ibyte=0; ibyteframeNumber; + }; //*((int*)(buff+5))&0xffffff;}; + + /** + + Returns the packet number for the given dataset. purely virtual func + \param buff pointer to the dataset + \returns packet number number + */ + int getPacketNumber(char *buff) { + return ((sls_detector_header *)buff)->packetNumber; + } //((*(((int*)(buff+4))))&0xff)+1;}; - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer + /* /\** */ - */ - moench04CtbReceiver10GbData(int nas=5000, int nds=0): slsDetectorData(400, 400, nas*2*32+sizeof(sls_detector_header)+nds*8), aSamples(nas), dSamples(nds) { + /* Loops over a memory slot until a complete frame is found (i.e. all + * packets 0 to nPackets, same frame number). purely virtual func */ + /* \param data pointer to the memory to be analyzed */ + /* \param ndata reference to the amount of data found for the frame, in + * case the frame is incomplete at the end of the memory slot */ + /* \param dsize size of the memory slot to be analyzed */ + /* \returns pointer to the beginning of the last good frame (might be + * incomplete if ndata smaller than dataSize), or NULL if no frame is found + */ - int nadc=32; - int sc_width=25; - int sc_height=200; + /* *\/ */ + /* virtual char *findNextFrame(char *data, int &ndata, int + * dsize){ndata=dsize; setDataSize(dsize); return data;}; */ - int adc_nr[32]={9, 8,11,10,13,12,15,14,1,0,3,2,5,4,7,6,23,22,21,20,19,18,17,16,31,30,29,28,27,26,25,24 }; + /* /\** */ - int row, col; + /* Loops over a file stream until a complete frame is found (i.e. all + * packets 0 to nPackets, same frame number). Can be overloaded for + * different kind of detectors! */ + /* \param filebin input file stream (binary) */ + /* \returns pointer to the begin of the last good frame, NULL if no + * frame is found or last frame is incomplete */ - int isample; - int iadc; - int ix, iy; - - int npackets=40; - int i; - int adc4(0); + /* *\/ */ + /* virtual char *readNextFrame(ifstream &filebin){ */ + /* // int afifo_length=0; */ + /* uint16_t *afifo_cont; */ + /* int ib=0; */ + /* if (filebin.is_open()) { */ + /* afifo_cont=new uint16_t[dataSize/2]; */ + /* while (filebin.read(((char*)afifo_cont)+ib,2)) { */ + /* ib+=2; */ + /* if (ib==dataSize) break; */ + /* } */ + /* if (ib>0) { */ + /* iframe++; */ + /* // cout << ib << "-" << endl; */ + /* return (char*)afifo_cont; */ + /* } else { */ + /* delete [] afifo_cont; */ + /* return NULL; */ + /* } */ + /* } */ + /* return NULL; */ + /* }; */ - for (int ip=0; ip0) { - row=199-i/sc_width; - } else { - row=200+i/sc_width; - } - if (nds>0) - dataMap[row][col]=sizeof(sls_detector_header)+((nadc+4)*i+iadc)*2;//+16*(ip+1); - else - dataMap[row][col]=sizeof(sls_detector_header)+(nadc*i+iadc)*2;//+16*(ip+1); - if (dataMap[row][col]<0 || dataMap[row][col]>=aSamples*2*32) - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - } - } - } + virtual char *readNextFrame(ifstream &filebin, int &ff) { + int np = -1; + return readNextFrame(filebin, ff, np); + }; + + virtual char *readNextFrame(ifstream &filebin, int &ff, int &np) { + char *data = new char[dataSize]; + char *d = readNextFrame(filebin, ff, np, data); + if (d == NULL) { + delete[] data; + data = NULL; + } + return data; } - int ipacket; - int ibyte; - int ii=0; - for (ibyte=0; ibyte= 0) + fnum = ff; + + if (filebin.is_open()) { + if (filebin.read(data, dataSize)) { + ff = getFrameNumber(data); + np = getPacketNumber(data); + return data; + } + } + return NULL; + }; + + /** + + Loops over a memory slot until a complete frame is found (i.e. all + packets 0 to nPackets, same frame number). purely virtual func \param + data pointer to the memory to be analyzed \param ndata reference to the + amount of data found for the frame, in case the frame is incomplete at + the end of the memory slot \param dsize size of the memory slot to be + analyzed \returns pointer to the beginning of the last good frame (might + be incomplete if ndata smaller than dataSize), or NULL if no frame is + found + + */ + virtual char *findNextFrame(char *data, int &ndata, int dsize) { + if (dsize < dataSize) + ndata = dsize; + else + ndata = dataSize; + return data; } - /* int off=sizeof(sls_detector_header)/2; */ - - /* for (ibyte=0; ibyteframeNumber;};//*((int*)(buff+5))&0xffffff;}; - - /** - - Returns the packet number for the given dataset. purely virtual func - \param buff pointer to the dataset - \returns packet number number - - - - */ - int getPacketNumber(char *buff){return ((sls_detector_header*)buff)->packetNumber;}//((*(((int*)(buff+4))))&0xff)+1;}; - -/* /\** */ - -/* Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func */ -/* \param data pointer to the memory to be analyzed */ -/* \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot */ -/* \param dsize size of the memory slot to be analyzed */ -/* \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found */ - -/* *\/ */ -/* virtual char *findNextFrame(char *data, int &ndata, int dsize){ndata=dsize; setDataSize(dsize); return data;}; */ - - -/* /\** */ - -/* Loops over a file stream until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). Can be overloaded for different kind of detectors! */ -/* \param filebin input file stream (binary) */ -/* \returns pointer to the begin of the last good frame, NULL if no frame is found or last frame is incomplete */ - -/* *\/ */ -/* virtual char *readNextFrame(ifstream &filebin){ */ -/* // int afifo_length=0; */ -/* uint16_t *afifo_cont; */ -/* int ib=0; */ -/* if (filebin.is_open()) { */ -/* afifo_cont=new uint16_t[dataSize/2]; */ -/* while (filebin.read(((char*)afifo_cont)+ib,2)) { */ -/* ib+=2; */ -/* if (ib==dataSize) break; */ -/* } */ -/* if (ib>0) { */ -/* iframe++; */ -/* // cout << ib << "-" << endl; */ -/* return (char*)afifo_cont; */ -/* } else { */ -/* delete [] afifo_cont; */ -/* return NULL; */ -/* } */ -/* } */ -/* return NULL; */ -/* }; */ - - - virtual char *readNextFrame(ifstream &filebin) { - int ff=-1, np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int &ff) { - int np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np) { - char *data=new char[dataSize]; - char *d=readNextFrame(filebin, ff, np, data); - if (d==NULL) {delete [] data; data=NULL;} - return data; - } - - - - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np, char *data) { - char *retval=0; - int nd; - int fnum = -1; - np=0; - int pn; - - // cout << dataSize << endl; - if (ff>=0) - fnum=ff; - - if (filebin.is_open()) { - if (filebin.read(data, dataSize) ){ - ff=getFrameNumber(data); - np=getPacketNumber(data); - return data; - } - } - return NULL; - - - - }; - - - - /** - - Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func - \param data pointer to the memory to be analyzed - \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot - \param dsize size of the memory slot to be analyzed - \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found - - */ - virtual char *findNextFrame(char *data, int &ndata, int dsize){ - if (dsize { - - private: - - int iframe; - int nadc; - int sc_width; - int sc_height; - const int aSamples; - const int dSamples; + private: + int iframe; + int nadc; + int sc_width; + int sc_height; + const int aSamples; + const int dSamples; - public: + public: + /** + Implements the slsReceiverData structure for the moench02 prototype read + out by a module i.e. using the slsReceiver (160x160 pixels, 40 packets + 1286 large etc.) \param c crosstalk parameter for the output buffer + + */ + moench04CtbReceiverData(int nas = 5000, int nds = 0) + : slsDetectorData( + 400, 400, nas * 2 * 32 + sizeof(sls_detector_header) + nds * 8), + aSamples(nas), dSamples(nds) { + + int nadc = 32; + int sc_width = 25; + int sc_height = 200; + + int adc_nr[32] = {9, 8, 11, 10, 13, 12, 15, 14, 1, 0, 3, + 2, 5, 4, 7, 6, 23, 22, 21, 20, 19, 18, + 17, 16, 31, 30, 29, 28, 27, 26, 25, 24}; + + int row, col; + + int isample; + int iadc; + int ix, iy; + + int npackets = 40; + int i; + int adc4(0); + + for (int ip = 0; ip < npackets; ip++) { + for (int is = 0; is < 128; is++) { + + for (iadc = 0; iadc < nadc; iadc++) { + i = 128 * ip + is; + adc4 = (int)iadc / 4; + if (i < sc_width * sc_height) { + // for (int i=0; i 0) { + row = 199 - i / sc_width; + } else { + row = 200 + i / sc_width; + } + dataMap[row][col] = sizeof(sls_detector_header) + + (nadc * i + iadc) * 2; //+16*(ip+1); + if (dataMap[row][col] < 0 || + dataMap[row][col] >= + aSamples * 2 * 32 + sizeof(sls_detector_header)) + cout << "Error: pointer " << dataMap[row][col] + << " out of range " << endl; + } + } + } + } + + int ipacket; + int ibyte; + int ii = 0; + for (ibyte = 0; ibyte < sizeof(sls_detector_header) / 2; ibyte++) { + xmap[ibyte] = -1; + ymap[ibyte] = -1; + } + /* int off=sizeof(sls_detector_header)/2; */ + + /* for (ibyte=0; ibyteframeNumber; + }; //*((int*)(buff+5))&0xffffff;}; + + /** + + Returns the packet number for the given dataset. purely virtual func + \param buff pointer to the dataset + \returns packet number number + */ + int getPacketNumber(char *buff) { + return ((sls_detector_header *)buff)->packetNumber; + } //((*(((int*)(buff+4))))&0xff)+1;}; - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer + /* /\** */ - */ - moench04CtbReceiverData(int nas=5000, int nds=0): slsDetectorData(400, 400, nas*2*32+sizeof(sls_detector_header)+nds*8), aSamples(nas), dSamples(nds) { + /* Loops over a memory slot until a complete frame is found (i.e. all + * packets 0 to nPackets, same frame number). purely virtual func */ + /* \param data pointer to the memory to be analyzed */ + /* \param ndata reference to the amount of data found for the frame, in + * case the frame is incomplete at the end of the memory slot */ + /* \param dsize size of the memory slot to be analyzed */ + /* \returns pointer to the beginning of the last good frame (might be + * incomplete if ndata smaller than dataSize), or NULL if no frame is found + */ - int nadc=32; - int sc_width=25; - int sc_height=200; + /* *\/ */ + /* virtual char *findNextFrame(char *data, int &ndata, int + * dsize){ndata=dsize; setDataSize(dsize); return data;}; */ - int adc_nr[32]={9, 8,11,10,13,12,15,14,1,0,3,2,5,4,7,6,23,22,21,20,19,18,17,16,31,30,29,28,27,26,25,24 }; + /* /\** */ - int row, col; + /* Loops over a file stream until a complete frame is found (i.e. all + * packets 0 to nPackets, same frame number). Can be overloaded for + * different kind of detectors! */ + /* \param filebin input file stream (binary) */ + /* \returns pointer to the begin of the last good frame, NULL if no + * frame is found or last frame is incomplete */ - int isample; - int iadc; - int ix, iy; - - int npackets=40; - int i; - int adc4(0); + /* *\/ */ + /* virtual char *readNextFrame(ifstream &filebin){ */ + /* // int afifo_length=0; */ + /* uint16_t *afifo_cont; */ + /* int ib=0; */ + /* if (filebin.is_open()) { */ + /* afifo_cont=new uint16_t[dataSize/2]; */ + /* while (filebin.read(((char*)afifo_cont)+ib,2)) { */ + /* ib+=2; */ + /* if (ib==dataSize) break; */ + /* } */ + /* if (ib>0) { */ + /* iframe++; */ + /* // cout << ib << "-" << endl; */ + /* return (char*)afifo_cont; */ + /* } else { */ + /* delete [] afifo_cont; */ + /* return NULL; */ + /* } */ + /* } */ + /* return NULL; */ + /* }; */ - for (int ip=0; ip0) { - row=199-i/sc_width; - } else { - row=200+i/sc_width; - } - dataMap[row][col]=sizeof(sls_detector_header)+(nadc*i+iadc)*2;//+16*(ip+1); - if (dataMap[row][col]<0 || dataMap[row][col]>=aSamples*2*32+sizeof(sls_detector_header)) - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - } - } - } + virtual char *readNextFrame(ifstream &filebin, int &ff) { + int np = -1; + return readNextFrame(filebin, ff, np); + }; + + virtual char *readNextFrame(ifstream &filebin, int &ff, int &np) { + char *data = new char[dataSize]; + char *d = readNextFrame(filebin, ff, np, data); + if (d == NULL) { + delete[] data; + data = NULL; + } + return data; } - int ipacket; - int ibyte; - int ii=0; - for (ibyte=0; ibyte= 0) + fnum = ff; + + if (filebin.is_open()) { + if (filebin.read(data, dataSize)) { + ff = getFrameNumber(data); + np = getPacketNumber(data); + return data; + } + } + return NULL; + }; + + /** + + Loops over a memory slot until a complete frame is found (i.e. all + packets 0 to nPackets, same frame number). purely virtual func \param + data pointer to the memory to be analyzed \param ndata reference to the + amount of data found for the frame, in case the frame is incomplete at + the end of the memory slot \param dsize size of the memory slot to be + analyzed \returns pointer to the beginning of the last good frame (might + be incomplete if ndata smaller than dataSize), or NULL if no frame is + found + + */ + virtual char *findNextFrame(char *data, int &ndata, int dsize) { + if (dsize < dataSize) + ndata = dsize; + else + ndata = dataSize; + return data; } - /* int off=sizeof(sls_detector_header)/2; */ - - /* for (ibyte=0; ibyteframeNumber;};//*((int*)(buff+5))&0xffffff;}; - - /** - - Returns the packet number for the given dataset. purely virtual func - \param buff pointer to the dataset - \returns packet number number - - - - */ - int getPacketNumber(char *buff){return ((sls_detector_header*)buff)->packetNumber;}//((*(((int*)(buff+4))))&0xff)+1;}; - -/* /\** */ - -/* Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func */ -/* \param data pointer to the memory to be analyzed */ -/* \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot */ -/* \param dsize size of the memory slot to be analyzed */ -/* \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found */ - -/* *\/ */ -/* virtual char *findNextFrame(char *data, int &ndata, int dsize){ndata=dsize; setDataSize(dsize); return data;}; */ - - -/* /\** */ - -/* Loops over a file stream until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). Can be overloaded for different kind of detectors! */ -/* \param filebin input file stream (binary) */ -/* \returns pointer to the begin of the last good frame, NULL if no frame is found or last frame is incomplete */ - -/* *\/ */ -/* virtual char *readNextFrame(ifstream &filebin){ */ -/* // int afifo_length=0; */ -/* uint16_t *afifo_cont; */ -/* int ib=0; */ -/* if (filebin.is_open()) { */ -/* afifo_cont=new uint16_t[dataSize/2]; */ -/* while (filebin.read(((char*)afifo_cont)+ib,2)) { */ -/* ib+=2; */ -/* if (ib==dataSize) break; */ -/* } */ -/* if (ib>0) { */ -/* iframe++; */ -/* // cout << ib << "-" << endl; */ -/* return (char*)afifo_cont; */ -/* } else { */ -/* delete [] afifo_cont; */ -/* return NULL; */ -/* } */ -/* } */ -/* return NULL; */ -/* }; */ - - - virtual char *readNextFrame(ifstream &filebin) { - int ff=-1, np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int &ff) { - int np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np) { - char *data=new char[dataSize]; - char *d=readNextFrame(filebin, ff, np, data); - if (d==NULL) {delete [] data; data=NULL;} - return data; - } - - - - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np, char *data) { - char *retval=0; - int nd; - int fnum = -1; - np=0; - int pn; - - // cout << dataSize << endl; - if (ff>=0) - fnum=ff; - - if (filebin.is_open()) { - if (filebin.read(data, dataSize) ){ - ff=getFrameNumber(data); - np=getPacketNumber(data); - return data; - } - } - return NULL; - - - - }; - - - - /** - - Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func - \param data pointer to the memory to be analyzed - \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot - \param dsize size of the memory slot to be analyzed - \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found - - */ - virtual char *findNextFrame(char *data, int &ndata, int dsize){ - if (dsize { - - private: - - int iframe; - int nadc; - int sc_width; - int sc_height; - const int aSamples; - const int dSamples; - int off; - public: + private: + int iframe; + int nadc; + int sc_width; + int sc_height; + const int aSamples; + const int dSamples; + int off; + public: + /** + Implements the slsReceiverData structure for the moench02 prototype read + out by a module i.e. using the slsReceiver (160x160 pixels, 40 packets + 1286 large etc.) \param c crosstalk parameter for the output buffer - - - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer - - */ - //moench04CtbZmq10GbData(int nas=5000, int nds=0): slsDetectorData(400, 400, nas*2*32+nds*8), aSamples(nas), dSamples(nds), nadc(32), sc_width(25), sc_height(200) { + */ + // moench04CtbZmq10GbData(int nas=5000, int nds=0): + // slsDetectorData(400, 400, nas*2*32+nds*8), aSamples(nas), + // dSamples(nds), nadc(32), sc_width(25), sc_height(200) { #ifndef RAWDATA - moench04CtbZmq10GbData(int nas=5000, int nds=0): slsDetectorData(400, 400, (nas > 0) && (nds>0) ? max(nas,nds)*(32*2+8) : nas*32*2+nds*8), nadc(32), sc_width(25), sc_height(200), aSamples(nas), dSamples(nds) { - int off=0; + moench04CtbZmq10GbData(int nas = 5000, int nds = 0) + : slsDetectorData(400, 400, + (nas > 0) && (nds > 0) + ? max(nas, nds) * (32 * 2 + 8) + : nas * 32 * 2 + nds * 8), + nadc(32), sc_width(25), sc_height(200), aSamples(nas), dSamples(nds) { + int off = 0; #endif #ifdef RAWDATA - moench04CtbZmq10GbData(int nas=5000, int nds=0): slsDetectorData(400, 400, sizeof(sls_detector_header)+((nas > 0) && (nds>0) ? max(nas,nds)*(32*2+8) : nas*32*2+nds*8)), nadc(32), sc_width(25), sc_height(200), aSamples(nas), dSamples(nds) { - int off=sizeof(sls_detector_header); - cout << "hh" << dataSize << endl; - cout << sizeof(sls_detector_header)+ ((nas > 0) && (nds>0) ? max(nas,nds)*(32*2+8) : nas*32*2+nds*8) << endl; + moench04CtbZmq10GbData(int nas = 5000, int nds = 0) + : slsDetectorData(400, 400, + sizeof(sls_detector_header) + + ((nas > 0) && (nds > 0) + ? max(nas, nds) * (32 * 2 + 8) + : nas * 32 * 2 + nds * 8)), + nadc(32), sc_width(25), sc_height(200), aSamples(nas), + dSamples(nds) { + int off = sizeof(sls_detector_header); + cout << "hh" << dataSize << endl; + cout << sizeof(sls_detector_header) + + ((nas > 0) && (nds > 0) ? max(nas, nds) * (32 * 2 + 8) + : nas * 32 * 2 + nds * 8) + << endl; #endif - /* int ds; */ - /* if (nas && nds) */ - /* if (nds>nas) */ - /* ds=nds*(32*2+8); */ - /* else */ - /* ds=nas*(32*2+8); */ - /* else */ - /* ds=nas*32*2+nds*8; */ + /* int ds; */ + /* if (nas && nds) */ + /* if (nds>nas) */ + /* ds=nds*(32*2+8); */ + /* else */ + /* ds=nas*(32*2+8); */ + /* else */ + /* ds=nas*32*2+nds*8; */ - /* new slsDetectorData(400, 400, ds); */ + /* new slsDetectorData(400, 400, ds); */ - int adc_nr[32]={9, 8,11,10,13,12,15,14,1,0,3,2,5,4,7,6,23,22,21,20,19,18,17,16,31,30,29,28,27,26,25,24 }; + int adc_nr[32] = {9, 8, 11, 10, 13, 12, 15, 14, 1, 0, 3, + 2, 5, 4, 7, 6, 23, 22, 21, 20, 19, 18, + 17, 16, 31, 30, 29, 28, 27, 26, 25, 24}; - /* - iadc=ptr%32 - isample=ptr/32 + /* + iadc=ptr%32 + isample=ptr/32 - col=(adc_nr[iadc]%16)*25+isample%25 - if (adc_nr[iadc]<16) - row=199-isample/25; - else - row=200+isample/25 + col=(adc_nr[iadc]%16)*25+isample%25 + if (adc_nr[iadc]<16) + row=199-isample/25; + else + row=200+isample/25 - adc0 col(9*25..10*25-1) row(199..0) - adc1 col(8*25..9*25-1) row(199..0) - adc2 col(11*25..12*25-1) row(199..0) - adc3 col(10*25..11*25-1) row(199..0) - adc4 col(13*25..14*25-1) row(199..0) - adc5 col(12*25..13*25-1) row(199..0) - adc6 col(15*25..16*25-1) row(199..0) - adc7 col(14*25..15*25-1) row(199..0) - adc8 col(1*25..2*25-1) row(199..0) + adc0 col(9*25..10*25-1) row(199..0) + adc1 col(8*25..9*25-1) row(199..0) + adc2 col(11*25..12*25-1) row(199..0) + adc3 col(10*25..11*25-1) row(199..0) + adc4 col(13*25..14*25-1) row(199..0) + adc5 col(12*25..13*25-1) row(199..0) + adc6 col(15*25..16*25-1) row(199..0) + adc7 col(14*25..15*25-1) row(199..0) + adc8 col(1*25..2*25-1) row(199..0) + */ + + int row, col; + + // int isample; + int iadc; + // int ix, iy; + + // int npackets=40; + int i; + // int adc4(0); + + for (int is = 0; is < aSamples; is++) { + + for (iadc = 0; iadc < nadc; iadc++) { + i = is; + // adc4=(int)iadc/4; + if (i < sc_width * sc_height) { + // for (int i=0; i 0) + dataMap[row][col] = + ((nadc + 4) * i + iadc) * 2 + off; //+16*(ip+1); + else + dataMap[row][col] = + (nadc * i + iadc) * 2 + off; //+16*(ip+1); + if (dataMap[row][col] < 0 || + dataMap[row][col] >= aSamples * 2 * 32 + off) + cout << "Error: pointer " << dataMap[row][col] + << " out of range " << endl; + } + } + } + + /* for (ibyte=0; ibyte= 32) + return 0; + if (ibit[isc] < 0 || ibit[isc] >= 64) + return 0; + if (dSamples > isample) { + ptr = data + 32 * (isample + 1) + 8 * isample; + sample = *((uint64_t *)ptr); + // cout << isc << " " << ibit[isc] << " " << isample << hex << + // sample << dec << endl; + if (sample & (1 << ibit[isc])) + return 1; + else + return 0; + } else + return 0; + } + + /** + + Returns the frame number for the given dataset. Purely virtual func. + \param buff pointer to the dataset + \returns frame number + */ - int row, col; - - //int isample; - int iadc; - // int ix, iy; - - // int npackets=40; - int i; - //int adc4(0); - - for (int is=0; is0) - dataMap[row][col]=((nadc+4)*i+iadc)*2+off;//+16*(ip+1); - else - dataMap[row][col]=(nadc*i+iadc)*2+off;//+16*(ip+1); - if (dataMap[row][col]<0 || dataMap[row][col]>=aSamples*2*32+off) - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - } - } - } - - - /* for (ibyte=0; ibyte=32) return 0; - if (ibit[isc]<0 || ibit[isc]>=64) return 0; - if (dSamples>isample) { - ptr=data+32*(isample+1)+8*isample; - sample=*((uint64_t*)ptr); - // cout << isc << " " << ibit[isc] << " " << isample << hex << sample << dec << endl; - if (sample & (1<frameNumber;};//*((int*)(buff+5))&0xffffff;}; + int getFrameNumber(char *buff) { + return ((sls_detector_header *)buff)->frameNumber; + }; //*((int*)(buff+5))&0xffffff;}; - /** + /** - Returns the packet number for the given dataset. purely virtual func - \param buff pointer to the dataset - \returns packet number number + Returns the packet number for the given dataset. purely virtual func + \param buff pointer to the dataset + \returns packet number number - */ - int getPacketNumber(char *buff){return ((sls_detector_header*)buff)->packetNumber;}//((*(((int*)(buff+4))))&0xff)+1;}; + */ + int getPacketNumber(char *buff) { + return ((sls_detector_header *)buff)->packetNumber; + } //((*(((int*)(buff+4))))&0xff)+1;}; #endif #ifndef RAWDATA - int getFrameNumber(char *buff){return iframe;};//((sls_detector_header*)buff)->frameNumber;};//*((int*)(buff+5))&0xffffff;}; + int getFrameNumber(char *buff) { + return iframe; + }; //((sls_detector_header*)buff)->frameNumber;};//*((int*)(buff+5))&0xffffff;}; #endif - /** + /** - Returns the packet number for the given dataset. purely virtual func - \param buff pointer to the dataset - \returns packet number number + Returns the packet number for the given dataset. purely virtual func + \param buff pointer to the dataset + \returns packet number number - */ - //int getPacketNumber(char *buff){return ((sls_detector_header*)buff)->packetNumber;}//((*(((int*)(buff+4))))&0xff)+1;}; + */ + // int getPacketNumber(char *buff){return + // ((sls_detector_header*)buff)->packetNumber;}//((*(((int*)(buff+4))))&0xff)+1;}; -/* /\** */ + /* /\** */ -/* Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func */ -/* \param data pointer to the memory to be analyzed */ -/* \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot */ -/* \param dsize size of the memory slot to be analyzed */ -/* \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found */ + /* Loops over a memory slot until a complete frame is found (i.e. + * all packets 0 to nPackets, same frame number). purely virtual func */ + /* \param data pointer to the memory to be analyzed */ + /* \param ndata reference to the amount of data found for the + * frame, in case the frame is incomplete at the end of the memory slot + */ + /* \param dsize size of the memory slot to be analyzed */ + /* \returns pointer to the beginning of the last good frame (might + * be incomplete if ndata smaller than dataSize), or NULL if no frame is + * found */ -/* *\/ */ -/* virtual char *findNextFrame(char *data, int &ndata, int dsize){ndata=dsize; setDataSize(dsize); return data;}; */ + /* *\/ */ + /* virtual char *findNextFrame(char *data, int &ndata, int + * dsize){ndata=dsize; setDataSize(dsize); return data;}; */ + /* /\** */ -/* /\** */ + /* Loops over a file stream until a complete frame is found (i.e. + * all packets 0 to nPackets, same frame number). Can be overloaded for + * different kind of detectors! */ + /* \param filebin input file stream (binary) */ + /* \returns pointer to the begin of the last good frame, NULL if no + * frame is found or last frame is incomplete */ -/* Loops over a file stream until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). Can be overloaded for different kind of detectors! */ -/* \param filebin input file stream (binary) */ -/* \returns pointer to the begin of the last good frame, NULL if no frame is found or last frame is incomplete */ + /* *\/ */ + /* virtual char *readNextFrame(ifstream &filebin){ */ + /* // int afifo_length=0; */ + /* uint16_t *afifo_cont; */ + /* int ib=0; */ + /* if (filebin.is_open()) { */ + /* afifo_cont=new uint16_t[dataSize/2]; */ + /* while (filebin.read(((char*)afifo_cont)+ib,2)) { */ + /* ib+=2; */ + /* if (ib==dataSize) break; */ + /* } */ + /* if (ib>0) { */ + /* iframe++; */ + /* // cout << ib << "-" << endl; */ + /* return (char*)afifo_cont; */ + /* } else { */ + /* delete [] afifo_cont; */ + /* return NULL; */ + /* } */ + /* } */ + /* return NULL; */ + /* }; */ -/* *\/ */ -/* virtual char *readNextFrame(ifstream &filebin){ */ -/* // int afifo_length=0; */ -/* uint16_t *afifo_cont; */ -/* int ib=0; */ -/* if (filebin.is_open()) { */ -/* afifo_cont=new uint16_t[dataSize/2]; */ -/* while (filebin.read(((char*)afifo_cont)+ib,2)) { */ -/* ib+=2; */ -/* if (ib==dataSize) break; */ -/* } */ -/* if (ib>0) { */ -/* iframe++; */ -/* // cout << ib << "-" << endl; */ -/* return (char*)afifo_cont; */ -/* } else { */ -/* delete [] afifo_cont; */ -/* return NULL; */ -/* } */ -/* } */ -/* return NULL; */ -/* }; */ + virtual char *readNextFrame(ifstream & filebin) { + int ff = -1, np = -1; + return readNextFrame(filebin, ff, np); + }; - virtual char *readNextFrame(ifstream &filebin) { - int ff=-1, np=-1; - return readNextFrame(filebin, ff, np); - }; + virtual char *readNextFrame(ifstream & filebin, int &ff) { + int np = -1; + return readNextFrame(filebin, ff, np); + }; - virtual char *readNextFrame(ifstream &filebin, int &ff) { - int np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np) { - char *data=new char[dataSize]; - char *d=readNextFrame(filebin, ff, np, data); - if (d==NULL) {delete [] data; data=NULL;} - return data; - } + virtual char *readNextFrame(ifstream & filebin, int &ff, int &np) { + char *data = new char[dataSize]; + char *d = readNextFrame(filebin, ff, np, data); + if (d == NULL) { + delete[] data; + data = NULL; + } + return data; + } #ifndef RAWDATA + virtual char *readNextFrame(ifstream & filebin, int &ff, int &np, + char *data) { + // char *retval=0; + // int nd; + // int fnum = -1; + np = 0; + // int pn; + // cout << dataSize << endl; + if (ff >= 0) + // fnum=ff; - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np, char *data) { - // char *retval=0; - // int nd; - // int fnum = -1; - np=0; - //int pn; - - // cout << dataSize << endl; - if (ff>=0) - // fnum=ff; - - if (filebin.is_open()) { - if (filebin.read(data, dataSize) ){ - ff=getFrameNumber(data); - // np=getPacketNumber(data); - return data; - } - } - return NULL; - - - - }; - + if (filebin.is_open()) { + if (filebin.read(data, dataSize)) { + ff = getFrameNumber(data); + // np=getPacketNumber(data); + return data; + } + } + return NULL; + }; #endif - #ifdef RAWDATA + virtual char *readNextFrame(ifstream & filebin, int &ff, int &np, + char *data) { + char *retval = 0; + int nd; + int fnum = -1; + np = 0; + int pn; + // cout << dataSize << endl; + if (ff >= 0) + fnum = ff; - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np, char *data) { - char *retval=0; - int nd; - int fnum = -1; - np=0; - int pn; - - // cout << dataSize << endl; - if (ff>=0) - fnum=ff; - - if (filebin.is_open()) { - if (filebin.read(data, dataSize) ){ - ff=getFrameNumber(data); - np=getPacketNumber(data); - return data; - } - } - return NULL; - - - - }; - - + if (filebin.is_open()) { + if (filebin.read(data, dataSize)) { + ff = getFrameNumber(data); + np = getPacketNumber(data); + return data; + } + } + return NULL; + }; #endif + /** - /** - - Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func - \param data pointer to the memory to be analyzed - \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot - \param dsize size of the memory slot to be analyzed - \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found - - */ - virtual char *findNextFrame(char *data, int &ndata, int dsize){ - if (dsize { - - private: - - int iframe; - int nadc; - int sc_width; - int sc_height; - const int aSamples; - const int dSamples; + private: + int iframe; + int nadc; + int sc_width; + int sc_height; + const int aSamples; + const int dSamples; - public: + public: + /** + Implements the slsReceiverData structure for the moench02 prototype read + out by a module i.e. using the slsReceiver (160x160 pixels, 40 packets + 1286 large etc.) \param c crosstalk parameter for the output buffer + */ + moench04CtbZmqData(int nas = 5000, int nds = 0) + : slsDetectorData(400, 400, nas * 2 * 32 + nds * 8), nadc(32), + sc_width(25), sc_height(200), aSamples(nas), dSamples(nds) { + int adc_nr[32] = {9, 8, 11, 10, 13, 12, 15, 14, 1, 0, 3, + 2, 5, 4, 7, 6, 23, 22, 21, 20, 19, 18, + 17, 16, 31, 30, 29, 28, 27, 26, 25, 24}; + int row, col; - /** - Implements the slsReceiverData structure for the moench02 prototype read out by a module i.e. using the slsReceiver - (160x160 pixels, 40 packets 1286 large etc.) - \param c crosstalk parameter for the output buffer + // int isample; + int iadc; + // int ix, iy; - */ - moench04CtbZmqData(int nas=5000, int nds=0): slsDetectorData(400, 400, nas*2*32+nds*8), nadc(32), sc_width(25), sc_height(200), aSamples(nas), dSamples(nds) { - + // int npackets=40; + int i; + // int adc4(0); - int adc_nr[32]={9, 8,11,10,13,12,15,14,1,0,3,2,5,4,7,6,23,22,21,20,19,18,17,16,31,30,29,28,27,26,25,24 }; + for (int is = 0; is < aSamples; is++) { - int row, col; + for (iadc = 0; iadc < nadc; iadc++) { + i = is; + // adc4=(int)iadc/4; + if (i < sc_width * sc_height) { + // for (int i=0; i= aSamples * 2 * 32) + cout << "Error: pointer " << dataMap[row][col] + << " out of range " << endl; + } + } + } - //int isample; - int iadc; - //int ix, iy; - - // int npackets=40; - int i; - //int adc4(0); + /* for (ibyte=0; ibyte=aSamples*2*32) - cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl; - } - } - } - + /* for (ibyte=0; ibyte=32) return 0; - if (ibit[isc]<0 || ibit[isc]>=64) return 0; - if (dSamples>isample) { - ptr=data+aoff+8*isample; - sample=*((uint64_t*)ptr); - // cout << isc << " " << ibit[isc] << " " << isample << hex << sample << dec << endl; - if (sample & (1<= 32) + return 0; + if (ibit[isc] < 0 || ibit[isc] >= 64) + return 0; + if (dSamples > isample) { + ptr = data + aoff + 8 * isample; + sample = *((uint64_t *)ptr); + // cout << isc << " " << ibit[isc] << " " << isample << hex << + // sample << dec << endl; + if (sample & (1 << ibit[isc])) + return 1; + else + return 0; + } else + return 0; + } - */ + /** -/* class jfrau_packet_header_t { */ -/* public: */ -/* unsigned char reserved[4]; */ -/* unsigned char packetNumber[1]; */ -/* unsigned char frameNumber[3]; */ -/* unsigned char bunchid[8]; */ -/* }; */ + Returns the frame number for the given dataset. Purely virtual func. + \param buff pointer to the dataset + \returns frame number + + */ + + /* class jfrau_packet_header_t { */ + /* public: */ + /* unsigned char reserved[4]; */ + /* unsigned char packetNumber[1]; */ + /* unsigned char frameNumber[3]; */ + /* unsigned char bunchid[8]; */ + /* }; */ + + int getFrameNumber(char *buff) { + return iframe; + }; //((sls_detector_header*)buff)->frameNumber;};//*((int*)(buff+5))&0xffffff;}; + + /** + + Returns the packet number for the given dataset. purely virtual func + \param buff pointer to the dataset + \returns packet number number - int getFrameNumber(char *buff){return iframe;};//((sls_detector_header*)buff)->frameNumber;};//*((int*)(buff+5))&0xffffff;}; + */ + // int getPacketNumber(char *buff){return + // ((sls_detector_header*)buff)->packetNumber;}//((*(((int*)(buff+4))))&0xff)+1;}; - /** + /* /\** */ - Returns the packet number for the given dataset. purely virtual func - \param buff pointer to the dataset - \returns packet number number + /* Loops over a memory slot until a complete frame is found (i.e. all + * packets 0 to nPackets, same frame number). purely virtual func */ + /* \param data pointer to the memory to be analyzed */ + /* \param ndata reference to the amount of data found for the frame, in + * case the frame is incomplete at the end of the memory slot */ + /* \param dsize size of the memory slot to be analyzed */ + /* \returns pointer to the beginning of the last good frame (might be + * incomplete if ndata smaller than dataSize), or NULL if no frame is found + */ + /* *\/ */ + /* virtual char *findNextFrame(char *data, int &ndata, int + * dsize){ndata=dsize; setDataSize(dsize); return data;}; */ + /* /\** */ - */ - //int getPacketNumber(char *buff){return ((sls_detector_header*)buff)->packetNumber;}//((*(((int*)(buff+4))))&0xff)+1;}; + /* Loops over a file stream until a complete frame is found (i.e. all + * packets 0 to nPackets, same frame number). Can be overloaded for + * different kind of detectors! */ + /* \param filebin input file stream (binary) */ + /* \returns pointer to the begin of the last good frame, NULL if no + * frame is found or last frame is incomplete */ -/* /\** */ + /* *\/ */ + /* virtual char *readNextFrame(ifstream &filebin){ */ + /* // int afifo_length=0; */ + /* uint16_t *afifo_cont; */ + /* int ib=0; */ + /* if (filebin.is_open()) { */ + /* afifo_cont=new uint16_t[dataSize/2]; */ + /* while (filebin.read(((char*)afifo_cont)+ib,2)) { */ + /* ib+=2; */ + /* if (ib==dataSize) break; */ + /* } */ + /* if (ib>0) { */ + /* iframe++; */ + /* // cout << ib << "-" << endl; */ + /* return (char*)afifo_cont; */ + /* } else { */ + /* delete [] afifo_cont; */ + /* return NULL; */ + /* } */ + /* } */ + /* return NULL; */ + /* }; */ -/* Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func */ -/* \param data pointer to the memory to be analyzed */ -/* \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot */ -/* \param dsize size of the memory slot to be analyzed */ -/* \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found */ + virtual char *readNextFrame(ifstream &filebin) { + int ff = -1, np = -1; + return readNextFrame(filebin, ff, np); + }; -/* *\/ */ -/* virtual char *findNextFrame(char *data, int &ndata, int dsize){ndata=dsize; setDataSize(dsize); return data;}; */ + virtual char *readNextFrame(ifstream &filebin, int &ff) { + int np = -1; + return readNextFrame(filebin, ff, np); + }; + virtual char *readNextFrame(ifstream &filebin, int &ff, int &np) { + char *data = new char[dataSize]; + char *d = readNextFrame(filebin, ff, np, data); + if (d == NULL) { + delete[] data; + data = NULL; + } + return data; + } -/* /\** */ + virtual char *readNextFrame(ifstream &filebin, int &ff, int &np, + char *data) { + // char *retval=0; + // int nd; + // int fnum = -1; + np = 0; + // int pn; -/* Loops over a file stream until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). Can be overloaded for different kind of detectors! */ -/* \param filebin input file stream (binary) */ -/* \returns pointer to the begin of the last good frame, NULL if no frame is found or last frame is incomplete */ + // cout << dataSize << endl; + if (ff >= 0) + // fnum=ff; -/* *\/ */ -/* virtual char *readNextFrame(ifstream &filebin){ */ -/* // int afifo_length=0; */ -/* uint16_t *afifo_cont; */ -/* int ib=0; */ -/* if (filebin.is_open()) { */ -/* afifo_cont=new uint16_t[dataSize/2]; */ -/* while (filebin.read(((char*)afifo_cont)+ib,2)) { */ -/* ib+=2; */ -/* if (ib==dataSize) break; */ -/* } */ -/* if (ib>0) { */ -/* iframe++; */ -/* // cout << ib << "-" << endl; */ -/* return (char*)afifo_cont; */ -/* } else { */ -/* delete [] afifo_cont; */ -/* return NULL; */ -/* } */ -/* } */ -/* return NULL; */ -/* }; */ + if (filebin.is_open()) { + if (filebin.read(data, dataSize)) { + ff = getFrameNumber(data); + // np=getPacketNumber(data); + return data; + } + } + return NULL; + }; + /** - virtual char *readNextFrame(ifstream &filebin) { - int ff=-1, np=-1; - return readNextFrame(filebin, ff, np); - }; + Loops over a memory slot until a complete frame is found (i.e. all + packets 0 to nPackets, same frame number). purely virtual func \param + data pointer to the memory to be analyzed \param ndata reference to the + amount of data found for the frame, in case the frame is incomplete at + the end of the memory slot \param dsize size of the memory slot to be + analyzed \returns pointer to the beginning of the last good frame (might + be incomplete if ndata smaller than dataSize), or NULL if no frame is + found - virtual char *readNextFrame(ifstream &filebin, int &ff) { - int np=-1; - return readNextFrame(filebin, ff, np); - }; - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np) { - char *data=new char[dataSize]; - char *d=readNextFrame(filebin, ff, np, data); - if (d==NULL) {delete [] data; data=NULL;} - return data; - } - - - - - virtual char *readNextFrame(ifstream &filebin, int& ff, int &np, char *data) { - // char *retval=0; - //int nd; - //int fnum = -1; - np=0; - //int pn; - - // cout << dataSize << endl; - if (ff>=0) - // fnum=ff; - - if (filebin.is_open()) { - if (filebin.read(data, dataSize) ){ - ff=getFrameNumber(data); - // np=getPacketNumber(data); - return data; - } - } - return NULL; - - - - }; - - - - /** - - Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). purely virtual func - \param data pointer to the memory to be analyzed - \param ndata reference to the amount of data found for the frame, in case the frame is incomplete at the end of the memory slot - \param dsize size of the memory slot to be analyzed - \returns pointer to the beginning of the last good frame (might be incomplete if ndata smaller than dataSize), or NULL if no frame is found - - */ - virtual char *findNextFrame(char *data, int &ndata, int dsize){ - if (dsize #include #include -#include using namespace std; +template class slsDetectorData { -template -class slsDetectorData { + protected: + const int nx; /**< Number of pixels in the x direction */ + const int ny; /**< Number of pixels in the y direction */ + int dataSize; /**= 0 && ix < nx && iy >= 0 && iy < ny) + dataROIMask[iy][ix] = i; + return isGood(ix, iy); + }; + /** + Define bad channel or roi mask for a single channel + \param ix channel x coordinate + \param iy channel y coordinate (1 for strips) + \returns 1 if pixel is good, 0 if it's bad, -1 if pixel is out of range + */ + int isGood(int ix, int iy) { + if (ix >= 0 && ix < nx && iy >= 0 && iy < ny) + return dataROIMask[iy][ix]; + else + return -1; + }; + + /** + Returns detector size in x,y + \param npx reference to number of channels in x + \param npy reference to number of channels in y (will be 1 for strips) + \returns total number of channels + */ + int getDetectorSize(int &npx, int &npy) { + npx = nx; + npy = ny; + return nx * ny; + }; + + /** Returns the size of the data frame */ + int getDataSize() { return dataSize; }; + + /** changes the size of the data frame */ + int setDataSize(int d) { + dataSize = d; + return dataSize; + }; + + virtual void getPixel(int ip, int &x, int &y) { + x = xmap[ip]; + y = ymap[ip]; + }; + + virtual dataType **getData(char *ptr, int dsize = -1) { + int el = dsize / sizeof(dataType); + // dataType **data; + int ix, iy; + // data=new dataType*[ny]; + // for(int i = 0; i < ny; i++) { + // data[i]=new dataType[nx]; + // } + isOrdered = 0; + if (dsize <= 0 || dsize > dataSize) + dsize = dataSize; + + for (int ip = 0; ip < (el); ip++) { + getPixel(ip, ix, iy); + if (ix >= 0 && ix < nx && iy >= 0 && iy < ny) { + // data[iy][ix]=getChannel(ptr,ix,iy); + orderedData[iy][ix] = *(ptr + ip); // getChannel(ptr,ix,iy); + } + } + isOrdered = 1; + return orderedData; } - for (iy=0; iy=0 && ix=0 && iy=0 && ix=0 && iydataSize) dsize=dataSize; + double **data; + int ix, iy; + data = new double *[ny]; + for (int i = 0; i < ny; i++) { + data[i] = new double[nx]; + } + int el = dsize / sizeof(dataType); + if (dsize <= 0 || dsize > dataSize) + dsize = dataSize; + for (int ip = 0; ip < el; ip++) { + getPixel(ip, ix, iy); + if (ix >= 0 && ix < nx && iy >= 0 && iy < ny) { + data[iy][ix] = getValue(ptr, ix, iy); + } + } + return data; + }; - for (int ip=0; ip<(el); ip++) { - getPixel(ip,ix,iy); - if (ix>=0 && ix=0 && iy= 0 && ix < nx && iy >= 0 && iy < ny && dataMap[iy][ix] >= 0 && + dataMap[iy][ix] < dataSize) { + // cout << ix << " " << iy << " " ; + // cout << dataMap[ix][iy] << " " << (void*)data << " " << + // dataSize<< endl; + m = dataMask[iy][ix]; + if (isOrdered == 0) + d = *((dataType *)(data + getPointer(ix, iy))); + else + d = orderedData[iy][ix]; + } + return d ^ m; + }; - virtual double **getImage(char *ptr, int dsize=-1) { - - double **data; - int ix,iy; - data=new double*[ny]; - for(int i = 0; i < ny; i++) { - data[i]=new double[nx]; - } - int el=dsize/sizeof(dataType); - if (dsize<=0 || dsize>dataSize) dsize=dataSize; - for (int ip=0; ip=0 && ix=0 && iy=0 && ix=0 && iy=0 && dataMap[iy][ix] -#include // exit() +#include // exit() template class slsReceiverData : public slsDetectorData { + public: + /** +slsReceiver data structure. Works for data acquired using the +slsDetectorReceiver subdivided in different packets with headers and footers. +Inherits and implements slsDetectorData. -public: +Constructor (no error checking if datasize and offsets are compatible!) +\param npx number of pixels in the x direction +\param npy number of pixels in the y direction (1 for strips) +\param np number of packets +\param psize packets size +\param dMap array of size nx*ny storing the pointers to the data in the dataset +(as offset) \param dMask Array of size nx*ny storing the polarity of the data in +the dataset (should be 0 if no inversion is required, 0xffffffff is inversion is +required) \param dROI Array of size nx*ny. The elements are 1s if the channel is +good or in the ROI, 0 is bad or out of the ROI. NULL (default) means all 1s. - /** - slsReceiver data structure. Works for data acquired using the slsDetectorReceiver subdivided in different packets with headers and footers. - Inherits and implements slsDetectorData. + */ + slsReceiverData(int npx, int npy, int np, int psize, int **dMap = NULL, + dataType **dMask = NULL, int **dROI = NULL) + : slsDetectorData(npx, npy, np * psize, dMap, dMask, dROI), + nPackets(np), packetSize(psize){}; - Constructor (no error checking if datasize and offsets are compatible!) - \param npx number of pixels in the x direction - \param npy number of pixels in the y direction (1 for strips) - \param np number of packets - \param psize packets size - \param dMap array of size nx*ny storing the pointers to the data in the dataset (as offset) - \param dMask Array of size nx*ny storing the polarity of the data in the dataset (should be 0 if no inversion is required, 0xffffffff is inversion is required) - \param dROI Array of size nx*ny. The elements are 1s if the channel is good or in the ROI, 0 is bad or out of the ROI. NULL (default) means all 1s. + /** - */ - slsReceiverData(int npx, int npy, int np, int psize, int **dMap=NULL, dataType **dMask=NULL, int **dROI=NULL): slsDetectorData(npx, npy, np*psize, dMap, dMask, dROI), nPackets(np), packetSize(psize) {}; + Returns the frame number for the given dataset. Virtual func: works for + slsDetectorReceiver data (also for each packet), but can be overloaded. \param + buff pointer to the dataset \returns frame number + */ - /** + virtual int getFrameNumber(char *buff) { + return ((*(int *)buff) & (0xffffff00)) >> 8; + }; - Returns the frame number for the given dataset. Virtual func: works for slsDetectorReceiver data (also for each packet), but can be overloaded. - \param buff pointer to the dataset - \returns frame number + /** - */ + Returns the packet number for the given dataset. Virtual func: works for + slsDetectorReceiver packets, but can be overloaded. \param buff pointer to the + dataset \returns packet number number - virtual int getFrameNumber(char *buff){return ((*(int*)buff)&(0xffffff00))>>8;}; + */ - /** + virtual int getPacketNumber(char *buff) { return (*(int *)buff) & 0xff; }; - Returns the packet number for the given dataset. Virtual func: works for slsDetectorReceiver packets, but can be overloaded. - \param buff pointer to the dataset - \returns packet number number + /** - */ + Loops over a memory slot until a complete frame is found (i.e. all packets 0 to + nPackets, same frame number). Can be overloaded for different kind of + detectors! \param data pointer to the memory to be analyzed \param ndata size + of frame returned \param dsize size of the memory slot to be analyzed \returns + pointer to the first packet of the last good frame (might be incomplete if + npackets lower than the number of packets), or NULL if no frame is found - virtual int getPacketNumber(char *buff){return (*(int*)buff)&0xff;}; + */ + virtual char *findNextFrame(char *data, int &ndata, int dsize) { + char *retval = NULL, *p = data; + int dd = 0; + int fn, fnum = -1, np = 0, pnum = -1; + while (dd <= (dsize - packetSize)) { + pnum = getPacketNumber(p); + fn = getFrameNumber(p); + // cout <<"fnum:"< nPackets) { + // cout << "Bad packet number " << pnum << " frame "<< fn << + // endl; + retval = NULL; + np = 0; + } else if (pnum == 1) { + retval = p; + if (np > 0) + /*cout << "*Incomplete frame number " << fnum << endl;*/ + np = 0; + fnum = fn; + } else if (fn != fnum) { + if (fnum != -1) { + /* cout << " **Incomplete frame number " << fnum << " pnum " + * << pnum << " " << getFrameNumber(p) << endl;*/ + retval = NULL; + } + np = 0; + } + p += packetSize; + dd += packetSize; + np++; + // cout <<"fnum:"< 0) { + // cprintf(BG_RED, "Too few packets for this frame! fnum:%d, + // pnum:%d np:%d\n",fnum,pnum,np); + cout << "Too few packets for this frame! " << fnum << " " + << pnum << " " << np + << endl; // cprintf(BG_RED,"Exiting\n");exit(-1); + } + } - /** + ndata = np * packetSize; + // cout << "return " << ndata << endl; + return retval; + }; - Loops over a memory slot until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). Can be overloaded for different kind of detectors! - \param data pointer to the memory to be analyzed - \param ndata size of frame returned - \param dsize size of the memory slot to be analyzed - \returns pointer to the first packet of the last good frame (might be incomplete if npackets lower than the number of packets), or NULL if no frame is found + /** - */ + Loops over a file stream until a complete frame is found (i.e. all packets 0 to + nPackets, same frame number). Can be overloaded for different kind of + detectors! \param filebin input file stream (binary) \returns pointer to the + first packet of the last good frame, NULL if no frame is found or last frame is + incomplete - virtual char *findNextFrame(char *data, int &ndata, int dsize) { - char *retval=NULL, *p=data; - int dd=0; - int fn, fnum=-1, np=0, pnum=-1; - while (dd<=(dsize-packetSize)) { - pnum=getPacketNumber(p); - fn=getFrameNumber(p); - //cout <<"fnum:"<nPackets) { - //cout << "Bad packet number " << pnum << " frame "<< fn << endl; - retval=NULL; - np=0; - } else if (pnum==1) { - retval=p; - if (np>0) - /*cout << "*Incomplete frame number " << fnum << endl;*/ - np=0; - fnum=fn; - } else if (fn!=fnum) { - if (fnum!=-1) { - /* cout << " **Incomplete frame number " << fnum << " pnum " << pnum << " " << getFrameNumber(p) << endl;*/ - retval=NULL; - } - np=0; - } - p+=packetSize; - dd+=packetSize; - np++; - //cout <<"fnum:"<0){ - //cprintf(BG_RED, "Too few packets for this frame! fnum:%d, pnum:%d np:%d\n",fnum,pnum,np); - cout << "Too few packets for this frame! "<< fnum << " " << pnum << " " << np < nPackets) { + cout << "too many packets!!!!!!!!!!" << endl; + delete[] data; + return NULL; + } else if (retval != NULL) { + // cout << "+" << endl;; + for (int ip = 0; ip < np; ip++) + memcpy(data + ip * packetSize, + retval + ip * packetSize, packetSize); + } - virtual char *readNextFrame(ifstream &filebin) { - char *data=new char[packetSize*nPackets]; - char *retval=0; - int np=0, nd; + } else if (np > nPackets) { + cout << "*******too many packets!!!!!!!!!!" << endl; + delete[] data; + return NULL; + } else { + // cout << "." << endl;; + np++; + } + } + } + delete[] data; + return NULL; + }; - if (filebin.is_open()) { - while (filebin.read(data+np*packetSize,packetSize)) { + /** - if (np==(nPackets-1)) { + Loops over a file stream until a complete frame is found (i.e. all + packets 0 to nPackets, same frame number). Can be overloaded for + different kind of detectors! \param filebin input file stream (binary) + \param fnum frame number of frame returned + \returns pointer to the first packet of the last good frame, NULL if no + frame is found or last frame is incomplete - retval=findNextFrame(data,nd,packetSize*nPackets); - np=nd/packetSize; - // cout << np << endl; + */ + virtual char *readNextFrame(ifstream &filebin, int &fnum) { + char *data = new char[packetSize * nPackets]; + char *retval = 0; + int np = 0, nd; + fnum = -1; - if (retval==data && np==nPackets) { - // cout << "-" << endl; - return data; + if (filebin.is_open()) { + while (filebin.read(data + np * packetSize, packetSize)) { - } else if (np>nPackets) { - cout << "too many packets!!!!!!!!!!" << endl; - delete [] data; - return NULL; - } else if (retval!=NULL) { - // cout << "+" << endl;; - for (int ip=0; ipnPackets) { - cout << "*******too many packets!!!!!!!!!!" << endl; - delete [] data; - return NULL; - } else { - // cout << "." << endl;; - np++; - } - } - } - delete [] data; - return NULL; - }; + fnum = getFrameNumber(data); // cout << "fnum:"< nPackets) { + cout << "too many packets!!!!!!!!!!" << endl; + delete[] data; + return NULL; + } else if (retval != NULL) { + // cout << "+" << endl;; + for (int ip = 0; ip < np; ip++) + memcpy(data + ip * packetSize, + retval + ip * packetSize, packetSize); + } - Loops over a file stream until a complete frame is found (i.e. all packets 0 to nPackets, same frame number). Can be overloaded for different kind of detectors! - \param filebin input file stream (binary) - \param fnum frame number of frame returned - \returns pointer to the first packet of the last good frame, NULL if no frame is found or last frame is incomplete + } else if (np > nPackets) { + cout << "*******too many packets!!!!!!!!!!" << endl; + delete[] data; + return NULL; + } else { + // cout << "." << endl;; + np++; + // cout<<"np:"<nPackets) { - cout << "too many packets!!!!!!!!!!" << endl; - delete [] data; - return NULL; - } else if (retval!=NULL) { - // cout << "+" << endl;; - for (int ip=0; ipnPackets) { - cout << "*******too many packets!!!!!!!!!!" << endl; - delete [] data; - return NULL; - } else { - // cout << "." << endl;; - np++; - //cout<<"np:"< +#include #include #include -#include +#include #endif #include -#define max(a,b) ((a) > (b) ? (a) : (b)) -#define min(a,b) ((a) < (b) ? (a) : (b)) -#define ELEM_SWAP(a,b) { register int t=(a);(a)=(b);(b)=t; } - +#define max(a, b) ((a) > (b) ? (a) : (b)) +#define min(a, b) ((a) < (b) ? (a) : (b)) +#define ELEM_SWAP(a, b) \ + { \ + register int t = (a); \ + (a) = (b); \ + (b) = t; \ + } using namespace std; #ifdef MYROOT -Double_t energyCalibrationFunctions::pedestal(Double_t *x, Double_t *par) { - return par[0]-par[1]*sign*x[0]; +Double_t energyCalibrationFunctions::pedestal(Double_t *x, Double_t *par) { + return par[0] - par[1] * sign * x[0]; } - -Double_t energyCalibrationFunctions::gaussChargeSharing(Double_t *x, Double_t *par) { - Double_t f, arg=0; - // Gaussian exponent - if (par[3]!=0) { - arg=sign*(x[0]-par[2])/par[3]; - } - // the Gaussian - f=TMath::Exp(-1*arg*arg/2.); - // Gaussian + error function - f=f+par[5]/2.*(TMath::Erfc(arg/(TMath::Sqrt(2.)))); - // Gaussian + error function + pedestal - return par[4]*f+pedestal(x,par); +Double_t energyCalibrationFunctions::gaussChargeSharing(Double_t *x, + Double_t *par) { + Double_t f, arg = 0; + // Gaussian exponent + if (par[3] != 0) { + arg = sign * (x[0] - par[2]) / par[3]; + } + // the Gaussian + f = TMath::Exp(-1 * arg * arg / 2.); + // Gaussian + error function + f = f + par[5] / 2. * (TMath::Erfc(arg / (TMath::Sqrt(2.)))); + // Gaussian + error function + pedestal + return par[4] * f + pedestal(x, par); } -Double_t energyCalibrationFunctions::gaussChargeSharingKb(Double_t *x, Double_t *par) { - Double_t f, arg=0,argb=0; - // Gaussian exponent - if (par[3]!=0) { - arg=sign*(x[0]-par[2])/par[3]; - argb=sign*(x[0]-(par[6]*par[2]))/par[3]; // using absolute kb mean might seem better but like this the ratio can be fixed - } - // the Gaussian - f=TMath::Exp(-1*arg*arg/2.); - f=f+par[7]*(TMath::Exp(-1*argb*argb/2.)); - // Gaussian + error function - f=f+par[5]/2.*(TMath::Erfc(arg/(TMath::Sqrt(2.)))); - f=f+par[7]*par[5]/2.*(TMath::Erfc(argb/(TMath::Sqrt(2.)))); - // Gaussian + error function + pedestal - return par[4]*f+pedestal(x,par); +Double_t energyCalibrationFunctions::gaussChargeSharingKb(Double_t *x, + Double_t *par) { + Double_t f, arg = 0, argb = 0; + // Gaussian exponent + if (par[3] != 0) { + arg = sign * (x[0] - par[2]) / par[3]; + argb = sign * (x[0] - (par[6] * par[2])) / + par[3]; // using absolute kb mean might seem better but like this + // the ratio can be fixed + } + // the Gaussian + f = TMath::Exp(-1 * arg * arg / 2.); + f = f + par[7] * (TMath::Exp(-1 * argb * argb / 2.)); + // Gaussian + error function + f = f + par[5] / 2. * (TMath::Erfc(arg / (TMath::Sqrt(2.)))); + f = f + par[7] * par[5] / 2. * (TMath::Erfc(argb / (TMath::Sqrt(2.)))); + // Gaussian + error function + pedestal + return par[4] * f + pedestal(x, par); } -Double_t energyCalibrationFunctions::gaussChargeSharingKaDoublet(Double_t *x, Double_t *par) { - Double_t f, f2, arg=0, arg2=0; - // Gaussian exponent - if (par[3]!=0) { - arg=sign*(x[0]-par[2])/par[3]; - arg2=sign*(x[0]-par[6])/par[3]; - } - // the Gaussian - f=TMath::Exp(-1*arg*arg/2.); - f2=TMath::Exp(-1*arg2*arg2/2.); - // Gaussian + error function - f=f+par[5]/2.*(TMath::Erfc(arg/(TMath::Sqrt(2.)))); - f2=f2+par[5]/2.*(TMath::Erfc(arg/(TMath::Sqrt(2.)))); // shouldn't this be arg2? - // Gaussian + error function + pedestal - return par[4]*f+par[7]*f2+pedestal(x,par); +Double_t +energyCalibrationFunctions::gaussChargeSharingKaDoublet(Double_t *x, + Double_t *par) { + Double_t f, f2, arg = 0, arg2 = 0; + // Gaussian exponent + if (par[3] != 0) { + arg = sign * (x[0] - par[2]) / par[3]; + arg2 = sign * (x[0] - par[6]) / par[3]; + } + // the Gaussian + f = TMath::Exp(-1 * arg * arg / 2.); + f2 = TMath::Exp(-1 * arg2 * arg2 / 2.); + // Gaussian + error function + f = f + par[5] / 2. * (TMath::Erfc(arg / (TMath::Sqrt(2.)))); + f2 = f2 + + par[5] / 2. * + (TMath::Erfc(arg / (TMath::Sqrt(2.)))); // shouldn't this be arg2? + // Gaussian + error function + pedestal + return par[4] * f + par[7] * f2 + pedestal(x, par); } -Double_t energyCalibrationFunctions::gaussChargeSharingPixel(Double_t *x, Double_t *par) { - Double_t f; - if (par[3]<=0 || par[2]*(*x)<=0 || par[5]<0 || par[4]<=0) return 0; +Double_t energyCalibrationFunctions::gaussChargeSharingPixel(Double_t *x, + Double_t *par) { + Double_t f; + if (par[3] <= 0 || par[2] * (*x) <= 0 || par[5] < 0 || par[4] <= 0) + return 0; - Double_t pp[3]; + Double_t pp[3]; - pp[0]=0; - pp[1]=par[2]; - pp[2]=par[3]; - + pp[0] = 0; + pp[1] = par[2]; + pp[2] = par[3]; - f=(par[5]-par[6]*(TMath::Log(*x/par[2])))*erfBox(x,pp); - f+=par[4]*TMath::Gaus(*x, par[2], par[3], kTRUE); - return f+pedestal(x,par); + f = (par[5] - par[6] * (TMath::Log(*x / par[2]))) * erfBox(x, pp); + f += par[4] * TMath::Gaus(*x, par[2], par[3], kTRUE); + return f + pedestal(x, par); } Double_t energyCalibrationFunctions::erfBox(Double_t *z, Double_t *par) { - - - Double_t m=par[0]; - Double_t M=par[1]; - - if (par[0]>par[1]) { - m=par[1]; - M=par[0]; - } - - if (m==M) - return 0; + Double_t m = par[0]; + Double_t M = par[1]; + if (par[0] > par[1]) { + m = par[1]; + M = par[0]; + } - if (par[2]<=0) { - if (*z>=m && *z<=M) - return 1./(M-m); - else - return 0; + if (m == M) + return 0; - } - - return (TMath::Erfc((z[0]-M)/par[2])-TMath::Erfc((z[0]-m)/par[2]))*0.5/(M-m); + if (par[2] <= 0) { + if (*z >= m && *z <= M) + return 1. / (M - m); + else + return 0; + } + return (TMath::Erfc((z[0] - M) / par[2]) - + TMath::Erfc((z[0] - m) / par[2])) * + 0.5 / (M - m); } - // basic erf function -Double_t energyCalibrationFunctions::erfFunction(Double_t *x, Double_t *par) { - double arg=0; - if (par[1]!=0) arg=(par[0]-x[0])/par[1]; - return ((par[2]/2.*(1+TMath::Erf(sign*arg/(TMath::Sqrt(2)))))); +Double_t energyCalibrationFunctions::erfFunction(Double_t *x, Double_t *par) { + double arg = 0; + if (par[1] != 0) + arg = (par[0] - x[0]) / par[1]; + return ((par[2] / 2. * (1 + TMath::Erf(sign * arg / (TMath::Sqrt(2)))))); }; - -Double_t energyCalibrationFunctions::erfFunctionChargeSharing(Double_t *x, Double_t *par) { - Double_t f; - - f=erfFunction(x, par+2)*(1+par[5]*(par[2]-x[0]))+par[0]-par[1]*x[0]*sign; - return f; +Double_t energyCalibrationFunctions::erfFunctionChargeSharing(Double_t *x, + Double_t *par) { + Double_t f; + + f = erfFunction(x, par + 2) * (1 + par[5] * (par[2] - x[0])) + par[0] - + par[1] * x[0] * sign; + return f; }; - - + Double_t energyCalibrationFunctions::erfFuncFluo(Double_t *x, Double_t *par) { - Double_t f; - f=erfFunctionChargeSharing(x, par)+erfFunction(x, par+6)*(1+par[9]*(par[6]-x[0])); - return f; + Double_t f; + f = erfFunctionChargeSharing(x, par) + + erfFunction(x, par + 6) * (1 + par[9] * (par[6] - x[0])); + return f; }; #endif -double energyCalibrationFunctions::median(double *x, int n){ - // sorts x into xmed array and returns median - // n is number of values already in the xmed array - double xmed[n]; - int k,i,j; +double energyCalibrationFunctions::median(double *x, int n) { + // sorts x into xmed array and returns median + // n is number of values already in the xmed array + double xmed[n]; + int k, i, j; - for (i=0; i*(x+j)) - k++; - if (*(x+i)==*(x+j)) { - if (i>j) - k++; - } + for (i = 0; i < n; i++) { + k = 0; + for (j = 0; j < n; j++) { + if (*(x + i) > *(x + j)) + k++; + if (*(x + i) == *(x + j)) { + if (i > j) + k++; + } + } + xmed[k] = *(x + i); } - xmed[k]=*(x+i); - } - k=n/2; - return xmed[k]; + k = n / 2; + return xmed[k]; } - -int energyCalibrationFunctions::quick_select(int arr[], int n){ - int low, high ; +int energyCalibrationFunctions::quick_select(int arr[], int n) { + int low, high; int median; int middle, ll, hh; - low = 0 ; high = n-1 ; median = (low + high) / 2; + low = 0; + high = n - 1; + median = (low + high) / 2; for (;;) { if (high <= low) /* One element only */ - return arr[median] ; + return arr[median]; - if (high == low + 1) { /* Two elements only */ + if (high == low + 1) { /* Two elements only */ if (arr[low] > arr[high]) - ELEM_SWAP(arr[low], arr[high]) ; - return arr[median] ; + ELEM_SWAP(arr[low], arr[high]); + return arr[median]; } - /* Find median of low, middle and high items; swap into position low */ - middle = (low + high) / 2; - if (arr[middle] > arr[high]) ELEM_SWAP(arr[middle], arr[high]) ; - if (arr[low] > arr[high]) ELEM_SWAP(arr[low], arr[high]) ; - if (arr[middle] > arr[low]) ELEM_SWAP(arr[middle], arr[low]) ; + /* Find median of low, middle and high items; swap into position low */ + middle = (low + high) / 2; + if (arr[middle] > arr[high]) + ELEM_SWAP(arr[middle], arr[high]); + if (arr[low] > arr[high]) + ELEM_SWAP(arr[low], arr[high]); + if (arr[middle] > arr[low]) + ELEM_SWAP(arr[middle], arr[low]); - /* Swap low item (now in position middle) into position (low+1) */ - ELEM_SWAP(arr[middle], arr[low+1]) ; + /* Swap low item (now in position middle) into position (low+1) */ + ELEM_SWAP(arr[middle], arr[low + 1]); - /* Nibble from each end towards middle, swapping items when stuck */ - ll = low + 1; - hh = high; - for (;;) { - do ll++; while (arr[low] > arr[ll]) ; - do hh--; while (arr[hh] > arr[low]) ; + /* Nibble from each end towards middle, swapping items when stuck */ + ll = low + 1; + hh = high; + for (;;) { + do + ll++; + while (arr[low] > arr[ll]); + do + hh--; + while (arr[hh] > arr[low]); - if (hh < ll) - break; + if (hh < ll) + break; - ELEM_SWAP(arr[ll], arr[hh]) ; - } + ELEM_SWAP(arr[ll], arr[hh]); + } - /* Swap middle item (in position low) back into correct position */ - ELEM_SWAP(arr[low], arr[hh]) ; + /* Swap middle item (in position low) back into correct position */ + ELEM_SWAP(arr[low], arr[hh]); - /* Re-set active partition */ - if (hh <= median) - low = ll; + /* Re-set active partition */ + if (hh <= median) + low = ll; if (hh >= median) - high = hh - 1; + high = hh - 1; } } -int energyCalibrationFunctions::kth_smallest(int *a, int n, int k){ - register int i,j,l,m ; - register double x ; +int energyCalibrationFunctions::kth_smallest(int *a, int n, int k) { + register int i, j, l, m; + register double x; - l=0 ; m=n-1 ; - while (lSetParNames("Background Offset","Background Slope","Inflection Point","Noise RMS", "Number of Photons","Charge Sharing Slope"); - - fspectrum=new TF1("fspectrum",funcs,&energyCalibrationFunctions::spectrum,0,1000,6,"energyCalibrationFunctions","spectrum"); - fspectrum->SetParNames("Background Pedestal","Background slope", "Peak position","Noise RMS", "Number of Photons","Charge Sharing Pedestal"); - fspectrumkb=new TF1("fspectrumkb",funcs,&energyCalibrationFunctions::spectrumkb,0,1000,8,"energyCalibrationFunctions","spectrumkb"); - fspectrumkb->SetParNames("Background Pedestal","Background slope", "Peak position","Noise RMS", "Number of Photons","Charge Sharing Pedestal","kb mean","kb frac"); - - fspectrumkadoublet=new TF1("fspectrumkadoublet",funcs,&energyCalibrationFunctions::spectrumkadoublet,0,1000,8,"energyCalibrationFunctions","spectrumkadoublet"); - fspectrumkadoublet->SetParNames("Background Pedestal","Background slope", "Peak position","Noise RMS", "Number of Photons","Charge Sharing Pedestal","ka2 mean","n2"); - - fspixel=new TF1("fspixel",funcs,&energyCalibrationFunctions::spectrumPixel,0,1000,7,"energyCalibrationFunctions","spectrumPixel"); - fspixel->SetParNames("Background Pedestal","Background slope", "Peak position","Noise RMS", "Number of Photons","Charge Sharing Pedestal","Corner"); - -#endif - - -} - - - -void energyCalibration::fixParameter(int ip, Double_t val){ - - fscurve->FixParameter(ip, val); - fspectrum->FixParameter(ip, val); - fspectrumkb->FixParameter(ip, val); - fspectrumkadoublet->FixParameter(ip, val); -} - - -void energyCalibration::releaseParameter(int ip){ - - fscurve->ReleaseParameter(ip); - fspectrum->ReleaseParameter(ip); - fspectrumkb->ReleaseParameter(ip); - fspectrumkadoublet->ReleaseParameter(ip); -} - - - - - - - -energyCalibration::~energyCalibration(){ +energyCalibration::energyCalibration() + : #ifdef MYROOT - delete fscurve; - delete fspectrum; - delete fspectrumkb; - delete fspectrumkadoublet; + fit_min(-1), fit_max(-1), bg_offset(-1), bg_slope(-1), flex(-1), + noise(-1), ampl(-1), cs_slope(-1), kb_mean(-1), kb_frac(-1), mean2(-1), + ampl2(-1), fscurve(NULL), fspectrum(NULL), fspectrumkb(NULL), + fspectrumkadoublet(NULL), +#endif + funcs(NULL), plot_flag(1), // fit parameters output to screen + cs_flag(1) { + +#ifdef MYROOT + funcs = new energyCalibrationFunctions(); + + fscurve = new TF1("fscurve", funcs, &energyCalibrationFunctions::scurve, 0, + 1000, 6, "energyCalibrationFunctions", "scurve"); + fscurve->SetParNames("Background Offset", "Background Slope", + "Inflection Point", "Noise RMS", "Number of Photons", + "Charge Sharing Slope"); + + fspectrum = + new TF1("fspectrum", funcs, &energyCalibrationFunctions::spectrum, 0, + 1000, 6, "energyCalibrationFunctions", "spectrum"); + fspectrum->SetParNames("Background Pedestal", "Background slope", + "Peak position", "Noise RMS", "Number of Photons", + "Charge Sharing Pedestal"); + fspectrumkb = + new TF1("fspectrumkb", funcs, &energyCalibrationFunctions::spectrumkb, + 0, 1000, 8, "energyCalibrationFunctions", "spectrumkb"); + fspectrumkb->SetParNames("Background Pedestal", "Background slope", + "Peak position", "Noise RMS", "Number of Photons", + "Charge Sharing Pedestal", "kb mean", "kb frac"); + + fspectrumkadoublet = + new TF1("fspectrumkadoublet", funcs, + &energyCalibrationFunctions::spectrumkadoublet, 0, 1000, 8, + "energyCalibrationFunctions", "spectrumkadoublet"); + fspectrumkadoublet->SetParNames( + "Background Pedestal", "Background slope", "Peak position", "Noise RMS", + "Number of Photons", "Charge Sharing Pedestal", "ka2 mean", "n2"); + + fspixel = + new TF1("fspixel", funcs, &energyCalibrationFunctions::spectrumPixel, 0, + 1000, 7, "energyCalibrationFunctions", "spectrumPixel"); + fspixel->SetParNames("Background Pedestal", "Background slope", + "Peak position", "Noise RMS", "Number of Photons", + "Charge Sharing Pedestal", "Corner"); + +#endif +} + +void energyCalibration::fixParameter(int ip, Double_t val) { + + fscurve->FixParameter(ip, val); + fspectrum->FixParameter(ip, val); + fspectrumkb->FixParameter(ip, val); + fspectrumkadoublet->FixParameter(ip, val); +} + +void energyCalibration::releaseParameter(int ip) { + + fscurve->ReleaseParameter(ip); + fspectrum->ReleaseParameter(ip); + fspectrumkb->ReleaseParameter(ip); + fspectrumkadoublet->ReleaseParameter(ip); +} + +energyCalibration::~energyCalibration() { +#ifdef MYROOT + delete fscurve; + delete fspectrum; + delete fspectrumkb; + delete fspectrumkadoublet; #endif - } #ifdef MYROOT +TH1F *energyCalibration::createMedianHistogram(TH2F *h2, int ch0, int nch, + int direction) { + if (h2 == NULL || nch == 0) + return NULL; + double *x = new double[nch]; + TH1F *h1 = NULL; + double val = -1; -TH1F* energyCalibration::createMedianHistogram(TH2F* h2, int ch0, int nch, int direction) { - - if (h2==NULL || nch==0) - return NULL; - - double *x=new double[nch]; - TH1F *h1=NULL; - - double val=-1; - - if (direction==0) { - h1=new TH1F("median","Median",h2->GetYaxis()->GetNbins(),h2->GetYaxis()->GetXmin(),h2->GetYaxis()->GetXmax()); - for (int ib=0; ibGetXaxis()->GetNbins(); ib++) { - for (int ich=0; ichGetBinContent(ch0+ich+1,ib+1); - } - val=energyCalibrationFunctions::median(x, nch); - h1->SetBinContent(ib+1,val); + if (direction == 0) { + h1 = new TH1F("median", "Median", h2->GetYaxis()->GetNbins(), + h2->GetYaxis()->GetXmin(), h2->GetYaxis()->GetXmax()); + for (int ib = 0; ib < h1->GetXaxis()->GetNbins(); ib++) { + for (int ich = 0; ich < nch; ich++) { + x[ich] = h2->GetBinContent(ch0 + ich + 1, ib + 1); + } + val = energyCalibrationFunctions::median(x, nch); + h1->SetBinContent(ib + 1, val); + } + } else if (direction == 1) { + h1 = new TH1F("median", "Median", h2->GetXaxis()->GetNbins(), + h2->GetXaxis()->GetXmin(), h2->GetXaxis()->GetXmax()); + for (int ib = 0; ib < h1->GetYaxis()->GetNbins(); ib++) { + for (int ich = 0; ich < nch; ich++) { + x[ich] = h2->GetBinContent(ib + 1, ch0 + ich + 1); + } + val = energyCalibrationFunctions::median(x, nch); + h1->SetBinContent(ib + 1, val); + } } - } else if (direction==1) { - h1=new TH1F("median","Median",h2->GetXaxis()->GetNbins(),h2->GetXaxis()->GetXmin(),h2->GetXaxis()->GetXmax()); - for (int ib=0; ibGetYaxis()->GetNbins(); ib++) { - for (int ich=0; ichGetBinContent(ib+1,ch0+ich+1); - } - val=energyCalibrationFunctions::median(x, nch); - h1->SetBinContent(ib+1,val); - } - } - delete [] x; - - return h1; + delete[] x; + return h1; } - - - - - - - - - - - - - -void energyCalibration::setStartParameters(Double_t *par){ - bg_offset=par[0]; - bg_slope=par[1]; - flex=par[2]; - noise=par[3]; - ampl=par[4]; - cs_slope=par[5]; +void energyCalibration::setStartParameters(Double_t *par) { + bg_offset = par[0]; + bg_slope = par[1]; + flex = par[2]; + noise = par[3]; + ampl = par[4]; + cs_slope = par[5]; } -void energyCalibration::setStartParametersKb(Double_t *par){ - bg_offset=par[0]; - bg_slope=par[1]; - flex=par[2]; - noise=par[3]; - ampl=par[4]; - cs_slope=par[5]; - kb_mean=par[6]; - kb_frac=par[7]; - //fit_min = 400; // used for soleil flat field - //fit_max = 800; +void energyCalibration::setStartParametersKb(Double_t *par) { + bg_offset = par[0]; + bg_slope = par[1]; + flex = par[2]; + noise = par[3]; + ampl = par[4]; + cs_slope = par[5]; + kb_mean = par[6]; + kb_frac = par[7]; + // fit_min = 400; // used for soleil flat field + // fit_max = 800; } -void energyCalibration::setStartParametersKaDoublet(Double_t *par){ - bg_offset=par[0]; - bg_slope=par[1]; - flex=par[2]; - noise=par[3]; - ampl=par[4]; - cs_slope=par[5]; - mean2=par[6]; - ampl2=par[7]; - //fit_min = 400; // used for soleil flat field - //fit_max = 800; +void energyCalibration::setStartParametersKaDoublet(Double_t *par) { + bg_offset = par[0]; + bg_slope = par[1]; + flex = par[2]; + noise = par[3]; + ampl = par[4]; + cs_slope = par[5]; + mean2 = par[6]; + ampl2 = par[7]; + // fit_min = 400; // used for soleil flat field + // fit_max = 800; } - -void energyCalibration::getStartParameters(Double_t *par){ - par[0]=bg_offset; - par[1]=bg_slope; - par[2]=flex; - par[3]=noise; - par[4]=ampl; - par[5]=cs_slope; +void energyCalibration::getStartParameters(Double_t *par) { + par[0] = bg_offset; + par[1] = bg_slope; + par[2] = flex; + par[3] = noise; + par[4] = ampl; + par[5] = cs_slope; } #endif int energyCalibration::setChargeSharing(int p) { - if (p>=0) { - cs_flag=p; -#ifdef MYROOT - if (p) { - fscurve->ReleaseParameter(5); - fspectrum->ReleaseParameter(1); - fspectrumkb->ReleaseParameter(1); - fspectrumkadoublet->ReleaseParameter(1); - } else { - fscurve->FixParameter(5,0); - fspectrum->FixParameter(1,0); - fspectrumkb->FixParameter(1,0); - fspectrumkadoublet->FixParameter(1,0); - } + if (p >= 0) { + cs_flag = p; +#ifdef MYROOT + if (p) { + fscurve->ReleaseParameter(5); + fspectrum->ReleaseParameter(1); + fspectrumkb->ReleaseParameter(1); + fspectrumkadoublet->ReleaseParameter(1); + } else { + fscurve->FixParameter(5, 0); + fspectrum->FixParameter(1, 0); + fspectrumkb->FixParameter(1, 0); + fspectrumkadoublet->FixParameter(1, 0); + } #endif - } - - return cs_flag; + } + + return cs_flag; } - -#ifdef MYROOT +#ifdef MYROOT void energyCalibration::initFitFunction(TF1 *fun, TH1 *h1) { - Double_t min=fit_min, max=fit_max; + Double_t min = fit_min, max = fit_max; - Double_t mypar[6]; - - if (max==-1) - max=h1->GetXaxis()->GetXmax(); - - if (min==-1) - min=h1->GetXaxis()->GetXmin(); + Double_t mypar[6]; - - if (bg_offset==-1) - mypar[0]=0; - else - mypar[0]=bg_offset; + if (max == -1) + max = h1->GetXaxis()->GetXmax(); + if (min == -1) + min = h1->GetXaxis()->GetXmin(); - if (bg_slope==-1) - mypar[1]=0; - else - mypar[1]=bg_slope; + if (bg_offset == -1) + mypar[0] = 0; + else + mypar[0] = bg_offset; + if (bg_slope == -1) + mypar[1] = 0; + else + mypar[1] = bg_slope; - if (flex==-1) - mypar[2]=(min+max)/2.; - else - mypar[2]=flex; + if (flex == -1) + mypar[2] = (min + max) / 2.; + else + mypar[2] = flex; + if (noise == -1) + mypar[3] = 0.1; + else + mypar[3] = noise; - if (noise==-1) - mypar[3]=0.1; - else - mypar[3]=noise; + if (ampl == -1) + mypar[4] = + h1->GetBinContent(h1->GetXaxis()->FindBin(0.5 * (max + min))); + else + mypar[4] = ampl; - if (ampl==-1) - mypar[4]=h1->GetBinContent(h1->GetXaxis()->FindBin(0.5*(max+min))); - else - mypar[4]=ampl; + if (cs_slope == -1) + mypar[5] = 0; + else + mypar[5] = cs_slope; - if (cs_slope==-1) - mypar[5]=0; - else - mypar[5]=cs_slope; - - fun->SetParameters(mypar); - - fun->SetRange(min,max); + fun->SetParameters(mypar); + fun->SetRange(min, max); } void energyCalibration::initFitFunctionKb(TF1 *fun, TH1 *h1) { - Double_t min=fit_min, max=fit_max; + Double_t min = fit_min, max = fit_max; - Double_t mypar[8]; - - if (max==-1) - max=h1->GetXaxis()->GetXmax(); - - if (min==-1) - min=h1->GetXaxis()->GetXmin(); + Double_t mypar[8]; - - if (bg_offset==-1) - mypar[0]=0; - else - mypar[0]=bg_offset; + if (max == -1) + max = h1->GetXaxis()->GetXmax(); + if (min == -1) + min = h1->GetXaxis()->GetXmin(); - if (bg_slope==-1) - mypar[1]=0; - else - mypar[1]=bg_slope; + if (bg_offset == -1) + mypar[0] = 0; + else + mypar[0] = bg_offset; + if (bg_slope == -1) + mypar[1] = 0; + else + mypar[1] = bg_slope; - if (flex==-1) - mypar[2]=(min+max)/2.; - else - mypar[2]=flex; + if (flex == -1) + mypar[2] = (min + max) / 2.; + else + mypar[2] = flex; + if (noise == -1) + mypar[3] = 0.1; + else + mypar[3] = noise; - if (noise==-1) - mypar[3]=0.1; - else - mypar[3]=noise; + if (ampl == -1) + mypar[4] = + h1->GetBinContent(h1->GetXaxis()->FindBin(0.5 * (max + min))); + else + mypar[4] = ampl; - if (ampl==-1) - mypar[4]=h1->GetBinContent(h1->GetXaxis()->FindBin(0.5*(max+min))); - else - mypar[4]=ampl; + if (cs_slope == -1) + mypar[5] = 0; + else + mypar[5] = cs_slope; - if (cs_slope==-1) - mypar[5]=0; - else - mypar[5]=cs_slope; + if (kb_mean == -1) + mypar[6] = 0; + else + mypar[6] = kb_mean; - if (kb_mean==-1) - mypar[6]=0; - else - mypar[6]=kb_mean; + if (kb_frac == -1) + mypar[7] = 0; + else + mypar[7] = kb_frac; - if (kb_frac==-1) - mypar[7]=0; - else - mypar[7]=kb_frac; - - fun->SetParameters(mypar); - - fun->SetRange(min,max); + fun->SetParameters(mypar); + fun->SetRange(min, max); } void energyCalibration::initFitFunctionKaDoublet(TF1 *fun, TH1 *h1) { - Double_t min=fit_min, max=fit_max; + Double_t min = fit_min, max = fit_max; - Double_t mypar[8]; - - if (max==-1) - max=h1->GetXaxis()->GetXmax(); - - if (min==-1) - min=h1->GetXaxis()->GetXmin(); + Double_t mypar[8]; - - if (bg_offset==-1) - mypar[0]=0; - else - mypar[0]=bg_offset; + if (max == -1) + max = h1->GetXaxis()->GetXmax(); + if (min == -1) + min = h1->GetXaxis()->GetXmin(); - if (bg_slope==-1) - mypar[1]=0; - else - mypar[1]=bg_slope; - - - if (flex==-1) - mypar[2]=(min+max)/2.; - else - mypar[2]=flex; - - - if (noise==-1) - mypar[3]=0.1; - else - mypar[3]=noise; - - if (ampl==-1) - mypar[4]=h1->GetBinContent(h1->GetXaxis()->FindBin(0.5*(max+min))); - else - mypar[4]=ampl; - - if (cs_slope==-1) - mypar[5]=0; - else - mypar[5]=cs_slope; - - if (mean2==-1) - mypar[6]=0; - else - mypar[6]=mean2; - - if (ampl2==-1) - mypar[7]=0; - else - mypar[7]=ampl2; - - fun->SetParameters(mypar); - - fun->SetRange(min,max); - -} - -TF1* energyCalibration::fitFunction(TF1 *fun, TH1 *h1, Double_t *mypar, Double_t *emypar) { - - - TF1* fitfun; - - char fname[100]; - - strcpy(fname, fun->GetName()); - - if (plot_flag) { - h1->Fit(fname,"R0Q"); - } else - h1->Fit(fname,"R0Q"); - - fitfun= h1->GetFunction(fname); - fitfun->GetParameters(mypar); - for (int ip=0; ip<6; ip++) { - emypar[ip]=fitfun->GetParError(ip); - } - return fitfun; -} - -TF1* energyCalibration::fitFunctionKb(TF1 *fun, TH1 *h1, Double_t *mypar, Double_t *emypar) { - - - TF1* fitfun; - - char fname[100]; - - strcpy(fname, fun->GetName()); - - if (plot_flag) { - h1->Fit(fname,"R0Q"); - } else - h1->Fit(fname,"R0Q"); - - fitfun= h1->GetFunction(fname); - fitfun->GetParameters(mypar); - for (int ip=0; ip<8; ip++) { - emypar[ip]=fitfun->GetParError(ip); - } - return fitfun; -} - -TF1* energyCalibration::fitFunctionKaDoublet(TF1 *fun, TH1 *h1, Double_t *mypar, Double_t *emypar) { - - - TF1* fitfun; - - char fname[100]; - - strcpy(fname, fun->GetName()); - - if (plot_flag) { - h1->Fit(fname,"R0Q"); - } else - h1->Fit(fname,"R0Q"); - - - fitfun= h1->GetFunction(fname); - fitfun->GetParameters(mypar); - for (int ip=0; ip<8; ip++) { - emypar[ip]=fitfun->GetParError(ip); - } - return fitfun; -} - -TF1* energyCalibration::fitSCurve(TH1 *h1, Double_t *mypar, Double_t *emypar) { - initFitFunction(fscurve,h1); - return fitFunction(fscurve, h1, mypar, emypar); -} - - - - - -TF1* energyCalibration::fitSpectrum(TH1 *h1, Double_t *mypar, Double_t *emypar) { - initFitFunction(fspectrum,h1); - return fitFunction(fspectrum, h1, mypar, emypar); -} - -TF1* energyCalibration::fitSpectrumKb(TH1 *h1, Double_t *mypar, Double_t *emypar) { - initFitFunctionKb(fspectrumkb,h1); - return fitFunctionKb(fspectrumkb, h1, mypar, emypar); -} - -TF1* energyCalibration::fitSpectrumKaDoublet(TH1 *h1, Double_t *mypar, Double_t *emypar) { - initFitFunctionKaDoublet(fspectrumkadoublet,h1); - return fitFunctionKaDoublet(fspectrumkadoublet, h1, mypar, emypar); -} - - -TGraphErrors* energyCalibration::linearCalibration(int nscan, Double_t *en, Double_t *een, Double_t *fl, Double_t *efl, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff) { - - TGraphErrors *gr; - - Double_t mypar[2]; - - gr = new TGraphErrors(nscan,en,fl,een,efl); - - if (plot_flag) { - gr->Fit("pol1"); - gr->SetMarkerStyle(20); - } else - gr->Fit("pol1","0Q"); - - TF1 *fitfun= gr->GetFunction("pol1"); - fitfun->GetParameters(mypar); - - egain=fitfun->GetParError(1); - eoff=fitfun->GetParError(0); - - gain=funcs->setScanSign()*mypar[1]; - - off=mypar[0]; - - return gr; -} - - -TGraphErrors* energyCalibration::calibrate(int nscan, Double_t *en, Double_t *een, TH1F **h1, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff, int integral) { - - TH1F *h; - - Double_t mypar[6], emypar[6]; - Double_t fl[nscan], efl[nscan]; - - - for (int ien=0; ienGetBinContent(h1->GetXaxis()->FindBin(0.5 * (max + min))); + else + mypar[4] = ampl; + + if (cs_slope == -1) + mypar[5] = 0; + else + mypar[5] = cs_slope; + + if (mean2 == -1) + mypar[6] = 0; + else + mypar[6] = mean2; + + if (ampl2 == -1) + mypar[7] = 0; + else + mypar[7] = ampl2; + + fun->SetParameters(mypar); + + fun->SetRange(min, max); +} + +TF1 *energyCalibration::fitFunction(TF1 *fun, TH1 *h1, Double_t *mypar, + Double_t *emypar) { + + TF1 *fitfun; + + char fname[100]; + + strcpy(fname, fun->GetName()); + + if (plot_flag) { + h1->Fit(fname, "R0Q"); + } else + h1->Fit(fname, "R0Q"); + + fitfun = h1->GetFunction(fname); + fitfun->GetParameters(mypar); + for (int ip = 0; ip < 6; ip++) { + emypar[ip] = fitfun->GetParError(ip); + } + return fitfun; +} + +TF1 *energyCalibration::fitFunctionKb(TF1 *fun, TH1 *h1, Double_t *mypar, + Double_t *emypar) { + + TF1 *fitfun; + + char fname[100]; + + strcpy(fname, fun->GetName()); + + if (plot_flag) { + h1->Fit(fname, "R0Q"); + } else + h1->Fit(fname, "R0Q"); + + fitfun = h1->GetFunction(fname); + fitfun->GetParameters(mypar); + for (int ip = 0; ip < 8; ip++) { + emypar[ip] = fitfun->GetParError(ip); + } + return fitfun; +} + +TF1 *energyCalibration::fitFunctionKaDoublet(TF1 *fun, TH1 *h1, Double_t *mypar, + Double_t *emypar) { + + TF1 *fitfun; + + char fname[100]; + + strcpy(fname, fun->GetName()); + + if (plot_flag) { + h1->Fit(fname, "R0Q"); + } else + h1->Fit(fname, "R0Q"); + + fitfun = h1->GetFunction(fname); + fitfun->GetParameters(mypar); + for (int ip = 0; ip < 8; ip++) { + emypar[ip] = fitfun->GetParError(ip); + } + return fitfun; +} + +TF1 *energyCalibration::fitSCurve(TH1 *h1, Double_t *mypar, Double_t *emypar) { + initFitFunction(fscurve, h1); + return fitFunction(fscurve, h1, mypar, emypar); +} + +TF1 *energyCalibration::fitSpectrum(TH1 *h1, Double_t *mypar, + Double_t *emypar) { + initFitFunction(fspectrum, h1); + return fitFunction(fspectrum, h1, mypar, emypar); +} + +TF1 *energyCalibration::fitSpectrumKb(TH1 *h1, Double_t *mypar, + Double_t *emypar) { + initFitFunctionKb(fspectrumkb, h1); + return fitFunctionKb(fspectrumkb, h1, mypar, emypar); +} + +TF1 *energyCalibration::fitSpectrumKaDoublet(TH1 *h1, Double_t *mypar, + Double_t *emypar) { + initFitFunctionKaDoublet(fspectrumkadoublet, h1); + return fitFunctionKaDoublet(fspectrumkadoublet, h1, mypar, emypar); +} + +TGraphErrors *energyCalibration::linearCalibration( + int nscan, Double_t *en, Double_t *een, Double_t *fl, Double_t *efl, + Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff) { + + TGraphErrors *gr; + + Double_t mypar[2]; + + gr = new TGraphErrors(nscan, en, fl, een, efl); + + if (plot_flag) { + gr->Fit("pol1"); + gr->SetMarkerStyle(20); + } else + gr->Fit("pol1", "0Q"); + + TF1 *fitfun = gr->GetFunction("pol1"); + fitfun->GetParameters(mypar); + + egain = fitfun->GetParError(1); + eoff = fitfun->GetParError(0); + + gain = funcs->setScanSign() * mypar[1]; + + off = mypar[0]; + + return gr; +} + +TGraphErrors *energyCalibration::calibrate(int nscan, Double_t *en, + Double_t *een, TH1F **h1, + Double_t &gain, Double_t &off, + Double_t &egain, Double_t &eoff, + int integral) { + + TH1F *h; + + Double_t mypar[6], emypar[6]; + Double_t fl[nscan], efl[nscan]; + + for (int ien = 0; ien < nscan; ien++) { + h = h1[ien]; + if (integral) + fitSCurve(h, mypar, emypar); + else + fitSpectrum(h, mypar, emypar); + + fl[ien] = mypar[2]; + efl[ien] = emypar[2]; + } + return linearCalibration(nscan, en, een, fl, efl, gain, off, egain, eoff); } #endif - - - - diff --git a/slsDetectorCalibration/energyCalibration.h b/slsDetectorCalibration/energyCalibration.h index 800f838cb..a319f305f 100644 --- a/slsDetectorCalibration/energyCalibration.h +++ b/slsDetectorCalibration/energyCalibration.h @@ -11,7 +11,6 @@ #define MYROOT #endif - #ifdef __MAKECINT__ #define MYROOT #endif @@ -23,40 +22,35 @@ #define MYROOT #ifdef MYROOT -#include #include +#include class TH1F; class TH2F; class TGraphErrors; #endif - using namespace std; - - - -const double conven=1000./3.6; /**< electrons/keV */ -const double el=1.67E-4; /**< electron charge in fC */ - - +const double conven = 1000. / 3.6; /**< electrons/keV */ +const double el = 1.67E-4; /**< electron charge in fC */ /** \mainpage Common Root library for SLS detectors data analysis * * \section intro_sec Introduction - We know very well s-curves etc. but at the end everybody uses different functions ;-). + We know very well s-curves etc. but at the end everybody uses different + functions ;-). * \subsection mot_sec Motivation It would be greate to use everybody the same functions... */ - /** - * * -@libdoc The energiCalibration class contains all the necessary functions for s-curve fitting and linear calibration of the threshold. + * +@libdoc The energiCalibration class contains all the necessary functions for +s-curve fitting and linear calibration of the threshold. * * @short Energy calibration functions * @author Anna Bergamaschi @@ -65,152 +59,155 @@ const double el=1.67E-4; /**< electron charge in fC */ */ -/** - class containing all the possible energy calibration functions (scurves with and without charge sharing, gaussian spectrum with and without charge sharing, possibility of chosing the sign of the X-axis) +/** + class containing all the possible energy calibration functions (scurves with + and without charge sharing, gaussian spectrum with and without charge sharing, + possibility of chosing the sign of the X-axis) */ class energyCalibrationFunctions { - public: - - energyCalibrationFunctions(int s=-1) {setScanSign(s);}; - + public: + energyCalibrationFunctions(int s = -1) { setScanSign(s); }; + /** sets scan sign - \param s can be 1 (energy and x-axis have the same direction) or -1 (energy and x-axis have opposite directions) otherwise gets - \returns current scan sign can be 1 (energy and x-axis have the same direction) or -1 (energy and x-axis have opposite directions) + \param s can be 1 (energy and x-axis have the same direction) or -1 + (energy and x-axis have opposite directions) otherwise gets \returns + current scan sign can be 1 (energy and x-axis have the same direction) or + -1 (energy and x-axis have opposite directions) */ - int setScanSign(int s=0) {if (s==1 || s==-1) sign=s; return sign;};; - + int setScanSign(int s = 0) { + if (s == 1 || s == -1) + sign = s; + return sign; + }; + ; #ifdef MYROOT - /** - Gaussian Function with charge sharing pedestal - par[0] is the absolute height of the background pedestal - par[1] is the slope of the background pedestal - */ - Double_t pedestal(Double_t *x, Double_t *par); + /** + Gaussian Function with charge sharing pedestal + par[0] is the absolute height of the background pedestal + par[1] is the slope of the background pedestal + */ + Double_t pedestal(Double_t *x, Double_t *par); - /** - Gaussian Function with charge sharing pedestal - par[0] is the absolute height of the background pedestal - par[1] is the slope of the background pedestal - par[2] is the gaussian peak position - par[3] is the RMS of the gaussian (and of the pedestal) - par[4] is the height of the function - par[5] is the fractional height of the charge sharing pedestal (scales with par[3]) - */ - Double_t gaussChargeSharing(Double_t *x, Double_t *par); - Double_t gaussChargeSharingKb(Double_t *x, Double_t *par); - Double_t gaussChargeSharingKaDoublet(Double_t *x, Double_t *par); - /** - Gaussian Function with charge sharing pedestal - par[0] is the absolute height of the background pedestal - par[1] is the slope of the background pedestal - par[2] is the gaussian peak position - par[3] is the RMS of the gaussian (and of the pedestal) - par[4] is the height of the function - par[5] is the fractional height of the charge sharing pedestal (scales with par[3]) - */ - Double_t gaussChargeSharingPixel(Double_t *x, Double_t *par); + /** + Gaussian Function with charge sharing pedestal + par[0] is the absolute height of the background pedestal + par[1] is the slope of the background pedestal + par[2] is the gaussian peak position + par[3] is the RMS of the gaussian (and of the pedestal) + par[4] is the height of the function + par[5] is the fractional height of the charge sharing pedestal (scales + with par[3]) + */ + Double_t gaussChargeSharing(Double_t *x, Double_t *par); + Double_t gaussChargeSharingKb(Double_t *x, Double_t *par); + Double_t gaussChargeSharingKaDoublet(Double_t *x, Double_t *par); + /** + Gaussian Function with charge sharing pedestal + par[0] is the absolute height of the background pedestal + par[1] is the slope of the background pedestal + par[2] is the gaussian peak position + par[3] is the RMS of the gaussian (and of the pedestal) + par[4] is the height of the function + par[5] is the fractional height of the charge sharing pedestal (scales + with par[3]) + */ + Double_t gaussChargeSharingPixel(Double_t *x, Double_t *par); - /** - Basic erf function - par[0] is the inflection point - par[1] is the RMS - par[2] is the amplitude - */ -Double_t erfFunction(Double_t *x, Double_t *par) ; - Double_t erfBox(Double_t *z, Double_t *par); - /** Erf function with charge sharing slope - par[0] is the pedestal - par[1] is the slope of the pedestal - par[2] is the inflection point - par[3] is the RMS - par[4] is the amplitude - par[5] is the angual coefficient of the charge sharing slope (scales with par[3]) - */ -Double_t erfFunctionChargeSharing(Double_t *x, Double_t *par); - - /** Double Erf function with charge sharing slope - par[0] is the pedestal - par[1] is the slope of the pedestal - par[2] is the inflection point of the first energy - par[3] is the RMS of the first energy - par[4] is the amplitude of the first energy - par[5] is the angual coefficient of the charge sharing slope of the first energy (scales with par[3]) - par[6] is the inflection point of the second energy - par[7] is the RMS of the second energy - par[8] is the amplitude of the second energy - par[9] is the angual coefficient of the charge sharing slope of the second energy (scales with par[8]) - */ + /** + Basic erf function + par[0] is the inflection point + par[1] is the RMS + par[2] is the amplitude + */ + Double_t erfFunction(Double_t *x, Double_t *par); + Double_t erfBox(Double_t *z, Double_t *par); + /** Erf function with charge sharing slope + par[0] is the pedestal + par[1] is the slope of the pedestal + par[2] is the inflection point + par[3] is the RMS + par[4] is the amplitude + par[5] is the angual coefficient of the charge sharing slope (scales + with par[3]) + */ + Double_t erfFunctionChargeSharing(Double_t *x, Double_t *par); -Double_t erfFuncFluo(Double_t *x, Double_t *par); + /** Double Erf function with charge sharing slope + par[0] is the pedestal + par[1] is the slope of the pedestal + par[2] is the inflection point of the first energy + par[3] is the RMS of the first energy + par[4] is the amplitude of the first energy + par[5] is the angual coefficient of the charge sharing slope of the + first energy (scales with par[3]) par[6] is the inflection point of the + second energy par[7] is the RMS of the second energy par[8] is the + amplitude of the second energy par[9] is the angual coefficient of the + charge sharing slope of the second energy (scales with par[8]) + */ - - /** - static function Gaussian with charge sharing pedestal with the correct scan sign - par[0] is the absolute height of the background pedestal - par[1] is the slope of the pedestal - par[2] is the gaussian peak position - par[3] is the RMS of the gaussian (and of the pedestal) - par[4] is the height of the function - par[5] is the fractional height of the charge sharing pedestal (scales with par[4] - */ - Double_t spectrum(Double_t *x, Double_t *par); - Double_t spectrumkb(Double_t *x, Double_t *par); - Double_t spectrumkadoublet(Double_t *x, Double_t *par); + Double_t erfFuncFluo(Double_t *x, Double_t *par); - /** - static function Gaussian with charge sharing pedestal with the correct scan sign - par[0] is the absolute height of the background pedestal - par[1] is the slope of the pedestal - par[2] is the gaussian peak position - par[3] is the RMS of the gaussian (and of the pedestal) - par[4] is the height of the function - par[5] is the fractional height of the charge sharing pedestal (scales with par[4] - */ - Double_t spectrumPixel(Double_t *x, Double_t *par); + /** + static function Gaussian with charge sharing pedestal with the correct + scan sign par[0] is the absolute height of the background pedestal par[1] + is the slope of the pedestal par[2] is the gaussian peak position par[3] + is the RMS of the gaussian (and of the pedestal) par[4] is the height of + the function par[5] is the fractional height of the charge sharing + pedestal (scales with par[4] + */ + Double_t spectrum(Double_t *x, Double_t *par); + Double_t spectrumkb(Double_t *x, Double_t *par); + Double_t spectrumkadoublet(Double_t *x, Double_t *par); + /** + static function Gaussian with charge sharing pedestal with the correct + scan sign par[0] is the absolute height of the background pedestal par[1] + is the slope of the pedestal par[2] is the gaussian peak position par[3] + is the RMS of the gaussian (and of the pedestal) par[4] is the height of + the function par[5] is the fractional height of the charge sharing + pedestal (scales with par[4] + */ + Double_t spectrumPixel(Double_t *x, Double_t *par); - /** Erf function with charge sharing slope with the correct scan sign - par[0] is the pedestal - par[1] is the slope of the pedestal - par[2] is the inflection point - par[3] is the RMS - par[4] is the amplitude - par[5] is the angual coefficient of the charge sharing slope (scales with par[3]) - */ - Double_t scurve(Double_t *x, Double_t *par); + /** Erf function with charge sharing slope with the correct scan sign + par[0] is the pedestal + par[1] is the slope of the pedestal + par[2] is the inflection point + par[3] is the RMS + par[4] is the amplitude + par[5] is the angual coefficient of the charge sharing slope (scales + with par[3]) + */ + Double_t scurve(Double_t *x, Double_t *par); - - - /** Double Erf function with charge sharing slope - par[0] is the pedestal - par[1] is the slope of the pedestal - par[2] is the inflection point of the first energy - par[3] is the RMS of the first energy - par[4] is the amplitude of the first energy - par[5] is the angual coefficient of the charge sharing slope of the first energy (scales with par[3]) - par[6] is the inflection point of the second energy - par[7] is the RMS of the second energy - par[8] is the amplitude of the second energy - par[9] is the angual coefficient of the charge sharing slope of the second energy (scales with par[8]) - */ - Double_t scurveFluo(Double_t *x, Double_t *par); + /** Double Erf function with charge sharing slope + par[0] is the pedestal + par[1] is the slope of the pedestal + par[2] is the inflection point of the first energy + par[3] is the RMS of the first energy + par[4] is the amplitude of the first energy + par[5] is the angual coefficient of the charge sharing slope of the first + energy (scales with par[3]) par[6] is the inflection point of the second + energy par[7] is the RMS of the second energy par[8] is the amplitude of + the second energy par[9] is the angual coefficient of the charge sharing + slope of the second energy (scales with par[8]) + */ + Double_t scurveFluo(Double_t *x, Double_t *par); #endif -/** Calculates the median of an array of n elements */ - static double median(double *x, int n); -/** Calculates the median of an array of n elements (swaps the arrays!)*/ - static int quick_select(int arr[], int n); -/** Calculates the median of an array of n elements (swaps the arrays!)*/ - static int kth_smallest(int *a, int n, int k); - - private: - int sign; - + /** Calculates the median of an array of n elements */ + static double median(double *x, int n); + /** Calculates the median of an array of n elements (swaps the arrays!)*/ + static int quick_select(int arr[], int n); + /** Calculates the median of an array of n elements (swaps the arrays!)*/ + static int kth_smallest(int *a, int n, int k); + private: + int sign; }; /** @@ -218,162 +215,186 @@ Double_t erfFuncFluo(Double_t *x, Double_t *par); */ -class energyCalibration { +class energyCalibration { - - public: - /** - default constructor - creates the function with which the s-curves will be fitted - */ - energyCalibration(); - - /** - default destructor - deletes the function with which the s-curves will be fitted - */ - ~energyCalibration(); - - /** sets plot flag - \param p plot flag (-1 gets, 0 unsets, >0 plot) - \returns current plot flag + public: + /** + default constructor - creates the function with which the s-curves + will be fitted */ - int setPlotFlag(int p=-1) {if (p>=0) plot_flag=p; return plot_flag;}; + energyCalibration(); + + /** + default destructor - deletes the function with which the s-curves will + be fitted + */ + ~energyCalibration(); + + /** sets plot flag + \param p plot flag (-1 gets, 0 unsets, >0 plot) + \returns current plot flag + */ + int setPlotFlag(int p = -1) { + if (p >= 0) + plot_flag = p; + return plot_flag; + }; /** sets scan sign - \param s can be 1 (energy and x-axis have the same direction) or -1 (energy and x-axis have opposite directions) otherwise gets - \returns current scan sign can be 1 (energy and x-axis have the same direction) or -1 (energy and x-axis have opposite directions) + \param s can be 1 (energy and x-axis have the same direction) or -1 + (energy and x-axis have opposite directions) otherwise gets \returns + current scan sign can be 1 (energy and x-axis have the same direction) or + -1 (energy and x-axis have opposite directions) */ - int setScanSign(int s=0) {return funcs->setScanSign(s);}; - + int setScanSign(int s = 0) { return funcs->setScanSign(s); }; + /** sets plot flag - \param p plot flag (-1 gets, 0 unsets, >0 plot) - \returns current plot flag + \param p plot flag (-1 gets, 0 unsets, >0 plot) + \returns current plot flag */ - int setChargeSharing(int p=-1); + int setChargeSharing(int p = -1); + void fixParameter(int ip, Double_t val); - void fixParameter(int ip, Double_t val); - - void releaseParameter(int ip); + void releaseParameter(int ip); #ifdef MYROOT - /** - Creates an histogram with the median of nchannels starting from a specified one. the direction on which it is mediated can be selected (defaults to x=0) - \param h2 2D histogram on which the median will be calculated - \param ch0 starting channel - \param nch number of channels to be mediated - \param direction can be either 0 (x, default) or 1 (y) - \returns a TH1F histogram with the X-axis as a clone of the h2 Y (if direction=0) or X (if direction=0) axis, and on the Y axis the median of the counts of the mediated channels f h2 - */ - static TH1F* createMedianHistogram(TH2F* h2, int ch0, int nch, int direction=0); + /** + Creates an histogram with the median of nchannels starting from a + specified one. the direction on which it is mediated can be selected + (defaults to x=0) \param h2 2D histogram on which the median will be + calculated \param ch0 starting channel \param nch number of channels to + be mediated \param direction can be either 0 (x, default) or 1 (y) + \returns a TH1F histogram with the X-axis as a clone of the h2 Y (if + direction=0) or X (if direction=0) axis, and on the Y axis the median of + the counts of the mediated channels f h2 + */ + static TH1F *createMedianHistogram(TH2F *h2, int ch0, int nch, + int direction = 0); + /** sets the s-curve fit range + \param mi minimum of the fit range (-1 is histogram x-min) + \param ma maximum of the fit range (-1 is histogram x-max) + */ + void setFitRange(Double_t mi, Double_t ma) { + fit_min = mi; + fit_max = ma; + }; - /** sets the s-curve fit range - \param mi minimum of the fit range (-1 is histogram x-min) - \param ma maximum of the fit range (-1 is histogram x-max) - */ - void setFitRange(Double_t mi, Double_t ma){fit_min=mi; fit_max=ma;}; + /** gets the s-curve fit range + \param mi reference for minimum of the fit range (-1 is histogram x-min) + \param ma reference for maximum of the fit range (-1 is histogram x-max) + */ + void getFitRange(Double_t &mi, Double_t &ma) { + mi = fit_min; + ma = fit_max; + }; - /** gets the s-curve fit range - \param mi reference for minimum of the fit range (-1 is histogram x-min) - \param ma reference for maximum of the fit range (-1 is histogram x-max) - */ - void getFitRange(Double_t &mi, Double_t &ma){mi=fit_min; ma=fit_max;}; + /** set start parameters for the s-curve function + \param par parameters, -1 sets to auto-calculation + par[0] is the pedestal + par[1] is the slope of the pedestal + par[2] is the inflection point + par[3] is the RMS + par[4] is the amplitude + par[5] is the angual coefficient of the charge sharing slope (scales + with par[3]) -- always positive + */ + void setStartParameters(Double_t *par); + void setStartParametersKb(Double_t *par); + void setStartParametersKaDoublet(Double_t *par); + /** get start parameters for the s-curve function + \param par parameters, -1 means auto-calculated + par[0] is the pedestal + par[1] is the slope of the pedestal + par[2] is the inflection point + par[3] is the RMS + par[4] is the amplitude + par[5] is the angual coefficient of the charge sharing slope (scales + with par[3]) -- always positive + */ + void getStartParameters(Double_t *par); -/** set start parameters for the s-curve function - \param par parameters, -1 sets to auto-calculation - par[0] is the pedestal - par[1] is the slope of the pedestal - par[2] is the inflection point - par[3] is the RMS - par[4] is the amplitude - par[5] is the angual coefficient of the charge sharing slope (scales with par[3]) -- always positive - */ - void setStartParameters(Double_t *par); - void setStartParametersKb(Double_t *par); - void setStartParametersKaDoublet(Double_t *par); + /** + fits histogram with the s-curve function + \param h1 1d-histogram to be fitted + \param mypar pointer to fit parameters array + \param emypar pointer to fit parameter errors + \returns the fitted function - can be used e.g. to get the Chi2 or + similar + */ + TF1 *fitSCurve(TH1 *h1, Double_t *mypar, Double_t *emypar); -/** get start parameters for the s-curve function - \param par parameters, -1 means auto-calculated - par[0] is the pedestal - par[1] is the slope of the pedestal - par[2] is the inflection point - par[3] is the RMS - par[4] is the amplitude - par[5] is the angual coefficient of the charge sharing slope (scales with par[3]) -- always positive - */ - void getStartParameters(Double_t *par); + /** + fits histogram with the spectrum + \param h1 1d-histogram to be fitted + \param mypar pointer to fit parameters array + \param emypar pointer to fit parameter errors + \returns the fitted function - can be used e.g. to get the Chi2 or + similar + */ + TF1 *fitSpectrum(TH1 *h1, Double_t *mypar, Double_t *emypar); + TF1 *fitSpectrumKb(TH1 *h1, Double_t *mypar, Double_t *emypar); + TF1 *fitSpectrumKaDoublet(TH1 *h1, Double_t *mypar, Double_t *emypar); - /** - fits histogram with the s-curve function - \param h1 1d-histogram to be fitted - \param mypar pointer to fit parameters array - \param emypar pointer to fit parameter errors - \returns the fitted function - can be used e.g. to get the Chi2 or similar - */ - TF1 *fitSCurve(TH1 *h1, Double_t *mypar, Double_t *emypar); + /** + calculates gain and offset for the set of inflection points + \param nscan number of energy scans + \param en array of energies (nscan long) + \param een array of errors on energies (nscan long) - can be NULL! + \param fl array of inflection points (nscan long) + \param efl array of errors on the inflection points (nscan long) + \param gain reference to gain resulting from the fit + \param off reference to offset resulting from the fit + \param egain reference to error on the gain resulting from the fit + \param eoff reference to the error on the offset resulting from the fit + \returns graph energy vs inflection point + */ + TGraphErrors *linearCalibration(int nscan, Double_t *en, Double_t *een, + Double_t *fl, Double_t *efl, Double_t &gain, + Double_t &off, Double_t &egain, + Double_t &eoff); + /** + calculates gain and offset for the set of energy scans + \param nscan number of energy scans + \param en array of energies (nscan long) + \param een array of errors on energies (nscan long) - can be NULL! + \param h1 array of TH1 + \param gain reference to gain resulting from the fit + \param off reference to offset resulting from the fit + \param egain reference to error on the gain resulting from the fit + \param eoff reference to the error on the offset resulting from the fit + \returns graph energy vs inflection point + */ + TGraphErrors *calibrateScurves(int nscan, Double_t *en, Double_t *een, + TH1F **h1, Double_t &gain, Double_t &off, + Double_t &egain, Double_t &eoff) { + return calibrate(nscan, en, een, h1, gain, off, egain, eoff, 1); + }; - /** - fits histogram with the spectrum - \param h1 1d-histogram to be fitted - \param mypar pointer to fit parameters array - \param emypar pointer to fit parameter errors - \returns the fitted function - can be used e.g. to get the Chi2 or similar - */ - TF1 *fitSpectrum(TH1 *h1, Double_t *mypar, Double_t *emypar); - TF1 *fitSpectrumKb(TH1 *h1, Double_t *mypar, Double_t *emypar); - TF1 *fitSpectrumKaDoublet(TH1 *h1, Double_t *mypar, Double_t *emypar); - - - /** - calculates gain and offset for the set of inflection points - \param nscan number of energy scans - \param en array of energies (nscan long) - \param een array of errors on energies (nscan long) - can be NULL! - \param fl array of inflection points (nscan long) - \param efl array of errors on the inflection points (nscan long) - \param gain reference to gain resulting from the fit - \param off reference to offset resulting from the fit - \param egain reference to error on the gain resulting from the fit - \param eoff reference to the error on the offset resulting from the fit - \returns graph energy vs inflection point - */ - TGraphErrors* linearCalibration(int nscan, Double_t *en, Double_t *een, Double_t *fl, Double_t *efl, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff); - - /** - calculates gain and offset for the set of energy scans - \param nscan number of energy scans - \param en array of energies (nscan long) - \param een array of errors on energies (nscan long) - can be NULL! - \param h1 array of TH1 - \param gain reference to gain resulting from the fit - \param off reference to offset resulting from the fit - \param egain reference to error on the gain resulting from the fit - \param eoff reference to the error on the offset resulting from the fit - \returns graph energy vs inflection point - */ - TGraphErrors* calibrateScurves(int nscan, Double_t *en, Double_t *een, TH1F **h1, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff){return calibrate(nscan, en, een, h1, gain, off, egain, eoff, 1);}; - - /** - calculates gain and offset for the set of energy spectra - \param nscan number of energy scans - \param en array of energies (nscan long) - \param een array of errors on energies (nscan long) - can be NULL! - \param h1 array of TH1 - \param gain reference to gain resulting from the fit - \param off reference to offset resulting from the fit - \param egain reference to error on the gain resulting from the fit - \param eoff reference to the error on the offset resulting from the fit - \returns graph energy vs peak - */ - TGraphErrors* calibrateSpectra(int nscan, Double_t *en, Double_t *een, TH1F **h1, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff){return calibrate(nscan, en, een, h1, gain, off, egain, eoff, 0);}; - + /** + calculates gain and offset for the set of energy spectra + \param nscan number of energy scans + \param en array of energies (nscan long) + \param een array of errors on energies (nscan long) - can be NULL! + \param h1 array of TH1 + \param gain reference to gain resulting from the fit + \param off reference to offset resulting from the fit + \param egain reference to error on the gain resulting from the fit + \param eoff reference to the error on the offset resulting from the fit + \returns graph energy vs peak + */ + TGraphErrors *calibrateSpectra(int nscan, Double_t *en, Double_t *een, + TH1F **h1, Double_t &gain, Double_t &off, + Double_t &egain, Double_t &eoff) { + return calibrate(nscan, en, een, h1, gain, off, egain, eoff, 0); + }; #endif - private: - + private: #ifdef MYROOT /** calculates gain and offset for the set of energies @@ -386,86 +407,72 @@ class energyCalibration { \param egain reference to error on the gain resulting from the fit \param eoff reference to the error on the offset resulting from the fit \param integral 1 is an s-curve set (default), 0 spectra - \returns graph energy vs peak/inflection point + \returns graph energy vs peak/inflection point */ - TGraphErrors* calibrate(int nscan, Double_t *en, Double_t *een, TH1F **h1, Double_t &gain, Double_t &off, Double_t &egain, Double_t &eoff, int integral=1); + TGraphErrors *calibrate(int nscan, Double_t *en, Double_t *een, TH1F **h1, + Double_t &gain, Double_t &off, Double_t &egain, + Double_t &eoff, int integral = 1); + /** + Initializes the start parameters and the range of the fit depending on + the histogram characteristics and/or on the start parameters specified by + the user \param fun pointer to function to be initialized \param h1 + histogram from which to extract the range and start parameters, if not + already specified by the user - /** - Initializes the start parameters and the range of the fit depending on the histogram characteristics and/or on the start parameters specified by the user - \param fun pointer to function to be initialized - \param h1 histogram from which to extract the range and start parameters, if not already specified by the user - -*/ - - void initFitFunction(TF1 *fun, TH1 *h1); - void initFitFunctionKb(TF1 *fun, TH1 *h1); - void initFitFunctionKaDoublet(TF1 *fun, TH1 *h1); - - - /** - Performs the fit according to the flags specified and returns the fitted function - \param fun function to fit - \param h1 histogram to fit - \param mypar pointer to fit parameters array - \param emypar pointer to fit parameter errors - \returns the fitted function - can be used e.g. to get the Chi2 or similar */ - TF1 *fitFunction(TF1 *fun, TH1 *h1, Double_t *mypar, Double_t *emypar); - TF1 *fitFunctionKb(TF1 *fun, TH1 *h1, Double_t *mypar, Double_t *emypar); - TF1 *fitFunctionKaDoublet(TF1 *fun, TH1 *h1, Double_t *mypar, Double_t *emypar); + + void initFitFunction(TF1 *fun, TH1 *h1); + void initFitFunctionKb(TF1 *fun, TH1 *h1); + void initFitFunctionKaDoublet(TF1 *fun, TH1 *h1); + + /** + Performs the fit according to the flags specified and returns the fitted + function \param fun function to fit \param h1 histogram to fit \param + mypar pointer to fit parameters array \param emypar pointer to fit + parameter errors \returns the fitted function - can be used e.g. to get + the Chi2 or similar + */ + TF1 *fitFunction(TF1 *fun, TH1 *h1, Double_t *mypar, Double_t *emypar); + TF1 *fitFunctionKb(TF1 *fun, TH1 *h1, Double_t *mypar, Double_t *emypar); + TF1 *fitFunctionKaDoublet(TF1 *fun, TH1 *h1, Double_t *mypar, + Double_t *emypar); #endif #ifdef MYROOT - Double_t fit_min; /**< minimum of the s-curve fitting range, -1 is histogram x-min */ - Double_t fit_max; /**< maximum of the s-curve fitting range, -1 is histogram x-max */ - - Double_t bg_offset; /**< start value for the background pedestal */ - Double_t bg_slope; /**< start value for the background slope */ - Double_t flex; /**< start value for the inflection point */ - Double_t noise; /**< start value for the noise */ - Double_t ampl; /**< start value for the number of photons */ - Double_t cs_slope; /**< start value for the charge sharing slope */ - Double_t kb_mean; - Double_t kb_frac; - Double_t mean2; - Double_t ampl2; + Double_t fit_min; /**< minimum of the s-curve fitting range, -1 is histogram + x-min */ + Double_t fit_max; /**< maximum of the s-curve fitting range, -1 is histogram + x-max */ - TF1 *fscurve; /**< function with which the s-curve will be fitted */ + Double_t bg_offset; /**< start value for the background pedestal */ + Double_t bg_slope; /**< start value for the background slope */ + Double_t flex; /**< start value for the inflection point */ + Double_t noise; /**< start value for the noise */ + Double_t ampl; /**< start value for the number of photons */ + Double_t cs_slope; /**< start value for the charge sharing slope */ + Double_t kb_mean; + Double_t kb_frac; + Double_t mean2; + Double_t ampl2; - TF1 *fspectrum; /**< function with which the spectrum will be fitted */ - TF1 *fspectrumkb; /**< function with which the spectrum will be fitted */ - TF1 *fspectrumkadoublet; /**< function with which the spectrum will be fitted */ + TF1 *fscurve; /**< function with which the s-curve will be fitted */ - TF1 *fspixel; /**< function with which the spectrum will be fitted */ + TF1 *fspectrum; /**< function with which the spectrum will be fitted */ + TF1 *fspectrumkb; /**< function with which the spectrum will be fitted */ + TF1 *fspectrumkadoublet; /**< function with which the spectrum will be + fitted */ + + TF1 *fspixel; /**< function with which the spectrum will be fitted */ #endif - energyCalibrationFunctions *funcs; - int plot_flag; /**< 0 does not plot, >0 plots (flags?) */ - - int cs_flag; /**< 0 functions without charge sharing contribution, >0 with charge sharing contribution */ + energyCalibrationFunctions *funcs; + int plot_flag; /**< 0 does not plot, >0 plots (flags?) */ + int cs_flag; /**< 0 functions without charge sharing contribution, >0 with + charge sharing contribution */ }; #endif - - - - - - - - - - - - - - - - - - - diff --git a/slsDetectorCalibration/ghostSummation.h b/slsDetectorCalibration/ghostSummation.h index e6986ecfe..fa31d966a 100644 --- a/slsDetectorCalibration/ghostSummation.h +++ b/slsDetectorCalibration/ghostSummation.h @@ -3,65 +3,61 @@ #ifndef GHOSTSUMMATION_H #define GHOSTSUMMATION_H -#include #include "slsDetectorData.h" +#include template class ghostSummation { - /** @short virtual calss to handle ghosting*/ + /** @short virtual calss to handle ghosting*/ - public: - - /** constructor - \param xt crosstalk - */ - ghostSummation(slsDetectorData *d, double xt) : xtalk(xt),det(d), nx(1), ny(1) { - if (det) - det->getDetectorSize(nx,ny); - ghost=new double[nx*ny]; - }; + public: + /** constructor + \param xt crosstalk + */ + ghostSummation(slsDetectorData *d, double xt) + : xtalk(xt), det(d), nx(1), ny(1) { + if (det) + det->getDetectorSize(nx, ny); + ghost = new double[nx * ny]; + }; - ghostSummation(ghostSummation *orig) { - xtalk=orig->xtalk; - det=orig->det; - nx=1; - ny=1; - det->getDetectorSize(nx,ny); - ghost=new double[nx*ny]; - - } - virtual ~ghostSummation() {delete [] ghost;}; + ghostSummation(ghostSummation *orig) { + xtalk = orig->xtalk; + det = orig->det; + nx = 1; + ny = 1; + det->getDetectorSize(nx, ny); + ghost = new double[nx * ny]; + } + virtual ~ghostSummation() { delete[] ghost; }; - virtual ghostSummation *Clone() { - return new ghostSummation(this); - } + virtual ghostSummation *Clone() { return new ghostSummation(this); } - double getXTalk(){return xtalk;}; - void setXTalk(double g) {xtalk=g;}; + double getXTalk() { return xtalk; }; + void setXTalk(double g) { xtalk = g; }; - virtual double calcGhost(char *data, int ix, int iy=1){ghost[iy*nx+ix]=0; return 0;}; + virtual double calcGhost(char *data, int ix, int iy = 1) { + ghost[iy * nx + ix] = 0; + return 0; + }; - virtual void calcGhost(char *data){ - for (int iy=0; iy=nx || iy<0 || iy>=ny) return 0; - return ghost[iy*nx+ix]; - } + virtual double getGhost(int ix, int iy) { + if (ix < 0 || ix >= nx || iy < 0 || iy >= ny) + return 0; + return ghost[iy * nx + ix]; + } - protected: + protected: double xtalk; slsDetectorData *det; double *ghost; int nx, ny; - }; - - - - #endif diff --git a/slsDetectorCalibration/interpolatingDetector.h b/slsDetectorCalibration/interpolatingDetector.h index 7053568d9..ed7623a37 100644 --- a/slsDetectorCalibration/interpolatingDetector.h +++ b/slsDetectorCalibration/interpolatingDetector.h @@ -1,8 +1,7 @@ // SPDX-License-Identifier: LGPL-3.0-or-other // Copyright (C) 2021 Contributors to the SLS Detector Package #ifndef INTERPOLATINGDETECTOR_H -#define INTERPOLATINGDETECTOR_H - +#define INTERPOLATINGDETECTOR_H #include "singlePhotonDetector.h" @@ -15,264 +14,255 @@ #endif - #include using namespace std; - class interpolatingDetector : public singlePhotonDetector { - /** @short class to perform pedestal subtraction etc. and find single photon clusters for an analog detector */ + /** @short class to perform pedestal subtraction etc. and find single photon + * clusters for an analog detector */ - public: + public: + /** + + Constructor (no error checking if datasize and offsets are compatible!) + \param d detector data structure to be used + \param csize cluster size (should be an odd number). Defaults to 3 + \param nsigma number of rms to discriminate from the noise. Defaults to 5 + \param sign 1 if photons are positive, -1 if negative + \param cm common mode subtraction algorithm, if any. Defaults to NULL + i.e. none \param nped number of samples for pedestal averaging \param nd + number of dark frames to average as pedestals without photon + discrimination at the beginning of the measurement - /** + */ - Constructor (no error checking if datasize and offsets are compatible!) - \param d detector data structure to be used - \param csize cluster size (should be an odd number). Defaults to 3 - \param nsigma number of rms to discriminate from the noise. Defaults to 5 - \param sign 1 if photons are positive, -1 if negative - \param cm common mode subtraction algorithm, if any. Defaults to NULL i.e. none - \param nped number of samples for pedestal averaging - \param nd number of dark frames to average as pedestals without photon discrimination at the beginning of the measurement + interpolatingDetector(slsDetectorData *d, slsInterpolation *inte, + double nsigma = 5, int sign = 1, + commonModeSubtraction *cm = NULL, int nped = 1000, + int nd = 100, int nnx = -1, int nny = -1, + double *gm = NULL, + ghostSummation *gs = NULL) + : singlePhotonDetector(d, 3, nsigma, sign, cm, nped, nd, nnx, nny, gm, + gs), + interp(inte), id(0) { + // cout << "**"<< xmin << " " << xmax << " " << ymin << " " << ymax << + // endl; + fi = new pthread_mutex_t; + }; + interpolatingDetector(interpolatingDetector *orig) + : singlePhotonDetector(orig) { + // if (orig->interp) + // interp=(orig->interp)->Clone(); + // else - */ - - - interpolatingDetector(slsDetectorData *d, slsInterpolation *inte, - double nsigma=5, - int sign=1, - commonModeSubtraction *cm=NULL, - int nped=1000, - int nd=100, int nnx=-1, int nny=-1, double *gm=NULL, ghostSummation *gs=NULL) : - singlePhotonDetector(d, 3,nsigma,sign, cm, nped, nd, nnx, nny, gm, gs) , interp(inte), id(0) { - //cout << "**"<< xmin << " " << xmax << " " << ymin << " " << ymax << endl; - fi=new pthread_mutex_t ; + interp = orig->interp; -}; - - - - interpolatingDetector(interpolatingDetector *orig) : singlePhotonDetector(orig) { - // if (orig->interp) - // interp=(orig->interp)->Clone(); - // else - - interp=orig->interp; - - id=orig->id; - fi=orig->fi; - } - - - virtual interpolatingDetector *Clone() { - return new interpolatingDetector(this); - } - - virtual int setId(int i) { - id=i; - // interp->setId(id); - return id; - }; - - virtual void prepareInterpolation(int &ok) { - /* cout << "*"<< endl; */ -/* #ifdef SAVE_ALL */ -/* char tit[1000]; */ -/* sprintf(tit,"/scratch/ped_%d.tiff",id); */ -/* writePedestals(tit); */ -/* sprintf(tit,"/scratch/ped_rms_%d.tiff",id); */ -/* writePedestalRMS(tit); */ -/* if (gmap) { */ -/* sprintf(tit,"/scratch/gmap_%d.tiff",id); */ -/* writeGainMap(tit); */ -/* } */ -/* #endif */ - if (interp){ - pthread_mutex_lock(fi); - interp->prepareInterpolation(ok); - pthread_mutex_unlock(fi); + id = orig->id; + fi = orig->fi; } - } + virtual interpolatingDetector *Clone() { + return new interpolatingDetector(this); + } - void clearImage() { - if (interp) { - pthread_mutex_lock(fi); - interp->clearInterpolatedImage(); - pthread_mutex_unlock(fi); - } else - singlePhotonDetector::clearImage(); - }; + virtual int setId(int i) { + id = i; + // interp->setId(id); + return id; + }; - int getImageSize(int &nnx, int &nny, int &nsx, int &nsy) { - if (interp) - return interp->getImageSize(nnx, nny, nsx, nsy); - else - return analogDetector::getImageSize(nnx, nny, nsx, nsy); - }; + virtual void prepareInterpolation(int &ok) { + /* cout << "*"<< endl; */ + /* #ifdef SAVE_ALL */ + /* char tit[1000]; */ + /* sprintf(tit,"/scratch/ped_%d.tiff",id); */ + /* writePedestals(tit); */ + /* sprintf(tit,"/scratch/ped_rms_%d.tiff",id); */ + /* writePedestalRMS(tit); */ + /* if (gmap) { */ + /* sprintf(tit,"/scratch/gmap_%d.tiff",id); */ + /* writeGainMap(tit); */ + /* } */ + /* #endif */ + if (interp) { + pthread_mutex_lock(fi); + interp->prepareInterpolation(ok); + pthread_mutex_unlock(fi); + } + } + void clearImage() { + if (interp) { + pthread_mutex_lock(fi); + interp->clearInterpolatedImage(); + pthread_mutex_unlock(fi); + } else + singlePhotonDetector::clearImage(); + }; - #ifdef MYROOT1 - virtual TH2F *getImage() -#endif -#ifndef MYROOT1 - virtual int *getImage() -#endif - { - // cout << "image " << endl; - if (interp) - return interp->getInterpolatedImage(); - else - return analogDetector::getImage(); - } + int getImageSize(int &nnx, int &nny, int &nsx, int &nsy) { + if (interp) + return interp->getImageSize(nnx, nny, nsx, nsy); + else + return analogDetector::getImageSize(nnx, nny, nsx, nsy); + }; #ifdef MYROOT1 - virtual TH2F *addToInterpolatedImage(char *data, int *val, int &nph) + virtual TH2F *getImage() #endif #ifndef MYROOT1 - virtual int *addToInterpolatedImage(char *data, int *val, int &nph) + virtual int *getImage() #endif - { - nph=addFrame(data,val,0); - if (interp) - return interp->getInterpolatedImage(); - //else - return singlePhotonDetector::getImage(); - //return NULL; - }; - + { + // cout << "image " << endl; + if (interp) + return interp->getInterpolatedImage(); + else + return analogDetector::getImage(); + } #ifdef MYROOT1 - virtual TH2F *addToFlatField(char *data, int *val, int &nph) + virtual TH2F *addToInterpolatedImage(char *data, int *val, int &nph) #endif #ifndef MYROOT1 - virtual int *addToFlatField(char *data, int *val, int &nph) + virtual int *addToInterpolatedImage(char *data, int *val, int &nph) #endif - { - nph=addFrame(data,val,1); - if (interp) - return interp->getFlatField(); - else - return NULL; - }; - - void *writeImage(const char * imgname) { - // cout << id << "=" << imgname<< endl; - if (interp) - interp->writeInterpolatedImage(imgname); - else - analogDetector::writeImage(imgname); - return NULL; - } - - - -int addFrame(char *data, int *ph=NULL, int ff=0) { - - singlePhotonDetector::processData(data,ph); - int nph=0; - - double int_x, int_y; - double eta_x, eta_y; - if (interp) { - // cout << "int" << endl; - pthread_mutex_lock(fi); - for (nph=0; nphaddToFlatField((clusters+nph)->quadTot,(clusters+nph)->quad,(clusters+nph)->get_cluster(),eta_x, eta_y); - } else { - interp->getInterpolatedPosition((clusters+nph)->x, (clusters+nph)->y, (clusters+nph)->quadTot,(clusters+nph)->quad,(clusters+nph)->get_cluster(),int_x, int_y); - interp->addToImage(int_x, int_y); - } - } - pthread_mutex_unlock(fi); - } - return nphFrame; - -}; - - virtual void processData(char *data, int *val=NULL) { - switch (dMode) { - case eAnalog: - // cout << "an" << endl; - analogDetector::processData(data,val); - break; - case ePhotonCounting: - // cout << "spc" << endl; - singlePhotonDetector::processData(data,val); - break; - default: - //cout << "int" << endl; - switch(fMode) { - case ePedestal: - addToPedestal(data); - break; - case eFlat: - if (interp) - addFrame(data,val,1); - else - singlePhotonDetector::processData(data,val); - break; - default: - if (interp) - addFrame(data,val,0); - else - singlePhotonDetector::processData(data,val); - } - } - + { + nph = addFrame(data, val, 0); + if (interp) + return interp->getInterpolatedImage(); + // else + return singlePhotonDetector::getImage(); + // return NULL; }; - - - virtual slsInterpolation *getInterpolation(){ - return interp; +#ifdef MYROOT1 + virtual TH2F *addToFlatField(char *data, int *val, int &nph) +#endif +#ifndef MYROOT1 + virtual int *addToFlatField(char *data, int *val, int &nph) +#endif + { + nph = addFrame(data, val, 1); + if (interp) + return interp->getFlatField(); + else + return NULL; }; - - virtual slsInterpolation *setInterpolation(slsInterpolation *ii){ - // int ok; - interp=ii; - /* pthread_mutex_lock(fi); - if (interp) - interp->prepareInterpolation(ok); - pthread_mutex_unlock(fi); */ - // cout << "det" << endl; - return interp; - }; - - virtual void resetFlatField() { if (interp) { - pthread_mutex_lock(fi); - interp->resetFlatField(); - pthread_mutex_unlock(fi); - } + + void *writeImage(const char *imgname) { + // cout << id << "=" << imgname<< endl; + if (interp) + interp->writeInterpolatedImage(imgname); + else + analogDetector::writeImage(imgname); + return NULL; } - virtual int getNSubPixels(){ if (interp) return interp->getNSubPixels(); else return 1;} + int addFrame(char *data, int *ph = NULL, int ff = 0) { - virtual int setNSubPixels(int ns) { - if (interp) { - pthread_mutex_lock(fi); - interp->getNSubPixels(); - pthread_mutex_unlock(fi); - } - return getNSubPixels(); + singlePhotonDetector::processData(data, ph); + int nph = 0; + + double int_x, int_y; + double eta_x, eta_y; + if (interp) { + // cout << "int" << endl; + pthread_mutex_lock(fi); + for (nph = 0; nph < nphFrame; nph++) { + if (ff) { + interp->addToFlatField( + (clusters + nph)->quadTot, (clusters + nph)->quad, + (clusters + nph)->get_cluster(), eta_x, eta_y); + } else { + interp->getInterpolatedPosition( + (clusters + nph)->x, (clusters + nph)->y, + (clusters + nph)->quadTot, (clusters + nph)->quad, + (clusters + nph)->get_cluster(), int_x, int_y); + interp->addToImage(int_x, int_y); + } + } + pthread_mutex_unlock(fi); + } + return nphFrame; + }; + + virtual void processData(char *data, int *val = NULL) { + switch (dMode) { + case eAnalog: + // cout << "an" << endl; + analogDetector::processData(data, val); + break; + case ePhotonCounting: + // cout << "spc" << endl; + singlePhotonDetector::processData(data, val); + break; + default: + // cout << "int" << endl; + switch (fMode) { + case ePedestal: + addToPedestal(data); + break; + case eFlat: + if (interp) + addFrame(data, val, 1); + else + singlePhotonDetector::processData(data, val); + break; + default: + if (interp) + addFrame(data, val, 0); + else + singlePhotonDetector::processData(data, val); + } + } + }; + + virtual slsInterpolation *getInterpolation() { return interp; }; + + virtual slsInterpolation *setInterpolation(slsInterpolation *ii) { + // int ok; + interp = ii; + /* pthread_mutex_lock(fi); + if (interp) + interp->prepareInterpolation(ok); + pthread_mutex_unlock(fi); */ + // cout << "det" << endl; + return interp; + }; + + virtual void resetFlatField() { + if (interp) { + pthread_mutex_lock(fi); + interp->resetFlatField(); + pthread_mutex_unlock(fi); + } } - protected: - - - slsInterpolation *interp; - int id; - pthread_mutex_t *fi; + virtual int getNSubPixels() { + if (interp) + return interp->getNSubPixels(); + else + return 1; + } + + virtual int setNSubPixels(int ns) { + if (interp) { + pthread_mutex_lock(fi); + interp->getNSubPixels(); + pthread_mutex_unlock(fi); + } + return getNSubPixels(); + } + + protected: + slsInterpolation *interp; + int id; + pthread_mutex_t *fi; }; - - - - #endif diff --git a/slsDetectorCalibration/interpolations/eta2InterpolationBase.h b/slsDetectorCalibration/interpolations/eta2InterpolationBase.h index bfc9685ec..88b61cc02 100644 --- a/slsDetectorCalibration/interpolations/eta2InterpolationBase.h +++ b/slsDetectorCalibration/interpolations/eta2InterpolationBase.h @@ -4,405 +4,378 @@ #define ETA2_INTERPOLATION_BASE_H #ifdef MYROOT1 -#include -#include #include #include +#include +#include #endif #include "etaInterpolationBase.h" class eta2InterpolationBase : public virtual etaInterpolationBase { - - public: - eta2InterpolationBase(int nx=400, int ny=400, int ns=25, int nsy=25, int nb=-1, int nby=-1, double emin=1, double emax=0) : etaInterpolationBase(nx,ny, ns, nsy, nb, nby, emin, emax) { - - /* if (etamin>=etamax) { */ - /* etamin=-1; */ - /* etamax=2; */ - /* // cout << ":" <2 || nSubPixelsY>2) - calcEta(totquad, sDum, etax, etay); - getInterpolatedPosition(x,y,etax,etay,corner,int_x,int_y); + public: + eta2InterpolationBase(int nx = 400, int ny = 400, int ns = 25, int nsy = 25, + int nb = -1, int nby = -1, double emin = 1, + double emax = 0) + : etaInterpolationBase(nx, ny, ns, nsy, nb, nby, emin, emax){ - return; - }; - + /* if (etamin>=etamax) { */ + /* etamin=-1; */ + /* etamax=2; */ + /* // cout << ":" <2 || nSubPixelsY>2 ) - calcEta(totquad, sDum, etax, etay); - getInterpolatedPosition(x,y,etax,etay,corner,int_x,int_y); + }; - return; - }; - + eta2InterpolationBase(eta2InterpolationBase *orig) + : etaInterpolationBase(orig){}; + ////////////////////////////////////////////////////////////////////////////// + //////////// /*It return position hit for the event in input */ + ///////////////// + virtual void getInterpolatedPosition(int x, int y, int *data, double &int_x, + double &int_y) { + double sDum[2][2]; + double tot, totquad; + double etax = 0, etay = 0; + int corner; + corner = calcQuad(data, tot, totquad, sDum); + if (nSubPixelsX > 2 || nSubPixelsY > 2) + calcEta(totquad, sDum, etax, etay); + getInterpolatedPosition(x, y, etax, etay, corner, int_x, int_y); - - - - - - virtual void getInterpolatedPosition(int x, int y, double totquad,int quad,double *cl,double &int_x, double &int_y) { - - double cc[2][2]; - int xoff=0, yoff=0; - switch (quad) { - case BOTTOM_LEFT: - xoff=0; - yoff=0; - break; - case BOTTOM_RIGHT: - xoff=1; - yoff=0; - break; - case TOP_LEFT: - xoff=0; - yoff=1; - break; - case TOP_RIGHT: - xoff=1; - yoff=1; - break; - default: - ; - } - double etax=0, etay=0; - if (nSubPixelsX>2 || nSubPixelsY>2) { - cc[0][0]=cl[xoff+3*yoff]; - cc[1][0]=cl[xoff+3*(yoff+1)]; - cc[0][1]=cl[xoff+1+3*yoff]; - cc[1][1]=cl[xoff+1+3*(yoff+1)]; - calcEta(totquad,cc,etax,etay); - } - - return getInterpolatedPosition(x,y,etax, etay,quad,int_x,int_y); - - } - - - - virtual void getInterpolatedPosition(int x, int y, double totquad,int quad,int *cl,double &int_x, double &int_y) { - - double cc[2][2]; - int xoff=0, yoff=0; - - switch (quad) { - case BOTTOM_LEFT: - xoff=0; - yoff=0; - break; - case BOTTOM_RIGHT: - xoff=1; - yoff=0; - break; - case TOP_LEFT: - xoff=0; - yoff=1; - break; - case TOP_RIGHT: - xoff=1; - yoff=1; - break; - default: - ; - } - double etax=0, etay=0; - if (nSubPixelsX>2 || nSubPixelsY>2) { - cc[0][0]=cl[xoff+3*yoff]; - cc[1][0]=cl[xoff+3*(yoff+1)]; - cc[0][1]=cl[xoff+1+3*yoff]; - cc[1][1]=cl[xoff+1+3*(xoff+1)]; - calcEta(totquad,cc,etax,etay); - } - return getInterpolatedPosition(x,y,etax, etay,quad,int_x,int_y); - - } - - - - - - - virtual void getInterpolatedPosition(int x, int y, double etax, double etay, int corner, double &int_x, double &int_y) - { - - - double xpos_eta=0,ypos_eta=0; - double dX,dY; - int ex,ey; - switch (corner) - { - case TOP_LEFT: - dX=-1.; - dY=0; - break; - case TOP_RIGHT: - ; - dX=0; - dY=0; - break; - case BOTTOM_LEFT: - dX=-1.; - dY=-1.; - break; - case BOTTOM_RIGHT: - dX=0; - dY=-1.; - break; - default: - cout << "bad quadrant" << endl; - dX=0.; - dY=0.; - } - - - if (nSubPixelsX>2 || nSubPixelsY>2 ) { - - ex=(etax-etamin)/etastepX; - ey=(etay-etamin)/etastepY; - if (ex<0) { - cout << "x*"<< ex << endl; - ex=0; - } - if (ex>=nbetaX) { - cout << "x?"<< ex << endl; - ex=nbetaX-1; - } - if (ey<0) { - cout << "y*"<< ey << " " << nbetaY << endl; - ey=0; - } - if (ey>=nbetaY) { - cout << "y?"<< ey << " " << nbetaY << endl; - ey=nbetaY-1; - } - - - - xpos_eta=(((double)hhx[(ey*nbetaX+ex)]))+dX ;///((double)nSubPixels); - ypos_eta=(((double)hhy[(ey*nbetaX+ex)]))+dY ;///((double)nSubPixels); - - } else { - xpos_eta=0.5*dX+0.25; - ypos_eta=0.5*dY+0.25; - } - - int_x=((double)x) + xpos_eta+0.5; - int_y=((double)y) + ypos_eta+0.5; - - - } - - - - virtual int addToFlatField(double totquad,int quad,int *cl,double &etax, double &etay) { - double cc[2][2]; - int xoff=0, yoff=0; - - switch (quad) { - case BOTTOM_LEFT: - xoff=0; - yoff=0; - break; - case BOTTOM_RIGHT: - xoff=1; - yoff=0; - break; - case TOP_LEFT: - xoff=0; - yoff=1; - break; - case TOP_RIGHT: - xoff=1; - yoff=1; - break; - default: - ; - } - cc[0][0]=cl[xoff+3*yoff]; - cc[1][0]=cl[xoff+3*(yoff+1)]; - cc[0][1]=cl[xoff+1+3*yoff]; - cc[1][1]=cl[xoff+1+3*(yoff+1)]; - - //calcMyEta(totquad,quad,cl,etax, etay); - calcEta(totquad, cc,etax, etay); - - // cout <<"******"<< etax << " " << etay << endl; - - - return addToFlatField(etax,etay); - } - - virtual int addToFlatField(double totquad,int quad,double *cl,double &etax, double &etay) { - double cc[2][2]; - int xoff=0, yoff=0; - - switch (quad) { - case BOTTOM_LEFT: - xoff=0; - yoff=0; - break; - case BOTTOM_RIGHT: - xoff=1; - yoff=0; - break; - case TOP_LEFT: - xoff=0; - yoff=1; - break; - case TOP_RIGHT: - xoff=1; - yoff=1; - break; - default: - ; - } - cc[0][0]=cl[xoff+3*yoff]; - cc[1][0]=cl[(yoff+1)*3+xoff]; - cc[0][1]=cl[yoff*3+xoff+1]; - cc[1][1]=cl[(yoff+1)*3+xoff+1]; - - /* cout << cl[0] << " " << cl[1] << " " << cl[2] << endl; */ - /* cout << cl[3] << " " << cl[4] << " " << cl[5] << endl; */ - /* cout << cl[6] << " " << cl[7] << " " << cl[8] << endl; */ - /* cout <<"******"< 2 || nSubPixelsY > 2) + calcEta(totquad, sDum, etax, etay); + getInterpolatedPosition(x, y, etax, etay, corner, int_x, int_y); + + return; }; + virtual void getInterpolatedPosition(int x, int y, double totquad, int quad, + double *cl, double &int_x, + double &int_y) { - virtual int addToFlatField(double etax, double etay){ + double cc[2][2]; + int xoff = 0, yoff = 0; + switch (quad) { + case BOTTOM_LEFT: + xoff = 0; + yoff = 0; + break; + case BOTTOM_RIGHT: + xoff = 1; + yoff = 0; + break; + case TOP_LEFT: + xoff = 0; + yoff = 1; + break; + case TOP_RIGHT: + xoff = 1; + yoff = 1; + break; + default:; + } + double etax = 0, etay = 0; + if (nSubPixelsX > 2 || nSubPixelsY > 2) { + cc[0][0] = cl[xoff + 3 * yoff]; + cc[1][0] = cl[xoff + 3 * (yoff + 1)]; + cc[0][1] = cl[xoff + 1 + 3 * yoff]; + cc[1][1] = cl[xoff + 1 + 3 * (yoff + 1)]; + calcEta(totquad, cc, etax, etay); + } + + return getInterpolatedPosition(x, y, etax, etay, quad, int_x, int_y); + } + + virtual void getInterpolatedPosition(int x, int y, double totquad, int quad, + int *cl, double &int_x, + double &int_y) { + + double cc[2][2]; + int xoff = 0, yoff = 0; + + switch (quad) { + case BOTTOM_LEFT: + xoff = 0; + yoff = 0; + break; + case BOTTOM_RIGHT: + xoff = 1; + yoff = 0; + break; + case TOP_LEFT: + xoff = 0; + yoff = 1; + break; + case TOP_RIGHT: + xoff = 1; + yoff = 1; + break; + default:; + } + double etax = 0, etay = 0; + if (nSubPixelsX > 2 || nSubPixelsY > 2) { + cc[0][0] = cl[xoff + 3 * yoff]; + cc[1][0] = cl[xoff + 3 * (yoff + 1)]; + cc[0][1] = cl[xoff + 1 + 3 * yoff]; + cc[1][1] = cl[xoff + 1 + 3 * (xoff + 1)]; + calcEta(totquad, cc, etax, etay); + } + return getInterpolatedPosition(x, y, etax, etay, quad, int_x, int_y); + } + + virtual void getInterpolatedPosition(int x, int y, double etax, double etay, + int corner, double &int_x, + double &int_y) { + + double xpos_eta = 0, ypos_eta = 0; + double dX, dY; + int ex, ey; + switch (corner) { + case TOP_LEFT: + dX = -1.; + dY = 0; + break; + case TOP_RIGHT:; + dX = 0; + dY = 0; + break; + case BOTTOM_LEFT: + dX = -1.; + dY = -1.; + break; + case BOTTOM_RIGHT: + dX = 0; + dY = -1.; + break; + default: + cout << "bad quadrant" << endl; + dX = 0.; + dY = 0.; + } + + if (nSubPixelsX > 2 || nSubPixelsY > 2) { + + ex = (etax - etamin) / etastepX; + ey = (etay - etamin) / etastepY; + if (ex < 0) { + cout << "x*" << ex << endl; + ex = 0; + } + if (ex >= nbetaX) { + cout << "x?" << ex << endl; + ex = nbetaX - 1; + } + if (ey < 0) { + cout << "y*" << ey << " " << nbetaY << endl; + ey = 0; + } + if (ey >= nbetaY) { + cout << "y?" << ey << " " << nbetaY << endl; + ey = nbetaY - 1; + } + + xpos_eta = (((double)hhx[(ey * nbetaX + ex)])) + + dX; ///((double)nSubPixels); + ypos_eta = (((double)hhy[(ey * nbetaX + ex)])) + + dY; ///((double)nSubPixels); + + } else { + xpos_eta = 0.5 * dX + 0.25; + ypos_eta = 0.5 * dY + 0.25; + } + + int_x = ((double)x) + xpos_eta + 0.5; + int_y = ((double)y) + ypos_eta + 0.5; + } + + virtual int addToFlatField(double totquad, int quad, int *cl, double &etax, + double &etay) { + double cc[2][2]; + int xoff = 0, yoff = 0; + + switch (quad) { + case BOTTOM_LEFT: + xoff = 0; + yoff = 0; + break; + case BOTTOM_RIGHT: + xoff = 1; + yoff = 0; + break; + case TOP_LEFT: + xoff = 0; + yoff = 1; + break; + case TOP_RIGHT: + xoff = 1; + yoff = 1; + break; + default:; + } + cc[0][0] = cl[xoff + 3 * yoff]; + cc[1][0] = cl[xoff + 3 * (yoff + 1)]; + cc[0][1] = cl[xoff + 1 + 3 * yoff]; + cc[1][1] = cl[xoff + 1 + 3 * (yoff + 1)]; + + // calcMyEta(totquad,quad,cl,etax, etay); + calcEta(totquad, cc, etax, etay); + + // cout <<"******"<< etax << " " << etay << endl; + + return addToFlatField(etax, etay); + } + + virtual int addToFlatField(double totquad, int quad, double *cl, + double &etax, double &etay) { + double cc[2][2]; + int xoff = 0, yoff = 0; + + switch (quad) { + case BOTTOM_LEFT: + xoff = 0; + yoff = 0; + break; + case BOTTOM_RIGHT: + xoff = 1; + yoff = 0; + break; + case TOP_LEFT: + xoff = 0; + yoff = 1; + break; + case TOP_RIGHT: + xoff = 1; + yoff = 1; + break; + default:; + } + cc[0][0] = cl[xoff + 3 * yoff]; + cc[1][0] = cl[(yoff + 1) * 3 + xoff]; + cc[0][1] = cl[yoff * 3 + xoff + 1]; + cc[1][1] = cl[(yoff + 1) * 3 + xoff + 1]; + + /* cout << cl[0] << " " << cl[1] << " " << cl[2] << endl; */ + /* cout << cl[3] << " " << cl[4] << " " << cl[5] << endl; */ + /* cout << cl[6] << " " << cl[7] << " " << cl[8] << endl; */ + /* cout <<"******"<Fill(etax,etay); + heta->Fill(etax, etay); #endif #ifndef MYROOT1 - int ex,ey; - ex=(etax-etamin)/etastepX; - ey=(etay-etamin)/etastepY; - if (ey=0 && ey>=0) - heta[ey*nbetaX+ex]++; + int ex, ey; + ex = (etax - etamin) / etastepX; + ey = (etay - etamin) / etastepY; + if (ey < nbetaY && ex < nbetaX && ex >= 0 && ey >= 0) + heta[ey * nbetaX + ex]++; #endif - return 0; - }; + return 0; + }; - virtual int *getInterpolatedImage(){ - int ipx, ipy; - // cout << "ff" << endl; - calcDiff(1, hhx, hhy); //get flat - double avg=0; - for (ipx=0; ipx0) - hintcorr[ibx+iby*nSubPixelsX*nPixelsX]=hint[ibx+iby*nSubPixelsX*nPixelsX]*(avg/flat[ipx+ipy*nSubPixelsX]); - else - hintcorr[ibx+iby*nSubPixelsX*nPixelsX]=hint[ibx+iby*nSubPixelsX*nPixelsX]; + for (int ibx = 0; ibx < nSubPixelsX * nPixelsX; ibx++) { + ipx = ibx % nSubPixelsX - nSubPixelsX / 2; + if (ipx < 0) + ipx = nSubPixelsX + ipx; + for (int iby = 0; iby < nSubPixelsY * nPixelsY; iby++) { + ipy = iby % nSubPixelsY - nSubPixelsY / 2; + if (ipy < 0) + ipy = nSubPixelsY + ipy; + // cout << ipx << " " << ipy << " " << ibx << " " << iby << + // endl; + if (flat[ipx + ipy * nSubPixelsX] > 0) + hintcorr[ibx + iby * nSubPixelsX * nPixelsX] = + hint[ibx + iby * nSubPixelsX * nPixelsX] * + (avg / flat[ipx + ipy * nSubPixelsX]); + else + hintcorr[ibx + iby * nSubPixelsX * nPixelsX] = + hint[ibx + iby * nSubPixelsX * nPixelsX]; + } + } + return hintcorr; + }; - } - } - - - - return hintcorr; - }; - -/* protected: */ - -/* #ifdef MYROOT1 */ -/* TH2D *heta; */ -/* TH2D *hhx; */ -/* TH2D *hhy; */ -/* #endif */ -/* #ifndef MYROOT1 */ -/* int *heta; */ -/* float *hhx; */ -/* float *hhy; */ -/* #endif */ -/* int nbeta; */ -/* double etamin, etamax, etastep; */ + /* protected: */ + /* #ifdef MYROOT1 */ + /* TH2D *heta; */ + /* TH2D *hhx; */ + /* TH2D *hhy; */ + /* #endif */ + /* #ifndef MYROOT1 */ + /* int *heta; */ + /* float *hhx; */ + /* float *hhy; */ + /* #endif */ + /* int nbeta; */ + /* double etamin, etamax, etastep; */ }; #endif diff --git a/slsDetectorCalibration/interpolations/eta3InterpolationBase.h b/slsDetectorCalibration/interpolations/eta3InterpolationBase.h index 233a11358..3b1eabab6 100644 --- a/slsDetectorCalibration/interpolations/eta3InterpolationBase.h +++ b/slsDetectorCalibration/interpolations/eta3InterpolationBase.h @@ -4,270 +4,260 @@ #define ETA3_INTERPOLATION_BASE_H #ifdef MYROOT1 -#include -#include #include #include +#include +#include #endif #include "etaInterpolationBase.h" -class eta3InterpolationBase : public virtual etaInterpolationBase { - - public: - eta3InterpolationBase(int nx=400, int ny=400, int ns=25, int nsy=25, int nb=-1, int nby=-1, double emin=1, double emax=0) : etaInterpolationBase(nx, ny, ns, nsy, nb, nby, emin, emax) { - // cout << "e3ib " << nb << " " << emin << " " << emax << endl; - /* if (nbeta<=0) { */ - /* nbeta=nSubPixels*10; */ - /* } */ - - // cout << nbeta << " " << etamin << " " << etamax << endl; -}; - - eta3InterpolationBase(eta3InterpolationBase *orig): etaInterpolationBase(orig){ }; +class eta3InterpolationBase : public virtual etaInterpolationBase { - /* virtual eta3InterpolationBase* Clone()=0; */ - - + public: + eta3InterpolationBase(int nx = 400, int ny = 400, int ns = 25, int nsy = 25, + int nb = -1, int nby = -1, double emin = 1, + double emax = 0) + : etaInterpolationBase(nx, ny, ns, nsy, nb, nby, emin, emax){ + // cout << "e3ib " << nb << " " << emin << " " << emax << endl; + /* if (nbeta<=0) { */ + /* nbeta=nSubPixels*10; */ + /* } */ - - // virtual void prepareInterpolation(int &ok){}; - + // cout << nbeta << " " << etamin << " " << etamax << endl; + }; - ////////////////////////////////////////////////////////////////////////////// - //////////// /*It return position hit for the event in input */ ////////////// - virtual void getInterpolatedPosition(int x, int y, int *data, double &int_x, double &int_y) - { - double tot; - double etax,etay; - - int corner=calcEta3(data,etax,etay, tot); - - getInterpolatedPosition(x,y,etax,etay,corner,int_x,int_y); + eta3InterpolationBase(eta3InterpolationBase *orig) + : etaInterpolationBase(orig){}; - return; - }; - + /* virtual eta3InterpolationBase* Clone()=0; */ - virtual void getInterpolatedPosition(int x, int y, double *data, double &int_x, double &int_y) - { - //double sDum[2][2]; - double tot; - double etax,etay; - - int corner=calcEta3(data,etax,etay, tot); - - getInterpolatedPosition(x,y,etax,etay,corner,int_x,int_y); + // virtual void prepareInterpolation(int &ok){}; - return; - }; - + ////////////////////////////////////////////////////////////////////////////// + //////////// /*It return position hit for the event in input */ + ///////////////// + virtual void getInterpolatedPosition(int x, int y, int *data, double &int_x, + double &int_y) { + double tot; + double etax, etay; - virtual void getInterpolatedPosition(int x, int y, double totquad,int quad,double *cl,double &int_x, double &int_y) { - - - double etax, etay; - if (nSubPixelsX>2 || nSubPixelsY>2 ) { - calcEta3(cl,etax,etay, totquad); - } - return getInterpolatedPosition(x,y,etax, etay,quad,int_x,int_y); + int corner = calcEta3(data, etax, etay, tot); - } - - - - virtual void getInterpolatedPosition(int x, int y, double totquad,int quad,int *cl,double &int_x, double &int_y) { - - - double etax, etay; - if (nSubPixelsX>2 || nSubPixelsY>2 ) { - calcEta3(cl,etax,etay, totquad); - } - return getInterpolatedPosition(x,y,etax, etay,quad,int_x,int_y); - - } - - - - virtual void getInterpolatedPosition(int x, int y, double etax, double etay, int corner, double &int_x, double &int_y) - { - - - double xpos_eta=0,ypos_eta=0; - int ex,ey; - - if (nSubPixelsX>2 || nSubPixelsY>2 ) { - -#ifdef MYROOT1 - xpos_eta=(hhx->GetBinContent(hhx->GetXaxis()->FindBin(etax),hhy->GetYaxis()->FindBin(etay)))/((double)nSubPixelsX); - ypos_eta=(hhy->GetBinContent(hhx->GetXaxis()->FindBin(etax),hhy->GetYaxis()->FindBin(etay)))/((double)nSubPixelsY); -#endif -#ifndef MYROOT1 - ex=(etax-etamin)/etastepX; - ey=(etay-etamin)/etastepY; - if (ex<0) { - /* cout << etax << " " << etamin << " "; */ - /* cout << "3x*"<< ex << endl; */ - ex=0; - } - if (ex>=nbetaX) { - /* cout << etax << " " << etamin << " "; */ - /* cout << "3x?"<< ex << endl; */ - ex=nbetaX-1; - } - if (ey<0) { - /* cout << etay << " " << etamin << " "; */ - /* cout << "3y*"<< ey << endl; */ - ey=0; - } - if (ey>=nbetaY) { - /* cout << etay << " " << etamin << " "; */ - /* cout << "3y?"<< ey << endl; */ - ey=nbetaY-1; - - } - xpos_eta=(((double)hhx[(ey*nbetaX+ex)]));///((double)nSubPixels); - ypos_eta=(((double)hhy[(ey*nbetaX+ex)]));///((double)nSubPixels); - -#endif - - } else { - switch (corner) { - case BOTTOM_LEFT: - xpos_eta=-0.25; - ypos_eta=-0.25; - break; - case BOTTOM_RIGHT: - xpos_eta=0.25; - ypos_eta=-0.25; - break; - case TOP_LEFT: - xpos_eta=-0.25; - ypos_eta=0.25; - break; - case TOP_RIGHT: - xpos_eta=0.25; - ypos_eta=0.25; - break; - default: - xpos_eta=0; - ypos_eta=0; - } - - } - int_x=((double)x) + xpos_eta; - int_y=((double)y) + ypos_eta; - // int_x=5. + xpos_eta; - // int_y=5. + ypos_eta; - - - } - - - - - - -/* ///////////////////////////////////////////////////////////////////////////////////////////////// */ -/* virtual void getPositionETA3(int x, int y, double *data, double &int_x, double &int_y) */ -/* { */ -/* double sDum[2][2]; */ -/* double tot, totquad; */ -/* double eta3x,eta3y; */ -/* double ex,ey; */ - -/* calcQuad(data, tot, totquad, sDum); */ -/* calcEta3(data,eta3x, eta3y,tot); */ - -/* double xpos_eta,ypos_eta; */ - -/* #ifdef MYROOT1 */ -/* xpos_eta=((hhx->GetBinContent(hhx->GetXaxis()->FindBin(eta3x),hhy->GetYaxis()->FindBin(eta3y))))/((double)nSubPixels); */ -/* ypos_eta=((hhy->GetBinContent(hhx->GetXaxis()->FindBin(eta3x),hhy->GetYaxis()->FindBin(eta3y))))/((double)nSubPixels); */ - -/* #endif */ -/* #ifndef MYROOT1 */ -/* ex=(eta3x-etamin)/etastep; */ -/* ey=(eta3y-etamin)/etastep; */ - -/* if (ex<0) ex=0; */ -/* if (ex>=nbeta) ex=nbeta-1; */ -/* if (ey<0) ey=0; */ -/* if (ey>=nbeta) ey=nbeta-1; */ - -/* xpos_eta=(((double)hhx[(int)(ey*nbeta+ex)]))/((double)nSubPixels); */ -/* ypos_eta=(((double)hhy[(int)(ey*nbeta+ex)]))/((double)nSubPixels); */ -/* #endif */ - -/* int_x=((double)x) + xpos_eta; */ -/* int_y=((double)y) + ypos_eta; */ - -/* return; */ -/* }; */ - - virtual int addToFlatField(double totquad,int quad,int *cl,double &etax, double &etay) { - - calcEta3(cl, etax, etay, totquad); - return addToFlatField(etax,etay); - } - - virtual int addToFlatField(double totquad,int quad,double *cl,double &etax, double &etay) { - - - calcEta3(cl, etax, etay, totquad); - return addToFlatField(etax,etay); - } - - - - ////////////////////////////////////////////////////////////////////////////////////// - virtual int addToFlatField(double *cluster, double &etax, double &etay){ - double totquad; - calcEta3(cluster, etax, etay, totquad); - return addToFlatField(etax,etay); + getInterpolatedPosition(x, y, etax, etay, corner, int_x, int_y); + return; }; - virtual int addToFlatField(int *cluster, double &etax, double &etay){ - - double totquad; - - calcEta3(cluster, etax, etay, totquad); - return addToFlatField(etax,etay); + virtual void getInterpolatedPosition(int x, int y, double *data, + double &int_x, double &int_y) { + // double sDum[2][2]; + double tot; + double etax, etay; + int corner = calcEta3(data, etax, etay, tot); + + getInterpolatedPosition(x, y, etax, etay, corner, int_x, int_y); + + return; }; + virtual void getInterpolatedPosition(int x, int y, double totquad, int quad, + double *cl, double &int_x, + double &int_y) { + + double etax, etay; + if (nSubPixelsX > 2 || nSubPixelsY > 2) { + calcEta3(cl, etax, etay, totquad); + } + return getInterpolatedPosition(x, y, etax, etay, quad, int_x, int_y); + } + + virtual void getInterpolatedPosition(int x, int y, double totquad, int quad, + int *cl, double &int_x, + double &int_y) { + + double etax, etay; + if (nSubPixelsX > 2 || nSubPixelsY > 2) { + calcEta3(cl, etax, etay, totquad); + } + return getInterpolatedPosition(x, y, etax, etay, quad, int_x, int_y); + } + + virtual void getInterpolatedPosition(int x, int y, double etax, double etay, + int corner, double &int_x, + double &int_y) { + + double xpos_eta = 0, ypos_eta = 0; + int ex, ey; + + if (nSubPixelsX > 2 || nSubPixelsY > 2) { - virtual int addToFlatField(double etax, double etay){ #ifdef MYROOT1 - heta->Fill(etax,etay); + xpos_eta = (hhx->GetBinContent(hhx->GetXaxis()->FindBin(etax), + hhy->GetYaxis()->FindBin(etay))) / + ((double)nSubPixelsX); + ypos_eta = (hhy->GetBinContent(hhx->GetXaxis()->FindBin(etax), + hhy->GetYaxis()->FindBin(etay))) / + ((double)nSubPixelsY); #endif #ifndef MYROOT1 - int ex,ey; - ex=(etax-etamin)/etastepX; - ey=(etay-etamin)/etastepY; - if (ey=0 && ey>=0) - heta[ey*nbetaX+ex]++; -#endif - return 0; - }; - - -/* protected: */ - -/* #ifdef MYROOT1 */ -/* TH2D *heta; */ -/* TH2D *hhx; */ -/* TH2D *hhy; */ -/* #endif */ -/* #ifndef MYROOT1 */ -/* int *heta; */ -/* float *hhx; */ -/* float *hhy; */ -/* #endif */ -/* int nbeta; */ -/* double etamin, etamax, etastep; */ + ex = (etax - etamin) / etastepX; + ey = (etay - etamin) / etastepY; + if (ex < 0) { + /* cout << etax << " " << etamin << " "; */ + /* cout << "3x*"<< ex << endl; */ + ex = 0; + } + if (ex >= nbetaX) { + /* cout << etax << " " << etamin << " "; */ + /* cout << "3x?"<< ex << endl; */ + ex = nbetaX - 1; + } + if (ey < 0) { + /* cout << etay << " " << etamin << " "; */ + /* cout << "3y*"<< ey << endl; */ + ey = 0; + } + if (ey >= nbetaY) { + /* cout << etay << " " << etamin << " "; */ + /* cout << "3y?"<< ey << endl; */ + ey = nbetaY - 1; + } + xpos_eta = + (((double)hhx[(ey * nbetaX + ex)])); ///((double)nSubPixels); + ypos_eta = + (((double)hhy[(ey * nbetaX + ex)])); ///((double)nSubPixels); +#endif + + } else { + switch (corner) { + case BOTTOM_LEFT: + xpos_eta = -0.25; + ypos_eta = -0.25; + break; + case BOTTOM_RIGHT: + xpos_eta = 0.25; + ypos_eta = -0.25; + break; + case TOP_LEFT: + xpos_eta = -0.25; + ypos_eta = 0.25; + break; + case TOP_RIGHT: + xpos_eta = 0.25; + ypos_eta = 0.25; + break; + default: + xpos_eta = 0; + ypos_eta = 0; + } + } + int_x = ((double)x) + xpos_eta; + int_y = ((double)y) + ypos_eta; + // int_x=5. + xpos_eta; + // int_y=5. + ypos_eta; + } + + /* ///////////////////////////////////////////////////////////////////////////////////////////////// + */ + /* virtual void getPositionETA3(int x, int y, double *data, double + * &int_x, double &int_y) */ + /* { */ + /* double sDum[2][2]; */ + /* double tot, totquad; */ + /* double eta3x,eta3y; */ + /* double ex,ey; */ + + /* calcQuad(data, tot, totquad, sDum); */ + /* calcEta3(data,eta3x, eta3y,tot); */ + + /* double xpos_eta,ypos_eta; */ + + /* #ifdef MYROOT1 */ + /* xpos_eta=((hhx->GetBinContent(hhx->GetXaxis()->FindBin(eta3x),hhy->GetYaxis()->FindBin(eta3y))))/((double)nSubPixels); + */ + /* ypos_eta=((hhy->GetBinContent(hhx->GetXaxis()->FindBin(eta3x),hhy->GetYaxis()->FindBin(eta3y))))/((double)nSubPixels); + */ + + /* #endif */ + /* #ifndef MYROOT1 */ + /* ex=(eta3x-etamin)/etastep; */ + /* ey=(eta3y-etamin)/etastep; */ + + /* if (ex<0) ex=0; */ + /* if (ex>=nbeta) ex=nbeta-1; */ + /* if (ey<0) ey=0; */ + /* if (ey>=nbeta) ey=nbeta-1; */ + + /* xpos_eta=(((double)hhx[(int)(ey*nbeta+ex)]))/((double)nSubPixels); */ + /* ypos_eta=(((double)hhy[(int)(ey*nbeta+ex)]))/((double)nSubPixels); */ + /* #endif */ + + /* int_x=((double)x) + xpos_eta; */ + /* int_y=((double)y) + ypos_eta; */ + + /* return; */ + /* }; */ + + virtual int addToFlatField(double totquad, int quad, int *cl, double &etax, + double &etay) { + + calcEta3(cl, etax, etay, totquad); + return addToFlatField(etax, etay); + } + + virtual int addToFlatField(double totquad, int quad, double *cl, + double &etax, double &etay) { + + calcEta3(cl, etax, etay, totquad); + return addToFlatField(etax, etay); + } + + ////////////////////////////////////////////////////////////////////////////////////// + virtual int addToFlatField(double *cluster, double &etax, double &etay) { + double totquad; + calcEta3(cluster, etax, etay, totquad); + return addToFlatField(etax, etay); + }; + + virtual int addToFlatField(int *cluster, double &etax, double &etay) { + + double totquad; + + calcEta3(cluster, etax, etay, totquad); + return addToFlatField(etax, etay); + }; + + virtual int addToFlatField(double etax, double etay) { +#ifdef MYROOT1 + heta->Fill(etax, etay); +#endif +#ifndef MYROOT1 + int ex, ey; + ex = (etax - etamin) / etastepX; + ey = (etay - etamin) / etastepY; + if (ey < nbetaY && ex < nbetaX && ex >= 0 && ey >= 0) + heta[ey * nbetaX + ex]++; +#endif + return 0; + }; + + /* protected: */ + + /* #ifdef MYROOT1 */ + /* TH2D *heta; */ + /* TH2D *hhx; */ + /* TH2D *hhy; */ + /* #endif */ + /* #ifndef MYROOT1 */ + /* int *heta; */ + /* float *hhx; */ + /* float *hhy; */ + /* #endif */ + /* int nbeta; */ + /* double etamin, etamax, etastep; */ }; #endif diff --git a/slsDetectorCalibration/interpolations/etaInterpolationAdaptiveBins.h b/slsDetectorCalibration/interpolations/etaInterpolationAdaptiveBins.h index e453d566d..4c477c937 100644 --- a/slsDetectorCalibration/interpolations/etaInterpolationAdaptiveBins.h +++ b/slsDetectorCalibration/interpolations/etaInterpolationAdaptiveBins.h @@ -3,285 +3,316 @@ #ifndef ETA_INTERPOLATION_ADAPTIVEBINS_H #define ETA_INTERPOLATION_ADAPTIVEBINS_H -#include #include "tiffIO.h" +#include //#include "etaInterpolationBase.h" #include "etaInterpolationPosXY.h" - - class etaInterpolationAdaptiveBins : public etaInterpolationPosXY { - // protected: + // protected: + private: + virtual void iterate(float *newhhx, float *newhhy) { - private: + double bsize = 1. / nSubPixels; - virtual void iterate(float *newhhx, float *newhhy) { + double hy[nSubPixels][nbeta]; // profile y + double hx[nSubPixels][nbeta]; // profile x + double hix[nSubPixels][nbeta]; // integral of projection x + double hiy[nSubPixels][nbeta]; // integral of projection y + int ipy, ipx; + double tot_eta_x[nSubPixels]; + double tot_eta_y[nSubPixels]; + // for (int ipy=0; ipy=nSubPixels) ipy=nSubPixels-1; - hx[ipy][ibx]+=heta[ibx+iby*nbeta]; + // cout << ipy << " " << ((ipy)*bsize) << " " << ((ipy+1)*bsize) << + // endl; + for (int ibx = 0; ibx < nbeta; ibx++) { + for (int iby = 0; iby < nbeta; iby++) { + ipy = hhy[ibx + iby * nbeta] * nSubPixels; + if (ipy < 0) + ipy = 0; + if (ipy >= nSubPixels) + ipy = nSubPixels - 1; + hx[ipy][ibx] += heta[ibx + iby * nbeta]; + ipx = hhx[ibx + iby * nbeta] * nSubPixels; + if (ipx < 0) + ipx = 0; + if (ipx >= nSubPixels) + ipx = nSubPixels - 1; + hy[ipx][iby] += heta[ibx + iby * nbeta]; + } + } - ipx=hhx[ibx+iby*nbeta]*nSubPixels; - if (ipx<0) ipx=0; - if (ipx>=nSubPixels) ipx=nSubPixels-1; - hy[ipx][iby]+=heta[ibx+iby*nbeta]; - } - } - - - - for (ipy=0; ipy=((ipy)*bsize) && hhy[ibx+iby*nbeta]<=((ipy+1)*bsize)) { - ipy=hhy[ibx+iby*nbeta]*nSubPixels; + for (ipy = 0; ipy < nSubPixels; ipy++) { + hix[ipy][0] = hx[ipy][0]; + hiy[ipy][0] = hy[ipy][0]; + for (int ib = 1; ib < nbeta; ib++) { + hix[ipy][ib] = hix[ipy][ib - 1] + hx[ipy][ib]; + hiy[ipy][ib] = hiy[ipy][ib - 1] + hy[ipy][ib]; + } + tot_eta_x[ipy] = hix[ipy][nbeta - 1] + 1; + tot_eta_y[ipy] = hiy[ipy][nbeta - 1] + 1; + // cout << ipy << " " << tot_eta_x[ipy] << " " << tot_eta_y[ipy] << + // endl; + } + // for (int ipy=0; ipy=nSubPixels) ipy=nSubPixels-1; + for (int ibx = 0; ibx < nbeta; ibx++) { + for (int iby = 0; iby < nbeta; iby++) { - if (ipy>=0 && ipy0) - newhhx[ibx+iby*nbeta]=hix[ipy][ibx]/(tot_eta_x[ipy]); - else - cout << "Bad tot_etax " << ipy << " " << tot_eta_x[ipy] << endl; - else - cout << "** Bad value ipy " << ibx << " " << iby << " "<< ipy << " " << hhy[ibx+iby*nbeta]*nSubPixels << endl; - // if (newhhx[ibx+iby*nbeta]>=1 || newhhx[ibx+iby*nbeta]<0 ) cout << "***"<< ibx << " " << iby << newhhx[ibx+iby*nbeta] << endl; - // if (ipy==3 && ibx==10) cout << newhhx[ibx+iby*nbeta] << " " << hix[ibx] << " " << ibx+iby*nbeta << endl; - // } - ipy=hhx[ibx+iby*nbeta]*nSubPixels; - //if (hhx[ibx+iby*nbeta]>=((ipy)*bsize) && hhx[ibx+iby*nbeta]<=((ipy+1)*bsize)) { - if (ipy<0) ipy=0; - if (ipy>=nSubPixels) ipy=nSubPixels-1; + // if ( hhy[ibx+iby*nbeta]>=((ipy)*bsize) && + // hhy[ibx+iby*nbeta]<=((ipy+1)*bsize)) { + ipy = hhy[ibx + iby * nbeta] * nSubPixels; - if (ipy>=0 && ipy0) - newhhy[ibx+iby*nbeta]=hiy[ipy][iby]/(tot_eta_y[ipy]); - else - cout << "Bad tot_etay " << ipy << " " << tot_eta_y[ipy] << endl; - else - cout << "** Bad value ipx " << ibx << " " << iby << " "<< ipy << " " << hhx[ibx+iby*nbeta]*nSubPixels << endl; - // if (newhhy[ibx+iby*nbeta]>=1 || newhhy[ibx+iby*nbeta]<0 ) cout << "***"<< ibx << " " << iby << newhhy[ibx+iby*nbeta] << endl; - // if (ipy==3 && iby==10) cout << newhhy[ibx+iby*nbeta] << " " << hiy[iby] << " " << ibx+iby*nbeta << endl; - // } - } - } - // } - - - } - + if (ipy < 0) + ipy = 0; + if (ipy >= nSubPixels) + ipy = nSubPixels - 1; - public: - etaInterpolationAdaptiveBins(int nx=400, int ny=400, int ns=25, int nb=-1, double emin=1, double emax=0) : etaInterpolationPosXY(nx,ny,ns, nb, emin,emax){ - // flat=new double[nSubPixels*nSubPixels]; flat_x=new double[nSubPixels]; flat_y=new double[nSubPixels]; - // flat=new double[nSubPixels*nSubPixels]; -}; + if (ipy >= 0 && ipy < nSubPixels) + if (tot_eta_x[ipy] > 0) + newhhx[ibx + iby * nbeta] = + hix[ipy][ibx] / (tot_eta_x[ipy]); + else + cout << "Bad tot_etax " << ipy << " " << tot_eta_x[ipy] + << endl; + else + cout << "** Bad value ipy " << ibx << " " << iby << " " + << ipy << " " << hhy[ibx + iby * nbeta] * nSubPixels + << endl; + // if (newhhx[ibx+iby*nbeta]>=1 || newhhx[ibx+iby*nbeta]<0 ) + // cout << "***"<< ibx << " " << iby << newhhx[ibx+iby*nbeta] << + // endl; if (ipy==3 && ibx==10) cout << newhhx[ibx+iby*nbeta] << + // " " << hix[ibx] << " " << ibx+iby*nbeta << endl; + // } + ipy = hhx[ibx + iby * nbeta] * nSubPixels; + // if (hhx[ibx+iby*nbeta]>=((ipy)*bsize) && + // hhx[ibx+iby*nbeta]<=((ipy+1)*bsize)) { + if (ipy < 0) + ipy = 0; + if (ipy >= nSubPixels) + ipy = nSubPixels - 1; - etaInterpolationAdaptiveBins(etaInterpolationAdaptiveBins *orig): etaInterpolationPosXY(orig){hintcorr=new int[nPixelsX*nPixelsY*nSubPixels];}; + if (ipy >= 0 && ipy < nSubPixels) + if (tot_eta_y[ipy] > 0) + newhhy[ibx + iby * nbeta] = + hiy[ipy][iby] / (tot_eta_y[ipy]); + else + cout << "Bad tot_etay " << ipy << " " << tot_eta_y[ipy] + << endl; + else + cout << "** Bad value ipx " << ibx << " " << iby << " " + << ipy << " " << hhx[ibx + iby * nbeta] * nSubPixels + << endl; + // if (newhhy[ibx+iby*nbeta]>=1 || newhhy[ibx+iby*nbeta]<0 ) + // cout << "***"<< ibx << " " << iby << newhhy[ibx+iby*nbeta] << + // endl; + // if (ipy==3 && iby==10) cout << newhhy[ibx+iby*nbeta] << " " + // << hiy[iby] << " " << ibx+iby*nbeta << endl; + // } + } + } + // } + } - virtual etaInterpolationAdaptiveBins* Clone()=0; + public: + etaInterpolationAdaptiveBins(int nx = 400, int ny = 400, int ns = 25, + int nb = -1, double emin = 1, double emax = 0) + : etaInterpolationPosXY(nx, ny, ns, nb, emin, emax){ + // flat=new double[nSubPixels*nSubPixels]; flat_x=new + // double[nSubPixels]; flat_y=new double[nSubPixels]; + // flat=new double[nSubPixels*nSubPixels]; + }; - /* return new etaInterpolationAdaptiveBins(this); */ + etaInterpolationAdaptiveBins(etaInterpolationAdaptiveBins *orig) + : etaInterpolationPosXY(orig) { + hintcorr = new int[nPixelsX * nPixelsY * nSubPixels]; + }; - /* }; */ + virtual etaInterpolationAdaptiveBins *Clone() = 0; + /* return new etaInterpolationAdaptiveBins(this); */ + /* }; */ - virtual void prepareInterpolation(int &ok) { - prepareInterpolation(ok, 1000); - } + virtual void prepareInterpolation(int &ok) { + prepareInterpolation(ok, 1000); + } - virtual void prepareInterpolation(int &ok, int nint) - { - ok=1; + virtual void prepareInterpolation(int &ok, int nint) { + ok = 1; - ///*Eta Distribution Rebinning*/// - double bsize=1./nSubPixels; //precision - // cout<<"nPixelsX = "< rms) { - double thr=1./((double)nSubPixels); - double avg=tot_eta/((double)(nSubPixels*nSubPixels)); - double rms=sqrt(tot_eta); - cout << "total eta entries is :"<< tot_eta << " avg: "<< avg << " rms: " << sqrt(tot_eta) << endl; - double old_diff=calcDiff(avg, hhx, hhy), new_diff=old_diff+1, best_diff=old_diff; - // cout << " chi2= " << old_diff << " (rms= " << sqrt(tot_eta) << ")" << endl; - cout << endl; - cout << endl; - debugSaveAll(0); - int iint=0; - float *newhhx=new float[nbeta*nbeta]; //profile x - float *newhhy=new float[nbeta*nbeta]; //profile y - float *besthhx=hhx; //profile x - float *besthhy=hhy; //profile y + /* #ifdef SAVE_ALL */ + /* if (iint%10==0) */ + /* debugSaveAll(iint); */ + /* #endif */ + // cout << "Iteration " << iint << endl; + iterate(newhhx, newhhy); + new_diff = calcDiff(avg, newhhx, newhhy); + // cout << " chi2= " << new_diff << " (rms= " << sqrt(tot_eta) << + // ")"< rms) { + if (new_diff < best_diff) { + best_diff = new_diff; + besthhx = newhhx; + besthhy = newhhy; + } -/* #ifdef SAVE_ALL */ -/* if (iint%10==0) */ -/* debugSaveAll(iint); */ -/* #endif */ - // cout << "Iteration " << iint << endl; - iterate(newhhx,newhhy); - new_diff=calcDiff(avg, newhhx, newhhy); - // cout << " chi2= " << new_diff << " (rms= " << sqrt(tot_eta) << ")"< -#include #include #include +#include +#include #endif -#include #include "slsInterpolation.h" #include "tiffIO.h" +#include class etaInterpolationBase : public slsInterpolation { - - public: - - etaInterpolationBase(int nx=400, int ny=400, int ns=25, int nsy=25, int nb=-1, int nby=-1, double emin=1, double emax=0) : slsInterpolation(nx,ny,ns,nsy), hhx(NULL), hhy(NULL), heta(NULL), nbetaX(nb), nbetaY(nby), etamin(emin), etamax(emax) { - // cout << "eb " << nb << " " << emin << " " << emax << endl; - // cout << nb << " " << etamin << " " << etamax << endl; - if (nbetaX<=0) { - //cout << "aaa:" <=etamax) { - etamin=-1; - etamax=2; - } - etastepX=(etamax-etamin)/nbetaX; - etastepY=(etamax-etamin)/nbetaY; - heta=new int[nbetaX*nbetaY]; - hhx=new float[nbetaX*nbetaY]; - hhy=new float[nbetaX*nbetaY]; - rangeMin=etamin; - rangeMax=etamax; - flat= new double[nSubPixelsX*nSubPixelsY]; - hintcorr=new int [nSubPixelsX*nSubPixelsY*nPixelsX*nPixelsY]; - - }; - - etaInterpolationBase(etaInterpolationBase *orig): slsInterpolation(orig){ - nbetaX=orig->nbetaX; - nbetaY=orig->nbetaY; - etamin=orig->etamin; - etamax=orig->etamax; - rangeMin=orig->rangeMin; - rangeMax=orig->rangeMax; - - etastepX=(etamax-etamin)/nbetaX; - etastepY=(etamax-etamin)/nbetaY; - heta=new int[nbetaX*nbetaY]; - memcpy(heta,orig->heta,nbetaX*nbetaY*sizeof(int)); - hhx=new float[nbetaX*nbetaY]; - memcpy(hhx,orig->hhx,nbetaX*nbetaY*sizeof(float)); - hhy=new float[nbetaX*nbetaY]; - memcpy(hhy,orig->hhy,nbetaX*nbetaY*sizeof(float)); - hintcorr=new int [nSubPixelsX*nSubPixelsY*nPixelsX*nPixelsY]; - - }; - - - - - - virtual void resetFlatField() { - for (int ibx=0; ibx=etamax) { - etamin=-1; - etamax=2; - } - rangeMin=etamin; - rangeMax=etamax; - etastepX=(etamax-etamin)/nbetaX; - etastepY=(etamax-etamin)/nbetaY; - } - return heta; - }; - - int *setFlatField(int *h, int nb=-1, int nby=-1, double emin=1, double emax=0) - { - return setEta(h, nb, nby, emin, emax); - }; - - - - int *getFlatField(){return setEta(NULL);}; - - int *getFlatField(int &nb, int &nby, double &emin, double &emax){ - nb=nbetaX; - nby=nbetaY; - emin=etamin; - emax=etamax; - return getFlatField(); - }; - - - void *writeFlatField(const char * imgname) { - float *gm=NULL; - gm=new float[nbetaX*nbetaY]; - for (int ix=0; ix=1) etamax=emax; - if (emin<=0) etamin=emin; - - if (etamin>=etamax) { - etamin=-1; - etamax=2; - } - - etastepX=(etamax-etamin)/nbetaX; - etastepY=(etamax-etamin)/nbetaY; - uint32_t nnx; - uint32_t nny; - float *gm=ReadFromTiff(imgname, nnx, nny); - /* if (nnx!=nny) { */ - /* cout << "different number of bins in x " << nnx << " and y " << nny<< " !"<< endl; */ - /* cout << "Aborting read"<< endl; */ - /* return 0; */ - /* } */ - nbetaX=nnx; - nbetaY=nny; - if (gm) { - if (heta) { - delete [] heta; - delete [] hhx; - delete [] hhy; - } - - heta=new int[nbetaX*nbetaY]; - hhx=new float[nbetaX*nbetaY]; - hhy=new float[nbetaX*nbetaY]; - - for (int ix=0; ixScale((double)nSubPixels); - return hhx; - }; - - float *gethhy() - { - // hhy->Scale((double)nSubPixels); - return hhy; + public: + etaInterpolationBase(int nx = 400, int ny = 400, int ns = 25, int nsy = 25, + int nb = -1, int nby = -1, double emin = 1, + double emax = 0) + : slsInterpolation(nx, ny, ns, nsy), hhx(NULL), hhy(NULL), heta(NULL), + nbetaX(nb), nbetaY(nby), etamin(emin), etamax(emax) { + // cout << "eb " << nb << " " << emin << " " << emax << endl; + // cout << nb << " " << etamin << " " << etamax << endl; + if (nbetaX <= 0) { + // cout << "aaa:" <= etamax) { + etamin = -1; + etamax = 2; + } + etastepX = (etamax - etamin) / nbetaX; + etastepY = (etamax - etamin) / nbetaY; + heta = new int[nbetaX * nbetaY]; + hhx = new float[nbetaX * nbetaY]; + hhy = new float[nbetaX * nbetaY]; + rangeMin = etamin; + rangeMax = etamax; + flat = new double[nSubPixelsX * nSubPixelsY]; + hintcorr = new int[nSubPixelsX * nSubPixelsY * nPixelsX * nPixelsY]; }; - virtual int addToFlatField(double etax, double etay){ - int ex,ey; - ex=(etax-etamin)/etastepX; - ey=(etay-etamin)/etastepY; - if (ey=0 && ey>=0) - heta[ey*nbetaX+ex]++; - return 0; - }; - - - // virtual void prepareInterpolation(int &ok)=0; + etaInterpolationBase(etaInterpolationBase *orig) : slsInterpolation(orig) { + nbetaX = orig->nbetaX; + nbetaY = orig->nbetaY; + etamin = orig->etamin; + etamax = orig->etamax; + rangeMin = orig->rangeMin; + rangeMax = orig->rangeMax; - void debugSaveAll(int ind=0) { - int ibx, iby; - char tit[10000]; - - float tot_eta=0; + etastepX = (etamax - etamin) / nbetaX; + etastepY = (etamax - etamin) / nbetaY; + heta = new int[nbetaX * nbetaY]; + memcpy(heta, orig->heta, nbetaX * nbetaY * sizeof(int)); + hhx = new float[nbetaX * nbetaY]; + memcpy(hhx, orig->hhx, nbetaX * nbetaY * sizeof(float)); + hhy = new float[nbetaX * nbetaY]; + memcpy(hhy, orig->hhy, nbetaX * nbetaY * sizeof(float)); + hintcorr = new int[nSubPixelsX * nSubPixelsY * nPixelsX * nPixelsY]; + }; - float *etah=new float[nbetaX*nbetaY]; - // int etabins=nbeta; - int ibb=0; + virtual void resetFlatField() { + for (int ibx = 0; ibx < nbetaX * nbetaY; ibx++) { + heta[ibx] = 0; + hhx[ibx] = 0; + hhy[ibx] = 0; + } + }; - for (int ii=0; ii= etamax) { + etamin = -1; + etamax = 2; + } + rangeMin = etamin; + rangeMax = etamax; + etastepX = (etamax - etamin) / nbetaX; + etastepY = (etamax - etamin) / nbetaY; + } + return heta; + }; - for (int ii=0; ii=nSubPixelsX) ibx=nSubPixelsX-1; - if (iby>=nSubPixelsY) iby=nSubPixelsY-1; - + int *getFlatField(int &nb, int &nby, double &emin, double &emax) { + nb = nbetaX; + nby = nbetaY; + emin = etamin; + emax = etamax; + return getFlatField(); + }; - if (ibx>=0 && ibx=0 && iby0 && iby>0) cout << ibx << " " << iby << " " << ii << endl; - ftest[ibx+iby*nSubPixelsX]+=heta[ii]; - } else - cout << "Bad interpolation "<< ii << " " << ibx << " " << iby<< endl; - - } + void *writeFlatField(const char *imgname) { + float *gm = NULL; + gm = new float[nbetaX * nbetaY]; + for (int ix = 0; ix < nbetaX; ix++) { + for (int iy = 0; iy < nbetaY; iy++) { + gm[iy * nbetaX + ix] = heta[iy * nbetaX + ix]; + } + } + WriteToTiff(gm, imgname, nbetaX, nbetaY); + delete[] gm; + return NULL; + }; - sprintf(tit,"/scratch/ftest_%d.tiff",ind); - WriteToTiff(ftest, tit, nSubPixelsX, nSubPixelsY); + int readFlatField(const char *imgname, double emin = 1, double emax = 0) { + if (emax >= 1) + etamax = emax; + if (emin <= 0) + etamin = emin; - //int ibx=0, iby=0; - tot_eta/=nSubPixelsX*nSubPixelsY; - int nbad=0; - for (int ii=0; iitot_eta*2.f){ - etah[ii]=2; - nbad++; - } else - etah[ii]=0; - } - sprintf(tit,"/scratch/eta_bad_%d.tiff",ind); - WriteToTiff(etah, tit, nbetaX, nbetaY); - // cout << "Index: " << ind << "\t Bad bins: "<< nbad << endl; - //int ibx=0, iby=0; + if (etamin >= etamax) { + etamin = -1; + etamax = 2; + } - delete [] ftest; - delete [] etah; + etastepX = (etamax - etamin) / nbetaX; + etastepY = (etamax - etamin) / nbetaY; + uint32_t nnx; + uint32_t nny; + float *gm = ReadFromTiff(imgname, nnx, nny); + /* if (nnx!=nny) { */ + /* cout << "different number of bins in x " << nnx << " and y " << + * nny<< " !"<< endl; */ + /* cout << "Aborting read"<< endl; */ + /* return 0; */ + /* } */ + nbetaX = nnx; + nbetaY = nny; + if (gm) { + if (heta) { + delete[] heta; + delete[] hhx; + delete[] hhy; + } - } + heta = new int[nbetaX * nbetaY]; + hhx = new float[nbetaX * nbetaY]; + hhy = new float[nbetaX * nbetaY]; + for (int ix = 0; ix < nbetaX; ix++) { + for (int iy = 0; iy < nbetaY; iy++) { + heta[iy * nbetaX + ix] = gm[iy * nbetaX + ix]; + } + } + delete[] gm; + return 1; + } + return 0; + }; - protected: - + float *gethhx() { + // hhx->Scale((double)nSubPixels); + return hhx; + }; - double calcDiff(double avg, float *hx, float *hy) { - //double p_tot=0; - double diff=0, d; - //double bsize=1./nSubPixels; - int nbad=0; - double *p_tot_x=new double[nSubPixelsX]; - double *p_tot_y=new double[nSubPixelsY]; - double *p_tot= new double[nSubPixelsX*nSubPixelsY]; + float *gethhy() { + // hhy->Scale((double)nSubPixels); + return hhy; + }; + virtual int addToFlatField(double etax, double etay) { + int ex, ey; + ex = (etax - etamin) / etastepX; + ey = (etay - etamin) / etastepY; + if (ey < nbetaY && ex < nbetaX && ex >= 0 && ey >= 0) + heta[ey * nbetaX + ex]++; + return 0; + }; + // virtual void prepareInterpolation(int &ok)=0; - double maxdiff=0, mindiff=avg*nSubPixelsX*nSubPixelsY; - - int ipx, ipy; - for (ipy=0; ipy= nSubPixelsX) + ibx = nSubPixelsX - 1; + if (iby >= nSubPixelsY) + iby = nSubPixelsY - 1; + + if (ibx >= 0 && ibx < nSubPixelsX && iby >= 0 && + iby < nSubPixelsY) { + // + // if (ibx>0 && iby>0) cout << ibx << " " << iby << " " << ii << + // endl; + ftest[ibx + iby * nSubPixelsX] += heta[ii]; + } else + cout << "Bad interpolation " << ii << " " << ibx << " " << iby + << endl; + } + + sprintf(tit, "/scratch/ftest_%d.tiff", ind); + WriteToTiff(ftest, tit, nSubPixelsX, nSubPixelsY); + + // int ibx=0, iby=0; + tot_eta /= nSubPixelsX * nSubPixelsY; + int nbad = 0; + for (int ii = 0; ii < nbetaX * nbetaY; ii++) { + ibx = nSubPixelsX * hhx[ii]; + iby = nSubPixelsY * hhy[ii]; + if (ftest[ibx + iby * nSubPixelsX] < tot_eta * 0.5f) { + etah[ii] = 1; + nbad++; + } else if (ftest[ibx + iby * nSubPixelsX] > tot_eta * 2.f) { + etah[ii] = 2; + nbad++; + } else + etah[ii] = 0; + } + sprintf(tit, "/scratch/eta_bad_%d.tiff", ind); + WriteToTiff(etah, tit, nbetaX, nbetaY); + // cout << "Index: " << ind << "\t Bad bins: "<< nbad << endl; + // int ibx=0, iby=0; + + delete[] ftest; + delete[] etah; } - - for (int ibx=0; ibx=nSubPixelsX) ipx=nSubPixelsX-1; - - ipy=hy[ibx+iby*nbetaX]*nSubPixelsY; - if (ipy<0) ipy=0; - if (ipy>=nSubPixelsY) ipy=nSubPixelsY-1; - - p_tot[ipx+ipy*nSubPixelsX]+=heta[ibx+iby*nbetaX]; - p_tot_y[ipy]+=heta[ibx+iby*nbetaX]; - p_tot_x[ipx]+=heta[ibx+iby*nbetaX]; - } + + protected: + double calcDiff(double avg, float *hx, float *hy) { + // double p_tot=0; + double diff = 0, d; + // double bsize=1./nSubPixels; + int nbad = 0; + double *p_tot_x = new double[nSubPixelsX]; + double *p_tot_y = new double[nSubPixelsY]; + double *p_tot = new double[nSubPixelsX * nSubPixelsY]; + + double maxdiff = 0, mindiff = avg * nSubPixelsX * nSubPixelsY; + + int ipx, ipy; + for (ipy = 0; ipy < nSubPixelsY; ipy++) { + for (ipx = 0; ipx < nSubPixelsX; ipx++) { + p_tot[ipx + ipy * nSubPixelsX] = 0; + } + p_tot_y[ipy] = 0; + p_tot_x[ipy] = 0; + } + + for (int ibx = 0; ibx < nbetaX; ibx++) { + for (int iby = 0; iby < nbetaY; iby++) { + ipx = hx[ibx + iby * nbetaX] * nSubPixelsX; + if (ipx < 0) + ipx = 0; + if (ipx >= nSubPixelsX) + ipx = nSubPixelsX - 1; + + ipy = hy[ibx + iby * nbetaX] * nSubPixelsY; + if (ipy < 0) + ipy = 0; + if (ipy >= nSubPixelsY) + ipy = nSubPixelsY - 1; + + p_tot[ipx + ipy * nSubPixelsX] += heta[ibx + iby * nbetaX]; + p_tot_y[ipy] += heta[ibx + iby * nbetaX]; + p_tot_x[ipx] += heta[ibx + iby * nbetaX]; + } + } + + // cout << endl << endl; + for (ipy = 0; ipy < nSubPixelsY; ipy++) { + cout.width(5); + // flat_y[ipy]=p_tot_y[ipy];//avg/nSubPixels; + for (ipx = 0; ipx < nSubPixelsX; ipx++) { + + // flat_x[ipx]=p_tot_x[ipx];///avg/nSubPixels; + flat[ipx + nSubPixelsX * ipy] = + p_tot[ipx + nSubPixelsX * ipy]; /// avg; + d = p_tot[ipx + nSubPixelsX * ipy] - avg; + if (d < 0) + d *= -1.; + if (d > 5 * sqrt(avg)) + nbad++; + diff += d * d; + if (d < mindiff) + mindiff = d; + if (d > maxdiff) + maxdiff = d; + // cout << setprecision(4) << p_tot[ipx+nSubPixels*ipy] << + //" "; + } + + /* cout << "** " << setprecision(4) << flat_y[ipy]; */ + // cout << "\n"; + } + /* cout << "**" << endl; cout.width(5); */ + /* for (ipx=0; ipx5*sqrt(avg) ) - nbad++; - diff+=d*d; - if (dmaxdiff) maxdiff=d; - // cout << setprecision(4) << p_tot[ipx+nSubPixels*ipy] << " "; - } - - /* cout << "** " << setprecision(4) << flat_y[ipy]; */ - //cout << "\n"; - } - /* cout << "**" << endl; cout.width(5); */ - /* for (ipx=0; ipx #include "tiffIO.h" +#include //#include "etaInterpolationBase.h" #include "etaInterpolationAdaptiveBins.h" - //#define HSIZE 1 - class etaInterpolationCleverAdaptiveBins : public etaInterpolationAdaptiveBins { - private: + private: + // double *gradientX, *gradientY, *gradientXY; + virtual void iterate(float *newhhx, float *newhhy) { - // double *gradientX, *gradientY, *gradientXY; + double bsize = 1. / nSubPixels; + /* double hy[nSubPixels*HSIZE][nbeta]; //profile y */ + /* double hx[nSubPixels*HSIZE][nbeta]; //profile x */ + // double hix[nSubPixels*HSIZE][nbeta]; //integral of projection x + // double hiy[nSubPixels*HSIZE][nbeta]; //integral of projection y + int ipy, ipx, ippx, ippy; + // double tot_eta_x[nSubPixels*HSIZE]; + // double tot_eta_y[nSubPixels*HSIZE]; - virtual void iterate(float *newhhx, float *newhhy) { + double mean = 0; + double maxflat = 0, minflat = 0, maxgradX = 0, mingradX = 0, + maxgradY = 0, mingradY = 0, maxgr = 0, mingr = 0; - double bsize=1./nSubPixels; - - /* double hy[nSubPixels*HSIZE][nbeta]; //profile y */ - /* double hx[nSubPixels*HSIZE][nbeta]; //profile x */ - // double hix[nSubPixels*HSIZE][nbeta]; //integral of projection x - // double hiy[nSubPixels*HSIZE][nbeta]; //integral of projection y - int ipy, ipx, ippx, ippy; - // double tot_eta_x[nSubPixels*HSIZE]; - //double tot_eta_y[nSubPixels*HSIZE]; + int ix_maxflat, iy_maxflat, ix_minflat, iy_minflat, ix_maxgrX, + iy_maxgrX, ix_mingrX, iy_mingrX, ix_maxgrY, iy_maxgrY, ix_mingrY, + iy_mingrY, ix_mingr, iy_mingr, ix_maxgr, iy_maxgr; + int maskMin[nSubPixels * nSubPixels], maskMax[nSubPixels * nSubPixels]; - double mean=0; - double maxflat=0, minflat=0, maxgradX=0, mingradX=0, maxgradY=0, mingradY=0, maxgr=0, mingr=0; + // for (int ipy=0; ipy mean + 3. * sqrt(mean)) + maskMax[ipx + nSubPixels * ipy] = 1; + else + maskMax[ipx + nSubPixels * ipy] = 0; + if (ipx > 0 && ipy > 0) { + if (flat[ipx + nSubPixels * ipy] < + flat[ipx - 1 + nSubPixels * (ipy - 1)]) + maskMax[ipx + nSubPixels * ipy] = 0; + if (flat[ipx + nSubPixels * ipy] > + flat[ipx - 1 + nSubPixels * (ipy - 1)]) + maskMin[ipx + nSubPixels * ipy] = 0; + } + if (ipx > 0 && ipy < nSubPixels - 1) { + if (flat[ipx + nSubPixels * ipy] < + flat[ipx - 1 + nSubPixels * (ipy + 1)]) + maskMax[ipx + nSubPixels * ipy] = 0; + if (flat[ipx + nSubPixels * ipy] > + flat[ipx - 1 + nSubPixels * (ipy + 1)]) + maskMin[ipx + nSubPixels * ipy] = 0; + } + if (ipy > 0 && ipx < nSubPixels - 1) { + if (flat[ipx + nSubPixels * ipy] < + flat[ipx + 1 + nSubPixels * (ipy - 1)]) + maskMax[ipx + nSubPixels * ipy] = 0; + if (flat[ipx + nSubPixels * ipy] > + flat[ipx + 1 + nSubPixels * (ipy - 1)]) + maskMin[ipx + nSubPixels * ipy] = 0; + } + if (ipy < nSubPixels - 1 && ipx < nSubPixels - 1) { + if (flat[ipx + nSubPixels * ipy] < + flat[ipx + 1 + nSubPixels * (ipy + 1)]) + maskMax[ipx + nSubPixels * ipy] = 0; + if (flat[ipx + nSubPixels * ipy] > + flat[ipx + 1 + nSubPixels * (ipy + 1)]) + maskMin[ipx + nSubPixels * ipy] = 0; + } + if (ipy < nSubPixels - 1) { + if (flat[ipx + nSubPixels * ipy] < + flat[ipx + nSubPixels * (ipy + 1)]) + maskMax[ipx + nSubPixels * ipy] = 0; + if (flat[ipx + nSubPixels * ipy] > + flat[ipx + nSubPixels * (ipy + 1)]) + maskMin[ipx + nSubPixels * ipy] = 0; + } + if (ipx < nSubPixels - 1) { + if (flat[ipx + nSubPixels * ipy] < + flat[ipx + 1 + nSubPixels * (ipy)]) + maskMax[ipx + nSubPixels * ipy] = 0; + if (flat[ipx + nSubPixels * ipy] > + flat[ipx + 1 + nSubPixels * (ipy)]) + maskMin[ipx + nSubPixels * ipy] = 0; + } + + if (ipy > 0) { + if (flat[ipx + nSubPixels * ipy] < + flat[ipx + nSubPixels * (ipy - 1)]) + maskMax[ipx + nSubPixels * ipy] = 0; + if (flat[ipx + nSubPixels * ipy] > + flat[ipx + nSubPixels * (ipy - 1)]) + maskMin[ipx + nSubPixels * ipy] = 0; + } + + if (ipx > 0) { + if (flat[ipx + nSubPixels * ipy] < + flat[ipx - 1 + nSubPixels * (ipy)]) + maskMax[ipx + nSubPixels * ipy] = 0; + if (flat[ipx + nSubPixels * ipy] > + flat[ipx - 1 + nSubPixels * (ipy)]) + maskMin[ipx + nSubPixels * ipy] = 0; + } + + // if (maskMin[ipx+nSubPixels*ipy]) cout << ipx << " " << + //ipy << " is a local minimum " << flat[ipx+nSubPixels*ipy] << + //endl; if (maskMax[ipx+nSubPixels*ipy]) cout << ipx << " " << + //ipy << " is a local maximum "<< flat[ipx+nSubPixels*ipy] << + //endl; + } + } + int is_a_border = 0; + + // initialize the new partition to the previous one + // int ibx_p, iby_p, ibx_n, iby_n; + int ibbx, ibby; + + memcpy(newhhx, hhx, nbeta * nbeta * sizeof(float)); + memcpy(newhhy, hhy, nbeta * nbeta * sizeof(float)); + + for (int ibx = 0; ibx < nbeta; ibx++) { + for (int iby = 0; iby < nbeta; iby++) { + + ippy = hhy[ibx + iby * nbeta] * nSubPixels; + ippx = hhx[ibx + iby * nbeta] * nSubPixels; + + is_a_border = 0; + + if (maskMin[ippx + nSubPixels * ippy] || + maskMax[ippx + nSubPixels * ippy]) { + + for (int ix = -1; ix < 2; ix++) { + ibbx = ibx + ix; + if (ibbx < 0) + ibbx = 0; + if (ibbx > nbeta - 1) + ibbx = nbeta - 1; + for (int iy = -1; iy < 2; iy++) { + ibby = iby + iy; + if (ibby < 0) + ibby = 0; + if (ibby > nbeta - 1) + ibby = nbeta - 1; + + ipy = hhy[ibbx + ibby * nbeta] * nSubPixels; + ipx = hhx[ibbx + ibby * nbeta] * nSubPixels; + + if (ipx != ippx || ipy != ippy) { + is_a_border = 1; + if (maskMin[ippx + nSubPixels * ippy]) { + // increase the region + newhhx[ibbx + ibby * nbeta] = + ((double)ippx + 0.5) / + ((double)nSubPixels); + newhhy[ibbx + ibby * nbeta] = + ((double)ippy + 0.5) / + ((double)nSubPixels); + } + if (maskMax[ippx + nSubPixels * ippy]) { + // reduce the region + newhhx[ibx + iby * nbeta] = + ((double)ipx + 0.5) / + ((double)nSubPixels); + newhhy[ibx + iby * nbeta] = + ((double)ipy + 0.5) / + ((double)nSubPixels); + } + + // cout << ippx << " " << ippy << " " << + //ibx << " " << iby << " * " << ipx << " " << + //ipy << " " << ibbx << " " << ibby << endl; + } + } + } + } + } + } + + // Check that the resulting histograms are monotonic and they don't have + // holes! + + for (int ibx = 0; ibx < nbeta - 1; ibx++) { + for (int iby = 0; iby < nbeta - 1; iby++) { + + ippy = newhhy[ibx + iby * nbeta] * nSubPixels; + ippx = newhhx[ibx + iby * nbeta] * nSubPixels; + + ipy = newhhy[ibx + (iby + 1) * nbeta] * nSubPixels; + ipx = newhhx[ibx + 1 + iby * nbeta] * nSubPixels; + + if (ippx > ipx) + newhhx[ibx + 1 + iby * nbeta] = newhhx[ibx + iby * nbeta]; + else if (ipx > ippx + 1) + newhhx[ibx + 1 + iby * nbeta] = + ((double)(ippx + 1 + 0.5)) / ((double)nSubPixels); + + if (ippy > ipy) + newhhy[ibx + (iby + 1) * nbeta] = newhhy[ibx + iby * nbeta]; + else if (ipy > ippy + 1) + newhhy[ibx + (iby + 1) * nbeta] = + ((double)(ippy + 1 + 0.5)) / ((double)nSubPixels); + } + } } - // cout << "Mean is " << mean << endl; + public: + etaInterpolationCleverAdaptiveBins(int nx = 400, int ny = 400, int ns = 25, + int nb = -1, double emin = 1, + double emax = 0) + : etaInterpolationAdaptiveBins(nx, ny, ns, nb, emin, emax){ - /*** Find local minima and maxima within the staistical uncertainty **/ - for (ipy=0; ipymean+3.*sqrt(mean)) maskMax[ipx+nSubPixels*ipy]=1; else maskMax[ipx+nSubPixels*ipy]=0; - if (ipx>0 && ipy>0) { - if (flat[ipx+nSubPixels*ipy]flat[ipx-1+nSubPixels*(ipy-1)]) maskMin[ipx+nSubPixels*ipy]=0; - } - if (ipx>0 && ipyflat[ipx-1+nSubPixels*(ipy+1)]) maskMin[ipx+nSubPixels*ipy]=0; - } - if (ipy>0 && ipxflat[ipx+1+nSubPixels*(ipy-1)]) maskMin[ipx+nSubPixels*ipy]=0; - } - if (ipyflat[ipx+1+nSubPixels*(ipy+1)]) maskMin[ipx+nSubPixels*ipy]=0; - } - if (ipyflat[ipx+nSubPixels*(ipy+1)]) maskMin[ipx+nSubPixels*ipy]=0; - } - if (ipxflat[ipx+1+nSubPixels*(ipy)]) maskMin[ipx+nSubPixels*ipy]=0; - } - - if (ipy>0 ) { - if (flat[ipx+nSubPixels*ipy]flat[ipx+nSubPixels*(ipy-1)]) maskMin[ipx+nSubPixels*ipy]=0; - } + }; - if (ipx>0 ) { - if (flat[ipx+nSubPixels*ipy]flat[ipx-1+nSubPixels*(ipy)]) maskMin[ipx+nSubPixels*ipy]=0; - } + etaInterpolationCleverAdaptiveBins(etaInterpolationCleverAdaptiveBins *orig) + : etaInterpolationAdaptiveBins(orig){}; - // if (maskMin[ipx+nSubPixels*ipy]) cout << ipx << " " << ipy << " is a local minimum " << flat[ipx+nSubPixels*ipy] << endl; - // if (maskMax[ipx+nSubPixels*ipy]) cout << ipx << " " << ipy << " is a local maximum "<< flat[ipx+nSubPixels*ipy] << endl; - - } - } - int is_a_border=0; - - //initialize the new partition to the previous one - // int ibx_p, iby_p, ibx_n, iby_n; - int ibbx, ibby; - - - memcpy(newhhx,hhx,nbeta*nbeta*sizeof(float)); - memcpy(newhhy,hhy,nbeta*nbeta*sizeof(float)); - - for (int ibx=0; ibxnbeta-1) ibbx=nbeta-1; - for (int iy=-1; iy<2; iy++) { - ibby=iby+iy; - if (ibby<0) ibby=0; - if (ibby>nbeta-1) ibby=nbeta-1; - - - ipy=hhy[ibbx+ibby*nbeta]*nSubPixels; - ipx=hhx[ibbx+ibby*nbeta]*nSubPixels; - - - if (ipx!=ippx || ipy!=ippy) { - is_a_border=1; - if (maskMin[ippx+nSubPixels*ippy]) { - //increase the region - newhhx[ibbx+ibby*nbeta]=((double)ippx+0.5)/((double)nSubPixels); - newhhy[ibbx+ibby*nbeta]=((double)ippy+0.5)/((double)nSubPixels); - } - if (maskMax[ippx+nSubPixels*ippy]) { - //reduce the region - newhhx[ibx+iby*nbeta]=((double)ipx+0.5)/((double)nSubPixels); - newhhy[ibx+iby*nbeta]=((double)ipy+0.5)/((double)nSubPixels); - } - - // cout << ippx << " " << ippy << " " << ibx << " " << iby << " * " << ipx << " " << ipy << " " << ibbx << " " << ibby << endl; - } - - - } - } - } - - - - } - - } - - - //Check that the resulting histograms are monotonic and they don't have holes! - - for (int ibx=0; ibxipx) - newhhx[ibx+1+iby*nbeta]=newhhx[ibx+iby*nbeta]; - else if (ipx >ippx+1) - newhhx[ibx+1+iby*nbeta]=((double)(ippx+1+0.5))/((double)nSubPixels); - - if ( ippy>ipy) - newhhy[ibx+(iby+1)*nbeta]=newhhy[ibx+iby*nbeta]; - else if (ipy >ippy+1) - newhhy[ibx+(iby+1)*nbeta]=((double)(ippy+1+0.5))/((double)nSubPixels); - - } - } - - - } - - - public: - etaInterpolationCleverAdaptiveBins(int nx=400, int ny=400, int ns=25, int nb=-1, double emin=1, double emax=0) : etaInterpolationAdaptiveBins(nx,ny,ns, nb, emin,emax){ - - - }; - - etaInterpolationCleverAdaptiveBins(etaInterpolationCleverAdaptiveBins *orig): etaInterpolationAdaptiveBins(orig){}; - - virtual etaInterpolationCleverAdaptiveBins* Clone()=0; - - /* return new etaInterpolationCleverAdaptiveBins(this); */ - - /* }; */ + virtual etaInterpolationCleverAdaptiveBins *Clone() = 0; + /* return new etaInterpolationCleverAdaptiveBins(this); */ + /* }; */ }; -class eta2InterpolationCleverAdaptiveBins : public virtual eta2InterpolationBase, public virtual etaInterpolationCleverAdaptiveBins { - public: - eta2InterpolationCleverAdaptiveBins(int nx=400, int ny=400, int ns=25, int nb=-1, double emin=1, double emax=0) : etaInterpolationBase(nx,ny,ns, nb, emin,emax),eta2InterpolationBase(nx,ny,ns, nb, emin,emax),etaInterpolationCleverAdaptiveBins(nx,ny,ns, nb, emin,emax){ - }; - - eta2InterpolationCleverAdaptiveBins(eta2InterpolationCleverAdaptiveBins *orig): etaInterpolationBase(orig), etaInterpolationCleverAdaptiveBins(orig) {}; +class eta2InterpolationCleverAdaptiveBins + : public virtual eta2InterpolationBase, + public virtual etaInterpolationCleverAdaptiveBins { + public: + eta2InterpolationCleverAdaptiveBins(int nx = 400, int ny = 400, int ns = 25, + int nb = -1, double emin = 1, + double emax = 0) + : etaInterpolationBase(nx, ny, ns, nb, emin, emax), + eta2InterpolationBase(nx, ny, ns, nb, emin, emax), + etaInterpolationCleverAdaptiveBins(nx, ny, ns, nb, emin, emax){}; - virtual eta2InterpolationCleverAdaptiveBins* Clone() { return new eta2InterpolationCleverAdaptiveBins(this);}; + eta2InterpolationCleverAdaptiveBins( + eta2InterpolationCleverAdaptiveBins *orig) + : etaInterpolationBase(orig), + etaInterpolationCleverAdaptiveBins(orig){}; - // virtual int *getInterpolatedImage(){return eta2InterpolationBase::getInterpolatedImage();}; + virtual eta2InterpolationCleverAdaptiveBins *Clone() { + return new eta2InterpolationCleverAdaptiveBins(this); + }; - /* virtual int *getInterpolatedImage(){ */ - /* int ipx, ipy; */ - /* cout << "ff" << endl; */ - /* calcDiff(1, hhx, hhy); //get flat */ - /* double avg=0; */ - /* for (ipx=0; ipx0) */ - /* hintcorr[ibx+iby*nSubPixels*nPixelsX]=hint[ibx+iby*nSubPixels*nPixelsX]*(avg/flat[ipx+ipy*nSubPixels]); */ - /* else */ - /* hintcorr[ibx+iby*nSubPixels*nPixelsX]=hint[ibx+iby*nSubPixels*nPixelsX]; */ + // virtual int *getInterpolatedImage(){return + // eta2InterpolationBase::getInterpolatedImage();}; + /* virtual int *getInterpolatedImage(){ */ + /* int ipx, ipy; */ + /* cout << "ff" << endl; */ + /* calcDiff(1, hhx, hhy); //get flat */ + /* double avg=0; */ + /* for (ipx=0; ipx0) */ + /* hintcorr[ibx+iby*nSubPixels*nPixelsX]=hint[ibx+iby*nSubPixels*nPixelsX]*(avg/flat[ipx+ipy*nSubPixels]); + */ + /* else */ + /* hintcorr[ibx+iby*nSubPixels*nPixelsX]=hint[ibx+iby*nSubPixels*nPixelsX]; + */ + /* } */ + /* } */ - /* return hintcorr; */ - /* }; */ - - + /* return hintcorr; */ + /* }; */ }; +class eta3InterpolationCleverAdaptiveBins + : public virtual eta3InterpolationBase, + public virtual etaInterpolationCleverAdaptiveBins { + public: + eta3InterpolationCleverAdaptiveBins(int nx = 400, int ny = 400, int ns = 25, + int nb = -1, double emin = 1, + double emax = 0) + : etaInterpolationBase(nx, ny, ns, nb, emin, emax), + eta3InterpolationBase(nx, ny, ns, nb, emin, emax), + etaInterpolationCleverAdaptiveBins(nx, ny, ns, nb, emin, emax){ + }; -class eta3InterpolationCleverAdaptiveBins : public virtual eta3InterpolationBase, public virtual etaInterpolationCleverAdaptiveBins { - public: - eta3InterpolationCleverAdaptiveBins(int nx=400, int ny=400, int ns=25, int nb=-1, double emin=1, double emax=0) : etaInterpolationBase(nx,ny,ns, nb, emin,emax),eta3InterpolationBase(nx,ny,ns, nb, emin,emax), etaInterpolationCleverAdaptiveBins(nx,ny,ns, nb, emin,emax){ - - }; + eta3InterpolationCleverAdaptiveBins( + eta3InterpolationCleverAdaptiveBins *orig) + : etaInterpolationBase(orig), + etaInterpolationCleverAdaptiveBins(orig){}; - eta3InterpolationCleverAdaptiveBins(eta3InterpolationCleverAdaptiveBins *orig): etaInterpolationBase(orig), etaInterpolationCleverAdaptiveBins(orig) {}; - - virtual eta3InterpolationCleverAdaptiveBins* Clone() { return new eta3InterpolationCleverAdaptiveBins(this);}; + virtual eta3InterpolationCleverAdaptiveBins *Clone() { + return new eta3InterpolationCleverAdaptiveBins(this); + }; }; #endif diff --git a/slsDetectorCalibration/interpolations/etaInterpolationGlobal.h b/slsDetectorCalibration/interpolations/etaInterpolationGlobal.h index 73d7e2833..41d074612 100644 --- a/slsDetectorCalibration/interpolations/etaInterpolationGlobal.h +++ b/slsDetectorCalibration/interpolations/etaInterpolationGlobal.h @@ -3,85 +3,94 @@ #ifndef ETA_INTERPOLATION_GLOBAL_H #define ETA_INTERPOLATION_GLOBAL_H - #include "etaInterpolationBase.h" -class etaInterpolationGlobal : public etaInterpolationBase{ - public: - globalEtaInterpolation(int nx=400, int ny=400, int ns=25, int nb=-1, double emin=1, double emax=0) : etaInterpolationBase(nx,ny,ns, nb, emin,emax){}; - +class etaInterpolationGlobal : public etaInterpolationBase { + public: + globalEtaInterpolation(int nx = 400, int ny = 400, int ns = 25, int nb = -1, + double emin = 1, double emax = 0) + : etaInterpolationBase(nx, ny, ns, nb, emin, emax){}; + virtual void prepareInterpolation(int &ok) { + ok = 1; +#ifdef MYROOT1 + if (hhx) + delete hhx; + if (hhy) + delete hhy; - virtual void prepareInterpolation(int &ok) - { - ok=1; -#ifdef MYROOT1 - if (hhx) delete hhx; - if (hhy) delete hhy; + hhx = new TH2D("hhx", "hhx", heta->GetNbinsX(), + heta->GetXaxis()->GetXmin(), heta->GetXaxis()->GetXmax(), + heta->GetNbinsY(), heta->GetYaxis()->GetXmin(), + heta->GetYaxis()->GetXmax()); + hhy = new TH2D("hhy", "hhy", heta->GetNbinsX(), + heta->GetXaxis()->GetXmin(), heta->GetXaxis()->GetXmax(), + heta->GetNbinsY(), heta->GetYaxis()->GetXmin(), + heta->GetYaxis()->GetXmax()); - hhx=new TH2D("hhx","hhx",heta->GetNbinsX(),heta->GetXaxis()->GetXmin(),heta->GetXaxis()->GetXmax(), heta->GetNbinsY(),heta->GetYaxis()->GetXmin(),heta->GetYaxis()->GetXmax()); - hhy=new TH2D("hhy","hhy",heta->GetNbinsX(),heta->GetXaxis()->GetXmin(),heta->GetXaxis()->GetXmax(), heta->GetNbinsY(),heta->GetYaxis()->GetXmin(),heta->GetYaxis()->GetXmax()); - #endif + ///*Eta Distribution Rebinning*/// + double bsize = 1. / nSubPixels; // precision + // cout<<"nPixelsX = "<(ib+1)*tot_eta*bsize) ib++; - for (int iby=0; ibySetBinContent(ibx+1,iby+1,ib); + int ib = 0; + for (int ibx = 0; ibx < nbeta; ibx++) { + if (hix[ibx] > (ib + 1) * tot_eta * bsize) + ib++; + for (int iby = 0; iby < nbeta; iby++) { +#ifdef MYROOT1 + hhx->SetBinContent(ibx + 1, iby + 1, ib); #endif -#ifndef MYROOT1 - hhx[ibx+iby*nbeta]=ib; +#ifndef MYROOT1 + hhx[ibx + iby * nbeta] = ib; #endif - } - } - ib=0; - for (int iby=0; iby(ib+1)*tot_eta*bsize) ib++; - for (int ibx=0; ibxSetBinContent(ibx+1,iby+1,ib); + } + } + ib = 0; + for (int iby = 0; iby < nbeta; iby++) { + if (hiy[iby] > (ib + 1) * tot_eta * bsize) + ib++; + for (int ibx = 0; ibx < nbeta; ibx++) { +#ifdef MYROOT1 + hhy->SetBinContent(ibx + 1, iby + 1, ib); #endif -#ifndef MYROOT1 - hhy[ibx+iby*nbeta]=ib; +#ifndef MYROOT1 + hhy[ibx + iby * nbeta] = ib; #endif - } - } - - return ; - }; + } + } + return; + }; }; #endif diff --git a/slsDetectorCalibration/interpolations/etaInterpolationPosXY.h b/slsDetectorCalibration/interpolations/etaInterpolationPosXY.h index 2596a3792..f892d5cab 100644 --- a/slsDetectorCalibration/interpolations/etaInterpolationPosXY.h +++ b/slsDetectorCalibration/interpolations/etaInterpolationPosXY.h @@ -3,210 +3,211 @@ #ifndef ETA_INTERPOLATION_POSXY_H #define ETA_INTERPOLATION_POSXY_H - //#include "tiffIO.h" -#include "etaInterpolationBase.h" #include "eta2InterpolationBase.h" #include "eta3InterpolationBase.h" +#include "etaInterpolationBase.h" -class etaInterpolationPosXY : public virtual etaInterpolationBase{ - public: - etaInterpolationPosXY(int nx=400, int ny=400, int ns=25, int nsy=25, int nb=-1, int nby=-1, double emin=1, double emax=0) : etaInterpolationBase(nx,ny, ns, nsy, nb, nby, emin, emax){ - // cout << "epxy " << nb << " " << emin << " " << emax << endl; cout << nbeta << " " << etamin << " " << etamax << endl; - }; +class etaInterpolationPosXY : public virtual etaInterpolationBase { + public: + etaInterpolationPosXY(int nx = 400, int ny = 400, int ns = 25, int nsy = 25, + int nb = -1, int nby = -1, double emin = 1, + double emax = 0) + : etaInterpolationBase(nx, ny, ns, nsy, nb, nby, emin, emax){ + // cout << "epxy " << nb << " " << emin << " " << emax << endl; + // cout << nbeta << " " << etamin << " " << etamax << endl; + }; - etaInterpolationPosXY(etaInterpolationPosXY *orig): etaInterpolationBase(orig) {}; + etaInterpolationPosXY(etaInterpolationPosXY *orig) + : etaInterpolationBase(orig){}; - virtual etaInterpolationPosXY* Clone()=0; /* { */ + virtual etaInterpolationPosXY *Clone() = 0; /* { */ /* return new etaInterpolationPosXY(this); */ /* }; */ - virtual void prepareInterpolation(int &ok) - { - ok=1; + virtual void prepareInterpolation(int &ok) { + ok = 1; + ///*Eta Distribution Rebinning*/// + // double bsize=1./nSubPixels; //precision + // cout<<"nPixelsX = "<= 0 && etay <= 1) + hy[iby] = heta[ib + iby * nbetaX]; + else + hy[iby] = 0; + // tot_eta_y+=hy[iby]; + } - for (int iby=0; iby=0 && etay<=1) - hy[iby]=heta[ib+iby*nbetaX]; - else - hy[iby]=0; - // tot_eta_y+=hy[iby]; - } + hiy[0] = hy[0]; - - hiy[0]=hy[0]; + for (int iby = 1; iby < nbetaY; iby++) { + hiy[iby] = hiy[iby - 1] + hy[iby]; + } - for (int iby=1; ibytot_eta_y*(ii+1)/nSubPixels) ii++; - hhy[ib+iby*nbetaX]=hiy[iby]/tot_eta_y; - } - } - } + for (int iby = 0; iby < nbetaY; iby++) { + if (tot_eta_y <= 0) { + hhy[ib + iby * nbetaX] = -1; + // ii=(ibx*nSubPixels)/nbeta; + } else { + // if (hiy[ibx]>tot_eta_y*(ii+1)/nSubPixels) ii++; + hhy[ib + iby * nbetaX] = hiy[iby] / tot_eta_y; + } + } + } + for (int ib = 0; ib < nbetaY; ib++) { + for (int ibx = 0; ibx < nbetaX; ibx++) { + etax = etamin + ibx * etastepX; + // cout << etax << endl; + if (etax >= 0 && etax <= 1) + hx[ibx] = heta[ibx + ib * nbetaX]; + else { + hx[ibx] = 0; + } + } + hix[0] = hx[0]; - for (int ib=0; ib=0 && etax<=1) - hx[ibx]=heta[ibx+ib*nbetaX]; - else { - hx[ibx]=0; - } - } - hix[0]=hx[0]; - - for (int ibx=1; ibxtot_eta_x*(ii+1)/nSubPixels) ii++; - hhx[ibx+ib*nbetaX]=hix[ibx]/tot_eta_x; - } - } - - } + for (int ibx = 0; ibx < nbetaX; ibx++) { + if (tot_eta_x <= 0) { + hhx[ibx + ib * nbetaX] = -1; + } else { + // if (hix[ibx]>tot_eta_x*(ii+1)/nSubPixels) ii++; + hhx[ibx + ib * nbetaX] = hix[ibx] / tot_eta_x; + } + } + } - - int ibx, iby, ib; - - iby=0; - while (hhx[iby*nbetaY+nbetaY/2]<0) iby++; - for (ib=0; ib #include +#include //#include -#include // std::abs +#include // std::abs -#define PI 3.14159265 -#define TWOPI 2.*PI +#define PI 3.14159265 +#define TWOPI 2. * PI using namespace std; class etaInterpolationRandomBins : public etaInterpolationPosXY { - private: - double calcDiff(double avg, float *hx, float *hy) { - double p_tot=0; - double diff=0; - double bsize=1./nSubPixels; - - for (int ipx=0; ipx=((ipx)*bsize) && hx[ibx+iby*nbeta]<((ipx+1)*bsize) && hy[ibx+iby*nbeta]>=((ipy)*bsize) && hy[ibx+iby*nbeta]<((ipy+1)*bsize)) { - p_tot+=heta[ibx+iby*nbeta]; - } - } - } - - // cout << p_tot << " \t "; + private: + double calcDiff(double avg, float *hx, float *hy) { + double p_tot = 0; + double diff = 0; + double bsize = 1. / nSubPixels; + for (int ipx = 0; ipx < nSubPixels; ipx++) { + for (int ipy = 0; ipy < nSubPixels; ipy++) { + p_tot = 0; + for (int ibx = 0; ibx < nbeta; ibx++) { + for (int iby = 0; iby < nbeta; iby++) { + if (hx[ibx + iby * nbeta] >= ((ipx)*bsize) && + hx[ibx + iby * nbeta] < ((ipx + 1) * bsize) && + hy[ibx + iby * nbeta] >= ((ipy)*bsize) && + hy[ibx + iby * nbeta] < ((ipy + 1) * bsize)) { + p_tot += heta[ibx + iby * nbeta]; + } + } + } + // cout << p_tot << " \t "; - diff+=(p_tot-avg)*(p_tot-avg); - - } - // cout << "\n"; + diff += (p_tot - avg) * (p_tot - avg); + } + // cout << "\n"; + } + return diff; } - return diff; - } - - double iterate(float *newhhx, float *newhhy, double avg) { - double bsize=1./nSubPixels; - - double hy[nbeta]; //profile y - double hx[nbeta]; //profile x - double hix[nbeta]; //integral of projection x - double hiy[nbeta]; //integral of projection y - - double tot_eta_x=0; - double tot_eta_y=0; + double iterate(float *newhhx, float *newhhy, double avg) { - int p0; - int vx[(nSubPixels+1)*(nSubPixels+1)], vy[(nSubPixels+1)*(nSubPixels+1)]; + double bsize = 1. / nSubPixels; - int arrx[nSubPixels+1], arry[nSubPixels+1]; + double hy[nbeta]; // profile y + double hx[nbeta]; // profile x + double hix[nbeta]; // integral of projection x + double hiy[nbeta]; // integral of projection y - int bad=1; + double tot_eta_x = 0; + double tot_eta_y = 0; + int p0; + int vx[(nSubPixels + 1) * (nSubPixels + 1)], + vy[(nSubPixels + 1) * (nSubPixels + 1)]; - int isby, isbx; - int ii=0; - + int arrx[nSubPixels + 1], arry[nSubPixels + 1]; - // using default comparison (operator <): - // std::sort (myvector.begin(), myvector.begin()+4); //(12 32 45 71)26 80 53 33 + int bad = 1; - for (isby=0; isby<(nSubPixels+1)/2+1; isby++) { - - for (isbx=0; isbx<(nSubPixels+1)/2+1; isbx++) { - p0=isby*(nSubPixels+1)+isbx; - // for (int iv=0; iv<(nSubPixels+1)*(nSubPixels+1); iv++) { - if (isbx==0) { - vy[p0]=isby*nbeta/nSubPixels; - vx[p0]=0; - } else if ( isby==0 ) { - vy[p0]=0; - vx[p0]=isbx*nbeta/nSubPixels; - } - else { - vy[p0]=rand()%(nbeta/2); - vx[p0]=rand()%(nbeta/2); - if (nSubPixels%2==0 && isbx==nSubPixels/2) - vx[p0]=nbeta/2; - if (nSubPixels%2==0 && isby==nSubPixels/2 ) - vy[p0]=nbeta/2; - } - // cout << "(" << vx[p0] << " , " << vy[p0] << " ) \t" ; - // } - } - //cout << endl; - } - // cout << "rand" << endl; - - - while (bad) { + int isby, isbx; + int ii = 0; - for (isby=0; isby<(nSubPixels+1)/2+1; isby++) { - - - for (isbx=0; isbx<(nSubPixels+1)/2+1; isbx++) { - arrx[isbx]=vx[isby*(nSubPixels+1)+isbx]; - arry[isbx]=vy[isbx*(nSubPixels+1)+isby]; - //cout << isbx << " " << arrx[isbx] << " " << isby << " " << arry[isbx] << endl; - } + // using default comparison (operator <): + // std::sort (myvector.begin(), myvector.begin()+4); //(12 32 + // 45 71)26 80 53 33 - sort(arrx,arrx+(nSubPixels+1)/2+1); - sort(arry,arry+(nSubPixels+1)/2+1); - - // cout << "*****"<< endl; - // cout << endl; + for (isby = 0; isby < (nSubPixels + 1) / 2 + 1; isby++) { - for (int isbx=0; isbx<(nSubPixels+1)/2+1; isbx++) { - vx[isby*(nSubPixels+1)+isbx]=arrx[isbx]; - vy[isbx*(nSubPixels+1)+isby]=arry[isbx]; - + for (isbx = 0; isbx < (nSubPixels + 1) / 2 + 1; isbx++) { + p0 = isby * (nSubPixels + 1) + isbx; + // for (int iv=0; iv<(nSubPixels+1)*(nSubPixels+1); iv++) { + if (isbx == 0) { + vy[p0] = isby * nbeta / nSubPixels; + vx[p0] = 0; + } else if (isby == 0) { + vy[p0] = 0; + vx[p0] = isbx * nbeta / nSubPixels; + } else { + vy[p0] = rand() % (nbeta / 2); + vx[p0] = rand() % (nbeta / 2); + if (nSubPixels % 2 == 0 && isbx == nSubPixels / 2) + vx[p0] = nbeta / 2; + if (nSubPixels % 2 == 0 && isby == nSubPixels / 2) + vy[p0] = nbeta / 2; + } + // cout << "(" << vx[p0] << " , " << vy[p0] << " ) \t" ; + // } + } + // cout << endl; + } + // cout << "rand" << endl; - vx[(nSubPixels-isby)*(nSubPixels+1)+(nSubPixels-isbx)]=nbeta-arrx[isbx]; - vy[(nSubPixels-isbx)*(nSubPixels+1)+(nSubPixels-isby)]=nbeta-arry[isbx]; + while (bad) { - vx[isby*(nSubPixels+1)+(nSubPixels-isbx)]=nbeta-arrx[isbx]; - vy[isbx*(nSubPixels+1)+(nSubPixels-isby)]=arry[isbx]; - + for (isby = 0; isby < (nSubPixels + 1) / 2 + 1; isby++) { - vx[(nSubPixels-isby)*(nSubPixels+1)+(isbx)]=arrx[isbx]; - vy[(nSubPixels-isbx)*(nSubPixels+1)+(isby)]=nbeta-arry[isbx]; + for (isbx = 0; isbx < (nSubPixels + 1) / 2 + 1; isbx++) { + arrx[isbx] = vx[isby * (nSubPixels + 1) + isbx]; + arry[isbx] = vy[isbx * (nSubPixels + 1) + isby]; + // cout << isbx << " " << arrx[isbx] << " " << isby << " " + // << arry[isbx] << endl; + } + sort(arrx, arrx + (nSubPixels + 1) / 2 + 1); + sort(arry, arry + (nSubPixels + 1) / 2 + 1); - } - - - - } - - /* for (isby=0; isbynSubPixels-1) isbx=nSubPixels-1; */ + if (nSubPixels % 2 == 0 && isbx == nSubPixels / 2) + ; + else + vy[isby * (nSubPixels + 1) + isbx] = + rand() % (nbeta / 2); - /* if (iby==0) */ - /* isby=0; */ - /* else */ - /* isby= (newhhx[ibx+(iby-1)*nbeta])/bsize-1; */ - - /* if (isby<0) isbx=0; */ - /* if (isby>nSubPixels-1) isby=nSubPixels-1; */ - /* // cout << isbx << " " << isby << endl; */ + if (bad == 0) + ii++; - for (isby=0; isby PI) - dtheta -= TWOPI; - while (dtheta < -PI) - dtheta += TWOPI; + for (int ibx = 0; ibx < nbeta; ibx++) { - angle += dtheta; - } + for (int iby = 0; iby < nbeta; iby++) { - if (abs((double)angle) < PI) - in_quad=0; - else - in_quad=1; - - if (in_quad) { - newhhx[ibx+iby*nbeta]=bsize*((double)isbx); - newhhy[ibx+iby*nbeta]=bsize*((double)isby); - break; - } - - - - - } - if (in_quad) break; - } - - } - } - - // cout << "hist" << endl; - return calcDiff(avg, newhhx, newhhy); - } - + in_quad = 0; - public: - etaInterpolationRandomBins(int nx=400, int ny=400, int ns=25, int nb=-1, double emin=1, double emax=0) : etaInterpolationPosXY(nx,ny,ns, nb, emin,emax){}; + /* if (ibx==0) */ + /* isbx=0; */ + /* else */ + /* isbx= (newhhx[ibx-1+iby*nbeta])/bsize-1; */ + /* if (isbx<0) isbx=0; */ + /* if (isbx>nSubPixels-1) isbx=nSubPixels-1; */ - etaInterpolationRandomBins(etaInterpolationRandomBins *orig): etaInterpolationPosXY(orig){}; + /* if (iby==0) */ + /* isby=0; */ + /* else */ + /* isby= (newhhx[ibx+(iby-1)*nbeta])/bsize-1; */ - virtual etaInterpolationRandomBins* Clone() { + /* if (isby<0) isbx=0; */ + /* if (isby>nSubPixels-1) isby=nSubPixels-1; */ + /* // cout << isbx << " " << isby << endl; */ - return new etaInterpolationRandomBins(this); + for (isby = 0; isby < nSubPixels; isby++) { - }; + for (isbx = 0; isbx < nSubPixels; isbx++) { + // cout << ibx << " " << iby << " " << isbx << " " << + // isby << endl; + p[0] = isby * (nSubPixels + 1) + isbx; + p[1] = isby * (nSubPixels + 1) + isbx + 1; + p[2] = (isby + 1) * (nSubPixels + 1) + isbx + 1; + p[3] = (isby + 1) * (nSubPixels + 1) + isbx; + angle = 0; + for (int i = 0; i < 4; i++) { + p1x = vx[p[i]] - ibx; + p1y = vy[p[i]] - iby; + p2x = vx[p[(i + 1) % 4]] - ibx; + p2y = vy[p[(i + 1) % 4]] - iby; + theta1 = atan2(p1y, p1x); + theta2 = atan2(p2y, p2x); + dtheta = theta2 - theta1; - virtual void prepareInterpolation(int &ok) - { - ok=1; - cout << "Adaptive bins" << endl; + while (dtheta > PI) + dtheta -= TWOPI; + while (dtheta < -PI) + dtheta += TWOPI; - ///*Eta Distribution Rebinning*/// - double bsize=1./nSubPixels; //precision - // cout<<"nPixelsX = "<1 || etah[ii]<0 ) cout << "***"<< ii << + * etah[ii] << endl; */ + /* } */ + /* sprintf(tit,"/scratch/randeta_hhx_%d.tiff",iint); */ + /* WriteToTiff(etah, tit, etabins, etabins); */ -/* #ifdef SAVE_ALL */ -/* for (int ii=0; ii1 || etah[ii]<0 ) cout << "***"<< ii << etah[ii] << endl; */ -/* } */ -/* sprintf(tit,"/scratch/randeta_hhx_%d.tiff",iint); */ -/* WriteToTiff(etah, tit, etabins, etabins); */ - -/* for (int ii=0; ii1 || etah[ii]<0 ) cout << "***"<< ii << etah[ii] << endl; */ -/* } */ -/* sprintf(tit,"/scratch/randeta_hhy_%d.tiff",iint); */ -/* WriteToTiff(etah, tit, etabins, etabins); */ -/* #endif */ - - if (new_diff1 || etah[ii]<0 ) cout << "***"<< ii << + * etah[ii] << endl; */ + /* } */ + /* sprintf(tit,"/scratch/randeta_hhy_%d.tiff",iint); */ + /* WriteToTiff(etah, tit, etabins, etabins); */ + /* #endif */ - cout << "performed " << iint << " iterations of which " << igood << " positive " << endl; + if (new_diff < old_diff) { + cout << "******************** GOOD! ***********************" + << endl; + delete[] hhx; + delete[] hhy; + igood++; + hhx = newhhx; + hhy = newhhy; + newhhx = new float[nbeta * nbeta]; // profile x */ + newhhy = new float[nbeta * nbeta]; // profile y */ + old_diff = new_diff; + } else + ibad++; -/* #ifdef SAVE_ALL */ - + iint++; + } + delete[] newhhx; + delete[] newhhy; -/* for (int ii=0; ii - // ClassImp(EtaVEL); // double Median(const TH1D * histo1) { @@ -18,664 +17,747 @@ // return TMath::Median(numBins, x, y); // } +double *EtaVEL::getPixelCorners(int x, int y) { + double tlX, tlY, trX, trY, blX, blY, brX, brY; + tlX = xPPos[getCorner(x, y + 1)]; + tlY = yPPos[getCorner(x, y + 1)]; + trX = xPPos[getCorner(x + 1, y + 1)]; + trY = yPPos[getCorner(x + 1, y + 1)]; + blX = xPPos[getCorner(x, y)]; + blY = yPPos[getCorner(x, y)]; + brX = xPPos[getCorner(x + 1, y)]; + brY = yPPos[getCorner(x + 1, y)]; -double *EtaVEL::getPixelCorners(int x, int y){ - double tlX,tlY,trX,trY,blX,blY,brX,brY; - tlX = xPPos[getCorner(x,y+1)]; - tlY = yPPos[getCorner(x,y+1)]; - trX = xPPos[getCorner(x+1,y+1)]; - trY = yPPos[getCorner(x+1,y+1)]; - blX = xPPos[getCorner(x,y)]; - blY = yPPos[getCorner(x,y)]; - brX = xPPos[getCorner(x+1,y)]; - brY = yPPos[getCorner(x+1,y)]; + // cout << "gPC: TL: " << getCorner(x,y+1) << " TR: " << getCorner(x+1,y+1) + // << " BL " << getCorner(x,y) << " BR " << getCorner(x+1,y) << endl; - //cout << "gPC: TL: " << getCorner(x,y+1) << " TR: " << getCorner(x+1,y+1) << " BL " << getCorner(x,y) << " BR " << getCorner(x+1,y) << endl; - - double *c = new double[8]; - c[0] = tlX; c[1] = trX; c[2] = brX; c[3] = blX; - c[4] = tlY; c[5] = trY; c[6] = brY; c[7] = blY; - return c; + double *c = new double[8]; + c[0] = tlX; + c[1] = trX; + c[2] = brX; + c[3] = blX; + c[4] = tlY; + c[5] = trY; + c[6] = brY; + c[7] = blY; + return c; } +int EtaVEL::findBin(double xx, double yy) { -int EtaVEL::findBin(double xx, double yy){ + double tlX, tlY, trX, trY, blX, blY, brX, brY; + /********Added by anna ******/ + // if (xxmax) xx=max-1E-6; + // if (yymax) yy=max-1E-6; + /**************/ - double tlX,tlY,trX,trY,blX,blY,brX,brY; - /********Added by anna ******/ - // if (xxmax) xx=max-1E-6; - // if (yymax) yy=max-1E-6; - /**************/ + int bin = -1; + for (int x = 0; x < nPixels; x++) { + for (int y = 0; y < nPixels; y++) { + double *c = getPixelCorners(x, y); + tlX = c[0]; + trX = c[1]; + brX = c[2]; + blX = c[3]; + tlY = c[4]; + trY = c[5]; + brY = c[6]; + blY = c[7]; + /// if(y == 0){ + // cout << "x: " << x << " blY " << blY << " brY " << brY << endl; + //} - int bin = -1; - for(int x = 0; x < nPixels; x++){ - for(int y = 0; y < nPixels; y++){ - double *c = getPixelCorners(x,y); - tlX = c[0]; trX = c[1]; brX = c[2]; blX = c[3]; - tlY = c[4]; trY = c[5]; brY = c[6]; blY = c[7]; + int out = 0; - ///if(y == 0){ - // cout << "x: " << x << " blY " << blY << " brY " << brY << endl; - //} - - int out = 0; - - double tb = 0; - double bb = 0; - double lb = 0; - double rb = 0; - - if((trX-tlX)>0.) - tb = (trY - tlY)/(trX-tlX); - - if((brX-blX)>0.) - bb = (brY - blY)/(brX-blX); - - if((tlY-blY)>0.) - lb = (tlX - blX)/(tlY-blY); - - if((trY-brY)>0.) - rb = (trX - brX)/(trY-brY); - - double ty = tlY + tb * (xx - tlX); - double by = blY + bb * (xx - blX); - - double lx = blX + lb * (yy - blY); - double rx = brX + rb * (yy - brY); - - + double tb = 0; + double bb = 0; + double lb = 0; + double rb = 0; + if ((trX - tlX) > 0.) + tb = (trY - tlY) / (trX - tlX); - if(yy >= ty) out++; - if(yy < by) out++; - if(xx < lx) out++; - if(xx >= rx) out++; - - //cout << "ty " << ty << endl; - //cout << "by " << by << endl; - //cout << "lx " << lx << endl; - //cout << "rx " << rx << endl; + if ((brX - blX) > 0.) + bb = (brY - blY) / (brX - blX); - //double dist = (xx - xPPos[getBin(x,y)]) * (xx - xPPos[getBin(x,y)]) + (yy - yPPos[getBin(x,y)]) * (yy - yPPos[getBin(x,y)]); - //cout << "x " << x << " y " << y << " out " << out << " ty " << ty << endl; - //cout << "tl " << tlX << "/" << tlY << " tr " << trX << "/" << trY << endl; - //cout << "bl " << blX << "/" << blY << " br " << brX << "/" << brY << endl; + if ((tlY - blY) > 0.) + lb = (tlX - blX) / (tlY - blY); - //cout << " tb " << tb << endl; + if ((trY - brY) > 0.) + rb = (trX - brX) / (trY - brY); + double ty = tlY + tb * (xx - tlX); + double by = blY + bb * (xx - blX); - delete[] c; - if(out == 0){ return getBin(x,y); } + double lx = blX + lb * (yy - blY); + double rx = brX + rb * (yy - brY); + + if (yy >= ty) + out++; + if (yy < by) + out++; + if (xx < lx) + out++; + if (xx >= rx) + out++; + + // cout << "ty " << ty << endl; + // cout << "by " << by << endl; + // cout << "lx " << lx << endl; + // cout << "rx " << rx << endl; + + // double dist = (xx - xPPos[getBin(x,y)]) * (xx - + // xPPos[getBin(x,y)]) + (yy - yPPos[getBin(x,y)]) * (yy - + // yPPos[getBin(x,y)]); cout << "x " << x << " y " << y << " out " + // << out << " ty " << ty << endl; cout << "tl " << tlX << "/" << + // tlY << " tr " << trX << "/" << trY << endl; cout << "bl " << blX + // << "/" << blY << " br " << brX << "/" << brY << endl; + + // cout << " tb " << tb << endl; + + delete[] c; + if (out == 0) { + return getBin(x, y); + } + } } - } - return -1; + return -1; } -void EtaVEL::createLogEntry(){ - if(it >= nIterations){ - cerr << "log full" << endl; - } - log[it].itN = it; - log[it].xPos = new double[nPixels*nPixels+1]; - log[it].yPos = new double[nPixels*nPixels+1]; - log[it].binCont = new double[nPixels*nPixels+1]; - for(int x = 0; x < nPixels; x++) - for(int y = 0; y < nPixels; y++){ - log[it].xPos[getBin(x,y)] = xPPos[getBin(x,y)]; - log[it].yPos[getBin(x,y)] = yPPos[getBin(x,y)]; - log[it].binCont[getBin(x,y)] = binCont[getBin(x,y)]; +void EtaVEL::createLogEntry() { + if (it >= nIterations) { + cerr << "log full" << endl; } - it++; + log[it].itN = it; + log[it].xPos = new double[nPixels * nPixels + 1]; + log[it].yPos = new double[nPixels * nPixels + 1]; + log[it].binCont = new double[nPixels * nPixels + 1]; + for (int x = 0; x < nPixels; x++) + for (int y = 0; y < nPixels; y++) { + log[it].xPos[getBin(x, y)] = xPPos[getBin(x, y)]; + log[it].yPos[getBin(x, y)] = yPPos[getBin(x, y)]; + log[it].binCont[getBin(x, y)] = binCont[getBin(x, y)]; + } + it++; } -void EtaVEL::updatePixelCorner(){ - double w = 20; - int rows = (nPixels+1)*(nPixels+1) + 4 + 4 * 4;//(4*(nPixels+1))-4; - int cols = (nPixels+1)*(nPixels+1); +void EtaVEL::updatePixelCorner() { + double w = 20; + int rows = (nPixels + 1) * (nPixels + 1) + 4 + 4 * 4; //(4*(nPixels+1))-4; + int cols = (nPixels + 1) * (nPixels + 1); - double *rVx = new double[rows]; - double *rVy = new double[rows]; - - double *posMat = new double[rows*cols]; - for(int i = 0 ; i < rows*cols; i++) posMat[i] = 0; - int boundaryPoint = 0; + double *rVx = new double[rows]; + double *rVy = new double[rows]; - cout << "linear sys stuff" << endl; + double *posMat = new double[rows * cols]; + for (int i = 0; i < rows * cols; i++) + posMat[i] = 0; + int boundaryPoint = 0; - double minELength = 100000000000000; int minX=-1, minY=-1; + cout << "linear sys stuff" << endl; - for(int y = 0; y < nPixels+1; y++){ - for(int x = 0; x < nPixels+1; x++){ - double bx = 0, by = 0; + double minELength = 100000000000000; + int minX = -1, minY = -1; - //boundary conditions + for (int y = 0; y < nPixels + 1; y++) { + for (int x = 0; x < nPixels + 1; x++) { + double bx = 0, by = 0; - if((x == 0 && y % 5 == 0) || - (x == nPixels && y % 5 == 0) || - (y == 0 && x % 5 == 0) || - (y == nPixels && x % 5 == 0)){ + // boundary conditions - bx = xPPos[getCorner(x,y)]; - //cout << "bP " << boundaryPoint << " bx " << bx << endl; - by = yPPos[getCorner(x,y)]; - rVx[(nPixels+1)*(nPixels+1) + boundaryPoint] = bx*w; - rVy[(nPixels+1)*(nPixels+1) + boundaryPoint] = by*w; - posMat[(nPixels+1)*(nPixels+1)*cols + boundaryPoint * cols + getCorner(x,y)-1] = w; - boundaryPoint++; - } + if ((x == 0 && y % 5 == 0) || (x == nPixels && y % 5 == 0) || + (y == 0 && x % 5 == 0) || (y == nPixels && x % 5 == 0)) { - double tot = 4 - (x == 0) - (y == 0) - (x == nPixels) - (y == nPixels); - //cout << "totW: " << tot << endl; - //tot = 4.; - double eLength = 0; - if(x != 0) eLength += edgeL[getEdgeX(x-1,y)]; - if(y != 0) eLength += edgeL[getEdgeY(x,y-1)]; - if(x != nPixels) eLength += edgeL[getEdgeX(x,y)]; - if(y != nPixels) eLength += edgeL[getEdgeY(x,y)]; + bx = xPPos[getCorner(x, y)]; + // cout << "bP " << boundaryPoint << " bx " << bx << endl; + by = yPPos[getCorner(x, y)]; + rVx[(nPixels + 1) * (nPixels + 1) + boundaryPoint] = bx * w; + rVy[(nPixels + 1) * (nPixels + 1) + boundaryPoint] = by * w; + posMat[(nPixels + 1) * (nPixels + 1) * cols + + boundaryPoint * cols + getCorner(x, y) - 1] = w; + boundaryPoint++; + } - /*cout << "Corner X:" <Print(); - k->SetMatrixArray(posMat); - // k->Print(); + TMatrixD *k = new TMatrixD(rows, cols); + TVectorD *fx = new TVectorD(rows, rVx); + TVectorD *fy = new TVectorD(rows, rVy); + // f->Print(); + k->SetMatrixArray(posMat); + // k->Print(); + // solve linear system - //solve linear system + Bool_t ok; + TDecompSVD *s = new TDecompSVD(*k); + s->Solve(*fx); + s->Solve(*fy); - Bool_t ok; - TDecompSVD *s = new TDecompSVD(*k); - s->Solve(*fx); - s->Solve(*fy); + double *fxA = fx->GetMatrixArray(); + double *fyA = fy->GetMatrixArray(); - double *fxA = fx->GetMatrixArray(); - double *fyA = fy->GetMatrixArray(); - + for (int y = 0; y < nPixels + 1; y++) { + for (int x = 0; x < nPixels + 1; x++) { + // do not update boundaries - for(int y = 0; y < nPixels+1; y++){ - for(int x = 0; x < nPixels+1; x++){ - //do not update boundaries - - if(!(x == 0 || - x == nPixels|| - y == 0 || - y == nPixels)){ - xPPos[getCorner(x,y)] = fxA[getCorner(x,y)-1]; - yPPos[getCorner(x,y)] = fyA[getCorner(x,y)-1]; - } + if (!(x == 0 || x == nPixels || y == 0 || y == nPixels)) { + xPPos[getCorner(x, y)] = fxA[getCorner(x, y) - 1]; + yPPos[getCorner(x, y)] = fyA[getCorner(x, y) - 1]; + } + } } - } } -void EtaVEL::updatePixelPos(){ - double xMov, yMov, d1Mov, d2Mov; - createLogEntry(); - double *chMap = getChangeMap(); - int ch =0; +void EtaVEL::updatePixelPos() { + double xMov, yMov, d1Mov, d2Mov; + createLogEntry(); + double *chMap = getChangeMap(); + int ch = 0; - cout << "update edge lengths" << endl; - for(int x = 0; x < nPixels; x++) - for(int y = 0; y < nPixels; y++){ - + cout << "update edge lengths" << endl; + for (int x = 0; x < nPixels; x++) + for (int y = 0; y < nPixels; y++) { - /*cout << "Pixel X:" < 0. & totCont > 0.){ - dd=sqrt(r/avg); - /**Added by Anna */ - if (dd>2.) dd=1.5; - if (dd<0.5) dd=0.75; - chMap[getBin(x,y)] = dd; - /** */ - //if( chMap[getBin(x,y)] < 1.){ chMap[getBin(x,y)] = 1/1.2; } - //if( chMap[getBin(x,y)] > 1.){ chMap[getBin(x,y)] = 1.2; } - //if( chMap[getBin(x,y)] < 1/1.2){ chMap[getBin(x,y)] = 1/1.2; } - //if( chMap[getBin(x,y)] > 1.2){ chMap[getBin(x,y)] = 1.2; } - }else if(totCont > 0.){ - chMap[getBin(x,y)] =0.5; //1/1.2; - }else{ - chMap[getBin(x,y)] = 1.; - } - - //if(r < avg + 2*acc && r > avg - 2*acc){ totInRange++;}// chMap[getBin(x,y)] = 1.; } + for (int x = 0; x < nPixels; x++) { + for (int y = 0; y < nPixels; y++) { + totInBins += binCont[getBin(x, y)]; + double r = (double)binCont[getBin(x, y)]; + if (r > 0. & totCont > 0.) { + dd = sqrt(r / avg); + /**Added by Anna */ + if (dd > 2.) + dd = 1.5; + if (dd < 0.5) + dd = 0.75; + chMap[getBin(x, y)] = dd; + /** */ + // if( chMap[getBin(x,y)] < 1.){ chMap[getBin(x,y)] = 1/1.2; } + // if( chMap[getBin(x,y)] > 1.){ chMap[getBin(x,y)] = 1.2; } + // if( chMap[getBin(x,y)] < 1/1.2){ chMap[getBin(x,y)] = 1/1.2; + // } if( chMap[getBin(x,y)] > 1.2){ chMap[getBin(x,y)] = 1.2; } + } else if (totCont > 0.) { + chMap[getBin(x, y)] = 0.5; // 1/1.2; + } else { + chMap[getBin(x, y)] = 1.; + } - /** Commente away by Anna - if(converged == 0 && r < med+20*acc){ chMap[getBin(x,y)] = 1.; } - if(converged == 2 && r < med+20*acc && r > med-03*acc){ chMap[getBin(x,y)] = 1.; } - if(r < med+03*acc){ totInRange03s++; } - if(r < med+07*acc){ totInRange07s++; } - if(r < med+12*acc){ totInRange12s++; } - if(r < med+20*acc){ totInRange20s++; } - if(r < med+25*acc){ totInRange25s++; } - */ + // if(r < avg + 2*acc && r > avg - 2*acc){ totInRange++;}// + // chMap[getBin(x,y)] = 1.; } - //cout << "x " << x << " y " << y << " r " << r << " ch " << chMap[getBin(x,y)] << endl; - // if(r - avg > acc){ totOffAcc += r-avg;} - //if(r - avg < -acc){ totOffAcc += avg-r;} - totOffAcc += (avg-r)*(avg-r); - chi_sq+=(avg-r)*(avg-r)/r; - //cout << " x " << x << " y " << y << " bC " << binCont[x*nPixels+y] << " r " << r << endl; + /** Commente away by Anna + if(converged == 0 && r < med+20*acc){ chMap[getBin(x,y)] = 1.; } + if(converged == 2 && r < med+20*acc && r > med-03*acc){ + chMap[getBin(x,y)] = 1.; } if(r < med+03*acc){ totInRange03s++; } + if(r < med+07*acc){ totInRange07s++; } + if(r < med+12*acc){ totInRange12s++; } + if(r < med+20*acc){ totInRange20s++; } + if(r < med+25*acc){ totInRange25s++; } + */ - if(r > maxC){ maxC = r; maxX = x; maxY = y; } - if(r < minC){minC = r; minX = x; minY = y; } + // cout << "x " << x << " y " << y << " r " << r << " ch " << + // chMap[getBin(x,y)] << endl; + // if(r - avg > acc){ totOffAcc += r-avg;} + // if(r - avg < -acc){ totOffAcc += avg-r;} + totOffAcc += (avg - r) * (avg - r); + chi_sq += (avg - r) * (avg - r) / r; + // cout << " x " << x << " y " << y << " bC " << + // binCont[x*nPixels+y] << " r " << r << endl; + if (r > maxC) { + maxC = r; + maxX = x; + maxY = y; + } + if (r < minC) { + minC = r; + minX = x; + minY = y; + } + } } - } - // cout << "totInBins " << totInBins << " zero Bin " << binCont[0] << endl; - cout << "AvgOffAcc: " << sqrt(totOffAcc/(double)(nPixels*nPixels)) << endl; - cout << "***********Reduced Chi Square: " << chi_sq/((double)(nPixels*nPixels)) << endl; - // cout << "totInRange03 (<" << med+03*acc << "): " << totInRange03s << endl; - // cout << "totInRange07 (<" << med+07*acc << "): " << totInRange07s << endl; - // cout << "totInRange12 (<" << med+12*acc << "): " << totInRange12s << endl; - // cout << "totInRange20 (<" << med+20*acc << "): " << totInRange20s << endl; - // cout << "totInRange25 (<" << med+25*acc << "): " << totInRange25s << endl; - double maxSig = (maxC - avg)*(maxC - avg) / avg;//acc; - double minSig = (avg - minC)*(avg - minC) / avg;//acc; - cout << "Max Pixel X: " << maxX << " Y: " << maxY << " P# " << getBin(maxX,maxY) << " count: " << maxC << " sig: "<< maxSig << endl; - cout << "Min Pixel X: " << minX << " Y: " << minY << " P# " << getBin(minX,minY) << " count: " << minC << " sig: "<< minSig << endl; + // cout << "totInBins " << totInBins << " zero Bin " << binCont[0] << endl; + cout << "AvgOffAcc: " << sqrt(totOffAcc / (double)(nPixels * nPixels)) + << endl; + cout << "***********Reduced Chi Square: " + << chi_sq / ((double)(nPixels * nPixels)) << endl; + // cout << "totInRange03 (<" << med+03*acc << "): " << totInRange03s << + // endl; cout << "totInRange07 (<" << med+07*acc << "): " << totInRange07s + // << endl; cout << "totInRange12 (<" << med+12*acc << "): " << + // totInRange12s << endl; cout << "totInRange20 (<" << med+20*acc << "): " + // << totInRange20s << endl; cout << "totInRange25 (<" << med+25*acc << "): + // " << totInRange25s << endl; + double maxSig = (maxC - avg) * (maxC - avg) / avg; // acc; + double minSig = (avg - minC) * (avg - minC) / avg; // acc; + cout << "Max Pixel X: " << maxX << " Y: " << maxY << " P# " + << getBin(maxX, maxY) << " count: " << maxC << " sig: " << maxSig + << endl; + cout << "Min Pixel X: " << minX << " Y: " << minY << " P# " + << getBin(minX, minY) << " count: " << minC << " sig: " << minSig + << endl; - // if(maxSig <= 25){ converged = 2; cout << "reached first converstion step!!!" << endl; } - //if(minSig <= 7 && converged == 2) { converged = 1; } - if (chi_sq<3) converged=2; - if (chi_sq<1) converged=1; - cout << "Conversion step "<< converged << endl; - return chMap; + // if(maxSig <= 25){ converged = 2; cout << "reached first converstion + // step!!!" << endl; } + // if(minSig <= 7 && converged == 2) { converged = 1; } + if (chi_sq < 3) + converged = 2; + if (chi_sq < 1) + converged = 1; + cout << "Conversion step " << converged << endl; + return chMap; } -TH2D *EtaVEL::getContent(int it, int changeType){ - TH2D *cont = new TH2D("cont","cont",nPixels,min,max,nPixels,min,max); - double *chMap = NULL; - if(changeType ==1) chMap = getChangeMap(); - double *szMap = getSizeMap(); - for(int x = 0; x < nPixels; x++) - for(int y = 0; y < nPixels; y++){ - if(changeType ==2 ){ - cont->SetBinContent(x+1,y+1,szMap[getBin(x,y)]); - } - if(changeType ==1 ){ - cont->SetBinContent(x+1,y+1,chMap[getBin(x,y)]); - } - if(changeType ==0 ){ - if(it == -1){ - cont->SetBinContent(x+1,y+1,binCont[getBin(x,y)]); - //cout << "x " << x << " y " << y << " cont " << binCont[getBin(x,y)] << endl; - } - else{cont->SetBinContent(x+1,y+1,log[it].binCont[getBin(x,y)]);} - } - } - return cont; +TH2D *EtaVEL::getContent(int it, int changeType) { + TH2D *cont = new TH2D("cont", "cont", nPixels, min, max, nPixels, min, max); + double *chMap = NULL; + if (changeType == 1) + chMap = getChangeMap(); + double *szMap = getSizeMap(); + for (int x = 0; x < nPixels; x++) + for (int y = 0; y < nPixels; y++) { + if (changeType == 2) { + cont->SetBinContent(x + 1, y + 1, szMap[getBin(x, y)]); + } + if (changeType == 1) { + cont->SetBinContent(x + 1, y + 1, chMap[getBin(x, y)]); + } + if (changeType == 0) { + if (it == -1) { + cont->SetBinContent(x + 1, y + 1, binCont[getBin(x, y)]); + // cout << "x " << x << " y " << y << " cont " << + // binCont[getBin(x,y)] << endl; + } else { + cont->SetBinContent(x + 1, y + 1, + log[it].binCont[getBin(x, y)]); + } + } + } + return cont; } -TH1D *EtaVEL::getCounts(){ - TH1D *ch = new TH1D("ch","ch",500,0,totCont/(nPixels*nPixels)*4); - for(int x = 0; x < nPixels; x++) - for(int y = 0; y < nPixels; y++){ - ch->Fill(binCont[getBin(x,y)]); - } - return ch; - +TH1D *EtaVEL::getCounts() { + TH1D *ch = new TH1D("ch", "ch", 500, 0, totCont / (nPixels * nPixels) * 4); + for (int x = 0; x < nPixels; x++) + for (int y = 0; y < nPixels; y++) { + ch->Fill(binCont[getBin(x, y)]); + } + return ch; } -void EtaVEL::printGrid(){ +void EtaVEL::printGrid() { - double *colSum = new double[nPixels+1]; - double *rowSum = new double[nPixels+1]; + double *colSum = new double[nPixels + 1]; + double *rowSum = new double[nPixels + 1]; - for(int i = 0; i < nPixels+1; i++){ - colSum[i] = 0.; - rowSum[i] = 0.; - for(int j = 0; j < nPixels; j++){ - rowSum[i] += edgeL[getEdgeX(j,i)]; - colSum[i] += edgeL[getEdgeY(i,j)]; - } - } - - cout << endl; - - cout.precision(3); cout << fixed; - cout << " "; - for(int x = 0; x < nPixels+1; x++){ - cout << setw(2) << x << " (" << colSum[x] << ") "; - } - cout << endl; - for(int y = 0; y < nPixels+1; y++){ - cout << setw(2) << y << " "; - for(int x = 0; x < nPixels+1; x++){ - cout << "(" << xPPos[getCorner(x,y)] << "/" << yPPos[getCorner(x,y)] << ") " ; - if(x < nPixels) cout << " -- " << edgeL[getEdgeX(x,y)]/rowSum[y]*(max-min) << " -- "; - } - cout << " | " << rowSum[y] << endl; - - if(y < nPixels){ - cout << " "; - for(int x = 0; x < nPixels+1; x++){ - cout << edgeL[getEdgeY(x,y)]/colSum[x]*(max-min) << " "; - } - cout << endl; + for (int i = 0; i < nPixels + 1; i++) { + colSum[i] = 0.; + rowSum[i] = 0.; + for (int j = 0; j < nPixels; j++) { + rowSum[i] += edgeL[getEdgeX(j, i)]; + colSum[i] += edgeL[getEdgeY(i, j)]; + } } - } - delete[] colSum; - delete[] rowSum; + cout << endl; + cout.precision(3); + cout << fixed; + cout << " "; + for (int x = 0; x < nPixels + 1; x++) { + cout << setw(2) << x << " (" << colSum[x] << ") "; + } + cout << endl; + for (int y = 0; y < nPixels + 1; y++) { + cout << setw(2) << y << " "; + for (int x = 0; x < nPixels + 1; x++) { + cout << "(" << xPPos[getCorner(x, y)] << "/" + << yPPos[getCorner(x, y)] << ") "; + if (x < nPixels) + cout << " -- " + << edgeL[getEdgeX(x, y)] / rowSum[y] * (max - min) + << " -- "; + } + cout << " | " << rowSum[y] << endl; + + if (y < nPixels) { + cout << " "; + for (int x = 0; x < nPixels + 1; x++) { + cout << edgeL[getEdgeY(x, y)] / colSum[x] * (max - min) + << " "; + } + cout << endl; + } + } + delete[] colSum; + delete[] rowSum; } -TMultiGraph *EtaVEL::plotPixelBorder(int plotCenters){ - TMultiGraph *mg = new TMultiGraph(); - double cx[5], cy[5]; - for(int x = 0; x < nPixels; x++) - for(int y = 0; y < nPixels; y++){ - double *c = getPixelCorners(x,y); - cx[0]=c[0]; cx[1]=c[1]; cx[2]=c[2]; cx[3]=c[3]; cx[4]=c[0]; - cy[0]=c[4]; cy[1]=c[5]; cy[2]=c[6]; cy[3]=c[7]; cy[4]=c[4]; +TMultiGraph *EtaVEL::plotPixelBorder(int plotCenters) { + TMultiGraph *mg = new TMultiGraph(); + double cx[5], cy[5]; + for (int x = 0; x < nPixels; x++) + for (int y = 0; y < nPixels; y++) { + double *c = getPixelCorners(x, y); + cx[0] = c[0]; + cx[1] = c[1]; + cx[2] = c[2]; + cx[3] = c[3]; + cx[4] = c[0]; + cy[0] = c[4]; + cy[1] = c[5]; + cy[2] = c[6]; + cy[3] = c[7]; + cy[4] = c[4]; - - TGraph *g = new TGraph(5,cx,cy); - mg->Add(g); - if(plotCenters){ - g = new TGraph(1,&(xPPos[getBin(x,y)]),&(yPPos[getBin(x,y)])); - mg->Add(g); - } - delete[] c; - } - return mg; + TGraph *g = new TGraph(5, cx, cy); + mg->Add(g); + if (plotCenters) { + g = new TGraph(1, &(xPPos[getBin(x, y)]), + &(yPPos[getBin(x, y)])); + mg->Add(g); + } + delete[] c; + } + return mg; } -TMultiGraph *EtaVEL::plotLog(int stepSize, int maxIt){ - int mIt; - TMultiGraph *mg = new TMultiGraph(); - double **xposl = new double*[nPixels*nPixels+1]; - double **yposl = new double*[nPixels*nPixels+1]; - if(maxIt==-1){ mIt = it; } else{ mIt = maxIt; }; - cout << "mIt " << mIt << " steps " << mIt/stepSize << endl; - for(int x = 0; x < nPixels; x++){ - for(int y = 0; y < nPixels; y++){ - xposl[getBin(x,y)] = new double[mIt/stepSize]; - yposl[getBin(x,y)] = new double[mIt/stepSize]; - for(int i = 0; i < mIt/stepSize; i++){ - xposl[getBin(x,y)][i] = log[i*stepSize].xPos[getBin(x,y)]; - yposl[getBin(x,y)][i] = log[i*stepSize].yPos[getBin(x,y)]; - } - TGraph *g = new TGraph(mIt/stepSize,xposl[getBin(x,y)],yposl[getBin(x,y)]); - g->SetLineColor((x*y % 9) + 1); - - if(x == 0) g->SetLineColor(2); - if(y == 0) g->SetLineColor(3); - if(x == nPixels-1) g->SetLineColor(4); - if(y == nPixels-1) g->SetLineColor(5); - mg->Add(g); +TMultiGraph *EtaVEL::plotLog(int stepSize, int maxIt) { + int mIt; + TMultiGraph *mg = new TMultiGraph(); + double **xposl = new double *[nPixels * nPixels + 1]; + double **yposl = new double *[nPixels * nPixels + 1]; + if (maxIt == -1) { + mIt = it; + } else { + mIt = maxIt; + }; + cout << "mIt " << mIt << " steps " << mIt / stepSize << endl; + for (int x = 0; x < nPixels; x++) { + for (int y = 0; y < nPixels; y++) { + xposl[getBin(x, y)] = new double[mIt / stepSize]; + yposl[getBin(x, y)] = new double[mIt / stepSize]; + for (int i = 0; i < mIt / stepSize; i++) { + xposl[getBin(x, y)][i] = log[i * stepSize].xPos[getBin(x, y)]; + yposl[getBin(x, y)][i] = log[i * stepSize].yPos[getBin(x, y)]; + } + TGraph *g = new TGraph(mIt / stepSize, xposl[getBin(x, y)], + yposl[getBin(x, y)]); + g->SetLineColor((x * y % 9) + 1); + + if (x == 0) + g->SetLineColor(2); + if (y == 0) + g->SetLineColor(3); + if (x == nPixels - 1) + g->SetLineColor(4); + if (y == nPixels - 1) + g->SetLineColor(5); + mg->Add(g); + } } - } - return mg; + return mg; } -void EtaVEL::serialize(ostream &o){ - // b.WriteVersion(EtaVEL::IsA()); - char del = '|'; - o << min << del; - o << max << del; - o << ds << del; - o << nPixels << del; - o << it << del; - o << totCont << del; - for(int i = 0; i < (nPixels+1)*(nPixels+1)+1; i++){ - o << xPPos[i] << del; - o << yPPos[i] << del; - } - for(int i = 0; i < nPixels*nPixels+1; i++){ - o << binCont[i] << del; - } +void EtaVEL::serialize(ostream &o) { + // b.WriteVersion(EtaVEL::IsA()); + char del = '|'; + o << min << del; + o << max << del; + o << ds << del; + o << nPixels << del; + o << it << del; + o << totCont << del; + for (int i = 0; i < (nPixels + 1) * (nPixels + 1) + 1; i++) { + o << xPPos[i] << del; + o << yPPos[i] << del; + } + for (int i = 0; i < nPixels * nPixels + 1; i++) { + o << binCont[i] << del; + } - for(int i = 0; i < it; i++){ - o << log[i].itN << del; - for(int j = 0; j < (nPixels+1)*(nPixels+1)+1; j++){ - o << log[i].xPos[j] << del; - o << log[i].yPos[j] << del; - } - for(int j = 0; j < nPixels*nPixels+1; j++){ - o << log[i].binCont[j] << del; - } - } + for (int i = 0; i < it; i++) { + o << log[i].itN << del; + for (int j = 0; j < (nPixels + 1) * (nPixels + 1) + 1; j++) { + o << log[i].xPos[j] << del; + o << log[i].yPos[j] << del; + } + for (int j = 0; j < nPixels * nPixels + 1; j++) { + o << log[i].binCont[j] << del; + } + } } -void EtaVEL::deserialize(istream &is){ - delete[] xPPos; - delete[] yPPos; - delete[] binCont; +void EtaVEL::deserialize(istream &is) { + delete[] xPPos; + delete[] yPPos; + delete[] binCont; - char del; + char del; - is >> min >> del; - is >> max >> del; - is >> ds >> del; - is >> nPixels >> del; - is >> it >> del; - is >> totCont >> del; - - xPPos = new double[(nPixels+1)*(nPixels+1)+1]; - yPPos = new double[(nPixels+1)*(nPixels+1)+1]; - binCont = new double[nPixels*nPixels+1]; + is >> min >> del; + is >> max >> del; + is >> ds >> del; + is >> nPixels >> del; + is >> it >> del; + is >> totCont >> del; - cout << "d"; + xPPos = new double[(nPixels + 1) * (nPixels + 1) + 1]; + yPPos = new double[(nPixels + 1) * (nPixels + 1) + 1]; + binCont = new double[nPixels * nPixels + 1]; - for(int i = 0; i < (nPixels+1)*(nPixels+1)+1; i++){ - is >> xPPos[i] >> del; - is >> yPPos[i] >> del; - } - - cout << "d"; - - for(int i = 0; i < nPixels*nPixels+1; i++){ - is >> binCont[i] >> del; - } - - cout << "d"; - - for(int i = 0; i < it; i++){ - is >> log[i].itN >> del; - log[i].xPos = new double[(nPixels+1)*(nPixels+1)+1]; - log[i].yPos = new double[(nPixels+1)*(nPixels+1)+1]; - log[i].binCont = new double[nPixels*nPixels+1]; - - for(int j = 0; j < (nPixels+1)*(nPixels+1)+1; j++){ - is >> log[i].xPos[j] >> del; - is >> log[i].yPos[j] >> del; - } - for(int j = 0; j < nPixels*nPixels+1; j++){ - is >> log[i].binCont[j] >> del; - } cout << "d"; - } - cout << endl; + + for (int i = 0; i < (nPixels + 1) * (nPixels + 1) + 1; i++) { + is >> xPPos[i] >> del; + is >> yPPos[i] >> del; + } + + cout << "d"; + + for (int i = 0; i < nPixels * nPixels + 1; i++) { + is >> binCont[i] >> del; + } + + cout << "d"; + + for (int i = 0; i < it; i++) { + is >> log[i].itN >> del; + log[i].xPos = new double[(nPixels + 1) * (nPixels + 1) + 1]; + log[i].yPos = new double[(nPixels + 1) * (nPixels + 1) + 1]; + log[i].binCont = new double[nPixels * nPixels + 1]; + + for (int j = 0; j < (nPixels + 1) * (nPixels + 1) + 1; j++) { + is >> log[i].xPos[j] >> del; + is >> log[i].yPos[j] >> del; + } + for (int j = 0; j < nPixels * nPixels + 1; j++) { + is >> log[i].binCont[j] >> del; + } + cout << "d"; + } + cout << endl; } -void EtaVEL::Streamer(TBuffer &b){ - if (b.IsReading()) { - Version_t v = b.ReadVersion(); - - delete[] xPPos; - delete[] yPPos; - delete[] binCont; +void EtaVEL::Streamer(TBuffer &b) { + if (b.IsReading()) { + Version_t v = b.ReadVersion(); - b >> min; - b >> max; - b >> ds; - b >> nPixels; - b >> it; - b >> totCont; + delete[] xPPos; + delete[] yPPos; + delete[] binCont; - xPPos = new double[(nPixels+1)*(nPixels+1)+1]; - yPPos = new double[(nPixels+1)*(nPixels+1)+1]; - binCont = new double[nPixels*nPixels+1]; + b >> min; + b >> max; + b >> ds; + b >> nPixels; + b >> it; + b >> totCont; - for(int i = 0; i < (nPixels+1)*(nPixels+1)+1; i++){ - b >> xPPos[i]; - b >> yPPos[i]; - } - for(int i = 0; i < nPixels*nPixels+1; i++){ - b >> binCont[i]; - } + xPPos = new double[(nPixels + 1) * (nPixels + 1) + 1]; + yPPos = new double[(nPixels + 1) * (nPixels + 1) + 1]; + binCont = new double[nPixels * nPixels + 1]; - for(int i = 0; i < it; i++){ - b >> log[i].itN; - log[i].xPos = new double[(nPixels+1)*(nPixels+1)+1]; - log[i].yPos = new double[(nPixels+1)*(nPixels+1)+1]; - log[i].binCont = new double[nPixels*nPixels+1]; + for (int i = 0; i < (nPixels + 1) * (nPixels + 1) + 1; i++) { + b >> xPPos[i]; + b >> yPPos[i]; + } + for (int i = 0; i < nPixels * nPixels + 1; i++) { + b >> binCont[i]; + } - for(int j = 0; j < (nPixels+1)*(nPixels+1)+1; j++){ - b >> log[i].xPos[j]; - b >> log[i].yPos[j]; - } - for(int j = 0; j < nPixels*nPixels+1; j++){ - b >> log[i].binCont[j]; - } - } + for (int i = 0; i < it; i++) { + b >> log[i].itN; + log[i].xPos = new double[(nPixels + 1) * (nPixels + 1) + 1]; + log[i].yPos = new double[(nPixels + 1) * (nPixels + 1) + 1]; + log[i].binCont = new double[nPixels * nPixels + 1]; - } else { - b.WriteVersion(EtaVEL::IsA()); - b << min; - b << max; - b << ds; - b << nPixels; - b << it; - b << totCont; - for(int i = 0; i < (nPixels+1)*(nPixels+1)+1; i++){ - b << xPPos[i]; - b << yPPos[i]; - } - for(int i = 0; i < nPixels*nPixels+1; i++){ - b << binCont[i]; - } + for (int j = 0; j < (nPixels + 1) * (nPixels + 1) + 1; j++) { + b >> log[i].xPos[j]; + b >> log[i].yPos[j]; + } + for (int j = 0; j < nPixels * nPixels + 1; j++) { + b >> log[i].binCont[j]; + } + } - for(int i = 0; i < it; i++){ - b << log[i].itN; - for(int j = 0; j < (nPixels+1)*(nPixels+1)+1; j++){ - b << log[i].xPos[j]; - b << log[i].yPos[j]; - } - for(int j = 0; j < nPixels*nPixels+1; j++){ - b << log[i].binCont[j]; - } - } - } + } else { + b.WriteVersion(EtaVEL::IsA()); + b << min; + b << max; + b << ds; + b << nPixels; + b << it; + b << totCont; + for (int i = 0; i < (nPixels + 1) * (nPixels + 1) + 1; i++) { + b << xPPos[i]; + b << yPPos[i]; + } + for (int i = 0; i < nPixels * nPixels + 1; i++) { + b << binCont[i]; + } + + for (int i = 0; i < it; i++) { + b << log[i].itN; + for (int j = 0; j < (nPixels + 1) * (nPixels + 1) + 1; j++) { + b << log[i].xPos[j]; + b << log[i].yPos[j]; + } + for (int j = 0; j < nPixels * nPixels + 1; j++) { + b << log[i].binCont[j]; + } + } + } } - diff --git a/slsDetectorCalibration/interpolations/etaVEL/EtaVEL.h b/slsDetectorCalibration/interpolations/etaVEL/EtaVEL.h index d2c31d803..5a850e31a 100644 --- a/slsDetectorCalibration/interpolations/etaVEL/EtaVEL.h +++ b/slsDetectorCalibration/interpolations/etaVEL/EtaVEL.h @@ -1,26 +1,25 @@ // SPDX-License-Identifier: LGPL-3.0-or-other // Copyright (C) 2021 Contributors to the SLS Detector Package -#include -#include #include -#include +#include +#include #include #include +#include #include -#include +#include #include #include //#include - #include #include #include -#include #include +#include using namespace std; @@ -28,139 +27,133 @@ using namespace std; #define ETAVPS typedef struct { - int itN; - double *xPos; - double *yPos; - double *binCont; + int itN; + double *xPos; + double *yPos; + double *binCont; } itLog; +class EtaVEL : public TObject { + public: + EtaVEL(int numberOfPixels = 25, double minn = 0., double maxx = 1., + int nnx = 160, int nny = 160) + : nPixels(numberOfPixels), min(minn), max(maxx), converged(0), nx(nnx), + ny(nny), chi_sq(0) { + // acc = 0.02; + ds = 0.005; -class EtaVEL : public TObject{ + init(); + } + void init() { + double pOffset = (max - min) / (double)nPixels; + xPPos = new double[(nPixels + 1) * (nPixels + 1) + 1]; + yPPos = new double[(nPixels + 1) * (nPixels + 1) + 1]; + binCont = new double[nPixels * nPixels + 1]; + totCont = 0.; + edgeL = new double[2 * nPixels * (nPixels + 1) + 1]; - public: - EtaVEL(int numberOfPixels = 25, double minn=0., double maxx=1., int nnx=160, int nny=160) : nPixels(numberOfPixels), min(minn), max(maxx), converged(0), nx(nnx), ny(nny), chi_sq(0){ - //acc = 0.02; - ds = 0.005; - - init(); - } - void init(){ - double pOffset = (max-min)/(double)nPixels; - xPPos = new double[(nPixels+1)*(nPixels+1)+1]; - yPPos = new double[(nPixels+1)*(nPixels+1)+1]; - binCont = new double[nPixels*nPixels+1]; - totCont = 0.; - edgeL = new double[2*nPixels*(nPixels+1)+1]; + for (int ii = 0; ii < 2 * nPixels * (nPixels + 1) + 1; ii++) { + edgeL[ii] = 1.0; + // cout << "ii " << ii << endl; + } - for(int ii = 0; ii < 2*nPixels*(nPixels+1)+1; ii++){ - edgeL[ii] = 1.0; - //cout << "ii " << ii << endl; + for (int x = 0; x < nPixels + 1; x++) { + for (int y = 0; y < nPixels + 1; y++) { + xPPos[getCorner(x, y)] = min + (double)x * pOffset; + yPPos[getCorner(x, y)] = min + (double)y * pOffset; + + if (x < nPixels && y < nPixels) + binCont[getBin(x, y)] = 0; + } + } + // edgeL[1] = 3.0; + updatePixelCorner(); + it = 0; + + log = new itLog[nIterations]; } - for(int x = 0; x < nPixels+1; x++){ - for(int y = 0; y < nPixels+1; y++){ - xPPos[getCorner(x,y)] = min + (double)x * pOffset; - yPPos[getCorner(x,y)] = min + (double)y * pOffset; - - if(x < nPixels && y < nPixels) binCont[getBin(x,y)] = 0; - } + void fill(double x, double y, double amount = 1.) { + totCont += amount; + int bin = findBin(x, y); + if (bin < 0) { + // cout << "can not find bin x: " << x << " y: " << y << endl; + totCont -= amount; + } + binCont[bin] += amount; } - // edgeL[1] = 3.0; - updatePixelCorner(); - it = 0; - - log = new itLog[nIterations]; - } - void fill(double x, double y, double amount = 1.){ - totCont+=amount; - int bin = findBin(x,y); - if(bin < 0) { - //cout << "can not find bin x: " << x << " y: " << y << endl; - totCont-=amount; + int getBin(int x, int y) { + if (x < 0 || x >= nPixels || y < 0 || y >= nPixels) { + // cout << "getBin: out of bounds : x " << x << " y " << y << endl; + return 0; + } + return y * nPixels + x + 1; } - binCont[bin]+=amount; - - } - int getBin(int x, int y){ - if(x < 0 || x >= nPixels || y < 0 || y >= nPixels){ - //cout << "getBin: out of bounds : x " << x << " y " << y << endl; - return 0; + int getXBin(int bin) { return (bin - 1) % nPixels; } + + int getYBin(int bin) { return (bin - 1) / nPixels; } + + int getCorner(int x, int y) { return y * (nPixels + 1) + x + 1; } + + int getEdgeX(int x, int row) { + int ret = row * nPixels + x + 1; + // cout << "| edge X x " << x << " row " << row << ": "<< ret << " | "; + return ret; } - return y*nPixels+x+1; - } - int getXBin(int bin){ - return (bin-1)%nPixels; - } - - int getYBin(int bin){ - return (bin-1)/nPixels; - } + int getEdgeY(int col, int y) { + int ret = nPixels * (nPixels + 1) + col * nPixels + y + 1; + // cout << "| edge Y col " << col << " y " << y << ": "<< ret << " | "; + return ret; + } - int getCorner(int x, int y){ - return y*(nPixels+1)+x+1; - } + int getIt() { return it; }; - int getEdgeX(int x,int row){ - int ret = row*nPixels+x+1; - //cout << "| edge X x " << x << " row " << row << ": "<< ret << " | "; - return ret; - } + int getNPixels() { return nPixels; } + double *getXPPos() { return xPPos; } + double *getYPPos() { return yPPos; } - int getEdgeY(int col, int y){ - int ret = nPixels*(nPixels+1)+col*nPixels+y+1; - //cout << "| edge Y col " << col << " y " << y << ": "<< ret << " | "; - return ret; - } - + void updatePixelCorner(); + double *getPixelCorners(int x, int y); + int findBin(double xx, double yy); + void createLogEntry(); - int getIt(){ return it; }; + void updatePixelPos(); + double *getSizeMap(); + double *getChangeMap(); + TH2D *getContent(int it = -1, int changeType = 0); + TMultiGraph *plotPixelBorder(int plotCenters = 0); + TMultiGraph *plotLog(int stepSize = 1, int maxIt = -1); + void printGrid(); + TH1D *getCounts(); - int getNPixels(){ return nPixels; } - double *getXPPos(){ return xPPos; } - double *getYPPos(){ return yPPos; } + void serialize(ostream &o); + void deserialize(istream &is); - void updatePixelCorner(); - double *getPixelCorners(int x, int y); - int findBin(double xx, double yy); - void createLogEntry(); - - void updatePixelPos(); - double *getSizeMap(); - double *getChangeMap(); - TH2D *getContent(int it=-1, int changeType = 0); - TMultiGraph *plotPixelBorder(int plotCenters=0); - TMultiGraph *plotLog(int stepSize=1, int maxIt=-1); - void printGrid(); - TH1D *getCounts(); + int converged; + double getChiSq() { return chi_sq; }; - void serialize(ostream &o); - void deserialize(istream &is); + private: + itLog *log; + int it; + const static int nIterations = 10000; + int nx, ny; + int nPixels; + double *xPPos; + double *yPPos; + double *binCont; + double totCont; + double *edgeL; + // double acc; + double ds; + double min, max; + double chi_sq; - int converged ; - double getChiSq(){return chi_sq;}; - - private: - itLog *log; - int it; - const static int nIterations =10000; - int nx, ny; - int nPixels; - double *xPPos; - double *yPPos; - double *binCont; - double totCont; - double *edgeL; - // double acc; - double ds; - double min,max; - double chi_sq; - - ClassDefNV(EtaVEL,1); - #pragma link C++ class EtaVEL-; + ClassDefNV(EtaVEL, 1); +#pragma link C++ class EtaVEL - ; }; #endif diff --git a/slsDetectorCalibration/interpolations/etaVEL/etaVELInterpolation.cpp b/slsDetectorCalibration/interpolations/etaVEL/etaVELInterpolation.cpp index 43e6ebed0..8d42653ee 100644 --- a/slsDetectorCalibration/interpolations/etaVEL/etaVELInterpolation.cpp +++ b/slsDetectorCalibration/interpolations/etaVEL/etaVELInterpolation.cpp @@ -1,136 +1,144 @@ // SPDX-License-Identifier: LGPL-3.0-or-other // Copyright (C) 2021 Contributors to the SLS Detector Package -#include "interpolation_EtaVEL.h" -#include "TH2F.h" #include "TCanvas.h" +#include "TH2F.h" #include "TROOT.h" +#include "interpolation_EtaVEL.h" //#include "EtaVEL.h" #include "EtaVEL.cpp" /* -Zum erstellen der correction map ist createGainAndEtaFile(...) in EVELAlg.C der entry point. -Zum erstellen des HR images ist createImage(...) der entry point. +Zum erstellen der correction map ist createGainAndEtaFile(...) in EVELAlg.C der +entry point. Zum erstellen des HR images ist createImage(...) der entry point. */ -interpolation_EtaVEL::interpolation_EtaVEL(int nx, int ny, int ns, double etamin, double etamax, int p) : slsInterpolation(nx, ny, ns), newEta(NULL), heta(NULL), plot(p) { - newEta = new EtaVEL(nSubPixels,etamin,etamax,nPixelsX, nPixelsY); - heta= new TH2F("heta","heta",50*nSubPixels, etamin,etamax,50*nSubPixels, etamin,etamax); - heta->SetStats(kFALSE); +interpolation_EtaVEL::interpolation_EtaVEL(int nx, int ny, int ns, + double etamin, double etamax, int p) + : slsInterpolation(nx, ny, ns), newEta(NULL), heta(NULL), plot(p) { + newEta = new EtaVEL(nSubPixels, etamin, etamax, nPixelsX, nPixelsY); + heta = new TH2F("heta", "heta", 50 * nSubPixels, etamin, etamax, + 50 * nSubPixels, etamin, etamax); + heta->SetStats(kFALSE); } interpolation_EtaVEL::~interpolation_EtaVEL() { - delete newEta; - delete heta; + delete newEta; + delete heta; } - void interpolation_EtaVEL::prepareInterpolation(int &ok, int maxit) { - int nit=0; - while ((newEta->converged != 1) && nit++Modified(); - gPad->Update(); - } - if (newEta->converged==1) ok=1; else ok=0; + int nit = 0; + while ((newEta->converged != 1) && nit++ < maxit) { + cout << " -------------- new step " << nit << endl; + iterate(); + } + if (plot) { + Draw(); + gPad->Modified(); + gPad->Update(); + } + if (newEta->converged == 1) + ok = 1; + else + ok = 0; } -int interpolation_EtaVEL::addToFlatField(Double_t *cluster, Double_t &etax, Double_t &etay) { - Double_t sum, totquad, sDum[2][2]; - int corner =calcEta(cluster, etax, etay, sum, totquad, sDum); - //check if it's OK...should redo it every time? - //or should we fill a finer histogram and afterwards re-fill the newEta? - addToFlatField(etax, etay); - return corner; +int interpolation_EtaVEL::addToFlatField(Double_t *cluster, Double_t &etax, + Double_t &etay) { + Double_t sum, totquad, sDum[2][2]; + int corner = calcEta(cluster, etax, etay, sum, totquad, sDum); + // check if it's OK...should redo it every time? + // or should we fill a finer histogram and afterwards re-fill the newEta? + addToFlatField(etax, etay); + return corner; } int interpolation_EtaVEL::addToFlatField(Double_t etax, Double_t etay) { - // newEta->fill(etaX,etaY); - heta->Fill(etax,etay); - return 0; + // newEta->fill(etaX,etaY); + heta->Fill(etax, etay); + return 0; } void interpolation_EtaVEL::iterate() { - cout << " -------------- newEta refilled"<< endl; - for (int ibx=0; ibxGetNbinsX(); ibx++) { - for (int iby=0; ibyGetNbinsY(); iby++) { - newEta->fill(heta->GetXaxis()->GetBinCenter(ibx+1),heta->GetYaxis()->GetBinCenter(iby+1),heta->GetBinContent(ibx+1,iby+1)); - } - } - newEta->updatePixelPos(); - cout << " -------------- pixelPosition updated"<< endl; + cout << " -------------- newEta refilled" << endl; + for (int ibx = 0; ibx < heta->GetNbinsX(); ibx++) { + for (int iby = 0; iby < heta->GetNbinsY(); iby++) { + newEta->fill(heta->GetXaxis()->GetBinCenter(ibx + 1), + heta->GetYaxis()->GetBinCenter(iby + 1), + heta->GetBinContent(ibx + 1, iby + 1)); + } + } + newEta->updatePixelPos(); + cout << " -------------- pixelPosition updated" << endl; } void interpolation_EtaVEL::DrawH() { - heta->Draw("col"); - (newEta->plotPixelBorder())->Draw(); + heta->Draw("col"); + (newEta->plotPixelBorder())->Draw(); } +void interpolation_EtaVEL::getInterpolatedPosition(Int_t x, Int_t y, + Double_t *cluster, + Double_t &int_x, + Double_t &int_y) { -void interpolation_EtaVEL::getInterpolatedPosition(Int_t x, Int_t y, Double_t *cluster, Double_t &int_x, Double_t &int_y) { + Double_t etax, etay, sum, totquad, sDum[2][2]; - Double_t etax, etay, sum, totquad, sDum[2][2]; + int corner = calcEta(cluster, etax, etay, sum, totquad, sDum); - int corner =calcEta(cluster, etax, etay, sum, totquad, sDum); - - int bin = newEta->findBin(etax,etay); - if (bin<=0) { - int_x=-1; - int_y=-1; - return; - } - double subX = ((double)(newEta->getXBin(bin))+.5)/((double)newEta->getNPixels()); - double subY = ((double)(newEta->getYBin(bin))+.5)/((double)newEta->getNPixels()); - - double dX, dY; - switch (corner) { - case TOP_LEFT: - dX=-1.; - dY=+1.; - break; - case TOP_RIGHT: - dX=+1.; - dY=+1.; - break; - case BOTTOM_LEFT: - dX=-1.; - dY=-1.; - break; - case BOTTOM_RIGHT: - dX=+1.; - dY=-1.; - break; - default: - dX=0; - dY=0; - } - - int_x=((double)x)+ subX+0.5*dX; - int_y=((double)y)+ subY+0.5*dY; - - // cout << corner << " " << subX<< " " << subY << " " << dX << " " << dY << " " << int_x << " " << int_y << endl; + int bin = newEta->findBin(etax, etay); + if (bin <= 0) { + int_x = -1; + int_y = -1; + return; + } + double subX = + ((double)(newEta->getXBin(bin)) + .5) / ((double)newEta->getNPixels()); + double subY = + ((double)(newEta->getYBin(bin)) + .5) / ((double)newEta->getNPixels()); + double dX, dY; + switch (corner) { + case TOP_LEFT: + dX = -1.; + dY = +1.; + break; + case TOP_RIGHT: + dX = +1.; + dY = +1.; + break; + case BOTTOM_LEFT: + dX = -1.; + dY = -1.; + break; + case BOTTOM_RIGHT: + dX = +1.; + dY = -1.; + break; + default: + dX = 0; + dY = 0; + } + + int_x = ((double)x) + subX + 0.5 * dX; + int_y = ((double)y) + subY + 0.5 * dY; + + // cout << corner << " " << subX<< " " << subY << " " << dX << " " << dY << + // " " << int_x << " " << int_y << endl; }; - // void interpolation_EtaVEL::Streamer(TBuffer &b){newEta->Streamer(b);}; -void interpolation_EtaVEL::getInterpolatedBin(Double_t *cluster, Int_t &int_x, Int_t &int_y) { +void interpolation_EtaVEL::getInterpolatedBin(Double_t *cluster, Int_t &int_x, + Int_t &int_y) { - Double_t etax, etay, sum, totquad, sDum[2][2]; - - int corner =calcEta(cluster, etax, etay, sum, totquad, sDum); - - int bin = newEta->findBin(etax,etay); - if (bin<0) { - int_x=-1; - int_y=-1; - return; - } - int_x=newEta->getXBin(bin); - int_y=newEta->getYBin(bin); - + Double_t etax, etay, sum, totquad, sDum[2][2]; + int corner = calcEta(cluster, etax, etay, sum, totquad, sDum); + int bin = newEta->findBin(etax, etay); + if (bin < 0) { + int_x = -1; + int_y = -1; + return; + } + int_x = newEta->getXBin(bin); + int_y = newEta->getYBin(bin); }; - diff --git a/slsDetectorCalibration/interpolations/etaVEL/etaVELInterpolation.h b/slsDetectorCalibration/interpolations/etaVEL/etaVELInterpolation.h index e35624da8..f0033e740 100644 --- a/slsDetectorCalibration/interpolations/etaVEL/etaVELInterpolation.h +++ b/slsDetectorCalibration/interpolations/etaVEL/etaVELInterpolation.h @@ -3,55 +3,61 @@ #ifndef INTERPOLATION_ETAVEL_H #define INTERPOLATION_ETAVEL_H -#include #include "EtaVEL.h" +#include //#include "TH2F.h" //#include "EtaVEL.cpp" -//class EtaVEL; +// class EtaVEL; -class etaVELInterpolation: public etaInterpolationBase { +class etaVELInterpolation : public etaInterpolationBase { - public: - interpolation_EtaVEL(int nx=40, int ny=160, int ns=25, double etamin=-0.02, double etamax=1.02, int p=0); - ~interpolation_EtaVEL(); - - - //create eta distribution, eta rebinnining etc. - //returns flat field image - void prepareInterpolation(int &ok){prepareInterpolation(ok,10000);}; - void prepareInterpolation(int &ok, int maxit); + public: + interpolation_EtaVEL(int nx = 40, int ny = 160, int ns = 25, + double etamin = -0.02, double etamax = 1.02, + int p = 0); + ~interpolation_EtaVEL(); - //create interpolated image - //returns interpolated image - - //return position inside the pixel for the given photon - void getInterpolatedPosition(Int_t x, Int_t y, Double_t *data, Double_t &int_x, Double_t &int_y); - void getInterpolatedBin(Double_t *cluster, Int_t &int_x, Int_t &int_y); - + // create eta distribution, eta rebinnining etc. + // returns flat field image + void prepareInterpolation(int &ok) { prepareInterpolation(ok, 10000); }; + void prepareInterpolation(int &ok, int maxit); + // create interpolated image + // returns interpolated image - int addToFlatField(Double_t *cluster, Double_t &etax, Double_t &etay); - int addToFlatField(Double_t etax, Double_t etay); - int setPlot(int p=-1) {if (p>=0) plot=p; return plot;}; - // int WriteH(){newEta->Write("newEta"); heta->Write("heta");}; - EtaVEL *setEta(EtaVEL *ev){if (ev) {delete newEta; newEta=ev;} return newEta;}; + // return position inside the pixel for the given photon + void getInterpolatedPosition(Int_t x, Int_t y, Double_t *data, + Double_t &int_x, Double_t &int_y); + void getInterpolatedBin(Double_t *cluster, Int_t &int_x, Int_t &int_y); + int addToFlatField(Double_t *cluster, Double_t &etax, Double_t &etay); + int addToFlatField(Double_t etax, Double_t etay); + int setPlot(int p = -1) { + if (p >= 0) + plot = p; + return plot; + }; + // int WriteH(){newEta->Write("newEta"); heta->Write("heta");}; + EtaVEL *setEta(EtaVEL *ev) { + if (ev) { + delete newEta; + newEta = ev; + } + return newEta; + }; + // TH2F *setEta(TH2F *ev){if (ev) {delete heta; heta=ev;} return heta;}; + void iterate(); + // void DrawH(); + double getChiSq() { return newEta->getChiSq(); }; - // TH2F *setEta(TH2F *ev){if (ev) {delete heta; heta=ev;} return heta;}; - void iterate(); - // void DrawH(); - double getChiSq(){return newEta->getChiSq();}; - + protected: + EtaVEL *newEta; + // TH2F *heta; + int plot; - - protected: - EtaVEL *newEta; - // TH2F *heta; - int plot; - - // ClassDefNV(interpolation_EtaVEL,1); - // #pragma link C++ class interpolation_EtaVEL-; + // ClassDefNV(interpolation_EtaVEL,1); + // #pragma link C++ class interpolation_EtaVEL-; }; #endif diff --git a/slsDetectorCalibration/interpolations/linearInterpolation.h b/slsDetectorCalibration/interpolations/linearInterpolation.h index 9eafc2fbf..a3d9a65fe 100644 --- a/slsDetectorCalibration/interpolations/linearInterpolation.h +++ b/slsDetectorCalibration/interpolations/linearInterpolation.h @@ -9,228 +9,215 @@ #include "slsInterpolation.h" -class linearInterpolation : public slsInterpolation{ +class linearInterpolation : public slsInterpolation { - public: - linearInterpolation(int nx=400, int ny=400, int ns=25) : slsInterpolation(nx,ny,ns) {}; - linearInterpolation(linearInterpolation *orig) : slsInterpolation(orig) {}; + public: + linearInterpolation(int nx = 400, int ny = 400, int ns = 25) + : slsInterpolation(nx, ny, ns){}; + linearInterpolation(linearInterpolation *orig) : slsInterpolation(orig){}; - virtual void prepareInterpolation(int &ok){ok=1;}; + virtual void prepareInterpolation(int &ok) { ok = 1; }; - virtual linearInterpolation* Clone() { + virtual linearInterpolation *Clone() { - return new linearInterpolation(this); + return new linearInterpolation(this); + }; - }; + ////////////////////////////////////////////////////////////////////////////// + //////////// /*It return position hit for the event in input */ + ///////////////// + virtual void getInterpolatedPosition(int x, int y, double *data, + double &int_x, double &int_y) { + double sDum[2][2]; + double tot, totquad; + double etax, etay; + int corner; + corner = calcQuad(data, tot, totquad, sDum); + if (nSubPixels > 2) { + calcEta(totquad, sDum, etax, etay); + } + getInterpolatedPosition(x, y, etax, etay, corner, int_x, int_y); - ////////////////////////////////////////////////////////////////////////////// - //////////// /*It return position hit for the event in input */ ////////////// - virtual void getInterpolatedPosition(int x, int y, double *data, double &int_x, double &int_y) - { - double sDum[2][2]; - double tot, totquad; - double etax,etay; - - int corner; - corner=calcQuad(data, tot, totquad, sDum); - if (nSubPixels>2) { - calcEta(totquad, sDum, etax, etay); - } - getInterpolatedPosition(x, y, etax,etay, corner, int_x, int_y); - - return; - }; + return; + }; - virtual void getInterpolatedPosition(int x, int y, int *data, double &int_x, double &int_y) - { - double sDum[2][2]; - double tot, totquad; - double etax,etay; - - int corner; - corner=calcQuad(data, tot, totquad, sDum); - if (nSubPixels>2) - calcEta(totquad, sDum, etax, etay); - getInterpolatedPosition(x,y,etax,etay,corner,int_x,int_y); + virtual void getInterpolatedPosition(int x, int y, int *data, double &int_x, + double &int_y) { + double sDum[2][2]; + double tot, totquad; + double etax, etay; - return; - }; - - virtual void getInterpolatedPosition(int x, int y, double totquad,int quad,double *cl,double &int_x, double &int_y) { - - double eta_x, eta_y; - if (nSubPixels>2) { - double cc[2][2]; - double *cluster[3]; - cluster[0]=cl; - cluster[1]=cl+3; - cluster[2]=cl+6; - int xoff, yoff; - - switch (quad) { - case BOTTOM_LEFT: - xoff=0; - yoff=0; - break; - case BOTTOM_RIGHT: - xoff=1; - yoff=0; - break; - case TOP_LEFT: - xoff=0; - yoff=1; - break; - case TOP_RIGHT: - xoff=1; - yoff=1; - break; - default: - ; - } - cc[0][0]=cluster[yoff][xoff]; - cc[1][0]=cluster[yoff+1][xoff]; - cc[0][1]=cluster[yoff][xoff+1]; - cc[1][1]=cluster[yoff+1][xoff+1]; - calcEta(totquad,cc,eta_x,eta_y); + int corner; + corner = calcQuad(data, tot, totquad, sDum); + if (nSubPixels > 2) + calcEta(totquad, sDum, etax, etay); + getInterpolatedPosition(x, y, etax, etay, corner, int_x, int_y); + + return; + }; + + virtual void getInterpolatedPosition(int x, int y, double totquad, int quad, + double *cl, double &int_x, + double &int_y) { + + double eta_x, eta_y; + if (nSubPixels > 2) { + double cc[2][2]; + double *cluster[3]; + cluster[0] = cl; + cluster[1] = cl + 3; + cluster[2] = cl + 6; + int xoff, yoff; + + switch (quad) { + case BOTTOM_LEFT: + xoff = 0; + yoff = 0; + break; + case BOTTOM_RIGHT: + xoff = 1; + yoff = 0; + break; + case TOP_LEFT: + xoff = 0; + yoff = 1; + break; + case TOP_RIGHT: + xoff = 1; + yoff = 1; + break; + default:; + } + cc[0][0] = cluster[yoff][xoff]; + cc[1][0] = cluster[yoff + 1][xoff]; + cc[0][1] = cluster[yoff][xoff + 1]; + cc[1][1] = cluster[yoff + 1][xoff + 1]; + calcEta(totquad, cc, eta_x, eta_y); + } + // cout << x << " " << y << " " << eta_x << " " << eta_y << " " << int_x + // << " " << int_y << endl; + return getInterpolatedPosition(x, y, eta_x, eta_y, quad, int_x, int_y); } - // cout << x << " " << y << " " << eta_x << " " << eta_y << " " << int_x << " " << int_y << endl; - return getInterpolatedPosition(x,y,eta_x, eta_y,quad,int_x,int_y); + virtual void getInterpolatedPosition(int x, int y, double totquad, int quad, + int *cl, double &int_x, + double &int_y) { + double cc[2][2]; + int *cluster[3]; + int xoff, yoff; + cluster[0] = cl; + cluster[1] = cl + 3; + cluster[2] = cl + 6; - - - - - } - - - virtual void getInterpolatedPosition(int x, int y, double totquad,int quad,int *cl,double &int_x, double &int_y) { - - double cc[2][2]; - int *cluster[3]; - int xoff, yoff; - cluster[0]=cl; - cluster[1]=cl+3; - cluster[2]=cl+6; - - switch (quad) { - case BOTTOM_LEFT: - xoff=0; - yoff=0; - break; - case BOTTOM_RIGHT: - xoff=1; - yoff=0; - break; - case TOP_LEFT: - xoff=0; - yoff=1; - break; - case TOP_RIGHT: - xoff=1; - yoff=1; - break; - default: - ; - } - double etax, etay; - if (nSubPixels>2) { - cc[0][0]=cluster[yoff][xoff]; - cc[1][0]=cluster[yoff+1][xoff]; - cc[0][1]=cluster[yoff][xoff+1]; - cc[1][1]=cluster[yoff+1][xoff+1]; - calcEta(totquad,cc,etax,etay); - } - // cout << x << " " << y << " " << etax << " " << etay << " " << int_x << " " << int_y << endl; - return getInterpolatedPosition(x,y,etax, etay,quad,int_x,int_y); - - } - - - - virtual void getInterpolatedPosition(int x, int y, double etax, double etay, int corner, double &int_x, double &int_y) - { - - double xpos_eta,ypos_eta; - double dX,dY; - switch (corner) - { - case TOP_LEFT: - dX=-1.; - dY=0; - break; - case TOP_RIGHT: - dX=0; - dY=0; - break; - case BOTTOM_LEFT: - dX=-1.; - dY=-1.; - break; - case BOTTOM_RIGHT: - dX=0; - dY=-1.; - break; - default: - cout << "bad quadrant" << endl; - dX=0.; - dY=0.; - } - - - if (nSubPixels>2) { - xpos_eta=(etax)+dX; - ypos_eta=(etay)+dY; - } else { - xpos_eta=0.5*dX+0.25; - ypos_eta=0.5*dY+0.25; + switch (quad) { + case BOTTOM_LEFT: + xoff = 0; + yoff = 0; + break; + case BOTTOM_RIGHT: + xoff = 1; + yoff = 0; + break; + case TOP_LEFT: + xoff = 0; + yoff = 1; + break; + case TOP_RIGHT: + xoff = 1; + yoff = 1; + break; + default:; + } + double etax, etay; + if (nSubPixels > 2) { + cc[0][0] = cluster[yoff][xoff]; + cc[1][0] = cluster[yoff + 1][xoff]; + cc[0][1] = cluster[yoff][xoff + 1]; + cc[1][1] = cluster[yoff + 1][xoff + 1]; + calcEta(totquad, cc, etax, etay); + } + // cout << x << " " << y << " " << etax << " " << etay << " " << int_x + // << " " << int_y << endl; + return getInterpolatedPosition(x, y, etax, etay, quad, int_x, int_y); } - int_x=((double)x) + xpos_eta; - int_y=((double)y) + ypos_eta; - // cout <<"**"<< x << " " << y << " " << xpos_eta << " " << ypos_eta << " " << corner << endl; - return; - }; + virtual void getInterpolatedPosition(int x, int y, double etax, double etay, + int corner, double &int_x, + double &int_y) { + double xpos_eta, ypos_eta; + double dX, dY; + switch (corner) { + case TOP_LEFT: + dX = -1.; + dY = 0; + break; + case TOP_RIGHT: + dX = 0; + dY = 0; + break; + case BOTTOM_LEFT: + dX = -1.; + dY = -1.; + break; + case BOTTOM_RIGHT: + dX = 0; + dY = -1.; + break; + default: + cout << "bad quadrant" << endl; + dX = 0.; + dY = 0.; + } + if (nSubPixels > 2) { + xpos_eta = (etax) + dX; + ypos_eta = (etay) + dY; + } else { + xpos_eta = 0.5 * dX + 0.25; + ypos_eta = 0.5 * dY + 0.25; + } + int_x = ((double)x) + xpos_eta; + int_y = ((double)y) + ypos_eta; + // cout <<"**"<< x << " " << y << " " << xpos_eta << " " << ypos_eta << + // " " << corner << endl; + return; + }; + //////////////////////////////////////////////////////////////////////////////////////////////////////// + virtual void getPositionETA3(int x, int y, double *data, double &int_x, + double &int_y) { + double sDum[2][2]; + double tot, totquad; + double eta3x, eta3y; + calcQuad(data, tot, totquad, sDum); + calcEta3(data, eta3x, eta3y, tot); + double xpos_eta, ypos_eta; - //////////////////////////////////////////////////////////////////////////////////////////////////////// - virtual void getPositionETA3(int x, int y, double *data, double &int_x, double &int_y) - { - double sDum[2][2]; - double tot, totquad; - double eta3x,eta3y; - - calcQuad(data, tot, totquad, sDum); - calcEta3(data,eta3x, eta3y,tot); - - double xpos_eta,ypos_eta; - - xpos_eta=eta3x; - ypos_eta=eta3y; - - int_x=((double)x) + xpos_eta; - int_y=((double)y) + ypos_eta; - - return; - }; - //////////////////////////////////////////////////////////////////////////////////////////////////////// - - virtual int addToFlatField(double *cluster, double &etax, double &etay){}; - virtual int addToFlatField(int *cluster, double &etax, double &etay){}; - virtual int addToFlatField(double etax, double etay){}; - virtual int addToFlatField(double totquad,int quad,double *cl,double &etax, double &etay) {}; - virtual int addToFlatField(double totquad,int quad,int *cl,double &etax, double &etay) {}; + xpos_eta = eta3x; + ypos_eta = eta3y; - protected: - ; + int_x = ((double)x) + xpos_eta; + int_y = ((double)y) + ypos_eta; + return; + }; + //////////////////////////////////////////////////////////////////////////////////////////////////////// + virtual int addToFlatField(double *cluster, double &etax, double &etay){}; + virtual int addToFlatField(int *cluster, double &etax, double &etay){}; + virtual int addToFlatField(double etax, double etay){}; + virtual int addToFlatField(double totquad, int quad, double *cl, + double &etax, double &etay){}; + virtual int addToFlatField(double totquad, int quad, int *cl, double &etax, + double &etay){}; + + protected: + ; }; #endif diff --git a/slsDetectorCalibration/interpolations/noInterpolation.h b/slsDetectorCalibration/interpolations/noInterpolation.h index 3f4b52b88..1ccaed431 100644 --- a/slsDetectorCalibration/interpolations/noInterpolation.h +++ b/slsDetectorCalibration/interpolations/noInterpolation.h @@ -11,96 +11,100 @@ /* #include */ /* #endif */ -#include #include "slsInterpolation.h" +#include +class noInterpolation : public slsInterpolation { + public: + noInterpolation(int nx = 400, int ny = 400, int ns = 25) + : slsInterpolation(nx, ny, ns){}; // {eventGenerator=new TRandom();}; + noInterpolation(noInterpolation *orig) : slsInterpolation(orig){}; + virtual void prepareInterpolation(int &ok) { ok = 1; }; + ////////////////////////////////////////////////////////////////////////////// + //////////// /*It return position hit for the event in input */ + ///////////////// -class noInterpolation : public slsInterpolation{ - public: - noInterpolation(int nx=400, int ny=400, int ns=25) : slsInterpolation(nx,ny,ns) {};// {eventGenerator=new TRandom();}; - noInterpolation(noInterpolation *orig) : slsInterpolation(orig){}; - virtual void prepareInterpolation(int &ok){ok=1;}; - - ////////////////////////////////////////////////////////////////////////////// - //////////// /*It return position hit for the event in input */ ////////////// + virtual noInterpolation *Clone() { return new noInterpolation(this); }; - virtual noInterpolation* Clone() { + virtual void getInterpolatedPosition(int x, int y, double *data, + double &int_x, double &int_y) { + // Random coordinate in the Pixel reference + int_x = x + ((double)rand()) / ((double)RAND_MAX) - + 0.5; // eventGenerator->Uniform(-0.5,0.5); + int_y = y + ((double)rand()) / ((double)RAND_MAX) - + 0.5; // eventGenerator->Uniform(-0.5,0.5); - return new noInterpolation(this); + return; + }; - }; + virtual void getInterpolatedPosition(int x, int y, int *data, double &int_x, + double &int_y) { + return getInterpolatedPosition(x, y, (double *)NULL, int_x, int_y); + } + virtual void getInterpolatedPosition(int x, int y, double etax, double etay, + int corner, double &int_x, + double &int_y) { + getInterpolatedPosition(x, y, (double *)NULL, int_x, int_y); + }; - virtual void getInterpolatedPosition(int x, int y, double *data, double &int_x, double &int_y) - { - //Random coordinate in the Pixel reference - int_x = x + ((double)rand())/((double)RAND_MAX) -0.5;//eventGenerator->Uniform(-0.5,0.5); - int_y = y + ((double)rand())/((double)RAND_MAX) -0.5;//eventGenerator->Uniform(-0.5,0.5); - - return ; - }; + virtual void getInterpolatedPosition(int x, int y, double totquad, int quad, + double *cl, double &etax, + double &etay) { + getInterpolatedPosition(x, y, (double *)NULL, etax, etay); + }; - virtual void getInterpolatedPosition(int x, int y, int *data, double &int_x, double &int_y) - { - return getInterpolatedPosition(x, y, (double*)NULL, int_x, int_y); - } - + virtual void getInterpolatedPosition(int x, int y, double totquad, int quad, + int *cl, double &etax, double &etay) { + getInterpolatedPosition(x, y, (double *)NULL, etax, etay); + }; - virtual void getInterpolatedPosition(int x, int y, double etax, double etay, int corner, double &int_x, double &int_y) - { - getInterpolatedPosition(x, y, (double*)NULL, int_x, int_y); - }; + ////////////////////////////////////////////////////////////////////////////////////// + virtual void getPositionETA3(int x, int y, double *data, double &int_x, + double &int_y) { + // Random coordinate in the Pixel reference + int_x = x + ((double)rand()) / ((double)RAND_MAX) - + 0.5; // eventGenerator->Uniform(-0.5,0.5); + int_y = y + ((double)rand()) / ((double)RAND_MAX) - + 0.5; // eventGenerator->Uniform(-0.5,0.5); + return; + }; + virtual void getPositionETA3(int x, int y, int *data, double &int_x, + double &int_y) { + return getPositionETA3(x, y, (double *)NULL, int_x, int_y); + }; + ////////////////////////////////////////////////////////////////////////////////////// + virtual int addToFlatField(double *cluster, double &etax, double &etay) { + return 0; + }; - virtual void getInterpolatedPosition(int x, int y, double totquad,int quad,double *cl,double &etax, double &etay){ - getInterpolatedPosition(x, y, (double*)NULL, etax, etay); - }; + virtual int addToFlatField(int *cluster, double &etax, double &etay) { + return 0; + }; + virtual int addToFlatField(double etax, double etay) { return 0; }; - virtual void getInterpolatedPosition(int x, int y, double totquad,int quad,int *cl,double &etax, double &etay){ - getInterpolatedPosition(x, y, (double*)NULL, etax, etay); - }; + virtual int addToFlatField(double totquad, int quad, double *cl, + double &etax, double &etay) { + return 0; + }; + virtual int addToFlatField(double totquad, int quad, int *cl, double &etax, + double &etay) { + return 0; + }; - - ////////////////////////////////////////////////////////////////////////////////////// - virtual void getPositionETA3(int x, int y, double *data, double &int_x, double &int_y) - { - //Random coordinate in the Pixel reference - int_x = x + ((double)rand())/((double)RAND_MAX) -0.5;//eventGenerator->Uniform(-0.5,0.5); - int_y = y + ((double)rand())/((double)RAND_MAX) -0.5;//eventGenerator->Uniform(-0.5,0.5); - - return ; - }; + virtual void resetFlatField(){}; - virtual void getPositionETA3(int x, int y, int *data, double &int_x, double &int_y) - { - return getPositionETA3(x, y, (double*)NULL, int_x, int_y); - }; - - - - ////////////////////////////////////////////////////////////////////////////////////// - virtual int addToFlatField(double *cluster, double &etax, double &etay){return 0;}; - - virtual int addToFlatField(int *cluster, double &etax, double &etay){return 0;}; - - virtual int addToFlatField(double etax, double etay){return 0;}; - - virtual int addToFlatField(double totquad,int quad,double *cl,double &etax, double &etay){return 0;}; - - - virtual int addToFlatField(double totquad,int quad,int *cl,double &etax, double &etay){return 0;}; - - virtual void resetFlatField(){}; - protected: - ; - // TRandom *eventGenerator; - // ClassDefNV(slsInterpolation,1); - // #pragma link C++ class slsInterpolation-; + protected: + ; + // TRandom *eventGenerator; + // ClassDefNV(slsInterpolation,1); + // #pragma link C++ class slsInterpolation-; }; #endif diff --git a/slsDetectorCalibration/interpolations/slsInterpolation.h b/slsDetectorCalibration/interpolations/slsInterpolation.h index 41290fafd..9ae544c96 100644 --- a/slsDetectorCalibration/interpolations/slsInterpolation.h +++ b/slsDetectorCalibration/interpolations/slsInterpolation.h @@ -3,577 +3,605 @@ #ifndef SLS_INTERPOLATION_H #define SLS_INTERPOLATION_H -#include +#include #ifndef MY_TIFF_IO_H #include "tiffIO.h" #endif #ifndef DEF_QUAD #define DEF_QUAD - enum quadrant { - TOP_LEFT=0, - TOP_RIGHT=1, - BOTTOM_LEFT=2, - BOTTOM_RIGHT=3, - UNDEFINED_QUADRANT=-1 - }; +enum quadrant { + TOP_LEFT = 0, + TOP_RIGHT = 1, + BOTTOM_LEFT = 2, + BOTTOM_RIGHT = 3, + UNDEFINED_QUADRANT = -1 +}; #endif #include -#include #include +#include using namespace std; //#ifdef MYROOT1 //: public TObject //#endif -class slsInterpolation -{ +class slsInterpolation { - public: - slsInterpolation(int nx=400, int ny=400, int ns=25, int nsy=-1) :nPixelsX(nx), nPixelsY(ny), nSubPixelsX(ns), nSubPixelsY(nsy),id(0) { - - if (nSubPixelsY<=0) nSubPixelsY=nSubPixelsX; - hint=new int[nSubPixelsX*nx*nSubPixelsY*ny]; + public: + slsInterpolation(int nx = 400, int ny = 400, int ns = 25, int nsy = -1) + : nPixelsX(nx), nPixelsY(ny), nSubPixelsX(ns), nSubPixelsY(nsy), id(0) { -}; - virtual ~slsInterpolation(){ delete [] hint;} + if (nSubPixelsY <= 0) + nSubPixelsY = nSubPixelsX; + hint = new int[nSubPixelsX * nx * nSubPixelsY * ny]; + }; + virtual ~slsInterpolation() { delete[] hint; } - slsInterpolation(slsInterpolation *orig){ - nPixelsX=orig->nPixelsX; - nPixelsY=orig->nPixelsY; - nSubPixelsX=orig->nSubPixelsX; - nSubPixelsY=orig->nSubPixelsY; - - hint=new int[nSubPixelsX*nPixelsX*nSubPixelsY*nPixelsY]; - memcpy(hint, orig->hint,nSubPixelsX*nPixelsX*nSubPixelsY*nPixelsY*sizeof(int)); - - }; + slsInterpolation(slsInterpolation *orig) { + nPixelsX = orig->nPixelsX; + nPixelsY = orig->nPixelsY; + nSubPixelsX = orig->nSubPixelsX; + nSubPixelsY = orig->nSubPixelsY; - virtual int setId(int i) {id=i; return id;}; + hint = new int[nSubPixelsX * nPixelsX * nSubPixelsY * nPixelsY]; + memcpy(hint, orig->hint, + nSubPixelsX * nPixelsX * nSubPixelsY * nPixelsY * sizeof(int)); + }; - virtual slsInterpolation* Clone() =0; /*{ - return new slsInterpolation(this); - }*/ + virtual int setId(int i) { + id = i; + return id; + }; - int getNSubPixelsX() {return nSubPixelsX;}; - int getNSubPixelsY() {return nSubPixelsY;}; - int getNSubPixels() {if (nSubPixelsX==nSubPixelsY) return nSubPixelsX; else return 0;}; - void getNSubPixels(int &nsx, int &nsy) {nsx=nSubPixelsX; nsy=nsx=nSubPixelsY;} + virtual slsInterpolation *Clone() = 0; /*{ + return new slsInterpolation(this); + }*/ - void setNSubPixels(int ns, int nsy=-1) { - - delete [] hint; - nSubPixelsX=ns; - if (nsy>0) nSubPixelsY=nsy; - else nSubPixelsY=ns; - - hint=new int[nSubPixelsX*nPixelsX*nSubPixelsY*nPixelsY]; - - //return nSubPixels; - } - - - - - int getImageSize(int &nnx, int &nny, int &nsx, int &nsy) { - nnx=nSubPixelsX*nPixelsX; - nny=nSubPixelsY*nPixelsY; - nsx=nSubPixelsX; - nsy=nSubPixelsY; - return nSubPixelsX*nSubPixelsY*nPixelsX*nPixelsY; - }; - - - int getImageSize() { - return nSubPixelsX*nSubPixelsY*nPixelsX*nPixelsY; - }; - - - //create eta distribution, eta rebinnining etc. - //returns flat field image - virtual void prepareInterpolation(int &ok)=0; - - //create interpolated image - //returns interpolated image - virtual int *getInterpolatedImage(){ - // cout << "return interpolated image " << endl; - /* for (int i=0; i=0 && ix<(nPixelsX*nSubPixelsX) && iy<(nSubPixelsY*nPixelsY) && iy>=0 ){ - // cout << int_x << " " << int_y << " " << " " << ix << " " << iy << " " << ix+iy*nPixelsX*nSubPixels << " " << hint[ix+iy*nPixelsX*nSubPixels]; - (*(hint+ix+iy*nPixelsX*nSubPixelsX))+=1; - // cout << " " << hint[ix+iy*nPixelsX*nSubPixels] << endl; - }// else - // cout << "bad! "<< int_x << " " << int_y << " " << " " << ix << " " << iy << " " << ix+iy*nPixelsX*nSubPixels << endl; - - return hint; - }; - - - virtual int addToFlatField(double *cluster, double &etax, double &etay)=0; - virtual int addToFlatField(int *cluster, double &etax, double &etay)=0; - virtual int addToFlatField(double totquad,int quad,int *cl,double &etax, double &etay)=0; - virtual int addToFlatField(double totquad,int quad,double *cluster,double &etax, double &etay)=0; - virtual int addToFlatField(double etax, double etay)=0; - - virtual int *getFlatField(){return NULL;}; - virtual int *setFlatField(int *h, int nb=-1, double emin=-1, double emax=-1){return NULL;}; - virtual void *writeFlatField(const char * imgname){return NULL;}; - virtual void *readFlatField(const char * imgname, int nb=-1, double emin=1, double emax=0){return NULL;}; - virtual int *getFlatField(int &nb, double &emin, double &emax){nb=0; emin=0; emax=0; return getFlatField();}; - - virtual void resetFlatField()=0; - - //virtual void Streamer(TBuffer &b); - - static int calcQuad(int *cl, double &sum, double &totquad, double sDum[2][2]){ - double cli[3*3];//=new int[3*3]; - for (int i=0; i<9; i++) - cli[i]=cl[i]; - return calcQuad(cli, sum, totquad, sDum); - - } - - - static int calcQuad(double *cl, double &sum, double &totquad, double sDum[2][2]){ - - int corner = UNDEFINED_QUADRANT; - /* double *cluster[3]; */ - /* cluster[0]=cl; */ - /* cluster[1]=cl+3; */ - /* cluster[2]=cl+6; */ - - sum=0; - int xoff=0, yoff=0; -#ifndef WRITE_QUAD - double sumBL=0; - double sumTL=0; - double sumBR=0; - double sumTR=0; - for (int ix=0; ix<3; ix++) { - for (int iy=0; iy<3; iy++) { - sum+=cl[ix+3*iy]; - if (ix<=1 && iy<=1) sumBL+=cl[ix+iy*3]; - if (ix<=1 && iy>=1) sumTL+=cl[ix+iy*3]; - if (ix>=1 && iy<=1) sumBR+=cl[ix+iy*3]; - if (ix>=1 && iy>=1) sumTR+=cl[ix+iy*3]; - } + int getNSubPixelsX() { return nSubPixelsX; }; + int getNSubPixelsY() { return nSubPixelsY; }; + int getNSubPixels() { + if (nSubPixelsX == nSubPixelsY) + return nSubPixelsX; + else + return 0; + }; + void getNSubPixels(int &nsx, int &nsy) { + nsx = nSubPixelsX; + nsy = nsx = nSubPixelsY; } - /* sDum[0][0] = cluster[0][0]; sDum[1][0] = cluster[1][0]; */ - /* sDum[0][1] = cluster[0][1]; sDum[1][1] = cluster[1][1]; */ - corner = BOTTOM_LEFT; - totquad=sumBL; - xoff=0; - yoff=0; + void setNSubPixels(int ns, int nsy = -1) { - - if(sumTL >= totquad){ -/* #ifdef WRITE_QUAD */ -/* /\* sDum[0][0] = cluster[1][0]; sDum[1][0] = cluster[2][0]; *\/ */ -/* /\* sDum[0][1] = cluster[1][1]; sDum[1][1] = cluster[2][1]; *\/ */ -/* if (sumTL ==sum) { */ -/* #endif */ - corner = TOP_LEFT; - totquad=sumTL; - xoff=0; - yoff=1; -/* #ifdef WRITE_QUAD */ -/* } */ -/* #endif */ - } + delete[] hint; + nSubPixelsX = ns; + if (nsy > 0) + nSubPixelsY = nsy; + else + nSubPixelsY = ns; - if(sumBR >= totquad){ - /* sDum[0][0] = cluster[0][1]; sDum[1][0] = cluster[1][1]; */ - /* sDum[0][1] = cluster[0][2]; sDum[1][1] = cluster[1][2]; */ - -/* #ifdef WRITE_QUAD */ -/* /\* sDum[0][0] = cluster[1][0]; sDum[1][0] = cluster[2][0]; *\/ */ -/* /\* sDum[0][1] = cluster[1][1]; sDum[1][1] = cluster[2][1]; *\/ */ -/* if (sumBR ==sum) { */ -/* #endif */ - corner = BOTTOM_RIGHT; - xoff=1; - yoff=0; - totquad=sumBR; -/* #ifdef WRITE_QUAD */ -/* } */ -/* #endif */ + hint = new int[nSubPixelsX * nPixelsX * nSubPixelsY * nPixelsY]; + + // return nSubPixels; } - - if(sumTR >= totquad){ -/* #ifdef WRITE_QUAD */ -/* /\* sDum[0][0] = cluster[1][0]; sDum[1][0] = cluster[2][0]; *\/ */ -/* /\* sDum[0][1] = cluster[1][1]; sDum[1][1] = cluster[2][1]; *\/ */ -/* if (sumTR ==sum) { */ -/* #endif */ - xoff=1; - yoff=1; - /* sDum[0][0] = cluster[1][1]; sDum[1][0] = cluster[2][1]; */ - /* sDum[0][1] = cluster[1][2]; sDum[1][1] = cluster[2][2]; */ - corner = TOP_RIGHT; - totquad=sumTR; -/* #ifdef WRITE_QUAD */ -/* } */ -/* #endif */ - } - -#endif -#ifdef WRITE_QUAD - - double sumB=0; - double sumT=0; - double sumR=0; - double sumL=0; - for (int ix=0; ix<3; ix++) { - for (int iy=0; iy<3; iy++) { - sum+=cl[ix+3*iy]; - if (ix<1 ) sumL+=cl[ix+iy*3]; - if (ix>1) sumR+=cl[ix+iy*3]; - if (iy<1) sumB=cl[ix+iy*3]; - if (iy>1) sumT+=cl[ix+iy*3]; - } - } - - totquad=sum; - if ( sumT==0 && sumR==0) { + int getImageSize(int &nnx, int &nny, int &nsx, int &nsy) { + nnx = nSubPixelsX * nPixelsX; + nny = nSubPixelsY * nPixelsY; + nsx = nSubPixelsX; + nsy = nSubPixelsY; + return nSubPixelsX * nSubPixelsY * nPixelsX * nPixelsY; + }; + + int getImageSize() { + return nSubPixelsX * nSubPixelsY * nPixelsX * nPixelsY; + }; + + // create eta distribution, eta rebinnining etc. + // returns flat field image + virtual void prepareInterpolation(int &ok) = 0; + + // create interpolated image + // returns interpolated image + virtual int *getInterpolatedImage() { + // cout << "return interpolated image " << endl; + /* for (int i=0; i= 0 && ix < (nPixelsX * nSubPixelsX) && + iy < (nSubPixelsY * nPixelsY) && iy >= 0) { + // cout << int_x << " " << int_y << " " << " " << ix << " " << iy + // << " " << ix+iy*nPixelsX*nSubPixels << " " << + // hint[ix+iy*nPixelsX*nSubPixels]; + (*(hint + ix + iy * nPixelsX * nSubPixelsX)) += 1; + // cout << " " << hint[ix+iy*nPixelsX*nSubPixels] << endl; + } // else + // cout << "bad! "<< int_x << " " << int_y << " " << " " << ix << " " + // << iy << " " << ix+iy*nPixelsX*nSubPixels << endl; + + return hint; + }; + + virtual int addToFlatField(double *cluster, double &etax, double &etay) = 0; + virtual int addToFlatField(int *cluster, double &etax, double &etay) = 0; + virtual int addToFlatField(double totquad, int quad, int *cl, double &etax, + double &etay) = 0; + virtual int addToFlatField(double totquad, int quad, double *cluster, + double &etax, double &etay) = 0; + virtual int addToFlatField(double etax, double etay) = 0; + + virtual int *getFlatField() { return NULL; }; + virtual int *setFlatField(int *h, int nb = -1, double emin = -1, + double emax = -1) { + return NULL; + }; + virtual void *writeFlatField(const char *imgname) { return NULL; }; + virtual void *readFlatField(const char *imgname, int nb = -1, + double emin = 1, double emax = 0) { + return NULL; + }; + virtual int *getFlatField(int &nb, double &emin, double &emax) { + nb = 0; + emin = 0; + emax = 0; + return getFlatField(); + }; + + virtual void resetFlatField() = 0; + + // virtual void Streamer(TBuffer &b); + + static int calcQuad(int *cl, double &sum, double &totquad, + double sDum[2][2]) { + double cli[3 * 3]; //=new int[3*3]; + for (int i = 0; i < 9; i++) + cli[i] = cl[i]; + return calcQuad(cli, sum, totquad, sDum); + } + + static int calcQuad(double *cl, double &sum, double &totquad, + double sDum[2][2]) { + + int corner = UNDEFINED_QUADRANT; + /* double *cluster[3]; */ + /* cluster[0]=cl; */ + /* cluster[1]=cl+3; */ + /* cluster[2]=cl+6; */ + + sum = 0; + int xoff = 0, yoff = 0; +#ifndef WRITE_QUAD + double sumBL = 0; + double sumTL = 0; + double sumBR = 0; + double sumTR = 0; + for (int ix = 0; ix < 3; ix++) { + for (int iy = 0; iy < 3; iy++) { + sum += cl[ix + 3 * iy]; + if (ix <= 1 && iy <= 1) + sumBL += cl[ix + iy * 3]; + if (ix <= 1 && iy >= 1) + sumTL += cl[ix + iy * 3]; + if (ix >= 1 && iy <= 1) + sumBR += cl[ix + iy * 3]; + if (ix >= 1 && iy >= 1) + sumTR += cl[ix + iy * 3]; + } + } + + /* sDum[0][0] = cluster[0][0]; sDum[1][0] = cluster[1][0]; */ + /* sDum[0][1] = cluster[0][1]; sDum[1][1] = cluster[1][1]; */ corner = BOTTOM_LEFT; - xoff=0; - yoff=0; - } else if ( sumB==0 && sumR==0 ) { - corner = TOP_LEFT; - xoff=0; - yoff=1; - } else if ( sumT==0 && sumL==0) { - corner = BOTTOM_RIGHT; - xoff=1; - yoff=0; - } else if ( sumB==0 && sumL==0) { - xoff=1; - yoff=1; - corner = TOP_RIGHT; - } else - printf("** bad 2x2 cluster!\n"); + totquad = sumBL; + xoff = 0; + yoff = 0; + + if (sumTL >= totquad) { + /* #ifdef WRITE_QUAD */ + /* /\* sDum[0][0] = cluster[1][0]; sDum[1][0] = cluster[2][0]; + * *\/ */ + /* /\* sDum[0][1] = cluster[1][1]; sDum[1][1] = cluster[2][1]; + * *\/ */ + /* if (sumTL ==sum) { */ + /* #endif */ + corner = TOP_LEFT; + totquad = sumTL; + xoff = 0; + yoff = 1; + /* #ifdef WRITE_QUAD */ + /* } */ + /* #endif */ + } + + if (sumBR >= totquad) { + /* sDum[0][0] = cluster[0][1]; sDum[1][0] = cluster[1][1]; */ + /* sDum[0][1] = cluster[0][2]; sDum[1][1] = cluster[1][2]; */ + + /* #ifdef WRITE_QUAD */ + /* /\* sDum[0][0] = cluster[1][0]; sDum[1][0] = cluster[2][0]; + * *\/ */ + /* /\* sDum[0][1] = cluster[1][1]; sDum[1][1] = cluster[2][1]; + * *\/ */ + /* if (sumBR ==sum) { */ + /* #endif */ + corner = BOTTOM_RIGHT; + xoff = 1; + yoff = 0; + totquad = sumBR; + /* #ifdef WRITE_QUAD */ + /* } */ + /* #endif */ + } + + if (sumTR >= totquad) { + /* #ifdef WRITE_QUAD */ + /* /\* sDum[0][0] = cluster[1][0]; sDum[1][0] = cluster[2][0]; + * *\/ */ + /* /\* sDum[0][1] = cluster[1][1]; sDum[1][1] = cluster[2][1]; + * *\/ */ + /* if (sumTR ==sum) { */ + /* #endif */ + xoff = 1; + yoff = 1; + /* sDum[0][0] = cluster[1][1]; sDum[1][0] = cluster[2][1]; */ + /* sDum[0][1] = cluster[1][2]; sDum[1][1] = cluster[2][2]; */ + corner = TOP_RIGHT; + totquad = sumTR; + /* #ifdef WRITE_QUAD */ + /* } */ + /* #endif */ + } + +#endif +#ifdef WRITE_QUAD + + double sumB = 0; + double sumT = 0; + double sumR = 0; + double sumL = 0; + + for (int ix = 0; ix < 3; ix++) { + for (int iy = 0; iy < 3; iy++) { + sum += cl[ix + 3 * iy]; + if (ix < 1) + sumL += cl[ix + iy * 3]; + if (ix > 1) + sumR += cl[ix + iy * 3]; + if (iy < 1) + sumB = cl[ix + iy * 3]; + if (iy > 1) + sumT += cl[ix + iy * 3]; + } + } + + totquad = sum; + if (sumT == 0 && sumR == 0) { + corner = BOTTOM_LEFT; + xoff = 0; + yoff = 0; + } else if (sumB == 0 && sumR == 0) { + corner = TOP_LEFT; + xoff = 0; + yoff = 1; + } else if (sumT == 0 && sumL == 0) { + corner = BOTTOM_RIGHT; + xoff = 1; + yoff = 0; + } else if (sumB == 0 && sumL == 0) { + xoff = 1; + yoff = 1; + corner = TOP_RIGHT; + } else + printf("** bad 2x2 cluster!\n"); #endif + for (int ix = 0; ix < 2; ix++) { + for (int iy = 0; iy < 2; iy++) { + sDum[iy][ix] = cl[ix + xoff + (iy + yoff) * 3]; + } + } - for (int ix=0; ix<2; ix++) { - for (int iy=0; iy<2; iy++) { - sDum[iy][ix] = cl[ix+xoff+(iy+yoff)*3]; - } - } - - return corner; - - } - - static int calcEta(double totquad, double sDum[2][2], double &etax, double &etay){ - double t,r; - - if (totquad>0) { - t = sDum[1][0] + sDum[1][1]; - r = sDum[0][1] + sDum[1][1]; - etax=r/totquad; - etay=t/totquad; - } - return 0; - - } - - static int calcEta(double *cl, double &etax, double &etay, double &sum, double &totquad, double sDum[2][2]) { - int corner = calcQuad(cl,sum,totquad,sDum); - calcEta(totquad, sDum, etax, etay); - - return corner; - } - - - static int calcEta(int *cl, double &etax, double &etay, double &sum, double &totquad, double sDum[2][2]) { - int corner = calcQuad(cl,sum,totquad,sDum); - calcEta(totquad, sDum, etax, etay); - - return corner; - } - - - static int calcEtaL(double totquad, int corner, double sDum[2][2], double &etax, double &etay){ - double t,r, toth, totv; - if (totquad>0) { - switch(corner) { - case TOP_LEFT: - t = sDum[1][1]; - r = sDum[0][1] ; - toth=sDum[0][1]+sDum[0][0]; - totv=sDum[0][1]+sDum[1][1]; - break; - case TOP_RIGHT: - t = sDum[1][0] ; - r = sDum[0][1] ; - toth=sDum[0][1]+sDum[0][0]; - totv=sDum[1][0]+sDum[0][0]; - break; - case BOTTOM_LEFT: - r = sDum[1][1] ; - t = sDum[1][1] ; - toth=sDum[1][0]+sDum[1][1]; - totv=sDum[0][1]+sDum[1][1]; - break; - case BOTTOM_RIGHT: - t = sDum[1][0] ; - r = sDum[1][1] ; - toth=sDum[1][0]+sDum[1][1]; - totv=sDum[1][0]+sDum[0][0]; - break; - default: - etax=-1000; - etay=-1000; - return 0; - } - //etax=r/totquad; - //etay=t/totquad; - etax=r/toth; - etay=t/totv; - } - return 0; - } - - - - static int calcEtaL(double *cl, double &etax, double &etay, double &sum, double &totquad, double sDum[2][2]) { - int corner = calcQuad(cl,sum,totquad,sDum); - calcEtaL(totquad, corner, sDum, etax, etay); - - return corner; - } - - static int calcEtaL(int *cl, double &etax, double &etay, double &sum, double &totquad, double sDum[2][2]) { - int corner = calcQuad(cl,sum,totquad,sDum); - calcEtaL(totquad, corner, sDum, etax, etay); - - return corner; - } - - - - static int calcEtaC3(double *cl, double &etax, double &etay, double &sum, double &totquad, double sDum[2][2]){ - - int corner = calcQuad(cl,sum,totquad,sDum); - calcEta(sum, sDum, etax, etay); - return corner; - - } - - - - static int calcEtaC3(int *cl, double &etax, double &etay, double &sum, double &totquad, double sDum[2][2]){ - - int corner = calcQuad(cl,sum,totquad,sDum); - calcEta(sum, sDum, etax, etay); - return corner; - - } - - - - static int calcEta3(double *cl, double &etax, double &etay, double &sum) { - double l=0,r=0,t=0,b=0, val; - sum=0; - // int quad; - for (int ix=0; ix<3; ix++) { - for (int iy=0; iy<3; iy++) { - val=cl[ix+3*iy]; - sum+=val; - if (iy==0) l+=val; - if (iy==2) r+=val; - if (ix==0) b+=val; - if (ix==2) t+=val; - } - } - if (sum>0) { - etax=(-l+r)/sum; - etay=(-b+t)/sum; + return corner; } - if (etax>=0 && etay>=0) - return TOP_RIGHT; - if (etax<0 && etay>=0) - return TOP_LEFT; - if (etax<0 && etay<0) - return BOTTOM_LEFT; - return BOTTOM_RIGHT; - } + static int calcEta(double totquad, double sDum[2][2], double &etax, + double &etay) { + double t, r; - - static int calcEta3(int *cl, double &etax, double &etay, double &sum) { - double cli[9]; - for (int ix=0; ix<9; ix++) cli[ix]=cl[ix]; - - return calcEta3(cli, etax, etay, sum); - } - - - - static int calcEta3X(double *cl, double &etax, double &etay, double &sum) { - double l,r,t,b; - sum=cl[0]+cl[1]+cl[2]+cl[3]+cl[4]+cl[5]+cl[6]+cl[7]+cl[8]; - if (sum>0) { - l=cl[3]; - r=cl[5]; - b=cl[1]; - t=cl[7]; - etax=(-l+r)/sum; - etay=(-b+t)/sum; + if (totquad > 0) { + t = sDum[1][0] + sDum[1][1]; + r = sDum[0][1] + sDum[1][1]; + etax = r / totquad; + etay = t / totquad; + } + return 0; } - return -1; - } - static int calcEta3X(int *cl, double &etax, double &etay, double &sum) { - double cli[9]; - for (int ix=0; ix<9; ix++) cli[ix]=cl[ix]; - - return calcEta3X(cli, etax, etay, sum); - } + static int calcEta(double *cl, double &etax, double &etay, double &sum, + double &totquad, double sDum[2][2]) { + int corner = calcQuad(cl, sum, totquad, sDum); + calcEta(totquad, sDum, etax, etay); + return corner; + } - /* static int calcMyEta(double totquad, int quad, double *cl, double &etax, double &etay) { */ - /* double l,r,t,b, sum; */ - /* int yoff; */ - /* switch (quad) { */ - /* case BOTTOM_LEFT: */ - /* case BOTTOM_RIGHT: */ - /* yoff=0; */ - /* break; */ - /* case TOP_LEFT: */ - /* case TOP_RIGHT: */ - /* yoff=1; */ - /* break; */ - /* default: */ - /* ; */ - /* } */ - /* l=cl[0+yoff*3]+cl[0+yoff*3+3]; */ - /* r=cl[2+yoff*3]+cl[2+yoff*3+3]; */ - /* b=cl[0+yoff*3]+cl[1+yoff*3]*cl[2+yoff*3]; */ - /* t=cl[0+yoff*3+3]+cl[1+yoff*3+3]*cl[0+yoff*3+3]; */ - /* sum=t+b; */ - /* if (sum>0) { */ - /* etax=(-l+r)/sum; */ - /* etay=(+t)/sum; */ - /* } */ - - /* return -1; */ - /* } */ + static int calcEta(int *cl, double &etax, double &etay, double &sum, + double &totquad, double sDum[2][2]) { + int corner = calcQuad(cl, sum, totquad, sDum); + calcEta(totquad, sDum, etax, etay); - /* static int calcMyEta(double totquad, int quad, int *cl, double &etax, double &etay) { */ - /* double l,r,t,b, sum; */ - /* int yoff; */ - /* switch (quad) { */ - /* case BOTTOM_LEFT: */ - /* case BOTTOM_RIGHT: */ - /* yoff=0; */ - /* break; */ - /* case TOP_LEFT: */ - /* case TOP_RIGHT: */ - /* yoff=1; */ - /* break; */ - /* default: */ - /* ; */ - /* } */ - /* l=cl[0+yoff*3]+cl[0+yoff*3+3]; */ - /* r=cl[2+yoff*3]+cl[2+yoff*3+3]; */ - /* b=cl[0+yoff*3]+cl[1+yoff*3]*cl[2+yoff*3]; */ - /* t=cl[0+yoff*3+3]+cl[1+yoff*3+3]*cl[0+yoff*3+3]; */ - /* sum=t+b; */ - /* if (sum>0) { */ - /* etax=(-l+r)/sum; */ - /* etay=(+t)/sum; */ - /* } */ - - /* return -1; */ - /* } */ + return corner; + } + static int calcEtaL(double totquad, int corner, double sDum[2][2], + double &etax, double &etay) { + double t, r, toth, totv; + if (totquad > 0) { + switch (corner) { + case TOP_LEFT: + t = sDum[1][1]; + r = sDum[0][1]; + toth = sDum[0][1] + sDum[0][0]; + totv = sDum[0][1] + sDum[1][1]; + break; + case TOP_RIGHT: + t = sDum[1][0]; + r = sDum[0][1]; + toth = sDum[0][1] + sDum[0][0]; + totv = sDum[1][0] + sDum[0][0]; + break; + case BOTTOM_LEFT: + r = sDum[1][1]; + t = sDum[1][1]; + toth = sDum[1][0] + sDum[1][1]; + totv = sDum[0][1] + sDum[1][1]; + break; + case BOTTOM_RIGHT: + t = sDum[1][0]; + r = sDum[1][1]; + toth = sDum[1][0] + sDum[1][1]; + totv = sDum[1][0] + sDum[0][0]; + break; + default: + etax = -1000; + etay = -1000; + return 0; + } + // etax=r/totquad; + // etay=t/totquad; + etax = r / toth; + etay = t / totv; + } + return 0; + } + static int calcEtaL(double *cl, double &etax, double &etay, double &sum, + double &totquad, double sDum[2][2]) { + int corner = calcQuad(cl, sum, totquad, sDum); + calcEtaL(totquad, corner, sDum, etax, etay); - /* static int calcEta3X(int *cl, double &etax, double &etay, double &sum) { */ - /* double l,r,t,b; */ - /* sum=cl[0]+cl[1]+cl[2]+cl[3]+cl[4]+cl[5]+cl[6]+cl[7]+cl[8]; */ - /* if (sum>0) { */ - /* l=cl[3]; */ - /* r=cl[5]; */ - /* b=cl[1]; */ - /* t=cl[7]; */ - /* etax=(-l+r)/sum; */ - /* etay=(-b+t)/sum; */ - /* } */ - /* return -1; */ - /* } */ + return corner; + } + static int calcEtaL(int *cl, double &etax, double &etay, double &sum, + double &totquad, double sDum[2][2]) { + int corner = calcQuad(cl, sum, totquad, sDum); + calcEtaL(totquad, corner, sDum, etax, etay); + return corner; + } + static int calcEtaC3(double *cl, double &etax, double &etay, double &sum, + double &totquad, double sDum[2][2]) { + int corner = calcQuad(cl, sum, totquad, sDum); + calcEta(sum, sDum, etax, etay); + return corner; + } + static int calcEtaC3(int *cl, double &etax, double &etay, double &sum, + double &totquad, double sDum[2][2]) { - protected: - int nPixelsX, nPixelsY; - int nSubPixelsX, nSubPixelsY; - int id; - int *hint; + int corner = calcQuad(cl, sum, totquad, sDum); + calcEta(sum, sDum, etax, etay); + return corner; + } + + static int calcEta3(double *cl, double &etax, double &etay, double &sum) { + double l = 0, r = 0, t = 0, b = 0, val; + sum = 0; + // int quad; + for (int ix = 0; ix < 3; ix++) { + for (int iy = 0; iy < 3; iy++) { + val = cl[ix + 3 * iy]; + sum += val; + if (iy == 0) + l += val; + if (iy == 2) + r += val; + if (ix == 0) + b += val; + if (ix == 2) + t += val; + } + } + if (sum > 0) { + etax = (-l + r) / sum; + etay = (-b + t) / sum; + } + + if (etax >= 0 && etay >= 0) + return TOP_RIGHT; + if (etax < 0 && etay >= 0) + return TOP_LEFT; + if (etax < 0 && etay < 0) + return BOTTOM_LEFT; + return BOTTOM_RIGHT; + } + + static int calcEta3(int *cl, double &etax, double &etay, double &sum) { + double cli[9]; + for (int ix = 0; ix < 9; ix++) + cli[ix] = cl[ix]; + + return calcEta3(cli, etax, etay, sum); + } + + static int calcEta3X(double *cl, double &etax, double &etay, double &sum) { + double l, r, t, b; + sum = cl[0] + cl[1] + cl[2] + cl[3] + cl[4] + cl[5] + cl[6] + cl[7] + + cl[8]; + if (sum > 0) { + l = cl[3]; + r = cl[5]; + b = cl[1]; + t = cl[7]; + etax = (-l + r) / sum; + etay = (-b + t) / sum; + } + return -1; + } + + static int calcEta3X(int *cl, double &etax, double &etay, double &sum) { + double cli[9]; + for (int ix = 0; ix < 9; ix++) + cli[ix] = cl[ix]; + + return calcEta3X(cli, etax, etay, sum); + } + + /* static int calcMyEta(double totquad, int quad, double *cl, double &etax, + * double &etay) { */ + /* double l,r,t,b, sum; */ + /* int yoff; */ + /* switch (quad) { */ + /* case BOTTOM_LEFT: */ + /* case BOTTOM_RIGHT: */ + /* yoff=0; */ + /* break; */ + /* case TOP_LEFT: */ + /* case TOP_RIGHT: */ + /* yoff=1; */ + /* break; */ + /* default: */ + /* ; */ + /* } */ + /* l=cl[0+yoff*3]+cl[0+yoff*3+3]; */ + /* r=cl[2+yoff*3]+cl[2+yoff*3+3]; */ + /* b=cl[0+yoff*3]+cl[1+yoff*3]*cl[2+yoff*3]; */ + /* t=cl[0+yoff*3+3]+cl[1+yoff*3+3]*cl[0+yoff*3+3]; */ + /* sum=t+b; */ + /* if (sum>0) { */ + /* etax=(-l+r)/sum; */ + /* etay=(+t)/sum; */ + /* } */ + + /* return -1; */ + /* } */ + + /* static int calcMyEta(double totquad, int quad, int *cl, double &etax, + * double &etay) { */ + /* double l,r,t,b, sum; */ + /* int yoff; */ + /* switch (quad) { */ + /* case BOTTOM_LEFT: */ + /* case BOTTOM_RIGHT: */ + /* yoff=0; */ + /* break; */ + /* case TOP_LEFT: */ + /* case TOP_RIGHT: */ + /* yoff=1; */ + /* break; */ + /* default: */ + /* ; */ + /* } */ + /* l=cl[0+yoff*3]+cl[0+yoff*3+3]; */ + /* r=cl[2+yoff*3]+cl[2+yoff*3+3]; */ + /* b=cl[0+yoff*3]+cl[1+yoff*3]*cl[2+yoff*3]; */ + /* t=cl[0+yoff*3+3]+cl[1+yoff*3+3]*cl[0+yoff*3+3]; */ + /* sum=t+b; */ + /* if (sum>0) { */ + /* etax=(-l+r)/sum; */ + /* etay=(+t)/sum; */ + /* } */ + + /* return -1; */ + /* } */ + + /* static int calcEta3X(int *cl, double &etax, double &etay, double &sum) { + */ + /* double l,r,t,b; */ + /* sum=cl[0]+cl[1]+cl[2]+cl[3]+cl[4]+cl[5]+cl[6]+cl[7]+cl[8]; */ + /* if (sum>0) { */ + /* l=cl[3]; */ + /* r=cl[5]; */ + /* b=cl[1]; */ + /* t=cl[7]; */ + /* etax=(-l+r)/sum; */ + /* etay=(-b+t)/sum; */ + /* } */ + /* return -1; */ + /* } */ + + protected: + int nPixelsX, nPixelsY; + int nSubPixelsX, nSubPixelsY; + int id; + int *hint; }; #endif diff --git a/slsDetectorCalibration/jungfrauExecutables/jungfrauClusterFinder.cpp b/slsDetectorCalibration/jungfrauExecutables/jungfrauClusterFinder.cpp index edf1a83b9..a5980e284 100644 --- a/slsDetectorCalibration/jungfrauExecutables/jungfrauClusterFinder.cpp +++ b/slsDetectorCalibration/jungfrauExecutables/jungfrauClusterFinder.cpp @@ -3,161 +3,148 @@ //#include "sls/ansi.h" #include - //#include "moench03T1ZmqData.h" #include "jungfrauHighZSingleChipData.h" - #include "multiThreadedAnalogDetector.h" #include "singlePhotonDetector.h" -#include -#include #include +#include +#include #include #include using namespace std; - int main(int argc, char *argv[]) { + if (argc < 6) { + cout << "Usage is " << argv[0] << "indir outdir fname runmin runmax " + << endl; + return 1; + } + int p = 10000; + int fifosize = 1000; + int nthreads = 1; + int nsubpix = 25; + int etabins = nsubpix * 10; + double etamin = -1, etamax = 2; + int csize = 3; + int nx = 400, ny = 400; + int save = 1; + int nsigma = 5; + int nped = 1000; + int ndark = 100; + int ok; + int iprog = 0; - if (argc<6) { - cout << "Usage is " << argv[0] << "indir outdir fname runmin runmax " << endl; - return 1; - } - int p=10000; - int fifosize=1000; - int nthreads=1; - int nsubpix=25; - int etabins=nsubpix*10; - double etamin=-1, etamax=2; - int csize=3; - int nx=400, ny=400; - int save=1; - int nsigma=5; - int nped=1000; - int ndark=100; - int ok; - int iprog=0; + jungfrauHighZSingleChipData *decoder = new jungfrauHighZSingleChipData(); + decoder->getDetectorSize(nx, ny); + cout << "nx " << nx << " ny " << ny << endl; + // moench03T1ZmqData *decoder=new moench03T1ZmqData(); + singlePhotonDetector *filter = + new singlePhotonDetector(decoder, csize, nsigma, 1, 0, nped, 200); + // char tit[10000]; + cout << "filter " << endl; + int *image; + filter->newDataSet(); - jungfrauHighZSingleChipData *decoder=new jungfrauHighZSingleChipData(); + int ff, np; + int dsize = decoder->getDataSize(); + cout << " data size is " << dsize; - decoder->getDetectorSize(nx,ny); - cout << "nx " << nx << " ny " << ny << endl; + char data[dsize]; - //moench03T1ZmqData *decoder=new moench03T1ZmqData(); - singlePhotonDetector *filter=new singlePhotonDetector(decoder,csize, nsigma, 1, 0, nped, 200); - // char tit[10000]; - cout << "filter " << endl; + ifstream filebin; + char *indir = argv[1]; + char *outdir = argv[2]; + char *fformat = argv[3]; + int runmin = atoi(argv[4]); + int runmax = atoi(argv[5]); + char fname[10000]; + char outfname[10000]; + char imgfname[10000]; + char pedfname[10000]; + char fn[10000]; + std::time_t end_time; + FILE *of = NULL; + cout << "input directory is " << indir << endl; + cout << "output directory is " << outdir << endl; + cout << "fileformat is " << fformat << endl; - int* image; - filter->newDataSet(); - - - int ff, np; - int dsize=decoder->getDataSize(); - cout << " data size is " << dsize; - - - char data[dsize]; - - ifstream filebin; - char *indir=argv[1]; - char *outdir=argv[2]; - char *fformat=argv[3]; - int runmin=atoi(argv[4]); - int runmax=atoi(argv[5]); - - char fname[10000]; - char outfname[10000]; - char imgfname[10000]; - char pedfname[10000]; - char fn[10000]; - - std::time_t end_time; - - FILE *of=NULL; - cout << "input directory is " << indir << endl; - cout << "output directory is " << outdir << endl; - cout << "fileformat is " << fformat << endl; - - - std::time(&end_time); - cout << std::ctime(&end_time) << endl; - - char* buff; - multiThreadedAnalogDetector *mt=new multiThreadedAnalogDetector(filter,nthreads,fifosize); - - - mt->setDetectorMode(ePhotonCounting); - mt->setFrameMode(eFrame); - mt->StartThreads(); - mt->popFree(buff); - - - cout << "mt " << endl; - - int ifr=0; - - - for (int irun=runmin; irunsetFilePointer(of); - // cout << "file pointer set " << endl; - } else { - cout << "Could not open "<< outfname << " for writing " << endl; - mt->setFilePointer(NULL); - return 1; - } - // //while read frame - ff=-1; - while (decoder->readNextFrame(filebin, ff, np,buff)) { + cout << std::ctime(&end_time) << endl; - mt->pushData(buff); - mt->nextThread(); - mt->popFree(buff); - ifr++; - if (ifr%10000==0) cout << ifr << " " << ff << endl; - ff=-1; - } - cout << "--" << endl; - filebin.close(); - while (mt->isBusy()) {;}//wait until all data are processed from the queues - if (of) - fclose(of); - - mt->writeImage(imgfname); - mt->clearImage(); - - std::time(&end_time); - cout << std::ctime(&end_time) << endl; + char *buff; + multiThreadedAnalogDetector *mt = + new multiThreadedAnalogDetector(filter, nthreads, fifosize); - } else - cout << "Could not open "<< fname << " for reading " << endl; - - - } - + mt->setDetectorMode(ePhotonCounting); + mt->setFrameMode(eFrame); + mt->StartThreads(); + mt->popFree(buff); - return 0; + cout << "mt " << endl; + + int ifr = 0; + + for (int irun = runmin; irun < runmax; irun++) { + sprintf(fn, fformat, irun); + sprintf(fname, "%s/%s.raw", indir, fn); + sprintf(outfname, "%s/%s.clust", outdir, fn); + sprintf(imgfname, "%s/%s.tiff", outdir, fn); + std::time(&end_time); + cout << std::ctime(&end_time) << endl; + cout << fname << " " << outfname << " " << imgfname << endl; + filebin.open((const char *)(fname), ios::in | ios::binary); + // //open file + if (filebin.is_open()) { + of = fopen(outfname, "w"); + if (of) { + mt->setFilePointer(of); + // cout << "file pointer set " << endl; + } else { + cout << "Could not open " << outfname << " for writing " + << endl; + mt->setFilePointer(NULL); + return 1; + } + // //while read frame + ff = -1; + while (decoder->readNextFrame(filebin, ff, np, buff)) { + + mt->pushData(buff); + mt->nextThread(); + mt->popFree(buff); + ifr++; + if (ifr % 10000 == 0) + cout << ifr << " " << ff << endl; + ff = -1; + } + cout << "--" << endl; + filebin.close(); + while (mt->isBusy()) { + ; + } // wait until all data are processed from the queues + if (of) + fclose(of); + + mt->writeImage(imgfname); + mt->clearImage(); + + std::time(&end_time); + cout << std::ctime(&end_time) << endl; + + } else + cout << "Could not open " << fname << " for reading " << endl; + } + + return 0; } - diff --git a/slsDetectorCalibration/jungfrauExecutables/jungfrauInterpolation.cpp b/slsDetectorCalibration/jungfrauExecutables/jungfrauInterpolation.cpp index dc9953590..889022679 100644 --- a/slsDetectorCalibration/jungfrauExecutables/jungfrauInterpolation.cpp +++ b/slsDetectorCalibration/jungfrauExecutables/jungfrauInterpolation.cpp @@ -17,100 +17,103 @@ #endif //#include "etaInterpolationPosXY.h" -#include "noInterpolation.h" #include "etaInterpolationPosXY.h" +#include "noInterpolation.h" //#include "etaInterpolationCleverAdaptiveBins.h" //#include "etaInterpolationRandomBins.h" using namespace std; -#define NC 400 -#define NR 400 -#define MAX_ITERATIONS (nSubPixels*100) +#define NC 400 +#define NR 400 +#define MAX_ITERATIONS (nSubPixels * 100) #define XTALK int main(int argc, char *argv[]) { #ifndef FF - if (argc<9) { - cout << "Wrong usage! Should be: "<< argv[0] << " infile etafile outfile runmin runmax ns cmin cmax" << endl; - return 1; - } -#endif - -#ifdef FF - if (argc<7) { - cout << "Wrong usage! Should be: "<< argv[0] << " infile etafile runmin runmax cmin cmax" << endl; - return 1; - } -#endif - int iarg=4; - char infname[10000]; - char fname[10000]; - char outfname[10000]; -#ifndef FF - iarg=4; + if (argc < 9) { + cout << "Wrong usage! Should be: " << argv[0] + << " infile etafile outfile runmin runmax ns cmin cmax" << endl; + return 1; + } #endif #ifdef FF - iarg=3; + if (argc < 7) { + cout << "Wrong usage! Should be: " << argv[0] + << " infile etafile runmin runmax cmin cmax" << endl; + return 1; + } #endif - int runmin=atoi(argv[iarg++]); - int runmax=atoi(argv[iarg++]); - cout << "Run min: " << runmin << endl; - cout << "Run max: " << runmax << endl; - - int nsubpix=4; + int iarg = 4; + char infname[10000]; + char fname[10000]; + char outfname[10000]; #ifndef FF - nsubpix=atoi(argv[iarg++]); - cout << "Subpix: " << nsubpix << endl; + iarg = 4; #endif - float cmin=atof(argv[iarg++]); - float cmax=atof(argv[iarg++]); - cout << "Energy min: " << cmin << endl; - cout << "Energy max: " << cmax << endl; - //int etabins=500; - int etabins=1000;//nsubpix*2*100; - double etamin=-1, etamax=2; - //double etamin=-0.1, etamax=1.1; - double eta3min=-2, eta3max=2; - int quad; - double sum, totquad; - double sDum[2][2]; - double etax, etay, int_x, int_y; - double eta3x, eta3y, int3_x, int3_y, noint_x, noint_y; - int ok; - int f0=-1; - int ix, iy, isx, isy; - int nframes=0, lastframe=-1; - double d_x, d_y, res=5, xx, yy; - int nph=0, badph=0, totph=0; - FILE *f=NULL; + +#ifdef FF + iarg = 3; +#endif + int runmin = atoi(argv[iarg++]); + int runmax = atoi(argv[iarg++]); + cout << "Run min: " << runmin << endl; + cout << "Run max: " << runmax << endl; + + int nsubpix = 4; +#ifndef FF + nsubpix = atoi(argv[iarg++]); + cout << "Subpix: " << nsubpix << endl; +#endif + float cmin = atof(argv[iarg++]); + float cmax = atof(argv[iarg++]); + cout << "Energy min: " << cmin << endl; + cout << "Energy max: " << cmax << endl; + // int etabins=500; + int etabins = 1000; // nsubpix*2*100; + double etamin = -1, etamax = 2; + // double etamin=-0.1, etamax=1.1; + double eta3min = -2, eta3max = 2; + int quad; + double sum, totquad; + double sDum[2][2]; + double etax, etay, int_x, int_y; + double eta3x, eta3y, int3_x, int3_y, noint_x, noint_y; + int ok; + int f0 = -1; + int ix, iy, isx, isy; + int nframes = 0, lastframe = -1; + double d_x, d_y, res = 5, xx, yy; + int nph = 0, badph = 0, totph = 0; + FILE *f = NULL; #ifdef DOUBLE_SPH - single_photon_hit_double cl(3,3); + single_photon_hit_double cl(3, 3); #endif #ifndef DOUBLE_SPH - single_photon_hit cl(3,3); + single_photon_hit cl(3, 3); #endif - int nSubPixels=nsubpix; + int nSubPixels = nsubpix; #ifndef NOINTERPOLATION - eta2InterpolationPosXY *interp=new eta2InterpolationPosXY(NC, NR, nsubpix, etabins, etamin, etamax); - //eta2InterpolationCleverAdaptiveBins *interp=new eta2InterpolationCleverAdaptiveBins(NC, NR, nsubpix, etabins, etamin, etamax); + eta2InterpolationPosXY *interp = + new eta2InterpolationPosXY(NC, NR, nsubpix, etabins, etamin, etamax); + // eta2InterpolationCleverAdaptiveBins *interp=new + // eta2InterpolationCleverAdaptiveBins(NC, NR, nsubpix, etabins, etamin, + // etamax); #endif #ifdef NOINTERPOLATION - noInterpolation *interp=new noInterpolation(NC, NR, nsubpix); + noInterpolation *interp = new noInterpolation(NC, NR, nsubpix); #endif - - #ifndef FF #ifndef NOINTERPOLATION cout << "read ff " << argv[2] << endl; - sprintf(fname,"%s",argv[2]); + sprintf(fname, "%s", argv[2]); interp->readFlatField(fname); - interp->prepareInterpolation(ok);//, MAX_ITERATIONS); + interp->prepareInterpolation(ok); //, MAX_ITERATIONS); #endif // return 0; #endif @@ -119,134 +122,144 @@ int main(int argc, char *argv[]) { #endif int *img; - float *totimg=new float[NC*NR*nsubpix*nsubpix]; - for (ix=0; ixcalcQuad(cl.get_cluster(), sum, totquad, sDum); - quad=interp->calcEta(cl.get_cluster(), etax, etay, sum, totquad, sDum); - if (sum>cmin && totquad/sum>0.8 && totquad/sum<1.2 && sum200 && sum<580) { - // interp->getInterpolatedPosition(cl.x,cl.y, totquad,quad,cl.get_cluster(),int_x, int_y); + f = fopen(infname, "r"); + if (f) { + cout << infname << endl; + nframes = 0; + f0 = -1; + + while (cl.read(f)) { + totph++; + if (lastframe != cl.iframe) { + lastframe = cl.iframe; + // cout << cl.iframe << endl; + // f0=cl.iframe; + if (nframes == 0) + f0 = lastframe; + nframes++; + } + // quad=interp->calcQuad(cl.get_cluster(), sum, totquad, sDum); + quad = interp->calcEta(cl.get_cluster(), etax, etay, sum, + totquad, sDum); + if (sum > cmin && totquad / sum > 0.8 && totquad / sum < 1.2 && + sum < cmax) { + nph++; + // if (sum>200 && sum<580) { + // interp->getInterpolatedPosition(cl.x,cl.y, + // totquad,quad,cl.get_cluster(),int_x, int_y); // #ifdef SOLEIL // if (cl.x>210 && cl.x<240 && cl.y>210 && cl.y<240) { // #endif #ifndef FF - // interp->getInterpolatedPosition(cl.x,cl.y, cl.get_cluster(),int_x, int_y); - interp->getInterpolatedPosition(cl.x,cl.y, etax, etay, quad,int_x, int_y); - // cout <<"**************"<< endl; - // cout << cl.x << " " << cl.y << " " << sum << endl; - // cl.print(); - // cout << int_x << " " << int_y << endl; - // cout <<"**************"<< endl; - // if (etax!=0 && etay!=0 && etax!=1 && etay!=1) - interp->addToImage(int_x, int_y); - if (int_x<0 || int_y<0 || int_x>400 || int_y>400) { - cout <<"**************"<< endl; - cout << cl.x << " " << cl.y << " " << sum << endl; - cl.print(); - cout << int_x << " " << int_y << endl; - cout <<"**************"<< endl; - } + // interp->getInterpolatedPosition(cl.x,cl.y, + // cl.get_cluster(),int_x, int_y); + interp->getInterpolatedPosition(cl.x, cl.y, etax, etay, + quad, int_x, int_y); + // cout <<"**************"<< endl; + // cout << cl.x << " " << cl.y << " " << sum << endl; + // cl.print(); + // cout << int_x << " " << int_y << endl; + // cout <<"**************"<< endl; + // if (etax!=0 && etay!=0 && etax!=1 && etay!=1) + interp->addToImage(int_x, int_y); + if (int_x < 0 || int_y < 0 || int_x > 400 || int_y > 400) { + cout << "**************" << endl; + cout << cl.x << " " << cl.y << " " << sum << endl; + cl.print(); + cout << int_x << " " << int_y << endl; + cout << "**************" << endl; + } #endif #ifdef FF - // interp->addToFlatField(cl.get_cluster(), etax, etay); -// #ifdef UCL -// if (cl.x>50) -// #endif -// if (etax!=0 && etay!=0 && etax!=1 && etay!=1) - interp->addToFlatField(etax, etay); - // if (etax==0 || etay==0) cout << cl.x << " " << cl.y << endl; - -#endif -// #ifdef SOLEIL -// } -// #endif - - if (nph%1000000==0) cout << nph << endl; - if (nph%10000000==0) { -#ifndef FF - interp->writeInterpolatedImage(outfname); -#endif -#ifdef FF - interp->writeFlatField(outfname); -#endif - - } - } - - } - - - fclose(f); -#ifdef FF - interp->writeFlatField(outfname); -#endif - -#ifndef FF - interp->writeInterpolatedImage(outfname); + // interp->addToFlatField(cl.get_cluster(), etax, etay); + // #ifdef UCL + // if (cl.x>50) + // #endif + // if (etax!=0 && etay!=0 && etax!=1 && etay!=1) + interp->addToFlatField(etax, etay); + // if (etax==0 || etay==0) cout << cl.x << " " << cl.y << + // endl; - img=interp->getInterpolatedImage(); - for (ix=0; ixwriteInterpolatedImage(outfname); +#endif +#ifdef FF + interp->writeFlatField(outfname); +#endif + } + } + } + + fclose(f); +#ifdef FF + interp->writeFlatField(outfname); +#endif + +#ifndef FF + interp->writeInterpolatedImage(outfname); + + img = interp->getInterpolatedImage(); + for (ix = 0; ix < NC; ix++) { + for (iy = 0; iy < NR; iy++) { + for (isx = 0; isx < nsubpix; isx++) { + for (isy = 0; isy < nsubpix; isy++) { + totimg[ix * nsubpix + isx + + (iy * nsubpix + isy) * (NC * nsubpix)] += + img[ix * nsubpix + isx + + (iy * nsubpix + isy) * (NC * nsubpix)]; + } + } + } + } + cout << "Read " << nframes << " frames (first frame: " << f0 + << " last frame: " << lastframe << " delta:" << lastframe - f0 + << ") nph=" << nph << endl; + interp->clearInterpolatedImage(); +#endif + + } else + cout << "could not open file " << infname << endl; } #ifndef FF - sprintf(outfname,argv[3],11111); - WriteToTiff(totimg, outfname,NC*nsubpix,NR*nsubpix); -#endif - -#ifdef FF - interp->writeFlatField(outfname); + sprintf(outfname, argv[3], 11111); + WriteToTiff(totimg, outfname, NC * nsubpix, NR * nsubpix); #endif - cout << "Filled " << nph << " (/"<< totph <<") " << endl; +#ifdef FF + interp->writeFlatField(outfname); +#endif + + cout << "Filled " << nph << " (/" << totph << ") " << endl; return 0; } - diff --git a/slsDetectorCalibration/jungfrauExecutables/jungfrauPhotonCounter.cpp b/slsDetectorCalibration/jungfrauExecutables/jungfrauPhotonCounter.cpp index 8b81cdebe..bf4ceffb0 100644 --- a/slsDetectorCalibration/jungfrauExecutables/jungfrauPhotonCounter.cpp +++ b/slsDetectorCalibration/jungfrauExecutables/jungfrauPhotonCounter.cpp @@ -22,13 +22,12 @@ #endif - #ifdef CSAXS_FP #include "moench03T1ReceiverData.h" -#endif +#endif #ifdef OLDDATA #include "moench03Ctb10GbT1Data.h" -#endif +#endif // #include "interpolatingDetector.h" //#include "etaInterpolationPosXY.h" @@ -36,420 +35,413 @@ // #include "noInterpolation.h" #include "multiThreadedCountingDetector.h" //#include "multiThreadedAnalogDetector.h" -#include "singlePhotonDetector.h" -#include "moench03GhostSummation.h" #include "moench03CommonMode.h" +#include "moench03GhostSummation.h" +#include "singlePhotonDetector.h" //#include "interpolatingDetector.h" -#include -#include #include +#include +#include #include #include using namespace std; - int main(int argc, char *argv[]) { + if (argc < 4) { + cout << "Usage is " << argv[0] + << "indir outdir fname [runmin] [runmax] [pedfile] [threshold] " + "[nframes] [xmin xmax ymin ymax] [gainmap]" + << endl; + cout << "threshold <0 means analog; threshold=0 means cluster finder; " + "threshold>0 means photon counting" + << endl; + cout << "nframes <0 means sum everything; nframes=0 means one file per " + "run; nframes>0 means one file every nframes" + << endl; + return 1; + } - if (argc<4) { - cout << "Usage is " << argv[0] << "indir outdir fname [runmin] [runmax] [pedfile] [threshold] [nframes] [xmin xmax ymin ymax] [gainmap]" << endl; - cout << "threshold <0 means analog; threshold=0 means cluster finder; threshold>0 means photon counting" << endl; - cout << "nframes <0 means sum everything; nframes=0 means one file per run; nframes>0 means one file every nframes" << endl; - return 1; - } + int p = 10000; + int fifosize = 1000; + int nthreads = 10; + int nsubpix = 25; + int etabins = nsubpix * 10; + double etamin = -1, etamax = 2; + int csize = 3; + int save = 1; + int nsigma = 5; + int nped = 10000; + int ndark = 100; + int ok; + int iprog = 0; - int p=10000; - int fifosize=1000; - int nthreads=10; - int nsubpix=25; - int etabins=nsubpix*10; - double etamin=-1, etamax=2; - int csize=3; - int save=1; - int nsigma=5; - int nped=10000; - int ndark=100; - int ok; - int iprog=0; - - int cf=0; + int cf = 0; #ifdef NEWRECEIVER #ifdef RECT - cout << "Should be rectangular!" <getDetectorSize(nx,ny); + decoder->getDetectorSize(nx, ny); - int ncol_cm=CM_ROWS; - double xt_ghost=C_GHOST; - moench03CommonMode *cm=NULL; - moench03GhostSummation *gs; - double *gainmap=NULL; - float *gm; + int ncol_cm = CM_ROWS; + double xt_ghost = C_GHOST; + moench03CommonMode *cm = NULL; + moench03GhostSummation *gs; + double *gainmap = NULL; + float *gm; + int size = 327680; ////atoi(argv[3]); + int *image; + // int* image =new int[327680/sizeof(int)]; - int size = 327680;////atoi(argv[3]); - - int* image; - //int* image =new int[327680/sizeof(int)]; + int ff, np; + // cout << " data size is " << dsize; - int ff, np; - //cout << " data size is " << dsize; - + ifstream filebin; + char *indir = argv[1]; + char *outdir = argv[2]; + char *fformat = argv[3]; + int runmin = 0; + // cout << "argc is " << argc << endl; + if (argc >= 5) { + runmin = atoi(argv[4]); + } - ifstream filebin; - char *indir=argv[1]; - char *outdir=argv[2]; - char *fformat=argv[3]; - int runmin=0; - - // cout << "argc is " << argc << endl; - if (argc>=5) { - runmin=atoi(argv[4]); - } + int runmax = runmin; - int runmax=runmin; + if (argc >= 6) { + runmax = atoi(argv[5]); + } - if (argc>=6) { - runmax=atoi(argv[5]); - } + char *pedfile = NULL; + if (argc >= 7) { + pedfile = argv[6]; + } + double thr = 0; + double thr1 = 1; - char *pedfile=NULL; - if (argc>=7) { - pedfile=argv[6]; - } - double thr=0; - double thr1=1; + if (argc >= 8) { + thr = atof(argv[7]); + } - if (argc>=8) { - thr=atof(argv[7]); - } - + int nframes = 0; - int nframes=0; - - if (argc>=9) { - nframes=atoi(argv[8]); - } + if (argc >= 9) { + nframes = atoi(argv[8]); + } - int xmin=0, xmax=nx, ymin=0, ymax=ny; - if (argc>=13) { - xmin=atoi(argv[9]); - xmax=atoi(argv[10]); - ymin=atoi(argv[11]); - ymax=atoi(argv[12]); - } + int xmin = 0, xmax = nx, ymin = 0, ymax = ny; + if (argc >= 13) { + xmin = atoi(argv[9]); + xmax = atoi(argv[10]); + ymin = atoi(argv[11]); + ymax = atoi(argv[12]); + } - - char *gainfname=NULL; - if (argc>13) { - gainfname=argv[13]; - cout << "Gain map file name is: " << gainfname << endl; - } + char *gainfname = NULL; + if (argc > 13) { + gainfname = argv[13]; + cout << "Gain map file name is: " << gainfname << endl; + } - + char ffname[10000]; + char fname[10000]; + char imgfname[10000]; + char cfname[10000]; + char fn[10000]; + std::time_t end_time; - char ffname[10000]; - char fname[10000]; - char imgfname[10000]; - char cfname[10000]; - char fn[10000]; - - std::time_t end_time; + FILE *of = NULL; + cout << "input directory is " << indir << endl; + cout << "output directory is " << outdir << endl; + cout << "input file is " << fformat << endl; + cout << "runmin is " << runmin << endl; + cout << "runmax is " << runmax << endl; + if (pedfile) + cout << "pedestal file is " << pedfile << endl; + if (thr > 0) + cout << "threshold is " << thr << endl; + cout << "Nframes is " << nframes << endl; - FILE *of=NULL; - cout << "input directory is " << indir << endl; - cout << "output directory is " << outdir << endl; - cout << "input file is " << fformat << endl; - cout << "runmin is " << runmin << endl; - cout << "runmax is " << runmax << endl; - if (pedfile) - cout << "pedestal file is " << pedfile << endl; - if (thr>0) - cout << "threshold is " << thr << endl; - cout << "Nframes is " << nframes << endl; - - uint32_t nnx, nny; - double *gmap; + uint32_t nnx, nny; + double *gmap; - // if (gainfname) { - // gm=ReadFromTiff(gainfname, nny, nnx); - // if (gm && nnx==nx && nny==ny) { - // gmap=new double[nx*ny]; - // for (int i=0; ireadGainMap(gainfname)) - cout << "using gain map " << gainfname << endl; - else - cout << "Could not open gain map " << gainfname << endl; - } else - thr=0.15*thr; - filter->newDataSet(); - int dsize=decoder->getDataSize(); + if (filter->readGainMap(gainfname)) + cout << "using gain map " << gainfname << endl; + else + cout << "Could not open gain map " << gainfname << endl; + } else + thr = 0.15 * thr; + filter->newDataSet(); + int dsize = decoder->getDataSize(); + char data[dsize]; - char data[dsize]; - - - - - - //#ifndef ANALOG - if (thr>0) { - cout << "threshold is " << thr << endl; //#ifndef ANALOG - filter->setThreshold(thr); + if (thr > 0) { + cout << "threshold is " << thr << endl; + //#ifndef ANALOG + filter->setThreshold(thr); + //#endif + cf = 0; + + } else + cf = 1; //#endif - cf=0; - } else - cf=1; - //#endif + filter->setROI(xmin, xmax, ymin, ymax); + std::time(&end_time); + cout << std::ctime(&end_time) << endl; + char *buff; - filter->setROI(xmin,xmax,ymin,ymax); - std::time(&end_time); - cout << std::ctime(&end_time) << endl; - - char* buff; - - // multiThreadedAnalogDetector *mt=new multiThreadedAnalogDetector(filter,nthreads,fifosize); - multiThreadedCountingDetector *mt=new multiThreadedCountingDetector(filter,nthreads,fifosize); + // multiThreadedAnalogDetector *mt=new + // multiThreadedAnalogDetector(filter,nthreads,fifosize); + multiThreadedCountingDetector *mt = + new multiThreadedCountingDetector(filter, nthreads, fifosize); #ifndef ANALOG mt->setDetectorMode(ePhotonCounting); cout << "Counting!" << endl; - if (thr>0) { - cf=0; - } + if (thr > 0) { + cf = 0; + } #endif //{ #ifdef ANALOG - mt->setDetectorMode(eAnalog); - cout << "Analog!" << endl; - cf=0; - //thr1=thr; -#endif - // } - - mt->StartThreads(); - mt->popFree(buff); + mt->setDetectorMode(eAnalog); + cout << "Analog!" << endl; + cf = 0; + // thr1=thr; +#endif + // } + mt->StartThreads(); + mt->popFree(buff); - // cout << "mt " << endl; + // cout << "mt " << endl; - int ifr=0; + int ifr = 0; - double ped[nx*ny], *ped1; + double ped[nx * ny], *ped1; + if (pedfile) { - if (pedfile) { + cout << "PEDESTAL " << endl; + sprintf(imgfname, "%s/pedestals.tiff", outdir); - cout << "PEDESTAL " << endl; - sprintf(imgfname,"%s/pedestals.tiff",outdir); + if (string(pedfile).find(".tif") == std::string::npos) { + sprintf(fname, "%s.raw", pedfile); + cout << fname << endl; + std::time(&end_time); + cout << "aaa" << std::ctime(&end_time) << endl; - if (string(pedfile).find(".tif")==std::string::npos){ - sprintf(fname,"%s.raw",pedfile); - cout << fname << endl ; - std::time(&end_time); - cout << "aaa" << std::ctime(&end_time) << endl; - - - mt->setFrameMode(ePedestal); - // sprintf(fn,fformat,irun); - filebin.open((const char *)(fname), ios::in | ios::binary); - // //open file - if (filebin.is_open()){ - ff=-1; - while (decoder->readNextFrame(filebin, ff, np,buff)) { - if (np==40) { - mt->pushData(buff); - mt->nextThread(); - mt->popFree(buff); - ifr++; - if (ifr%100==0) - cout << ifr << " " << ff << " " << np << endl; - } else - cout << ifr << " " << ff << " " << np << endl; - ff=-1; - } - filebin.close(); - while (mt->isBusy()) {;} - - } else - cout << "Could not open pedestal file "<< fname << " for reading " << endl; - } else { - float *pp=ReadFromTiff(pedfile, nny, nnx); - if (pp && nnx==nx && nny==ny) { - for (int i=0; isetPedestal(ped); - // ped1=mt->getPedestal(); - - // for (int i=0; isetFrameMode(ePedestal); + // sprintf(fn,fformat,irun); + filebin.open((const char *)(fname), ios::in | ios::binary); + // //open file + if (filebin.is_open()) { + ff = -1; + while (decoder->readNextFrame(filebin, ff, np, buff)) { + if (np == 40) { + mt->pushData(buff); + mt->nextThread(); + mt->popFree(buff); + ifr++; + if (ifr % 100 == 0) + cout << ifr << " " << ff << " " << np << endl; + } else + cout << ifr << " " << ff << " " << np << endl; + ff = -1; + } + filebin.close(); + while (mt->isBusy()) { + ; + } - // cout << ped[i]<<"/"<setPedestal(ped); + // ped1=mt->getPedestal(); + + // for (int i=0; iwritePedestal(imgfname); + std::time(&end_time); + cout << std::ctime(&end_time) << endl; } - mt->writePedestal(imgfname); - std::time(&end_time); - cout << std::ctime(&end_time) << endl; - } - + ifr = 0; + int ifile = 0; - ifr=0; - int ifile=0; - - mt->setFrameMode(eFrame); + mt->setFrameMode(eFrame); - for (int irun=runmin; irun<=runmax; irun++) { - cout << "DATA " ; - // sprintf(fn,fformat,irun); - sprintf(ffname,"%s/%s.raw",indir,fformat); - sprintf(fname,ffname,irun); - sprintf(ffname,"%s/%s.tiff",outdir,fformat); - sprintf(imgfname,ffname,irun); - sprintf(ffname,"%s/%s.clust",outdir,fformat); - sprintf(cfname,ffname,irun); - cout << fname << " " ; - cout << imgfname << endl; - std::time(&end_time); - cout << std::ctime(&end_time) << endl; - // cout << fname << " " << outfname << " " << imgfname << endl; - filebin.open((const char *)(fname), ios::in | ios::binary); - // //open file - ifile=0; - if (filebin.is_open()){ - if (thr<=0 && cf!=0) { //cluster finder - if (of==NULL) { - of=fopen(cfname,"w"); - if (of) { - mt->setFilePointer(of); - cout << "file pointer set " << endl; - } else { - cout << "Could not open "<< cfname << " for writing " << endl; - mt->setFilePointer(NULL); - return 1; - } - } - } - // //while read frame - ff=-1; - ifr=0; - while (decoder->readNextFrame(filebin, ff, np,buff)) { - if (np==40) { - // cout << "*"<pushData(buff); - // // //pop - mt->nextThread(); - // // // cout << " " << (void*)buff; - mt->popFree(buff); + for (int irun = runmin; irun <= runmax; irun++) { + cout << "DATA "; + // sprintf(fn,fformat,irun); + sprintf(ffname, "%s/%s.raw", indir, fformat); + sprintf(fname, ffname, irun); + sprintf(ffname, "%s/%s.tiff", outdir, fformat); + sprintf(imgfname, ffname, irun); + sprintf(ffname, "%s/%s.clust", outdir, fformat); + sprintf(cfname, ffname, irun); + cout << fname << " "; + cout << imgfname << endl; + std::time(&end_time); + cout << std::ctime(&end_time) << endl; + // cout << fname << " " << outfname << " " << imgfname << endl; + filebin.open((const char *)(fname), ios::in | ios::binary); + // //open file + ifile = 0; + if (filebin.is_open()) { + if (thr <= 0 && cf != 0) { // cluster finder + if (of == NULL) { + of = fopen(cfname, "w"); + if (of) { + mt->setFilePointer(of); + cout << "file pointer set " << endl; + } else { + cout << "Could not open " << cfname << " for writing " + << endl; + mt->setFilePointer(NULL); + return 1; + } + } + } + // //while read frame + ff = -1; + ifr = 0; + while (decoder->readNextFrame(filebin, ff, np, buff)) { + if (np == 40) { + // cout << "*"<pushData(buff); + // // //pop + mt->nextThread(); + // // // cout << " " << (void*)buff; + mt->popFree(buff); + ifr++; + if (ifr % 100 == 0) + cout << ifr << " " << ff << endl; + if (nframes > 0) { + if (ifr % nframes == 0) { + // The name has an additional "_fXXXXX" at the end, + // where "XXXXX" is the initial frame number of the + // image (0,1000,2000...) + sprintf(ffname, "%s/%s_f%05d.tiff", outdir, fformat, + ifile); + sprintf(imgfname, ffname, irun); + // cout << "Writing tiff to " << imgfname << " " << + // thr1 << endl; + mt->writeImage(imgfname, thr1); + mt->clearImage(); + ifile++; + } + } + } else + cout << ifr << " " << ff << " " << np << endl; + ff = -1; + } + cout << "--" << endl; + filebin.close(); + // //close file + // //join threads + while (mt->isBusy()) { + ; + } + if (nframes >= 0) { + if (nframes > 0) { + sprintf(ffname, "%s/%s_f%05d.tiff", outdir, fformat, ifile); + sprintf(imgfname, ffname, irun); + } else { + sprintf(ffname, "%s/%s.tiff", outdir, fformat); + sprintf(imgfname, ffname, irun); + } + cout << "Writing tiff to " << imgfname << " " << thr1 << endl; + mt->writeImage(imgfname, thr1); + mt->clearImage(); + if (of) { + fclose(of); + of = NULL; + mt->setFilePointer(NULL); + } + } + std::time(&end_time); + cout << std::ctime(&end_time) << endl; + } else + cout << "Could not open " << fname << " for reading " << endl; + } + if (nframes < 0) { + sprintf(ffname, "%s/%s.tiff", outdir, fformat); + strcpy(imgfname, ffname); + cout << "Writing tiff to " << imgfname << " " << thr1 << endl; + mt->writeImage(imgfname, thr1); + } - - ifr++; - if (ifr%100==0) cout << ifr << " " << ff << endl; - if (nframes>0) { - if (ifr%nframes==0) { - //The name has an additional "_fXXXXX" at the end, where "XXXXX" is the initial frame number of the image (0,1000,2000...) - - sprintf(ffname,"%s/%s_f%05d.tiff",outdir,fformat,ifile); - sprintf(imgfname,ffname,irun); - //cout << "Writing tiff to " << imgfname << " " << thr1 << endl; - mt->writeImage(imgfname, thr1); - mt->clearImage(); - ifile++; - } - } - } else - cout << ifr << " " << ff << " " << np << endl; - ff=-1; - } - cout << "--" << endl; - filebin.close(); - // //close file - // //join threads - while (mt->isBusy()) {;} - if (nframes>=0) { - if (nframes>0) { - sprintf(ffname,"%s/%s_f%05d.tiff",outdir,fformat,ifile); - sprintf(imgfname,ffname,irun); - } else { - sprintf(ffname,"%s/%s.tiff",outdir,fformat); - sprintf(imgfname,ffname,irun); - } - cout << "Writing tiff to " << imgfname << " " << thr1 <writeImage(imgfname, thr1); - mt->clearImage(); - if (of) { - fclose(of); - of=NULL; - mt->setFilePointer(NULL); - } - } - std::time(&end_time); - cout << std::ctime(&end_time) << endl; - } else - cout << "Could not open "<< fname << " for reading " << endl; - } - if (nframes<0){ - sprintf(ffname,"%s/%s.tiff",outdir,fformat); - strcpy(imgfname,ffname); - cout << "Writing tiff to " << imgfname << " " << thr1 <writeImage(imgfname, thr1); - } - - - - return 0; + return 0; } - diff --git a/slsDetectorCalibration/jungfrauExecutables/jungfrauZmqProcess.cpp b/slsDetectorCalibration/jungfrauExecutables/jungfrauZmqProcess.cpp index a92561821..82a675a39 100644 --- a/slsDetectorCalibration/jungfrauExecutables/jungfrauZmqProcess.cpp +++ b/slsDetectorCalibration/jungfrauExecutables/jungfrauZmqProcess.cpp @@ -7,8 +7,8 @@ #define CM_ROWS 20 -#include "sls/sls_detector_defs.h" #include "sls/ZmqSocket.h" +#include "sls/sls_detector_defs.h" #ifndef RECT #ifndef MOENCH04 #include "moench03T1ZmqDataNew.h" @@ -21,600 +21,622 @@ #ifdef RECT #include "moench03T1ZmqDataNewRect.h" #endif -#include "moench03GhostSummation.h" #include "moench03CommonMode.h" -#include -#include -#include -#include -#include +#include "moench03GhostSummation.h" #include "tiffIO.h" +#include +#include +#include +#include +#include #include //json header in zmq stream -#include +#include //#include "analogDetector.h" //#include "multiThreadedAnalogDetector.h" //#include "singlePhotonDetector.h" //#include "interpolatingDetector.h" //#include "multiThreadedCountingDetector.h" -#include "multiThreadedInterpolatingDetector.h" #include "etaInterpolationPosXY.h" +#include "multiThreadedInterpolatingDetector.h" #include "sls/ansi.h" #include #include -#include // time_t #include +#include // time_t using namespace std; using namespace std::chrono; //#define SLS_DETECTOR_JSON_HEADER_VERSION 0x2 - // myDet->setNetworkParameter(ADDITIONAL_JSON_HEADER, " \"what\":\"nothing\" "); +// myDet->setNetworkParameter(ADDITIONAL_JSON_HEADER, " +//\"what\":\"nothing\" "); int main(int argc, char *argv[]) { -/** - * trial.o [socket ip] [starting port number] [send_socket ip] [send port number] - * - */ - FILE *of=NULL; - int fifosize=5000; - int etabins=1000, etabinsy=1000;//nsubpix*2*100; - double etamin=-1, etamax=2; - int nSubPixelsX=2; - // int emin, emax; - int nSubPixelsY=2; - // help - if (argc < 3 ) { - cprintf(RED, "Help: ./trial [receive socket ip] [receive starting port number] [send_socket ip] [send starting port number] [nthreads] [nsubpix] [gainmap] [etafile]\n"); - return EXIT_FAILURE; - } - - // receive parameters - bool send = false; - char* socketip=argv[1]; - uint32_t portnum = atoi(argv[2]); - // send parameters if any - char* socketip2 = 0; - uint32_t portnum2 = 0; + /** + * trial.o [socket ip] [starting port number] [send_socket ip] [send port + * number] + * + */ + FILE *of = NULL; + int fifosize = 5000; + int etabins = 1000, etabinsy = 1000; // nsubpix*2*100; + double etamin = -1, etamax = 2; + int nSubPixelsX = 2; + // int emin, emax; + int nSubPixelsY = 2; + // help + if (argc < 3) { + cprintf(RED, "Help: ./trial [receive socket ip] [receive starting port " + "number] [send_socket ip] [send starting port number] " + "[nthreads] [nsubpix] [gainmap] [etafile]\n"); + return EXIT_FAILURE; + } - zmqHeader zHeader, outHeader; - zHeader.jsonversion = SLS_DETECTOR_JSON_HEADER_VERSION; - outHeader.jsonversion = SLS_DETECTOR_JSON_HEADER_VERSION; + // receive parameters + bool send = false; + char *socketip = argv[1]; + uint32_t portnum = atoi(argv[2]); + // send parameters if any + char *socketip2 = 0; + uint32_t portnum2 = 0; - uint32_t nSigma=5; + zmqHeader zHeader, outHeader; + zHeader.jsonversion = SLS_DETECTOR_JSON_HEADER_VERSION; + outHeader.jsonversion = SLS_DETECTOR_JSON_HEADER_VERSION; - int ok; + uint32_t nSigma = 5; - high_resolution_clock::time_point t1; - high_resolution_clock::time_point t2 ; - std::chrono::steady_clock::time_point begin,end,finished; - //time_t begin,end,finished; - int rms=0; - + int ok; + high_resolution_clock::time_point t1; + high_resolution_clock::time_point t2; + std::chrono::steady_clock::time_point begin, end, finished; + // time_t begin,end,finished; + int rms = 0; - if (argc > 4) { - socketip2 = argv[3]; - portnum2 = atoi(argv[4]); - if (portnum2>0) - send = true; - } - cout << "\nrx socket ip : " << socketip << - "\nrx port num : " << portnum ; - if (send) { - cout << "\ntx socket ip : " << socketip2 << - "\ntx port num : " << portnum2; - } - int nthreads=5; - if (argc>5) - nthreads=atoi(argv[5]); + if (argc > 4) { + socketip2 = argv[3]; + portnum2 = atoi(argv[4]); + if (portnum2 > 0) + send = true; + } + cout << "\nrx socket ip : " << socketip << "\nrx port num : " << portnum; + if (send) { + cout << "\ntx socket ip : " << socketip2 + << "\ntx port num : " << portnum2; + } + int nthreads = 5; + if (argc > 5) + nthreads = atoi(argv[5]); - cout << "Number of threads is: " << nthreads << endl; - if (argc>6) { - nSubPixelsX=atoi(argv[6]); - nSubPixelsY=nSubPixelsX; + cout << "Number of threads is: " << nthreads << endl; + if (argc > 6) { + nSubPixelsX = atoi(argv[6]); + nSubPixelsY = nSubPixelsX; #ifdef RECT - nSubPixelsX=2; + nSubPixelsX = 2; #endif - } - cout << "Number of subpixels is: " << nSubPixelsX << " " << nSubPixelsY << endl; + } + cout << "Number of subpixels is: " << nSubPixelsX << " " << nSubPixelsY + << endl; - char *gainfname=NULL; - if (argc>7) { - gainfname=argv[7]; - cout << "Gain map file name is: " << gainfname << endl; - } + char *gainfname = NULL; + if (argc > 7) { + gainfname = argv[7]; + cout << "Gain map file name is: " << gainfname << endl; + } - char *etafname=NULL; - if (argc>8) { - etafname=argv[8]; - cout << "Eta file name is: " << etafname << endl; - } + char *etafname = NULL; + if (argc > 8) { + etafname = argv[8]; + cout << "Eta file name is: " << etafname << endl; + } - //slsDetectorData *det=new moench03T1ZmqDataNew(); + // slsDetectorData *det=new moench03T1ZmqDataNew(); #ifndef MOENCH04 - moench03T1ZmqDataNew *det=new moench03T1ZmqDataNew(); + moench03T1ZmqDataNew *det = new moench03T1ZmqDataNew(); #endif #ifdef MOENCH04 - moench04CtbZmq10GbData *det=new moench04CtbZmq10GbData(); + moench04CtbZmq10GbData *det = new moench04CtbZmq10GbData(); #endif - cout << endl << " det" <getDetectorSize(npx, npy); + cout << endl << " det" << endl; + int npx, npy; + det->getDetectorSize(npx, npy); - int send_something=0; + int send_something = 0; + int maxSize = npx * npy * 2; // 32*2*8192;//5000;//atoi(argv[3]); + int size = maxSize; // 32*2*5000; + // int multisize=size; + // int dataSize=size; - int maxSize = npx*npy*2;//32*2*8192;//5000;//atoi(argv[3]); - int size= maxSize;//32*2*5000; - //int multisize=size; - //int dataSize=size; + char dummybuff[size]; - char dummybuff[size]; - - - moench03CommonMode *cm=NULL; - moench03GhostSummation *gs=NULL; + moench03CommonMode *cm = NULL; + moench03GhostSummation *gs = NULL; #ifdef CORR - - //int ncol_cm=CM_ROWS; - //double xt_ghost=C_GHOST; - cm=new moench03CommonMode(CM_ROWS); - gs=new moench03GhostSummation(det, C_GHOST); + // int ncol_cm=CM_ROWS; + // double xt_ghost=C_GHOST; + + cm = new moench03CommonMode(CM_ROWS); + gs = new moench03GhostSummation(det, C_GHOST); #endif - double *gainmap=NULL; - float *gm; - double *gmap=NULL; + double *gainmap = NULL; + float *gm; + double *gmap = NULL; - uint32_t nnnx, nnny; - if (gainfname) { - gm=ReadFromTiff(gainfname, nnny, nnnx); - if (gm && nnnx==(uint)npx && nnny==(uint)npy) { - gmap=new double[npx*npy]; - for (int i=0; i *filter=new analogDetector(det,1,NULL,1000); + // analogDetector *filter=new + // analogDetector(det,1,NULL,1000); #ifndef INTERP - singlePhotonDetector *filter=new singlePhotonDetector(det,3, nSigma, 1, cm, 1000, 100, -1, -1, gainmap, gs); + singlePhotonDetector *filter = new singlePhotonDetector( + det, 3, nSigma, 1, cm, 1000, 100, -1, -1, gainmap, gs); - multiThreadedCountingDetector *mt=new multiThreadedCountingDetector(filter,nthreads,fifosize); + multiThreadedCountingDetector *mt = + new multiThreadedCountingDetector(filter, nthreads, fifosize); - // multiThreadedAnalogDetector *mt=new multiThreadedAnalogDetector(filter,nthreads,fifosize); + // multiThreadedAnalogDetector *mt=new + // multiThreadedAnalogDetector(filter,nthreads,fifosize); #endif #ifdef INTERP - eta2InterpolationPosXY *interp=new eta2InterpolationPosXY(npx, npy, nSubPixelsX,nSubPixelsY, etabins, etabinsy, etamin, etamax); + eta2InterpolationPosXY *interp = new eta2InterpolationPosXY( + npx, npy, nSubPixelsX, nSubPixelsY, etabins, etabinsy, etamin, etamax); - if (etafname) interp->readFlatField(etafname); + if (etafname) + interp->readFlatField(etafname); - interpolatingDetector *filter=new interpolatingDetector(det,interp, nSigma, 1, cm, 1000, 10, -1, -1, gainmap, gs); - multiThreadedInterpolatingDetector *mt=new multiThreadedInterpolatingDetector(filter,nthreads,fifosize); + interpolatingDetector *filter = new interpolatingDetector( + det, interp, nSigma, 1, cm, 1000, 10, -1, -1, gainmap, gs); + multiThreadedInterpolatingDetector *mt = + new multiThreadedInterpolatingDetector(filter, nthreads, fifosize); #endif + char *buff; + mt->setFrameMode(eFrame); + mt->StartThreads(); + mt->popFree(buff); - - char* buff; - mt->setFrameMode(eFrame); - mt->StartThreads(); - mt->popFree(buff); - - ZmqSocket* zmqsocket=NULL; + ZmqSocket *zmqsocket = NULL; #ifdef NEWZMQ - // receive socket - try{ + // receive socket + try { #endif - - zmqsocket = new ZmqSocket(socketip,portnum); - + + zmqsocket = new ZmqSocket(socketip, portnum); #ifdef NEWZMQ - } catch (...) { - cprintf(RED, "Error: Could not create Zmq socket on port %d with ip %s\n", portnum, socketip); - delete zmqsocket; - return EXIT_FAILURE; + } catch (...) { + cprintf(RED, + "Error: Could not create Zmq socket on port %d with ip %s\n", + portnum, socketip); + delete zmqsocket; + return EXIT_FAILURE; + } +#endif + +#ifndef NEWZMQ + if (zmqsocket->IsError()) { + cprintf(RED, + "Error: Could not create Zmq socket on port %d with ip %s\n", + portnum, socketip); + delete zmqsocket; + return EXIT_FAILURE; + } +#endif + if (zmqsocket->Connect()) { + cprintf(RED, "Error: Could not connect to socket %s\n", + (zmqsocket->GetZmqServerAddress()).c_str()); + delete zmqsocket; + return EXIT_FAILURE; + } else + printf("Zmq Client at %s\n", zmqsocket->GetZmqServerAddress().c_str()); + + // send socket + ZmqSocket *zmqsocket2 = 0; + // cout << "zmq2 " << endl; + if (send) { +#ifdef NEWZMQ + // receive socket + try { +#endif + zmqsocket2 = new ZmqSocket(portnum2, socketip2); + +#ifdef NEWZMQ + } catch (...) { + cprintf(RED, + "Error: Could not create Zmq socket server on port %d and " + "ip %s\n", + portnum2, socketip2); + // delete zmqsocket2; + // zmqsocket2=NULL; + // delete zmqsocket; + // return EXIT_FAILURE; + send = false; } #endif -#ifndef NEWZMQ - if (zmqsocket->IsError()) { - cprintf(RED, "Error: Could not create Zmq socket on port %d with ip %s\n", portnum, socketip); - delete zmqsocket; - return EXIT_FAILURE; - } +#ifndef NEWZMQ + if (zmqsocket2->IsError()) { + cprintf(RED, + "AAA Error: Could not create Zmq socket server on port %d " + "and ip %s\n", + portnum2, socketip2); + // delete zmqsocket2; + // delete zmqsocket; + // return EXIT_FAILURE; + send = false; + } #endif - if (zmqsocket->Connect()) { - cprintf(RED, "Error: Could not connect to socket %s\n", - (zmqsocket->GetZmqServerAddress()).c_str()); - delete zmqsocket; - return EXIT_FAILURE; - } else - printf("Zmq Client at %s\n", zmqsocket->GetZmqServerAddress().c_str()); - - // send socket - ZmqSocket* zmqsocket2 = 0; - // cout << "zmq2 " << endl; - if (send) { -#ifdef NEWZMQ - // receive socket - try{ -#endif - zmqsocket2 = new ZmqSocket(portnum2, socketip2); + if (zmqsocket2->Connect()) { + cprintf(RED, "BBB Error: Could not connect to socket %s\n", + zmqsocket2->GetZmqServerAddress().c_str()); + // delete zmqsocket2; + send = false; + // return EXIT_FAILURE; + } else + printf("Zmq Client at %s\n", + zmqsocket2->GetZmqServerAddress().c_str()); + } - - -#ifdef NEWZMQ - } catch (...) { - cprintf(RED, "Error: Could not create Zmq socket server on port %d and ip %s\n", portnum2, socketip2); - // delete zmqsocket2; - // zmqsocket2=NULL; - // delete zmqsocket; - // return EXIT_FAILURE; - send = false; - } -#endif - -#ifndef NEWZMQ - if (zmqsocket2->IsError()) { - cprintf(RED, "AAA Error: Could not create Zmq socket server on port %d and ip %s\n", portnum2, socketip2); - // delete zmqsocket2; - //delete zmqsocket; - // return EXIT_FAILURE; - send = false; - } -#endif - if (zmqsocket2->Connect()) { - cprintf(RED, "BBB Error: Could not connect to socket %s\n", - zmqsocket2->GetZmqServerAddress().c_str()); - // delete zmqsocket2; - send = false; - // return EXIT_FAILURE; - } else - printf("Zmq Client at %s\n", zmqsocket2->GetZmqServerAddress().c_str()); - - } - - - // header variables - uint64_t acqIndex = -1; - uint64_t frameIndex = -1; + // header variables + uint64_t acqIndex = -1; + uint64_t frameIndex = -1; #ifdef MOENCH_BRANCH - uint32_t subFrameIndex = -1; - int* flippedData = 0; + uint32_t subFrameIndex = -1; + int *flippedData = 0; #endif - - uint64_t subframes=0; - //uint64_t isubframe=0; - uint64_t insubframe=0; - double subnorm=1; - uint64_t f0=-1, nsubframes=0, nnsubframe=0; - uint64_t fileindex = -1; - string filename = ""; - // char* image = new char[size]; - //int* image = new int[(size/sizeof(int))](); - //uint32_t flippedDataX = -1; - //int *nph; - int iframe=0; - char ofname[10000]; - - string fname; - // int length; - int *detimage=NULL; - int nnx, nny,nnsx, nnsy; - //uint32_t imageSize = 0, nPixelsX = 0, nPixelsY = 0, - //uint32_t dynamicRange = 0; - // infinite loop - uint32_t packetNumber = 0; - uint64_t bunchId = 0; - uint64_t timestamp = 0; - int16_t modId = 0; - uint32_t expLength=0; - uint16_t xCoord = 0; - uint16_t yCoord = 0; - //uint16_t zCoord = 0; - uint32_t debug = 0; - //uint32_t dr = 16; - //int16_t *dout;//=new int16_t [nnx*nny]; - uint32_t dr = 32; - int32_t *dout=NULL;//=new int32_t [nnx*nny]; - float *doutf=NULL;//=new int32_t [nnx*nny]; - uint16_t roundRNumber = 0; - uint8_t detType = 0; - uint8_t version = 0; - string additionalJsonHeader="" ; + uint64_t subframes = 0; + // uint64_t isubframe=0; + uint64_t insubframe = 0; + double subnorm = 1; + uint64_t f0 = -1, nsubframes = 0, nnsubframe = 0; - int32_t threshold=0; - - int32_t xmin=0, xmax=400, ymin=0, ymax=400; - - string frameMode_s, detectorMode_s, intMode_s; + uint64_t fileindex = -1; + string filename = ""; + // char* image = new char[size]; + // int* image = new int[(size/sizeof(int))](); + // uint32_t flippedDataX = -1; + // int *nph; + int iframe = 0; + char ofname[10000]; - // int resetFlat=0; - //int resetPed=0; - // int nsubPixels=1; - //int isPedestal=0; - //int isFlat=0; - int newFrame=1; - detectorMode dMode=eAnalog; - frameMode fMode=eFrame; - double *ped; + string fname; + // int length; + int *detimage = NULL; + int nnx, nny, nnsx, nnsy; + // uint32_t imageSize = 0, nPixelsX = 0, nPixelsY = 0, + // uint32_t dynamicRange = 0; + // infinite loop + uint32_t packetNumber = 0; + uint64_t bunchId = 0; + uint64_t timestamp = 0; + int16_t modId = 0; + uint32_t expLength = 0; + uint16_t xCoord = 0; + uint16_t yCoord = 0; + // uint16_t zCoord = 0; + uint32_t debug = 0; + // uint32_t dr = 16; + // int16_t *dout;//=new int16_t [nnx*nny]; + uint32_t dr = 32; + int32_t *dout = NULL; //=new int32_t [nnx*nny]; + float *doutf = NULL; //=new int32_t [nnx*nny]; + uint16_t roundRNumber = 0; + uint8_t detType = 0; + uint8_t version = 0; + string additionalJsonHeader = ""; - filter->getImageSize(nnx, nny,nnsx, nnsy); + int32_t threshold = 0; - - std::map addJsonHeader; + int32_t xmin = 0, xmax = 400, ymin = 0, ymax = 400; + string frameMode_s, detectorMode_s, intMode_s; + // int resetFlat=0; + // int resetPed=0; + // int nsubPixels=1; + // int isPedestal=0; + // int isFlat=0; + int newFrame = 1; + detectorMode dMode = eAnalog; + frameMode fMode = eFrame; + double *ped; + filter->getImageSize(nnx, nny, nnsx, nnsy); - while(1) { + std::map addJsonHeader; + while (1) { - // cout << "+++++++++++++++++++++++++++++++LOOP" << endl; - // get header, (if dummy, fail is on parse error or end of acquisition) + // cout << "+++++++++++++++++++++++++++++++LOOP" << endl; + // get header, (if dummy, fail is on parse error or end of acquisition) + // rapidjson::Document doc; + if (!zmqsocket->ReceiveHeader(0, zHeader, + SLS_DETECTOR_JSON_HEADER_VERSION)) { + /* zmqsocket->CloseHeaderMessage();*/ + // if (!zmqsocket->ReceiveHeader(0, acqIndex, frameIndex, + //subframeIndex, filename, fileindex)) { + cprintf(RED, "Got Dummy\n"); + // t1=high_resolution_clock::now(); + // time(&end); + // cout << "Measurement lasted " << difftime(end,begin) << endl; - // rapidjson::Document doc; - if (!zmqsocket->ReceiveHeader(0, zHeader, SLS_DETECTOR_JSON_HEADER_VERSION)) { - /* zmqsocket->CloseHeaderMessage();*/ + end = std::chrono::steady_clock::now(); + cout << "Measurement lasted " << (end - begin).count() * 0.000001 + << " ms" << endl; - // if (!zmqsocket->ReceiveHeader(0, acqIndex, frameIndex, subframeIndex, filename, fileindex)) { - cprintf(RED, "Got Dummy\n"); - // t1=high_resolution_clock::now(); - //time(&end); - //cout << "Measurement lasted " << difftime(end,begin) << endl; + while (mt->isBusy()) { + ; + } // wait until all data are processed from the queues - end = std::chrono::steady_clock::now(); - cout << "Measurement lasted " << (end-begin).count()*0.000001 << " ms" << endl; + if (of) { + mt->setFilePointer(NULL); + fclose(of); + of = NULL; + } + if (newFrame > 0) { + cprintf(RED, "DIDn't receive any data!\n"); + if (send) { - while (mt->isBusy()) {;}//wait until all data are processed from the queues - - if (of) { - mt->setFilePointer(NULL); - fclose(of); - of=NULL; - } - if (newFrame>0) { - cprintf(RED,"DIDn't receive any data!\n"); - if (send) { - - //zHeader.data = false; - outHeader.data=false; - // zmqsocket2->SendHeaderData(0, true, SLS_DETECTOR_JSON_HEADER_VERSION); - zmqsocket2->SendHeader(0,outHeader); - cprintf(RED, "Sent Dummy\n"); - } - } else { - send_something=0; - if (fMode==ePedestal) { - sprintf(ofname,"%s_%ld_ped.tiff",fname.c_str(),fileindex); - mt->writePedestal(ofname); - cout << "Writing pedestal to " << ofname << endl; - if (rms){ - sprintf(ofname,"%s_%ld_var.tiff",fname.c_str(),fileindex); - mt->writePedestalRMS(ofname); - - } - send_something=1; - } + // zHeader.data = false; + outHeader.data = false; + // zmqsocket2->SendHeaderData(0, true, + // SLS_DETECTOR_JSON_HEADER_VERSION); + zmqsocket2->SendHeader(0, outHeader); + cprintf(RED, "Sent Dummy\n"); + } + } else { + send_something = 0; + if (fMode == ePedestal) { + sprintf(ofname, "%s_%ld_ped.tiff", fname.c_str(), + fileindex); + mt->writePedestal(ofname); + cout << "Writing pedestal to " << ofname << endl; + if (rms) { + sprintf(ofname, "%s_%ld_var.tiff", fname.c_str(), + fileindex); + mt->writePedestalRMS(ofname); + } + send_something = 1; + } #ifdef INTERP - else if (fMode==eFlat) { - mt->prepareInterpolation(ok); - sprintf(ofname,"%s_%ld_eta.tiff",fname.c_str(),fileindex); - mt->writeFlatField(ofname); - cout << "Writing eta to " << ofname << endl; - send_something=1; - } + else if (fMode == eFlat) { + mt->prepareInterpolation(ok); + sprintf(ofname, "%s_%ld_eta.tiff", fname.c_str(), + fileindex); + mt->writeFlatField(ofname); + cout << "Writing eta to " << ofname << endl; + send_something = 1; + } #endif - else { - if (subframes>0 ) { - if (insubframe>0) { - sprintf(ofname,"%s_sf%ld_%ld.tiff",fname.c_str(),nnsubframe,fileindex); - // mt->writeImage(ofname); - doutf= new float[nnx*nny]; - if (subframes>0 && insubframe!=subframes && insubframe>0) - subnorm=((double)subframes)/((double)insubframe); - else - subnorm=1.; - for (int ix=0; ixwriteImage(ofname); - send_something=1; - } - - cout << "Writing image to " << ofname << endl; - } - // cout << nns*nnx*nny*nns*dr/8 << " " << length << endl; + else { + if (subframes > 0) { + if (insubframe > 0) { + sprintf(ofname, "%s_sf%ld_%ld.tiff", fname.c_str(), + nnsubframe, fileindex); + // mt->writeImage(ofname); + doutf = new float[nnx * nny]; + if (subframes > 0 && insubframe != subframes && + insubframe > 0) + subnorm = + ((double)subframes) / ((double)insubframe); + else + subnorm = 1.; + for (int ix = 0; ix < nnx * nny; ix++) { + doutf[ix] = detimage[ix] * subnorm; + if (doutf[ix] < 0) + doutf[ix] = 0; + } - if (send) { - - if (fMode==ePedestal) { - cprintf(MAGENTA,"Get pedestal!\n"); - nnsx=1; - nnsy=1; - - nnx=npx; - nny=npy; - //dout= new int16_t[nnx*nny*nns*nns]; - dout= new int32_t[nnx*nny*nnsx*nnsy]; - // cout << "get pedestal " << endl; - ped=mt->getPedestal(); - // cout << "got pedestal " << endl; - for (int ix=0; ixwriteImage(ofname); + send_something = 1; + } + + cout << "Writing image to " << ofname << endl; + } + // cout << nns*nnx*nny*nns*dr/8 << " " << length << endl; + + if (send) { + + if (fMode == ePedestal) { + cprintf(MAGENTA, "Get pedestal!\n"); + nnsx = 1; + nnsy = 1; + + nnx = npx; + nny = npy; + // dout= new int16_t[nnx*nny*nns*nns]; + dout = new int32_t[nnx * nny * nnsx * nnsy]; + // cout << "get pedestal " << endl; + ped = mt->getPedestal(); + // cout << "got pedestal " << endl; + for (int ix = 0; ix < nnx * nny; ix++) { + + dout[ix] = ped[ix]; + // if (ix<100*400) + // cout << ix << " " << ped[ix] << endl; + } + + } #ifdef INTERP - else if (fMode==eFlat) { - int nb; - double emi=0, ema=1; - int *ff=mt->getFlatField(nb, emi, ema); - nnx=nb; - nny=nb; - dout= new int32_t[nb*nb]; - for (int ix=0; ixgetFlatField(nb, emi, ema); + nnx = nb; + nny = nb; + dout = new int32_t[nb * nb]; + for (int ix = 0; ix < nb * nb; ix++) { + dout[ix] = ff[ix]; + } + } #endif - else { - detimage=mt->getImage(nnx,nny,nnsx, nnsy); - cprintf(MAGENTA,"Get image!\n"); - cout << nnx << " " << nny << " " << nnsx << " " << nnsy << endl; - // nns=1; - // nnx=npx; - // nny=npy; - // nnx=nnx*nns; - //nny=nny*nns; - dout= new int32_t[nnx*nny]; - if (subframes>0 && insubframe!=subframes && insubframe>0) - subnorm=((double)subframes)/((double)insubframe); - else - subnorm=1.; - for (int ix=0; ix0 && subframes>0) || (subframes<=0) ){ + else { + detimage = mt->getImage(nnx, nny, nnsx, nnsy); + cprintf(MAGENTA, "Get image!\n"); + cout << nnx << " " << nny << " " << nnsx << " " << nnsy + << endl; + // nns=1; + // nnx=npx; + // nny=npy; + // nnx=nnx*nns; + // nny=nny*nns; + dout = new int32_t[nnx * nny]; + if (subframes > 0 && insubframe != subframes && + insubframe > 0) + subnorm = + ((double)subframes) / ((double)insubframe); + else + subnorm = 1.; + for (int ix = 0; ix < nnx * nny; ix++) { + // for (int iy=0; iySendHeaderData (0, false,SLS_DETECTOR_JSON_HEADER_VERSION , dr, fileindex, 1,1,nnx,nny,nnx*nny*dr/8,acqIndex, frameIndex, fname,acqIndex,0 , packetNumber,bunchId, timestamp, modId,xCoord, yCoord, zCoord,debug, roundRNumber, detType, version, 0,0, 0,&additionalJsonHeader); - - outHeader.data=true; - outHeader.dynamicRange=dr; - outHeader.fileIndex=fileindex; - outHeader.ndetx=1; - outHeader.ndety=1; - outHeader.npixelsx=nnx; - outHeader.npixelsy=nny; - outHeader.imageSize=nnx*nny*dr/8; - outHeader.acqIndex=acqIndex; - outHeader.frameIndex=frameIndex; - outHeader.fname=fname; - outHeader.frameNumber=acqIndex; - outHeader.expLength=expLength; - outHeader.packetNumber=packetNumber; - outHeader.bunchId=bunchId; - outHeader.timestamp=timestamp; - outHeader.modId=modId; - outHeader.row=xCoord; - outHeader.column=yCoord; - outHeader.debug=debug; - outHeader.roundRNumber=roundRNumber; - outHeader.detType=detType; - outHeader.version=version; - - zmqsocket2->SendHeader(0,outHeader); - zmqsocket2->SendData((char*)dout,nnx*nny*dr/8); - cprintf(GREEN, "Sent Data\n"); - } - outHeader.data=false; - zmqsocket2->SendHeader(0,outHeader); - // zmqsocket2->SendHeaderData(0, true, SLS_DETECTOR_JSON_HEADER_VERSION); - cprintf(RED, "Sent Dummy\n"); - if (dout) - delete [] dout; - dout=NULL; - - } - } + // } + // } + dout[ix] = detimage[ix] * subnorm; + if (dout[ix] < 0) + dout[ix] = 0; + // cout << ix << " " << dout[ix] << endl; + // } + } + } + // if ((insubframe>0 && subframes>0) || (subframes<=0) ){ - mt->clearImage(); - - newFrame=1; - - - //time(&finished); - //cout << "Processing lasted " << difftime(finished,begin) << endl; - - finished = std::chrono::steady_clock::now(); - cout << "Processing lasted " << (finished-begin).count()*0.000001 << " ms" << endl; + if (send_something) { + + // zmqsocket2->SendHeaderData (0, + // false,SLS_DETECTOR_JSON_HEADER_VERSION , dr, + // fileindex, 1,1,nnx,nny,nnx*nny*dr/8,acqIndex, + // frameIndex, fname,acqIndex,0 , packetNumber,bunchId, + // timestamp, modId,xCoord, yCoord, zCoord,debug, + // roundRNumber, detType, version, 0,0, + // 0,&additionalJsonHeader); + + outHeader.data = true; + outHeader.dynamicRange = dr; + outHeader.fileIndex = fileindex; + outHeader.ndetx = 1; + outHeader.ndety = 1; + outHeader.npixelsx = nnx; + outHeader.npixelsy = nny; + outHeader.imageSize = nnx * nny * dr / 8; + outHeader.acqIndex = acqIndex; + outHeader.frameIndex = frameIndex; + outHeader.fname = fname; + outHeader.frameNumber = acqIndex; + outHeader.expLength = expLength; + outHeader.packetNumber = packetNumber; + outHeader.bunchId = bunchId; + outHeader.timestamp = timestamp; + outHeader.modId = modId; + outHeader.row = xCoord; + outHeader.column = yCoord; + outHeader.debug = debug; + outHeader.roundRNumber = roundRNumber; + outHeader.detType = detType; + outHeader.version = version; + + zmqsocket2->SendHeader(0, outHeader); + zmqsocket2->SendData((char *)dout, nnx * nny * dr / 8); + cprintf(GREEN, "Sent Data\n"); + } + outHeader.data = false; + zmqsocket2->SendHeader(0, outHeader); + // zmqsocket2->SendHeaderData(0, true, + // SLS_DETECTOR_JSON_HEADER_VERSION); + cprintf(RED, "Sent Dummy\n"); + if (dout) + delete[] dout; + dout = NULL; + } + } + + mt->clearImage(); + + newFrame = 1; + + // time(&finished); + // cout << "Processing lasted " << difftime(finished,begin) << endl; + + finished = std::chrono::steady_clock::now(); + cout << "Processing lasted " + << (finished - begin).count() * 0.000001 << " ms" << endl; #ifdef OPTIMIZE - return 0; + return 0; #endif - continue; //continue to not get out + continue; // continue to not get out + } + //#ifdef NEWZMQ + if (newFrame) { + begin = std::chrono::steady_clock::now(); - } + size = zHeader.imageSize; // doc["size"].GetUint(); - //#ifdef NEWZMQ - if (newFrame) { - begin = std::chrono::steady_clock::now(); - - size = zHeader.imageSize;//doc["size"].GetUint(); - - // dynamicRange = zheader.dynamicRange; //doc["bitmode"].GetUint(); - // nPixelsX = zHeader.npixelsx; //doc["shape"][0].GetUint(); - // nPixelsY = zHeader.npixelsy;// doc["shape"][1].GetUint(); - filename = zHeader.fname;//doc["fname"].GetString(); - acqIndex = zHeader.acqIndex; //doc["acqIndex"].GetUint64(); - // frameIndex = zHeader.frameIndex;//doc["fIndex"].GetUint64(); - fileindex = zHeader.fileIndex;//doc["fileIndex"].GetUint64(); - expLength = zHeader.expLength;//doc["expLength"].GetUint(); - packetNumber=zHeader.packetNumber;//doc["packetNumber"].GetUint(); - bunchId=zHeader.bunchId;//doc["bunchId"].GetUint(); - timestamp=zHeader.timestamp;//doc["timestamp"].GetUint(); - modId=zHeader.modId;//doc["modId"].GetUint(); - debug=zHeader.debug;//doc["debug"].GetUint(); - // roundRNumber=r.roundRNumber;//doc["roundRNumber"].GetUint(); - detType=zHeader.detType;//doc["detType"].GetUint(); - version=zHeader.version;//doc["version"].GetUint(); - /*document["bitmode"].GetUint(); zHeader.dynamicRange + // dynamicRange = zheader.dynamicRange; //doc["bitmode"].GetUint(); + // nPixelsX = zHeader.npixelsx; //doc["shape"][0].GetUint(); + // nPixelsY = zHeader.npixelsy;// doc["shape"][1].GetUint(); + filename = zHeader.fname; // doc["fname"].GetString(); + acqIndex = + zHeader + .acqIndex; // doc["acqIndex"].GetUint64(); + // frameIndex = + // zHeader.frameIndex;//doc["fIndex"].GetUint64(); + fileindex = zHeader.fileIndex; // doc["fileIndex"].GetUint64(); + expLength = zHeader.expLength; // doc["expLength"].GetUint(); + packetNumber = + zHeader.packetNumber; // doc["packetNumber"].GetUint(); + bunchId = zHeader.bunchId; // doc["bunchId"].GetUint(); + timestamp = zHeader.timestamp; // doc["timestamp"].GetUint(); + modId = zHeader.modId; // doc["modId"].GetUint(); + debug = zHeader.debug; // doc["debug"].GetUint(); + // roundRNumber=r.roundRNumber;//doc["roundRNumber"].GetUint(); + detType = zHeader.detType; // doc["detType"].GetUint(); + version = zHeader.version; // doc["version"].GetUint(); + /*document["bitmode"].GetUint(); zHeader.dynamicRange document["fileIndex"].GetUint64(); zHeader.fileIndex @@ -669,360 +691,349 @@ document["flippedDataX"].GetUint(); zHeader.flippedDataX document["quad"].GetUint(); zHeader.quad document["completeImage"].GetUint(); zHeader.completeImage - */ - //dataSize=size; + */ + // dataSize=size; - //strcpy(fname,filename.c_str()); - fname=filename; - // cprintf(BLUE, "Header Info:\n" - // "size: %u\n" - // "multisize: %u\n" - // "dynamicRange: %u\n" - // "nPixelsX: %u\n" - // "nPixelsY: %u\n" - // "currentFileName: %s\n" - // "currentAcquisitionIndex: %lu\n" - // "currentFrameIndex: %lu\n" - // "currentFileIndex: %lu\n" - // "currentSubFrameIndex: %u\n" - // "xCoordX: %u\n" - // "yCoordY: %u\n" - // "zCoordZ: %u\n" - // "flippedDataX: %u\n" - // "packetNumber: %u\n" - // "bunchId: %u\n" - // "timestamp: %u\n" - // "modId: %u\n" - // "debug: %u\n" - // "roundRNumber: %u\n" - // "detType: %u\n" - // "version: %u\n", - // size, multisize, dynamicRange, nPixelsX, nPixelsY, - // filename.c_str(), acqIndex, - // frameIndex, fileindex, subFrameIndex, - // xCoord, yCoord,zCoord, - // flippedDataX, packetNumber, bunchId, timestamp, modId, debug, roundRNumber, detType, version); - - addJsonHeader=zHeader.addJsonHeader; + // strcpy(fname,filename.c_str()); + fname = filename; + // cprintf(BLUE, "Header Info:\n" + // "size: %u\n" + // "multisize: %u\n" + // "dynamicRange: %u\n" + // "nPixelsX: %u\n" + // "nPixelsY: %u\n" + // "currentFileName: %s\n" + // "currentAcquisitionIndex: %lu\n" + // "currentFrameIndex: %lu\n" + // "currentFileIndex: %lu\n" + // "currentSubFrameIndex: %u\n" + // "xCoordX: %u\n" + // "yCoordY: %u\n" + // "zCoordZ: %u\n" + // "flippedDataX: %u\n" + // "packetNumber: %u\n" + // "bunchId: %u\n" + // "timestamp: %u\n" + // "modId: %u\n" + // "debug: %u\n" + // "roundRNumber: %u\n" + // "detType: %u\n" + // "version: %u\n", + // size, multisize, dynamicRange, nPixelsX, nPixelsY, + // filename.c_str(), acqIndex, + // frameIndex, fileindex, subFrameIndex, + // xCoord, yCoord,zCoord, + // flippedDataX, packetNumber, bunchId, timestamp, modId, + // debug, roundRNumber, detType, version); - /* Analog detector commands */ - //isPedestal=0; - //isFlat=0; - rms=0; - fMode=eFrame; - frameMode_s="frame"; - cprintf(MAGENTA, "Frame mode: "); - // if (doc.HasMember("frameMode")) { - if (addJsonHeader.find("frameMode")!= addJsonHeader.end()) { - // if (doc["frameMode"].IsString()) { - frameMode_s=addJsonHeader.at("frameMode");//doc["frameMode"].GetString(); - if (frameMode_s == "pedestal"){ - fMode=ePedestal; - //isPedestal=1; - } else if (frameMode_s == "newPedestal"){ - mt->newDataSet(); //resets pedestal - // cprintf(MAGENTA, "Resetting pedestal\n"); - fMode=ePedestal; - //isPedestal=1; - } else if (frameMode_s == "variance"){ - mt->newDataSet(); //resets pedestal - // cprintf(MAGENTA, "Resetting pedestal\n"); - fMode=ePedestal; - //isPedestal=1; - rms=1; - } -#ifdef INTERP - else if (frameMode_s == "flatfield") { - fMode=eFlat; - //isFlat=1; - } else if (frameMode_s == "newFlatfield") { - mt->resetFlatField(); - //isFlat=1; - cprintf(MAGENTA, "Resetting flatfield\n"); - fMode=eFlat; - } - //#endif - else { - fMode=eFrame; - //isPedestal=0; - //isFlat=0; - fMode=eFrame; - frameMode_s="frame"; - } - //} - } - cprintf(MAGENTA, "%s\n" , frameMode_s.c_str()); - mt->setFrameMode(fMode); + addJsonHeader = zHeader.addJsonHeader; - // threshold=0; - cprintf(MAGENTA, "Threshold: "); - if (addJsonHeader.find("threshold")!= addJsonHeader.end()) { - istringstream(addJsonHeader.at("threshold")) >>threshold; - // threshold=atoi(addJsonHeader.at("threshold").c_str());//doc["frameMode"].GetString(); - } - //if (doc.HasMember("threshold")) { - //if (doc["threshold"].IsInt()) { - // threshold=doc["threshold"].GetInt(); - mt->setThreshold(threshold); - // } - // } - cprintf(MAGENTA, "%d\n", threshold); - - xmin=0; - xmax=npx; - ymin=0; - ymax=npy; - cprintf(MAGENTA, "ROI: "); - - if (addJsonHeader.find("roi")!= addJsonHeader.end()) { - istringstream(addJsonHeader.at("roi")) >> xmin >> xmax >> ymin >> ymax ; - // if (doc.HasMember("roi")) { - //if (doc["roi"].IsArray()) { - // if (doc["roi"].Size() > 0 ) - // if (doc["roi"][0].IsInt()) - // xmin=doc["roi"][0].GetInt(); - - // if (doc["roi"].Size() > 1 ) - // if (doc["roi"][1].IsInt()) - // xmax=doc["roi"][1].GetInt(); - - // if (doc["roi"].Size() > 2 ) - // if (doc["roi"][2].IsInt()) - // ymin=doc["roi"][2].GetInt(); - - // if (doc["roi"].Size() > 3 ) - // if (doc["roi"][3].IsInt()) - // ymax=doc["roi"][3].GetInt(); - // } - } - - cprintf(MAGENTA, "%d %d %d %d\n", xmin, xmax, ymin, ymax); - mt->setROI(xmin, xmax, ymin, ymax); - if (addJsonHeader.find("dynamicRange")!= addJsonHeader.end()) { - istringstream(addJsonHeader.at("dynamicRange")) >> dr ; - dr=32; - } - // if (doc.HasMember("dynamicRange")) { - // dr=doc["dynamicRange"].GetUint(); - // dr=32; - // } - - dMode=eAnalog; - detectorMode_s="analog"; - cprintf(MAGENTA, "Detector mode: "); - if (addJsonHeader.find("detectorMode")!= addJsonHeader.end()) {; - //if (doc.HasMember("detectorMode")) { - //if (doc["detectorMode"].IsString()) { - detectorMode_s=addJsonHeader.at("detectorMode");//=doc["detectorMode"].GetString(); + /* Analog detector commands */ + // isPedestal=0; + // isFlat=0; + rms = 0; + fMode = eFrame; + frameMode_s = "frame"; + cprintf(MAGENTA, "Frame mode: "); + // if (doc.HasMember("frameMode")) { + if (addJsonHeader.find("frameMode") != addJsonHeader.end()) { + // if (doc["frameMode"].IsString()) { + frameMode_s = addJsonHeader.at( + "frameMode"); // doc["frameMode"].GetString(); + if (frameMode_s == "pedestal") { + fMode = ePedestal; + // isPedestal=1; + } else if (frameMode_s == "newPedestal") { + mt->newDataSet(); // resets pedestal + // cprintf(MAGENTA, "Resetting pedestal\n"); + fMode = ePedestal; + // isPedestal=1; + } else if (frameMode_s == "variance") { + mt->newDataSet(); // resets pedestal + // cprintf(MAGENTA, "Resetting pedestal\n"); + fMode = ePedestal; + // isPedestal=1; + rms = 1; + } #ifdef INTERP - if (detectorMode_s == "interpolating"){ - dMode=eInterpolating; - mt->setInterpolation(interp); - } else -#endif - if (detectorMode_s == "counting"){ - dMode=ePhotonCounting; + else if (frameMode_s == "flatfield") { + fMode = eFlat; + // isFlat=1; + } else if (frameMode_s == "newFlatfield") { + mt->resetFlatField(); + // isFlat=1; + cprintf(MAGENTA, "Resetting flatfield\n"); + fMode = eFlat; + } + //#endif + else { + fMode = eFrame; + // isPedestal=0; + // isFlat=0; + fMode = eFrame; + frameMode_s = "frame"; + } + //} + } + cprintf(MAGENTA, "%s\n", frameMode_s.c_str()); + mt->setFrameMode(fMode); + + // threshold=0; + cprintf(MAGENTA, "Threshold: "); + if (addJsonHeader.find("threshold") != addJsonHeader.end()) { + istringstream(addJsonHeader.at("threshold")) >> threshold; + // threshold=atoi(addJsonHeader.at("threshold").c_str());//doc["frameMode"].GetString(); + } + // if (doc.HasMember("threshold")) { + // if (doc["threshold"].IsInt()) { + // threshold=doc["threshold"].GetInt(); + mt->setThreshold(threshold); + // } + // } + cprintf(MAGENTA, "%d\n", threshold); + + xmin = 0; + xmax = npx; + ymin = 0; + ymax = npy; + cprintf(MAGENTA, "ROI: "); + + if (addJsonHeader.find("roi") != addJsonHeader.end()) { + istringstream(addJsonHeader.at("roi")) >> xmin >> xmax >> + ymin >> ymax; + // if (doc.HasMember("roi")) { + // if (doc["roi"].IsArray()) { + // if (doc["roi"].Size() > 0 ) + // if (doc["roi"][0].IsInt()) + // xmin=doc["roi"][0].GetInt(); + + // if (doc["roi"].Size() > 1 ) + // if (doc["roi"][1].IsInt()) + // xmax=doc["roi"][1].GetInt(); + + // if (doc["roi"].Size() > 2 ) + // if (doc["roi"][2].IsInt()) + // ymin=doc["roi"][2].GetInt(); + + // if (doc["roi"].Size() > 3 ) + // if (doc["roi"][3].IsInt()) + // ymax=doc["roi"][3].GetInt(); + // } + } + + cprintf(MAGENTA, "%d %d %d %d\n", xmin, xmax, ymin, ymax); + mt->setROI(xmin, xmax, ymin, ymax); + if (addJsonHeader.find("dynamicRange") != addJsonHeader.end()) { + istringstream(addJsonHeader.at("dynamicRange")) >> dr; + dr = 32; + } + // if (doc.HasMember("dynamicRange")) { + // dr=doc["dynamicRange"].GetUint(); + // dr=32; + // } + + dMode = eAnalog; + detectorMode_s = "analog"; + cprintf(MAGENTA, "Detector mode: "); + if (addJsonHeader.find("detectorMode") != addJsonHeader.end()) { + ; + // if (doc.HasMember("detectorMode")) { + // if (doc["detectorMode"].IsString()) { + detectorMode_s = addJsonHeader.at( + "detectorMode"); //=doc["detectorMode"].GetString(); #ifdef INTERP - mt->setInterpolation(NULL); + if (detectorMode_s == "interpolating") { + dMode = eInterpolating; + mt->setInterpolation(interp); + } else #endif - } else { - dMode=eAnalog; + if (detectorMode_s == "counting") { + dMode = ePhotonCounting; #ifdef INTERP - mt->setInterpolation(NULL); + mt->setInterpolation(NULL); #endif - } - // } - - } + } else { + dMode = eAnalog; +#ifdef INTERP + mt->setInterpolation(NULL); +#endif + } + // } + } - mt->setDetectorMode(dMode); - cprintf(MAGENTA, "%s\n" , detectorMode_s.c_str()); + mt->setDetectorMode(dMode); + cprintf(MAGENTA, "%s\n", detectorMode_s.c_str()); - // cout << "done " << endl; + // cout << "done " << endl; - // /* Single Photon Detector commands */ - // nSigma=5; - // if (doc.HasMember("nSigma")) { - // if (doc["nSigma"].IsInt()) - // nSigma=doc["nSigma"].GetInt(); - // mt->setNSigma(nSigma); - // } - - // emin=-1; - // emax=-1; - // if (doc.HasMember("energyRange")) { - // if (doc["energyRange"].IsArray()) { - // if (doc["energyRange"].Size() > 0 ) - // if (doc["energyRange"][0].IsInt()) - // emin=doc["energyRange"][0].GetInt(); - - // if (doc["energyRange"].Size() > 1 ) - // if (doc["energyRange"][1].IsInt()) - // emax=doc["energyRange"][1].GetUint(); - // } - // } - // if (doc.HasMember("eMin")) { - // if (doc["eMin"][1].IsInt()) - // emin=doc["eMin"].GetInt(); - // } - // if (doc.HasMember("eMax")) { - // if (doc["eMax"][1].IsInt()) - // emin=doc["eMax"].GetInt(); - // } - // mt->setEnergyRange(emin,emax); - - // /* interpolating detector commands */ + // /* Single Photon Detector commands */ + // nSigma=5; + // if (doc.HasMember("nSigma")) { + // if (doc["nSigma"].IsInt()) + // nSigma=doc["nSigma"].GetInt(); + // mt->setNSigma(nSigma); + // } - // if (doc.HasMember("nSubPixels")) { - // if (doc["nSubPixels"].IsUint()) - // nSubPixels=doc["nSubPixels"].GetUint(); - // mt->setNSubPixels(nSubPixels); - // } - - // threshold=0; - // cprintf(MAGENTA, "Subframes: "); - // subframes=0; - // //isubframe=0; - // insubframe=0; - // subnorm=1; - // f0=0; - // nnsubframe=0; - // if (doc.HasMember("subframes")) { - // if (doc["subframes"].IsInt()) { - // subframes=doc["subframes"].GetInt(); - // } - // } - // cprintf(MAGENTA, "%ld\n", subframes); + // emin=-1; + // emax=-1; + // if (doc.HasMember("energyRange")) { + // if (doc["energyRange"].IsArray()) { + // if (doc["energyRange"].Size() > 0 ) + // if (doc["energyRange"][0].IsInt()) + // emin=doc["energyRange"][0].GetInt(); - - newFrame=0; - /* zmqsocket->CloseHeaderMessage();*/ - } + // if (doc["energyRange"].Size() > 1 ) + // if (doc["energyRange"][1].IsInt()) + // emax=doc["energyRange"][1].GetUint(); + // } + // } + // if (doc.HasMember("eMin")) { + // if (doc["eMin"][1].IsInt()) + // emin=doc["eMin"].GetInt(); + // } + // if (doc.HasMember("eMax")) { + // if (doc["eMax"][1].IsInt()) + // emin=doc["eMax"].GetInt(); + // } + // mt->setEnergyRange(emin,emax); + + // /* interpolating detector commands */ + + // if (doc.HasMember("nSubPixels")) { + // if (doc["nSubPixels"].IsUint()) + // nSubPixels=doc["nSubPixels"].GetUint(); + // mt->setNSubPixels(nSubPixels); + // } + + // threshold=0; + // cprintf(MAGENTA, "Subframes: "); + // subframes=0; + // //isubframe=0; + // insubframe=0; + // subnorm=1; + // f0=0; + // nnsubframe=0; + // if (doc.HasMember("subframes")) { + // if (doc["subframes"].IsInt()) { + // subframes=doc["subframes"].GetInt(); + // } + // } + // cprintf(MAGENTA, "%ld\n", subframes); + + newFrame = 0; + /* zmqsocket->CloseHeaderMessage();*/ + } #endif - // cout << "file" << endl; - // cout << "data " << endl; - if (of==NULL) { + // cout << "file" << endl; + // cout << "data " << endl; + if (of == NULL) { #ifdef WRITE_QUAD - sprintf(ofname,"%s_%ld.clust2",filename.c_str(),fileindex); + sprintf(ofname, "%s_%ld.clust2", filename.c_str(), fileindex); #endif #ifndef WRITE_QUAD - sprintf(ofname,"%s_%ld.clust",filename.c_str(),fileindex); + sprintf(ofname, "%s_%ld.clust", filename.c_str(), fileindex); #endif - of=fopen(ofname,"w"); - if (of) { - mt->setFilePointer(of); - }else { - cout << "Could not open "<< ofname << " for writing " << endl; - mt->setFilePointer(NULL); - } - } + of = fopen(ofname, "w"); + if (of) { + mt->setFilePointer(of); + } else { + cout << "Could not open " << ofname << " for writing " << endl; + mt->setFilePointer(NULL); + } + } - + // cout << "data" << endl; + // get data + // acqIndex = doc["acqIndex"].GetUint64(); - // cout << "data" << endl; - // get data - // acqIndex = doc["acqIndex"].GetUint64(); + frameIndex = zHeader.frameIndex; ////doc["fIndex"].GetUint64(); - frameIndex = zHeader.frameIndex;////doc["fIndex"].GetUint64(); + // subFrameIndex = doc["expLength"].GetUint(); - // subFrameIndex = doc["expLength"].GetUint(); + // bunchId=doc["bunchId"].GetUint(); + // timestamp=doc["timestamp"].GetUint(); + packetNumber = zHeader.packetNumber; // doc["packetNumber"].GetUint(); + // cout << acqIndex << " " << frameIndex << " " << subFrameIndex << " + // "<< bunchId << " " << timestamp << " " << packetNumber << endl; + // cprintf(GREEN, "frame\n"); + if (packetNumber >= 40) { + //*((int*)buff)=frameIndex; + if (insubframe == 0) + f0 = frameIndex; + memcpy(buff, &frameIndex, sizeof(int)); + // length = + zmqsocket->ReceiveData(0, buff + sizeof(int), size); + mt->pushData(buff); + mt->nextThread(); + mt->popFree(buff); + insubframe++; + nsubframes = frameIndex + 1 - f0; + } else { + cprintf(RED, "Incomplete frame: received only %d packet\n", + packetNumber); + // length = + zmqsocket->ReceiveData(0, dummybuff, size); + } - // bunchId=doc["bunchId"].GetUint(); - // timestamp=doc["timestamp"].GetUint(); - packetNumber=zHeader.packetNumber; //doc["packetNumber"].GetUint(); - // cout << acqIndex << " " << frameIndex << " " << subFrameIndex << " "<< bunchId << " " << timestamp << " " << packetNumber << endl; - //cprintf(GREEN, "frame\n"); - if (packetNumber>=40) { - //*((int*)buff)=frameIndex; - if (insubframe==0) f0=frameIndex; - memcpy(buff,&frameIndex,sizeof(int)); - //length = - zmqsocket->ReceiveData(0, buff+sizeof(int), size); - mt->pushData(buff); - mt->nextThread(); - mt->popFree(buff); - insubframe++; - nsubframes=frameIndex+1-f0; - } else { - cprintf(RED, "Incomplete frame: received only %d packet\n", packetNumber); - //length = - zmqsocket->ReceiveData(0, dummybuff, size); - } - + if (subframes > 0 && insubframe >= subframes && fMode == eFrame) { + while (mt->isBusy()) { + ; + } // wait until all data are processed from the queues + detimage = mt->getImage(nnx, nny, nnsx, nnsy); + cprintf(MAGENTA, "Get image!\n"); + dout = new int32_t[nnx * nny]; + doutf = new float[nnx * nny]; + if (subframes > 0 && insubframe != subframes && insubframe > 0) + subnorm = ((double)subframes) / ((double)insubframe); + else + subnorm = 1.; + for (int ix = 0; ix < nnx * nny; ix++) { + dout[ix] = detimage[ix] * subnorm; + if (dout[ix] < 0) + dout[ix] = 0; + doutf[ix] = dout[ix]; + } + sprintf(ofname, "%s_sf%ld_%ld.tiff", fname.c_str(), nnsubframe, + fileindex); + cout << "Writing image to " << ofname << endl; + WriteToTiff(doutf, ofname, nnx, nny); + nsubframes++; + insubframe = 0; + nnsubframe++; - if (subframes>0 && insubframe>=subframes && fMode==eFrame) { - while (mt->isBusy()) {;}//wait until all data are processed from the queues - detimage=mt->getImage(nnx,nny,nnsx, nnsy); - cprintf(MAGENTA,"Get image!\n"); - dout= new int32_t[nnx*nny]; - doutf= new float[nnx*nny]; - if (subframes>0 && insubframe!=subframes && insubframe>0) - subnorm=((double)subframes)/((double)insubframe); - else - subnorm=1.; - for (int ix=0; ixSendHeaderData (0, + // false,SLS_DETECTOR_JSON_HEADER_VERSION , dr, fileindex, + // 1,1,nnx,nny,nnx*nny*dr/8,acqIndex, frameIndex, fname,acqIndex,0 + // , packetNumber,bunchId, timestamp, modId,xCoord, yCoord, + // zCoord,debug, roundRNumber, detType, version, 0,0, + // 0,&additionalJsonHeader); + zHeader.data = true; + zmqsocket2->SendHeader(0, zHeader); + zmqsocket2->SendData((char *)dout, nnx * nny * dr / 8); + cprintf(GREEN, "Sent subdata\n"); - WriteToTiff(doutf,ofname ,nnx, nny); - nsubframes++; - insubframe=0; - nnsubframe++; + if (dout) + delete[] dout; + dout = NULL; + if (doutf) + delete[] doutf; + doutf = NULL; - - // zmqsocket2->SendHeaderData (0, false,SLS_DETECTOR_JSON_HEADER_VERSION , dr, fileindex, 1,1,nnx,nny,nnx*nny*dr/8,acqIndex, frameIndex, fname,acqIndex,0 , packetNumber,bunchId, timestamp, modId,xCoord, yCoord, zCoord,debug, roundRNumber, detType, version, 0,0, 0,&additionalJsonHeader); - zHeader.data = true; - zmqsocket2->SendHeader(0,zHeader); - zmqsocket2->SendData((char*)dout,nnx*nny*dr/8); - cprintf(GREEN, "Sent subdata\n"); - + mt->clearImage(); + } - if (dout) - delete [] dout; - dout=NULL; + iframe++; - if (doutf) - delete [] doutf; - doutf=NULL; - - mt->clearImage(); - - } + } // exiting infinite loop - + delete zmqsocket; + if (send) + delete zmqsocket2; - - - - - - - - - - - - iframe++; - - } // exiting infinite loop - - - - delete zmqsocket; - if (send) - delete zmqsocket2; - - - cout<<"Goodbye"<< endl; - return 0; + cout << "Goodbye" << endl; + return 0; } - diff --git a/slsDetectorCalibration/moench03CommonMode.h b/slsDetectorCalibration/moench03CommonMode.h index 876146630..2765b12a0 100644 --- a/slsDetectorCalibration/moench03CommonMode.h +++ b/slsDetectorCalibration/moench03CommonMode.h @@ -5,59 +5,60 @@ #include "commonModeSubtractionNew.h" -class commonModeSubtractionColumn: public commonModeSubtraction{ -public: - commonModeSubtractionColumn(int nr=200) : commonModeSubtraction(800), rows(nr) {}; - virtual int getROI(int ix, int iy){return ix+(iy/200)*400;}; - - virtual void addToCommonMode(double val, int ix=0, int iy=0) { - if (iy399-rows) { - int iroi=getROI(ix,iy); - // cout << iy << " " << ix << " " << iroi ; - if (iroi>=0 && iroirows) cout << "Too many pixels added " << nCm[iroi] << endl; - /* if (ix==10 && iy<20) */ - /* cout << " ** "< 399 - rows) { + int iroi = getROI(ix, iy); + // cout << iy << " " << ix << " " << iroi ; + if (iroi >= 0 && iroi < nROI) { + mean[iroi] += val; + mean2[iroi] += val * val; + nCm[iroi]++; + if (nCm[iroi] > rows) + cout << "Too many pixels added " << nCm[iroi] << endl; + /* if (ix==10 && iy<20) */ + /* cout << " ** "<rows); + virtual commonModeSubtractionColumn *Clone() { + return new commonModeSubtractionColumn(this->rows); } - private: - int rows; + private: + int rows; }; - -class commonModeSubtractionSuperColumn: public commonModeSubtraction{ -public: -commonModeSubtractionSuperColumn() : commonModeSubtraction(32) {}; - virtual int getROI(int ix, int iy){ return ix/25+(iy/200)*16;}; +class commonModeSubtractionSuperColumn : public commonModeSubtraction { + public: + commonModeSubtractionSuperColumn() : commonModeSubtraction(32){}; + virtual int getROI(int ix, int iy) { return ix / 25 + (iy / 200) * 16; }; }; - -class commonModeSubtractionHalf: public commonModeSubtraction{ -public: -commonModeSubtractionHalf() : commonModeSubtraction(2) {}; - virtual int getROI(int ix, int iy){ (void) ix; return iy/200;}; +class commonModeSubtractionHalf : public commonModeSubtraction { + public: + commonModeSubtractionHalf() : commonModeSubtraction(2){}; + virtual int getROI(int ix, int iy) { + (void)ix; + return iy / 200; + }; }; - class moench03CommonMode : public commonModeSubtractionColumn { - /** @short class to calculate the common mode noise for moench02 i.e. on 4 supercolumns separately */ - public: - /** constructor - initalizes a commonModeSubtraction with 4 different regions of interest - \param nn number of samples for the moving average - */ - moench03CommonMode(int nr=20) : commonModeSubtractionColumn(nr){} ; - - + /** @short class to calculate the common mode noise for moench02 i.e. on 4 + * supercolumns separately */ + public: + /** constructor - initalizes a commonModeSubtraction with 4 different + regions of interest \param nn number of samples for the moving average + */ + moench03CommonMode(int nr = 20) : commonModeSubtractionColumn(nr){}; }; - #endif diff --git a/slsDetectorCalibration/moench03GhostSummation.h b/slsDetectorCalibration/moench03GhostSummation.h index ce5574b8e..73de83755 100644 --- a/slsDetectorCalibration/moench03GhostSummation.h +++ b/slsDetectorCalibration/moench03GhostSummation.h @@ -7,60 +7,58 @@ class moench03GhostSummation : public ghostSummation { - /** @short virtual calss to handle ghosting*/ + /** @short virtual calss to handle ghosting*/ - public: - - /** constructor - \param xt crosstalk - */ - moench03GhostSummation(slsDetectorData *d, double xt=0.0004) : ghostSummation(d, xt) {} - - virtual void calcGhost(char *data){ - for (int iy=0; iy<200; iy++){ - for (int ix=0; ix<25; ix++){ - calcGhost(data,ix,iy); - } + public: + /** constructor + \param xt crosstalk + */ + moench03GhostSummation(slsDetectorData *d, double xt = 0.0004) + : ghostSummation(d, xt) {} + + virtual void calcGhost(char *data) { + for (int iy = 0; iy < 200; iy++) { + for (int ix = 0; ix < 25; ix++) { + calcGhost(data, ix, iy); + } + } + }; + + moench03GhostSummation(moench03GhostSummation *orig) + : ghostSummation(orig) {} + + virtual moench03GhostSummation *Clone() { + return new moench03GhostSummation(this); } - }; - - moench03GhostSummation(moench03GhostSummation *orig) : ghostSummation(orig) { - } - - virtual moench03GhostSummation *Clone() { - return new moench03GhostSummation(this); - } - - virtual double calcGhost(char *data, int x, int y=0){ - int ix=x%25; - int iy=y; - if (y>=200) iy=399-y; - if (iy<0 || ix<0) return 0; - double val=0; - val=0; - for (int isc=0; isc<16; isc++) { - val+=det->getChannel(data,ix+25*isc,iy); - // cout << val << " " ; - val+=det->getChannel(data,ix+25*isc,399-iy); - // cout << val << " " ; - } - ghost[iy*nx+ix]=xtalk*val; - // if (ix==15 && iy==15) cout << ":" << ghost[iy*nx+ix] << " " << val << endl; - return ghost[iy*nx+ix]; - }; - - - virtual double getGhost(int ix, int iy) { - if (iy >=0 && iy<200) return ghost[iy*nx+(ix%25)]; - if (iy<400) return ghost[(399-iy)*nx+(ix%25)]; - return 0; - }; + virtual double calcGhost(char *data, int x, int y = 0) { + int ix = x % 25; + int iy = y; + if (y >= 200) + iy = 399 - y; + if (iy < 0 || ix < 0) + return 0; + double val = 0; + val = 0; + for (int isc = 0; isc < 16; isc++) { + val += det->getChannel(data, ix + 25 * isc, iy); + // cout << val << " " ; + val += det->getChannel(data, ix + 25 * isc, 399 - iy); + // cout << val << " " ; + } + ghost[iy * nx + ix] = xtalk * val; + // if (ix==15 && iy==15) cout << ":" << ghost[iy*nx+ix] << " " << val << + // endl; + return ghost[iy * nx + ix]; + }; + virtual double getGhost(int ix, int iy) { + if (iy >= 0 && iy < 200) + return ghost[iy * nx + (ix % 25)]; + if (iy < 400) + return ghost[(399 - iy) * nx + (ix % 25)]; + return 0; + }; }; - - - - #endif diff --git a/slsDetectorCalibration/moenchCommonMode.h b/slsDetectorCalibration/moenchCommonMode.h index df5959ca2..2ccc1e142 100644 --- a/slsDetectorCalibration/moenchCommonMode.h +++ b/slsDetectorCalibration/moenchCommonMode.h @@ -6,16 +6,18 @@ #include "commonModeSubtractionNew.h" class moenchCommonMode : public commonModeSubtraction { - /** @short class to calculate the common mode noise for moench02 i.e. on 4 supercolumns separately */ - public: - /** constructor - initalizes a commonModeSubtraction with 4 different regions of interest - \param nn number of samples for the moving average - */ + /** @short class to calculate the common mode noise for moench02 i.e. on 4 + * supercolumns separately */ + public: + /** constructor - initalizes a commonModeSubtraction with 4 different + regions of interest \param nn number of samples for the moving average + */ - moenchCommonMode(int nn=0) : commonModeSubtraction(0){} ; - + moenchCommonMode(int nn = 0) : commonModeSubtraction(0){}; - /* /\** add value to common mode as a function of the pixel value, subdividing the region of interest in the 4 supercolumns of 40 columns each; */ + /* /\** add value to common mode as a function of the pixel value, + * subdividing the region of interest in the 4 supercolumns of 40 columns + * each; */ /* \param val value to add to the common mode */ /* \param ix pixel coordinate in the x direction */ /* \param iy pixel coordinate in the y direction */ @@ -28,7 +30,9 @@ class moenchCommonMode : public commonModeSubtraction { /* nCm[isc]++; */ /* } */ /* }; */ - /* /\**returns common mode value as a function of the pixel value, subdividing the region of interest in the 4 supercolumns of 40 columns each; */ + /* /\**returns common mode value as a function of the pixel value, + * subdividing the region of interest in the 4 supercolumns of 40 columns + * each; */ /* \param ix pixel coordinate in the x direction */ /* \param iy pixel coordinate in the y direction */ /* \returns common mode value */ @@ -41,8 +45,6 @@ class moenchCommonMode : public commonModeSubtraction { /* } */ /* return 0; */ /* }; */ - }; - #endif diff --git a/slsDetectorCalibration/moenchExecutables/moench03ClusterFinder.cpp b/slsDetectorCalibration/moenchExecutables/moench03ClusterFinder.cpp index 4ed5d26e4..a1f84b28e 100644 --- a/slsDetectorCalibration/moenchExecutables/moench03ClusterFinder.cpp +++ b/slsDetectorCalibration/moenchExecutables/moench03ClusterFinder.cpp @@ -3,7 +3,6 @@ //#include "sls/ansi.h" #include - //#include "moench03T1ZmqData.h" #ifdef NEWRECEIVER #ifndef RECT @@ -16,13 +15,12 @@ #endif - #ifdef CSAXS_FP #include "moench03T1ReceiverData.h" -#endif +#endif #ifdef OLDDATA #include "moench03Ctb10GbT1Data.h" -#endif +#endif #ifdef REORDERED #include "moench03T1ReorderedData.h" @@ -36,204 +34,186 @@ #include "singlePhotonDetector.h" //#include "interpolatingDetector.h" -#include -#include #include +#include +#include #include #include using namespace std; - int main(int argc, char *argv[]) { - - if (argc<6) { - cout << "Usage is " << argv[0] << "indir outdir fname runmin runmax " << endl; - return 1; - } - int p=10000; - int fifosize=1000; - int nthreads=1; - int nsubpix=25; - int etabins=nsubpix*10; - double etamin=-1, etamax=2; - int csize=3; - int nx=400, ny=400; - int save=1; - int nsigma=5; - int nped=1000; - int ndark=100; - int ok; - int iprog=0; - - - - + if (argc < 6) { + cout << "Usage is " << argv[0] << "indir outdir fname runmin runmax " + << endl; + return 1; + } + int p = 10000; + int fifosize = 1000; + int nthreads = 1; + int nsubpix = 25; + int etabins = nsubpix * 10; + double etamin = -1, etamax = 2; + int csize = 3; + int nx = 400, ny = 400; + int save = 1; + int nsigma = 5; + int nped = 1000; + int ndark = 100; + int ok; + int iprog = 0; #ifdef NEWRECEIVER #ifdef RECT - cout << "Should be rectangular!" <getDetectorSize(nx, ny); + cout << "nx " << nx << " ny " << ny << endl; - decoder->getDetectorSize(nx,ny); - cout << "nx " << nx << " ny " << ny << endl; + // moench03T1ZmqData *decoder=new moench03T1ZmqData(); + singlePhotonDetector *filter = + new singlePhotonDetector(decoder, csize, nsigma, 1, 0, nped, 200); + // char tit[10000]; + cout << "filter " << endl; - //moench03T1ZmqData *decoder=new moench03T1ZmqData(); - singlePhotonDetector *filter=new singlePhotonDetector(decoder,csize, nsigma, 1, 0, nped, 200); - // char tit[10000]; - cout << "filter " << endl; + // filter->readPedestals("/scratch/ped_100.tiff"); + // interp->readFlatField("/scratch/eta_100.tiff",etamin,etamax); + // cout << "filter "<< endl; + int size = 327680; ////atoi(argv[3]); + int *image; + // int* image =new int[327680/sizeof(int)]; + filter->newDataSet(); - // filter->readPedestals("/scratch/ped_100.tiff"); - // interp->readFlatField("/scratch/eta_100.tiff",etamin,etamax); - // cout << "filter "<< endl; - + int ff, np; + int dsize = decoder->getDataSize(); + cout << " data size is " << dsize; - int size = 327680;////atoi(argv[3]); - - int* image; - //int* image =new int[327680/sizeof(int)]; - filter->newDataSet(); + char data[dsize]; + ifstream filebin; + char *indir = argv[1]; + char *outdir = argv[2]; + char *fformat = argv[3]; + int runmin = atoi(argv[4]); + int runmax = atoi(argv[5]); - int ff, np; - int dsize=decoder->getDataSize(); - cout << " data size is " << dsize; - + char fname[10000]; + char outfname[10000]; + char imgfname[10000]; + char pedfname[10000]; + // strcpy(pedfname,argv[6]); + char fn[10000]; - char data[dsize]; + std::time_t end_time; - ifstream filebin; - char *indir=argv[1]; - char *outdir=argv[2]; - char *fformat=argv[3]; - int runmin=atoi(argv[4]); - int runmax=atoi(argv[5]); - - char fname[10000]; - char outfname[10000]; - char imgfname[10000]; - char pedfname[10000]; - // strcpy(pedfname,argv[6]); - char fn[10000]; - - std::time_t end_time; + FILE *of = NULL; + cout << "input directory is " << indir << endl; + cout << "output directory is " << outdir << endl; + cout << "fileformat is " << fformat << endl; - FILE *of=NULL; - cout << "input directory is " << indir << endl; - cout << "output directory is " << outdir << endl; - cout << "fileformat is " << fformat << endl; - - - std::time(&end_time); - cout << std::ctime(&end_time) << endl; - - - - - - - - - char* buff; - multiThreadedAnalogDetector *mt=new multiThreadedAnalogDetector(filter,nthreads,fifosize); - - - mt->setDetectorMode(ePhotonCounting); - mt->setFrameMode(eFrame); - mt->StartThreads(); - mt->popFree(buff); - - - cout << "mt " << endl; - - int ifr=0; - - - for (int irun=runmin; irunsetFilePointer(of); - // cout << "file pointer set " << endl; - } else { - cout << "Could not open "<< outfname << " for writing " << endl; - mt->setFilePointer(NULL); - return 1; - } - // //while read frame - ff=-1; - while (decoder->readNextFrame(filebin, ff, np,buff)) { - // cout << "*"<getChannel(buff, ix, iy)<3000 || decoder->getChannel(buff, ix, iy)>8000) { - // cout << ifr << " " << ff << " " << ix << " " << iy << " " << decoder->getChannel(buff, ix, iy) << endl ; - // } - // } + cout << std::ctime(&end_time) << endl; - mt->pushData(buff); - // // //pop - mt->nextThread(); - // // // cout << " " << (void*)buff; - mt->popFree(buff); - ifr++; - if (ifr%10000==0) cout << ifr << " " << ff << endl; - ff=-1; - } - cout << "--" << endl; - filebin.close(); - // //close file - // //join threads - while (mt->isBusy()) {;}//wait until all data are processed from the queues - if (of) - fclose(of); - - mt->writeImage(imgfname); - mt->clearImage(); - - std::time(&end_time); - cout << std::ctime(&end_time) << endl; + char *buff; + multiThreadedAnalogDetector *mt = + new multiThreadedAnalogDetector(filter, nthreads, fifosize); - } else - cout << "Could not open "<< fname << " for reading " << endl; - - - } - + mt->setDetectorMode(ePhotonCounting); + mt->setFrameMode(eFrame); + mt->StartThreads(); + mt->popFree(buff); - return 0; + cout << "mt " << endl; + + int ifr = 0; + + for (int irun = runmin; irun < runmax; irun++) { + sprintf(fn, fformat, irun); + sprintf(fname, "%s/%s.raw", indir, fn); + sprintf(outfname, "%s/%s.clust", outdir, fn); + sprintf(imgfname, "%s/%s.tiff", outdir, fn); + std::time(&end_time); + cout << std::ctime(&end_time) << endl; + cout << fname << " " << outfname << " " << imgfname << endl; + filebin.open((const char *)(fname), ios::in | ios::binary); + // //open file + if (filebin.is_open()) { + of = fopen(outfname, "w"); + if (of) { + mt->setFilePointer(of); + // cout << "file pointer set " << endl; + } else { + cout << "Could not open " << outfname << " for writing " + << endl; + mt->setFilePointer(NULL); + return 1; + } + // //while read frame + ff = -1; + while (decoder->readNextFrame(filebin, ff, np, buff)) { + // cout << "*"<getChannel(buff, ix, iy)<3000 || + // decoder->getChannel(buff, ix, iy)>8000) { + // cout << ifr << " " << ff << " " << ix << " " << iy << + // " " << decoder->getChannel(buff, ix, iy) << endl ; + // } + // } + + mt->pushData(buff); + // // //pop + mt->nextThread(); + // // // cout << " " << (void*)buff; + mt->popFree(buff); + ifr++; + if (ifr % 10000 == 0) + cout << ifr << " " << ff << endl; + ff = -1; + } + cout << "--" << endl; + filebin.close(); + // //close file + // //join threads + while (mt->isBusy()) { + ; + } // wait until all data are processed from the queues + if (of) + fclose(of); + + mt->writeImage(imgfname); + mt->clearImage(); + + std::time(&end_time); + cout << std::ctime(&end_time) << endl; + + } else + cout << "Could not open " << fname << " for reading " << endl; + } + + return 0; } - diff --git a/slsDetectorCalibration/moenchExecutables/moench03Interpolation.cpp b/slsDetectorCalibration/moenchExecutables/moench03Interpolation.cpp index dc9953590..889022679 100644 --- a/slsDetectorCalibration/moenchExecutables/moench03Interpolation.cpp +++ b/slsDetectorCalibration/moenchExecutables/moench03Interpolation.cpp @@ -17,100 +17,103 @@ #endif //#include "etaInterpolationPosXY.h" -#include "noInterpolation.h" #include "etaInterpolationPosXY.h" +#include "noInterpolation.h" //#include "etaInterpolationCleverAdaptiveBins.h" //#include "etaInterpolationRandomBins.h" using namespace std; -#define NC 400 -#define NR 400 -#define MAX_ITERATIONS (nSubPixels*100) +#define NC 400 +#define NR 400 +#define MAX_ITERATIONS (nSubPixels * 100) #define XTALK int main(int argc, char *argv[]) { #ifndef FF - if (argc<9) { - cout << "Wrong usage! Should be: "<< argv[0] << " infile etafile outfile runmin runmax ns cmin cmax" << endl; - return 1; - } -#endif - -#ifdef FF - if (argc<7) { - cout << "Wrong usage! Should be: "<< argv[0] << " infile etafile runmin runmax cmin cmax" << endl; - return 1; - } -#endif - int iarg=4; - char infname[10000]; - char fname[10000]; - char outfname[10000]; -#ifndef FF - iarg=4; + if (argc < 9) { + cout << "Wrong usage! Should be: " << argv[0] + << " infile etafile outfile runmin runmax ns cmin cmax" << endl; + return 1; + } #endif #ifdef FF - iarg=3; + if (argc < 7) { + cout << "Wrong usage! Should be: " << argv[0] + << " infile etafile runmin runmax cmin cmax" << endl; + return 1; + } #endif - int runmin=atoi(argv[iarg++]); - int runmax=atoi(argv[iarg++]); - cout << "Run min: " << runmin << endl; - cout << "Run max: " << runmax << endl; - - int nsubpix=4; + int iarg = 4; + char infname[10000]; + char fname[10000]; + char outfname[10000]; #ifndef FF - nsubpix=atoi(argv[iarg++]); - cout << "Subpix: " << nsubpix << endl; + iarg = 4; #endif - float cmin=atof(argv[iarg++]); - float cmax=atof(argv[iarg++]); - cout << "Energy min: " << cmin << endl; - cout << "Energy max: " << cmax << endl; - //int etabins=500; - int etabins=1000;//nsubpix*2*100; - double etamin=-1, etamax=2; - //double etamin=-0.1, etamax=1.1; - double eta3min=-2, eta3max=2; - int quad; - double sum, totquad; - double sDum[2][2]; - double etax, etay, int_x, int_y; - double eta3x, eta3y, int3_x, int3_y, noint_x, noint_y; - int ok; - int f0=-1; - int ix, iy, isx, isy; - int nframes=0, lastframe=-1; - double d_x, d_y, res=5, xx, yy; - int nph=0, badph=0, totph=0; - FILE *f=NULL; + +#ifdef FF + iarg = 3; +#endif + int runmin = atoi(argv[iarg++]); + int runmax = atoi(argv[iarg++]); + cout << "Run min: " << runmin << endl; + cout << "Run max: " << runmax << endl; + + int nsubpix = 4; +#ifndef FF + nsubpix = atoi(argv[iarg++]); + cout << "Subpix: " << nsubpix << endl; +#endif + float cmin = atof(argv[iarg++]); + float cmax = atof(argv[iarg++]); + cout << "Energy min: " << cmin << endl; + cout << "Energy max: " << cmax << endl; + // int etabins=500; + int etabins = 1000; // nsubpix*2*100; + double etamin = -1, etamax = 2; + // double etamin=-0.1, etamax=1.1; + double eta3min = -2, eta3max = 2; + int quad; + double sum, totquad; + double sDum[2][2]; + double etax, etay, int_x, int_y; + double eta3x, eta3y, int3_x, int3_y, noint_x, noint_y; + int ok; + int f0 = -1; + int ix, iy, isx, isy; + int nframes = 0, lastframe = -1; + double d_x, d_y, res = 5, xx, yy; + int nph = 0, badph = 0, totph = 0; + FILE *f = NULL; #ifdef DOUBLE_SPH - single_photon_hit_double cl(3,3); + single_photon_hit_double cl(3, 3); #endif #ifndef DOUBLE_SPH - single_photon_hit cl(3,3); + single_photon_hit cl(3, 3); #endif - int nSubPixels=nsubpix; + int nSubPixels = nsubpix; #ifndef NOINTERPOLATION - eta2InterpolationPosXY *interp=new eta2InterpolationPosXY(NC, NR, nsubpix, etabins, etamin, etamax); - //eta2InterpolationCleverAdaptiveBins *interp=new eta2InterpolationCleverAdaptiveBins(NC, NR, nsubpix, etabins, etamin, etamax); + eta2InterpolationPosXY *interp = + new eta2InterpolationPosXY(NC, NR, nsubpix, etabins, etamin, etamax); + // eta2InterpolationCleverAdaptiveBins *interp=new + // eta2InterpolationCleverAdaptiveBins(NC, NR, nsubpix, etabins, etamin, + // etamax); #endif #ifdef NOINTERPOLATION - noInterpolation *interp=new noInterpolation(NC, NR, nsubpix); + noInterpolation *interp = new noInterpolation(NC, NR, nsubpix); #endif - - #ifndef FF #ifndef NOINTERPOLATION cout << "read ff " << argv[2] << endl; - sprintf(fname,"%s",argv[2]); + sprintf(fname, "%s", argv[2]); interp->readFlatField(fname); - interp->prepareInterpolation(ok);//, MAX_ITERATIONS); + interp->prepareInterpolation(ok); //, MAX_ITERATIONS); #endif // return 0; #endif @@ -119,134 +122,144 @@ int main(int argc, char *argv[]) { #endif int *img; - float *totimg=new float[NC*NR*nsubpix*nsubpix]; - for (ix=0; ixcalcQuad(cl.get_cluster(), sum, totquad, sDum); - quad=interp->calcEta(cl.get_cluster(), etax, etay, sum, totquad, sDum); - if (sum>cmin && totquad/sum>0.8 && totquad/sum<1.2 && sum200 && sum<580) { - // interp->getInterpolatedPosition(cl.x,cl.y, totquad,quad,cl.get_cluster(),int_x, int_y); + f = fopen(infname, "r"); + if (f) { + cout << infname << endl; + nframes = 0; + f0 = -1; + + while (cl.read(f)) { + totph++; + if (lastframe != cl.iframe) { + lastframe = cl.iframe; + // cout << cl.iframe << endl; + // f0=cl.iframe; + if (nframes == 0) + f0 = lastframe; + nframes++; + } + // quad=interp->calcQuad(cl.get_cluster(), sum, totquad, sDum); + quad = interp->calcEta(cl.get_cluster(), etax, etay, sum, + totquad, sDum); + if (sum > cmin && totquad / sum > 0.8 && totquad / sum < 1.2 && + sum < cmax) { + nph++; + // if (sum>200 && sum<580) { + // interp->getInterpolatedPosition(cl.x,cl.y, + // totquad,quad,cl.get_cluster(),int_x, int_y); // #ifdef SOLEIL // if (cl.x>210 && cl.x<240 && cl.y>210 && cl.y<240) { // #endif #ifndef FF - // interp->getInterpolatedPosition(cl.x,cl.y, cl.get_cluster(),int_x, int_y); - interp->getInterpolatedPosition(cl.x,cl.y, etax, etay, quad,int_x, int_y); - // cout <<"**************"<< endl; - // cout << cl.x << " " << cl.y << " " << sum << endl; - // cl.print(); - // cout << int_x << " " << int_y << endl; - // cout <<"**************"<< endl; - // if (etax!=0 && etay!=0 && etax!=1 && etay!=1) - interp->addToImage(int_x, int_y); - if (int_x<0 || int_y<0 || int_x>400 || int_y>400) { - cout <<"**************"<< endl; - cout << cl.x << " " << cl.y << " " << sum << endl; - cl.print(); - cout << int_x << " " << int_y << endl; - cout <<"**************"<< endl; - } + // interp->getInterpolatedPosition(cl.x,cl.y, + // cl.get_cluster(),int_x, int_y); + interp->getInterpolatedPosition(cl.x, cl.y, etax, etay, + quad, int_x, int_y); + // cout <<"**************"<< endl; + // cout << cl.x << " " << cl.y << " " << sum << endl; + // cl.print(); + // cout << int_x << " " << int_y << endl; + // cout <<"**************"<< endl; + // if (etax!=0 && etay!=0 && etax!=1 && etay!=1) + interp->addToImage(int_x, int_y); + if (int_x < 0 || int_y < 0 || int_x > 400 || int_y > 400) { + cout << "**************" << endl; + cout << cl.x << " " << cl.y << " " << sum << endl; + cl.print(); + cout << int_x << " " << int_y << endl; + cout << "**************" << endl; + } #endif #ifdef FF - // interp->addToFlatField(cl.get_cluster(), etax, etay); -// #ifdef UCL -// if (cl.x>50) -// #endif -// if (etax!=0 && etay!=0 && etax!=1 && etay!=1) - interp->addToFlatField(etax, etay); - // if (etax==0 || etay==0) cout << cl.x << " " << cl.y << endl; - -#endif -// #ifdef SOLEIL -// } -// #endif - - if (nph%1000000==0) cout << nph << endl; - if (nph%10000000==0) { -#ifndef FF - interp->writeInterpolatedImage(outfname); -#endif -#ifdef FF - interp->writeFlatField(outfname); -#endif - - } - } - - } - - - fclose(f); -#ifdef FF - interp->writeFlatField(outfname); -#endif - -#ifndef FF - interp->writeInterpolatedImage(outfname); + // interp->addToFlatField(cl.get_cluster(), etax, etay); + // #ifdef UCL + // if (cl.x>50) + // #endif + // if (etax!=0 && etay!=0 && etax!=1 && etay!=1) + interp->addToFlatField(etax, etay); + // if (etax==0 || etay==0) cout << cl.x << " " << cl.y << + // endl; - img=interp->getInterpolatedImage(); - for (ix=0; ixwriteInterpolatedImage(outfname); +#endif +#ifdef FF + interp->writeFlatField(outfname); +#endif + } + } + } + + fclose(f); +#ifdef FF + interp->writeFlatField(outfname); +#endif + +#ifndef FF + interp->writeInterpolatedImage(outfname); + + img = interp->getInterpolatedImage(); + for (ix = 0; ix < NC; ix++) { + for (iy = 0; iy < NR; iy++) { + for (isx = 0; isx < nsubpix; isx++) { + for (isy = 0; isy < nsubpix; isy++) { + totimg[ix * nsubpix + isx + + (iy * nsubpix + isy) * (NC * nsubpix)] += + img[ix * nsubpix + isx + + (iy * nsubpix + isy) * (NC * nsubpix)]; + } + } + } + } + cout << "Read " << nframes << " frames (first frame: " << f0 + << " last frame: " << lastframe << " delta:" << lastframe - f0 + << ") nph=" << nph << endl; + interp->clearInterpolatedImage(); +#endif + + } else + cout << "could not open file " << infname << endl; } #ifndef FF - sprintf(outfname,argv[3],11111); - WriteToTiff(totimg, outfname,NC*nsubpix,NR*nsubpix); -#endif - -#ifdef FF - interp->writeFlatField(outfname); + sprintf(outfname, argv[3], 11111); + WriteToTiff(totimg, outfname, NC * nsubpix, NR * nsubpix); #endif - cout << "Filled " << nph << " (/"<< totph <<") " << endl; +#ifdef FF + interp->writeFlatField(outfname); +#endif + + cout << "Filled " << nph << " (/" << totph << ") " << endl; return 0; } - diff --git a/slsDetectorCalibration/moenchExecutables/moench03NoInterpolation.cpp b/slsDetectorCalibration/moenchExecutables/moench03NoInterpolation.cpp index 406c5ae33..2a25030ee 100644 --- a/slsDetectorCalibration/moenchExecutables/moench03NoInterpolation.cpp +++ b/slsDetectorCalibration/moenchExecutables/moench03NoInterpolation.cpp @@ -12,161 +12,165 @@ using namespace std; #define NC 400 #define NR 400 - int main(int argc, char *argv[]) { -/** - * trial.o [socket ip] [starting port number] [outfname] - * - */ + /** + * trial.o [socket ip] [starting port number] [outfname] + * + */ - if (argc<7) { - cout << "Wrong usage! Should be: "<< argv[0] << " infile " << " etafile outfile runmin runmax ns" << endl; - return 1; - } + if (argc < 7) { + cout << "Wrong usage! Should be: " << argv[0] << " infile " + << " etafile outfile runmin runmax ns" << endl; + return 1; + } - char infname[10000]; - char outfname[10000]; - int runmin=atoi(argv[4]); - int runmax=atoi(argv[5]); - int nsubpix=atoi(argv[6]); - - int etabins=1000;//nsubpix*2*100; - double etamin=-1, etamax=2; - int quad; - double sum, totquad; - double sDum[2][2]; - double etax, etay, int_x, int_y; - int ok; + char infname[10000]; + char outfname[10000]; + int runmin = atoi(argv[4]); + int runmax = atoi(argv[5]); + int nsubpix = atoi(argv[6]); - int ix, iy, isx, isy; + int etabins = 1000; // nsubpix*2*100; + double etamin = -1, etamax = 2; + int quad; + double sum, totquad; + double sDum[2][2]; + double etax, etay, int_x, int_y; + int ok; + int ix, iy, isx, isy; - FILE *f=NULL; + FILE *f = NULL; - single_photon_hit cl(3,3); - // etaInterpolationPosXY *interp=new etaInterpolationPosXY(NC, NR, nsubpix, etabins, etamin, etamax); - noInterpolation *interp=new noInterpolation(NC, NR, nsubpix); + single_photon_hit cl(3, 3); + // etaInterpolationPosXY *interp=new etaInterpolationPosXY(NC, NR, nsubpix, + // etabins, etamin, etamax); + noInterpolation *interp = new noInterpolation(NC, NR, nsubpix); // interp->readFlatField(argv[2]); // interp->prepareInterpolation(ok); int *img; - float *totimg=new float[NC*NR*nsubpix*nsubpix]; - for (ix=0; ixcalcQuad(cl.get_cluster(), sum, totquad, sDum); - if (sum>200 && sum<580) { - interp->getInterpolatedPosition(cl.x,cl.y, totquad,quad,cl.get_cluster(),int_x, int_y); - interp->addToImage(int_x, int_y); - } - } - fclose(f); + for (int irun = runmin; irun < runmax; irun++) { + sprintf(infname, argv[1], irun); + sprintf(outfname, argv[3], irun); + + f = fopen(infname, "r"); + + if (f) { + while (cl.read(f)) { + quad = interp->calcQuad(cl.get_cluster(), sum, totquad, sDum); + if (sum > 200 && sum < 580) { + interp->getInterpolatedPosition(cl.x, cl.y, totquad, quad, + cl.get_cluster(), int_x, + int_y); + interp->addToImage(int_x, int_y); + } + } + fclose(f); #ifdef FF - img=interp->getInterpolatedImage(); - for (isx=0; isxgetInterpolatedImage(); + for (isx = 0; isx < nsubpix; isx++) { + for (isy = 0; isy < nsubpix; isy++) { + ff[isy * nsubpix + isx] = 0; + } + } + totff = 0; + for (ix = 0; ix < NC; ix++) { + for (iy = 0; iy < NR - 100; iy++) { + for (isx = 0; isx < nsubpix; isx++) { + for (isy = 0; isy < nsubpix; isy++) { + ff[isy * nsubpix + isx] += + img[ix * nsubpix + isx + + (iy * nsubpix + isy) * (NC * nsubpix)]; + } + } + } + } + for (isx = 0; isx < nsubpix; isx++) { + for (isy = 0; isy < nsubpix; isy++) { + totff += ff[isy * nsubpix + isx]; + } + } + totff /= nsubpix * nsubpix; - if (totff) { + if (totff) { - cout << "ff: " << totff << endl; + cout << "ff: " << totff << endl; - for (isx=0; isxwriteInterpolatedImage(outfname); - img=interp->getInterpolatedImage(); - for (ix=0; ixwriteInterpolatedImage(outfname); + img = interp->getInterpolatedImage(); + for (ix = 0; ix < NC; ix++) { + for (iy = 0; iy < NR; iy++) { + for (isx = 0; isx < nsubpix; isx++) { + for (isy = 0; isy < nsubpix; isy++) { + totimg[ix * nsubpix + isx + + (iy * nsubpix + isy) * (NC * nsubpix)] += + img[ix * nsubpix + isx + + (iy * nsubpix + isy) * (NC * nsubpix)]; + } + } + } + } + #endif - interp->clearInterpolatedImage(); - - } + interp->clearInterpolatedImage(); + } } - sprintf(outfname,argv[3],11111); - WriteToTiff(totimg, outfname,NC*nsubpix,NR*nsubpix); - + sprintf(outfname, argv[3], 11111); + WriteToTiff(totimg, outfname, NC * nsubpix, NR * nsubpix); + return 0; } - diff --git a/slsDetectorCalibration/moenchExecutables/moenchPhotonCounter.cpp b/slsDetectorCalibration/moenchExecutables/moenchPhotonCounter.cpp index 8b81cdebe..bf4ceffb0 100644 --- a/slsDetectorCalibration/moenchExecutables/moenchPhotonCounter.cpp +++ b/slsDetectorCalibration/moenchExecutables/moenchPhotonCounter.cpp @@ -22,13 +22,12 @@ #endif - #ifdef CSAXS_FP #include "moench03T1ReceiverData.h" -#endif +#endif #ifdef OLDDATA #include "moench03Ctb10GbT1Data.h" -#endif +#endif // #include "interpolatingDetector.h" //#include "etaInterpolationPosXY.h" @@ -36,420 +35,413 @@ // #include "noInterpolation.h" #include "multiThreadedCountingDetector.h" //#include "multiThreadedAnalogDetector.h" -#include "singlePhotonDetector.h" -#include "moench03GhostSummation.h" #include "moench03CommonMode.h" +#include "moench03GhostSummation.h" +#include "singlePhotonDetector.h" //#include "interpolatingDetector.h" -#include -#include #include +#include +#include #include #include using namespace std; - int main(int argc, char *argv[]) { + if (argc < 4) { + cout << "Usage is " << argv[0] + << "indir outdir fname [runmin] [runmax] [pedfile] [threshold] " + "[nframes] [xmin xmax ymin ymax] [gainmap]" + << endl; + cout << "threshold <0 means analog; threshold=0 means cluster finder; " + "threshold>0 means photon counting" + << endl; + cout << "nframes <0 means sum everything; nframes=0 means one file per " + "run; nframes>0 means one file every nframes" + << endl; + return 1; + } - if (argc<4) { - cout << "Usage is " << argv[0] << "indir outdir fname [runmin] [runmax] [pedfile] [threshold] [nframes] [xmin xmax ymin ymax] [gainmap]" << endl; - cout << "threshold <0 means analog; threshold=0 means cluster finder; threshold>0 means photon counting" << endl; - cout << "nframes <0 means sum everything; nframes=0 means one file per run; nframes>0 means one file every nframes" << endl; - return 1; - } + int p = 10000; + int fifosize = 1000; + int nthreads = 10; + int nsubpix = 25; + int etabins = nsubpix * 10; + double etamin = -1, etamax = 2; + int csize = 3; + int save = 1; + int nsigma = 5; + int nped = 10000; + int ndark = 100; + int ok; + int iprog = 0; - int p=10000; - int fifosize=1000; - int nthreads=10; - int nsubpix=25; - int etabins=nsubpix*10; - double etamin=-1, etamax=2; - int csize=3; - int save=1; - int nsigma=5; - int nped=10000; - int ndark=100; - int ok; - int iprog=0; - - int cf=0; + int cf = 0; #ifdef NEWRECEIVER #ifdef RECT - cout << "Should be rectangular!" <getDetectorSize(nx,ny); + decoder->getDetectorSize(nx, ny); - int ncol_cm=CM_ROWS; - double xt_ghost=C_GHOST; - moench03CommonMode *cm=NULL; - moench03GhostSummation *gs; - double *gainmap=NULL; - float *gm; + int ncol_cm = CM_ROWS; + double xt_ghost = C_GHOST; + moench03CommonMode *cm = NULL; + moench03GhostSummation *gs; + double *gainmap = NULL; + float *gm; + int size = 327680; ////atoi(argv[3]); + int *image; + // int* image =new int[327680/sizeof(int)]; - int size = 327680;////atoi(argv[3]); - - int* image; - //int* image =new int[327680/sizeof(int)]; + int ff, np; + // cout << " data size is " << dsize; - int ff, np; - //cout << " data size is " << dsize; - + ifstream filebin; + char *indir = argv[1]; + char *outdir = argv[2]; + char *fformat = argv[3]; + int runmin = 0; + // cout << "argc is " << argc << endl; + if (argc >= 5) { + runmin = atoi(argv[4]); + } - ifstream filebin; - char *indir=argv[1]; - char *outdir=argv[2]; - char *fformat=argv[3]; - int runmin=0; - - // cout << "argc is " << argc << endl; - if (argc>=5) { - runmin=atoi(argv[4]); - } + int runmax = runmin; - int runmax=runmin; + if (argc >= 6) { + runmax = atoi(argv[5]); + } - if (argc>=6) { - runmax=atoi(argv[5]); - } + char *pedfile = NULL; + if (argc >= 7) { + pedfile = argv[6]; + } + double thr = 0; + double thr1 = 1; - char *pedfile=NULL; - if (argc>=7) { - pedfile=argv[6]; - } - double thr=0; - double thr1=1; + if (argc >= 8) { + thr = atof(argv[7]); + } - if (argc>=8) { - thr=atof(argv[7]); - } - + int nframes = 0; - int nframes=0; - - if (argc>=9) { - nframes=atoi(argv[8]); - } + if (argc >= 9) { + nframes = atoi(argv[8]); + } - int xmin=0, xmax=nx, ymin=0, ymax=ny; - if (argc>=13) { - xmin=atoi(argv[9]); - xmax=atoi(argv[10]); - ymin=atoi(argv[11]); - ymax=atoi(argv[12]); - } + int xmin = 0, xmax = nx, ymin = 0, ymax = ny; + if (argc >= 13) { + xmin = atoi(argv[9]); + xmax = atoi(argv[10]); + ymin = atoi(argv[11]); + ymax = atoi(argv[12]); + } - - char *gainfname=NULL; - if (argc>13) { - gainfname=argv[13]; - cout << "Gain map file name is: " << gainfname << endl; - } + char *gainfname = NULL; + if (argc > 13) { + gainfname = argv[13]; + cout << "Gain map file name is: " << gainfname << endl; + } - + char ffname[10000]; + char fname[10000]; + char imgfname[10000]; + char cfname[10000]; + char fn[10000]; + std::time_t end_time; - char ffname[10000]; - char fname[10000]; - char imgfname[10000]; - char cfname[10000]; - char fn[10000]; - - std::time_t end_time; + FILE *of = NULL; + cout << "input directory is " << indir << endl; + cout << "output directory is " << outdir << endl; + cout << "input file is " << fformat << endl; + cout << "runmin is " << runmin << endl; + cout << "runmax is " << runmax << endl; + if (pedfile) + cout << "pedestal file is " << pedfile << endl; + if (thr > 0) + cout << "threshold is " << thr << endl; + cout << "Nframes is " << nframes << endl; - FILE *of=NULL; - cout << "input directory is " << indir << endl; - cout << "output directory is " << outdir << endl; - cout << "input file is " << fformat << endl; - cout << "runmin is " << runmin << endl; - cout << "runmax is " << runmax << endl; - if (pedfile) - cout << "pedestal file is " << pedfile << endl; - if (thr>0) - cout << "threshold is " << thr << endl; - cout << "Nframes is " << nframes << endl; - - uint32_t nnx, nny; - double *gmap; + uint32_t nnx, nny; + double *gmap; - // if (gainfname) { - // gm=ReadFromTiff(gainfname, nny, nnx); - // if (gm && nnx==nx && nny==ny) { - // gmap=new double[nx*ny]; - // for (int i=0; ireadGainMap(gainfname)) - cout << "using gain map " << gainfname << endl; - else - cout << "Could not open gain map " << gainfname << endl; - } else - thr=0.15*thr; - filter->newDataSet(); - int dsize=decoder->getDataSize(); + if (filter->readGainMap(gainfname)) + cout << "using gain map " << gainfname << endl; + else + cout << "Could not open gain map " << gainfname << endl; + } else + thr = 0.15 * thr; + filter->newDataSet(); + int dsize = decoder->getDataSize(); + char data[dsize]; - char data[dsize]; - - - - - - //#ifndef ANALOG - if (thr>0) { - cout << "threshold is " << thr << endl; //#ifndef ANALOG - filter->setThreshold(thr); + if (thr > 0) { + cout << "threshold is " << thr << endl; + //#ifndef ANALOG + filter->setThreshold(thr); + //#endif + cf = 0; + + } else + cf = 1; //#endif - cf=0; - } else - cf=1; - //#endif + filter->setROI(xmin, xmax, ymin, ymax); + std::time(&end_time); + cout << std::ctime(&end_time) << endl; + char *buff; - filter->setROI(xmin,xmax,ymin,ymax); - std::time(&end_time); - cout << std::ctime(&end_time) << endl; - - char* buff; - - // multiThreadedAnalogDetector *mt=new multiThreadedAnalogDetector(filter,nthreads,fifosize); - multiThreadedCountingDetector *mt=new multiThreadedCountingDetector(filter,nthreads,fifosize); + // multiThreadedAnalogDetector *mt=new + // multiThreadedAnalogDetector(filter,nthreads,fifosize); + multiThreadedCountingDetector *mt = + new multiThreadedCountingDetector(filter, nthreads, fifosize); #ifndef ANALOG mt->setDetectorMode(ePhotonCounting); cout << "Counting!" << endl; - if (thr>0) { - cf=0; - } + if (thr > 0) { + cf = 0; + } #endif //{ #ifdef ANALOG - mt->setDetectorMode(eAnalog); - cout << "Analog!" << endl; - cf=0; - //thr1=thr; -#endif - // } - - mt->StartThreads(); - mt->popFree(buff); + mt->setDetectorMode(eAnalog); + cout << "Analog!" << endl; + cf = 0; + // thr1=thr; +#endif + // } + mt->StartThreads(); + mt->popFree(buff); - // cout << "mt " << endl; + // cout << "mt " << endl; - int ifr=0; + int ifr = 0; - double ped[nx*ny], *ped1; + double ped[nx * ny], *ped1; + if (pedfile) { - if (pedfile) { + cout << "PEDESTAL " << endl; + sprintf(imgfname, "%s/pedestals.tiff", outdir); - cout << "PEDESTAL " << endl; - sprintf(imgfname,"%s/pedestals.tiff",outdir); + if (string(pedfile).find(".tif") == std::string::npos) { + sprintf(fname, "%s.raw", pedfile); + cout << fname << endl; + std::time(&end_time); + cout << "aaa" << std::ctime(&end_time) << endl; - if (string(pedfile).find(".tif")==std::string::npos){ - sprintf(fname,"%s.raw",pedfile); - cout << fname << endl ; - std::time(&end_time); - cout << "aaa" << std::ctime(&end_time) << endl; - - - mt->setFrameMode(ePedestal); - // sprintf(fn,fformat,irun); - filebin.open((const char *)(fname), ios::in | ios::binary); - // //open file - if (filebin.is_open()){ - ff=-1; - while (decoder->readNextFrame(filebin, ff, np,buff)) { - if (np==40) { - mt->pushData(buff); - mt->nextThread(); - mt->popFree(buff); - ifr++; - if (ifr%100==0) - cout << ifr << " " << ff << " " << np << endl; - } else - cout << ifr << " " << ff << " " << np << endl; - ff=-1; - } - filebin.close(); - while (mt->isBusy()) {;} - - } else - cout << "Could not open pedestal file "<< fname << " for reading " << endl; - } else { - float *pp=ReadFromTiff(pedfile, nny, nnx); - if (pp && nnx==nx && nny==ny) { - for (int i=0; isetPedestal(ped); - // ped1=mt->getPedestal(); - - // for (int i=0; isetFrameMode(ePedestal); + // sprintf(fn,fformat,irun); + filebin.open((const char *)(fname), ios::in | ios::binary); + // //open file + if (filebin.is_open()) { + ff = -1; + while (decoder->readNextFrame(filebin, ff, np, buff)) { + if (np == 40) { + mt->pushData(buff); + mt->nextThread(); + mt->popFree(buff); + ifr++; + if (ifr % 100 == 0) + cout << ifr << " " << ff << " " << np << endl; + } else + cout << ifr << " " << ff << " " << np << endl; + ff = -1; + } + filebin.close(); + while (mt->isBusy()) { + ; + } - // cout << ped[i]<<"/"<setPedestal(ped); + // ped1=mt->getPedestal(); + + // for (int i=0; iwritePedestal(imgfname); + std::time(&end_time); + cout << std::ctime(&end_time) << endl; } - mt->writePedestal(imgfname); - std::time(&end_time); - cout << std::ctime(&end_time) << endl; - } - + ifr = 0; + int ifile = 0; - ifr=0; - int ifile=0; - - mt->setFrameMode(eFrame); + mt->setFrameMode(eFrame); - for (int irun=runmin; irun<=runmax; irun++) { - cout << "DATA " ; - // sprintf(fn,fformat,irun); - sprintf(ffname,"%s/%s.raw",indir,fformat); - sprintf(fname,ffname,irun); - sprintf(ffname,"%s/%s.tiff",outdir,fformat); - sprintf(imgfname,ffname,irun); - sprintf(ffname,"%s/%s.clust",outdir,fformat); - sprintf(cfname,ffname,irun); - cout << fname << " " ; - cout << imgfname << endl; - std::time(&end_time); - cout << std::ctime(&end_time) << endl; - // cout << fname << " " << outfname << " " << imgfname << endl; - filebin.open((const char *)(fname), ios::in | ios::binary); - // //open file - ifile=0; - if (filebin.is_open()){ - if (thr<=0 && cf!=0) { //cluster finder - if (of==NULL) { - of=fopen(cfname,"w"); - if (of) { - mt->setFilePointer(of); - cout << "file pointer set " << endl; - } else { - cout << "Could not open "<< cfname << " for writing " << endl; - mt->setFilePointer(NULL); - return 1; - } - } - } - // //while read frame - ff=-1; - ifr=0; - while (decoder->readNextFrame(filebin, ff, np,buff)) { - if (np==40) { - // cout << "*"<pushData(buff); - // // //pop - mt->nextThread(); - // // // cout << " " << (void*)buff; - mt->popFree(buff); + for (int irun = runmin; irun <= runmax; irun++) { + cout << "DATA "; + // sprintf(fn,fformat,irun); + sprintf(ffname, "%s/%s.raw", indir, fformat); + sprintf(fname, ffname, irun); + sprintf(ffname, "%s/%s.tiff", outdir, fformat); + sprintf(imgfname, ffname, irun); + sprintf(ffname, "%s/%s.clust", outdir, fformat); + sprintf(cfname, ffname, irun); + cout << fname << " "; + cout << imgfname << endl; + std::time(&end_time); + cout << std::ctime(&end_time) << endl; + // cout << fname << " " << outfname << " " << imgfname << endl; + filebin.open((const char *)(fname), ios::in | ios::binary); + // //open file + ifile = 0; + if (filebin.is_open()) { + if (thr <= 0 && cf != 0) { // cluster finder + if (of == NULL) { + of = fopen(cfname, "w"); + if (of) { + mt->setFilePointer(of); + cout << "file pointer set " << endl; + } else { + cout << "Could not open " << cfname << " for writing " + << endl; + mt->setFilePointer(NULL); + return 1; + } + } + } + // //while read frame + ff = -1; + ifr = 0; + while (decoder->readNextFrame(filebin, ff, np, buff)) { + if (np == 40) { + // cout << "*"<pushData(buff); + // // //pop + mt->nextThread(); + // // // cout << " " << (void*)buff; + mt->popFree(buff); + ifr++; + if (ifr % 100 == 0) + cout << ifr << " " << ff << endl; + if (nframes > 0) { + if (ifr % nframes == 0) { + // The name has an additional "_fXXXXX" at the end, + // where "XXXXX" is the initial frame number of the + // image (0,1000,2000...) + sprintf(ffname, "%s/%s_f%05d.tiff", outdir, fformat, + ifile); + sprintf(imgfname, ffname, irun); + // cout << "Writing tiff to " << imgfname << " " << + // thr1 << endl; + mt->writeImage(imgfname, thr1); + mt->clearImage(); + ifile++; + } + } + } else + cout << ifr << " " << ff << " " << np << endl; + ff = -1; + } + cout << "--" << endl; + filebin.close(); + // //close file + // //join threads + while (mt->isBusy()) { + ; + } + if (nframes >= 0) { + if (nframes > 0) { + sprintf(ffname, "%s/%s_f%05d.tiff", outdir, fformat, ifile); + sprintf(imgfname, ffname, irun); + } else { + sprintf(ffname, "%s/%s.tiff", outdir, fformat); + sprintf(imgfname, ffname, irun); + } + cout << "Writing tiff to " << imgfname << " " << thr1 << endl; + mt->writeImage(imgfname, thr1); + mt->clearImage(); + if (of) { + fclose(of); + of = NULL; + mt->setFilePointer(NULL); + } + } + std::time(&end_time); + cout << std::ctime(&end_time) << endl; + } else + cout << "Could not open " << fname << " for reading " << endl; + } + if (nframes < 0) { + sprintf(ffname, "%s/%s.tiff", outdir, fformat); + strcpy(imgfname, ffname); + cout << "Writing tiff to " << imgfname << " " << thr1 << endl; + mt->writeImage(imgfname, thr1); + } - - ifr++; - if (ifr%100==0) cout << ifr << " " << ff << endl; - if (nframes>0) { - if (ifr%nframes==0) { - //The name has an additional "_fXXXXX" at the end, where "XXXXX" is the initial frame number of the image (0,1000,2000...) - - sprintf(ffname,"%s/%s_f%05d.tiff",outdir,fformat,ifile); - sprintf(imgfname,ffname,irun); - //cout << "Writing tiff to " << imgfname << " " << thr1 << endl; - mt->writeImage(imgfname, thr1); - mt->clearImage(); - ifile++; - } - } - } else - cout << ifr << " " << ff << " " << np << endl; - ff=-1; - } - cout << "--" << endl; - filebin.close(); - // //close file - // //join threads - while (mt->isBusy()) {;} - if (nframes>=0) { - if (nframes>0) { - sprintf(ffname,"%s/%s_f%05d.tiff",outdir,fformat,ifile); - sprintf(imgfname,ffname,irun); - } else { - sprintf(ffname,"%s/%s.tiff",outdir,fformat); - sprintf(imgfname,ffname,irun); - } - cout << "Writing tiff to " << imgfname << " " << thr1 <writeImage(imgfname, thr1); - mt->clearImage(); - if (of) { - fclose(of); - of=NULL; - mt->setFilePointer(NULL); - } - } - std::time(&end_time); - cout << std::ctime(&end_time) << endl; - } else - cout << "Could not open "<< fname << " for reading " << endl; - } - if (nframes<0){ - sprintf(ffname,"%s/%s.tiff",outdir,fformat); - strcpy(imgfname,ffname); - cout << "Writing tiff to " << imgfname << " " << thr1 <writeImage(imgfname, thr1); - } - - - - return 0; + return 0; } - diff --git a/slsDetectorCalibration/moenchExecutables/moenchZmqProcess.cpp b/slsDetectorCalibration/moenchExecutables/moenchZmqProcess.cpp index 49f7668b5..0999d4cdb 100644 --- a/slsDetectorCalibration/moenchExecutables/moenchZmqProcess.cpp +++ b/slsDetectorCalibration/moenchExecutables/moenchZmqProcess.cpp @@ -9,8 +9,8 @@ #define CM_ROWS 20 -#include "sls/sls_detector_defs.h" #include "sls/ZmqSocket.h" +#include "sls/sls_detector_defs.h" #ifndef RECT #ifndef MOENCH04 #include "moench03T1ZmqDataNew.h" @@ -23,925 +23,943 @@ #ifdef RECT #include "moench03T1ZmqDataNewRect.h" #endif -#include "moench03GhostSummation.h" #include "moench03CommonMode.h" -#include -#include -#include -#include -#include +#include "moench03GhostSummation.h" #include "tiffIO.h" - +#include +#include +#include +#include +#include #include //json header in zmq stream -#include +#include //#include "analogDetector.h" //#include "multiThreadedAnalogDetector.h" //#include "singlePhotonDetector.h" //#include "interpolatingDetector.h" //#include "multiThreadedCountingDetector.h" -#include "multiThreadedInterpolatingDetector.h" #include "etaInterpolationPosXY.h" +#include "multiThreadedInterpolatingDetector.h" #include "sls/ansi.h" #include #include -#include // time_t #include +#include // time_t using namespace std; using namespace std::chrono; //#define SLS_DETECTOR_JSON_HEADER_VERSION 0x2 - // myDet->setNetworkParameter(ADDITIONAL_JSON_HEADER, " \"what\":\"nothing\" "); +// myDet->setNetworkParameter(ADDITIONAL_JSON_HEADER, " +//\"what\":\"nothing\" "); int main(int argc, char *argv[]) { -/** - * trial.o [socket ip] [starting port number] [send_socket ip] [send port number] - * - */ - FILE *of=NULL; - int fifosize=5000; - int etabins=1000, etabinsy=1000;//nsubpix*2*100; - double etamin=-1, etamax=2; - int nSubPixelsX=2; - int emin, emax; - int nSubPixelsY=2; - - // help - if (argc < 3 ) { - cprintf(RED, "Help: ./trial [receive socket ip] [receive starting port number] [send_socket ip] [send starting port number] [nthreads] [nsubpix] [gainmap] [etafile]\n"); - return EXIT_FAILURE; - } - - // receive parameters - bool send = false; - char* socketip=argv[1]; - uint32_t portnum = atoi(argv[2]); - // send parameters if any - char* socketip2 = 0; - uint32_t portnum2 = 0; + /** + * trial.o [socket ip] [starting port number] [send_socket ip] [send port + * number] + * + */ + FILE *of = NULL; + int fifosize = 5000; + int etabins = 1000, etabinsy = 1000; // nsubpix*2*100; + double etamin = -1, etamax = 2; + int nSubPixelsX = 2; + int emin, emax; + int nSubPixelsY = 2; - zmqHeader zHeader, outHeader; - zHeader.jsonversion = SLS_DETECTOR_JSON_HEADER_VERSION; - outHeader.jsonversion = SLS_DETECTOR_JSON_HEADER_VERSION; + // help + if (argc < 3) { + cprintf(RED, "Help: ./trial [receive socket ip] [receive starting port " + "number] [send_socket ip] [send starting port number] " + "[nthreads] [nsubpix] [gainmap] [etafile]\n"); + return EXIT_FAILURE; + } - uint32_t nSigma=5; + // receive parameters + bool send = false; + char *socketip = argv[1]; + uint32_t portnum = atoi(argv[2]); + // send parameters if any + char *socketip2 = 0; + uint32_t portnum2 = 0; - int ok; + zmqHeader zHeader, outHeader; + zHeader.jsonversion = SLS_DETECTOR_JSON_HEADER_VERSION; + outHeader.jsonversion = SLS_DETECTOR_JSON_HEADER_VERSION; - high_resolution_clock::time_point t1; - high_resolution_clock::time_point t2 ; - std::chrono::steady_clock::time_point begin,end,finished; - //time_t begin,end,finished; - int rms=0; - + uint32_t nSigma = 5; + int ok; - if (argc > 4) { - socketip2 = argv[3]; - portnum2 = atoi(argv[4]); - if (portnum2>0) - send = true; - } - cout << "\nrx socket ip : " << socketip << - "\nrx port num : " << portnum ; - if (send) { - cout << "\ntx socket ip : " << socketip2 << - "\ntx port num : " << portnum2; - } - int nthreads=5; - if (argc>5) - nthreads=atoi(argv[5]); + high_resolution_clock::time_point t1; + high_resolution_clock::time_point t2; + std::chrono::steady_clock::time_point begin, end, finished; + // time_t begin,end,finished; + int rms = 0; - cout << "Number of threads is: " << nthreads << endl; - if (argc>6) { - nSubPixelsX=atoi(argv[6]); - nSubPixelsY=nSubPixelsX; + if (argc > 4) { + socketip2 = argv[3]; + portnum2 = atoi(argv[4]); + if (portnum2 > 0) + send = true; + } + cout << "\nrx socket ip : " << socketip << "\nrx port num : " << portnum; + if (send) { + cout << "\ntx socket ip : " << socketip2 + << "\ntx port num : " << portnum2; + } + int nthreads = 5; + if (argc > 5) + nthreads = atoi(argv[5]); + + cout << "Number of threads is: " << nthreads << endl; + if (argc > 6) { + nSubPixelsX = atoi(argv[6]); + nSubPixelsY = nSubPixelsX; #ifdef RECT - nSubPixelsX=2; + nSubPixelsX = 2; #endif - } - cout << "Number of subpixels is: " << nSubPixelsX << " " << nSubPixelsY << endl; + } + cout << "Number of subpixels is: " << nSubPixelsX << " " << nSubPixelsY + << endl; - char *gainfname=NULL; - if (argc>7) { - gainfname=argv[7]; - cout << "Gain map file name is: " << gainfname << endl; - } + char *gainfname = NULL; + if (argc > 7) { + gainfname = argv[7]; + cout << "Gain map file name is: " << gainfname << endl; + } - char *etafname=NULL; - if (argc>8) { - etafname=argv[8]; - cout << "Eta file name is: " << etafname << endl; - } + char *etafname = NULL; + if (argc > 8) { + etafname = argv[8]; + cout << "Eta file name is: " << etafname << endl; + } - //slsDetectorData *det=new moench03T1ZmqDataNew(); + // slsDetectorData *det=new moench03T1ZmqDataNew(); #ifndef MOENCH04 - cout << "This is a Moench03" << endl; - moench03T1ZmqDataNew *det=new moench03T1ZmqDataNew(); + cout << "This is a Moench03" << endl; + moench03T1ZmqDataNew *det = new moench03T1ZmqDataNew(); #endif #ifdef MOENCH04 - cout << "This is a Moench04" << endl; - moench04CtbZmq10GbData *det=new moench04CtbZmq10GbData(); + cout << "This is a Moench04" << endl; + moench04CtbZmq10GbData *det = new moench04CtbZmq10GbData(); #endif - cout << endl << " det" <getDetectorSize(npx, npy); + cout << endl << " det" << endl; + int npx, npy; + det->getDetectorSize(npx, npy); - int send_something=0; + int send_something = 0; + int maxSize = npx * npy * 2; // 32*2*8192;//5000;//atoi(argv[3]); + int size = maxSize; // 32*2*5000; + // int multisize=size; + // int dataSize=size; - int maxSize = npx*npy*2;//32*2*8192;//5000;//atoi(argv[3]); - int size= maxSize;//32*2*5000; - //int multisize=size; - //int dataSize=size; + char *dummybuff = new char[size]; - char *dummybuff=new char[size]; - - - moench03CommonMode *cm=NULL; - moench03GhostSummation *gs=NULL; + moench03CommonMode *cm = NULL; + moench03GhostSummation *gs = NULL; #ifdef CORR - - //int ncol_cm=CM_ROWS; - //double xt_ghost=C_GHOST; - cm=new moench03CommonMode(CM_ROWS); - gs=new moench03GhostSummation(det, C_GHOST); + // int ncol_cm=CM_ROWS; + // double xt_ghost=C_GHOST; + + cm = new moench03CommonMode(CM_ROWS); + gs = new moench03GhostSummation(det, C_GHOST); #endif - double *gainmap=NULL; - float *gm; - double *gmap=NULL; + double *gainmap = NULL; + float *gm; + double *gmap = NULL; - uint32_t nnnx, nnny; - if (gainfname) { - gm=ReadFromTiff(gainfname, nnny, nnnx); - if (gm && nnnx==(uint)npx && nnny==(uint)npy) { - gmap=new double[npx*npy]; - for (int i=0; i *filter=new analogDetector(det,1,NULL,1000); + // analogDetector *filter=new + // analogDetector(det,1,NULL,1000); #ifndef INTERP - singlePhotonDetector *filter=new singlePhotonDetector(det,3, nSigma, 1, cm, 1000, 100, -1, -1, gainmap, gs); + singlePhotonDetector *filter = new singlePhotonDetector( + det, 3, nSigma, 1, cm, 1000, 100, -1, -1, gainmap, gs); - multiThreadedCountingDetector *mt=new multiThreadedCountingDetector(filter,nthreads,fifosize); + multiThreadedCountingDetector *mt = + new multiThreadedCountingDetector(filter, nthreads, fifosize); - // multiThreadedAnalogDetector *mt=new multiThreadedAnalogDetector(filter,nthreads,fifosize); + // multiThreadedAnalogDetector *mt=new + // multiThreadedAnalogDetector(filter,nthreads,fifosize); #endif #ifdef INTERP - eta2InterpolationPosXY *interp=new eta2InterpolationPosXY(npx, npy, nSubPixelsX,nSubPixelsY, etabins, etabinsy, etamin, etamax); + eta2InterpolationPosXY *interp = new eta2InterpolationPosXY( + npx, npy, nSubPixelsX, nSubPixelsY, etabins, etabinsy, etamin, etamax); - if (etafname) interp->readFlatField(etafname); + if (etafname) + interp->readFlatField(etafname); - interpolatingDetector *filter=new interpolatingDetector(det,interp, nSigma, 1, cm, 1000, 10, -1, -1, gainmap, gs); - multiThreadedInterpolatingDetector *mt=new multiThreadedInterpolatingDetector(filter,nthreads,fifosize); + interpolatingDetector *filter = new interpolatingDetector( + det, interp, nSigma, 1, cm, 1000, 10, -1, -1, gainmap, gs); + multiThreadedInterpolatingDetector *mt = + new multiThreadedInterpolatingDetector(filter, nthreads, fifosize); #endif + char *buff; + mt->setFrameMode(eFrame); + mt->StartThreads(); + mt->popFree(buff); - - char* buff; - mt->setFrameMode(eFrame); - mt->StartThreads(); - mt->popFree(buff); - - ZmqSocket* zmqsocket=NULL; + ZmqSocket *zmqsocket = NULL; #ifdef NEWZMQ - // receive socket - try{ + // receive socket + try { #endif - - zmqsocket = new ZmqSocket(socketip,portnum); - + + zmqsocket = new ZmqSocket(socketip, portnum); #ifdef NEWZMQ - } catch (...) { - cprintf(RED, "Error: Could not create Zmq socket on port %d with ip %s\n", portnum, socketip); - delete zmqsocket; - return EXIT_FAILURE; + } catch (...) { + cprintf(RED, + "Error: Could not create Zmq socket on port %d with ip %s\n", + portnum, socketip); + delete zmqsocket; + return EXIT_FAILURE; + } +#endif + +#ifndef NEWZMQ + if (zmqsocket->IsError()) { + cprintf(RED, + "Error: Could not create Zmq socket on port %d with ip %s\n", + portnum, socketip); + delete zmqsocket; + return EXIT_FAILURE; + } +#endif + if (zmqsocket->Connect()) { + cprintf(RED, "Error: Could not connect to socket %s\n", + (zmqsocket->GetZmqServerAddress()).c_str()); + delete zmqsocket; + return EXIT_FAILURE; + } else + printf("Zmq Client at %s\n", zmqsocket->GetZmqServerAddress().c_str()); + + // send socket + ZmqSocket *zmqsocket2 = 0; + // cout << "zmq2 " << endl; + if (send) { +#ifdef NEWZMQ + // receive socket + try { +#endif + zmqsocket2 = new ZmqSocket(portnum2, socketip2); + +#ifdef NEWZMQ + } catch (...) { + cprintf(RED, + "Error: Could not create Zmq socket server on port %d and " + "ip %s\n", + portnum2, socketip2); + // delete zmqsocket2; + // zmqsocket2=NULL; + // delete zmqsocket; + // return EXIT_FAILURE; + send = false; } #endif -#ifndef NEWZMQ - if (zmqsocket->IsError()) { - cprintf(RED, "Error: Could not create Zmq socket on port %d with ip %s\n", portnum, socketip); - delete zmqsocket; - return EXIT_FAILURE; - } +#ifndef NEWZMQ + if (zmqsocket2->IsError()) { + cprintf(RED, + "AAA Error: Could not create Zmq socket server on port %d " + "and ip %s\n", + portnum2, socketip2); + // delete zmqsocket2; + // delete zmqsocket; + // return EXIT_FAILURE; + send = false; + } #endif - if (zmqsocket->Connect()) { - cprintf(RED, "Error: Could not connect to socket %s\n", - (zmqsocket->GetZmqServerAddress()).c_str()); - delete zmqsocket; - return EXIT_FAILURE; - } else - printf("Zmq Client at %s\n", zmqsocket->GetZmqServerAddress().c_str()); - - // send socket - ZmqSocket* zmqsocket2 = 0; - // cout << "zmq2 " << endl; - if (send) { -#ifdef NEWZMQ - // receive socket - try{ -#endif - zmqsocket2 = new ZmqSocket(portnum2, socketip2); + if (zmqsocket2->Connect()) { + cprintf(RED, "BBB Error: Could not connect to socket %s\n", + zmqsocket2->GetZmqServerAddress().c_str()); + // delete zmqsocket2; + send = false; + // return EXIT_FAILURE; + } else + printf("Zmq Client at %s\n", + zmqsocket2->GetZmqServerAddress().c_str()); + } - - -#ifdef NEWZMQ - } catch (...) { - cprintf(RED, "Error: Could not create Zmq socket server on port %d and ip %s\n", portnum2, socketip2); - // delete zmqsocket2; - // zmqsocket2=NULL; - // delete zmqsocket; - // return EXIT_FAILURE; - send = false; - } -#endif - -#ifndef NEWZMQ - if (zmqsocket2->IsError()) { - cprintf(RED, "AAA Error: Could not create Zmq socket server on port %d and ip %s\n", portnum2, socketip2); - // delete zmqsocket2; - //delete zmqsocket; - // return EXIT_FAILURE; - send = false; - } -#endif - if (zmqsocket2->Connect()) { - cprintf(RED, "BBB Error: Could not connect to socket %s\n", - zmqsocket2->GetZmqServerAddress().c_str()); - // delete zmqsocket2; - send = false; - // return EXIT_FAILURE; - } else - printf("Zmq Client at %s\n", zmqsocket2->GetZmqServerAddress().c_str()); - - } - - - // header variables - uint64_t acqIndex = -1; - uint64_t frameIndex = -1; + // header variables + uint64_t acqIndex = -1; + uint64_t frameIndex = -1; #ifdef MOENCH_BRANCH - uint32_t subFrameIndex = -1; - int* flippedData = 0; + uint32_t subFrameIndex = -1; + int *flippedData = 0; #endif - - uint64_t subframes=0; - //uint64_t isubframe=0; - uint64_t insubframe=0; - double subnorm=1; - uint64_t f0=-1, nsubframes=0, nnsubframe=0; - uint64_t fileindex = -1; - string filename = ""; - // char* image = new char[size]; - //int* image = new int[(size/sizeof(int))](); - //uint32_t flippedDataX = -1; - //int *nph; - int iframe=0; - char ofname[10000]; - - string fname; - // int length; - int *detimage=NULL; - int nnx, nny,nnsx, nnsy; - //uint32_t imageSize = 0, nPixelsX = 0, nPixelsY = 0, - //uint32_t dynamicRange = 0; - // infinite loop - uint32_t packetNumber = 0; - uint64_t bunchId = 0; - uint64_t timestamp = 0; - int16_t modId = 0; - uint32_t expLength=0; - uint16_t xCoord = 0; - uint16_t yCoord = 0; - //uint16_t zCoord = 0; - uint32_t debug = 0; - //uint32_t dr = 16; - //int16_t *dout;//=new int16_t [nnx*nny]; - uint32_t dr = 32; - int32_t *dout=NULL;//=new int32_t [nnx*nny]; - float *doutf=NULL;//=new int32_t [nnx*nny]; - uint16_t roundRNumber = 0; - uint8_t detType = 0; - uint8_t version = 0; - string additionalJsonHeader="" ; + uint64_t subframes = 0; + // uint64_t isubframe=0; + uint64_t insubframe = 0; + double subnorm = 1; + uint64_t f0 = -1, nsubframes = 0, nnsubframe = 0; - int32_t threshold=0; - - int32_t xmin=0, xmax=400, ymin=0, ymax=400; - - string frameMode_s, detectorMode_s, intMode_s; + uint64_t fileindex = -1; + string filename = ""; + // char* image = new char[size]; + // int* image = new int[(size/sizeof(int))](); + // uint32_t flippedDataX = -1; + // int *nph; + int iframe = 0; + char ofname[10000]; - // int resetFlat=0; - //int resetPed=0; - //int nsubPixels=1; - //int isPedestal=0; - //int isFlat=0; - int newFrame=1; - detectorMode dMode=eAnalog; - frameMode fMode=eFrame; - double *ped; + string fname; + // int length; + int *detimage = NULL; + int nnx, nny, nnsx, nnsy; + // uint32_t imageSize = 0, nPixelsX = 0, nPixelsY = 0, + // uint32_t dynamicRange = 0; + // infinite loop + uint32_t packetNumber = 0; + uint64_t bunchId = 0; + uint64_t timestamp = 0; + int16_t modId = 0; + uint32_t expLength = 0; + uint16_t xCoord = 0; + uint16_t yCoord = 0; + // uint16_t zCoord = 0; + uint32_t debug = 0; + // uint32_t dr = 16; + // int16_t *dout;//=new int16_t [nnx*nny]; + uint32_t dr = 32; + int32_t *dout = NULL; //=new int32_t [nnx*nny]; + float *doutf = NULL; //=new int32_t [nnx*nny]; + uint16_t roundRNumber = 0; + uint8_t detType = 0; + uint8_t version = 0; + string additionalJsonHeader = ""; - filter->getImageSize(nnx, nny,nnsx, nnsy); + int32_t threshold = 0; - - std::map addJsonHeader; + int32_t xmin = 0, xmax = 400, ymin = 0, ymax = 400; + string frameMode_s, detectorMode_s, intMode_s; + // int resetFlat=0; + // int resetPed=0; + // int nsubPixels=1; + // int isPedestal=0; + // int isFlat=0; + int newFrame = 1; + detectorMode dMode = eAnalog; + frameMode fMode = eFrame; + double *ped; + filter->getImageSize(nnx, nny, nnsx, nnsy); - while(1) { + std::map addJsonHeader; + while (1) { - // cout << "+++++++++++++++++++++++++++++++LOOP" << endl; - // get header, (if dummy, fail is on parse error or end of acquisition) + // cout << "+++++++++++++++++++++++++++++++LOOP" << endl; + // get header, (if dummy, fail is on parse error or end of acquisition) + // rapidjson::Document doc; + if (!zmqsocket->ReceiveHeader(0, zHeader, + SLS_DETECTOR_JSON_HEADER_VERSION)) { + /* zmqsocket->CloseHeaderMessage();*/ + // if (!zmqsocket->ReceiveHeader(0, acqIndex, frameIndex, + //subframeIndex, filename, fileindex)) { + cprintf(RED, "Got Dummy\n"); + // t1=high_resolution_clock::now(); + // time(&end); + // cout << "Measurement lasted " << difftime(end,begin) << endl; - // rapidjson::Document doc; - if (!zmqsocket->ReceiveHeader(0, zHeader, SLS_DETECTOR_JSON_HEADER_VERSION)) { - /* zmqsocket->CloseHeaderMessage();*/ + end = std::chrono::steady_clock::now(); + cout << "Measurement lasted " << (end - begin).count() * 0.000001 + << " ms" << endl; - // if (!zmqsocket->ReceiveHeader(0, acqIndex, frameIndex, subframeIndex, filename, fileindex)) { - cprintf(RED, "Got Dummy\n"); - // t1=high_resolution_clock::now(); - //time(&end); - //cout << "Measurement lasted " << difftime(end,begin) << endl; + while (mt->isBusy()) { + ; + } // wait until all data are processed from the queues + usleep(100); + if (of) { + mt->setFilePointer(NULL); + fclose(of); + of = NULL; + } + if (newFrame > 0) { + cprintf(RED, "DIDn't receive any data!\n"); + if (send) { - end = std::chrono::steady_clock::now(); - cout << "Measurement lasted " << (end-begin).count()*0.000001 << " ms" << endl; - - while (mt->isBusy()) {;}//wait until all data are processed from the queues - usleep(100); - if (of) { - mt->setFilePointer(NULL); - fclose(of); - of=NULL; - } - if (newFrame>0) { - cprintf(RED,"DIDn't receive any data!\n"); - if (send) { - - //zHeader.data = false; - outHeader.data=false; - // zmqsocket2->SendHeaderData(0, true, SLS_DETECTOR_JSON_HEADER_VERSION); - zmqsocket2->SendHeader(0,outHeader); - cprintf(RED, "Sent Dummy\n"); - } - } else { - send_something=0; - if (fMode==ePedestal) { - sprintf(ofname,"%s_%ld_ped.tiff",fname.c_str(),fileindex); - mt->writePedestal(ofname); - cout << "Writing pedestal to " << ofname << endl; - if (rms){ - sprintf(ofname,"%s_%ld_var.tiff",fname.c_str(),fileindex); - mt->writePedestalRMS(ofname); - - } - send_something=1; - } + // zHeader.data = false; + outHeader.data = false; + // zmqsocket2->SendHeaderData(0, true, + // SLS_DETECTOR_JSON_HEADER_VERSION); + zmqsocket2->SendHeader(0, outHeader); + cprintf(RED, "Sent Dummy\n"); + } + } else { + send_something = 0; + if (fMode == ePedestal) { + sprintf(ofname, "%s_%ld_ped.tiff", fname.c_str(), + fileindex); + mt->writePedestal(ofname); + cout << "Writing pedestal to " << ofname << endl; + if (rms) { + sprintf(ofname, "%s_%ld_var.tiff", fname.c_str(), + fileindex); + mt->writePedestalRMS(ofname); + } + send_something = 1; + } #ifdef INTERP - else if (fMode==eFlat) { - mt->prepareInterpolation(ok); - sprintf(ofname,"%s_%ld_eta.tiff",fname.c_str(),fileindex); - mt->writeFlatField(ofname); - cout << "Writing eta to " << ofname << endl; - send_something=1; - } + else if (fMode == eFlat) { + mt->prepareInterpolation(ok); + sprintf(ofname, "%s_%ld_eta.tiff", fname.c_str(), + fileindex); + mt->writeFlatField(ofname); + cout << "Writing eta to " << ofname << endl; + send_something = 1; + } #endif - else { - if (subframes>0 ) { - if (insubframe>0) { - sprintf(ofname,"%s_sf%ld_%ld.tiff",fname.c_str(),nnsubframe,fileindex); - // mt->writeImage(ofname); - doutf= new float[nnx*nny]; - if (subframes>0 && insubframe!=subframes && insubframe>0) - subnorm=((double)subframes)/((double)insubframe); - else - subnorm=1.; - for (int ix=0; ixwriteImage(ofname); - send_something=1; - } - - cout << "Writing image to " << ofname << endl; - } - // cout << nns*nnx*nny*nns*dr/8 << " " << length << endl; + else { + if (subframes > 0) { + if (insubframe > 0) { + sprintf(ofname, "%s_sf%ld_%ld.tiff", fname.c_str(), + nnsubframe, fileindex); + // mt->writeImage(ofname); + doutf = new float[nnx * nny]; + if (subframes > 0 && insubframe != subframes && + insubframe > 0) + subnorm = + ((double)subframes) / ((double)insubframe); + else + subnorm = 1.; + for (int ix = 0; ix < nnx * nny; ix++) { + doutf[ix] = detimage[ix] * subnorm; + if (doutf[ix] < 0) + doutf[ix] = 0; + } - if (send) { - - if (fMode==ePedestal) { - cprintf(MAGENTA,"Get pedestal!\n"); - nnsx=1; - nnsy=1; - - nnx=npx; - nny=npy; - //dout= new int16_t[nnx*nny*nns*nns]; - dout= new int32_t[nnx*nny*nnsx*nnsy]; - // cout << "get pedestal " << endl; - ped=mt->getPedestal(); - // cout << "got pedestal " << endl; - for (int ix=0; ixwriteImage(ofname); + send_something = 1; + } + + cout << "Writing image to " << ofname << endl; + } + // cout << nns*nnx*nny*nns*dr/8 << " " << length << endl; + + if (send) { + + if (fMode == ePedestal) { + cprintf(MAGENTA, "Get pedestal!\n"); + nnsx = 1; + nnsy = 1; + + nnx = npx; + nny = npy; + // dout= new int16_t[nnx*nny*nns*nns]; + dout = new int32_t[nnx * nny * nnsx * nnsy]; + // cout << "get pedestal " << endl; + ped = mt->getPedestal(); + // cout << "got pedestal " << endl; + for (int ix = 0; ix < nnx * nny; ix++) { + + dout[ix] = ped[ix]; + // if (ix<100*400) + // cout << ix << " " << ped[ix] << endl; + } + + } #ifdef INTERP - else if (fMode==eFlat) { - int nb; - double emi=0, ema=1; - int *ff=mt->getFlatField(nb, emi, ema); - nnx=nb; - nny=nb; - dout= new int32_t[nb*nb]; - for (int ix=0; ixgetFlatField(nb, emi, ema); + nnx = nb; + nny = nb; + dout = new int32_t[nb * nb]; + for (int ix = 0; ix < nb * nb; ix++) { + dout[ix] = ff[ix]; + } + } #endif - else { - detimage=mt->getImage(nnx,nny,nnsx, nnsy); - cprintf(MAGENTA,"Get image!\n"); - cout << nnx << " " << nny << " " << nnsx << " " << nnsy << endl; - // nns=1; - // nnx=npx; - // nny=npy; - // nnx=nnx*nns; - //nny=nny*nns; - dout= new int32_t[nnx*nny]; - if (subframes>0 && insubframe!=subframes && insubframe>0) - subnorm=((double)subframes)/((double)insubframe); - else - subnorm=1.; - for (int ix=0; ix0 && subframes>0) || (subframes<=0) ){ + else { + detimage = mt->getImage(nnx, nny, nnsx, nnsy); + cprintf(MAGENTA, "Get image!\n"); + cout << nnx << " " << nny << " " << nnsx << " " << nnsy + << endl; + // nns=1; + // nnx=npx; + // nny=npy; + // nnx=nnx*nns; + // nny=nny*nns; + dout = new int32_t[nnx * nny]; + if (subframes > 0 && insubframe != subframes && + insubframe > 0) + subnorm = + ((double)subframes) / ((double)insubframe); + else + subnorm = 1.; + for (int ix = 0; ix < nnx * nny; ix++) { + // for (int iy=0; iySendHeaderData (0, false,SLS_DETECTOR_JSON_HEADER_VERSION , dr, fileindex, 1,1,nnx,nny,nnx*nny*dr/8,acqIndex, frameIndex, fname,acqIndex,0 , packetNumber,bunchId, timestamp, modId,xCoord, yCoord, zCoord,debug, roundRNumber, detType, version, 0,0, 0,&additionalJsonHeader); - - outHeader.data=true; - outHeader.dynamicRange=dr; - outHeader.fileIndex=fileindex; - outHeader.ndetx=1; - outHeader.ndety=1; - outHeader.npixelsx=nnx; - outHeader.npixelsy=nny; - outHeader.imageSize=nnx*nny*dr/8; - outHeader.acqIndex=acqIndex; - outHeader.frameIndex=frameIndex; - outHeader.fname=fname; - outHeader.frameNumber=acqIndex; - outHeader.expLength=expLength; - outHeader.packetNumber=packetNumber; - outHeader.bunchId=bunchId; - outHeader.timestamp=timestamp; - outHeader.modId=modId; - outHeader.row=xCoord; - outHeader.column=yCoord; - outHeader.debug=debug; - outHeader.roundRNumber=roundRNumber; - outHeader.detType=detType; - outHeader.version=version; - - zmqsocket2->SendHeader(0,outHeader); - zmqsocket2->SendData((char*)dout,nnx*nny*dr/8); - cprintf(GREEN, "Sent Data\n"); - } - outHeader.data=false; - zmqsocket2->SendHeader(0,outHeader); - // zmqsocket2->SendHeaderData(0, true, SLS_DETECTOR_JSON_HEADER_VERSION); - cprintf(RED, "Sent Dummy\n"); - if (dout) - delete [] dout; - dout=NULL; - - } - } + // } + // } + dout[ix] = detimage[ix] * subnorm; + if (dout[ix] < 0) + dout[ix] = 0; + // cout << ix << " " << dout[ix] << endl; + // } + } + } + // if ((insubframe>0 && subframes>0) || (subframes<=0) ){ - mt->clearImage(); - - newFrame=1; - - - //time(&finished); - //cout << "Processing lasted " << difftime(finished,begin) << endl; - - finished = std::chrono::steady_clock::now(); - cout << "Processing lasted " << (finished-begin).count()*0.000001 << " ms" << endl; + if (send_something) { + + // zmqsocket2->SendHeaderData (0, + // false,SLS_DETECTOR_JSON_HEADER_VERSION , dr, + // fileindex, 1,1,nnx,nny,nnx*nny*dr/8,acqIndex, + // frameIndex, fname,acqIndex,0 , packetNumber,bunchId, + // timestamp, modId,xCoord, yCoord, zCoord,debug, + // roundRNumber, detType, version, 0,0, + // 0,&additionalJsonHeader); + + outHeader.data = true; + outHeader.dynamicRange = dr; + outHeader.fileIndex = fileindex; + outHeader.ndetx = 1; + outHeader.ndety = 1; + outHeader.npixelsx = nnx; + outHeader.npixelsy = nny; + outHeader.imageSize = nnx * nny * dr / 8; + outHeader.acqIndex = acqIndex; + outHeader.frameIndex = frameIndex; + outHeader.fname = fname; + outHeader.frameNumber = acqIndex; + outHeader.expLength = expLength; + outHeader.packetNumber = packetNumber; + outHeader.bunchId = bunchId; + outHeader.timestamp = timestamp; + outHeader.modId = modId; + outHeader.row = xCoord; + outHeader.column = yCoord; + outHeader.debug = debug; + outHeader.roundRNumber = roundRNumber; + outHeader.detType = detType; + outHeader.version = version; + + zmqsocket2->SendHeader(0, outHeader); + zmqsocket2->SendData((char *)dout, nnx * nny * dr / 8); + cprintf(GREEN, "Sent Data\n"); + } + outHeader.data = false; + zmqsocket2->SendHeader(0, outHeader); + // zmqsocket2->SendHeaderData(0, true, + // SLS_DETECTOR_JSON_HEADER_VERSION); + cprintf(RED, "Sent Dummy\n"); + if (dout) + delete[] dout; + dout = NULL; + } + } + + mt->clearImage(); + + newFrame = 1; + + // time(&finished); + // cout << "Processing lasted " << difftime(finished,begin) << endl; + + finished = std::chrono::steady_clock::now(); + cout << "Processing lasted " + << (finished - begin).count() * 0.000001 << " ms" << endl; #ifdef OPTIMIZE - return 0; + return 0; #endif - continue; //continue to not get out + continue; // continue to not get out + } + + //#ifdef NEWZMQ + if (newFrame) { + begin = std::chrono::steady_clock::now(); + + size = zHeader.imageSize; // doc["size"].GetUint(); + + // dynamicRange = zheader.dynamicRange; //doc["bitmode"].GetUint(); + // nPixelsX = zHeader.npixelsx; //doc["shape"][0].GetUint(); + // nPixelsY = zHeader.npixelsy;// doc["shape"][1].GetUint(); + filename = zHeader.fname; // doc["fname"].GetString(); + acqIndex = + zHeader + .acqIndex; // doc["acqIndex"].GetUint64(); + // frameIndex = + // zHeader.frameIndex;//doc["fIndex"].GetUint64(); + fileindex = zHeader.fileIndex; // doc["fileIndex"].GetUint64(); + expLength = zHeader.expLength; // doc["expLength"].GetUint(); + packetNumber = + zHeader.packetNumber; // doc["packetNumber"].GetUint(); + bunchId = zHeader.bunchId; // doc["bunchId"].GetUint(); + timestamp = zHeader.timestamp; // doc["timestamp"].GetUint(); + modId = zHeader.modId; // doc["modId"].GetUint(); + debug = zHeader.debug; // doc["debug"].GetUint(); + // roundRNumber=r.roundRNumber;//doc["roundRNumber"].GetUint(); + detType = zHeader.detType; // doc["detType"].GetUint(); + version = zHeader.version; // doc["version"].GetUint(); + /*document["bitmode"].GetUint(); zHeader.dynamicRange - } + */ - //#ifdef NEWZMQ - if (newFrame) { - begin = std::chrono::steady_clock::now(); - - size = zHeader.imageSize;//doc["size"].GetUint(); - - // dynamicRange = zheader.dynamicRange; //doc["bitmode"].GetUint(); - // nPixelsX = zHeader.npixelsx; //doc["shape"][0].GetUint(); - // nPixelsY = zHeader.npixelsy;// doc["shape"][1].GetUint(); - filename = zHeader.fname;//doc["fname"].GetString(); - acqIndex = zHeader.acqIndex; //doc["acqIndex"].GetUint64(); - // frameIndex = zHeader.frameIndex;//doc["fIndex"].GetUint64(); - fileindex = zHeader.fileIndex;//doc["fileIndex"].GetUint64(); - expLength = zHeader.expLength;//doc["expLength"].GetUint(); - packetNumber=zHeader.packetNumber;//doc["packetNumber"].GetUint(); - bunchId=zHeader.bunchId;//doc["bunchId"].GetUint(); - timestamp=zHeader.timestamp;//doc["timestamp"].GetUint(); - modId=zHeader.modId;//doc["modId"].GetUint(); - debug=zHeader.debug;//doc["debug"].GetUint(); - // roundRNumber=r.roundRNumber;//doc["roundRNumber"].GetUint(); - detType=zHeader.detType;//doc["detType"].GetUint(); - version=zHeader.version;//doc["version"].GetUint(); - /*document["bitmode"].GetUint(); zHeader.dynamicRange + // strcpy(fname,filename.c_str()); + fname = filename; + addJsonHeader = zHeader.addJsonHeader; - - */ - - //strcpy(fname,filename.c_str()); - fname=filename; - addJsonHeader=zHeader.addJsonHeader; - - rms=0; - fMode=eFrame; - frameMode_s="frame"; - cprintf(MAGENTA, "Frame mode: "); - // if (doc.HasMember("frameMode")) { - if (addJsonHeader.find("frameMode")!= addJsonHeader.end()) { - // if (doc["frameMode"].IsString()) { - frameMode_s=addJsonHeader.at("frameMode");//doc["frameMode"].GetString(); - if (frameMode_s == "pedestal"){ - fMode=ePedestal; - //isPedestal=1; - } else if (frameMode_s == "newPedestal"){ - mt->newDataSet(); //resets pedestal - // cprintf(MAGENTA, "Resetting pedestal\n"); - fMode=ePedestal; - //isPedestal=1; - } else if (frameMode_s == "variance"){ - mt->newDataSet(); //resets pedestal - // cprintf(MAGENTA, "Resetting pedestal\n"); - fMode=ePedestal; - //isPedestal=1; - rms=1; - } else if (frameMode_s == "raw"){ - //mt->newDataSet(); //resets pedestal - // cprintf(MAGENTA, "Resetting pedestal\n"); - fMode=eRaw; - //isPedestal=1; - } -#ifdef INTERP - else if (frameMode_s == "flatfield") { - fMode=eFlat; - //isFlat=1; - } else if (frameMode_s == "newFlatfield") { - mt->resetFlatField(); - //isFlat=1; - cprintf(MAGENTA, "Resetting flatfield\n"); - fMode=eFlat; - } - //#endif - else { - //isPedestal=0; - //isFlat=0; - fMode=eFrame; - frameMode_s="frame"; - } - //} - } - cprintf(MAGENTA, "%s\n" , frameMode_s.c_str()); - mt->setFrameMode(fMode); - - // threshold=0; - cprintf(MAGENTA, "Threshold: "); - if (addJsonHeader.find("threshold")!= addJsonHeader.end()) { - istringstream(addJsonHeader.at("threshold")) >>threshold; - } - mt->setThreshold(threshold); - cprintf(MAGENTA, "%d\n", threshold); - - xmin=0; - xmax=npx; - ymin=0; - ymax=npy; - cprintf(MAGENTA, "ROI: "); - - if (addJsonHeader.find("roi")!= addJsonHeader.end()) { - istringstream(addJsonHeader.at("roi")) >> xmin >> xmax >> ymin >> ymax ; - } - - cprintf(MAGENTA, "%d %d %d %d\n", xmin, xmax, ymin, ymax); - mt->setROI(xmin, xmax, ymin, ymax); - if (addJsonHeader.find("dynamicRange")!= addJsonHeader.end()) { - istringstream(addJsonHeader.at("dynamicRange")) >> dr ; - dr=32; - } - dMode=eAnalog; - detectorMode_s="analog"; - cprintf(MAGENTA, "Detector mode: "); - if (addJsonHeader.find("detectorMode")!= addJsonHeader.end()) {; - detectorMode_s=addJsonHeader.at("detectorMode");//=doc["detectorMode"].GetString(); + rms = 0; + fMode = eFrame; + frameMode_s = "frame"; + cprintf(MAGENTA, "Frame mode: "); + // if (doc.HasMember("frameMode")) { + if (addJsonHeader.find("frameMode") != addJsonHeader.end()) { + // if (doc["frameMode"].IsString()) { + frameMode_s = addJsonHeader.at( + "frameMode"); // doc["frameMode"].GetString(); + if (frameMode_s == "pedestal") { + fMode = ePedestal; + // isPedestal=1; + } else if (frameMode_s == "newPedestal") { + mt->newDataSet(); // resets pedestal + // cprintf(MAGENTA, "Resetting pedestal\n"); + fMode = ePedestal; + // isPedestal=1; + } else if (frameMode_s == "variance") { + mt->newDataSet(); // resets pedestal + // cprintf(MAGENTA, "Resetting pedestal\n"); + fMode = ePedestal; + // isPedestal=1; + rms = 1; + } else if (frameMode_s == "raw") { + // mt->newDataSet(); //resets pedestal + // cprintf(MAGENTA, "Resetting pedestal\n"); + fMode = eRaw; + // isPedestal=1; + } #ifdef INTERP - if (detectorMode_s == "interpolating"){ - dMode=eInterpolating; - mt->setInterpolation(interp); - } else -#endif - if (detectorMode_s == "counting"){ - dMode=ePhotonCounting; + else if (frameMode_s == "flatfield") { + fMode = eFlat; + // isFlat=1; + } else if (frameMode_s == "newFlatfield") { + mt->resetFlatField(); + // isFlat=1; + cprintf(MAGENTA, "Resetting flatfield\n"); + fMode = eFlat; + } + //#endif + else { + // isPedestal=0; + // isFlat=0; + fMode = eFrame; + frameMode_s = "frame"; + } + //} + } + cprintf(MAGENTA, "%s\n", frameMode_s.c_str()); + mt->setFrameMode(fMode); + + // threshold=0; + cprintf(MAGENTA, "Threshold: "); + if (addJsonHeader.find("threshold") != addJsonHeader.end()) { + istringstream(addJsonHeader.at("threshold")) >> threshold; + } + mt->setThreshold(threshold); + cprintf(MAGENTA, "%d\n", threshold); + + xmin = 0; + xmax = npx; + ymin = 0; + ymax = npy; + cprintf(MAGENTA, "ROI: "); + + if (addJsonHeader.find("roi") != addJsonHeader.end()) { + istringstream(addJsonHeader.at("roi")) >> xmin >> xmax >> + ymin >> ymax; + } + + cprintf(MAGENTA, "%d %d %d %d\n", xmin, xmax, ymin, ymax); + mt->setROI(xmin, xmax, ymin, ymax); + if (addJsonHeader.find("dynamicRange") != addJsonHeader.end()) { + istringstream(addJsonHeader.at("dynamicRange")) >> dr; + dr = 32; + } + dMode = eAnalog; + detectorMode_s = "analog"; + cprintf(MAGENTA, "Detector mode: "); + if (addJsonHeader.find("detectorMode") != addJsonHeader.end()) { + ; + detectorMode_s = addJsonHeader.at( + "detectorMode"); //=doc["detectorMode"].GetString(); #ifdef INTERP - mt->setInterpolation(NULL); + if (detectorMode_s == "interpolating") { + dMode = eInterpolating; + mt->setInterpolation(interp); + } else #endif - } else { - dMode=eAnalog; + if (detectorMode_s == "counting") { + dMode = ePhotonCounting; #ifdef INTERP - mt->setInterpolation(NULL); + mt->setInterpolation(NULL); #endif - } - // } - if (fMode==eRaw) { - detectorMode_s = "analog"; - dMode=eAnalog; - - } - } + } else { + dMode = eAnalog; +#ifdef INTERP + mt->setInterpolation(NULL); +#endif + } + // } + if (fMode == eRaw) { + detectorMode_s = "analog"; + dMode = eAnalog; + } + } - mt->setDetectorMode(dMode); - cprintf(MAGENTA, "%s\n" , detectorMode_s.c_str()); + mt->setDetectorMode(dMode); + cprintf(MAGENTA, "%s\n", detectorMode_s.c_str()); - cout << "done " << endl; + cout << "done " << endl; - /* Single Photon Detector commands */ - nSigma=5; - - if (addJsonHeader.find("nSigma")!= addJsonHeader.end()) {; - istringstream(addJsonHeader.at("nSigma")) >> nSigma ; - mt->setNSigma(nSigma); - } - - emin=-1; - emax=-1; - if (addJsonHeader.find("energyRange")!= addJsonHeader.end()) { - istringstream(addJsonHeader.at("energyRange")) >> emin >> emax ; - } - if (addJsonHeader.find("eMin")!= addJsonHeader.end()) { - istringstream(addJsonHeader.at("eMin")) >> emin ; - } - - if (addJsonHeader.find("eMax")!= addJsonHeader.end()) { - istringstream(addJsonHeader.at("eMax")) >> emax ; - } - - mt->setEnergyRange(emin,emax); - - /* interpolating detector commands */ - //must set subpixels X and Y separately - // if (addJsonHeader.find("nSubPixels")!= addJsonHeader.end()) { - // istringstream(addJsonHeader.at("nSubPixels")) >> nSubPixels ; - // mt->setNSubPixels(nSubPixels); - // } - - threshold=0; - cprintf(MAGENTA, "Subframes: "); - subframes=0; - //isubframe=0; - insubframe=0; - subnorm=1; - f0=0; - nnsubframe=0; - if (addJsonHeader.find("subframes")!= addJsonHeader.end()) { - istringstream(addJsonHeader.at("subframes")) >> subframes ; - } - - cprintf(MAGENTA, "%ld\n", subframes); + /* Single Photon Detector commands */ + nSigma = 5; - - newFrame=0; - } + if (addJsonHeader.find("nSigma") != addJsonHeader.end()) { + ; + istringstream(addJsonHeader.at("nSigma")) >> nSigma; + mt->setNSigma(nSigma); + } + + emin = -1; + emax = -1; + if (addJsonHeader.find("energyRange") != addJsonHeader.end()) { + istringstream(addJsonHeader.at("energyRange")) >> emin >> emax; + } + if (addJsonHeader.find("eMin") != addJsonHeader.end()) { + istringstream(addJsonHeader.at("eMin")) >> emin; + } + + if (addJsonHeader.find("eMax") != addJsonHeader.end()) { + istringstream(addJsonHeader.at("eMax")) >> emax; + } + + mt->setEnergyRange(emin, emax); + + /* interpolating detector commands */ + // must set subpixels X and Y separately + // if (addJsonHeader.find("nSubPixels")!= addJsonHeader.end()) { + // istringstream(addJsonHeader.at("nSubPixels")) >> + // nSubPixels ; mt->setNSubPixels(nSubPixels); + // } + + threshold = 0; + cprintf(MAGENTA, "Subframes: "); + subframes = 0; + // isubframe=0; + insubframe = 0; + subnorm = 1; + f0 = 0; + nnsubframe = 0; + if (addJsonHeader.find("subframes") != addJsonHeader.end()) { + istringstream(addJsonHeader.at("subframes")) >> subframes; + } + + cprintf(MAGENTA, "%ld\n", subframes); + + newFrame = 0; + } #endif + frameIndex = zHeader.frameIndex; ////doc["fIndex"].GetUint64(); + // subFrameIndex = doc["expLength"].GetUint(); - frameIndex = zHeader.frameIndex;////doc["fIndex"].GetUint64(); + // bunchId=doc["bunchId"].GetUint(); + // timestamp=doc["timestamp"].GetUint(); + packetNumber = zHeader.packetNumber; // doc["packetNumber"].GetUint(); + // cout << acqIndex << " " << frameIndex << " " << subFrameIndex << " + // "<< bunchId << " " << timestamp << " " << packetNumber << endl; + // cprintf(GREEN, "frame\n"); + if (packetNumber >= 40) { + //*((int*)buff)=frameIndex; + if (insubframe == 0) + f0 = frameIndex; + memcpy(buff, &frameIndex, sizeof(int)); + // length = + zmqsocket->ReceiveData(0, buff + sizeof(int), size); - // subFrameIndex = doc["expLength"].GetUint(); - - // bunchId=doc["bunchId"].GetUint(); - // timestamp=doc["timestamp"].GetUint(); - packetNumber=zHeader.packetNumber; //doc["packetNumber"].GetUint(); - // cout << acqIndex << " " << frameIndex << " " << subFrameIndex << " "<< bunchId << " " << timestamp << " " << packetNumber << endl; - //cprintf(GREEN, "frame\n"); - if (packetNumber>=40) { - //*((int*)buff)=frameIndex; - if (insubframe==0) f0=frameIndex; - memcpy(buff,&frameIndex,sizeof(int)); - //length = - zmqsocket->ReceiveData(0, buff+sizeof(int), size); - - - - - - if (fMode!=ePedestal || dMode!=eAnalog) { - if (of==NULL) { + if (fMode != ePedestal || dMode != eAnalog) { + if (of == NULL) { #ifdef WRITE_QUAD - sprintf(ofname,"%s_%ld.clust2",filename.c_str(),fileindex); + sprintf(ofname, "%s_%ld.clust2", filename.c_str(), + fileindex); #endif #ifndef WRITE_QUAD - sprintf(ofname,"%s_%ld.clust",filename.c_str(),fileindex); + sprintf(ofname, "%s_%ld.clust", filename.c_str(), + fileindex); #endif - of=fopen(ofname,"w"); - if (of) { - mt->setFilePointer(of); - }else { - cout << "Could not open "<< ofname << " for writing " << endl; - mt->setFilePointer(NULL); - } - } - } + of = fopen(ofname, "w"); + if (of) { + mt->setFilePointer(of); + } else { + cout << "Could not open " << ofname << " for writing " + << endl; + mt->setFilePointer(NULL); + } + } + } - + mt->pushData(buff); + mt->nextThread(); + mt->popFree(buff); + insubframe++; + nsubframes = frameIndex + 1 - f0; + // cout << "insubframe " << insubframe << endl; + // cout << "nsubframes " << nsubframes << endl; + // cout << "f0 " << f0 << endl; + // cout << "frameIndex " << frameIndex << endl; + } else { + cprintf(RED, "Incomplete frame: received only %d packet\n", + packetNumber); + // length = + zmqsocket->ReceiveData(0, dummybuff, size); + } + if (subframes > 0 && insubframe >= subframes && + (fMode == eFrame || fMode == eRaw)) { + while (mt->isBusy()) { + ; + } // wait until all data are processed from the queues + usleep(100); + detimage = mt->getImage(nnx, nny, nnsx, nnsy); + cprintf(MAGENTA, "Get image!\n"); + dout = new int32_t[nnx * nny]; + doutf = new float[nnx * nny]; + if (subframes > 0 && insubframe != subframes && insubframe > 0) + subnorm = ((double)subframes) / ((double)insubframe); + else + subnorm = 1.; + for (int ix = 0; ix < nnx * nny; ix++) { + dout[ix] = detimage[ix] * subnorm; + if (dout[ix] < 0) + dout[ix] = 0; + doutf[ix] = dout[ix]; + } + sprintf(ofname, "%s_sf%ld_%ld.tiff", fname.c_str(), nnsubframe, + fileindex); - mt->pushData(buff); - mt->nextThread(); - mt->popFree(buff); - insubframe++; - nsubframes=frameIndex+1-f0; - // cout << "insubframe " << insubframe << endl; - // cout << "nsubframes " << nsubframes << endl; - // cout << "f0 " << f0 << endl; - // cout << "frameIndex " << frameIndex << endl; - - } else { - cprintf(RED, "Incomplete frame: received only %d packet\n", packetNumber); - //length = - zmqsocket->ReceiveData(0, dummybuff, size); - } - + cout << "Writing image to " << ofname << endl; + WriteToTiff(doutf, ofname, nnx, nny); + nsubframes++; + insubframe = 0; + nnsubframe++; + // zmqsocket2->SendHeaderData (0, + // false,SLS_DETECTOR_JSON_HEADER_VERSION , dr, fileindex, + // 1,1,nnx,nny,nnx*nny*dr/8,acqIndex, frameIndex, fname,acqIndex,0 + // , packetNumber,bunchId, timestamp, modId,xCoord, yCoord, + // zCoord,debug, roundRNumber, detType, version, 0,0, + // 0,&additionalJsonHeader); - if (subframes>0 && insubframe>=subframes && (fMode==eFrame ||fMode==eRaw) ) { - while (mt->isBusy()) {;}//wait until all data are processed from the queues - usleep(100); + // zmqsocket2->SendHeaderData (0, + // false,SLS_DETECTOR_JSON_HEADER_VERSION , dr, fileindex, + // 1,1,nnx,nny,nnx*nny*dr/8,acqIndex, frameIndex, fname,acqIndex,0 + // , packetNumber,bunchId, timestamp, modId,xCoord, yCoord, + // zCoord,debug, roundRNumber, detType, version, 0,0, + // 0,&additionalJsonHeader); - detimage=mt->getImage(nnx,nny,nnsx, nnsy); + outHeader.data = true; + outHeader.dynamicRange = dr; + outHeader.fileIndex = fileindex; + outHeader.ndetx = 1; + outHeader.ndety = 1; + outHeader.npixelsx = nnx; + outHeader.npixelsy = nny; + outHeader.imageSize = nnx * nny * dr / 8; + outHeader.acqIndex = acqIndex; + outHeader.frameIndex = frameIndex; + outHeader.fname = fname; + outHeader.frameNumber = acqIndex; + outHeader.expLength = expLength; + outHeader.packetNumber = packetNumber; + outHeader.bunchId = bunchId; + outHeader.timestamp = timestamp; + outHeader.modId = modId; + outHeader.row = xCoord; + outHeader.column = yCoord; + outHeader.debug = debug; + outHeader.roundRNumber = roundRNumber; + outHeader.detType = detType; + outHeader.version = version; + zmqsocket2->SendHeader(0, outHeader); + zmqsocket2->SendData((char *)dout, nnx * nny * dr / 8); + cprintf(GREEN, "Sent subdata\n"); - cprintf(MAGENTA,"Get image!\n"); - dout= new int32_t[nnx*nny]; - doutf= new float[nnx*nny]; - if (subframes>0 && insubframe!=subframes && insubframe>0) - subnorm=((double)subframes)/((double)insubframe); - else - subnorm=1.; - for (int ix=0; ixclearImage(); + } - - // zmqsocket2->SendHeaderData (0, false,SLS_DETECTOR_JSON_HEADER_VERSION , dr, fileindex, 1,1,nnx,nny,nnx*nny*dr/8,acqIndex, frameIndex, fname,acqIndex,0 , packetNumber,bunchId, timestamp, modId,xCoord, yCoord, zCoord,debug, roundRNumber, detType, version, 0,0, 0,&additionalJsonHeader); - + iframe++; + } // exiting infinite loop - // zmqsocket2->SendHeaderData (0, false,SLS_DETECTOR_JSON_HEADER_VERSION , dr, fileindex, 1,1,nnx,nny,nnx*nny*dr/8,acqIndex, frameIndex, fname,acqIndex,0 , packetNumber,bunchId, timestamp, modId,xCoord, yCoord, zCoord,debug, roundRNumber, detType, version, 0,0, 0,&additionalJsonHeader); - - outHeader.data=true; - outHeader.dynamicRange=dr; - outHeader.fileIndex=fileindex; - outHeader.ndetx=1; - outHeader.ndety=1; - outHeader.npixelsx=nnx; - outHeader.npixelsy=nny; - outHeader.imageSize=nnx*nny*dr/8; - outHeader.acqIndex=acqIndex; - outHeader.frameIndex=frameIndex; - outHeader.fname=fname; - outHeader.frameNumber=acqIndex; - outHeader.expLength=expLength; - outHeader.packetNumber=packetNumber; - outHeader.bunchId=bunchId; - outHeader.timestamp=timestamp; - outHeader.modId=modId; - outHeader.row=xCoord; - outHeader.column=yCoord; - outHeader.debug=debug; - outHeader.roundRNumber=roundRNumber; - outHeader.detType=detType; - outHeader.version=version; - - zmqsocket2->SendHeader(0,outHeader); - zmqsocket2->SendData((char*)dout,nnx*nny*dr/8); - cprintf(GREEN, "Sent subdata\n"); - + delete zmqsocket; + if (send) + delete zmqsocket2; - if (dout) - delete [] dout; - dout=NULL; - - if (doutf) - delete [] doutf; - doutf=NULL; - - mt->clearImage(); - - } - - - iframe++; - - } // exiting infinite loop - - - - delete zmqsocket; - if (send) - delete zmqsocket2; - - - cout<<"Goodbye"<< endl; - return 0; + cout << "Goodbye" << endl; + return 0; } - diff --git a/slsDetectorCalibration/multiThreadedAnalogDetector.h b/slsDetectorCalibration/multiThreadedAnalogDetector.h index ff70cd8a4..a7695c286 100644 --- a/slsDetectorCalibration/multiThreadedAnalogDetector.h +++ b/slsDetectorCalibration/multiThreadedAnalogDetector.h @@ -5,657 +5,635 @@ #define MAXTHREADS 1000 -#include -#include -#include -#include #include +#include +#include #include +#include +#include //#include //#include //#include +#include #include -#include #include #include "analogDetector.h" #include "circularFifo.h" -#include #include #include +#include //#include - using namespace std; +class threadedAnalogDetector { + public: + threadedAnalogDetector(analogDetector *d, int fs = 10000) { + char *mm; //*mem, + det = d; + fifoFree = new CircularFifo(fs); + fifoData = new CircularFifo(fs); + // mem==NULL; + /* mem=(char*)calloc(fs, det->getDataSize()); */ + /* if (mem) */ + /* memset(mem,0, fs*det->getDataSize()); */ + int i; + for (i = 0; i < fs; i++) { + // + // mm=mem+i*det->getDataSize(); + // cout << i << endl; + mm = (char *)calloc(1, det->getDataSize()); + if (mm) { + // memset(mm,0, det->getDataSize()); + fifoFree->push(mm); + } else + break; + } + if (i < fs) + cout << "Could allocate only " << i << " frames"; -class threadedAnalogDetector -{ -public: - threadedAnalogDetector(analogDetector *d, int fs=10000) { - char *mm;//*mem, - det=d; - fifoFree=new CircularFifo(fs); - fifoData=new CircularFifo(fs); - // mem==NULL; - /* mem=(char*)calloc(fs, det->getDataSize()); */ - /* if (mem) */ - /* memset(mem,0, fs*det->getDataSize()); */ - int i; - for (i=0; igetDataSize(); - // cout << i << endl; - mm=(char*)calloc(1, det->getDataSize()); - - if (mm) { - //memset(mm,0, det->getDataSize()); - fifoFree->push(mm); - } else - break; - } - if (i=0) { - det->setFrameMode((frameMode)fm); - fMode=fm; + busy = 0; + stop = 1; + fMode = eFrame; + ff = NULL; } - return fMode; - }; - virtual double setThreshold(double th) {return det->setThreshold(th);}; + virtual int setFrameMode(int fm) { + if (fm >= 0) { + det->setFrameMode((frameMode)fm); + fMode = fm; + } + return fMode; + }; + virtual double setThreshold(double th) { return det->setThreshold(th); }; + virtual void setROI(int xmin, int xmax, int ymin, int ymax) { + det->setROI(xmin, xmax, ymin, ymax); + }; + virtual int setDetectorMode(int dm) { + if (dm >= 0) { + det->setDetectorMode((detectorMode)dm); + dMode = dm; + } + return dMode; + }; - virtual void setROI(int xmin, int xmax, int ymin, int ymax) {det->setROI(xmin,xmax,ymin,ymax);}; - virtual int setDetectorMode(int dm) { - if (dm>=0) { - det->setDetectorMode((detectorMode)dm); - dMode=dm; + virtual void newDataSet() { det->newDataSet(); }; + // fMode=fm; return fMode;} + + /* void prepareInterpolation(int &ok) { */ + /* cout << "-" << endl; */ + /* det->prepareInterpolation(ok); */ + /* }; */ + + virtual int *getImage() { return det->getImage(); } + virtual int getImageSize(int &nnx, int &nny, int &ns, int &nsy) { + return det->getImageSize(nnx, nny, ns, nsy); + }; + virtual int getDetectorSize(int &nnx, int &nny) { + return det->getDetectorSize(nnx, nny); + }; + + virtual ~threadedAnalogDetector() { + StopThread(); + delete fifoFree; + delete fifoData; } - return dMode; - }; - virtual void newDataSet(){det->newDataSet();}; - //fMode=fm; return fMode;} + /** Returns true if the thread was successfully started, false if there was + * an error starting the thread */ + virtual bool StartThread() { + stop = 0; + cout << "Detector number " << det->getId() << endl; + cout << "common mode is " << det->getCommonModeSubtraction() << endl; + cout << "ghos summation is " << det->getGhostSummation() << endl; + return (pthread_create(&_thread, NULL, processData, this) == 0); + } - /* void prepareInterpolation(int &ok) { */ - /* cout << "-" << endl; */ - /* det->prepareInterpolation(ok); */ - /* }; */ + virtual void StopThread() { + stop = 1; + (void)pthread_join(_thread, NULL); + } - virtual int *getImage() { - return det->getImage(); - } - virtual int getImageSize(int &nnx, int &nny, int &ns, int &nsy) {return det->getImageSize(nnx, nny, ns, nsy);}; - virtual int getDetectorSize(int &nnx, int &nny) {return det->getDetectorSize(nnx, nny);}; + virtual bool pushData(char *&ptr) { return fifoData->push(ptr); } - virtual ~threadedAnalogDetector() {StopThread(); delete fifoFree; delete fifoData;} + virtual bool popFree(char *&ptr) { return fifoFree->pop(ptr); } - /** Returns true if the thread was successfully started, false if there was an error starting the thread */ - virtual bool StartThread() - { stop=0; - cout << "Detector number " << det->getId() << endl; - cout << "common mode is " << det->getCommonModeSubtraction()<< endl; - cout << "ghos summation is " << det->getGhostSummation()<< endl; - return (pthread_create(&_thread, NULL, processData, this) == 0); - } + // virtual int isBusy() {if (fifoData->isEmpty() && busy==0) return 0; + // return 1;} - virtual void StopThread() - { stop=1; - (void) pthread_join(_thread, NULL); - } - + virtual int isBusy() { + if (busy == 0) { + usleep(100); + if (busy == 0) { + if (fifoData->isEmpty()) { + usleep(100); + return 0; + } + } + } + return 1; + } + // protected: + /** Implement this method in your subclass with the code you want your + * thread to run. */ + // virtual void InternalThreadEntry() = 0; + virtual void *writeImage(const char *imgname) { + return det->writeImage(imgname); + }; - virtual bool pushData(char* &ptr) { - return fifoData->push(ptr); - } + virtual void clearImage() { det->clearImage(); }; - virtual bool popFree(char* &ptr) { - return fifoFree->pop(ptr); - } + virtual void setPedestal(double *ped, double *rms = NULL, int m = -1) { + det->setPedestal(ped, rms, m); + }; - // virtual int isBusy() {if (fifoData->isEmpty() && busy==0) return 0; return 1;} - - virtual int isBusy() { - if (busy==0) { - usleep(100); - if (busy==0) { - if (fifoData->isEmpty()) { - usleep(100); - return 0; - } - } - } - return 1; - } - //protected: - /** Implement this method in your subclass with the code you want your thread to run. */ - //virtual void InternalThreadEntry() = 0; - virtual void *writeImage(const char * imgname) {return det->writeImage(imgname);}; + virtual void setPedestalRMS(double *rms) { det->setPedestalRMS(rms); }; - virtual void clearImage(){det->clearImage();}; + virtual double *getPedestal(double *ped = NULL) { + return det->getPedestal(ped); + }; - - virtual void setPedestal(double *ped, double *rms=NULL, int m=-1){det->setPedestal(ped,rms,m);}; - - - virtual void setPedestalRMS(double *rms){ det->setPedestalRMS(rms);}; - - virtual double *getPedestal(double *ped=NULL){return det->getPedestal(ped);}; - - - virtual double *getPedestalRMS(double *rms=NULL){ return det->getPedestalRMS(rms);}; - - - + virtual double *getPedestalRMS(double *rms = NULL) { + return det->getPedestalRMS(rms); + }; -/** sets file pointer where to write the clusters to - \param f file pointer - \returns current file pointer -*/ - FILE *setFilePointer(FILE *f){return det->setFilePointer(f); }; + /** sets file pointer where to write the clusters to + \param f file pointer + \returns current file pointer + */ + FILE *setFilePointer(FILE *f) { return det->setFilePointer(f); }; -/** gets file pointer where to write the clusters to - \returns current file pointer -*/ -FILE *getFilePointer(){return det->getFilePointer();}; + /** gets file pointer where to write the clusters to + \returns current file pointer + */ + FILE *getFilePointer() { return det->getFilePointer(); }; + virtual double setNSigma(double n) { return det->setNSigma(n); }; + virtual void setEnergyRange(double emi, double ema) { + det->setEnergyRange(emi, ema); + }; + virtual void prepareInterpolation(int &ok) { + slsInterpolation *interp = det->getInterpolation(); + if (interp) + interp->prepareInterpolation(ok); + } - virtual double setNSigma(double n) {return det->setNSigma(n);}; - virtual void setEnergyRange(double emi, double ema) {det->setEnergyRange(emi,ema);}; + virtual int *getFlatField() { + slsInterpolation *interp = (det)->getInterpolation(); + if (interp) + return interp->getFlatField(); + else + return NULL; + } + virtual int *setFlatField(int *ff, int nb, double emin, double emax) { + slsInterpolation *interp = (det)->getInterpolation(); + if (interp) + return interp->setFlatField(ff, nb, emin, emax); + else + return NULL; + } - virtual void prepareInterpolation(int &ok){ - slsInterpolation *interp=det->getInterpolation(); - if (interp) - interp->prepareInterpolation(ok); - } + void *writeFlatField(const char *imgname) { + slsInterpolation *interp = (det)->getInterpolation(); + // cout << "interp " << interp << endl; + if (interp) { + cout << imgname << endl; + return interp->writeFlatField(imgname); + } + return NULL; + } - virtual int *getFlatField(){ - slsInterpolation *interp=(det)->getInterpolation(); - if (interp) - return interp->getFlatField(); - else - return NULL; - } - - virtual int *setFlatField(int *ff, int nb, double emin, double emax){ - slsInterpolation *interp=(det)->getInterpolation(); - if (interp) - return interp->setFlatField(ff, nb, emin, emax); - else - return NULL; - } + void *readFlatField(const char *imgname, int nb = -1, double emin = 1, + double emax = 0) { + slsInterpolation *interp = (det)->getInterpolation(); + if (interp) + return interp->readFlatField(imgname, nb, emin, emax); + return NULL; + } - void *writeFlatField(const char * imgname) { - slsInterpolation *interp=(det)->getInterpolation(); - //cout << "interp " << interp << endl; - if (interp) { - cout << imgname << endl; - return interp->writeFlatField(imgname); - } - return NULL; - } + virtual int *getFlatField(int &nb, double emi, double ema) { + slsInterpolation *interp = (det)->getInterpolation(); + int *ff = NULL; + if (interp) { + ff = interp->getFlatField(nb, emi, ema); + } + return ff; + } - void *readFlatField(const char * imgname, int nb=-1, double emin=1, double emax=0){ - slsInterpolation *interp=(det)->getInterpolation(); - if (interp) - return interp->readFlatField(imgname, nb, emin, emax); - return NULL; - } + virtual slsInterpolation *getInterpolation() { + return (det)->getInterpolation(); + } - virtual int *getFlatField(int &nb, double emi, double ema){ - slsInterpolation *interp=(det)->getInterpolation(); - int *ff=NULL; - if (interp) { - ff=interp->getFlatField(nb,emi,ema); - } - return ff; - } - - virtual slsInterpolation *getInterpolation() { - return (det)->getInterpolation(); - } - - virtual void resetFlatField() { - slsInterpolation *interp=(det)->getInterpolation(); - if (interp) interp->resetFlatField();//((interpolatingDetector*)det)->resetFlatField(); - } + virtual void resetFlatField() { + slsInterpolation *interp = (det)->getInterpolation(); + if (interp) + interp + ->resetFlatField(); //((interpolatingDetector*)det)->resetFlatField(); + } + virtual int setNSubPixels(int ns, int nsy) { + slsInterpolation *interp = (det)->getInterpolation(); + if (interp) + interp->setNSubPixels(ns, nsy); + return 1; + }; - virtual int setNSubPixels(int ns, int nsy) { - slsInterpolation *interp=(det)->getInterpolation(); - if (interp) interp->setNSubPixels(ns, nsy); - return 1;}; + virtual slsInterpolation *setInterpolation(slsInterpolation *f) { + return (det)->setInterpolation(f); + }; + protected: + analogDetector *det; + int fMode; + int dMode; + int *dataSize; + pthread_t _thread; + CircularFifo *fifoFree; + CircularFifo *fifoData; + int stop; + int busy; + char *data; + int *ff; - virtual slsInterpolation *setInterpolation(slsInterpolation *f){ - return (det)->setInterpolation(f); - }; -protected: - analogDetector *det; - int fMode; - int dMode; - int *dataSize; - pthread_t _thread; - CircularFifo *fifoFree; - CircularFifo *fifoData; - int stop; - int busy; - char *data; - int *ff; - - static void * processData(void * ptr) { - threadedAnalogDetector *This=((threadedAnalogDetector *)ptr); - return This->processData(); - } - - void * processData() { - // busy=1; - while (!stop) { - if (fifoData->isEmpty()) { - usleep(100); - if (fifoData->isEmpty()) { - busy=0; - } else - busy=1; - } else - busy=1; - - if (busy==1) { - fifoData->pop(data); //blocking! - det->processData(data); - fifoFree->push(data); - //busy=0; - } - } - return NULL; - } - + static void *processData(void *ptr) { + threadedAnalogDetector *This = ((threadedAnalogDetector *)ptr); + return This->processData(); + } + void *processData() { + // busy=1; + while (!stop) { + if (fifoData->isEmpty()) { + usleep(100); + if (fifoData->isEmpty()) { + busy = 0; + } else + busy = 1; + } else + busy = 1; + if (busy == 1) { + fifoData->pop(data); // blocking! + det->processData(data); + fifoFree->push(data); + // busy=0; + } + } + return NULL; + } }; +class multiThreadedAnalogDetector { + public: + multiThreadedAnalogDetector(analogDetector *d, int n, + int fs = 1000) + : stop(0), nThreads(n), ithread(0) { + dd[0] = d; + if (nThreads == 1) + dd[0]->setId(100); + else + dd[0]->setId(0); + for (int i = 1; i < nThreads; i++) { + dd[i] = d->Clone(); + dd[i]->setId(i); + } + for (int i = 0; i < nThreads; i++) { + cout << "**" << i << endl; + dets[i] = new threadedAnalogDetector(dd[i], fs); + } -class multiThreadedAnalogDetector -{ -public: - multiThreadedAnalogDetector(analogDetector *d, int n, int fs=1000) : stop(0), nThreads(n), ithread(0) { - dd[0]=d; - if (nThreads==1) - dd[0]->setId(100); - else - dd[0]->setId(0); - for (int i=1; iClone(); - dd[i]->setId(i); - } - - for (int i=0; isetFrameMode(fm); for (int i=1; isetFrameMode(fm);} return ret;}; - virtual double setThreshold(int fm) { double ret=dets[0]->setThreshold(fm); for (int i=1; isetThreshold(fm); return ret;}; - virtual int setDetectorMode(int dm) { int ret=dets[0]->setDetectorMode(dm);; for (int i=1; isetDetectorMode(dm); return ret;}; - virtual void setROI(int xmin, int xmax, int ymin, int ymax) { for (int i=0; isetROI(xmin, xmax,ymin,ymax);}; - - - virtual void newDataSet(){for (int i=0; inewDataSet();}; - - virtual int *getImage(int &nnx, int &nny, int &ns, int &nsy) { - int *img; - // int nnx, nny, ns; - // int nnx, nny, ns; - int nn=dets[0]->getImageSize(nnx, nny,ns, nsy); - if (image) { - delete [] image; - image=NULL; - } - image=new int[nn]; - //int nn=dets[0]->getImageSize(nnx, nny, ns); - //for (i=0; igetImage(); - for (int i=0; i0) - image[i]=img[i]; - // else - // image[i]=0; - else //if (img[i]>0) - image[i]+=img[i]; - //if (img[i]) cout << "det " << ii << " pix " << i << " val " << img[i] << " " << image[i] << endl; - } - - } - return image; - - } - - - virtual void clearImage() { - - for (int ii=0; iiclearImage(); - } - - } - - virtual void *writeImage(const char * imgname, double t=1) { -/* #ifdef SAVE_ALL */ -/* for (int ii=0; iiwriteImage(tit); */ -/* } */ -/* #endif */ - int nnx, nny, ns, nsy; - getImage(nnx, nny, ns,nsy); - //int nnx, nny, ns; - int nn=dets[0]->getImageSize(nnx, nny, ns, nsy); - float *gm=new float[nn]; - if (gm) { - for (int ix=0; ix0 && ix/nnx<350) cout << ix/nnx << " " << ix%nnx << " " << image[ix]<< " " << gm[ix] << endl; - } - //cout << "image " << nnx << " " << nny << endl; - WriteToTiff(gm,imgname ,nnx, nny); - delete [] gm; - } else cout << "Could not allocate float image " << endl; - return NULL; - } - - - virtual void StartThreads() { - for (int i=0; iStartThread(); - } - - } - - - - virtual void StopThreads() { - for (int i=0; iStopThread(); - + image = NULL; + ff = NULL; + ped = NULL; + cout << "Ithread is " << ithread << endl; } - - virtual int isBusy() { - int ret=0, ret1; - for (int i=0; iisBusy(); - ret|=ret1; - // if (ret1) cout << "thread " << i <<" still busy " << endl; + virtual ~multiThreadedAnalogDetector() { + StopThreads(); + for (int i = 0; i < nThreads; i++) + delete dets[i]; + /* for (int i=1; ipushData(ptr); - } - virtual bool popFree(char* &ptr) { - // cout << ithread << endl; - return dets[ithread]->popFree(ptr); - } - - virtual int nextThread() { - ithread++; - if (ithread==nThreads) ithread=0; - return ithread; - } + virtual int setFrameMode(int fm) { + int ret = dets[0]->setFrameMode(fm); + for (int i = 1; i < nThreads; i++) { + dets[i]->setFrameMode(fm); + } + return ret; + }; + virtual double setThreshold(int fm) { + double ret = dets[0]->setThreshold(fm); + for (int i = 1; i < nThreads; i++) + dets[i]->setThreshold(fm); + return ret; + }; + virtual int setDetectorMode(int dm) { + int ret = dets[0]->setDetectorMode(dm); + ; + for (int i = 1; i < nThreads; i++) + dets[i]->setDetectorMode(dm); + return ret; + }; + virtual void setROI(int xmin, int xmax, int ymin, int ymax) { + for (int i = 0; i < nThreads; i++) + dets[i]->setROI(xmin, xmax, ymin, ymax); + }; + virtual void newDataSet() { + for (int i = 0; i < nThreads; i++) + dets[i]->newDataSet(); + }; - virtual double *getPedestal(){ - int nx, ny; - dets[0]->getDetectorSize(nx,ny); - if (ped) delete [] ped; - ped=new double[nx*ny]; - double *p0=new double[nx*ny]; - - for (int i=0; igetInterpolation(nb,emi,ema); - // cout << i << endl; - p0=dets[i]->getPedestal(p0); - if (p0) { - if (i==0) { + virtual int *getImage(int &nnx, int &nny, int &ns, int &nsy) { + int *img; + // int nnx, nny, ns; + // int nnx, nny, ns; + int nn = dets[0]->getImageSize(nnx, nny, ns, nsy); + if (image) { + delete[] image; + image = NULL; + } + image = new int[nn]; + // int nn=dets[0]->getImageSize(nnx, nny, ns); + // for (i=0; igetDetectorSize(nx,ny); - // if (ped) delete [] ped; - double *rms=new double[nx*ny]; - double *p0=new double[nx*ny]; - - for (int i=0; igetInterpolation(nb,emi,ema); - // cout << i << endl; - p0=dets[i]->getPedestalRMS(p0); - if (p0) { - if (i==0) { - - for (int ib=0; ibgetImage(); + for (int i = 0; i < nn; i++) { + if (ii == 0) + // if (img[i]>0) + image[i] = img[i]; + // else + // image[i]=0; + else // if (img[i]>0) + image[i] += img[i]; + // if (img[i]) cout << "det " << ii << " pix " << i << " val + // " << img[i] << " " << image[i] << endl; + } + } + return image; } - delete [] p0; - - /* for (int ib=0; ib0) */ - /* rms[ib]=sqrt(ped[ib]); */ - /* else */ - /* rms[ib]=0; */ - /* } */ + virtual void clearImage() { - return rms; - }; - - - - - - virtual double *setPedestal(double *h=NULL){ - //int nb=0; - - int nx, ny; - dets[0]->getDetectorSize(nx,ny); - if (h==NULL) h=ped; - for (int i=0; isetPedestal(h); - } - - return NULL; - }; - - - - - virtual void *writePedestal(const char * imgname){ - - int nx, ny; - dets[0]->getDetectorSize(nx,ny); - - getPedestal(); - float *gm=new float[nx*ny]; - if (gm) { - for (int ix=0; ixgetDetectorSize(nx,ny); - - double *rms=getPedestalRMS(); - float *gm=new float[nx*ny]; - if (gm) { - for (int ix=0; ixgetDetectorSize(nx,ny); - uint32_t nnx; - uint32_t nny; - float *gm=ReadFromTiff(imgname, nnx, nny); - if (ped) delete [] ped; - if (nnx>(uint)nx) nx=nnx; - if (nny>(uint)ny) ny=nny; - ped=new double[nx*ny]; - - for (int ix=0; ixclearImage(); + } } - delete [] gm; - - return setPedestal(); - - }; - + virtual void *writeImage(const char *imgname, double t = 1) { + /* #ifdef SAVE_ALL */ + /* for (int ii=0; iiwriteImage(tit); */ + /* } */ + /* #endif */ + int nnx, nny, ns, nsy; + getImage(nnx, nny, ns, nsy); + // int nnx, nny, ns; + int nn = dets[0]->getImageSize(nnx, nny, ns, nsy); + float *gm = new float[nn]; + if (gm) { + for (int ix = 0; ix < nn; ix++) { + if (t) { + if (image[ix] < 0) + gm[ix] = 0; + else + gm[ix] = (image[ix]) / t; + } else + gm[ix] = image[ix]; + // if (image[ix]>0 && ix/nnx<350) cout << ix/nnx << " " << + // ix%nnx << " " << image[ix]<< " " << gm[ix] << endl; + } + // cout << "image " << nnx << " " << nny << endl; + WriteToTiff(gm, imgname, nnx, nny); + delete[] gm; + } else + cout << "Could not allocate float image " << endl; + return NULL; + } + virtual void StartThreads() { + for (int i = 0; i < nThreads; i++) { + dets[i]->StartThread(); + } + } + virtual void StopThreads() { + for (int i = 0; i < nThreads; i++) + dets[i]->StopThread(); + } -/** sets file pointer where to write the clusters to - \param f file pointer - \returns current file pointer -*/ - virtual FILE *setFilePointer(FILE *f){ - for (int i=0; isetFilePointer(f); - //dets[i]->setMutex(&fmutex); - } - return dets[0]->getFilePointer(); - }; + virtual int isBusy() { + int ret = 0, ret1; + for (int i = 0; i < nThreads; i++) { + ret1 = dets[i]->isBusy(); + ret |= ret1; + // if (ret1) cout << "thread " << i <<" still busy " << endl; + } + return ret; + } - /** gets file pointer where to write the clusters to - \returns current file pointer - */ - virtual FILE *getFilePointer(){return dets[0]->getFilePointer();}; + virtual bool pushData(char *&ptr) { return dets[ithread]->pushData(ptr); } + virtual bool popFree(char *&ptr) { + // cout << ithread << endl; + return dets[ithread]->popFree(ptr); + } + virtual int nextThread() { + ithread++; + if (ithread == nThreads) + ithread = 0; + return ithread; + } - protected: - bool stop; - const int nThreads; - threadedAnalogDetector *dets[MAXTHREADS]; - analogDetector *dd[MAXTHREADS]; - int ithread; - int *image; - int *ff; - double *ped; - pthread_mutex_t fmutex; + virtual double *getPedestal() { + int nx, ny; + dets[0]->getDetectorSize(nx, ny); + if (ped) + delete[] ped; + ped = new double[nx * ny]; + double *p0 = new double[nx * ny]; + + for (int i = 0; i < nThreads; i++) { + // inte=(slsInterpolation*)dets[i]->getInterpolation(nb,emi,ema); + // cout << i << endl; + p0 = dets[i]->getPedestal(p0); + if (p0) { + if (i == 0) { + + for (int ib = 0; ib < nx * ny; ib++) { + ped[ib] = p0[ib] / ((double)nThreads); + // cout << p0[ib] << " "; + } + } else { + for (int ib = 0; ib < nx * ny; ib++) { + ped[ib] += p0[ib] / ((double)nThreads); + // cout << p0[ib] << " "; + } + } + } + } + delete[] p0; + return ped; + }; + + virtual double *getPedestalRMS() { + int nx, ny; + dets[0]->getDetectorSize(nx, ny); + // if (ped) delete [] ped; + double *rms = new double[nx * ny]; + double *p0 = new double[nx * ny]; + + for (int i = 0; i < nThreads; i++) { + // inte=(slsInterpolation*)dets[i]->getInterpolation(nb,emi,ema); + // cout << i << endl; + p0 = dets[i]->getPedestalRMS(p0); + if (p0) { + if (i == 0) { + + for (int ib = 0; ib < nx * ny; ib++) { + rms[ib] = p0[ib] * p0[ib] / ((double)nThreads); + // cout << p0[ib] << " "; + } + } else { + for (int ib = 0; ib < nx * ny; ib++) { + rms[ib] += p0[ib] * p0[ib] / ((double)nThreads); + // cout << p0[ib] << " "; + } + } + } + } + delete[] p0; + + /* for (int ib=0; ib0) */ + /* rms[ib]=sqrt(ped[ib]); */ + /* else */ + /* rms[ib]=0; */ + /* } */ + + return rms; + }; + + virtual double *setPedestal(double *h = NULL) { + // int nb=0; + + int nx, ny; + dets[0]->getDetectorSize(nx, ny); + if (h == NULL) + h = ped; + for (int i = 0; i < nThreads; i++) { + dets[i]->setPedestal(h); + } + + return NULL; + }; + + virtual void *writePedestal(const char *imgname) { + + int nx, ny; + dets[0]->getDetectorSize(nx, ny); + + getPedestal(); + float *gm = new float[nx * ny]; + if (gm) { + for (int ix = 0; ix < nx * ny; ix++) { + gm[ix] = ped[ix]; + } + WriteToTiff(gm, imgname, nx, ny); + delete[] gm; + } else + cout << "Could not allocate float image " << endl; + + return NULL; + }; + + virtual void *writePedestalRMS(const char *imgname) { + + int nx, ny; + dets[0]->getDetectorSize(nx, ny); + + double *rms = getPedestalRMS(); + float *gm = new float[nx * ny]; + if (gm) { + for (int ix = 0; ix < nx * ny; ix++) { + gm[ix] = rms[ix]; + } + WriteToTiff(gm, imgname, nx, ny); + delete[] gm; + delete[] rms; + } else + cout << "Could not allocate float image " << endl; + + return NULL; + }; + + virtual void *readPedestal(const char *imgname, int nb = -1, + double emin = 1, double emax = 0) { + + int nx, ny; + dets[0]->getDetectorSize(nx, ny); + uint32_t nnx; + uint32_t nny; + float *gm = ReadFromTiff(imgname, nnx, nny); + if (ped) + delete[] ped; + if (nnx > (uint)nx) + nx = nnx; + if (nny > (uint)ny) + ny = nny; + ped = new double[nx * ny]; + + for (int ix = 0; ix < nx * ny; ix++) { + ped[ix] = gm[ix]; + } + delete[] gm; + + return setPedestal(); + }; + + /** sets file pointer where to write the clusters to + \param f file pointer + \returns current file pointer + */ + virtual FILE *setFilePointer(FILE *f) { + for (int i = 0; i < nThreads; i++) { + dets[i]->setFilePointer(f); + // dets[i]->setMutex(&fmutex); + } + return dets[0]->getFilePointer(); + }; + + /** gets file pointer where to write the clusters to + \returns current file pointer + */ + virtual FILE *getFilePointer() { return dets[0]->getFilePointer(); }; + + protected: + bool stop; + const int nThreads; + threadedAnalogDetector *dets[MAXTHREADS]; + analogDetector *dd[MAXTHREADS]; + int ithread; + int *image; + int *ff; + double *ped; + pthread_mutex_t fmutex; }; #endif - - - - - - - - - - - - - - - - - - diff --git a/slsDetectorCalibration/multiThreadedCountingDetector.h b/slsDetectorCalibration/multiThreadedCountingDetector.h index c2bdc4a87..fb77866b1 100644 --- a/slsDetectorCalibration/multiThreadedCountingDetector.h +++ b/slsDetectorCalibration/multiThreadedCountingDetector.h @@ -3,51 +3,36 @@ #ifndef MULTITHREADED_COUNTING_DETECTOR_H #define MULTITHREADED_COUNTING_DETECTOR_H - -#include "singlePhotonDetector.h" #include "multiThreadedAnalogDetector.h" +#include "singlePhotonDetector.h" //#include - using namespace std; - /* class threadedCountingDetector : public threadedAnalogDetector */ /* { */ /* public: */ -/* threadedCountingDetector(singlePhotonDetector *d, int fs=10000) : threadedAnalogDetector(d,fs) {}; */ - +/* threadedCountingDetector(singlePhotonDetector *d, int fs=10000) : + * threadedAnalogDetector(d,fs) {}; */ /* }; */ - - -class multiThreadedCountingDetector : public multiThreadedAnalogDetector -{ -public: - multiThreadedCountingDetector(singlePhotonDetector *d, int n, int fs=1000) : multiThreadedAnalogDetector(d,n,fs) { }; - //virtual ~multiThreadedCountingDetector{multiThreadedAnalogDetector::~multiThreadedAnalogDetector();}; - virtual double setNSigma(double n) {double ret=(dets[0])->setNSigma(n); for (int i=1; isetNSigma(n); return ret;}; - virtual void setEnergyRange(double emi, double ema) {for (int i=0; isetEnergyRange(emi,ema);}; - +class multiThreadedCountingDetector : public multiThreadedAnalogDetector { + public: + multiThreadedCountingDetector(singlePhotonDetector *d, int n, int fs = 1000) + : multiThreadedAnalogDetector(d, n, fs){}; + // virtual + // ~multiThreadedCountingDetector{multiThreadedAnalogDetector::~multiThreadedAnalogDetector();}; + virtual double setNSigma(double n) { + double ret = (dets[0])->setNSigma(n); + for (int i = 1; i < nThreads; i++) + (dets[i])->setNSigma(n); + return ret; + }; + virtual void setEnergyRange(double emi, double ema) { + for (int i = 0; i < nThreads; i++) + (dets[i])->setEnergyRange(emi, ema); + }; }; #endif - - - - - - - - - - - - - - - - - - diff --git a/slsDetectorCalibration/multiThreadedInterpolatingDetector.h b/slsDetectorCalibration/multiThreadedInterpolatingDetector.h index 344ac9e7f..53994ea9e 100644 --- a/slsDetectorCalibration/multiThreadedInterpolatingDetector.h +++ b/slsDetectorCalibration/multiThreadedInterpolatingDetector.h @@ -3,112 +3,88 @@ #ifndef MULTITHREADED_INTERPOLATING_DETECTOR_H #define MULTITHREADED_INTERPOLATING_DETECTOR_H - #include "interpolatingDetector.h" #include "multiThreadedCountingDetector.h" //#include - using namespace std; - - -class multiThreadedInterpolatingDetector : public multiThreadedCountingDetector -{ -public: - multiThreadedInterpolatingDetector(interpolatingDetector *d, int n, int fs=1000) : multiThreadedCountingDetector(d,n,fs) { }; - //virtual ~multiThreadedInterpolatingDetector() {multiThreadedCountingDetector::~multiThreadedCountingDetector();}; - virtual void prepareInterpolation(int &ok){ - /* getFlatField(); //sum up all etas */ - /* setFlatField(); //set etas to all detectors */ - /* for (int i=0; iprepareInterpolation(ok); - // } - } - - virtual int *getFlatField(){ - return (dets[0])->getFlatField(); - } - - virtual int *getFlatField(int &nb, double emi, double ema){ - return (dets[0])->getFlatField(nb,emi,ema); - } - - virtual int *setFlatField(int *h=NULL, int nb=-1, double emin=1, double emax=0){ - return (dets[0])->setFlatField(h,nb,emin,emax); - }; - - void *writeFlatField(const char * imgname){ - return dets[0]->writeFlatField(imgname); - }; - - - void *readFlatField(const char * imgname, int nb=-1, double emin=1, double emax=0){ - return (dets[0])->readFlatField(imgname, nb, emin, emax); - }; - - - /* virtual int setNSubPixels(int ns) { return (dets[0])->setNSubPixels(ns);}; */ - - virtual void resetFlatField() {(dets[0])->resetFlatField();}; - - -/** sets file pointer where to write the clusters to - \param f file pointer - \returns current file pointer -*/ - virtual slsInterpolation *setInterpolation(slsInterpolation *f){ - //int ok; - for (int i=0; isetInterpolation(f); - return (dets[0])->getInterpolation(); - }; - - virtual slsInterpolation *getInterpolation(){ - - return (dets[0])->getInterpolation(); - }; - - - - virtual int *getImage(int &nnx, int &nny, int &nsx, int &nsy) { - if (getInterpolation()==NULL) return multiThreadedAnalogDetector::getImage(nnx,nny,nsx, nsy); - //if one interpolates, the whole image is stored in detector 0; - int *img; - // int nnx, nny, ns; - // int nnx, nny, ns; - int nn=dets[0]->getImageSize(nnx, nny,nsx, nsy); - if (image) { - delete image; - image=NULL; +class multiThreadedInterpolatingDetector + : public multiThreadedCountingDetector { + public: + multiThreadedInterpolatingDetector(interpolatingDetector *d, int n, + int fs = 1000) + : multiThreadedCountingDetector(d, n, fs){}; + // virtual ~multiThreadedInterpolatingDetector() + // {multiThreadedCountingDetector::~multiThreadedCountingDetector();}; + virtual void prepareInterpolation(int &ok) { + /* getFlatField(); //sum up all etas */ + /* setFlatField(); //set etas to all detectors */ + /* for (int i=0; iprepareInterpolation(ok); + // } } - image=new int[nn]; - img=dets[0]->getImage(); - for (int i=0; igetFlatField(); } + + virtual int *getFlatField(int &nb, double emi, double ema) { + return (dets[0])->getFlatField(nb, emi, ema); } - return image; - }; + virtual int *setFlatField(int *h = NULL, int nb = -1, double emin = 1, + double emax = 0) { + return (dets[0])->setFlatField(h, nb, emin, emax); + }; + void *writeFlatField(const char *imgname) { + return dets[0]->writeFlatField(imgname); + }; + + void *readFlatField(const char *imgname, int nb = -1, double emin = 1, + double emax = 0) { + return (dets[0])->readFlatField(imgname, nb, emin, emax); + }; + + /* virtual int setNSubPixels(int ns) { return + * (dets[0])->setNSubPixels(ns);}; */ + + virtual void resetFlatField() { (dets[0])->resetFlatField(); }; + + /** sets file pointer where to write the clusters to + \param f file pointer + \returns current file pointer + */ + virtual slsInterpolation *setInterpolation(slsInterpolation *f) { + // int ok; + for (int i = 0; i < nThreads; i++) + (dets[i])->setInterpolation(f); + return (dets[0])->getInterpolation(); + }; + + virtual slsInterpolation *getInterpolation() { + + return (dets[0])->getInterpolation(); + }; + + virtual int *getImage(int &nnx, int &nny, int &nsx, int &nsy) { + if (getInterpolation() == NULL) + return multiThreadedAnalogDetector::getImage(nnx, nny, nsx, nsy); + // if one interpolates, the whole image is stored in detector 0; + int *img; + // int nnx, nny, ns; + // int nnx, nny, ns; + int nn = dets[0]->getImageSize(nnx, nny, nsx, nsy); + if (image) { + delete image; + image = NULL; + } + image = new int[nn]; + img = dets[0]->getImage(); + for (int i = 0; i < nn; i++) { + image[i] = img[i]; + } + return image; + }; }; #endif - - - - - - - - - - - - - - - - - - diff --git a/slsDetectorCalibration/pedestalSubtraction.h b/slsDetectorCalibration/pedestalSubtraction.h index 8283d6769..5438f967c 100644 --- a/slsDetectorCalibration/pedestalSubtraction.h +++ b/slsDetectorCalibration/pedestalSubtraction.h @@ -5,61 +5,64 @@ #include "MovingStat.h" -class pedestalSubtraction { - /** @short class defining the pedestal subtraction based on an approximated moving average */ - public: - /** constructor - \param nn number of samples to calculate the moving average (defaults to 1000) - */ - pedestalSubtraction (int nn=1000) : stat(nn) {}; - /* void setPointers(double *me, double *va) {mean=me; var=va; stat.setPointers(mean, var);}; */ - /** virtual destructorr +class pedestalSubtraction { + /** @short class defining the pedestal subtraction based on an approximated + * moving average */ + public: + /** constructor + \param nn number of samples to calculate the moving average (defaults to + 1000) + */ + pedestalSubtraction(int nn = 1000) : stat(nn){}; + /* void setPointers(double *me, double *va) {mean=me; var=va; + * stat.setPointers(mean, var);}; */ + /** virtual destructorr */ - virtual ~pedestalSubtraction() {}; - + virtual ~pedestalSubtraction(){}; + /** clears the moving average */ - virtual void Clear() {stat.Clear();} - - /** adds the element to the moving average - \param val value to be added - */ - virtual void addToPedestal(double val){stat.Calc(val);}; + virtual void Clear() { stat.Clear(); } - /** returns the average value of the pedestal - \returns mean of the moving average + /** adds the element to the moving average + \param val value to be added */ - virtual double getPedestal(){return stat.Mean();}; + virtual void addToPedestal(double val) { stat.Calc(val); }; - /** returns the standard deviation of the moving average - \returns standard deviation of the moving average - */ - virtual double getPedestalRMS(){return stat.StandardDeviation();}; + /** returns the average value of the pedestal + \returns mean of the moving average + */ + virtual double getPedestal() { return stat.Mean(); }; - /**sets/gets the number of samples for the moving average - \param i number of elements for the moving average. If -1 (default) or negative, gets. - \returns actual number of samples for the moving average - */ - virtual int SetNPedestals(int i=-1) {return stat.SetN(i);}; + /** returns the standard deviation of the moving average + \returns standard deviation of the moving average + */ + virtual double getPedestalRMS() { return stat.StandardDeviation(); }; + + /**sets/gets the number of samples for the moving average + \param i number of elements for the moving average. If -1 (default) or + negative, gets. \returns actual number of samples for the moving average + */ + virtual int SetNPedestals(int i = -1) { return stat.SetN(i); }; + + /**sets/gets the number of samples for the moving average + \returns actual number of samples for the moving average + */ + virtual int GetNPedestals() { return stat.GetN(); }; - /**sets/gets the number of samples for the moving average - \returns actual number of samples for the moving average - */ - virtual int GetNPedestals() {return stat.GetN();}; - /** sets the moving average */ - virtual void setPedestal(double val, double rms=0, int m=-1) {stat.Set(val, rms, m);} + virtual void setPedestal(double val, double rms = 0, int m = -1) { + stat.Set(val, rms, m); + } - /** sets the moving average */ - virtual void setPedestalRMS(double rms) {stat.SetRMS(rms);} + virtual void setPedestalRMS(double rms) { stat.SetRMS(rms); } /**sets/gets the number of samples for the moving average \returns actual number of samples for the moving average */ - virtual int getNumpedestals() {return stat.NumDataValues();}; + virtual int getNumpedestals() { return stat.NumDataValues(); }; - private: + private: MovingStat stat; /**< approximated moving average struct */ - }; #endif diff --git a/slsDetectorCalibration/singlePhotonDetector.h b/slsDetectorCalibration/singlePhotonDetector.h index b63d8df85..083e25f7b 100644 --- a/slsDetectorCalibration/singlePhotonDetector.h +++ b/slsDetectorCalibration/singlePhotonDetector.h @@ -3,697 +3,720 @@ #ifndef SINGLEPHOTONDETECTOR_H #define SINGLEPHOTONDETECTOR_H -#include "analogDetector.h" +#include "analogDetector.h" #include "single_photon_hit.h" - - //#define MYROOT1 #ifdef MYROOT1 #include #endif - #ifndef EVTYPE_DEF #define EVTYPE_DEF /** enum to define the even types */ enum eventType { - PEDESTAL=0, /** pedestal */ - NEIGHBOUR=1, /** neighbour i.e. below threshold, but in the cluster of a photon */ - PHOTON=2, /** photon i.e. above threshold */ - PHOTON_MAX=3, /** maximum of a cluster satisfying the photon conditions */ - NEGATIVE_PEDESTAL=4, /** negative value, will not be accounted for as pedestal in order to avoid drift of the pedestal towards negative values */ - UNDEFINED_EVENT=-1 /** undefined */ + PEDESTAL = 0, /** pedestal */ + NEIGHBOUR = + 1, /** neighbour i.e. below threshold, but in the cluster of a photon */ + PHOTON = 2, /** photon i.e. above threshold */ + PHOTON_MAX = 3, /** maximum of a cluster satisfying the photon conditions */ + NEGATIVE_PEDESTAL = + 4, /** negative value, will not be accounted for as pedestal in order to + avoid drift of the pedestal towards negative values */ + UNDEFINED_EVENT = -1 /** undefined */ }; #endif -//template class singlePhotonDetector : -//public analogDetector { -class singlePhotonDetector : -public analogDetector { +// template class singlePhotonDetector : +// public analogDetector { +class singlePhotonDetector : public analogDetector { - /** @short class to perform pedestal subtraction etc. and find single photon clusters for an analog detector */ + /** @short class to perform pedestal subtraction etc. and find single photon + * clusters for an analog detector */ - public: - - - /** - - Constructor (no error checking if datasize and offsets are compatible!) - \param d detector data structure to be used - \param csize cluster size (should be an odd number). Defaults to 3 - \param nsigma number of rms to discriminate from the noise. Defaults to 5 - \param sign 1 if photons are positive, -1 if negative - \param cm common mode subtraction algorithm, if any. Defaults to NULL i.e. none - \param nped number of samples for pedestal averaging - \param nd number of dark frames to average as pedestals without photon discrimination at the beginning of the measurement - - - */ - - singlePhotonDetector(slsDetectorData *d, - int csize=3, - double nsigma=5, - int sign=1, - commonModeSubtraction *cm=NULL, - int nped=1000, - int nd=100, int nnx=-1, int nny=-1, double *gm=NULL, ghostSummation *gs=NULL) : analogDetector(d, sign, cm, nped, nnx, nny, gm, gs), nDark(nd), eventMask(NULL),nSigma (nsigma), eMin(-1), eMax(-1), clusterSize(csize), clusterSizeY(csize), c2(1),c3(1), clusters(NULL), quad(UNDEFINED_QUADRANT), tot(0), quadTot(0) { - - - - - fm=new pthread_mutex_t ; - - eventMask=new eventType*[ny]; - // val=new double*[ny]; - for (int i=0; i(orig) { + singlePhotonDetector(slsDetectorData *d, int csize = 3, + double nsigma = 5, int sign = 1, + commonModeSubtraction *cm = NULL, int nped = 1000, + int nd = 100, int nnx = -1, int nny = -1, + double *gm = NULL, ghostSummation *gs = NULL) + : analogDetector(d, sign, cm, nped, nnx, nny, gm, gs), + nDark(nd), eventMask(NULL), nSigma(nsigma), eMin(-1), eMax(-1), + clusterSize(csize), clusterSizeY(csize), c2(1), c3(1), clusters(NULL), + quad(UNDEFINED_QUADRANT), tot(0), quadTot(0) { - nDark=orig->nDark; - myFile=orig->myFile; - - eventMask=new eventType*[ny]; - // val=new double*[ny]; - for (int i=0; i(orig) { + + nDark = orig->nDark; + myFile = orig->myFile; + + eventMask = new eventType *[ny]; + // val=new double*[ny]; + for (int i = 0; i < ny; i++) { + eventMask[i] = new eventType[nx]; + // val[i]=new double[nx]; + } + eMin = orig->eMin; + eMax = orig->eMax; + + nSigma = orig->nSigma; + clusterSize = orig->clusterSize; + clusterSizeY = orig->clusterSizeY; + // cluster=new single_photon_hit(clusterSize,clusterSizeY); + + c2 = sqrt((clusterSizeY + 1) / 2 * (clusterSize + 1) / 2); + c3 = sqrt(clusterSizeY * clusterSize); + + clusters = new single_photon_hit[nx * ny]; + + // cluster=clusters; + + setClusterSize(clusterSize); + fm = orig->fm; + + quad = UNDEFINED_QUADRANT; + tot = 0; + quadTot = 0; + gmap = orig->gmap; + nphTot = 0; + nphFrame = 0; + nphTot = 0; + nphFrame = 0; } - eMin=orig->eMin; - eMax=orig->eMax; - - - nSigma=orig->nSigma; - clusterSize=orig->clusterSize; - clusterSizeY=orig->clusterSizeY; - // cluster=new single_photon_hit(clusterSize,clusterSizeY); - c2=sqrt((clusterSizeY+1)/2* (clusterSize+1)/2); - c3=sqrt(clusterSizeY*clusterSize); + /** + duplicates the detector structure + \returns new single photon detector with same parameters - clusters=new single_photon_hit[nx*ny]; - - // cluster=clusters; - - setClusterSize(clusterSize); - fm=orig->fm; - - quad=UNDEFINED_QUADRANT; - tot=0; - quadTot=0; - gmap=orig->gmap; - nphTot=0; - nphFrame=0; - nphTot=0; - nphFrame=0; - - } - - - - /** - duplicates the detector structure - \returns new single photon detector with same parameters - - */ - virtual singlePhotonDetector *Clone() { - return new singlePhotonDetector(this); - } + */ + virtual singlePhotonDetector *Clone() { + return new singlePhotonDetector(this); + } /** sets/gets number of rms threshold to detect photons - \param n number of sigma to be set (0 or negative gets) - \returns actual number of sigma parameter + \param n number of sigma to be set (0 or negative gets) + \returns actual number of sigma parameter */ - double setNSigma(double n=-1){if (n>=0) nSigma=n; return nSigma;} - - /** sets/gets cluster size - \param n cluster size to be set, (0 or negative gets). If even is incremented by 1. - \returns actual cluster size - */ - int setClusterSize(int n=-1){ - if (n>0 && n!=clusterSize) { - if (n%2==0) - n+=1; - clusterSize=n; - // if (clusters) - // delete [] clusters; - if (ny>clusterSize) - clusterSizeY=clusterSize; - else - clusterSizeY=1; - for (int ip=0; ipset_cluster_size(clusterSize,clusterSizeY); - //cluster=new single_photon_hit(clusterSize,clusterSizeY); - } - return clusterSize; + double setNSigma(double n = -1) { + if (n >= 0) + nSigma = n; + return nSigma; } - + /** sets/gets cluster size + \param n cluster size to be set, (0 or negative gets). If even is + incremented by 1. \returns actual cluster size + */ + int setClusterSize(int n = -1) { + if (n > 0 && n != clusterSize) { + if (n % 2 == 0) + n += 1; + clusterSize = n; + // if (clusters) + // delete [] clusters; + if (ny > clusterSize) + clusterSizeY = clusterSize; + else + clusterSizeY = 1; + for (int ip = 0; ip < nx * ny; ip++) + (clusters + ip)->set_cluster_size(clusterSize, clusterSizeY); + // cluster=new single_photon_hit(clusterSize,clusterSizeY); + } + return clusterSize; + } /** converts the image into number of photons \param data pointer to data - \param nph pointer where to add the calculated photons. If NULL, the internal image will be used - \returns array with data converted into number of photons. + \param nph pointer where to add the calculated photons. If NULL, the + internal image will be used \returns array with data converted into + number of photons. */ - - virtual int *getNPhotons(char *data, int *nph=NULL) { - // cout << "spc frame" << endl; - nphFrame=0; - double val; - if (nph==NULL) - nph=image; - //nph=new int[nx*ny]; - - //int cy=(clusterSizeY+1)/2; //quad size - //int cs=(clusterSize+1)/2; //quad size - - //int ccs=clusterSize; //cluster size - //int ccy=clusterSizeY; //cluster size - - //double g=1.; - - double tthr=thr, tthr1, tthr2; - int nn=0; - double max=0, tl=0, tr=0, bl=0,br=0, v; - double rms=0; - int cm=0; - if (cmSub) cm=1; + virtual int *getNPhotons(char *data, int *nph = NULL) { + // cout << "spc frame" << endl; + nphFrame = 0; + double val; + if (nph == NULL) + nph = image; + // nph=new int[nx*ny]; - if (thr>0) { - //cy=1; - //cs=1; - //ccs=1; - //ccy=1; - } - if (iframe0) { - double *rest=new double[ny*nx]; - newFrame(data); - if (cmSub) { - cout << "add to common mode?"<< endl; - addToCommonMode(data); - } - for (iy=ymin; iyisGood(ix,iy)) { - val=subtractPedestal(data,ix,iy, cm); - - nn=analogDetector::convertToPhotons(data,ix,iy);//val/thr;// - if (nn>0) { - nph[ix+nx*iy]+=nn; - rest[iy*nx+ix]=(val-nn*thr);//?+0.5*thr - nphFrame+=nn; - nphTot+=nn; - } else - rest[iy*nx+ix]=val; - - } - } - } - - for (iy=ymin; iyisGood(ix,iy)) { - eventMask[iy][ix]=PEDESTAL; - max=0; - tl=0; - tr=0; - bl=0; - br=0; - tot=0; - quadTot=0; - - if (rest[iy*nx+ix]>0.25*thr) { - eventMask[iy][ix]=NEIGHBOUR; - for (int ir=-(clusterSizeY/2); ir<(clusterSizeY/2)+1; ir++) { - for (int ic=-(clusterSize/2); ic<(clusterSize/2)+1; ic++) { - if ((iy+ir)>=0 && (iy+ir)=0 && (ix+ic)set_data(rest[iy+ir][ix+ic], ic, ir); - - - v=rest[(iy+ir)*nx+ix+ic];//clusters->get_data(ic,ir); - tot+=v; - - if (ir<=0 && ic<=0) - bl+=v; - if (ir<=0 && ic>=0) - br+=v; - if (ir>=0 && ic<=0) - tl+=v; - if (ir>=0 && ic>=0) - tr+=v; - - if (v>max) { - max=v; - } - // if (ir==0 && ic==0) { - //} - } - } - - if (rest[iy*nx+ix]>=max) { - if (bl>=br && bl>=tl && bl>=tr) { - quad=BOTTOM_LEFT; - quadTot=bl; - } else if (br>=bl && br>=tl && br>=tr) { - quad=BOTTOM_RIGHT; - quadTot=br; - } else if (tl>=br && tl>=bl && tl>=tr) { - quad=TOP_LEFT; - quadTot=tl; - } else if (tr>=bl && tr>=tl && tr>=br) { - quad=TOP_RIGHT; - quadTot=tr; - } - - if (nSigma==0) { - tthr=thr; - tthr1=thr; - tthr2=thr; - } else { - - rms=getPedestalRMS(ix,iy); - tthr=nSigma*rms; - - tthr1=nSigma*sqrt(clusterSize*clusterSizeY)*rms; - tthr2=nSigma*sqrt((clusterSize+1)/2.*((clusterSizeY+1)/2.))*rms; - - - if (thr>2*tthr) tthr=thr-tthr; - if (thr>2*tthr1) tthr1=tthr-tthr1; - if (thr>2*tthr2) tthr2=tthr-tthr2; - - } - - if (tot>tthr1 || quadTot>tthr2 || max>tthr) { - eventMask[iy][ix]=PHOTON; - nph[ix+nx*iy]++; - rest[iy*nx+ix]-=thr; - nphFrame++; - nphTot++; - - } - } - } - } - } - } - } - delete [] rest; - } else return getClusters(data, nph); - } - return NULL; + // int cy=(clusterSizeY+1)/2; //quad size + // int cs=(clusterSize+1)/2; //quad size + + // int ccs=clusterSize; //cluster size + // int ccy=clusterSizeY; //cluster size + + // double g=1.; + + double tthr = thr, tthr1, tthr2; + int nn = 0; + double max = 0, tl = 0, tr = 0, bl = 0, br = 0, v; + double rms = 0; + int cm = 0; + if (cmSub) + cm = 1; + + if (thr > 0) { + // cy=1; + // cs=1; + // ccs=1; + // ccy=1; + } + if (iframe < nDark) { + // cout << "ped " << iframe << endl; + // this already adds to common mode + addToPedestal(data); + return nph; + } else { + if (thr > 0) { + double *rest = new double[ny * nx]; + newFrame(data); + if (cmSub) { + cout << "add to common mode?" << endl; + addToCommonMode(data); + } + for (iy = ymin; iy < ymax; ++iy) { + for (ix = xmin; ix < xmax; ++ix) { + if (det->isGood(ix, iy)) { + val = subtractPedestal(data, ix, iy, cm); + + nn = analogDetector::convertToPhotons( + data, ix, iy); // val/thr;// + if (nn > 0) { + nph[ix + nx * iy] += nn; + rest[iy * nx + ix] = + (val - nn * thr); //?+0.5*thr + nphFrame += nn; + nphTot += nn; + } else + rest[iy * nx + ix] = val; + } + } + } + + for (iy = ymin; iy < ymax; ++iy) { + for (ix = xmin; ix < xmax; ++ix) { + + if (det->isGood(ix, iy)) { + eventMask[iy][ix] = PEDESTAL; + max = 0; + tl = 0; + tr = 0; + bl = 0; + br = 0; + tot = 0; + quadTot = 0; + + if (rest[iy * nx + ix] > 0.25 * thr) { + eventMask[iy][ix] = NEIGHBOUR; + for (int ir = -(clusterSizeY / 2); + ir < (clusterSizeY / 2) + 1; ir++) { + for (int ic = -(clusterSize / 2); + ic < (clusterSize / 2) + 1; ic++) { + if ((iy + ir) >= 0 && (iy + ir) < ny && + (ix + ic) >= 0 && (ix + ic) < nx) { + // clusters->set_data(rest[iy+ir][ix+ic], + // ic, ir); + + v = rest + [(iy + ir) * nx + ix + + ic]; // clusters->get_data(ic,ir); + tot += v; + + if (ir <= 0 && ic <= 0) + bl += v; + if (ir <= 0 && ic >= 0) + br += v; + if (ir >= 0 && ic <= 0) + tl += v; + if (ir >= 0 && ic >= 0) + tr += v; + + if (v > max) { + max = v; + } + // if (ir==0 && ic==0) { + //} + } + } + + if (rest[iy * nx + ix] >= max) { + if (bl >= br && bl >= tl && bl >= tr) { + quad = BOTTOM_LEFT; + quadTot = bl; + } else if (br >= bl && br >= tl && + br >= tr) { + quad = BOTTOM_RIGHT; + quadTot = br; + } else if (tl >= br && tl >= bl && + tl >= tr) { + quad = TOP_LEFT; + quadTot = tl; + } else if (tr >= bl && tr >= tl && + tr >= br) { + quad = TOP_RIGHT; + quadTot = tr; + } + + if (nSigma == 0) { + tthr = thr; + tthr1 = thr; + tthr2 = thr; + } else { + + rms = getPedestalRMS(ix, iy); + tthr = nSigma * rms; + + tthr1 = nSigma * + sqrt(clusterSize * + clusterSizeY) * + rms; + tthr2 = + nSigma * + sqrt( + (clusterSize + 1) / 2. * + ((clusterSizeY + 1) / 2.)) * + rms; + + if (thr > 2 * tthr) + tthr = thr - tthr; + if (thr > 2 * tthr1) + tthr1 = tthr - tthr1; + if (thr > 2 * tthr2) + tthr2 = tthr - tthr2; + } + + if (tot > tthr1 || quadTot > tthr2 || + max > tthr) { + eventMask[iy][ix] = PHOTON; + nph[ix + nx * iy]++; + rest[iy * nx + ix] -= thr; + nphFrame++; + nphTot++; + } + } + } + } + } + } + } + delete[] rest; + } else + return getClusters(data, nph); + } + return NULL; }; + /** + Loops in the region of interest to find the clusters + \param data pointer to the data structure + \returns number of clusters found + */ + int *getClusters(char *data, int *ph = NULL) { + int nph = 0; + // const int cy=(clusterSizeY+1)/2; + // const int cs=(clusterSize+1)/2; + // int ir, ic; + eventType ee; + double max = 0, tl = 0, tr = 0, bl = 0, br = 0, *v; + int cm = 0; + int good = 1; + int ir, ic; + // double quadTot; + // quadrant quad; + double rms; + // if (cmSub) cm=1; + if (ph == NULL) + ph = image; -/** - Loops in the region of interest to find the clusters - \param data pointer to the data structure - \returns number of clusters found + if (iframe < nDark) { + addToPedestal(data); + return 0; + } + newFrame(data); - */ + if (cmSub) { + addToCommonMode(data); + cm = 1; + } -int *getClusters(char *data, int *ph=NULL) { + double *val = new double[ny * nx]; - - int nph=0; - // const int cy=(clusterSizeY+1)/2; - //const int cs=(clusterSize+1)/2; + for (iy = ymin; iy < ymax; ++iy) { + for (ix = xmin; ix < xmax; ++ix) { + if (det->isGood(ix, iy) == 0) + continue; - //int ir, ic; - eventType ee; - double max=0, tl=0, tr=0, bl=0,br=0, *v; - int cm=0; - int good=1; - int ir, ic; - // double quadTot; - //quadrant quad; - double rms; - //if (cmSub) cm=1; - if (ph==NULL) - ph=image; - - if (iframeisGood(ix,iy)==0) continue; - - max=0; - tl=0; - tr=0; - bl=0; - br=0; - tot=0; - quadTot=0; - quad=UNDEFINED_QUADRANT; - - - - //eventMask[iy][ix] - ee=PEDESTAL; - - - rms=getPedestalRMS(ix,iy); - // cluster=clusters+nph; - - // cout << ix << " " << iy << endl; - for (ir=-(clusterSizeY/2); ir<(clusterSizeY/2)+1; ir++) { - for (ic=-(clusterSize/2); ic<(clusterSize/2)+1; ic++) { - - if ((iy+ir)>=iy && (iy+ir)=ix && (ix+ic)=0) - br+=*v; - if (ir>=0 && ic<=0) - tl+=*v; - if (ir>=0 && ic>=0) - tr+=*v; - if (*v>max) { - max=*v; - } - - } - - - } - } - /* if (ix==50 && iy==50) */ - /* cout << id << " " << ix << " " << iy << " " << det->getValue(data,ix,iy)<< " " << val[iy][ix] << " " << getPedestal(ix,iy) << " " << rms << endl; */ - if (val[iy*nx+ix]<-nSigma*rms){ - ee=NEGATIVE_PEDESTAL; - continue; - } - if (max>nSigma*rms){ - // cout << "ph1 " << max << " " << nSigma*rms << endl; - ee=PHOTON; - if (val[iy*nx+ix]c3*nSigma*rms) { - // cout << "ph3 " << tot << " " << c3*nSigma*rms << endl; - ee=PHOTON; - } + if ((iy + ir) >= iy && (iy + ir) < ny && + (ix + ic) >= ix && (ix + ic) < nx) { + val[(iy + ir) * nx + ix + ic] = + subtractPedestal(data, ix + ic, iy + ir, cm); + v = &(val[(iy + ir) * nx + ix + ic]); + tot += *v; + if (ir <= 0 && ic <= 0) + bl += *v; + if (ir <= 0 && ic >= 0) + br += *v; + if (ir >= 0 && ic <= 0) + tl += *v; + if (ir >= 0 && ic >= 0) + tr += *v; + if (*v > max) { + max = *v; + } + } + } + } + /* if (ix==50 && iy==50) */ + /* cout << id << " " << ix << " " << iy << " " << + * det->getValue(data,ix,iy)<< " " << val[iy][ix] << " " << + * getPedestal(ix,iy) << " " << rms << endl; */ + if (val[iy * nx + ix] < -nSigma * rms) { + ee = NEGATIVE_PEDESTAL; + continue; + } + if (max > nSigma * rms) { + // cout << "ph1 " << max << " " << nSigma*rms << endl; + ee = PHOTON; + if (val[iy * nx + ix] < max) + continue; + } else if (tot > c3 * nSigma * rms) { + // cout << "ph3 " << tot << " " << c3*nSigma*rms << endl; + ee = PHOTON; + } #ifndef WRITE_QUAD - else { + else { #endif - quad=BOTTOM_RIGHT; - quadTot=br; - if (bl>=quadTot) { - quad=BOTTOM_LEFT; - quadTot=bl; - } - if (tl>=quadTot) { - quad=TOP_LEFT; - quadTot=tl; - } - if (tr>=quadTot) { - quad=TOP_RIGHT; - quadTot=tr; - } - - if (quadTot>c2*nSigma*rms) { - // cout << "ph2 " << quadTot << " " << c2*nSigma*rms << endl; - ee=PHOTON; - } - -#ifndef WRITE_QUAD - } -#endif - if (ee==PHOTON && val[iy*nx+ix]==max) { - ee=PHOTON_MAX; - // cout << "**" <tot=tot; - (clusters+nph)->x=ix; - (clusters+nph)->y=iy; - (clusters+nph)->quad=quad; - (clusters+nph)->quadTot=quadTot; - //(clusters+nph)->rms=rms; - // (clusters+nph)->iframe=det->getFrameNumber(data); - // cout << det->getFrameNumber(data) << " " << (clusters+nph)->iframe << endl; - // (clusters+nph)->ped=getPedestal(ix,iy,0); - for (ir=-(clusterSizeY/2); ir<(clusterSizeY/2)+1; ir++) { - for (ic=-(clusterSize/2); ic<(clusterSize/2)+1; ic++) { - if ((iy+ir)>=0 && (iy+ir)=0 && (ix+ic)set_data(val[(iy+ir)*nx+ix+ic],ic,ir); - } - } - good=1; - if (eMin>0 && tot0 && tot>eMax) good=0; - if (good) { - nph++; - image[iy*nx+ix]++; - } - - - } else if (ee==PEDESTAL) { - addToPedestal(data,ix,iy,cm); - } /*else { - eventMask[iy][ix]=PHOTON; - }*/ - //eventMask[iy][ix]=ee; - } -} - - nphFrame=nph; - nphTot+=nph; - //cout << nphFrame << endl; - //cout <getFrameNumber(data) << " " << nphFrame << endl; - writeClusters(det->getFrameNumber(data)); - delete [] val; - return image; - -}; + quad = BOTTOM_RIGHT; + quadTot = br; + if (bl >= quadTot) { + quad = BOTTOM_LEFT; + quadTot = bl; + } + if (tl >= quadTot) { + quad = TOP_LEFT; + quadTot = tl; + } + if (tr >= quadTot) { + quad = TOP_RIGHT; + quadTot = tr; + } + if (quadTot > c2 * nSigma * rms) { + // cout << "ph2 " << quadTot << " " << c2*nSigma*rms + // << endl; + ee = PHOTON; + } + +#ifndef WRITE_QUAD + } +#endif + if (ee == PHOTON && val[iy * nx + ix] == max) { + ee = PHOTON_MAX; + // cout << "**" <tot = tot; + (clusters + nph)->x = ix; + (clusters + nph)->y = iy; + (clusters + nph)->quad = quad; + (clusters + nph)->quadTot = quadTot; + //(clusters+nph)->rms=rms; + // (clusters+nph)->iframe=det->getFrameNumber(data); + // cout << det->getFrameNumber(data) << " " << + // (clusters+nph)->iframe << endl; + // (clusters+nph)->ped=getPedestal(ix,iy,0); + for (ir = -(clusterSizeY / 2); ir < (clusterSizeY / 2) + 1; + ir++) { + for (ic = -(clusterSize / 2); + ic < (clusterSize / 2) + 1; ic++) { + if ((iy + ir) >= 0 && (iy + ir) < ny && + (ix + ic) >= 0 && (ix + ic) < nx) + (clusters + nph) + ->set_data(val[(iy + ir) * nx + ix + ic], + ic, ir); + } + } + good = 1; + if (eMin > 0 && tot < eMin) + good = 0; + if (eMax > 0 && tot > eMax) + good = 0; + if (good) { + nph++; + image[iy * nx + ix]++; + } + + } else if (ee == PEDESTAL) { + addToPedestal(data, ix, iy, cm); + } /*else { + eventMask[iy][ix]=PHOTON; + }*/ + // eventMask[iy][ix]=ee; + } + } + + nphFrame = nph; + nphTot += nph; + // cout << nphFrame << endl; + // cout <getFrameNumber(data) << " " << nphFrame << endl; + writeClusters(det->getFrameNumber(data)); + delete[] val; + return image; + }; /**< returns the total signal in a cluster \param size cluser size should be 1,2 or 3 - \returns cluster center if size=1, sum of the maximum quadrant if size=2, total of the cluster if size=3 or anything else + \returns cluster center if size=1, sum of the maximum quadrant if size=2, + total of the cluster if size=3 or anything else */ double getClusterTotal(int size) { - switch (size) { - case 1: - return getClusterElement(0,0); - case 2: - return quadTot; - default: - return tot; - }; + switch (size) { + case 1: + return getClusterElement(0, 0); + case 2: + return quadTot; + default: + return tot; + }; }; - /**< - retrurns the quadrant with maximum signal - \returns quadrant where the cluster is located */ + /**< + retrurns the quadrant with maximum signal + \returns quadrant where the cluster is located */ - quadrant getQuadrant() {return quad;}; + quadrant getQuadrant() { return quad; }; - /** returns value for cluster element in relative coordinates - \param ic x coordinate (center is (0,0)) - \param ir y coordinate (center is (0,0)) - \returns cluster element + \param ic x coordinate (center is (0,0)) + \param ir y coordinate (center is (0,0)) + \returns cluster element */ - double getClusterElement(int ic, int ir=0){return clusters->get_data(ic,ir);}; + double getClusterElement(int ic, int ir = 0) { + return clusters->get_data(ic, ir); + }; /** returns event mask for the given pixel - \param ic x coordinate (center is (0,0)) - \param ir y coordinate (center is (0,0)) - \returns event mask enum for the given pixel + \param ic x coordinate (center is (0,0)) + \param ir y coordinate (center is (0,0)) + \returns event mask enum for the given pixel */ - eventType getEventMask(int ic, int ir=0){return eventMask[ir][ic];}; - + eventType getEventMask(int ic, int ir = 0) { return eventMask[ir][ic]; }; #ifdef MYROOT1 /** generates a tree and maps the branches - \param tname name for the tree - \param iFrame pointer to the frame number - \returns returns pointer to the TTree + \param tname name for the tree + \param iFrame pointer to the frame number + \returns returns pointer to the TTree */ - TTree *initEventTree(char *tname, int *iFrame=NULL) { - TTree* tall=new TTree(tname,tname); + TTree *initEventTree(char *tname, int *iFrame = NULL) { + TTree *tall = new TTree(tname, tname); - if (iFrame) - tall->Branch("iFrame",iFrame,"iframe/I"); - else - tall->Branch("iFrame",&(clusters->iframe),"iframe/I"); + if (iFrame) + tall->Branch("iFrame", iFrame, "iframe/I"); + else + tall->Branch("iFrame", &(clusters->iframe), "iframe/I"); - tall->Branch("x",&(clusters->x),"x/I"); - tall->Branch("y",&(clusters->y),"y/I"); - char tit[100]; - sprintf(tit,"data[%d]/D",clusterSize*clusterSizeY); - tall->Branch("data",clusters->data,tit); - tall->Branch("pedestal",&(clusters->ped),"pedestal/D"); - tall->Branch("rms",&(clusters->rms),"rms/D"); - tall->Branch("tot",&(clusters->tot),"tot/D"); - tall->Branch("quadTot",&(clusters->quadTot),"quadTot/D"); - tall->Branch("quad",&(clusters->quad),"quad/I"); - return tall; + tall->Branch("x", &(clusters->x), "x/I"); + tall->Branch("y", &(clusters->y), "y/I"); + char tit[100]; + sprintf(tit, "data[%d]/D", clusterSize * clusterSizeY); + tall->Branch("data", clusters->data, tit); + tall->Branch("pedestal", &(clusters->ped), "pedestal/D"); + tall->Branch("rms", &(clusters->rms), "rms/D"); + tall->Branch("tot", &(clusters->tot), "tot/D"); + tall->Branch("quadTot", &(clusters->quadTot), "quadTot/D"); + tall->Branch("quad", &(clusters->quad), "quad/I"); + return tall; }; #else -/** write cluster to filer - \param f file pointer -*/ - void writeCluster(FILE* f){clusters->write(f);}; + /** write cluster to filer + \param f file pointer + */ + void writeCluster(FILE *f) { clusters->write(f); }; -/** - write clusters to file - \param f file pointer - \param clusters array of clusters structures - \param nph number of clusters to be written to file + /** + write clusters to file + \param f file pointer + \param clusters array of clusters structures + \param nph number of clusters to be written to file -*/ + */ - static void writeClusters(FILE *f, single_photon_hit *cl, int nph, int fn=0){ - if (f) { - if (nph>0) { -#ifndef OLDFORMAT - if (fwrite((void*)&fn, 1, sizeof(int), f)) - if (fwrite((void*)&nph, 1, sizeof(int), f)) -#endif - for (int i=0; iwrite(f); - } - } + static void writeClusters(FILE *f, single_photon_hit *cl, int nph, + int fn = 0) { + if (f) { + if (nph > 0) { +#ifndef OLDFORMAT + if (fwrite((void *)&fn, 1, sizeof(int), f)) + if (fwrite((void *)&nph, 1, sizeof(int), f)) +#endif + for (int i = 0; i < nph; i++) + (cl + i)->write(f); + } + } }; - - - - - - void writeClusters(FILE *f, int fn=0){ - writeClusters(f,clusters,nphFrame, fn); - //for (int i=0; iwrite(f); -}; - void writeClusters(int fn){ - if (myFile) { - //cout << "++" << endl; - pthread_mutex_lock(fm); - // cout <<"**********************************"<< fn << " " << nphFrame << endl; - writeClusters(myFile,clusters,nphFrame, fn); - // for (int i=0; iwrite(myFile); - pthread_mutex_unlock(fm); - //cout << "--" << endl; - } - }; + void writeClusters(FILE *f, int fn = 0) { + writeClusters(f, clusters, nphFrame, fn); + // for (int i=0; iwrite(f); + }; + void writeClusters(int fn) { + if (myFile) { + // cout << "++" << endl; + pthread_mutex_lock(fm); + // cout <<"**********************************"<< fn << " " << + // nphFrame << endl; + writeClusters(myFile, clusters, nphFrame, fn); + // for (int i=0; iwrite(myFile); + pthread_mutex_unlock(fm); + // cout << "--" << endl; + } + }; #endif - virtual void processData(char *data, int *val=NULL) { - // cout << "sp" << endl; - switch(fMode) { - case ePedestal: - //cout <<"spc add to ped " << endl; - addToPedestal(data,1); - break; - default: - switch (dMode) { - case eAnalog: - analogDetector::processData(data,val); - break; - default: - //cout <<"spc " << endl; - getNPhotons(data,val); - } - } - iframe++; - // cout << "done" << endl; + virtual void processData(char *data, int *val = NULL) { + // cout << "sp" << endl; + switch (fMode) { + case ePedestal: + // cout <<"spc add to ped " << endl; + addToPedestal(data, 1); + break; + default: + switch (dMode) { + case eAnalog: + analogDetector::processData(data, val); + break; + default: + // cout <<"spc " << endl; + getNPhotons(data, val); + } + } + iframe++; + // cout << "done" << endl; }; - int getPhFrame(){return nphFrame;}; - int getPhTot(){return nphTot;}; + int getPhFrame() { return nphFrame; }; + int getPhTot() { return nphTot; }; - void setEnergyRange(double emi, double ema){eMin=emi; eMax=ema;}; - void getEnergyRange(double &emi, double &ema){emi=eMin; ema=eMax;}; + void setEnergyRange(double emi, double ema) { + eMin = emi; + eMax = ema; + }; + void getEnergyRange(double &emi, double &ema) { + emi = eMin; + ema = eMax; + }; - void setMutex(pthread_mutex_t *m){fm=m;}; + void setMutex(pthread_mutex_t *m) { fm = m; }; - protected: - - int nDark; /**< number of frames to be used at the beginning of the dataset to calculate pedestal without applying photon discrimination */ + protected: + int nDark; /**< number of frames to be used at the beginning of the dataset + to calculate pedestal without applying photon discrimination + */ eventType **eventMask; /**< matrix of event type or each pixel */ double nSigma; /**< number of sigma parameter for photon discrimination */ double eMin, eMax; - int clusterSize; /**< cluster size in the x direction */ - int clusterSizeY; /**< cluster size in the y direction i.e. 1 for strips, clusterSize for pixels */ + int clusterSize; /**< cluster size in the x direction */ + int clusterSizeY; /**< cluster size in the y direction i.e. 1 for strips, + clusterSize for pixels */ double c2, c3; // single_photon_hit *cluster; /**< single photon hit data structure */ single_photon_hit *clusters; /**< single photon hit data structure */ - quadrant quad; /**< quadrant where the photon is located */ - double tot; /**< sum of the 3x3 cluster */ - double quadTot; /**< sum of the maximum 2x2cluster */ + quadrant quad; /**< quadrant where the photon is located */ + double tot; /**< sum of the 3x3 cluster */ + double quadTot; /**< sum of the maximum 2x2cluster */ int nphTot; int nphFrame; // double **val; pthread_mutex_t *fm; - - }; - - - - +}; #endif diff --git a/slsDetectorCalibration/single_photon_hit.h b/slsDetectorCalibration/single_photon_hit.h index 74da45dbe..919f6af4b 100644 --- a/slsDetectorCalibration/single_photon_hit.h +++ b/slsDetectorCalibration/single_photon_hit.h @@ -2,261 +2,279 @@ // Copyright (C) 2021 Contributors to the SLS Detector Package #ifndef SINGLE_PHOTON_HIT_H #define SINGLE_PHOTON_HIT_H -#include #include +#include -typedef double double32_t; -typedef float float32_t; -typedef int int32_t; +typedef double double32_t; +typedef float float32_t; +typedef int int32_t; #ifndef DEF_QUAD #define DEF_QUAD - enum quadrant { - TOP_LEFT=0, - TOP_RIGHT=1, - BOTTOM_LEFT=2, - BOTTOM_RIGHT=3, - UNDEFINED_QUADRANT=-1 - }; +enum quadrant { + TOP_LEFT = 0, + TOP_RIGHT = 1, + BOTTOM_LEFT = 2, + BOTTOM_RIGHT = 3, + UNDEFINED_QUADRANT = -1 +}; #endif - class single_photon_hit { - /** @short Structure for a single photon hit */ + /** @short Structure for a single photon hit */ - public: - /** constructor, instantiates the data array -- all class elements are public! - \param nx cluster size in x direction - \param ny cluster size in y direction (defaults to 1 for 1D detectors) - */ - single_photon_hit(int nx=3, int ny=3): dx(nx), dy(ny) {data=new int[dx*dy];}; + public: + /** constructor, instantiates the data array -- all class elements are + public! \param nx cluster size in x direction \param ny cluster size in y + direction (defaults to 1 for 1D detectors) + */ + single_photon_hit(int nx = 3, int ny = 3) : dx(nx), dy(ny) { + data = new int[dx * dy]; + }; - ~single_photon_hit(){delete [] data;}; /**< destructor, deletes the data array */ + ~single_photon_hit() { + delete[] data; + }; /**< destructor, deletes the data array */ - /** binary write to file of all elements of the structure, except size of the cluster - \param myFile file descriptor - */ - size_t write(FILE *myFile) { - //fwrite((void*)this, 1, 3*sizeof(int)+4*sizeof(double)+sizeof(quad), myFile); // if (fwrite((void*)this, 1, sizeof(int)+2*sizeof(int16_t), myFile)) -#ifdef OLDFORMAT - if (fwrite((void*)&iframe, 1, sizeof(int), myFile)) {}; -#endif -#ifndef WRITE_QUAD - //printf("no quad "); - if (fwrite((void*)&x, sizeof(int16_t), 2, myFile)) - return fwrite((void*)data, sizeof(int), dx*dy, myFile); -#endif -#ifdef WRITE_QUAD - // printf("quad "); - int qq[4]; - switch(quad) { - case TOP_LEFT: - qq[0]=data[3]; - qq[1]=data[4]; - qq[2]=data[6]; - qq[3]=data[7]; - x=x-1; - y=y; - break; - - case TOP_RIGHT: - qq[0]=data[4]; - qq[1]=data[5]; - qq[2]=data[7]; - qq[3]=data[8]; - x=x; - y=y; - break; - - - case BOTTOM_LEFT: - qq[0]=data[0]; - qq[1]=data[1]; - qq[2]=data[3]; - qq[3]=data[4]; - x=x-1; - y=y-1; - break; - case BOTTOM_RIGHT: - qq[0]=data[1]; - qq[1]=data[2]; - qq[2]=data[4]; - qq[3]=data[5]; - x=x; - y=y-1; - break; - - - default: - ; - } - if (fwrite((void*)&x, sizeof(int16_t), 2, myFile)) - return fwrite((void*)qq, sizeof(int), 4, myFile); + /** binary write to file of all elements of the structure, except size of + the cluster \param myFile file descriptor + */ + size_t write(FILE *myFile) { + // fwrite((void*)this, 1, 3*sizeof(int)+4*sizeof(double)+sizeof(quad), + // myFile); // if (fwrite((void*)this, 1, + // sizeof(int)+2*sizeof(int16_t), myFile)) +#ifdef OLDFORMAT + if (fwrite((void *)&iframe, 1, sizeof(int), myFile)) { + }; #endif - return 0; - }; - - /** - binary read from file of all elements of the structure, except size of the cluster. The structure is then filled with those args - \param myFile file descriptor - */ - size_t read(FILE *myFile) { - //fread((void*)this, 1, 3*sizeof(int)+4*sizeof(double)+sizeof(quad), myFile); - -#ifdef OLDFORMAT - if (fread((void*)&iframe, 1, sizeof(int), myFile)) {} -#endif #ifndef WRITE_QUAD - // printf( "no quad \n"); - if (fread((void*)&x, sizeof(int16_t),2, myFile)) - return fread((void*)data, sizeof(int), dx*dy,myFile); -#endif + // printf("no quad "); + if (fwrite((void *)&x, sizeof(int16_t), 2, myFile)) + return fwrite((void *)data, sizeof(int), dx * dy, myFile); +#endif #ifdef WRITE_QUAD - int qq[4]; - printf( "quad \n"); - if (fread((void*)&x, sizeof(int16_t), 2, myFile)) - if (fread((void*)qq, sizeof(int), 4, myFile)) { + // printf("quad "); + int qq[4]; + switch (quad) { + case TOP_LEFT: + qq[0] = data[3]; + qq[1] = data[4]; + qq[2] = data[6]; + qq[3] = data[7]; + x = x - 1; + y = y; + break; - quad=TOP_RIGHT; - /* int mm=qq[0]; */ - /* for (int i=1; i<4; i++) { */ - /* if (qq[i]>mm) { */ - /* switch (i) { */ - /* case 1: */ - /* quad=TOP_LEFT; */ - /* break; */ - /* case 2: */ - /* quad=BOTTOM_RIGHT; */ - /* break; */ - /* case 3: */ - /* quad=BOTTOM_LEFT; */ - /* break; */ - /* default: */ - /* ; */ - /* } */ + case TOP_RIGHT: + qq[0] = data[4]; + qq[1] = data[5]; + qq[2] = data[7]; + qq[3] = data[8]; + x = x; + y = y; + break; - /* } */ + case BOTTOM_LEFT: + qq[0] = data[0]; + qq[1] = data[1]; + qq[2] = data[3]; + qq[3] = data[4]; + x = x - 1; + y = y - 1; + break; + case BOTTOM_RIGHT: + qq[0] = data[1]; + qq[1] = data[2]; + qq[2] = data[4]; + qq[3] = data[5]; + x = x; + y = y - 1; + break; - /* } */ + default:; + } + if (fwrite((void *)&x, sizeof(int16_t), 2, myFile)) + return fwrite((void *)qq, sizeof(int), 4, myFile); +#endif + return 0; + }; + /** + binary read from file of all elements of the structure, except size of + the cluster. The structure is then filled with those args \param myFile + file descriptor + */ + size_t read(FILE *myFile) { + // fread((void*)this, 1, 3*sizeof(int)+4*sizeof(double)+sizeof(quad), + // myFile); - /* switch(quad) { */ - /* case TOP_LEFT: */ - /* data[0]=0; */ - /* data[1]=0; */ - /* data[2]=0; */ - /* data[3]=qq[0]; */ - /* data[4]=qq[1]; */ - /* data[5]=0; */ - /* data[6]=qq[2]; */ - /* data[7]=qq[3]; */ - /* data[8]=0; */ - /* x=x+1; */ - /* y=y; */ - /* break; */ - - /* case TOP_RIGHT: */ - data[0]=0; - data[1]=0; - data[2]=0; - data[3]=0; - data[4]=qq[0]; - data[5]=qq[1]; - data[6]=0; - data[7]=qq[2]; - data[8]=qq[3]; - x=x; - y=y; - /* break; */ +#ifdef OLDFORMAT + if (fread((void *)&iframe, 1, sizeof(int), myFile)) { + } +#endif +#ifndef WRITE_QUAD + // printf( "no quad \n"); + if (fread((void *)&x, sizeof(int16_t), 2, myFile)) + return fread((void *)data, sizeof(int), dx * dy, myFile); +#endif +#ifdef WRITE_QUAD + int qq[4]; + printf("quad \n"); + if (fread((void *)&x, sizeof(int16_t), 2, myFile)) + if (fread((void *)qq, sizeof(int), 4, myFile)) { + quad = TOP_RIGHT; + /* int mm=qq[0]; */ + /* for (int i=1; i<4; i++) { */ + /* if (qq[i]>mm) { */ + /* switch (i) { */ + /* case 1: */ + /* quad=TOP_LEFT; */ + /* break; */ + /* case 2: */ + /* quad=BOTTOM_RIGHT; */ + /* break; */ + /* case 3: */ + /* quad=BOTTOM_LEFT; */ + /* break; */ + /* default: */ + /* ; */ + /* } */ - /* case BOTTOM_LEFT: */ - /* data[0]=qq[0]; */ - /* data[1]=qq[1]; */ - /* data[2]=0; */ - /* data[3]=qq[2]; */ - /* data[4]=qq[3]; */ - /* data[5]=0; */ - /* data[6]=0; */ - /* data[7]=0; */ - /* data[8]=0; */ - /* x=x+1; */ - /* y=y+1; */ - /* break; */ - /* case BOTTOM_RIGHT: */ - /* data[0]=0; */ - /* data[1]=qq[0]; */ - /* data[2]=qq[1]; */ - /* data[3]=0; */ - /* data[4]=qq[2]; */ - /* data[5]=qq[3]; */ - /* data[6]=0; */ - /* data[7]=0; */ - /* data[8]=0; */ - /* x=x; */ - /* y=y+1; */ - /* break; */ + /* } */ + /* } */ - /* default: */ - /* ; */ - /* } */ - return 1; - } + /* switch(quad) { */ + /* case TOP_LEFT: */ + /* data[0]=0; */ + /* data[1]=0; */ + /* data[2]=0; */ + /* data[3]=qq[0]; */ + /* data[4]=qq[1]; */ + /* data[5]=0; */ + /* data[6]=qq[2]; */ + /* data[7]=qq[3]; */ + /* data[8]=0; */ + /* x=x+1; */ + /* y=y; */ + /* break; */ + + /* case TOP_RIGHT: */ + data[0] = 0; + data[1] = 0; + data[2] = 0; + data[3] = 0; + data[4] = qq[0]; + data[5] = qq[1]; + data[6] = 0; + data[7] = qq[2]; + data[8] = qq[3]; + x = x; + y = y; + /* break; */ + + /* case BOTTOM_LEFT: */ + /* data[0]=qq[0]; */ + /* data[1]=qq[1]; */ + /* data[2]=0; */ + /* data[3]=qq[2]; */ + /* data[4]=qq[3]; */ + /* data[5]=0; */ + /* data[6]=0; */ + /* data[7]=0; */ + /* data[8]=0; */ + /* x=x+1; */ + /* y=y+1; */ + /* break; */ + /* case BOTTOM_RIGHT: */ + /* data[0]=0; */ + /* data[1]=qq[0]; */ + /* data[2]=qq[1]; */ + /* data[3]=0; */ + /* data[4]=qq[2]; */ + /* data[5]=qq[3]; */ + /* data[6]=0; */ + /* data[7]=0; */ + /* data[8]=0; */ + /* x=x; */ + /* y=y+1; */ + /* break; */ + + /* default: */ + /* ; */ + /* } */ + return 1; + } #endif - return 0; - }; + return 0; + }; - void print() { + void print() { - // int ix, iy; - - for (int iy=0; iy0) dx=nx; if (ny>0) dy=ny; delete [] data; data=new int[dx*dy];}; - void get_cluster_size(int &nx, int &ny) {nx=dx; ny=dy;}; - void get_pixel(int &x1, int &y1) {x1=x; y1=y;}; + void set_cluster_size(int nx, int ny) { + if (nx > 0) + dx = nx; + if (ny > 0) + dy = ny; + delete[] data; + data = new int[dx * dy]; + }; + void get_cluster_size(int &nx, int &ny) { + nx = dx; + ny = dy; + }; + void get_pixel(int &x1, int &y1) { + x1 = x; + y1 = y; + }; - /** - gets the value to the element of the cluster matrix, with relative coordinates where the center of the cluster is (0,0) - \param ix coordinate x within the cluster (center is (0,0)) - \param iy coordinate y within the cluster (center is (0,0)) - \returns value of the cluster element + /** + gets the value to the element of the cluster matrix, with relative + coordinates where the center of the cluster is (0,0) \param ix coordinate + x within the cluster (center is (0,0)) \param iy coordinate y within the + cluster (center is (0,0)) \returns value of the cluster element */ - double get_data(int ix, int iy=0){return data[(iy+dy/2)*dx+ix+dx/2];}; - int *get_cluster() {return data;}; + double get_data(int ix, int iy = 0) { + return data[(iy + dy / 2) * dx + ix + dx / 2]; + }; + int *get_cluster() { return data; }; - int iframe; /**< frame number */ - double rms; /**< noise of central pixel l -- at some point it can be removed*/ - double ped; /**< pedestal of the central pixel -- at some point it can be removed*/ - double tot; /**< sum of the 3x3 cluster */ - quadrant quad; /**< quadrant where the photon is located */ - double quadTot; /**< sum of the maximum 2x2cluster */ - int dx; /**< size of data cluster in x */ - int dy; /**< size of data cluster in y */ - int16_t x; /**< x-coordinate of the center of hit */ - int16_t y; /**< x-coordinate of the center of hit */ - int *data; /**< pointer to data */ + int iframe; /**< frame number */ + double + rms; /**< noise of central pixel l -- at some point it can be removed*/ + double ped; /**< pedestal of the central pixel -- at some point it can be + removed*/ + double tot; /**< sum of the 3x3 cluster */ + quadrant quad; /**< quadrant where the photon is located */ + double quadTot; /**< sum of the maximum 2x2cluster */ + int dx; /**< size of data cluster in x */ + int dy; /**< size of data cluster in y */ + int16_t x; /**< x-coordinate of the center of hit */ + int16_t y; /**< x-coordinate of the center of hit */ + int *data; /**< pointer to data */ }; - - #endif diff --git a/slsDetectorCalibration/tiffIO.cpp b/slsDetectorCalibration/tiffIO.cpp index a60978eee..06be4d1f5 100644 --- a/slsDetectorCalibration/tiffIO.cpp +++ b/slsDetectorCalibration/tiffIO.cpp @@ -3,77 +3,78 @@ #ifndef MY_TIFF_IO_H #include "tiffIO.h" #endif -#include +#include using namespace std; -// #undef cbf_failnez -// #define cbf_failnez(x) -// { -// int err; -// err = (x); -// if (err) { -// fprintf(stderr,"\nCBFlib fatal error %x \n",err); -// exit(-1); -// } +// #undef cbf_failnez +// #define cbf_failnez(x) +// { +// int err; +// err = (x); +// if (err) { +// fprintf(stderr,"\nCBFlib fatal error %x \n",err); +// exit(-1); +// } // } -void *WriteToTiff(float * imgData, const char * imgname, int nrow, int ncol){ - int sampleperpixel=1; - // unsigned char * buff=NULL; - //tsize_t linebytes; - // cout << "--" < -#include -#include +#include #include -#include +#include #include -#include - +#include +#include /*****************************************************************************/ // -//CBFlib must be installed to use this program +// CBFlib must be installed to use this program // /*****************************************************************************/ #include -#undef cbf_failnez -#define cbf_failnez(x) \ - { \ - int err; \ - err = (x); \ - if (err) { \ - fprintf(stderr,"\nCBFlib fatal error %x \n",err); \ - exit(-1); \ - } \ - } +#undef cbf_failnez +#define cbf_failnez(x) \ + { \ + int err; \ + err = (x); \ + if (err) { \ + fprintf(stderr, "\nCBFlib fatal error %x \n", err); \ + exit(-1); \ + } \ + } -void *WriteToTiff(float * imgData, const char * imgname, int nrow, int ncol); +void *WriteToTiff(float *imgData, const char *imgname, int nrow, int ncol); -float *ReadFromTiff( const char * imgname, uint32_t &nrow, uint32_t &ncol); +float *ReadFromTiff(const char *imgname, uint32_t &nrow, uint32_t &ncol); #endif diff --git a/slsReceiverSoftware/src/Listener.h b/slsReceiverSoftware/src/Listener.h index 18dbf3ef5..87c8dfb72 100644 --- a/slsReceiverSoftware/src/Listener.h +++ b/slsReceiverSoftware/src/Listener.h @@ -63,7 +63,8 @@ class Listener : private virtual slsDetectorDefs, public ThreadObject { */ uint64_t GetLastFrameIndexCaught() const; - /** Get number of missing packets, returns negative values in case to extra packet */ + /** Get number of missing packets, returns negative values in case to extra + * packet */ int64_t GetNumMissingPacket(bool stoppedFlag, uint64_t numPackets) const; /** diff --git a/slsSupportLib/include/sls/file_utils.h b/slsSupportLib/include/sls/file_utils.h index 0959154d8..6c9f3f1a3 100644 --- a/slsSupportLib/include/sls/file_utils.h +++ b/slsSupportLib/include/sls/file_utils.h @@ -10,7 +10,6 @@ namespace sls { - /** * @param data array of data values * @param nch number of channels @@ -25,7 +24,6 @@ int readDataFile(std::ifstream &infile, short int *data, int nch, */ int readDataFile(std::string fname, short int *data, int nch); - std::vector readBinaryFile(const std::string &fname, const std::string &errorPrefix); @@ -47,7 +45,7 @@ int writeDataFile(std::string fname, int nch, short int *data); void mkdir_p(const std::string &path, std::string dir = ""); int getFileSize(std::ifstream &ifs); -ssize_t getFileSize(FILE* fd, const std::string &prependErrorString); +ssize_t getFileSize(FILE *fd, const std::string &prependErrorString); std::string getFileNameFromFilePath(const std::string &fpath); -} +} // namespace sls diff --git a/slsSupportLib/include/sls/versionAPI.h b/slsSupportLib/include/sls/versionAPI.h index 37bee4ec7..518f5b2c9 100644 --- a/slsSupportLib/include/sls/versionAPI.h +++ b/slsSupportLib/include/sls/versionAPI.h @@ -3,13 +3,13 @@ /** API versions */ #define GITBRANCH "developer" -#define APILIB 0x211125 -#define APIRECEIVER 0x211124 -#define APIGUI 0x211124 -#define APICTB 0x220118 -#define APIGOTTHARD 0x220118 +#define APILIB 0x211125 +#define APIRECEIVER 0x211124 +#define APIGUI 0x211124 +#define APICTB 0x220118 +#define APIGOTTHARD 0x220118 #define APIGOTTHARD2 0x220118 -#define APIJUNGFRAU 0x220118 -#define APIMYTHEN3 0x220118 -#define APIMOENCH 0x220118 -#define APIEIGER 0x220118 +#define APIJUNGFRAU 0x220118 +#define APIMYTHEN3 0x220118 +#define APIMOENCH 0x220118 +#define APIEIGER 0x220118 diff --git a/slsSupportLib/src/file_utils.cpp b/slsSupportLib/src/file_utils.cpp index ee6c9e15f..b38ff296b 100644 --- a/slsSupportLib/src/file_utils.cpp +++ b/slsSupportLib/src/file_utils.cpp @@ -67,7 +67,8 @@ std::vector readBinaryFile(const std::string &fname, FILE *fp = fopen(fname.c_str(), "rb"); if (fp == nullptr) { throw sls::RuntimeError(errorPrefix + - std::string(" (Could not open file: ") + fname + std::string(")")); + std::string(" (Could not open file: ") + fname + + std::string(")")); } // get file size to print progress @@ -148,17 +149,19 @@ std::string getFileNameFromFilePath(const std::string &fpath) { return fname; } -ssize_t getFileSize(FILE* fd, const std::string &prependErrorString) { +ssize_t getFileSize(FILE *fd, const std::string &prependErrorString) { if (fseek(fd, 0, SEEK_END) != 0) { - throw RuntimeError(prependErrorString + std::string(" (Seek error in src file)")); + throw RuntimeError(prependErrorString + + std::string(" (Seek error in src file)")); } size_t fileSize = ftell(fd); if (fileSize <= 0) { - throw RuntimeError(prependErrorString + std::string(" (Could not get length of source file)")); + throw RuntimeError( + prependErrorString + + std::string(" (Could not get length of source file)")); } rewind(fd); return fileSize; } - } // namespace sls diff --git a/slsSupportLib/src/md5.c b/slsSupportLib/src/md5.c index 55260b339..99a84f7ac 100644 --- a/slsSupportLib/src/md5.c +++ b/slsSupportLib/src/md5.c @@ -34,36 +34,42 @@ namespace sls { #endif -/** - * Modification 2021 Paul Scherrer Institut +/** + * Modification 2021 Paul Scherrer Institut * Macros exported from md5_local.h */ -#define F(b,c,d) ((((c) ^ (d)) & (b)) ^ (d)) -#define G(b,c,d) ((((b) ^ (c)) & (d)) ^ (c)) -#define H(b,c,d) ((b) ^ (c) ^ (d)) -#define I(b,c,d) (((~(d)) | (b)) ^ (c)) +#define F(b, c, d) ((((c) ^ (d)) & (b)) ^ (d)) +#define G(b, c, d) ((((b) ^ (c)) & (d)) ^ (c)) +#define H(b, c, d) ((b) ^ (c) ^ (d)) +#define I(b, c, d) (((~(d)) | (b)) ^ (c)) -#define R0(a,b,c,d,k,s,t) { \ - a+=((k)+(t)+F((b),(c),(d))); \ - a=ROTATE(a,s); \ - a+=b; }; +#define R0(a, b, c, d, k, s, t) \ + { \ + a += ((k) + (t) + F((b), (c), (d))); \ + a = ROTATE(a, s); \ + a += b; \ + }; -#define R1(a,b,c,d,k,s,t) { \ - a+=((k)+(t)+G((b),(c),(d))); \ - a=ROTATE(a,s); \ - a+=b; }; - -#define R2(a,b,c,d,k,s,t) { \ - a+=((k)+(t)+H((b),(c),(d))); \ - a=ROTATE(a,s); \ - a+=b; }; - -#define R3(a,b,c,d,k,s,t) { \ - a+=((k)+(t)+I((b),(c),(d))); \ - a=ROTATE(a,s); \ - a+=b; }; +#define R1(a, b, c, d, k, s, t) \ + { \ + a += ((k) + (t) + G((b), (c), (d))); \ + a = ROTATE(a, s); \ + a += b; \ + }; +#define R2(a, b, c, d, k, s, t) \ + { \ + a += ((k) + (t) + H((b), (c), (d))); \ + a = ROTATE(a, s); \ + a += b; \ + }; +#define R3(a, b, c, d, k, s, t) \ + { \ + a += ((k) + (t) + I((b), (c), (d))); \ + a = ROTATE(a, s); \ + a += b; \ + }; /* * Implemented from RFC1321 The MD5 Message-Digest Algorithm @@ -74,8 +80,7 @@ namespace sls { #define INIT_DATA_C (unsigned long)0x98badcfeL #define INIT_DATA_D (unsigned long)0x10325476L -int MD5_Init_SLS(MD5_CTX *c) -{ +int MD5_Init_SLS(MD5_CTX *c) { memset(c, 0, sizeof(*c)); c->A = INIT_DATA_A; c->B = INIT_DATA_B; @@ -84,14 +89,13 @@ int MD5_Init_SLS(MD5_CTX *c) return 1; } -void md5_block_data_order(MD5_CTX *c, const void *data_, size_t num) -{ +void md5_block_data_order(MD5_CTX *c, const void *data_, size_t num) { const unsigned char *data = data_; register unsigned MD32_REG_T A, B, C, D, l; /* See comment in crypto/sha/sha_local.h for details. */ - unsigned MD32_REG_T XX0, XX1, XX2, XX3, XX4, XX5, XX6, XX7, - XX8, XX9, XX10, XX11, XX12, XX13, XX14, XX15; -# define X(i) XX##i + unsigned MD32_REG_T XX0, XX1, XX2, XX3, XX4, XX5, XX6, XX7, XX8, XX9, XX10, + XX11, XX12, XX13, XX14, XX15; +#define X(i) XX##i A = c->A; B = c->B; @@ -207,12 +211,11 @@ void md5_block_data_order(MD5_CTX *c, const void *data_, size_t num) } } -/** - * Modification 2021 Paul Scherrer Institut - * from md32_common.h +/** + * Modification 2021 Paul Scherrer Institut + * from md32_common.h */ -int HASH_UPDATE(HASH_CTX *c, const void *data_, size_t len) -{ +int HASH_UPDATE(HASH_CTX *c, const void *data_, size_t len) { const unsigned char *data = data_; unsigned char *p; HASH_LONG l; @@ -221,11 +224,11 @@ int HASH_UPDATE(HASH_CTX *c, const void *data_, size_t len) if (len == 0) return 1; - l = (c->Nl + (((HASH_LONG) len) << 3)) & 0xffffffffUL; - if (l < c->Nl) /* overflow */ + l = (c->Nl + (((HASH_LONG)len) << 3)) & 0xffffffffUL; + if (l < c->Nl) /* overflow */ c->Nh++; - c->Nh += (HASH_LONG) (len >> 29); /* might cause compiler warning on - * 16-bit */ + c->Nh += (HASH_LONG)(len >> 29); /* might cause compiler warning on + * 16-bit */ c->Nl = l; n = c->num; @@ -269,16 +272,15 @@ int HASH_UPDATE(HASH_CTX *c, const void *data_, size_t len) return 1; } -/** - * Modification 2021 Paul Scherrer Institut - * from md32_common.h +/** + * Modification 2021 Paul Scherrer Institut + * from md32_common.h */ -int HASH_FINAL(unsigned char *md, HASH_CTX *c) -{ +int HASH_FINAL(unsigned char *md, HASH_CTX *c) { unsigned char *p = (unsigned char *)c->data; size_t n = c->num; - p[n] = 0x80; /* there is always room for one */ + p[n] = 0x80; /* there is always room for one */ n++; if (n > (HASH_CBLOCK - 8)) { @@ -289,7 +291,7 @@ int HASH_FINAL(unsigned char *md, HASH_CTX *c) memset(p + n, 0, HASH_CBLOCK - 8 - n); p += HASH_CBLOCK - 8; -#if defined(DATA_ORDER_IS_BIG_ENDIAN) +#if defined(DATA_ORDER_IS_BIG_ENDIAN) (void)HOST_l2c(c->Nh, p); (void)HOST_l2c(c->Nl, p); #elif defined(DATA_ORDER_IS_LITTLE_ENDIAN) @@ -300,7 +302,7 @@ int HASH_FINAL(unsigned char *md, HASH_CTX *c) HASH_BLOCK_DATA_ORDER(c, p, 1); c->num = 0; // OPENSSL_cleanse(p, HASH_CBLOCK); - //Erik: Since we don't do encryption secure cleaning is not needed + // Erik: Since we don't do encryption secure cleaning is not needed memset(p, 0, HASH_CBLOCK); HASH_MAKE_STRING(c, md); diff --git a/slsSupportLib/tests/test-network_utils.cpp b/slsSupportLib/tests/test-network_utils.cpp index e6bea6af0..d02296f1f 100644 --- a/slsSupportLib/tests/test-network_utils.cpp +++ b/slsSupportLib/tests/test-network_utils.cpp @@ -115,7 +115,8 @@ TEST_CASE("Copy construct a MacAddr") { } TEST_CASE("udp dst struct basic properties") { - static_assert(sizeof(UdpDestination) == 36, "udpDestination struct size does not match"); + static_assert(sizeof(UdpDestination) == 36, + "udpDestination struct size does not match"); UdpDestination dst{}; REQUIRE(dst.entry == 0); REQUIRE(dst.port == 0);