Merge branch 'developer' into gui

This commit is contained in:
2019-06-03 11:13:03 +02:00
201 changed files with 25684 additions and 2843 deletions

View File

@@ -23,10 +23,10 @@ AnalyzeTemporaryDtors: false
FormatStyle: none
CheckOptions:
- { key: readability-identifier-naming.NamespaceCase, value: lower_case }
- { key: readability-identifier-naming.FunctionCase, value: lower_case }
# - { key: readability-identifier-naming.FunctionCase, value: lower_case }
- { key: readability-identifier-naming.ClassCase, value: CamelCase }
- { key: readability-identifier-naming.MethodCase, value: CamelCase }
- { key: readability-identifier-naming.StructCase, value: CamelCase }
- { key: readability-identifier-naming.VariableCase, value: lower_case }
# - { key: readability-identifier-naming.MethodCase, value: CamelCase }
# - { key: readability-identifier-naming.StructCase, value: CamelCase }
# - { key: readability-identifier-naming.VariableCase, value: lower_case }
- { key: readability-identifier-naming.GlobalConstantCase, value: UPPER_CASE }
...

View File

@@ -25,7 +25,8 @@ install:
- conda config --add channels slsdetectorgroup
- conda update conda
- conda update --all
- conda install conda-build anaconda-client
- conda install conda-build=3.17
- conda install anaconda-client
- conda install conda-verify
# Useful for debugging any issues with conda

View File

@@ -35,11 +35,12 @@ if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
endif()
option (SLS_USE_HDF5 "HDF5 File format" OFF)
option (SLS_USE_TEXTCLIENT "Text Client" OFF)
option (SLS_USE_RECEIVER "Receiver" OFF)
option (SLS_USE_TEXTCLIENT "Text Client" ON)
option (SLS_USE_RECEIVER "Receiver" ON)
option (SLS_USE_GUI "GUI" OFF)
option (SLS_USE_TESTS "TESTS" ON)
option (SLS_USE_INTEGRATION_TESTS "Integration Tests" ON)
option (SLS_USE_SIMULATOR "Simulator" OFF)
option (SLS_USE_TESTS "TESTS" OFF)
option (SLS_USE_INTEGRATION_TESTS "Integration Tests" OFF)
option(SLS_USE_SANITIZER "Sanitizers for debugging" OFF)
option(SLS_USE_PYTHON "Python bindings" OFF)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
@@ -106,11 +107,10 @@ if(SLS_USE_SANITIZER)
target_link_libraries(slsProjectOptions INTERFACE -fsanitize=address,undefined)
# target_compile_options(slsProjectOptions INTERFACE -fsanitize=thread)
# target_link_libraries(slsProjectOptions INTERFACE -fsanitize=thread)
endif()
endif()
# Install fake the library
# Install fake the libraries
install(TARGETS slsProjectOptions slsProjectWarnings
EXPORT "${TARGETS_EXPORT_NAME}"
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
@@ -132,8 +132,7 @@ if (SLS_USE_TESTS)
add_subdirectory(tests)
endif(SLS_USE_TESTS)
# Support library containing functionallity common to
# detector and receiver
# Common functionallity to detector and receiver
add_subdirectory(slsSupportLib)
if (SLS_USE_TEXTCLIENT)
@@ -157,7 +156,9 @@ if (SLS_USE_GUI)
endif()
endif (SLS_USE_GUI)
if (SLS_USE_SIMULATOR)
add_subdirectory(slsDetectorServers)
endif (SLS_USE_SIMULATOR)
if (SLS_USE_INTEGRATION_TESTS)
add_subdirectory(integrationTests)

45
cmk.sh
View File

@@ -8,6 +8,8 @@ RECEIVER=0
GUI=0
DEBUG=0
PYTHON=0
TESTS=0
SIMULATOR=0
CLEAN=0
@@ -16,7 +18,7 @@ CMAKE_PRE=""
CMAKE_POST=""
usage() { echo -e "
Usage: $0 [-c] [-b] [-p] [e] [t] [r] [g] [-h] [-d <HDF5 directory>] [-j] <Number of threads>
Usage: $0 [-c] [-b] [-p] [e] [t] [r] [g] [s] [i] [-h] [-d <HDF5 directory>] [-j] <Number of threads>
-[no option]: only make
-c: Clean
-b: Builds/Rebuilds CMake files normal mode
@@ -26,8 +28,10 @@ Usage: $0 [-c] [-b] [-p] [e] [t] [r] [g] [-h] [-d <HDF5 directory>] [-j] <Number
-t: Build/Rebuilds only text client
-r: Build/Rebuilds only receiver
-g: Build/Rebuilds only gui
-s: Simulator
-j: Number of threads to compile through
-e: Debug mode
-i: Builds tests
Rebuild when you switch to a new build and compile in parallel:
./cmk.sh -bj5
@@ -63,7 +67,7 @@ For rebuilding only certain sections
" ; exit 1; }
while getopts ":bpchd:j:trges:" opt ; do
while getopts ":bpchd:j:trgeis" opt ; do
case $opt in
b)
echo "Building of CMake files Required"
@@ -110,16 +114,24 @@ while getopts ":bpchd:j:trges:" opt ; do
echo "Compiling Options: Debug"
DEBUG=1
;;
\?)
echo "Invalid option: -$OPTARG"
i)
echo "Compiling Options: Tests"
TESTS=1
;;
s)
echo "Compiling Options: Simulator"
SIMULATOR=1
;;
\?)
echo "Invalid option: -$OPTARG"
usage
exit 1
;;
:)
echo "Option -$OPTARG requires an argument."
exit 1
;;
:)
echo "Option -$OPTARG requires an argument."
usage
exit 1
;;
exit 1
;;
esac
done
@@ -173,6 +185,19 @@ if [ $DEBUG -eq 1 ]; then
echo "Debug Option enabled"
fi
#Simulator
if [ $SIMULATOR -eq 1 ]; then
CMAKE_POST+=" -DCMAKE_BUILD_TYPE=Debug -DSLS_USE_SIMULATOR=ON "
echo "Simulator Option enabled"
fi
#Tests
if [ $TESTS -eq 1 ]; then
CMAKE_POST+=" -DCMAKE_BUILD_TYPE=Debug -DSLS_USE_TESTS=ON -DSLS_USE_INTEGRATION_TESTS=ON"
echo "Tests Option enabled"
fi
#hdf5 rebuild
if [ $HDF5 -eq 1 ]; then

View File

@@ -7,7 +7,7 @@ source:
- path: ..
build:
number: 0
number: 1
rpaths:
- lib/
@@ -16,8 +16,8 @@ requirements:
- {{ compiler('c') }}
- {{compiler('cxx')}}
- cmake
- qwt 6.*
- qt=4.8.7=7
# - qwt 6.* #require qt5 investigate befor activating gui
# - qt=4.8.7=7
- zeromq=4.2.5=hfc679d8_5
- pyzmq
- xorg-libx11

58
configure vendored
View File

@@ -1,58 +0,0 @@
##!/bin/bash
: ${INSTALLROOT=$PWD}
read -p "Installation directory [default:\"$INSTALLROOT\"]:" -e t3
if [ -z "$t3" ]
then
echo
else
INSTALLROOT=$t3
fi
echo "INSTALLROOT will be \"$INSTALLROOT\""
export INSTALLROOT
: ${BINDIR="bin"}
read -p "Binaries directory [default:\"$BINDIR\"]:" -e t4
if [ -z "$t4" ]
then
BINDIR=$INSTALLROOT/$BINDIR
else
BINDIR=$INSTALLROOT/$t4
fi
echo "BINDIR will be \"$BINDIR\""
export BINDIR
: ${LIBDIR="bin"}
read -p "Libraries directory [default:\"$LIBDIR\"]:" -e t5
if [ -z "$t5" ]
then
LIBDIR=$INSTALLROOT/$LIBDIR
else
LIBDIR=$INSTALLROOT/$t5
fi
echo "LIBDIR will be \"$LIBDIR\""
export LIBDIR
: ${INCDIR="include"}
read -p "Includes directory [default:\"$INCDIR\"]:" -e t6
if [ -z "$t6" ]
then
INCDIR=$INSTALLROOT/$INCDIR
else
INCDIR=$INSTALLROOT/$t6
fi
echo "INCDIR will be \"$INCDIR\""
export INCDIR
: ${DOCDIR="doc"}
read -p "Documentation directory [default:\"$DOCDIR\"]:" -e t7
if [ -z "$t7" ]
then
DOCDIR=$INSTALLROOT/$DOCDIR
else
DOCDIR=$INSTALLROOT/$t7
fi
echo "DOCDIR will be \"$DOCDIR\""
export DOCDIR

44
ctbGui/Makefile.root5 Normal file
View File

@@ -0,0 +1,44 @@
INCS=ctbMain.h ctbDacs.h ctbPattern.h ctbSignals.h ctbAdcs.h ctbAcquisition.h ctbPowers.h ctbSlowAdcs.h
SRC= $(SRC:.h=.cpp) ctbDict.cpp
LINKDEF=ctbLinkDef.h
ZMQLIB=../slsReceiverSoftware/include
LIBRARYCBF=$(CBFLIBDIR)/lib/*.o
INCDIR=-I../slsReceiverSoftware/include/ -I../slsDetectorSoftware/include/ -I../slsSupportLib/include/ -I../slsDetectorCalibration -I../slsDetectorCalibration/dataStructures -I$(CBFLIBDIR)/include -I../slsDetectorCalibration/interpolations
LDFLAG=-L../bin -lSlsDetector -lSlsSupport -L/usr/lib64/ -lpthread -lm -lstdc++ -lzmq -pthread -lrt -ltiff -L$(ZMQLIB) -L$(CBFLIBDIR)/lib/ -std=c++11
#
MAIN=ctbGui.cpp
DESTDIR?=../bin
OBJS = $(SRC:.cpp=.o) $(MAIN:.cpp=.o)
all: $(DESTDIR)/ctbGui
doc:
cd manual && make DESTDIR=$(DESTDIR)
htmldoc:
cd manual && make html DESTDIR=$(DESTDIR)
ctbDict.cpp: $(INCS) $(LINKDEF)
rootcint -f ctbDict.cpp -c $(INCS) $(LINKDEF)
%.o : %.cpp
echo $@
g++ -DMYROOT `source root-config --cflags --glibs` -lMinuit -DCTB $(LDFLAG) -o $@ -c $< $(INCDIR)
#$(CXX) -o $@ -c $< $(INCLUDES) $(DFLAGS) -fPIC $(EPICSFLAGS) -lpthread #$(FLAGS)
$(DESTDIR)/ctbGui: $(OBJS) $(LINKDEF)
g++ -DMYROOT `source root-config --cflags --glibs` -lMinuit -DCTB $(LDFLAG) -o ctbGui $(INCDIR) $(OBJS) ../slsDetectorCalibration/tiffIO.cpp
mv ctbGui $(DESTDIR)
clean:
rm -f $(DESTDIR)/ctbGui *.o ctbDict.* $(OBJS)

46
ctbGui/Makefile.root6 Normal file
View File

@@ -0,0 +1,46 @@
INCS=ctbMain.h ctbDacs.h ctbPattern.h ctbSignals.h ctbAdcs.h ctbAcquisition.h ctbPowers.h ctbSlowAdcs.h
SRC= $(INCS:.h=.cpp) ctbDict.cpp
LINKDEF=ctbLinkDef.h
#ctbActions.h
ZMQLIB=../slsReceiverSoftware/include
LIBRARYCBF=$(CBFLIBDIR)/lib/*.o
INCDIR=-I../slsReceiverSoftware/include/ -I../slsDetectorSoftware/include/ -I../slsSupportLib/include/ -I../slsDetectorCalibration -I../slsDetectorCalibration/dataStructures -I$(CBFLIBDIR)/include -I../slsDetectorCalibration/interpolations
LDFLAG=-L../build/bin -lSlsDetector -lSlsSupport -L/usr/lib64/ -lpthread -lm -lstdc++ -lzmq -pthread -lrt -ltiff -L$(ZMQLIB) -L$(CBFLIBDIR)/lib/ -std=c++11
#
MAIN=ctbGui.cpp
DESTDIR?=../build/bin
OBJS = $(SRC:.cpp=.o) $(MAIN:.cpp=.o)
all: $(DESTDIR)/ctbGui
doc:
cd manual && make DESTDIR=$(DESTDIR)
htmldoc:
cd manual && make html DESTDIR=$(DESTDIR)
ctbDict.cpp: $(INCS) $(LINKDEF)
rootcling -f ctbDict.cpp -c $(INCS) $(LINKDEF)
%.o : %.cpp
echo $@
g++ -DMYROOT `source root-config --cflags --glibs` -lMinuit -DCTB $(LDFLAG) -o $@ -c $< $(INCDIR)
#$(CXX) -o $@ -c $< $(INCLUDES) $(DFLAGS) -fPIC $(EPICSFLAGS) -lpthread #$(FLAGS)
$(DESTDIR)/ctbGui: $(OBJS) $(LINKDEF)
g++ -DMYROOT `source root-config --cflags --glibs` -lMinuit -DCTB $(LDFLAG) -o ctbGui $(INCDIR) $(OBJS) ../slsDetectorCalibration/tiffIO.cpp
mv ctbGui $(DESTDIR)
clean:
rm -f $(DESTDIR)/ctbGui *.o ctbDict.* $(OBJS)

2091
ctbGui/ctbAcquisition.cpp Executable file

File diff suppressed because it is too large Load Diff

235
ctbGui/ctbAcquisition.h Executable file
View File

@@ -0,0 +1,235 @@
#ifndef CTBACQUISITION_H
#define CTBACQUISITION_H
#include <TGFrame.h>
#include "ctbAdcs.h"
#include "ctbSignals.h"
#include "ctbPattern.h"
class TGTextEntry;
class TGLabel;
class TGNumberEntry;
class TGCheckButton;
class TThread;
class TGraph;
class TMultiGraph;
class THStack;
class TGButtonGroup;
class TGRadioButton;
class TGComboBox;
class TTimer;
class TCanvas;
class TH2F;
class TH1F;
class TGLabel;
class TGTextButton;
class multiSlsDetector;
class detectorData;
template <class dataType> class slsDetectorData;
class singlePhotonDetector;
//class singlePhotonDetector;
class commonModeSubtraction;
#include <string>
#include <stdint.h>
using namespace std;
class ctbAcquisition : public TGGroupFrame {
enum {DESERIALIZER, MOENCH04, MOENCH02, ADCSAR2, MYTHEN301, MYTHEN302};
private:
TGTextEntry *eOutdir;
TGTextEntry *eFname;
TGNumberEntry *eFindex;
TGCheckButton *cFileSave;
TGNumberEntry *eSerOff;
TGNumberEntry *eDynRange;
TGNumberEntry *eNumCount;
TGNumberEntry *eFitADC;
TGNumberEntry *eBitPlot;
TGNumberEntry *eMinRaw;
TGNumberEntry *eMaxRaw;
TGNumberEntry *eMinPedSub;
TGNumberEntry *eMaxPedSub;
TGCheckButton *cMinMaxRaw;
TGCheckButton *cMinMaxPedSub;
TGNumberEntry *eMeasurements;
TGTextButton *bStatus;
// TGTextButton
TGCheckButton *cCompile;
TGTextButton *cLoad;
// TGCheckButton *cRun;
TThread *acqThread;
THStack *adcStack;
THStack *bitStack;
THStack *countsStack;
TH1F *adcHisto[NADCS];
TH1F *countsHisto[NADCS];
TH1F *bitHisto[NSIGNALS];
float bitOffset[NSIGNALS];
// int enableFlag[NADCS+4];
int roMode;
int dBitOffset;
TH1F *adcFit;
TH1F *bitPlot;
TH1F *countsFit;
TH2F *h2DMap; // for 2D detectors
TH1F *h1DMap; //for 1D detectors
// TH2F *h2Scan; // for 2D detectors
// TMultiGraph *mgAdcs;
// TH1I *plotAdc[NADCS];
multiSlsDetector* myDet;
int plotFlag[NADCS];
int bitPlotFlag[NSIGNALS];
int ip;
// int nChannels;
// int chanEnable;
//int nADCs;
std::vector <int> dbitlist;
std::vector <int> adclist;
TGButtonGroup *bgPlot;// = new TGVButtonGroup(main_frame);
TGRadioButton *rbPlotOff;
TGRadioButton *rbWaveform;
TGRadioButton *rbDistribution;
TGRadioButton *rb2D;
// TGRadioButton *rbScan;
TGComboBox *cbDetType;
TGCheckButton *cbGetPedestal;
TGCheckButton *cbSubtractPedestal;
TGCheckButton *cbCommonMode;
TGTextButton *bResetPedestal;
TGLabel *lClickX;
TGLabel *lClickY;
TGLabel *lClickValue;
TCanvas *myCanvas;
TTimer *plotTimer;
char patternFile[10000];
char patternCompiler[10000];
int globalPlot;
int nAnalogSamples, nDigitalSamples;
// int iScanStep;
slsDetectorData<uint16_t> *dataStructure;
singlePhotonDetector *photonFinder;
//singlePhotonDetector *photonFinder;
commonModeSubtraction *commonMode;
int cmSub;
int stop;
uint64_t dBitMask;
int deserializer;
public:
ctbAcquisition(TGVerticalFrame*, multiSlsDetector*);
void setOutdir();
void setFname();
void setMeasurements();
void setFsave(Bool_t);
void changePlot(Int_t);
void changeDetector(Int_t);
void changePlot();
void changeDetector();
void setFindex();
void Draw();
void setCanvas(TCanvas*);
void toggleAcquisition();
void loadPattern();
static void* ThreadHandle(void *arg);
void update();
void acquisitionFinished();
// string getParameters();
void setGraph (int i ,int en, Pixel_t col);
void setBitGraph (int i ,int en, Pixel_t col);
void startAcquisition();
static int progressCallback(double,void*);
static int dataCallback(detectorData*, int,int, void*);
int StopFlag;
int plotData(detectorData*, int);
void setPatternFile(const char* t);
void setPatternCompiler(const char* t);
void setAnalogSamples(int);
void setDigitalSamples(int);
void setADCEnable(Int_t);
void setDbitEnable(Int_t);
void setReadoutMode(int);
void updateChans();
void resetPedestal();
void ToggleCommonMode(Bool_t);
void TogglePedSub(Bool_t);
void ChangeHistoLimitsPedSub(Long_t );
void ChangeHistoLimitsRaw(Long_t);
void ChangeHistoLimitsPedSub( );
void ChangeHistoLimitsRaw();
void ChangeHistoLimitsPedSub(Bool_t );
void ChangeHistoLimitsRaw(Bool_t);
void ChangeSerialOffset();
void ChangeSerialOffset(Long_t);
void ChangeNumberOfChannels();
void ChangeNumberOfChannels(Long_t);
void ChangeDynamicRange();
void ChangeDynamicRange(Long_t);
void canvasClicked();
void FitADC();
void plotBit();
ClassDef(ctbAcquisition,0)
};
#endif

710
ctbGui/ctbAdcs.cpp Executable file
View File

@@ -0,0 +1,710 @@
#include <TApplication.h>
#include <TGClient.h>
#include <TCanvas.h>
#include <TF1.h>
#include <TRandom.h>
#include <TGButton.h>
#include <TRootEmbeddedCanvas.h>
#include <TGButtonGroup.h>
#include <TGNumberEntry.h>
#include <TGLabel.h>
#include <TList.h>
#include <TGFileDialog.h>
#include <TGComboBox.h>
#include <TH2F.h>
#include <TColor.h>
#include <TH1F.h>
#include <TGraphErrors.h>
#include <TGColorSelect.h>
#include <THStack.h>
#include <TGTab.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include "ctbAdcs.h"
#include "multiSlsDetector.h"
#include "slsDetectorCommand.h"
using namespace std;
ctbAdc::ctbAdc(TGVerticalFrame *page, int i, multiSlsDetector *det)
: TGHorizontalFrame(page, 800,800), id(i), myDet(det) {
TGHorizontalFrame *hframe=this;
char tit[100];
page->AddFrame(hframe,new TGLayoutHints(kLHintsTop | kLHintsExpandX , 1,1,1,1));
hframe->MapWindow();
sprintf(tit, "ADC%d", id);
sAdcLabel= new TGLabel(hframe, tit);
hframe->AddFrame(sAdcLabel,new TGLayoutHints(kLHintsTop | kLHintsLeft| kLHintsExpandX, 1, 1, 1, 1));
sAdcLabel->MapWindow();
sAdcLabel->SetTextJustify(kTextLeft);
sAdcInvert= new TGCheckButton(hframe, "Inv");
hframe->AddFrame( sAdcInvert,new TGLayoutHints(kLHintsTop | kLHintsLeft| kLHintsExpandX, 1, 1, 1, 1));
sAdcInvert->MapWindow();
sAdcInvert->Connect("Toggled(Bool_t)","ctbAdc",this,"ToggledInvert(Bool_t)");
sAdcEnable= new TGCheckButton(hframe, "En");
hframe->AddFrame( sAdcEnable,new TGLayoutHints(kLHintsTop | kLHintsLeft| kLHintsExpandX, 1, 1, 1, 1));
sAdcEnable->MapWindow();
// sAdcEnable->SetOn(kTRUE);
// sAdcEnable->SetEnabled(kFALSE);
sAdcEnable->Connect("Toggled(Bool_t)","ctbAdc",this,"ToggledEnable(Bool_t)");
sAdcPlot= new TGCheckButton(hframe, "Plot");
hframe->AddFrame( sAdcPlot,new TGLayoutHints(kLHintsTop | kLHintsLeft| kLHintsExpandX, 1, 1, 1, 1));
sAdcPlot->MapWindow();
sAdcPlot->Connect("Toggled(Bool_t)","ctbAdc",this,"ToggledPlot(Bool_t)");
fColorSel = new TGColorSelect(hframe, id+1, 0);
fColorSel->Connect("ColorSelected(Pixel_t)","ctbAdc",this,"ColorChanged(Pixel_t)");
hframe->AddFrame(fColorSel, new TGLayoutHints(kLHintsTop |
kLHintsLeft, 2, 0, 2, 2));
fColorSel->SetColor(TColor::Number2Pixel(id+1));
// sprintf(tit,"adc%d",id);
// gADC=new TGraph();
// gADC->SetName(tit);
// gADC->SetLineColor(id+1);
// gADC->SetMarkerColor(id+1);
};
Pixel_t ctbAdc::getColor(){
return fColorSel->GetColor();
}
Bool_t ctbAdc::getEnabled(){
return getPlot();
}
Bool_t ctbAdc::getPlot(){
return sAdcPlot->IsOn();
}
Bool_t ctbAdc::getInverted(){
return sAdcInvert->IsOn();
}
Bool_t ctbAdc::getEnable(){
return sAdcEnable->IsOn();
}
void ctbAdc::setInverted(Bool_t b){
// cout << id << "set enabled " << b << endl;
if (b)
sAdcInvert->SetOn(kTRUE,kTRUE);
else
sAdcInvert->SetOn(kFALSE,kTRUE);
}
void ctbAdc::setEnable(Bool_t b){
// cout << id << "set enabled " << b << endl;
if (b)
sAdcEnable->SetOn(kTRUE,kFALSE);
else
sAdcEnable->SetOn(kFALSE,kFALSE);
}
void ctbAdc::setAdcAlias(char *tit, int plot, int color) {
if (tit)
sAdcLabel->SetText(tit);
if (plot>0)
sAdcPlot->SetOn(kTRUE,kTRUE);
else if (plot==0)
sAdcPlot->SetOn(kFALSE,kTRUE);
if (color>=0)
fColorSel->SetColor(color);
fColorSel->SetEnabled(sAdcPlot->IsOn());
}
string ctbAdc::getAdcAlias() {
char line[1000];
sprintf(line,"ADC%d %s %d %x\n",id,sAdcLabel->GetText()->Data(),sAdcPlot->IsOn(),fColorSel->GetColor());
return string(line);
}
void ctbAdc::update() {
//Emit("ToggledAdcEnable(Int_t)", id);
}
void ctbAdc::ToggledPlot(Bool_t b){
// Long_t mask=b<<id;
// ToggledAdcPlot(mask);
cout << "Colsel " << id << " enable " << b << endl;
if (b)
fColorSel->SetEnabled(kTRUE);
else
fColorSel->SetEnabled(kFALSE);
// fColorSel->SetEnabled(sAdcPlot->IsOn());
Emit("ToggledAdcPlot(Int_t)", id);
}
void ctbAdc::ToggledInvert(Bool_t b){
// fColorSel->SetEnabled(sAdcPlot->IsOn());
Emit("ToggledAdcInvert(Int_t)", id);
}
void ctbAdc::ToggledEnable(Bool_t b){
fColorSel->SetEnabled(sAdcPlot->IsOn());
Emit("ToggledAdcEnable(Int_t)", id);
}
void ctbAdc::ColorChanged(Pixel_t) {
Emit("ToggledAdcPlot(Int_t)", id);
}
void ctbAdc::ToggledAdcPlot(Int_t b){
Emit("ToggledAdcPlot(Int_t)", id);
}
void ctbAdc::ToggledAdcInvert(Int_t b){
Emit("ToggledAdcInvert(Int_t)", id);
}
void ctbAdc::ToggledAdcEnable(Int_t b){
Emit("ToggledAdcEnable(Int_t)", id);
}
void ctbAdc::setEnabled(Bool_t b){
// cout << id << "set enabled " << b << endl;
if (b)
sAdcPlot->SetOn(kTRUE,kFALSE);
else
sAdcPlot->SetOn(kFALSE,kFALSE);
}
ctbAdcs::ctbAdcs(TGVerticalFrame *page, multiSlsDetector *det)
: TGGroupFrame(page,"Adcs",kVerticalFrame), myDet(det) {
SetTitlePos(TGGroupFrame::kLeft);
page->AddFrame(this,new TGLayoutHints( kLHintsTop | kLHintsExpandX , 10,10,10,10));
MapWindow();
char tit[100];
TGHorizontalFrame* hframe=new TGHorizontalFrame(this, 800,800);
AddFrame(hframe,new TGLayoutHints(kLHintsTop | kLHintsExpandX , 1,1,1,1));
hframe->MapWindow();
int idac=0;
TGHorizontalFrame* hhframe=new TGHorizontalFrame(this, 800,800);
AddFrame(hhframe,new TGLayoutHints(kLHintsTop | kLHintsExpandX , 1,1,1,1));
hhframe->MapWindow();
TGVerticalFrame *vframe;
for (idac=0; idac<NADCS; idac++) {
if (idac%16==0) {
vframe=new TGVerticalFrame(hhframe, 400,800);
hhframe->AddFrame(vframe,new TGLayoutHints(kLHintsTop | kLHintsExpandX , 1,1,1,1));
vframe->MapWindow();
}
sAdc[idac]=new ctbAdc(vframe,idac,myDet);
sAdc[idac]->Connect("ToggledAdcPlot(Int_t)","ctbAdcs",this,"ToggledAdcPlot(Int_t)");
sAdc[idac]->Connect("ToggledAdcInvert(Int_t)","ctbAdcs",this,"ToggledAdcInvert(Int_t)");
sAdc[idac]->Connect("ToggledAdcEnable(Int_t)","ctbAdcs",this,"ToggledAdcEnable(Int_t)");
}
hframe=new TGHorizontalFrame(this, 800,800);
AddFrame(hframe,new TGLayoutHints(kLHintsTop | kLHintsExpandX , 1,1,1,1));
hframe->MapWindow();
bCheckHalf[0]=new TGTextButton(hframe, "All 0-15");
hframe->AddFrame(bCheckHalf[0],new TGLayoutHints(kLHintsTop | kLHintsExpandX, 5, 5, 5, 5));
bCheckHalf[0]->MapWindow();
bCheckHalf[0]->Connect("Clicked()","ctbAdcs",this,"CheckHalf0()");
bRemoveHalf[0]=new TGTextButton(hframe, "None 0-15");
hframe->AddFrame(bRemoveHalf[0],new TGLayoutHints(kLHintsBottom | kLHintsExpandX, 5, 5, 5, 5));
bRemoveHalf[0]->MapWindow();
bRemoveHalf[0]->Connect("Clicked()","ctbAdcs",this,"RemoveHalf0()");
bCheckHalf[1]=new TGTextButton(hframe, "All 16-23");
hframe->AddFrame(bCheckHalf[1],new TGLayoutHints(kLHintsTop | kLHintsExpandX, 5, 5, 5, 5));
bCheckHalf[1]->MapWindow();
bCheckHalf[1]->Connect("Clicked()","ctbAdcs",this,"CheckHalf1()");
// bCheckAll->Connect("Clicked()","ctbAdcs",this,"CheckAll()");
bRemoveHalf[1]=new TGTextButton(hframe, "None 16-23");
hframe->AddFrame(bRemoveHalf[1],new TGLayoutHints(kLHintsBottom | kLHintsExpandX, 5, 5, 5, 5));
bRemoveHalf[1]->MapWindow();
bRemoveHalf[1]->Connect("Clicked()","ctbAdcs",this,"RemoveHalf1()");
// bRemoveAll->Connect("Clicked()","ctbAdcs",this,"RemoveAll()");
hframe=new TGHorizontalFrame(this, 800,800);
AddFrame(hframe,new TGLayoutHints(kLHintsTop | kLHintsExpandX , 1,1,1,1));
hframe->MapWindow();
bCheckAll=new TGTextButton(hframe, "All");
hframe->AddFrame(bCheckAll,new TGLayoutHints(kLHintsTop | kLHintsExpandX, 5, 5, 5, 5));
bCheckAll->MapWindow();
bCheckAll->Connect("Clicked()","ctbAdcs",this,"CheckAll()");
bRemoveAll=new TGTextButton(hframe, "None");
hframe->AddFrame(bRemoveAll,new TGLayoutHints(kLHintsBottom | kLHintsExpandX, 5, 5, 5, 5));
bRemoveAll->MapWindow();
bRemoveAll->Connect("Clicked()","ctbAdcs",this,"RemoveAll()");
hframe=new TGHorizontalFrame(this, 800,50);
AddFrame(hframe,new TGLayoutHints(kLHintsTop | kLHintsExpandX , 1,1,1,1));
hframe->MapWindow();
TGLabel *label= new TGLabel(hframe, "Inversion mask: ");
hframe->AddFrame(label,new TGLayoutHints(kLHintsTop | kLHintsLeft| kLHintsExpandX, 1, 1, 1, 1));
label->MapWindow();
label->SetTextJustify(kTextLeft);
eInversionMask = new TGNumberEntry(hframe, 0, 16,999, TGNumberFormat::kNESHex,
TGNumberFormat::kNEANonNegative,
TGNumberFormat::kNELNoLimits);
hframe->AddFrame(eInversionMask,new TGLayoutHints(kLHintsTop | kLHintsExpandX, 1, 1, 1, 1));
eInversionMask->MapWindow();
eInversionMask->Resize(150,30);
eInversionMask->SetState(kFALSE);
hframe=new TGHorizontalFrame(this, 800,50);
AddFrame(hframe,new TGLayoutHints(kLHintsTop | kLHintsExpandX , 1,1,1,1));
hframe->MapWindow();
label= new TGLabel(hframe, "Enable mask: ");
hframe->AddFrame(label,new TGLayoutHints(kLHintsTop | kLHintsLeft| kLHintsExpandX, 1, 1, 1, 1));
label->MapWindow();
label->SetTextJustify(kTextLeft);
eEnableMask = new TGNumberEntry(hframe, 0, 16,999, TGNumberFormat::kNESHex,
TGNumberFormat::kNEANonNegative,
TGNumberFormat::kNELNoLimits);
hframe->AddFrame(eEnableMask,new TGLayoutHints(kLHintsTop | kLHintsExpandX, 1, 1, 1, 1));
eEnableMask->MapWindow();
eEnableMask->Resize(150,30);
eEnableMask->SetState(kFALSE);
}
int ctbAdcs::setEnable(int reg) {
// char aargs[10][100];
// char *args[10];
string retval;
int retreg;
// for (int i=0; i<10; i++) args[i]=aargs[i];
// sprintf(args[0],"adcenable");
// sprintf(args[1],"%x",reg);
// slsDetectorCommand *cmd=new slsDetectorCommand(myDet);
// if (reg>-1) {
// retval=cmd->executeLine(1,args,slsDetectorDefs::PUT_ACTION);
// }
if (reg>-1) {
try {
myDet->setADCEnableMask(reg);
} catch (...) {
cout << "Do nothing for this error" << endl;
}
}
// retval=cmd->executeLine(1,args,slsDetectorDefs::GET_ACTION);
// cout <<"enable: " << retval << endl;;
// delete cmd;
// sscanf(retval.c_str(),"%x",&retreg);
try {
retreg=myDet->getADCEnableMask();
} catch (...) {
cout << "Do nothing for this error" << endl;
}
eEnableMask->SetHexNumber(retreg);
return retreg;
}
int ctbAdcs::setInvert(int reg) {
// char aargs[10][100];
// char *args[10];
string retval;
int retreg;
// for (int i=0; i<10; i++) args[i]=aargs[i];
//sprint// f(args[0],"adcinvert");
// sprintf(args[1],"%x",reg);
// slsDetectorCommand *cmd=new slsDetectorCommand(myDet);
if (reg>-1) {
try {
myDet->setADCInvert(reg);
} catch (...) {
cout << "Do nothing for this error" << endl;
}
//retval=cmd->executeLine(1,args,slsDetectorDefs::PUT_ACTION);
}
try {
retreg=myDet->getADCInvert();
} catch (...) {
cout << "Do nothing for this error" << endl;
}
// retval=cmd->executeLine(1,args,slsDetectorDefs::GET_ACTION);
// cout <<"invert: " << retval << endl;;
// delete cmd;
// sscanf(retval.c_str(),"%x",&retreg);
eInversionMask->SetHexNumber(retreg);
return retreg;
}
void ctbAdcs::update() {
Int_t invreg;//=myDet->readRegister(67);//(120);
Int_t disreg;//=myDet->readRegister(120);//(94);
// for (int i=0; i<10; i++)
// args[i]=aargs[i];
// string retval;
// sprintf(args[0],"adcenable");
// slsDetectorCommand *cmd=new slsDetectorCommand(myDet);
// retval=cmd->executeLine(1,args,slsDetectorDefs::GET_ACTION);
// delete cmd;
// // cout << retval << endl;
// sscanf(retval.c_str(),"adcenable %x",&disreg);
// eInversionMask->SetHexNumber(invreg);
// eEnableMask->SetHexNumber(disreg);
disreg=setEnable();
invreg=setInvert();
for (int is=0; is<NADCS; is++) {
sAdc[is]->setAdcAlias(NULL,-1,-1);
if (invreg & (1<<is) )
sAdc[is]->setInverted(kTRUE);
else
sAdc[is]->setInverted(kFALSE);
if (disreg & (1<<is) )
sAdc[is]->setEnable(kTRUE);
else
sAdc[is]->setEnable(kFALSE);
}
Emit("AdcEnable(Int_t)", disreg);
}
string ctbAdcs::getAdcParameters() {
ostringstream line;
line << "reg "<< hex << setInvert() << "# ADC invert reg" << dec << endl;
line << "reg "<< hex << setEnable() << " # ADC enable reg"<< dec << endl;
// line << "reg "<< hex << 67 << " " << myDet->readRegister(67) << "# ADC invert reg" << dec << endl;
// line << "reg "<< hex << 120 << " " << myDet->readRegister(120) << " # ADC enable reg"<< dec << endl;
// // line << "reg "<< hex << 94 << " " << myDet->readRegister(94) << " # ADC enable reg"<< dec << endl;
return line.str();
}
void ctbAdcs::CheckAll() {
for (int is=0; is<NADCS; is++)
sAdc[is]->setEnabled(kTRUE);
}
void ctbAdcs::RemoveAll() {
for (int is=0; is<NADCS; is++)
sAdc[is]->setEnabled(kFALSE);
}
void ctbAdcs::CheckHalf0() {
for (int is=0; is<NADCS/2; is++)
sAdc[is]->setEnabled(kTRUE);
}
void ctbAdcs::RemoveHalf0() {
for (int is=0; is<NADCS/2; is++)
sAdc[is]->setEnabled(kFALSE);
}
void ctbAdcs::CheckHalf1() {
for (int is=NADCS/2; is<NADCS; is++)
sAdc[is]->setEnabled(kTRUE);
}
void ctbAdcs::RemoveHalf1() {
for (int is=NADCS/2; is<NADCS; is++)
sAdc[is]->setEnabled(kFALSE);
}
// TGraph* ctbAdcs::getGraph(int i) {
// if (i>=0 && i<NADCS)
// return sAdc[i]->getGraph();
// return NULL;
// }
int ctbAdcs::setAdcAlias(string line) {
int is=-1, plot=0, color=-1;
char tit[100];
int narg=sscanf(line.c_str(),"ADC%d %s %d %x",&is,tit,&plot, &color);
if (narg<2)
return -1;
if (narg!=3)
color=-1;
if (is>=0 && is<NADCS) {
sAdc[is]->setAdcAlias(tit,plot,color);
}
return is;
}
string ctbAdcs::getAdcAlias() {
ostringstream line;
for (int is=0; is<NADCS; is++)
line << sAdc[is]->getAdcAlias();
return line.str();
}
void ctbAdcs::ToggledAdcPlot(Int_t b){
Emit("ToggledAdcPlot(Int_t)", b);
}
void ctbAdcs::AdcEnable(Int_t b){
Emit("AdcEnable(Int_t)", b);
}
void ctbAdcs::ToggledAdcEnable(Int_t b){
Int_t oreg=setEnable();//myDet->readRegister(67);
Int_t m=1<<b;
if (sAdc[b]->getEnable())
oreg|=m;
else
oreg&=~m;
// cout << dec << sizeof(Long64_t) << " " << mask << " " << hex << m << " ioreg " << oreg << endl;
setEnable(oreg);//)writeRegister(67, oreg);
//oreg=setEnable();//myDet->readRegister(67);
Emit("AdcEnable(Int_t)", oreg);
//cout << "enable!" << endl;
// Emit("ToggledAdcPlot(Int_t)", b);
}
void ctbAdcs::ToggledAdcInvert(Int_t b){
// char val[1000];
Int_t oreg=setInvert();//myDet->readRegister(67);
Int_t m=1<<b;
if (sAdc[b]->getInverted())
oreg|=m;
else
oreg&=~m;
// cout << dec << sizeof(Long64_t) << " " << mask << " " << hex << m << " ioreg " << oreg << endl;
setInvert(oreg);//)writeRegister(67, oreg);
// oreg=setInvert();//myDet->readRegister(67);
// cout << dec << sizeof(Long64_t) << " " << mask << " " << hex << m << " ioreg " << oreg << endl;
//sprintf(val,"%X",oreg);
//eInversionMask->SetHexNumber(oreg);
}
Pixel_t ctbAdcs::getColor(int i){
if (i>=0 && i<NADCS)
return sAdc[i]->getColor();
}
Bool_t ctbAdcs::getEnabled(int i){
if (i>=0 && i<NADCS)
return sAdc[i]->getEnabled();
}
Bool_t ctbAdcs::getEnable(int i){
if (i>=0 && i<NADCS)
return sAdc[i]->getEnable();
}
Bool_t ctbAdcs::getPlot(int i){
if (i>=0 && i<NADCS)
return sAdc[i]->getPlot();
}

151
ctbGui/ctbAdcs.h Executable file
View File

@@ -0,0 +1,151 @@
#ifndef CTBADCS_H
#define CTBADCS_H
#include <TGFrame.h>
#define NADCS 32
class TRootEmbeddedCanvas;
class TGButtonGroup;
class TGVerticalFrame;
class TGHorizontalFrame;
class TGTextEntry;
class TGLabel;
class TGNumberEntry;
class TH2F;
class TGComboBox;
class TGCheckButton;
class TGColorSelect;
class TColor;
class THStack;
class TGraphErrors;
class TGTextButton;
class TGTab;
class TGraph;
class multiSlsDetector;
#include <string>
using namespace std;
class ctbAdc : public TGHorizontalFrame {
private:
TGLabel *sAdcLabel;
TGCheckButton *sAdcEnable;
TGCheckButton *sAdcPlot;
TGCheckButton *sAdcInvert;
TGColorSelect *fColorSel;
// TGraph *gADC;
int id;
multiSlsDetector *myDet;
public:
ctbAdc(TGVerticalFrame *page, int i, multiSlsDetector *det);
void setAdcAlias(char *tit, int plot, int color);
string getAdcAlias();
void ToggledAdcPlot(Int_t b);
void ToggledAdcEnable(Int_t b);
void ToggledAdcInvert(Int_t b);
void ToggledPlot(Bool_t b);
void ToggledEnable(Bool_t b);
void ToggledInvert(Bool_t b);
void ColorChanged(Pixel_t);
void setEnabled(Bool_t b);
Bool_t getEnabled();
// TGraph *getGraph();
void update();
Pixel_t getColor();
Bool_t getEnable();
void setEnable(Bool_t);
Bool_t getInverted();
Bool_t getPlot();
void setInverted(Bool_t);
ClassDef(ctbAdc,0)
};
class ctbAdcs : public TGGroupFrame {
private:
ctbAdc *sAdc[NADCS];
multiSlsDetector *myDet;
TGTextButton *bCheckAll;
TGTextButton *bRemoveAll;
TGTextButton *bCheckHalf[2];
TGTextButton *bRemoveHalf[2];
TGNumberEntry *eInversionMask;
TGNumberEntry *eEnableMask;
/* TGTextButton *bPlotSelected; */
/* TGNumberEntry *eMinX; */
/* TGNumberEntry *eMaxX; */
/* TGNumberEntry *eMinY; */
/* TGNumberEntry *eMaxY; */
/* TGTextButton *bGetPixel; */
/* TGNumberEntry *ePixelX; */
/* TGNumberEntry *ePixelY; */
/* TGLabel *lPixelValue; */
public:
ctbAdcs(TGVerticalFrame *page, multiSlsDetector *det);
int setAdcAlias(string line);
string getAdcAlias();
string getAdcParameters();
void ToggledAdcPlot(Int_t);
void ToggledAdcInvert(Int_t);
void ToggledAdcEnable(Int_t);
void AdcEnable(Int_t b);
// TGraph *getGraph(int i);
void CheckAll();
void RemoveAll();
void update();
int setInvert(int reg=-1);
int setEnable(int reg=-1);
Pixel_t getColor(int i);
Bool_t getEnabled(int i);
Bool_t getPlot(int i);
Bool_t getEnable(int i);
void CheckHalf0();
void RemoveHalf0();
void CheckHalf1();
void RemoveHalf1();
ClassDef(ctbAdcs,0)
};
#endif

251
ctbGui/ctbDacs.cpp Executable file
View File

@@ -0,0 +1,251 @@
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <TGTextEntry.h>
#include <TGLabel.h>
#include <TGNumberEntry.h>
#include <TGButton.h>
#include "ctbDacs.h"
#include "multiSlsDetector.h"
#include "sls_detector_defs.h"
using namespace std;
ctbDac::ctbDac(TGGroupFrame *page, int idac, multiSlsDetector *det) : TGHorizontalFrame(page, 800,50) , id(idac), myDet(det) {
TGHorizontalFrame *hframe=this;
page->AddFrame(hframe,new TGLayoutHints(kLHintsTop | kLHintsExpandX , 1,1,1,1));
MapWindow();
char tit[100];
sprintf(tit, "DAC %d:",idac);
dacsLabel= new TGCheckButton(hframe, tit);// new TGLabel(hframe, tit);
dacsLabel->SetOn(kTRUE, kTRUE);
dacsLabel->Connect("Toggled(Bool_t)","ctbDac",this,"setOn(Bool_t)");
hframe->AddFrame(dacsLabel,new TGLayoutHints(kLHintsTop | kLHintsLeft| kLHintsExpandX, 5, 5, 5, 5));
dacsLabel->MapWindow();
dacsLabel->SetTextJustify(kTextLeft);
dacsEntry = new TGNumberEntry(hframe, 0, 9,999, TGNumberFormat::kNESInteger,
TGNumberFormat::kNEANonNegative,
TGNumberFormat::kNELLimitMinMax,
0, 65535);
hframe->AddFrame(dacsEntry,new TGLayoutHints(kLHintsTop | kLHintsExpandX, 5, 5, 5, 5));
dacsEntry->MapWindow();
dacsEntry->Resize(150,30);
dacsUnit= new TGCheckButton(hframe, "mV");
// if (idac!=slsDetectorDefs::ADC_VPP) {
hframe->AddFrame( dacsUnit,new TGLayoutHints(kLHintsTop | kLHintsLeft| kLHintsExpandX, 5, 5, 5, 5));
dacsUnit->MapWindow();
if (idac==slsDetectorDefs::ADC_VPP) {
dacsUnit->SetEnabled(kFALSE);
hframe->HideFrame(dacsUnit);
dacsUnit->MapWindow();
cout << "hiding!" << endl;
}
if (idac==slsDetectorDefs::HIGH_VOLTAGE) {
dacsUnit->SetText("V");
dacsUnit->SetOn(kTRUE,kTRUE);
dacsUnit->SetEnabled(kFALSE);
}
//}
sprintf(tit, "xxx");
dacsValue= new TGLabel(hframe, tit);
hframe->AddFrame( dacsValue,new TGLayoutHints(kLHintsTop | kLHintsLeft| kLHintsExpandX, 5, 5, 5, 5));
dacsValue->MapWindow();
dacsValue->SetTextJustify(kTextLeft);
TGTextEntry *e=dacsEntry->TGNumberEntry::GetNumberEntry();
e->Connect("ReturnPressed()","ctbDac",this,"setValue()");
// e->Connect("ValueSet(Long_t)","ctbDac",this,"setValue(Long_t)");
dacsEntry->Connect("ValueSet(Long_t)","ctbDac",this,"setValue(Long_t)");
// cout << "(((((((((((((((((((((((((((((((" << dacsEntry->GetListOfSignals()->At(0)->IsA() << endl;
}
int ctbDac::setLabel(char *tit, int mv) {
if(tit)
dacsLabel->SetText(tit);
if (mv==1)
dacsUnit->SetOn(kTRUE,kTRUE);
else if (mv==0)
dacsUnit->SetOn(kFALSE,kTRUE);
// else if (mv==2) {
// ;}
// else if (mv==3)
// ;
return id;
}
string ctbDac::getLabel() {
ostringstream line;
line << dacsLabel->GetText() << " " << dacsUnit->IsOn() << endl;
// line << "DAC" << dec << id << " " << dacsUnit->IsOn() << endl;
return line.str();
}
void ctbDac::setValue(Long_t a) {setValue();}
void ctbDac::setValue() {
cout << "setting dac! "<< id << " value " << dacsEntry->GetIntNumber() << " units " << dacsUnit->IsOn() << endl;
try {
myDet->setDAC(dacsEntry->GetIntNumber(), (slsDetectorDefs::dacIndex)id, dacsUnit->IsOn()); } catch (...) {
cout << "Do nothing for this error" << endl;
}
getValue();
}
void ctbDac::setOn(Bool_t b) {
// cout << "setting dac! "<< id << endl;
if ( dacsLabel->IsOn()) {
setValue();
} else {
try {
myDet->setDAC(-100, (slsDetectorDefs::dacIndex)id, 0);
} catch (...) {
cout << "Do nothing for this error" << endl;
}
}
getValue();
}
int ctbDac::getValue() {
int val;
try {
val=myDet->setDAC(-1,(slsDetectorDefs::dacIndex)id, dacsUnit->IsOn());
} catch (...) {
cout << "Do nothing for this error" << endl;
}
char s[100];
cout << "dac " << id << " " << val << endl;
sprintf(s,"%d",val);
dacsValue->SetText(s);
if (val>=0) {
dacsLabel->SetOn(kTRUE);
} else {
dacsLabel->SetOn(kFALSE);
}
return val;
}
ctbDacs::ctbDacs(TGVerticalFrame *page, multiSlsDetector *det) : TGGroupFrame(page,"DACs",kVerticalFrame) , myDet(det){
SetTitlePos(TGGroupFrame::kLeft);
page->AddFrame(this,new TGLayoutHints( kLHintsTop | kLHintsExpandX , 10,10,10,10));
MapWindow();
// cout << "window mapped " << endl;
for (int idac=0; idac<NDACS; idac++) {
dacs[idac]=new ctbDac(this, idac, myDet);
}
dacs[NDACS]=new ctbDac(this, slsDetectorDefs::ADC_VPP, myDet);
dacs[NDACS+1]=new ctbDac(this, slsDetectorDefs::HIGH_VOLTAGE, myDet);
dacs[NDACS]->setLabel("ADC Vpp",2);
dacs[NDACS+1]->setLabel("High Voltage",3);
}
int ctbDacs::setDacAlias(string line) {
int is=-1, mv=0;
char tit[100];
int narg=sscanf(line.c_str(),"DAC%d %s %d",&is,tit,&mv);
if (narg<2)
return -1;
if (is>=0 && is<NDACS)
dacs[is]->setLabel(tit,mv);
return is;
}
string ctbDacs::getDacAlias() {
ostringstream line;
for (int i=0; i<NDACS; i++)
line << dacs[i]->getLabel() << endl;
return line.str();
}
string ctbDacs::getDacParameters() {
ostringstream line;
for (int i=0; i<NDACS; i++) {
//line << "dacs:" << i << " " << dacs[i]->getValue << endl;
line << "dac:" << i << " " << dacs[i]->getValue() << endl;
}
return line.str();
}
void ctbDacs::update() {
for (int idac=0; idac<NDACS+1; idac++) {
dacs[idac]->getValue();
}
}

74
ctbGui/ctbDacs.h Executable file
View File

@@ -0,0 +1,74 @@
#ifndef CTBDACS_H
#define CTBDACS_H
#include <TGFrame.h>
#define NDACS 18
//#define NDACS 16
class TGTextEntry;
class TGLabel;
class TGNumberEntry;
class TGCheckButton;
class multiSlsDetector;
#include <string>
using namespace std;
class ctbDac : public TGHorizontalFrame {
protected:
// TGLabel *dacsLabel;
TGNumberEntry *dacsEntry;
TGCheckButton *dacsUnit;
TGCheckButton *dacsLabel;
TGLabel *dacsValue;
int id;
multiSlsDetector* myDet;
public:
ctbDac(TGGroupFrame*, int , multiSlsDetector*);
void setValue();
void setValue(Long_t);
int getValue();
void setOn(Bool_t);
int setLabel(char *tit, int mv);
string getLabel();
ClassDef(ctbDac,0)
};
class ctbDacs : public TGGroupFrame {
private:
ctbDac *dacs[NDACS+2];
multiSlsDetector* myDet;
public:
ctbDacs(TGVerticalFrame *page, multiSlsDetector*);
int setDacAlias(string line);
// int setDacAlias(string line);
string getDacAlias();
string getDacParameters();
void update();
ClassDef(ctbDacs,0)
};
#endif

161
ctbGui/ctbGui.cpp Executable file
View File

@@ -0,0 +1,161 @@
#include <TApplication.h>
#include <TColor.h>
#include <TStyle.h>
#include <TROOT.h>
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include "multiSlsDetector.h"
#include "sls_detector_defs.h"
//#include "sls_receiver_defs.h"
#include "ctbMain.h"
using namespace std;
int main(int argc, char **argv) {
string afname, cfname, pfname;
int id=0;
int af=0, cf=0, pf=0;
cout << " *** " << argc << endl;
for (int ia=0; ia<argc; ia++) {
if (strcmp(argv[ia],"-alias")==0) {
if (ia+1<argc) {
afname=argv[ia+1];
ia++;
af=1;
}
} else if (strcmp(argv[ia],"-config")==0) {
if (ia+1<argc) {
cfname=argv[ia+1];
ia++;
cf=1;
}
} else if (strcmp(argv[ia],"-par")==0) {
if (ia+1<argc) {
pfname=argv[ia+1];
ia++;
pf=1;
}
} else if (strcmp(argv[ia],"-id")==0) {
if (ia+1<argc) {
id=atoi(argv[ia+1]);
ia++;
}
}
}
cout << " *** " << endl;
/****** Create detector ****************/
multiSlsDetector *myDet=new multiSlsDetector(id);
myDet->setOnline(slsDetectorDefs::ONLINE_FLAG);
//cout << id << " " << myDet << " " << myDet->setOnline() << endl;
if (cf) {
myDet->readConfigurationFile(cfname);
} else
cout << "No config file specified" << endl;
cout << "aa" << endl;
cout << "Created multi detector id " << id << " hostname " << myDet->getHostname() << endl;
cout << "bb" << endl;
if (pf) {
myDet->retrieveDetectorSetup(pfname);
} else
cout << "No parameter file specified" << endl;
/***********Create GUI stuff *******************/
TApplication theApp("App",&argc,argv);
gStyle->SetDrawBorder(0);
gStyle->SetCanvasColor(kWhite);
gStyle->SetCanvasDefH(800);
gStyle->SetCanvasDefW(800);
gStyle->SetCanvasBorderMode(0);
gStyle->SetPadBorderMode(0);
gStyle->SetPaintTextFormat("5.2f");
gStyle->SetLineWidth(2);
gStyle->SetTextSize(1.1);
gStyle->SetLabelSize(0.04,"xy");
gStyle->SetTitleSize(0.05,"xy");
gStyle->SetTitleOffset(1.0,"x");
gStyle->SetTitleOffset(1.1,"y");
gStyle->SetPadTopMargin(0.15);
gStyle->SetPadRightMargin(0.15);
gStyle->SetPadBottomMargin(0.15);
gStyle->SetPadLeftMargin(0.15);
gStyle->SetLegendBorderSize(1);
gStyle->SetFrameBorderMode(0);
gStyle->SetFrameFillColor(kWhite);
// gStyle->SetLegendFillColor(kWhite);
gStyle->SetTitleFillColor(kWhite);
gStyle->SetFillColor(kWhite);
gStyle->SetStatFontSize(0.03);
gStyle->SetStatBorderSize(1);
gStyle->SetStatFormat("6.4g");
gStyle->SetStatX(0.95);
gStyle->SetStatY(0.95);
gStyle->SetStatW(0.2);
gStyle->SetStatH(0.2);
gStyle->SetTitleX(0.1);
gStyle->SetTitleY(0.95);
gStyle->SetTitleBorderSize(0);
gStyle->SetTitleFontSize(0.05);
gROOT->SetStyle("Default");
TColor::InitializeColors();
const Int_t NRGBs = 5;
const Int_t NCont = 90;
Double_t stops[NRGBs] = { 0.00, 0.34, 0.61, 0.84, 1.00 };
Double_t red[NRGBs] = { 0.00, 0.00, 0.87, 1.00, 0.51 };
Double_t green[NRGBs] = { 0.00, 0.81, 1.00, 0.20, 0.00 };
Double_t blue[NRGBs] = { 0.51, 1.00, 0.12, 0.00, 0.00 };
TColor::CreateGradientColorTable(NRGBs, stops, red, green, blue, NCont);
gStyle->SetNumberContours(NCont);
gROOT->ForceStyle();
ctbMain *mf=new ctbMain(gClient->GetRoot(),myDet);
cout << " *** " << argc << endl;
for (int ia=0; ia<argc; ia++)
cout << argv[ia] << endl;
cout << " *** " << endl;
if (af)
mf->loadAlias(afname);
else
cout << "no alias specified" << endl;
theApp.Run();
return 0;
}

15
ctbGui/ctbLinkDef.h Executable file
View File

@@ -0,0 +1,15 @@
#pragma link C++ class ctbMain;
#pragma link C++ class ctbDacs;
#pragma link C++ class ctbDac;
#pragma link C++ class ctbSignals;
#pragma link C++ class ctbSignal;
#pragma link C++ class ctbAdc;
#pragma link C++ class ctbAdcs;
#pragma link C++ class ctbLoop;
#pragma link C++ class ctbWait;
#pragma link C++ class ctbPattern;
#pragma link C++ class ctbAcquisition;
#pragma link C++ class ctbPower;
#pragma link C++ class ctbPowers;
#pragma link C++ class ctbSlowAdc;
#pragma link C++ class ctbSlowAdcs;

709
ctbGui/ctbMain.cpp Executable file
View File

@@ -0,0 +1,709 @@
#include <TApplication.h>
#include <TGClient.h>
#include <TCanvas.h>
#include <TF1.h>
#include <TRandom.h>
#include <TGButton.h>
#include <TRootEmbeddedCanvas.h>
#include <TGButtonGroup.h>
#include <TGNumberEntry.h>
#include <TGLabel.h>
#include <TList.h>
#include <TGFileDialog.h>
#include <TGComboBox.h>
#include <TH2F.h>
#include <TColor.h>
#include <TH1F.h>
#include <TGraphErrors.h>
#include <THStack.h>
#include <TGTab.h>
#include <TApplication.h>
#include <TGCanvas.h>
#include <stdlib.h>
#include <TGMenu.h>
#include <TGDockableFrame.h>
//#include <TGMenuBar.h>
//#include <TGPopupMenu.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include "multiSlsDetector.h"
#include "ctbMain.h"
#include "ctbDacs.h"
#include "ctbSlowAdcs.h"
#include "ctbPowers.h"
#include "ctbSignals.h"
#include "ctbPattern.h"
#include "ctbAdcs.h"
#include "ctbAcquisition.h"
//#include "ctbActions.h"
using namespace std;
ctbMain::ctbMain(const TGWindow *p, multiSlsDetector *det)
: TGMainFrame(p,800,800), pwrs(NULL), senses(NULL) {
myDet=det;
Connect("CloseWindow()", "ctbMain", this, "CloseWindow()");
// fMenuDock = new TGDockableFrame(this);
// AddFrame(fMenuDock, new TGLayoutHints(kLHintsExpandX, 0, 0, 1, 0));
// fMenuDock->SetWindowName("GuiTest Menu");
fMenuBarLayout = new TGLayoutHints(kLHintsTop | kLHintsExpandX);
fMenuBarItemLayout = new TGLayoutHints(kLHintsTop | kLHintsLeft, 0, 4, 0, 0);
fMenuBarHelpLayout = new TGLayoutHints(kLHintsTop | kLHintsRight);
fMenuFile = new TGPopupMenu(gClient->GetRoot());
int im=0;
fMenuFile->AddEntry("Open Alias", im++);
fMenuFile->AddEntry("Save Alias", im++);
fMenuFile->AddSeparator();
fMenuFile->AddEntry("Open Parameters", im++);
fMenuFile->AddEntry("Save Parameters", im++);
fMenuFile->AddSeparator();
fMenuFile->AddEntry("Open Configuration", im++);
fMenuFile->AddEntry("Save Configuration", im++);
fMenuFile->AddSeparator();
fMenuFile->AddEntry("Open Pattern", im++);
fMenuFile->AddEntry("Save Pattern", im++);
fMenuFile->AddSeparator();
fMenuFile->AddEntry("Exit", im++);
fMenuFile->Connect("Activated(Int_t)", "ctbMain", this,
"HandleMenu(Int_t)");
i_dacs=-1;
i_pwrs=-1;
i_senses=-1;
i_sig=-1;
i_adcs=-1;
i_pat=-1;
i_acq=-1;
int i_page=0;
TGVerticalFrame *vframe=new TGVerticalFrame(this, 800,1200); //main frame
fMenuBar = new TGMenuBar(vframe, 1, 1, kHorizontalFrame);
fMenuBar->AddPopup("&File", fMenuFile, fMenuBarItemLayout);
// fMenuBar->AddPopup("&Test", fMenuTest, fMenuBarItemLayout);
// fMenuBar->AddPopup("&View", fMenuView, fMenuBarItemLayout);
// fMenuBar->AddPopup("&Help", fMenuHelp, fMenuBarHelpLayout);
vframe->AddFrame(fMenuBar, fMenuBarLayout);
TGHorizontalFrame* hpage=new TGHorizontalFrame(vframe, 800,1200); //horizontal frame. Inside there should be the tab and the canvas
mtab=new TGTab(hpage, 1500, 1200); //tab!
// page=new TGVerticalFrame(mtab, 1500,1200);
cout << "DACS" << endl;
TGCompositeFrame *tf = mtab->AddTab("DACs");
TGVerticalFrame *page=new TGVerticalFrame(tf, 1500,1200);
tf->AddFrame(page, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY, 10,10,10,1));
dacs=new ctbDacs(page, myDet);
i_dacs=i_page++;
cout << "power " << endl;
tf = mtab->AddTab("Power Supplies");
page=new TGVerticalFrame(tf, 1500,1200);
tf->AddFrame(page, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY, 10,10,10,1));
pwrs=new ctbPowers(page, myDet);
i_pwrs=i_page++;
cout << "sense " << endl;
tf = mtab->AddTab("Sense");
page=new TGVerticalFrame(tf, 1500,1200);
tf->AddFrame(page, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY, 10,10,10,1));
senses=new ctbSlowAdcs(page, myDet);
i_senses=i_page++;
cout << "signals " << endl;
tf = mtab->AddTab("Signals");
page=new TGVerticalFrame(tf, 1500,1200);
tf->AddFrame(page, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY, 10,10,10,1));
sig=new ctbSignals(page, myDet);
sig->Connect("ToggledSignalPlot(Int_t)","ctbMain",this,"setSignalPlot(Int_t)");
i_sig=i_page++;
cout << "adcs " << endl;
tf = mtab->AddTab("ADCs");
page=new TGVerticalFrame(tf, 1500,1200);
tf->AddFrame(page, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY, 10,10,10,1));
adcs=new ctbAdcs(page, myDet);
adcs->Connect("ToggledAdcPlot(Int_t)","ctbMain",this,"setADCPlot(Int_t)");
adcs->Connect("AdcEnable(Int_t)","ctbMain",this,"setADCEnable(Int_t)");
i_adcs=i_page++;
cout << "pattern" << endl;
tf = mtab->AddTab("Pattern");
page=new TGVerticalFrame(tf, 1500,1200);
tf->AddFrame(page, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY, 10,10,10,1));
pat=new ctbPattern(page, myDet);
pat->Connect("patternFileChanged(const char*)","ctbMain",this,"setPatternFile(const char*)");
pat->Connect("patternCompilerChanged(const char*)","ctbMain",this,"setPatternCompiler(const char*)");
pat->Connect("analogSamplesChanged(const int)","ctbMain",this,"setAnalogSamples(int)");
pat->Connect("digitalSamplesChanged(const int)","ctbMain",this,"setDigitalSamples(int)");
pat->Connect("readoutModeChanged(int)","ctbMain",this,"setReadoutMode(int)");
i_pat=i_page++;
cout << "acquisition" << endl;
tf = mtab->AddTab("Acquisition");
page=new TGVerticalFrame(tf, 1500,1200);
tf->AddFrame(page, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY, 10,10,10,1));
acq=new ctbAcquisition(page, myDet);
i_acq=i_page++;
// cout << "actions" << endl;
// tf = mtab->AddTab("Actions");
// page=new TGVerticalFrame(tf, 1500,1200);
// tf->AddFrame(page, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY, 10,10,10,1));
// actions=new ctbActions(page, myDet);
// i_actions=i_page++;
cout << "tabs finished" << endl;
hpage->AddFrame(mtab,new TGLayoutHints(kLHintsExpandX | kLHintsExpandY, 10,10,10,1));
vframe->AddFrame(hpage,new TGLayoutHints(kLHintsExpandX | kLHintsExpandY, 10,10,10,1));
AddFrame(vframe,new TGLayoutHints(kLHintsExpandX | kLHintsExpandY, 10,10,10,1));
vframe->MapWindow();
hpage->MapWindow();
mtab->MapWindow();
page->MapWindow();
// Sets window name and shows the main frame
cout << "dockabel" << endl;
TGDockableFrame *fdock=new TGDockableFrame(hpage);
hpage->AddFrame(fdock, new TGLayoutHints(kLHintsBottom | kLHintsCenterX | kLHintsExpandX | kLHintsExpandY, 10,10,10,10));
fdock->MapWindow();
cout << "canvas" << endl;
// // Creates widgets of the example
fEcanvas = new TRootEmbeddedCanvas ("Ecanvas",fdock,800,800);//hpage,800,800);
//fEcanvas = new TRootEmbeddedCanvas ("Ecanvas",this,800,800);//hpage,800,800);
// fEcanvas->Resize();
// fEcanvas->GetCanvas()->Update();
//AddFrame(fEcanvas, new TGLayoutHints(kLHintsBottom | kLHintsCenterX | kLHintsExpandX | kLHintsExpandY, 10,10,10,10));
// // hpage->
fdock->AddFrame(fEcanvas, new TGLayoutHints(kLHintsBottom | kLHintsCenterX | kLHintsExpandX | kLHintsExpandY, 10,10,10,10));
fEcanvas->MapWindow();
acq->setCanvas(getCanvas());
hpage->MapSubwindows();
mtab->Connect("Selected(Int_t)","ctbMain",this,"tabSelected(Int_t)");
cout << "connect mtab" << endl;
setReadoutMode(pat->getReadoutMode());
setADCEnable(adcs->setEnable());
setAnalogSamples(pat->getAnalogSamples());
setDigitalSamples(pat->getDigitalSamples());
tabSelected(0);
SetWindowName("CTB Gui");
MapSubwindows();
Resize(1500,1200);
MapWindow();
}
void ctbMain::CloseWindow() {
gApplication->Terminate();
}
TCanvas* ctbMain::getCanvas() {
return fEcanvas->GetCanvas();
}
void ctbMain::HandleMenu(Int_t id)
{
// Handle menu items.
switch (id) {
case 0: // fMenuFile->AddEntry("Open Alias", im++);
cout << "Open Alias" << endl;
{
static TString dir(".");
TGFileInfo fi;
//fi.fFileTypes = filetypes;
fi.fIniDir = StrDup(dir);
printf("fIniDir = %s\n", fi.fIniDir);
new TGFileDialog(gClient->GetRoot(), this, kFDOpen, &fi);
printf("Open file: %s (dir: %s)\n", fi.fFilename);
// dir = fi.fIniDir;
if (fi.fFilename)
loadAlias(fi.fFilename);
}
break;
case 1: // fMenuFile->AddEntry("Save Alias", im++);
cout << "Save Alias" << endl;
{
static TString dir(".");
TGFileInfo fi;
//fi.fFileTypes = filetypes;
fi.fIniDir = StrDup(dir);
printf("fIniDir = %s\n", fi.fIniDir);
new TGFileDialog(gClient->GetRoot(), this, kFDSave, &fi);
printf("Save file: %s (dir: %s)\n", fi.fFilename);
// dir = fi.fIniDir;
if (fi.fFilename)
saveAlias(fi.fFilename);
}
break;
case 2: //fMenuFile->AddEntry("Open Parameters", im++);
cout << "Open Parameters" << endl;
{
static TString dir(".");
TGFileInfo fi;
//fi.fFileTypes = filetypes;
fi.fIniDir = StrDup(dir);
printf("fIniDir = %s\n", fi.fIniDir);
new TGFileDialog(gClient->GetRoot(), this, kFDOpen, &fi);
printf("Open file: %s (dir: %s)\n", fi.fFilename, fi.fIniDir);
// dir = fi.fIniDir;
if (fi.fFilename)
loadParameters(fi.fFilename);
}
break;
case 3: //fMenuFile->AddEntry("Save Parameters", im++);
cout << "Save Parameters" << endl;
{
static TString dir(".");
TGFileInfo fi;
//fi.fFileTypes = filetypes;
fi.fIniDir = StrDup(dir);
printf("fIniDir = %s\n", fi.fIniDir);
new TGFileDialog(gClient->GetRoot(), this, kFDSave, &fi);
printf("Open file: %s (dir: %s)\n", fi.fFilename, fi.fIniDir);
// dir = fi.fIniDir;
if (fi.fFilename)
saveParameters(fi.fFilename);
}
break;
case 4: // fMenuFile->AddEntry("Open Configuration", im++);
cout << "Open configuration" << endl;
{
static TString dir(".");
TGFileInfo fi;
//fi.fFileTypes = filetypes;
fi.fIniDir = StrDup(dir);
printf("fIniDir = %s\n", fi.fIniDir);
new TGFileDialog(gClient->GetRoot(), this, kFDOpen, &fi);
printf("Open file: %s (dir: %s)\n", fi.fFilename, fi.fIniDir);
// dir = fi.fIniDir;
if (fi.fFilename)
loadConfiguration(fi.fFilename);
}
break;
case 5: // fMenuFile->AddEntry("Save Configuration", im++);
cout << "Save configuration" << endl;
{
static TString dir(".");
TGFileInfo fi;
//fi.fFileTypes = filetypes;
fi.fIniDir = StrDup(dir);
printf("fIniDir = %s\n", fi.fIniDir);
new TGFileDialog(gClient->GetRoot(), this, kFDSave, &fi);
printf("Open file: %s (dir: %s)\n", fi.fFilename, fi.fIniDir);
// dir = fi.fIniDir;
if (fi.fFilename)
saveConfiguration(fi.fFilename);
}
break;
case 6: //fMenuFile->AddEntry("Open Pattern", im++);
cout << "Open pattern" << endl;
{
static TString dir(".");
TGFileInfo fi;
//fi.fFileTypes = filetypes;
fi.fIniDir = StrDup(dir);
printf("fIniDir = %s\n", fi.fIniDir);
new TGFileDialog(gClient->GetRoot(), this, kFDOpen, &fi);
printf("Open file: %s (dir: %s)\n", fi.fFilename, fi.fIniDir);
// dir = fi.fIniDir;
if (fi.fFilename)
loadParameters(fi.fFilename);
}
break;
case 7: //fMenuFile->AddEntry("Save Pattern", im++);
cout << "Save pattern" << endl;
{
static TString dir(".");
TGFileInfo fi;
//fi.fFileTypes = filetypes;
fi.fIniDir = StrDup(dir);
printf("fIniDir = %s\n", fi.fIniDir);
new TGFileDialog(gClient->GetRoot(), this, kFDSave, &fi);
printf("Open file: %s (dir: %s)\n", fi.fFilename, fi.fIniDir);
// dir = fi.fIniDir;
if (fi.fFilename)
saveParameters(fi.fFilename);
}
break;
case 8: // fMenuFile->AddEntry("Exit", im++);
CloseWindow();
default:
printf("Menu item %d selected\n", id);
break;
}
}
int ctbMain::setADCPlot(Int_t i) {
// cout << "ADC " << i << " plot or color toggled" << endl;
// acq->setGraph(i,adcs->getGraph(i));
acq->setGraph(i,adcs->getEnabled(i),adcs->getColor(i));
}
int ctbMain::setSignalPlot(Int_t i) {
// cout << "ADC " << i << " plot or color toggled" << endl;
// acq->setGraph(i,adcs->getGraph(i));
acq->setBitGraph(i,sig->getPlot(i),sig->getColor(i));
}
int ctbMain::loadConfiguration(string fname) {
myDet->readConfigurationFile(fname);
// string line;
// int i;
// ifstream myfile (fname.c_str());
// if (myfile.is_open())
// {
// while ( getline (myfile,line) )
// {
// }
// myfile.close();
// }
// else cout << "Unable to open file";
return 0;
}
int ctbMain::saveConfiguration(string fname) {
myDet->writeConfigurationFile(fname);
// string line;
// int i;
// ofstream myfile (fname.c_str());
// if (myfile.is_open())
// {
// myfile.close();
// }
// else cout << "Unable to open file";
return 0;
}
int ctbMain::loadParameters(string fname) {
myDet->retrieveDetectorSetup(fname);
// string line;
// int i;
// ifstream myfile (fname.c_str());
// if (myfile.is_open())
// {
// while ( getline (myfile,line) )
// {
// }
// myfile.close();
// }
// else cout << "Unable to open file";
return 0;
}
int ctbMain::saveParameters(string fname) {
string line;
int i;
myDet->dumpDetectorSetup(fname);
// ofstream myfile (fname.c_str());
// if (myfile.is_open())
// {
// myfile << dacs->getDacParameters();
// myfile << sig->getSignalParameters();
// myfile << adcs->getAdcParameters();
// myfile.close();
// }
// else cout << "Unable to open file";
return 0;
}
int ctbMain::loadAlias(string fname) {
string line;
char aaaa[1000];
int i;
ifstream myfile (fname.c_str());
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
// cout << line ;
if (sscanf(line.c_str(),"BIT%d",&i)>0) {
//cout << "*******" << line<< endl;
sig->setSignalAlias(line);
// cout << line ;
} else if (sscanf(line.c_str(),"DAC%d",&i)>0) {
dacs->setDacAlias(line);
// cout << "+++++++++" << line<< endl;
} else if (sscanf(line.c_str(),"ADC%d",&i)>0) {
adcs->setAdcAlias(line);
// cout << "---------" << line<< endl;
} // else
// cout << "<<<<<<<" << line << endl;
else if (sscanf(line.c_str(),"PAT%s",aaaa)>0) {
pat->setPatternAlias(line);
// cout << "---------" << line<< endl;
} else if (sscanf(line.c_str(),"V%s",&i)>0) {
if (pwrs) pwrs->setPwrAlias(line);
// cout << "+++++++++" << line<< endl;
} else if (sscanf(line.c_str(),"SENSE%d",&i)>0) {
if (senses) senses->setSlowAdcAlias(line);
// cout << "+++++++++" << line<< endl;
}
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
int ctbMain::saveAlias(string fname) {
string line;
int i;
ofstream myfile (fname.c_str());
if (myfile.is_open())
{
//while ( getline (myfile,line) )
// {
// cout << line ;
//if (sscanf(line.c_str(),"BIT%d",&i)>0) {
//cout << "*******" << line<< endl;
myfile << sig->getSignalAlias();
// cout << line ;
// } else if (sscanf(line.c_str(),"DAC%d",&i)>0) {
myfile << dacs->getDacAlias();
if (pwrs) myfile << pwrs->getPwrAlias();
if (senses) myfile << senses->getSlowAdcAlias();
// cout << "+++++++++" << line<< endl;
// } else if (sscanf(line.c_str(),"ADC%d",&i)>0) {
myfile << adcs->getAdcAlias();
// cout << "---------" << line<< endl;
// } // else
// cout << "<<<<<<<" << line << endl;
myfile << pat->getPatternAlias();
//}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
void ctbMain::tabSelected(Int_t i) {
// cout << "Selected tab " << i << endl;
// cout << "Current tab is " << mtab->GetCurrent() << endl;
if (i==i_dacs) dacs->update();
else if (i==i_pwrs) pwrs->update();
else if (i==i_senses) ;//senses->update();
else if (i==i_sig) sig->update();
else if (i==i_adcs) adcs->update();
else if (i==i_pat) pat->update();
else if (i==i_acq) acq->update();
else if (i==i_acq) acq->update();
// else if (i==i_actions) actions->update();
else cout << "Unknown tab " << i << endl;
}
void ctbMain::setPatternFile(const char* t) {
acq->setPatternFile(t);
}
void ctbMain::setPatternCompiler(const char* t) {
acq->setPatternCompiler(t);
}
void ctbMain::setAnalogSamples(const int n) {
acq->setAnalogSamples(n);
}
void ctbMain::setDigitalSamples(const int n) {
acq->setDigitalSamples(n);
}
void ctbMain::setReadoutMode(int flags) {
acq->setReadoutMode(flags);
}
void ctbMain::setADCEnable(Int_t reg){
acq->setADCEnable(reg);
}

126
ctbGui/ctbMain.h Executable file
View File

@@ -0,0 +1,126 @@
#ifndef CTBMAIN_H
#define CTBMAIN_H
#include <TGFrame.h>
class TRootEmbeddedCanvas;
class TGButtonGroup;
class TGVerticalFrame;
class TGHorizontalFrame;
class TGTextEntry;
class TGLabel;
class TGNumberEntry;
class TH2F;
class TGComboBox;
class TGCheckButton;
class THStack;
class TGraphErrors;
class TGTextButton;
class TGTab;
class TGMenuBar;
class TGPopupMenu;
class TGDockableFrame;
class TGLayoutHints;
class TGCanvas;
class TCanvas;
class ctbDacs;
class ctbSlowAdcs;
class ctbPowers;
class ctbSignals;
class multiSlsDetector;
class ctbPattern;
class ctbAdcs;
class ctbAcquisition;
//class ctbActions;
#include <string>
using namespace std;
class ctbMain : public TGMainFrame {
private:
multiSlsDetector *myDet;
TRootEmbeddedCanvas *fEcanvas;
TRootEmbeddedCanvas *fModulecanvas;
TGButtonGroup *br;
TGTab *mtab;
ctbDacs *dacs;
int i_dacs;
ctbPowers *pwrs;
int i_pwrs;
ctbSlowAdcs *senses;
int i_senses;
ctbSignals *sig;
int i_sig;
ctbAdcs *adcs;
int i_adcs;
ctbPattern *pat;
int i_pat;
ctbAcquisition *acq;
int i_acq;
// ctbActions *actions;
int i_actions;
TGDockableFrame *fMenuDock;
TGMenuBar *fMenuBar;
TGPopupMenu *fMenuFile, *fMenuTest, *fMenuView, *fMenuHelp;
TGPopupMenu *fCascadeMenu, *fCascade1Menu, *fCascade2Menu;
TGPopupMenu *fMenuNew1, *fMenuNew2;
TGLayoutHints *fMenuBarLayout, *fMenuBarItemLayout, *fMenuBarHelpLayout;
TGCanvas *myCanvas;
public:
ctbMain(const TGWindow *p, multiSlsDetector *det);
int loadAlias(string fname);
int saveAlias(string fname);
int loadParameters(string fname);
int saveParameters(string fname);
int loadConfiguration(string fname);
int saveConfiguration(string fname);
void tabSelected(Int_t);
int setADCPlot(Int_t);
int setSignalPlot(Int_t);
void CloseWindow();
void setPatternFile(const char* t);
void setPatternCompiler(const char* t);
void setAnalogSamples(const int);
void setDigitalSamples(const int);
void setReadoutMode(int);
void setADCEnable(Int_t);
void HandleMenu(Int_t);
TCanvas* getCanvas();
ClassDef(ctbMain,0)
};
#endif

1263
ctbGui/ctbPattern.cpp Executable file

File diff suppressed because it is too large Load Diff

176
ctbGui/ctbPattern.h Executable file
View File

@@ -0,0 +1,176 @@
#ifndef CTBPATTERN_H
#define CTBPATTERN_H
#include <TGFrame.h>
#define NLOOPS 3
#define NWAITS 3
#define NADCS 32
#define PATLEN 1024
class TRootEmbeddedCanvas;
class TGButtonGroup;
class TGVerticalFrame;
class TGHorizontalFrame;
class TGTextEntry;
class TGLabel;
class TGNumberEntry;
class TH2F;
class TGComboBox;
class TGCheckButton;
class TGTextEntry;
class TGCheckButton;
class THStack;
class TGraphErrors;
class energyCalibration;
class TGTextButton;
class TGTab;
class multiSlsDetector;
#include <string>
using namespace std;
class ctbLoop : public TGHorizontalFrame {
private:
TGNumberEntry *eLoopStartAddr;
TGNumberEntry *eLoopStopAddr;
TGNumberEntry *eLoopNumber;
int id;
multiSlsDetector *myDet;
public:
ctbLoop(TGGroupFrame *page, int i,multiSlsDetector *det);
void setNLoops();
void update();
ClassDef(ctbLoop,0)
};
class ctbWait : public TGHorizontalFrame {
private:
TGNumberEntry *eWaitAddr;
TGNumberEntry *eWaitTime;
int id;
multiSlsDetector *myDet;
public:
ctbWait(TGGroupFrame *page, int i,multiSlsDetector *det);
void setWaitTime();
void update();
ClassDef(ctbWait,0)
};
class ctbPattern : public TGGroupFrame {
private:
TGNumberEntry *eAdcClkFreq;
TGNumberEntry *eRunClkFreq;
TGNumberEntry *eDBitClkFreq;
TGNumberEntry *eAdcClkPhase;
TGNumberEntry *eDBitClkPhase;
//TGNumberEntry *eRunClkPhase;
TGNumberEntry *eStartAddr;
TGNumberEntry *eStopAddr;
TGNumberEntry *eFrames;
TGNumberEntry *ePeriod;
TGNumberEntry *eCycles;
TGNumberEntry *eMeasurements;
TGNumberEntry *eAdcPipeline;
TGNumberEntry *eDBitPipeline;
ctbLoop *eLoop[NLOOPS];
ctbWait *eWait[NWAITS];
TGTextEntry *patternCompiler;
TGTextEntry *patternFile;
TGTextButton *browseCompiler;
TGTextButton *browseFile;
TGNumberEntry *eAnalogSamples;
TGNumberEntry *eDigitalSamples;
TGCheckButton *cbAnalog;
TGCheckButton *cbDigital;
char pat[PATLEN*8];
multiSlsDetector *myDet;
public:
ctbPattern(TGVerticalFrame *page, multiSlsDetector *det);
void update();
void setAdcFreq();
void setRunFreq();
void setDBitFreq();
void setAdcPhase();
void setDBitPhase();
// void setRunPhase();
void setAdcPipeline();
void setDBitPipeline();
void setFrames();
void setCycles();
void setMeasurements();
void setPeriod();
void chooseCompiler();
void choosePattern();
string getCompiler();
string getPatternFile();
void setPatternAlias(string);
string getPatternAlias();
int getAnalogSamples();
void setAnalogSamples();
int getDigitalSamples();
void setDigitalSamples();
void setReadoutMode(Bool_t);
int getReadoutMode();
void setFile();
void setCompiler();
void patternFileChanged(const char*);
void patternCompilerChanged(const char*);
void analogSamplesChanged(const int t);
void digitalSamplesChanged(const int t);
void readoutModeChanged(int);
ClassDef(ctbPattern,0)
};
#endif

243
ctbGui/ctbPowers.cpp Normal file
View File

@@ -0,0 +1,243 @@
#include <TGFrame.h>
#include <TGButtonGroup.h>
#include <TGNumberEntry.h>
#include <TGLabel.h>
#include <TList.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include "ctbDacs.h"
#include "ctbPowers.h"
#include "multiSlsDetector.h"
#include "sls_detector_defs.h"
using namespace std;
ctbPower::ctbPower(TGGroupFrame* f, int i, multiSlsDetector* d)
: ctbDac(f, i, d)
{
cout << "****************************************************************power " << i << endl;
dacsUnit->SetOn(kTRUE);
dacsUnit->SetEnabled(kFALSE);
int ii=0;
switch(i) {
case slsDetectorDefs::V_POWER_IO:
dacsLabel->SetText("VIO");
ii=slsDetectorDefs::I_POWER_IO;
break;
case slsDetectorDefs::V_POWER_A:
dacsLabel->SetText("VA");
ii=slsDetectorDefs::I_POWER_A;
break;
case slsDetectorDefs::V_POWER_B:
dacsLabel->SetText("VB");
ii=slsDetectorDefs::I_POWER_B;
break;
case slsDetectorDefs::V_POWER_C:
dacsLabel->SetText("VC");
ii=slsDetectorDefs::I_POWER_C;
break;
case slsDetectorDefs::V_POWER_D:
dacsLabel->SetText("VD");
ii=slsDetectorDefs::I_POWER_D;
break;
case slsDetectorDefs::V_POWER_CHIP:
dacsLabel->SetText("VCHIP");
dacsLabel->SetEnabled(kFALSE);
ii=-1;
break;
default:
dacsLabel->SetText("Bad index");
ii=-1;
break;
};
// ctbSlowAdc *vm=new ctbSlowAdc(f,i,d);
// vm->setLabel("V: ");
// if (ii>=0) {
// ctbSlowAdc *im=new ctbSlowAdc(f,ii,d);
// im->setLabel("I: ");
// }
TGTextEntry *e=dacsEntry->TGNumberEntry::GetNumberEntry();
e->Disconnect ("ReturnPressed()");
e->Disconnect ("ValueSet(Long_t)");
e->Connect("ReturnPressed()","ctbPower",this,"setValue()");
dacsEntry->Connect("ValueSet(Long_t)","ctbPower",this,"setValue(Long_t)");
};
string ctbPower::getLabel() {
ostringstream line;
switch (id) {
case slsDetectorDefs::V_POWER_IO:
line << "VIO";
break;
case slsDetectorDefs::V_POWER_A:
line << "VA";
break;
case slsDetectorDefs::V_POWER_B:
line << "VB";
break;
case slsDetectorDefs::V_POWER_C:
line << "VC";
break;
case slsDetectorDefs::V_POWER_D:
line << "VD";
break;
case slsDetectorDefs::V_POWER_CHIP:
line << "VCHIP";
break;
default:
line << "VBAD";
break;
}
line << " " << dacsLabel->GetText() << endl;
return line.str();
}
void ctbPower::setValue(Long_t a) {cout << "ssssssssss" << endl; ctbPower::setValue();}
void ctbPower::setValue() {
cout << "***************************Setting power " << dacsEntry->GetIntNumber() << " " << (slsDetectorDefs::dacIndex)id <<" " << 1 << endl;
myDet->setDAC(dacsEntry->GetIntNumber(), (slsDetectorDefs::dacIndex)id, 1);
getValue();
}
int ctbPower::getValue() {
int val=myDet->setDAC(-1, (slsDetectorDefs::dacIndex)id, 1);
char s[100];
cout << "****************************Getting power " << val << " " << (slsDetectorDefs::dacIndex)id <<" " << 1 << endl;
sprintf(s,"%d",val);
dacsValue->SetText(s);
if (val>0) {
if (id!=slsDetectorDefs::V_POWER_CHIP)
dacsLabel->SetOn(kTRUE);
} else {
dacsLabel->SetOn(kFALSE);
}
return val;
}
ctbPowers::ctbPowers(TGVerticalFrame* page, multiSlsDetector* det) : TGGroupFrame(page,"Power Supplies",kVerticalFrame) , myDet(det){
SetTitlePos(TGGroupFrame::kLeft);
page->AddFrame(this,new TGLayoutHints( kLHintsTop | kLHintsExpandX , 10,10,10,10));
MapWindow();
// cout << "window mapped " << endl;
for (int idac=0; idac<NPOWERS; idac++) {
dacs[idac]=new ctbPower(this, slsDetectorDefs::V_POWER_A+idac, myDet);
}
}
int ctbPowers::setPwrAlias(string line) {
int is=-1, mv=0;
char tit[100];
int narg;
if (sscanf(line.c_str(),"VA %s",tit)) {
dacs[0]->setLabel(tit,1);
is=0;
}
if (sscanf(line.c_str(),"VB %s",tit)) {
dacs[1]->setLabel(tit,1);
is=1;
}
if (sscanf(line.c_str(),"VC %s",tit)) {
dacs[2]->setLabel(tit,1);
is=2;
}
if (sscanf(line.c_str(),"VD %s",tit)) {
dacs[3]->setLabel(tit,1);
is=3;
}
if (sscanf(line.c_str(),"VIO %s",tit)) {
dacs[4]->setLabel(tit,1);
is=4;
}
if (sscanf(line.c_str(),"VCHIP %s",tit)) {
dacs[5]->setLabel(tit,1);
is=5;
}
return is;
}
string ctbPowers::getPwrAlias() {
ostringstream line;
for (int i=0; i<NPOWERS; i++)
line << dacs[i]->getLabel() << endl;
return line.str();
}
string ctbPowers::getPwrParameters() {
ostringstream line;
line << "v_a" << " " << dacs[0]->getValue() << " mv" << endl;
line << "v_b" << " " << dacs[1]->getValue() << " mv" << endl;
line << "v_c" << " " << dacs[2]->getValue() << " mv" << endl;
line << "v_d" << " " << dacs[3]->getValue() << " mv" << endl;
line << "v_io" << " " << dacs[4]->getValue() << " mv" << endl;
line << "v_chip" << " " << dacs[5]->getValue() << " mv" << endl;
// for (int i=0; i<POWERS; i++) {
// //line << "dacs:" << i << " " << dacs[i]->getValue << endl;
// line << "dac:" << i << " " << dacs[i]->getValue() << endl;
// }
return line.str();
}
void ctbPowers::update() {
for (int idac=0; idac<NPOWERS; idac++) {
dacs[idac]->getValue();
}
}

72
ctbGui/ctbPowers.h Normal file
View File

@@ -0,0 +1,72 @@
#ifndef CTBPOWERS_H
#define CTBPOWERS_H
#include <TGFrame.h>
#ifndef CTB
#define NPOWERS 0
#else
#define NPOWERS 6
#endif
class TGTextEntry;
class TGLabel;
class TGNumberEntry;
class TGCheckButton;
class multiSlsDetector;
#include <string>
using namespace std;
class ctbPower : public ctbDac {
public:
ctbPower(TGGroupFrame* f, int i, multiSlsDetector* d);
string getLabel();
int getValue();
void setValue();
void setValue(Long_t);
ClassDef(ctbPower,0)
};
class ctbPowers : public TGGroupFrame
{
private:
ctbPower *dacs[NPOWERS];
multiSlsDetector* myDet;
public:
//ctbPowers();
ctbPowers(TGVerticalFrame*, multiSlsDetector*);
int setPwrAlias(string);
string getPwrAlias();
string getPwrParameters();
void update();
ClassDef(ctbPowers,0)
};
#endif

548
ctbGui/ctbSignals.cpp Executable file
View File

@@ -0,0 +1,548 @@
#include <TApplication.h>
#include <TGClient.h>
#include <TCanvas.h>
#include <TF1.h>
#include <TRandom.h>
#include <TGButton.h>
#include <TRootEmbeddedCanvas.h>
#include <TGButtonGroup.h>
#include <TGNumberEntry.h>
#include <TGLabel.h>
#include <TList.h>
#include <TGFileDialog.h>
#include <TGComboBox.h>
#include <TH2F.h>
#include <TColor.h>
#include <TH1F.h>
#include <TGraphErrors.h>
#include <THStack.h>
#include <TGTab.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <TGButton.h>
#include <TRootEmbeddedCanvas.h>
#include <TGButtonGroup.h>
#include <TGNumberEntry.h>
#include <TGLabel.h>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <TColor.h>
#include <TGColorSelect.h>
#include "ctbSignals.h"
#include "multiSlsDetector.h"
using namespace std;
//#define DEFAULTFN "run_0.encal"
ctbSignal::ctbSignal(TGFrame *page, int i, multiSlsDetector *det)
: TGHorizontalFrame(page, 800,50), myDet(det), id(i), hsig(NULL) {
TGHorizontalFrame *hframe=this;
char tit[100];
sprintf(tit, "BIT%d ",id);
sLabel= new TGLabel(hframe, tit);
hframe->AddFrame( sLabel,new TGLayoutHints(kLHintsTop | kLHintsLeft| kLHintsExpandX, 1, 1, 1, 1));
sLabel->MapWindow();
sLabel->SetTextJustify(kTextLeft);
sOutput= new TGCheckButton(hframe, "Out");
hframe->AddFrame( sOutput,new TGLayoutHints(kLHintsTop | kLHintsLeft| kLHintsExpandX, 1, 1, 1, 1));
sOutput->MapWindow();
sOutput->Connect("Toggled(Bool_t)","ctbSignal",this,"ToggledOutput(Bool_t)");
sDbitList= new TGCheckButton(hframe, "DB List");
hframe->AddFrame( sDbitList,new TGLayoutHints(kLHintsTop | kLHintsLeft| kLHintsExpandX, 1, 1, 1, 1));
sDbitList->MapWindow();
sDbitList->Connect("Toggled(Bool_t)","ctbSignal",this,"ToggledDbitList(Bool_t)");
sPlot= new TGCheckButton(hframe, "Plot");
hframe->AddFrame( sPlot,new TGLayoutHints(kLHintsTop | kLHintsLeft| kLHintsExpandX, 1, 1, 1, 1));
sPlot->MapWindow();
sPlot->Connect("Toggled(Bool_t)","ctbSignal",this,"ToggledPlot(Bool_t)");
fColorSel = new TGColorSelect(hframe, id+1, 0);
fColorSel->Connect("ColorSelected(Pixel_t)","ctbSignal",this,"ColorChanged(Pixel_t)");
hframe->AddFrame(fColorSel, new TGLayoutHints(kLHintsTop |
kLHintsLeft, 2, 0, 2, 2));
fColorSel->SetColor(TColor::Number2Pixel(id+1));
ToggledOutput(kFALSE);
ToggledPlot(kFALSE);
// if (id==63) {
// sOutput->SetOn(kTRUE);
// sOutput->SetEnabled(kFALSE);
// }
// #ifdef CTB
// if (id==62) {
// sOutput->SetOn(kTRUE);
// sOutput->SetEnabled(kFALSE);
// }
// // if (id>=32 && id<48)
// // fixOutput(1);
// // else if (id>=48 && id<64)
// // fixOutput(0);
// #endif
}
int ctbSignal::setSignalAlias(char *tit, int plot, int col) {
if (tit)
sLabel->SetText(tit);
if (plot>0) {
sPlot->SetOn(kTRUE,kTRUE);
} else if (plot==0)
sPlot->SetOn(kFALSE,kTRUE);
if (col>=0)
fColorSel->SetColor(col);//TColor::Number2Pixel(col+1));
fColorSel->SetEnabled(sPlot->IsOn());
return 0;
}
string ctbSignal::getSignalAlias() {
ostringstream oss;
oss << "BIT" << dec << id << " " << sLabel->GetText()->Data() << " " << sPlot->IsOn() << hex << " " << fColorSel->GetColor() << endl;
return oss.str();
}
int ctbSignal::setOutput(Long64_t r) {
// cout << hex << r << dec <<endl;
Long64_t mask=((Long64_t)1<<id);
if (r&mask)
sOutput->SetOn(kTRUE,kTRUE);
else
sOutput->SetOn(kFALSE,kTRUE);
return sOutput->IsOn();
}
int ctbSignal::fixOutput(int i) {
if (i) {
sPlot->SetOn(kFALSE);
//sClock->SetOn(kFALSE,kTRUE);
sOutput->SetOn(kTRUE);
// sPlot->SetEnabled(kFALSE);
// sClock->SetEnabled(kTRUE);
} else {
sOutput->SetOn(kFALSE,kTRUE);
// sClock->SetOn(kFALSE);
// sClock->SetEnabled(kFALSE);
sPlot->SetEnabled(kTRUE);
}
sOutput->SetEnabled(kFALSE);
return 0;
}
int ctbSignal::setDbitList(Long64_t r) {
Long64_t mask=((Long64_t)1<<id);
// cout << hex << r << dec <<endl;
if (r)
sDbitList->SetOn(kTRUE,kFALSE);
else
sDbitList->SetOn(kFALSE,kFALSE);
return sDbitList->IsOn();
}
int ctbSignal::isDbitList() { return sDbitList->IsOn();}
int ctbSignal::isOutput() { return sOutput->IsOn();}
int ctbSignal::isPlot() { return sPlot->IsOn();}
Pixel_t ctbSignal::getColor(){return fColorSel->GetColor();}
void ctbSignal::ToggledOutput(Bool_t b) {
Long_t mask=b<<id;
ToggledSignalOutput(id);
if (b) {
// sClock->SetEnabled(kTRUE);
sPlot->SetOn(kFALSE);
// sPlot->SetEnabled(kFALSE);
fColorSel->SetEnabled(kFALSE);
} else {
// sClock->SetEnabled(kFALSE);
// sClock->SetOn(kFALSE);
sPlot->SetEnabled(kTRUE);
if ( sPlot->IsOn())
fColorSel->SetEnabled(kFALSE);
else
fColorSel->SetEnabled(kTRUE);
}
}
void ctbSignal::ToggledDbitList(Bool_t b){
Long_t mask=id;
ToggledSignalDbitList(mask);
}
void ctbSignal::ToggledPlot(Bool_t b){
Long_t mask=b<<id;
ToggledSignalPlot(mask);
fColorSel->SetEnabled(b);
}
void ctbSignal::ColorChanged(Pixel_t p){
ToggledSignalPlot(id);
}
void ctbSignal::ToggledSignalOutput(Int_t b) {
cout << "Toggle signal " << id << " " << b << " " << sOutput->IsOn() <<endl;;
Emit("ToggledSignalOutput(Int_t)", id);
}
void ctbSignal::ToggledSignalDbitList(Int_t b){
cout << "Toggle dbitlist " << id << " " << b << endl;;
Emit("ToggledSignalDbitList(Int_t)", id);
}
void ctbSignal::ToggledSignalPlot(Int_t b){
Emit("ToggledSignalPlot(Int_t)", id);
}
ctbSignals::ctbSignals(TGVerticalFrame *page, multiSlsDetector *det)
: TGGroupFrame(page,"IO Signals",kVerticalFrame), myDet(det) {
SetTitlePos(TGGroupFrame::kLeft);
page->AddFrame(this,new TGLayoutHints( kLHintsTop | kLHintsExpandX , 10,10,10,10));
MapWindow();
TGHorizontalFrame *hframe;
char tit[100];
TGHorizontalFrame* hhframe=new TGHorizontalFrame(this, 800,800);
AddFrame(hhframe,new TGLayoutHints(kLHintsTop | kLHintsExpandX , 1,1,1,1));
hhframe->MapWindow();
TGVerticalFrame *vframe;
int idac=0;
for (idac=0; idac<NSIGNALS; idac++) {
if (idac%((NSIGNALS+2)/2)==0) {
vframe=new TGVerticalFrame(hhframe, 400,800);
hhframe->AddFrame(vframe,new TGLayoutHints(kLHintsTop | kLHintsExpandX , 1,1,1,1));
vframe->MapWindow();
}
signals[idac]=new ctbSignal(vframe,idac,myDet);
signals[idac]->Connect("ToggledSignalOutput(Int_t)","ctbSignals",this,"ToggledOutReg(Int_t)");
signals[idac]->Connect("ToggledSignalDbitList(Int_t)","ctbSignals",this,"ToggledDbitList(Int_t)");
signals[idac]->Connect("ToggledSignalPlot(Int_t)","ctbSignals",this,"ToggledPlot(Int_t)");
vframe->AddFrame(signals[idac],new TGLayoutHints(kLHintsTop | kLHintsExpandX , 1,1,1,1));
signals[idac]->MapWindow();
}
// #ifdef CTB
// idac=62;
// signals[idac]=new ctbSignal(vframe,idac,myDet);
// vframe->AddFrame(signals[idac],new TGLayoutHints(kLHintsTop | kLHintsExpandX , 1,1,1,1));
// signals[idac]->MapWindow();
// sprintf(tit,"DBIT Latch");
// signals[idac]->setSignalAlias(tit,-1,-1);
// signals[idac]->Connect("ToggledSignalOutput(Int_t)","ctbSignals",this,"ToggledOutReg(Int_t)");
// signals[idac]->Connect("ToggledSignalDbitList(Int_t)","ctbSignals",this,"ToggledDbitList(Int_t)");
// signals[idac]->Connect("ToggledSignalPlot(Int_t)","ctbSignals",this,"ToggledPlot(Int_t)");
// #endif
// idac=63;
// signals[idac]=new ctbSignal(vframe,idac,myDet);
// vframe->AddFrame(signals[idac],new TGLayoutHints(kLHintsTop | kLHintsExpandX , 1,1,1,1));
// signals[idac]->MapWindow();
// sprintf(tit,"ADC Latch");
// signals[idac]->setSignalAlias(tit,-1,-1);
// signals[idac]->Connect("ToggledSignalOutput(Int_t)","ctbSignals",this,"ToggledOutReg(Int_t)");
// signals[idac]->Connect("ToggledSignalDbitList(Int_t)","ctbSignals",this,"ToggledDbitList(Int_t)");
// signals[idac]->Connect("ToggledSignalPlot(Int_t)","ctbSignals",this,"ToggledPlot(Int_t)");
hframe=new TGHorizontalFrame(vframe, 800,50);
vframe->AddFrame(hframe,new TGLayoutHints(kLHintsTop | kLHintsExpandX , 1,1,1,1));
hframe->MapWindow();
TGLabel *label= new TGLabel(hframe, "IO Control Register: ");
hframe->AddFrame(label,new TGLayoutHints(kLHintsTop | kLHintsLeft| kLHintsExpandX, 1, 1, 1, 1));
label->MapWindow();
label->SetTextJustify(kTextLeft);
eIOCntrlRegister = new TGNumberEntry(hframe, 0, 16,999, TGNumberFormat::kNESHex,
TGNumberFormat::kNEANonNegative,
TGNumberFormat::kNELNoLimits);
hframe->AddFrame(eIOCntrlRegister,new TGLayoutHints(kLHintsTop | kLHintsExpandX, 1, 1, 1, 1));
eIOCntrlRegister->MapWindow();
eIOCntrlRegister->Resize(150,30);
hframe=new TGHorizontalFrame(vframe, 800,50);
vframe->AddFrame(hframe,new TGLayoutHints(kLHintsTop | kLHintsExpandX , 1,1,1,1));
hframe->MapWindow();
label= new TGLabel(hframe, "DBit Offset: ");
hframe->AddFrame(label,new TGLayoutHints(kLHintsTop | kLHintsLeft| kLHintsExpandX, 1, 1, 1, 1));
label->MapWindow();
label->SetTextJustify(kTextLeft);
eDbitOffset = new TGNumberEntry(hframe, 0, 9,999, TGNumberFormat::kNESInteger,
TGNumberFormat::kNEANonNegative,
TGNumberFormat::kNELNoLimits);
hframe->AddFrame(eDbitOffset,new TGLayoutHints(kLHintsTop | kLHintsExpandX, 1, 1, 1, 1));
eDbitOffset->MapWindow();
eDbitOffset->Resize(150,30);
TGTextEntry *e= eDbitOffset->TGNumberEntry::GetNumberEntry();
e->Connect("ReturnPressed()","ctbSignals",this,"setDbitOffset()");
e->Connect("ValueSet(Long_t)","ctbSignals",this,"setDbitOffset(Long_t)");
}
int ctbSignals::setSignalAlias(string line) {
int is=-1, plot=0, col=-1;
char tit[100];
int narg=sscanf(line.c_str(),"BIT%d %s %d %d",&is,tit,&plot,&col);
if (narg<2)
return -1;
if (is>=0 && is<NIOSIGNALS) {
signals[is]->setSignalAlias(tit,plot,col);
}
return is;
}
string ctbSignals::getSignalAlias() {
ostringstream oss;
for (int is=0; is<NIOSIGNALS; is++)
oss << signals[is]->getSignalAlias() << endl;
return oss.str();
}
void ctbSignals::update() {
Long64_t oreg=myDet->setPatternIOControl();//setCTBWord(-1,-1);
// Long64_t creg=myDet->setPatternClockControl();//setCTBWord(-2,-1);
char val[1000];
cout << hex << oreg << dec << endl;
// cout << hex << creg << dec << endl;
sprintf(val,"%llX",oreg);
// eIOCntrlRegister->SetHexNumber(oreg);
for (int idac=0; idac<NIOSIGNALS; idac++) {
signals[idac]->setOutput(oreg);
}
Long64_t mask;
std::vector <int> dbitlist=myDet->getReceiverDbitList();
if (dbitlist.empty())
for (int is=0; is<64; is++) {
signals[is]->setDbitList(1);
}
else {
for (int is=0; is<64; is++) signals[is]->setDbitList(0);
for (const auto &value : dbitlist) {
signals[value]->setDbitList(1);
}
}
eDbitOffset->SetNumber(myDet->getReceiverDbitOffset());
}
string ctbSignals::getSignalParameters() {
ostringstream line;
line << "patioctrl " << hex << myDet->setPatternIOControl() << dec << endl;//setCTBWord(-1,-1)
return line.str();
}
void ctbSignals::ToggledOutReg(Int_t mask) {
char val[1000];
Long64_t oreg=myDet->setPatternIOControl();//setCTBWord(-1,-1);
Long64_t m=((Long64_t)1)<<mask;
cout << dec << sizeof(Long64_t) << " " << mask << " " << hex << m << " ioreg " << oreg;
if (signals[mask]->isOutput()) {
cout << " or " << m ;
oreg|=m;
} else {
cout << " not " << ~m ;
oreg&=~m;
}
cout << " after " << oreg << endl;
myDet->setPatternIOControl(oreg);//setCTBWord(-1,oreg);
oreg=myDet->setPatternIOControl();//myDet->setCTBWord(-1,-1);
cout << dec << sizeof(Long64_t) << " " << mask << " " << hex << m << " ioreg " << oreg << endl;
sprintf(val,"%llX",oreg);
// eIOCntrlRegister->SetHexNumber(oreg);
eIOCntrlRegister->SetText(val);
// eIOCntrlRegister->SetNumber(oreg);
}
void ctbSignals::ToggledDbitList(Int_t mask){
cout << "************* Here" << endl;
std::vector <int> new_dbitlist;
std::vector <int> old_dbitlist=myDet->getReceiverDbitList();
char val[1000];
Long64_t m=((Long64_t)1)<<mask;
if (old_dbitlist.empty() && signals[mask]->isDbitList())
;
else {
int ns=0;
for (int is=0; is<64; is++) {
if (signals[is]->isDbitList()){
new_dbitlist.push_back(is);
ns++;
cout << is << " " << ns << endl;
}
}
if (ns>63) new_dbitlist.clear();
myDet->setReceiverDbitList(new_dbitlist);
}
std::vector <int> dbitlist=myDet->getReceiverDbitList();
if (dbitlist.empty())
for (int is=0; is<64; is++) signals[is]->setDbitList(1);
else
for (int is=0; is<64; is++) signals[is]->setDbitList(0);
for (const auto &value : dbitlist) signals[value]->setDbitList(1);
}
void ctbSignals::ToggledPlot(Int_t b) {
Emit("ToggledSignalPlot(Int_t)", b);
}
void ctbSignals::ToggledSignalPlot(Int_t b) {
Emit("ToggledSignalPlot(Int_t)", b);
}
Pixel_t ctbSignals::getColor(int i){
if (i>=0 && i<NSIGNALS) return signals[i]->getColor();
}
int ctbSignals::getPlot(int i){
if (i>=0 && i<NSIGNALS) return signals[i]->isPlot();
};
void ctbSignals::setDbitOffset(Long_t) {
setDbitOffset();
}
void ctbSignals::setDbitOffset(){
myDet->setReceiverDbitOffset(eDbitOffset->GetNumber());
}

118
ctbGui/ctbSignals.h Executable file
View File

@@ -0,0 +1,118 @@
#ifndef CTBSIGNALS_H
#define CTBSIGNALS_H
#include <TGFrame.h>
#define NSIGNALS 64
#define NIOSIGNALS 64 //for moench board was 52
#define ADCLATCH 63
#define DIGSIGLATCH 62
class TGTextEntry;
class TGLabel;
class TGNumberEntry;
class TGCheckButton;
class TH1I;
class TGTextButton;
class TGColorSelect;
class TGNumberEntry;
class multiSlsDetector;
class ctbSignal;
#include <string>
using namespace std;
class ctbSignal : public TGHorizontalFrame {
// RQ_OBJECT("ctbSignal")
private:
TGLabel *sLabel;
TGCheckButton *sOutput;
TGCheckButton *sDbitList;
TGCheckButton *sPlot;
TGLabel *sValue;
TGNumberEntry *sEntry;
TGColorSelect *fColorSel;
multiSlsDetector *myDet;
Int_t id;
TH1I *hsig;
public:
ctbSignal(TGFrame *page, int i, multiSlsDetector *det);
int setSignalAlias(char *tit, int plot, int col);
string getSignalAlias();
TH1I *getPlot() {return hsig;};
int setOutput(Long64_t);
int fixOutput(int);
int setDbitList(Long64_t);
void ToggledOutput(Bool_t);
void ToggledDbitList(Bool_t);
void ToggledPlot(Bool_t);
void ColorChanged(Pixel_t);
int isDbitList();
int isOutput();
int isPlot();
Pixel_t getColor();
void ToggledSignalOutput(Int_t); //*SIGNAL*
void ToggledSignalDbitList(Int_t); //*SIGNAL*
void ToggledSignalPlot(Int_t); //*SIGNAL*
ClassDef(ctbSignal,0)
};
class ctbSignals : public TGGroupFrame {
private:
ctbSignal *signals[NSIGNALS];
TGNumberEntry *eIOCntrlRegister;
TGNumberEntry *eDbitOffset;
multiSlsDetector *myDet;
public:
ctbSignals(TGVerticalFrame *page, multiSlsDetector *det);
int setSignalAlias(string line);
string getSignalAlias();
int getPlot(int);
Pixel_t getColor(int);
void update();
// void saveParameters();
string getSignalParameters();
//void setDbitList(Int_t);
void setDbitOffset(Long_t);
void setDbitOffset();
void ToggledOutReg(Int_t);
void ToggledDbitList(Int_t);
void ToggledPlot(Int_t);
void ToggledSignalPlot(Int_t); //*SIGNAL*
ClassDef(ctbSignals,0)
};
#endif

185
ctbGui/ctbSlowAdcs.cpp Normal file
View File

@@ -0,0 +1,185 @@
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <TGTextEntry.h>
#include <TGLabel.h>
#include <TGNumberEntry.h>
#include <TGButton.h>
#include "ctbSlowAdcs.h"
#include "multiSlsDetector.h"
#include "sls_detector_defs.h"
using namespace std;
ctbSlowAdc::ctbSlowAdc(TGGroupFrame *page, int idac, multiSlsDetector *det) : TGHorizontalFrame(page, 800,50) , id(idac), myDet(det) {
TGHorizontalFrame *hframe=this;
page->AddFrame(hframe,new TGLayoutHints(kLHintsTop | kLHintsExpandX , 1,1,1,1));
MapWindow();
char tit[100];
sprintf(tit, "SENSE %d:",idac-1000);
dacsLabel= new TGLabel(hframe, tit);// new TGLabel(hframe, tit);
hframe->AddFrame(dacsLabel,new TGLayoutHints(kLHintsTop | kLHintsLeft| kLHintsExpandX, 5, 5, 5, 5));
dacsLabel->MapWindow();
dacsLabel->SetTextJustify(kTextLeft);
sprintf(tit, "xxx");
dacsValue= new TGLabel(hframe, tit);
hframe->AddFrame( dacsValue,new TGLayoutHints(kLHintsTop | kLHintsLeft| kLHintsExpandX, 5, 5, 5, 5));
dacsValue->MapWindow();
dacsValue->SetTextJustify(kTextLeft);
TGTextButton *b= new TGTextButton(hframe, "Update");
hframe->AddFrame( b,new TGLayoutHints(kLHintsTop | kLHintsLeft| kLHintsExpandX, 5, 5, 5, 5));
b->MapWindow();
b->SetTextJustify(kTextLeft);
b->Connect("Clicked()","ctbSlowAdc",this,"getValue()");
}
int ctbSlowAdc::setLabel(char *tit) {
if(tit)
dacsLabel->SetText(tit);
return id;
}
string ctbSlowAdc::getLabel() {
ostringstream line;
line << dacsLabel->GetText() << endl;
// line << "DAC" << dec << id << " " << dacsUnit->IsOn() << endl;
return line.str();
}
int ctbSlowAdc::getValue() {
int val=myDet->getADC((slsDetectorDefs::dacIndex)id);
char s[100];
cout << "adc " << id << " " << val << endl;
sprintf(s,"%d mV",val);
if (id==999)
sprintf(s,"%d <20>C",val);
dacsValue->SetText(s);
return val;
}
ctbSlowAdcs::ctbSlowAdcs(TGVerticalFrame *page, multiSlsDetector *det) : TGGroupFrame(page,"Sense",kVerticalFrame) , myDet(det){
SetTitlePos(TGGroupFrame::kLeft);
page->AddFrame(this,new TGLayoutHints( kLHintsTop | kLHintsExpandX , 10,10,10,10));
MapWindow();
// cout << "window mapped " << endl;
for (int idac=0; idac<NSLOWADCS; idac++) {
adcs[idac]=new ctbSlowAdc(this, idac+1000, myDet);
}
adcs[NSLOWADCS]=new ctbSlowAdc(this, 999, myDet);
adcs[NSLOWADCS]->setLabel("Temperature");
}
int ctbSlowAdcs::setSlowAdcAlias(string line) {
int is=-1, mv=0;
char tit[100];
int narg=sscanf(line.c_str(),"SENSE%d %s",&is,tit,&mv);
if (narg<2)
return -1;
if (is>=0 && is<NSLOWADCS)
adcs[is]->setLabel(tit);
return is;
}
string ctbSlowAdcs::getSlowAdcAlias() {
ostringstream line;
for (int i=0; i<NSLOWADCS; i++)
line << adcs[i]->getLabel() << endl;
return line.str();
}
string ctbSlowAdcs::getAdcParameters() {
ostringstream line;
for (int i=0; i<NSLOWADCS; i++) {
//line << "dacs:" << i << " " << dacs[i]->getValue << endl;
line << "adc:" << i << " " << adcs[i]->getValue() << endl;
}
line << "adc:-1" << adcs[NSLOWADCS]->getValue() << endl;
return line.str();
}
void ctbSlowAdcs::update() {
for (int idac=0; idac<NSLOWADCS+1; idac++) {
adcs[idac]->getValue();
}
}

75
ctbGui/ctbSlowAdcs.h Normal file
View File

@@ -0,0 +1,75 @@
#ifndef CTBSLOWADCS_H
#define CTBSLOWADCS_H
#include <TGFrame.h>
//#define NDACS 16
#define NSLOWADCS 8
class TGTextEntry;
class TGLabel;
class TGNumberEntry;
class TGCheckButton;
class TGTextButton;
class multiSlsDetector;
#include <string>
using namespace std;
class ctbSlowAdc : public TGHorizontalFrame {
protected:
// TGLabel *dacsLabel;
// TGNumberEntry *dacsEntry;
// TGCheckButton *dacsUnit;
TGLabel *dacsLabel;
TGLabel *dacsValue;
int id;
multiSlsDetector* myDet;
public:
ctbSlowAdc(TGGroupFrame*, int , multiSlsDetector*);
int getValue();
int setLabel(char *tit);
string getLabel();
ClassDef(ctbSlowAdc,0)
};
class ctbSlowAdcs : public TGGroupFrame {
private:
ctbSlowAdc *adcs[NSLOWADCS+1];
multiSlsDetector* myDet;
public:
ctbSlowAdcs(TGVerticalFrame *page, multiSlsDetector*);
int setSlowAdcAlias(string line);
// int setDacAlias(string line);
string getSlowAdcAlias();
string getAdcParameters();
void update();
ClassDef(ctbSlowAdcs,0)
};
#endif

View File

@@ -0,0 +1,110 @@
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <sys/utsname.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <math.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
int iarg;
char fname[10000];
uint64_t word;
int val[64];
int bit[64];
FILE *fdin;
int nb=2;
int off=0;
int ioff=0;
int dr=24;
int idr=0;
int ib=0;
int iw=0;
bit[0]=19;
bit[1]=8;
// for (iarg=0; iarg<argc; iarg++) printf("%d %s\n",iarg, argv[iarg]);
if (argc<2) printf("Error: usage is %s fname [dr off b0 b1 bn]\n");
if (argc>2) dr=atoi(argv[2]);
if (argc>3) off=atoi(argv[3]);
if (argc>4) {
for (ib=0; ib<64; ib++) {
if (argc>4+ib) {
bit[ib]=atoi(argv[4+ib]);
nb++;
}
}
}
idr=0;
for (ib=0; ib<nb; ib++) {
val[ib]=0;
}
fdin=fopen(argv[1],"rb");
if (fdin==NULL) {
printf("Cannot open input file %s for reading\n",argv[1]);
return 200;
}
while (fread((void*)&word, 8, 1, fdin)) {
// printf("%llx\n",word);
if (ioff<off) ioff++;
else {
for (ib=0; ib<nb; ib++) {
if (word&(1<<bit[ib])) val[ib]|=(1<<idr);
}
idr++;
if (idr==dr) {
idr=0;
fprintf(stdout,"%d\t",iw++);
for (ib=0; ib<nb; ib++) {
#ifdef HEX
fprintf(stdout,"%08llx\t",val[ib]);
#else
fprintf(stdout,"%lld\t",val[ib]);
#endif
val[ib]=0;
}
fprintf(stdout,"\n");
}
}
}
if (idr!=0) {
fprintf(stdout,"%d\t",iw++);
for (ib=0; ib<nb; ib++) {
#ifdef HEX
fprintf(stdout,"%08llx\t",val[ib]);
#else
fprintf(stdout,"%lld\t",val[ib]);
#endif
val[ib]=0;
}
fprintf(stdout,"\n");
}
fclose(fdin);
return 0;
}

View File

@@ -0,0 +1,30 @@
if [ "$#" -eq 0 ]; then
echo "Wrong number of arguments: usage should be $0 patname"
exit 1
fi
infile=$1
outfile=$infile"at"
outfilebin=$infile"bin"
if [ "$#" -ge 2 ]; then
outfile=$2
fi
exe=$infile"exe"
if [ "$#" -ge 4 ]; then
exe=$4
fi
if [ "$#" -ge 3 ]; then
outfilebin=$3
fi
if [ -f "$infile" ]
then
gcc -DINFILE="\"$infile\"" -DOUTFILE="\"$outfile\"" -DOUTFILEBIN="\"$outfilebin\"" -o $exe generator.c ;
echo compiling
$exe ;
echo cleaning
rm $exe
echo done
else
echo "$infile not found."
fi

View File

@@ -0,0 +1,177 @@
/****************************************************************************
usage to generate a patter test.pat from test.p
gcc -DINFILE="\"test.p\"" -DOUTFILE="\"test.pat\"" -o test.exe generator.c ; ./test.exe ; rm test.exe
*************************************************************************/
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <sys/utsname.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <math.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#define MAXLOOPS 3
#define MAXTIMERS 3
#define MAXWORDS 1024
uint64_t pat=0;
uint64_t iopat=0;
uint64_t clkpat=0;
int iaddr=0;
int waitaddr[3]={MAXWORDS,MAXWORDS,MAXWORDS};
int startloopaddr[3]={MAXWORDS,MAXWORDS,MAXWORDS};
int stoploopaddr[3]={MAXWORDS,MAXWORDS,MAXWORDS};
int start=0, stop=0;
uint64_t waittime[3]={0,0,0};
int nloop[3]={0,0,0};
char infile[10000], outfile[10000];
FILE *fd, *fd1;
uint64_t PAT[MAXWORDS];
int i,ii,iii,j,jj,jjj,pixx,pixy,memx,memy,muxout,memclk,colclk,rowclk,muxclk,memcol,memrow,loopcounter;
void setstart() {
start=iaddr;
}
void setstop() {
stop=iaddr;
}
void setinput(int bit) {
uint64_t mask=1;
mask=mask<<bit;
iopat &= ~mask;
}
void setoutput(int bit) {
uint64_t mask=1;
mask=mask<<bit;
iopat |= mask;
}
void setclk(int bit) {
uint64_t mask=1;
mask=mask<<bit;
iopat |= mask;
clkpat |= mask;
}
void clearbit(int bit){
uint64_t mask=1;
mask=mask<<bit;
pat &= ~mask;
}
void setbit(int bit){
uint64_t mask=1;
mask=mask<<bit;
pat |= mask;
}
int checkbit(int bit) {
uint64_t mask=1;
mask=mask<<bit;
return (pat & mask ) >>bit;
}
void setstartloop(int iloop) {
if (iloop>=0 && iloop<MAXLOOPS)
startloopaddr[iloop]=iaddr;
}
void setstoploop(int iloop) {
if (iloop>=0 && iloop<MAXLOOPS)
stoploopaddr[iloop]=iaddr;
}
void setnloop(int iloop, int n) {
if (iloop>=0 && iloop<MAXLOOPS)
nloop[iloop]=n;
}
void setwaitpoint(int iloop) {
if (iloop>=0 && iloop<MAXTIMERS)
waitaddr[iloop]=iaddr;
}
void setwaittime(int iloop, uint64_t t) {
if (iloop>=0 && iloop<MAXTIMERS)
waittime[iloop]=t;
}
void pw(){
if (iaddr<MAXWORDS)
PAT[iaddr]= pat;
fprintf(fd,"patword %04x %016llx\n",iaddr, pat);
iaddr++;
if (iaddr>=MAXWORDS) printf("ERROR: too many word in the pattern (%d instead of %d)!",iaddr, MAXWORDS);
}
int parseCommand(int clk, int cmdbit, int cmd, int length) {
int ibit;
clearbit(clk);
for (ibit=0; ibit<length; ibit++) {
if (cmd&(1>>ibit))
setbit(cmdbit);
else
clearbit(cmdbit);
pw();
/******/
setbit(clk);
pw();
/******/
}
};
main(void) {
int iloop=0;
fd=fopen(OUTFILE,"w");
#include INFILE
fprintf(fd,"patioctrl %016llx\n",iopat);
fprintf(fd,"patclkctrl %016llx\n",clkpat);
fprintf(fd,"patlimits %04x %04x\n",start, stop);
for (iloop=0; iloop<MAXLOOPS; iloop++) {
fprintf(fd,"patloop%d %04x %04x\n",iloop, startloopaddr[iloop], stoploopaddr[iloop]);
if ( startloopaddr[iloop]<0 || stoploopaddr[iloop]<= startloopaddr[iloop]) nloop[iloop]=0;
fprintf(fd,"patnloop%d %d\n",iloop, nloop[iloop]);
}
for (iloop=0; iloop<MAXTIMERS; iloop++) {
fprintf(fd,"patwait%d %04x\n",iloop, waitaddr[iloop]);
if (waitaddr[iloop]<0) waittime[iloop]=0;
fprintf(fd,"patwaittime%d %lld\n",iloop, waittime[iloop]);
}
close((int)fd);
fd1=fopen(OUTFILEBIN,"w");
fwrite(PAT,sizeof(uint64_t),iaddr, fd1);
close((int)fd1);
}

201
ctbGui/patternGenerator/test.p Executable file
View File

@@ -0,0 +1,201 @@
//define signals and directions (Input, outputs, clocks)
#define compTestIN 1
setoutput(compTestIN);
#define curON 32
setoutput(curON);
#define side_clk 2
setclk(side_clk);
#define side_din 3
setoutput(side_din);
#define clear_shr 4
setoutput(clear_shr);
#define bottom_din 5
setoutput(bottom_din);
#define bottom_clk 6
setclk(bottom_clk);
#define gHG 7
setoutput(gHG);
#define bypassCDS 31
setoutput(bypassCDS);
#define ENprechPRE 8
setoutput(ENprechPRE);
#define res 9
setoutput(res);
#define pulseOFF 30
setoutput(pulseOFF);
#define connCDS 27
setoutput(connCDS);
#define Dsg_1 24
setoutput(Dsg_1);
#define Dsg_2 25
setoutput(Dsg_2);
#define Dsg_3 23
setoutput(Dsg_3);
#define sto0 10
setoutput(sto0);
#define sto1 11
setoutput(sto1);
#define sto2 12
setoutput(sto2);
#define resCDS 13
setoutput(resCDS);
#define prechargeConnect 14
setoutput(prechargeConnect);
#define pulse 15
setoutput(pulse);
#define PCT_mode 21
setoutput(PCT_mode);
#define res_DGS 16
setoutput(res_DGS);
#define adc_ena 17
setoutput(adc_ena);
#define CLKBIT 18
setclk(CLKBIT);
#define adc_sync 63
setoutput(adc_sync);
#define PW pw()
#define SB(x) setbit(x)
#define CB(x) clearbit(x)
#define CLOCK clearbit(CLKBIT); pw();setbit(CLKBIT);pw()
#define LCLOCK clearbit(CLKBIT); pw();setbit(CLKBIT);pw();clearbit(CLKBIT); pw()
#define CLOCKS(x) for (i=0;i<x;i++) {clearbit(CLKBIT);pw(); setbit(CLKBIT); pw();}
#define STOP setstop();
#define START setstart();
#define REPEAT(x) for (i=0;i<(x);i++) {pw();}
#define DOFOR(x) for (j=0;j<(x);j++) {
// }
#define STARTUP1 CB(compTestIN);SB(clear_shr);CB(side_clk);CB(side_din);CB(bottom_din);CB(bottom_clk);
#define STARTUP2 CB(pulse);SB(PCT_mode);SB(pulseOFF);CB(curON);
#define STARTUP3 SB(res);SB(gHG);SB(ENprechPRE);
#define STARTUP4 SB(bypassCDS); CB(connCDS);CB(sto0);SB(sto1);SB(sto2);
#define STARTUP5 SB(resCDS);CB(Dsg_1);CB(Dsg_2);SB(Dsg_3);CB(prechargeConnect);SB(res_DGS);
#define STARTUP STARTUP1 STARTUP2 STARTUP3 STARTUP4 STARTUP5 PW;
//****NOTES****//
//FUNCTIONS
//Declare functions at the beginning
void load_pix(int nx, int ny)
{//SELECT PIXEL 1,1 for readout
SB(clear_shr);PW;PW;
CB(clear_shr);PW;PW;PW;PW;
SB(side_din);PW;
SB(side_clk);PW;
CB(side_din);
setstartloop(0); //loop on the rows
SB(side_clk);PW;
setstoploop(0); //finish loop on the rows
setnloop(0,ny); //set number row selected -can be changed dynamically
CB(side_clk);PW;
SB(bottom_din);PW;
SB(bottom_clk);PW;
CB(bottom_din);
setstartloop(1); //loop on the columns
SB(bottom_clk);PW;
setstoploop(1); //loop on the columns
setnloop(1,ny); //set number columns selected -can be changed dynamically
}
void load_col(void)
{//SELECT COLUMN 1 for readout
SB(clear_shr);PW;PW;
CB(clear_shr);PW;PW;PW;PW;
SB(bottom_din);PW;
SB(bottom_clk);PW;
CB(bottom_clk);PW;
CB(bottom_din);PW;
}
//END of FUNCTIONS
////////////////////////////////////////////////////////
//LET BYPASS PREAMP AND CDS and write on preamp out.//
//THIS ALLOWS CHECKING SOURCE FOLLOWERS //
////////////////////////////////////////////////////////
PW;
SB(5); PW;
CB(5); PW;
START; //pattern starts from here
STARTUP;
setwaitpoint(0); //set wait points
PW;
setwaittime(0,20); //wait time - can be changed dynamically
SB(adc_ena);PW;
printf("ADC sync %x %d %llx\n",iaddr,adc_sync, pat);
SB(adc_sync);PW;
printf("ADC sync %x %d %llx\n",iaddr, adc_sync, pat);
CB(gHG);
setwaitpoint(1); //set wait points
setwaittime(1,16); //wait time - can be changed dynamically
CB(adc_sync);PW;
load_pix(10, 20);
CB(res);
//CB(Dsg_3);PW;
CB(res_DGS);
setwaitpoint(2); //set wait points
setwaittime(2,1000); //wait time - can be changed dynamically
//SB(res_DGS);
//PW;
//SB(Dsg_3);
//
//CB(connCDS);
//TEST SIGNALS END
//
REPEAT(20)
//****************//
//*FINAL COMMANDS*//
//****************//
CB(adc_ena);PW;
//STARTUP;
STOP; PW; //stops here
//REPEAT(4);

View File

@@ -1,24 +0,0 @@
module 0 center 6.395E+02 +- 0.00E+00 conversion 6.5660E-05 +- 7.10E-09 offset 0.00000 +- 0.00015
module 1 center 6.395E+02 +- 0.00E+00 conversion 6.5650E-05 +- 7.09E-09 offset 5.00211 +- 0.00015
module 2 center 6.395E+02 +- 0.00E+00 conversion 6.5625E-05 +- 7.09E-09 offset 10.00733 +- 0.00015
module 3 center 6.395E+02 +- 0.00E+00 conversion 6.5618E-05 +- 7.09E-09 offset 15.00742 +- 0.00015
module 4 center 6.395E+02 +- 0.00E+00 conversion 6.5642E-05 +- 7.15E-09 offset 20.00620 +- 0.00015
module 5 center 6.395E+02 +- 0.00E+00 conversion 6.5612E-05 +- 7.09E-09 offset 25.00281 +- 0.00015
module 6 center 6.395E+02 +- 0.00E+00 conversion 6.5623E-05 +- 6.93E-09 offset 30.00704 +- 0.00015
module 7 center 6.395E+02 +- 0.00E+00 conversion 6.5605E-05 +- 7.10E-09 offset 34.99715 +- 0.00015
module 8 center 6.395E+02 +- 0.00E+00 conversion 6.5643E-05 +- 7.21E-09 offset 39.99533 +- 0.00015
module 9 center 6.395E+02 +- 0.00E+00 conversion 6.5638E-05 +- 7.09E-09 offset 44.99969 +- 0.00015
module 10 center 6.395E+02 +- 0.00E+00 conversion 6.5638E-05 +- 6.94E-09 offset 49.99859 +- 0.00015
module 11 center 6.395E+02 +- 0.00E+00 conversion 6.5644E-05 +- 7.10E-09 offset 54.99499 +- 0.00015
module 12 center 6.395E+02 +- 0.00E+00 conversion 6.5618E-05 +- 7.09E-09 offset 59.99120 +- 0.00015
module 13 center 6.395E+02 +- 0.00E+00 conversion 6.5607E-05 +- 7.11E-09 offset 64.98880 +- 0.00015
module 14 center 6.395E+02 +- 0.00E+00 conversion 6.5609E-05 +- 7.09E-09 offset 69.98205 +- 0.00015
module 15 center 6.395E+02 +- 0.00E+00 conversion 6.5611E-05 +- 7.09E-09 offset 74.98379 +- 0.00015
module 16 center 6.395E+02 +- 0.00E+00 conversion 6.5619E-05 +- 4.72E-09 offset 79.98559 +- 0.00015
module 17 center 6.395E+02 +- 0.00E+00 conversion 6.5604E-05 +- 7.09E-09 offset 84.98376 +- 0.00015
module 18 center 6.395E+02 +- 0.00E+00 conversion 6.5605E-05 +- 7.09E-09 offset 89.98307 +- 0.00015
module 19 center 6.395E+02 +- 0.00E+00 conversion 6.5616E-05 +- 7.09E-09 offset 94.98907 +- 0.00015
module 20 center 6.395E+02 +- 0.00E+00 conversion 6.5634E-05 +- 7.08E-09 offset 99.97965 +- 0.00015
module 21 center 6.395E+02 +- 0.00E+00 conversion 6.5608E-05 +- 4.16E-09 offset 104.99732 +- 0.00016
module 22 center 6.395E+02 +- 0.00E+00 conversion 6.5608E-05 +- 7.09E-09 offset 109.98646 +- 0.00015
module 23 center 6.395E+02 +- 0.00E+00 conversion 6.5649E-05 +- 7.09E-09 offset 114.98765 +- 0.00015

View File

@@ -1,5 +0,0 @@
15
1528
5000
6513

View File

@@ -0,0 +1,39 @@
hostname hostname1+hostname2+hostname3+hostname55+
header_var1 wow
header_var2 great
header_var3 very nice
0:counter1 100
0:counter2 1024
0:counter3 1500
0:forallmodules val_mod1
0:constant1 const1
0:constant2 const2
0:constant3 const3 /path/to/something
1:counter1 101
1:counter2 1036
1:counter3 1503
1:forallmodules val_mod2
1:constant1 const1
1:constant2 const2
1:constant3 const3 /path/to/something
2:counter1 102
2:counter2 1048
2:counter3 1506
2:forallmodules val_mod3
2:constant1 const1
2:constant2 const2
2:constant3 const3 /path/to/something
3:counter1 103
3:counter2 1060
3:counter3 1509
3:forallmodules val_mod4
3:constant1 const1
3:constant2 const2
3:constant3 const3 /path/to/something
footer1 foot1
footer2 somethingelseathebottom

View File

@@ -0,0 +1,47 @@
#!/bin/bash
# local variables
a_variable=/path/to/something
# HOSTNAMES is special
# Beside of the hostname line it also defines the amount of modules
# for the body part
# take care for the last space
HOSTNAMES="hostname1 hostname2 hostname3 hostname55 "
## header contains constant values at the beginning of the file
header=(
header_var1="wow"
header_var2="great"
header_var3="very nice"
)
## the body part is for each half module
# counters will count automatically
# the number behind ':' indicates the incrementation value
counters=(
counter1="100:1"
counter2="1024:12"
counter3="1500:3"
)
# constant values
constants=(
constant1="const1"
constant2="const2"
constant3="const3 ${a_variable}"
)
# lists contains space separated lists each value for each half module
lists=(
forallmodules="val_mod1 val_mod2 val_mod3 val_mod4"
)
## footer contains constant values for the end of the file
footer=(
footer1=foot1
footer2=somethingelseathebottom
)

View File

@@ -1,15 +1,15 @@
hostname bchip038+
hostname localhost
0:rx_udpport 50004
0:rx_udpip 10.1.1.100
0:detectorip 10.1.1.10
rx_hostname pcmoench01
0:rx_udpip 172.24.8.84
0:detectorip 172.24.8.254
rx_hostname localhost
powerchip 1
#powerchip 1
#extsig:0 trigger_in_rising_edge
#timing trigger
outdir /external_pool/jungfrau_data/softwaretest
outdir /tmp/slsdetector

View File

@@ -1,32 +0,0 @@
type Mythen+
0:hostname mcs1x21
0:port 1952
0:stopport 1953
0:settingsdir /afs/psi.ch/user/b/bergamaschi
0:outdir /afs/psi.ch/user/b/bergamaschi
0:angdir 1.000000
0:moveflag 1.000000
0:lock 0
0:caldir /afs/psi.ch/user/b/bergamaschi
0:ffdir /afs/psi.ch/user/b/bergamaschi
0:nmod 1
0:waitstates 13
0:setlength 3
0:clkdivider 6
0:extsig:0 gate_in_active_high
0:extsig:1 trigger_in_rising_edge
0:extsig:2 off
0:extsig:3 off
master -1
sync none
outdir /afs/psi.ch/user/b/bergamaschi
ffdir /afs/psi.ch/user/b/bergamaschi
headerbefore none
headerafter none
headerbeforepar none
headerafterpar none
badchannels none
angconv none
globaloff 0.000000
binsize 0.001000
threaded 1

View File

@@ -1 +0,0 @@
dataport 1955

View File

@@ -1,10 +0,0 @@
#!/bin/csh -f
#set l = `ipcs -m | grep "$USER"| cut -c12-19`
set l = `ipcs -m | cut -c0-10`
foreach s ( $l )
echo $s
ipcrm -M $s
end
#if ($#l != 0 )
echo $#l shared memory\(s\) for $user removed

View File

@@ -1,142 +0,0 @@
#! /bin/awk -f
# this is an awk script to start a run
# you first need to run inimodule.awk to initialize
# the pattern, set Vc and set the trimbits
#
#####################################################################
# revision history #
#####################################################################
# 31.10.2001 first version #
#####################################################################
# #
# Bernd Schmitt #
# #
# bernd.schmitt@psi.ch #
# #
#####################################################################
# #
# modifications: #
# #
# 1.3.2002 BS adapted for use with DCB #
# #
# 25.5.2002 BS adapted to new convert program #
# #
# 29.5.2002 sleep -> usleep for meas. time , TS #
# #
#####################################################################
BEGIN {
# initialize variables
NPAR=3
PAR[1]="nrun"
PAR[2]="fn"
PAR[3]="par"
# initialize default values
PARVAL[1] = 100
PARVAL[2] = "microstrip_july2007"
PARVAL[3]=0
printf("\n\nnumber of command line arguments: %i (incl. command)\n\n", ARGC);
# read command line defined variables
if (ARGC>1) {
printf("\n\nnumber of command line arguments: %i (incl. command)\n\n", ARGC);
for (i=1; i<=ARGC; i++) {
printf("%s \n", ARGV[i]);
nsplit=split(ARGV[i],array,"=")
VAR = array[1];
VAL = array[2];
for (j=1; j<=NPAR; j++) {
if ( VAR==PAR[j] ) {
PARVAL[j] = VAL
}
}
}
}
run=PARVAL[1]
fn=PARVAL[2]
par=PARVAL[3]
# print command line arguments
for (i=1; i<=NPAR; i++){
printf("\t... %2i.\t%7s = %s\n", i, PAR[i], PARVAL[i] );
}
printf("\n\n");
# generate parameter file
fnamep=fn".parab"
printf("header before\n")>> fnamep
system("date >>"fnamep)
printf("run=%i \n", run ) >> fnamep
#print detector parameters to file
if (par==1) {
command="sls_detector_get exptime| awk -F \" \" '{print $2}'"
command | getline var
printf("acquisition time = %11.6f second(s)\n", var) >> fnamep
command="sls_detector_get settings| awk -F \" \" '{print $2}'"
command | getline var
printf("settings = %s\n", var) >> fnamep;
command="sls_detector_get threshold| awk -F \" \" '{print $2}'"
command | getline var
printf("threshold energy = %d eV\n", var) >> fnamep;
command="sls_detector_get badchannels| awk -F \" \" '{print $2}'"
command | getline var
printf("bad channel list = %s\n",var) >> fnamep;
command="sls_detector_get angconv| awk -F \" \" '{print $2}'"
command | getline var
printf("angle calibration conversion = %s\n",var) >> fnamep;
command="sls_detector_get globaloff| awk -F \" \" '{print $2}'"
command | getline var
printf("beamline offset = %f deg\n", var) >> fnamep;
command="sls_detector_get fineoff| awk -F \" \" '{print $2}'"
command | getline var
printf("fine offset = %f deg\n", var) >> fnamep;
command="sls_detector_get flatfield| awk -F \" \" '{print $2}'"
command | getline var
printf("Flat field corrections = %s\n",var) >> fnamep;
command="sls_detector_get ratecorr| awk -F \" \" '{print $2}'"
command | getline var
printf("Dead time corrections tau = %d ns\n",var) >> fnamep;
}
#print beamline parameters to file
#read detector position
system("caget X04SA-ES2-TH2:RO.RBV >>"fnamep)
#read I0
system("caget X04SA-ES2-SC:CH6>>"fnamep)
}

View File

@@ -1,87 +0,0 @@
#! /bin/awk -f
# this is an awk script to start a run
# you first need to run inimodule.awk to initialize
# the pattern, set Vc and set the trimbits
#
#####################################################################
# revision history #
#####################################################################
# 31.10.2001 first version #
#####################################################################
# #
# Bernd Schmitt #
# #
# bernd.schmitt@psi.ch #
# #
#####################################################################
# #
# modifications: #
# #
# 1.3.2002 BS adapted for use with DCB #
# #
# 25.5.2002 BS adapted to new convert program #
# #
# 29.5.2002 sleep -> usleep for meas. time , TS #
# #
#####################################################################
BEGIN {
# initialize variables
NPAR=4
PAR[1]="nrun"
PAR[2]="fn"
PAR[3]="var"
PAR[4]="par"
# initialize default values
PARVAL[1] = 100
PARVAL[2] = "myfname"
PARVAL[3] = 0
PARVAL[2] = "none"
# read command line defined variables
if (ARGC>1) {
printf("\n\nnumber of command line arguments: %i (incl. command)\n\n", ARGC);
for (i=1; i<=ARGC; i++) {
nsplit=split(ARGV[i],array,"=")
VAR = array[1];
VAL = array[2];
for (j=1; j<=NPAR; j++) {
if ( VAR==PAR[j] ) {
PARVAL[j] = VAL
}
}
}
}
run=PARVAL[1]
fn=PARVAL[2]
var=PARVAL[3]
par=PARVAL[4]
# print command line arguments
for (i=1; i<=NPAR; i++){
printf("\t... %2i.\t%7s = %s\n", i, PAR[i], PARVAL[i] );
}
#execute you command hereafter e.g. change temperature etc.
}

View File

@@ -1,100 +0,0 @@
#! /bin/awk -f
# this is an awk script to start a run
# you first need to run inimodule.awk to initialize
# the pattern, set Vc and set the trimbits
#
#####################################################################
# revision history #
#####################################################################
# 31.10.2001 first version #
#####################################################################
# #
# Bernd Schmitt #
# #
# bernd.schmitt@psi.ch #
# #
#####################################################################
# #
# modifications: #
# #
# 1.3.2002 BS adapted for use with DCB #
# #
# 25.5.2002 BS adapted to new convert program #
# #
# 29.5.2002 sleep -> usleep for meas. time , TS #
# #
#####################################################################
BEGIN {
# initialize variables
NPAR=7
PAR[1]="nrun"
PAR[2]="fn"
PAR[3]="par"
PAR[4]="sv0"
PAR[5]="sv1"
PAR[6]="p0"
PAR[7]="p1"
# initialize default values
PARVAL[1] = 100
PARVAL[2] = "myfname"
PARVAL[3] = 1
PARVAL[4] = 0
PARVAL[5] = 0
PARVAL[6] = "none"
PARVAL[7] = "none"
# read command line defined variables
if (ARGC>1) {
printf("\n\nnumber of command line arguments: %i (incl. command)\n\n", ARGC);
for (i=1; i<=ARGC; i++) {
nsplit=split(ARGV[i],array,"=")
VAR = array[1];
VAL = array[2];
for (j=1; j<=NPAR; j++) {
if ( VAR==PAR[j] ) {
PARVAL[j] = VAL
}
}
}
}
run=PARVAL[1]
fn=PARVAL[2]
"par"PAR[3]=
sv0=PAR[4]
sv1=PAR[5]
p0=PAR[6]
p1=PAR[7]
# print command line arguments
for (i=1; i<=NPAR; i++){
printf("\t... %2i.\t%7s = %s\n", i, PAR[i], PARVAL[i] );
}
# printf("\n\n");
# system("close_shutter_g95")
# execute your actions hereafter
if (par==1) {
#open shutter
} else {
#close shutter
}
}

View File

@@ -1,79 +0,0 @@
#! /bin/awk -f
# this is an awk script to start a run
# you first need to run inimodule.awk to initialize
# the pattern, set Vc and set the trimbits
#
#####################################################################
# revision history #
#####################################################################
# 31.10.2001 first version #
#####################################################################
# #
# Bernd Schmitt #
# #
# bernd.schmitt@psi.ch #
# #
#####################################################################
# #
# modifications: #
# #
# 1.3.2002 BS adapted for use with DCB #
# #
# 25.5.2002 BS adapted to new convert program #
# #
# 29.5.2002 sleep -> usleep for meas. time , TS #
# #
#####################################################################
BEGIN {
# initialize variables
NPAR=2
PAR[1]="nrun"
PAR[2]="par"
# initialize default values
PARVAL[1] = 100
PARVAL[2] = "none"
# read command line defined variables
if (ARGC>1) {
printf("\n\nnumber of command line arguments: %i (incl. command)\n\n", ARGC);
for (i=1; i<=ARGC; i++) {
nsplit=split(ARGV[i],array,"=")
VAR = array[1];
VAL = array[2];
for (j=1; j<=NPAR; j++) {
if ( VAR==PAR[j] ) {
PARVAL[j] = VAL
}
}
}
}
run=PARVAL[1]
par=PARVAL[2]
# print command line arguments
for (i=1; i<=NPAR; i++){
printf("\t... %2i.\t%7s = %s\n", i, PAR[i], PARVAL[i] );
}
#execute action hereafter
}

View File

@@ -1,64 +0,0 @@
#####Any line with a # is not read######
#type Gotthard+
hostname bchip007+bchip009+
#0:hostname bchip007
#0:port 1952
#0:stopport 1953
#0:rx_tcpport 1956
0:settingsdir /home/l_msdetect/dhanya/slsDetectorsPackage/settingsdir/gotthard
0:angdir 1.000000
0:moveflag 0.000000
0:lock 0
0:caldir /home/l_msdetect/dhanya/slsDetectorsPackage/settingsdir/gotthard
0:ffdir /home/l_msdetect
0:extsig:0 off
0:extsig:1 off
0:extsig:2 off
0:extsig:3 off
#0:detectorip 10.1.1.2
#0:detectormac 00:aa:bb:cc:dd:ee
#0:rx_udpport 50001
#0:rx_udpip 10.1.1.1
#0:rx_hostname 129.129.202.134
0:outdir /data/speedt
0:vhighvoltage 120
#1:hostname bchip009
#1:port 1952
#1:stopport 1953
1:rx_tcpport 1957
1:settingsdir /home/l_msdetect/dhanya/slsDetectorsPackage/settingsdir/gotthard
1:angdir 1.000000
1:moveflag 0.000000
1:lock 0
1:caldir /home/l_msdetect/dhanya/slsDetectorsPackage/settingsdir/gotthard
1:ffdir /home/l_msdetect
1:extsig:0 off
1:extsig:1 off
1:extsig:2 off
1:extsig:3 off
#1:detectorip 10.1.2.2
#1:detectormac 00:aa:bb:cc:dd:ee
#1:rx_udpport 50004
#1:rx_udpip 10.1.2.1
#1:rx_hostname 129.129.202.134
1:outdir /data/speedt
1:vhighvoltage 120
master -1
sync none
outdir /data/speedt
ffdir /home/l_msdetect
headerbefore none
headerafter none
headerbeforepar none
headerafterpar none
badchannels none
angconv none
globaloff 0.000000
binsize 0.001000
threaded 1

View File

@@ -479,4 +479,42 @@ TEST_CASE("Chiptestboard Dbit offset, list, sampling, advinvert", "[.ctbintegrat
CHECK(m.getExternalSampling() == 1);
CHECK(m.readRegister(0x7b) == 0x1003E);
}
TEST_CASE("Eiger or Jungfrau startingfnum", "[.eigerintegration][.jungfrauintegration][startingfnum]") {
SingleDetectorConfig c;
// pick up multi detector from shm id 0
multiSlsDetector m(0);
// ensure ctb detector type, hostname and online
REQUIRE(((m.getDetectorTypeAsEnum() == slsDetectorDefs::detectorType::EIGER) || (m.getDetectorTypeAsEnum() == slsDetectorDefs::detectorType::JUNGFRAU)));
REQUIRE(m.getHostname() == c.hostname);
REQUIRE(m.setOnline(true) == slsDetectorDefs::ONLINE_FLAG);
CHECK(m.setTimer(slsDetectorDefs::FRAME_NUMBER, 1) == 1);
// starting fnum
uint64_t val = 8;
m.setStartingFrameNumber(val);
CHECK(m.getStartingFrameNumber() == val);
CHECK(m.acquire() == slsDetectorDefs::OK);
CHECK(m.getReceiverCurrentFrameIndex() == val);
++val;
CHECK(m.acquire() == slsDetectorDefs::OK);
CHECK(m.getReceiverCurrentFrameIndex() == val);
CHECK_THROWS_AS(m.setStartingFrameNumber(0), sls::RuntimeError);
if (m.getDetectorTypeAsString() == "Eiger") {
val = 281474976710655;
} else if (m.getDetectorTypeAsString() == "Jungfrau") {
val = 18446744073709551615;
}
m.setStartingFrameNumber(val);
CHECK(m.getStartingFrameNumber() == val);
CHECK(m.acquire() == slsDetectorDefs::OK);
CHECK(m.getReceiverCurrentFrameIndex() == val);
}

View File

@@ -107,4 +107,4 @@ TEST_CASE("Set and read timers", "[.integration][.multi]") {
// MAX_TIMERS
d.freeSharedMemory();
}
}

View File

@@ -19,18 +19,18 @@ It is linked in manual/manual-api from slsReceiverSoftware/include ]
#include "sls_detector_defs.h"
#include "slsReceiverUsers.h"
#include <iostream>
#include <string.h>
#include <signal.h> //SIGINT
#include <csignal> //SIGINT
#include <cstdlib> //system
#include <cstring>
#include <iostream>
//#include "utilities.h"
//#include "logger.h"
#include <cerrno>
#include <string>
#include <sys/types.h> //wait
#include <sys/wait.h> //wait
#include <string>
#include <unistd.h> //usleep
#include <errno.h>
#include <syscall.h> //tid
#include <unistd.h> //usleep
using namespace std;

View File

@@ -127,7 +127,7 @@ conda install sls_detector_gui=4.0.0
\begin{verbatim}
#Add conda channels
conda config --add channels conda-forge
conda config --add channels sls_detector
conda config --add channels slsdetectorgroup
#Install latest version
conda install sls_detector

View File

@@ -7,12 +7,9 @@
#include <string>
#include <vector>
#include "error_defs.h"
#include "multiSlsDetector.h"
#include "slsDetector.h"
// #include "slsDetectorUtils.h"
#include "sls_detector_defs.h"
// #include "sls_receiver_defs.h"
class Detector {
public:

View File

@@ -0,0 +1,156 @@
#ifndef MOVINGSTAT_H
#define MOVINGSTAT_H
#include <math.h>
class MovingStat
{
/** @short approximated moving average structure */
public:
/** constructor
\param nn number of samples parameter to be used
*/
MovingStat(int nn=1000) : n(nn), m_n(0) {}
/**
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);
}
/**
clears the moving average number of samples parameter, mean and standard deviation
*/
void SetRMS(double rms)
{
if (rms<=0) {
m_newM2=m_newM*m_newM/n;
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<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
{
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 > 1) ? (M2()-Mean()*Mean()) : 0.0 );
}
/** returns the standard deviation, 0 if no elements are inside
\returns returns the standard deviation
*/
inline double StandardDeviation() const
{
return ( (Variance() > 0) ? sqrt( Variance() ) : -1 );
}
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

View File

@@ -0,0 +1,55 @@
class RunningStat
{
public:
RunningStat() : 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;
}
}
int NumDataValues() const
{
return m_n;
}
double Mean() const
{
return (m_n > 0) ? m_newM : 0.0;
}
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;
};

View File

@@ -0,0 +1,45 @@
class Stat
{
public:
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;
}
double Mean() const
{
return (n > 0) ? m/n : 0.0;
}
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;
};

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,82 @@
#ifndef COMMONMODESUBTRACTION_H
#define COMMONMODESUBTRACTION_H
#include "MovingStat.h"
class commonModeSubtraction {
/** @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
*/
commonModeSubtraction(int nn=1000, int iroi=1) : cmStat(NULL), cmPed(NULL), nCm(NULL), nROI(iroi) {cmStat=new MovingStat[nROI]; for (int i=0; i<nROI; i++) cmStat[i].SetN(nn); cmPed=new double[nROI]; nCm=new double[nROI];};
/** destructor - deletes the moving average(s) and the sum of pedestals calculator(s) */
virtual ~commonModeSubtraction() {delete [] cmStat; delete [] cmPed; delete [] nCm;};
/** clears the moving average and the sum of pedestals calculation - virtual func*/
virtual void Clear(){
for (int i=0; i<nROI; i++) {
cmStat[i].Clear();
nCm[i]=0;
cmPed[i]=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(){
for (int i=0; i<nROI; i++) {
if (nCm[i]>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 void addToCommonMode(double val, int ix=0, int iy=0) {
(void) ix; (void) iy;
//if (isc>=0 && isc<nROI) {
cmPed[0]+=val;
nCm[0]++;//}
};
/** gets the common mode i.e. the difference between the current average sum of pedestals mode and the average pedestal -- virtual func must be overloaded to define the regions of interest
\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 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;};
protected:
MovingStat *cmStat; /**<array of moving average of the pedestal average per region of interest */
double *cmPed; /**< array storing the sum of pedestals per region of interest */
double *nCm; /**< array storing the number of pixels currently contributing to the pedestals */
const int nROI; /**< constant parameter for number of regions on which the common mode should be calculated separately e.g. supercolumns */
};
#endif

View File

@@ -0,0 +1,116 @@
#ifndef COMMONMODESUBTRACTION_H
#define COMMONMODESUBTRACTION_H
#include <cmath>
class commonModeSubtraction {
/** @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
*/
commonModeSubtraction(int iroi=1, int ns=3) : nROI(iroi), nsigma(ns) {
mean=new double[nROI];
mean2=new double[nROI];
nCm=new double[nROI];
};
/** destructor - deletes the moving average(s) and the sum of pedestals calculator(s) */
virtual ~commonModeSubtraction() {delete [] mean; delete [] mean2; delete [] nCm;};
/** clears the moving average and the sum of pedestals calculation - virtual func*/
virtual void Clear(){
for (int i=0; i<nROI; i++) {
mean[i]=0;
nCm[i]=0;
mean2[i]=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(){
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;
}};
/** 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<nROI) {
if (iroi>=0 && iroi<nROI) {
mean[iroi]+=val;
mean2[iroi]+=val*val;
nCm[iroi]++;
}
};
/** 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 getCommonMode(int ix=0, int iy=0) {
int iroi=getROI(ix,iy);
/* if (iroi==0) */
/* return 100; */
/* else */
/* return -100; */
if (iroi>=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;};
protected:
double *mean; /**<array of moving average of the pedestal average per region of interest */
double *mean2; /**< array storing the sum of pedestals per region of interest */
double *nCm; /**< array storing the number of pixels currently contributing to the pedestals */
int nsigma; /** number of rms above which the pedestal should be considered as a photon */
const int nROI; /**< constant parameter for number of regions on which the common mode should be calculated separately e.g. supercolumns */
};
#endif

View File

@@ -0,0 +1,123 @@
#ifndef MYTHEN301JCTBDATA_H
#define MYTHEN301JCTBDATA_H
class mythen3_01_jctbData : public slsDetectorData<short unsigned int> {
public:
mythen3_01_jctbData( int nch=64*3,int dr=24, int off=5): slsDetectorData<short unsigned int>(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 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<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;
}
virtual char *readNextFrame(ifstream &filebin) {
char *data=NULL;
if (filebin.is_open()) {
data=new char[dataSize];
filebin.read(data,dataSize);
}
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<nch; ib++) {
val[ib]=0;
}
wp=(int64_t*)ptr;
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

View File

@@ -0,0 +1,130 @@
#ifndef MYTHEN302JCTBDATA_H
#define MYTHEN302JCTBDATA_H
#include "Mythen3_01_jctbData.h"
//class mythen3_02_jctbData : public slsDetectorData<short unsigned int> {
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<short unsigned int>(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 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<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; */
/* } */
/* virtual char *readNextFrame(ifstream &filebin) { */
/* char *data=NULL; */
/* if (filebin.is_open()) { */
/* data=new char[dataSize]; */
/* filebin.read(data,dataSize); */
/* } */
/* 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 ich=0;
int ii=0;
int iw=0;
bit[0]=17;//19;
bit[1]=6;//8;
idr=0;
for (ib=0; ib<nch; ib++) {
val[ib]=0;
}
wp=(int64_t*)ptr;
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 << "-" ;
}
// cout << iw+nch/nb*(ib)<< " " ;
}//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.02 Decoded "<<ii << " samples"<< endl;
cout << "M3.02 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

View File

@@ -0,0 +1,63 @@
#ifndef ADCSAR2_JCTBDATA_H
#define ADCSAR2_JCTBDATA_H
class adcSar2_jctbData : public slsDetectorData<short unsigned int> {
public:
adcSar2_jctbData(int nsamples=1000): slsDetectorData<short unsigned int>(nsamples,1,nsamples*8,NULL,NULL,NULL){};
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));
}
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;
}
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 setFrameNumber(int f=0) {if (f>=0) frameNumber=f; return frameNumber; };
private:
int frameNumber;
};
#endif

View File

@@ -0,0 +1,89 @@
#ifndef CHIPTESTDATA_H
#define CHIPTESTDATA_H
#include "slsDetectorData.h"
class chiptestBoardData : public slsDetectorData<uint16_t> {
public:
/**
chiptestBoard data structure. Works for data acquired using the chiptestBoard.
Inherits and implements slsDetectorData.
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<uint16_t>(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
*/
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 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 *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; /**<number of ADC read out */
const int offSize; /**< offset at the beginning of the frame (depends on the pattern) */
int iframe; /**< frame number (calculated in software! not in the data)*/
};
#endif

View File

@@ -0,0 +1,171 @@
#ifndef DESERIALIZER_H
#define DESERIALIZER_H
#include <vector>
class deserializer : public slsDetectorData<int> {
public:
deserializer( std::vector <int> dbl, int nch=64*3,int dr=24, int off=2): slsDetectorData<int>(nch,1,nch*dr*8+off*8,NULL,NULL,NULL), dbitlist(dbl), dynamicRange(dr), serialOffset(off), frameNumber(0), numberOfCounters(nch) {};
deserializer( std::vector <int> dbl, int nch,int dr, int off, int ds): slsDetectorData<int>(nch,1,ds,NULL,NULL,NULL), dbitlist(dbl), dynamicRange(dr), serialOffset(off), frameNumber(0), numberOfCounters(nch) {};
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<numberOfCounters) {
int *val=deserializeAll(data,dbitlist,dynamicRange,numberOfCounters,serialOffset);
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;
}
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]=deserializeAll(ptr,dbitlist,dynamicRange,nx,serialOffset);
return val;
}
static int* deserializeAll(char *ptr, std::vector <int> dbl, int dr=24, int nch=64*3, int off=5) {
// off=0;
int iarg;
int64_t word, *wp;
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; ib<nch; ib++) {
val[ib]=0;
}
wp=(int64_t*)ptr;
for (iw=0; iw<nch*dr/nb; iw) {
word=*wp;;
if (ioff<off) {
ioff++;
cout <<"*";
} else {
//if (idr<16) {
ib=0;
for (const auto &bit : dbl) {
ich=iw+nch/nb*(ib);
if (word&(1<<bit) && ich<nch) {
//cout << "+" ;
val[ich]|=(1<<idr);
} //else {
//cout << "-" ;
//}
ib++;
}
}
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
return val;
}
static int* deserializeList(char *ptr, std::vector <int> 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();
char *dval;
idr=0;
for (ib=0; ib<nch; ib++) {
val[ib]=0;
}
dval=ptr;
ib=0;
ich=0;
for (const auto &bit : dbl) {
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 <int> setDBitList(std::vector <int> dbl) {dbitlist=dbl; return dbitlist;};
virtual std::vector <int> getDBitList() {return dbitlist;};
private:
int dynamicRange;
int serialOffset;
int frameNumber;
int numberOfCounters;
std::vector <int> dbitlist;
};
#endif

View File

@@ -0,0 +1,172 @@
#ifndef GOTTHARD2MODULEDATANEW_H
#define GOTTHARD2MODULEDATANEW_H
#include "gotthardModuleDataNew.h"
class gotthardDoubleModuleDataNew : public slsDetectorData<uint16_t> {
private:
const int nModules;
const int offset;
int iframe;
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<uint16_t>(1280*nmod, 1, nmod*(1280*2+off)), nModules(nmod), offset(off),iframe(0) {
#ifdef BCHIP074_BCHIP075
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];
for(int ix=0; ix<xpixels; ix++) {
imod=ix%2;
if (imod==0)
ipix=ix/2;
else
ipix=1280-1-ix/2;
if (imod==0)
dMap[0][ix] =ipix*2+offset;
else
dMap[0][ix] = 1280*2+2*offset+ipix*2;//dataSize-2-ix;//+2*offset;
// dMap[0][ix] = 2*ipix+offset*(imod+1)+1280*2*imod;
dMask[0][ix] = 0x0;
#ifdef BCHIP074_BCHIP075
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);
};
/**
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 getPacketNumber(char *buff){if (offset>=sizeof(sls_detector_header))return ((sls_detector_header*)buff)->packetNumber;};
/**
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;
}
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;
};
};
#endif

View File

@@ -0,0 +1,127 @@
#ifndef GOTTHARDSHORTMODULEDATA_H
#define GOTTHARDSHORTMODULEDATA_H
#include "slsReceiverData.h"
class gotthardShortModuleData : public slsReceiverData<uint16_t> {
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<uint16_t>(xpixels, ypixels, npackets, buffersize), xtalk(c){
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];
}
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++;
}
setDataMap(dMap);
setDataMask(dMask);
};
/**
Returns the frame number for the given dataset.
\param buff pointer to the dataset
\returns frame number
*/
int getFrameNumber(char *buff){
return (*(int*)buff);
};
/**
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<uint16_t>::getValue(data, ix, iy);
else
return slsDetectorData<uint16_t>::getValue(data, ix, iy)-xtalk*slsDetectorData<uint16_t>::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; /**<output buffer crosstalk correction parameter */
const static int xpixels = 256;
const static int ypixels = 1;
const static int npackets = 1;
const static int buffersize = 518;
};
#endif

View File

@@ -0,0 +1,169 @@
#ifndef MOENCH02CTBDATA_H
#define MOENCH02CTBDATA_H
#include "slsDetectorData.h"
class moench02CtbData : public slsDetectorData<uint16_t> {
private:
int iframe;
// int *xmap, *ymap;
int nadc;
int sc_width;
int sc_height;
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
*/
moench02CtbData(int ns=6400): slsDetectorData<uint16_t>(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<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;
}
}
}
for (int i=0; i<maplength; i++) {
//cout << i << endl;
isample=i/32;
iiadc=i%32;
iadc=-1;
for (int iii=0; iii<4; iii++) {
if (iiadc==adc_nr[iii]) iadc=iii;
}
ix=isample%sc_width;
iy=isample/sc_width;
if(iadc>=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"<<endl;
cerr<<"Trying to access the "<<ip<<"-th element"<<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/2 << "-" << endl;
//for (int i=0; i<ib/2; i++)
//cout << i << " " << afifo_cont[i] << endl;
return (char*)afifo_cont;
} else {
delete [] afifo_cont;
return NULL;
}
}
return NULL;
};
};
#endif

View File

@@ -0,0 +1,157 @@
#ifndef MOENCH03CTBDATA_H
#define MOENCH03CTBDATA_H
#include "slsDetectorData.h"
class moench03CtbData : public slsDetectorData<uint16_t> {
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<uint16_t>(400, 400, ns*2*32, NULL, NULL) , nadc(32), sc_width(25), sc_height(200) {
int row, col;
int isample;
int iadc;
int ix, 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<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;
}
}
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

View File

@@ -0,0 +1,158 @@
#ifndef MOENCH03T1CTBDATA_H
#define MOENCH03T1CTBDATA_H
#include "slsDetectorData.h"
class moench03T1CtbData : public slsDetectorData<uint16_t> {
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<uint16_t>(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 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;
}
}
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

View File

@@ -0,0 +1,290 @@
#ifndef 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 */
#ifndef VERSION_V1
uint64_t packetCaught[8]; /**< is the version number of this structure format */
#endif
} sls_detector_header;
class moench03T1ReceiverDataNew : public slsDetectorData<uint16_t> {
private:
int iframe;
int nadc;
int sc_width;
int sc_height;
const int nSamples;
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<uint16_t>(400, 400, ns*2*32+sizeof(sls_detector_header)), nSamples(ns) {
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<sc_width*sc_height; i++) {
col=adc_nr[iadc]+(i%sc_width);
if (adc4%2==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]>=nSamples*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 (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 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 ((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<dataSize) ndata=dsize;
else ndata=dataSize;
return data;
}
//int getPacketNumber(int x, int y) {return dataMap[y][x]/packetSize;};
};
#endif

View File

@@ -0,0 +1,321 @@
#ifndef MOENCH03T1RECDATANEWRECT_H
#define MOENCH03T1RECDATANEWRECT_H
#include "slsDetectorData.h"
#define VERT 1
/**
@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 */
} sls_detector_header;
class moench03T1ReceiverDataNew : public slsDetectorData<uint16_t> {
private:
int iframe;
int nadc;
int sc_width;
int sc_height;
const int nSamples;
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
*/
#ifdef HOR
moench03T1ReceiverDataNew(int ns=5000): slsDetectorData<uint16_t>(800, 200, ns*2*32+sizeof(sls_detector_header)), nSamples(ns) {
#endif
#ifdef VERT
moench03T1ReceiverDataNew(int ns=5000): slsDetectorData<uint16_t>(200, 800, ns*2*32+sizeof(sls_detector_header)), nSamples(ns) {
#endif
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);
int pix;
int off=0;
#ifdef OFF_1
off=1;
#endif
cout << "This is a MOENCH with rectangular pixels!" << endl;
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<sc_width*sc_height; i++) {
col=adc_nr[iadc]+(i%sc_width);
if (adc4%2==0) {
row=199-i/sc_width;
} else {
row=200+i/sc_width;
}
pix=sizeof(sls_detector_header)+(nadc*i+iadc)*2;//+16*(ip+1);
if (pix<0 || pix>=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;
}
#endif
#ifdef VERT
if (col%2==off) {
ix=col/2;
iy=row*2+1;
} else {
ix=col/2;
iy=row*2;
}
#endif
dataMap[iy][ix]=pix;
}
}
}
}
/* 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 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 ((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<dataSize) ndata=dsize;
else ndata=dataSize;
return data;
}
//int getPacketNumber(int x, int y) {return dataMap[y][x]/packetSize;};
};
#endif

View File

@@ -0,0 +1,176 @@
#ifndef MOENCH03T1REORDERED_H
#define MOENCH03T1REORDERED_H
#include "slsDetectorData.h"
class moench03T1ReorderedData : public slsDetectorData<uint16_t> {
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<uint16_t>(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;
}
// 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<dataSize) ndata=dsize;
else ndata=dataSize;
return data;
}
//int getPacketNumber(int x, int y) {return dataMap[y][x]/packetSize;};
};
#endif

View File

@@ -0,0 +1,268 @@
#ifndef MOENCH03T1ZMQDATANEW_H
#define MOENCH03T1ZMQDATANEW_H
#include "slsDetectorData.h"
class moench03T1ZmqDataNew : public slsDetectorData<uint16_t> {
private:
// int iframe;
int nadc;
int sc_width;
int sc_height;
const int nSamples;
const int offset;
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<uint16_t>(400, 400, ns*32*2+sizeof(int)), nSamples(ns), offset(sizeof(int)) {
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<sc_width*sc_height; i++) {
col=adc_nr[iadc]+(i%sc_width);
if (adc4%2==0) {
row=199-i/sc_width;
} else {
row=200+i/sc_width;
}
dataMap[row][col]=(nadc*i+iadc)*2+offset;//+16*(ip+1);
if (dataMap[row][col]<0 || dataMap[row][col]>=dataSize)
cout << "Error: pointer " << dataMap[row][col] << " out of range "<< endl;
}
}
}
}
int ii=0;
for (i=0; i< dataSize; i++) {
if (i<offset) {
//header! */
xmap[i]=-1;
ymap[i]=-1;
} else {
// ii=ibyte+128*32*ipacket;
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]=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 *((int*)buff);};//*((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[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;};
};
#endif

View File

@@ -0,0 +1,180 @@
#ifndef MOENCH03TCTBDATA_H
#define MOENCH03TCTBDATA_H
#include "slsDetectorData.h"
class moench03TCtbData : public slsDetectorData<uint16_t> {
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<uint16_t>(400, 400, ns*2*32, NULL, NULL) , nadc(32), sc_width(25), sc_height(200) {
int row, col;
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 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}; */
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<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; */
/* } */
/* } */
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

View File

@@ -0,0 +1,291 @@
#ifndef MOENCH04RECDATA_H
#define MOENCH04RECDATA_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;
class moench04CtbReceiverData : public slsDetectorData<uint16_t> {
private:
int iframe;
int nadc;
int sc_width;
int sc_height;
const int aSamples;
const int dSamples;
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<uint16_t>(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<sc_width*sc_height; i++) {
col=(adc_nr[iadc]%16)*sc_width+(i%sc_width);
// if (adc4%2==0) {
if (iadc/16>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)
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; ibyte<dataSize; ibyte++) { */
/* 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 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 ((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<dataSize) ndata=dsize;
else ndata=dataSize;
return data;
}
//int getPacketNumber(int x, int y) {return dataMap[y][x]/packetSize;};
};
#endif

View File

@@ -0,0 +1,338 @@
#ifndef SLSDETECTORDATA_H
#define SLSDETECTORDATA_H
#include <inttypes.h>
#include <iostream>
#include <fstream>
using namespace std;
template <class dataType>
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; /**<size of the data constituting one frame */
int **dataMap; /**< Array of size nx*ny storing the pointers to the data in the dataset (as offset)*/
dataType **dataMask; /**< 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) */
int **dataROIMask; /**< Array of size nx*ny 1 if channel is good (or in the ROI), 0 if bad channel (or out of ROI) */
int *xmap;
int *ymap;
public:
/**
General slsDetectors data structure. Works for data acquired using the slsDetectorReceiver. Can be generalized to other detectors (many virtual funcs).
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 dsize size of the data
\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.
*/
slsDetectorData(int npx, int npy, int dsize, int **dMap=NULL, dataType **dMask=NULL, int **dROI=NULL): nx(npx), ny(npy), dataSize(dsize) {
xmap=new int[dsize/sizeof(dataType)];
ymap=new int[dsize/sizeof(dataType)];
// if (dataMask==NULL) {
dataMask=new dataType*[ny];
for(int i = 0; i < ny; i++) {
dataMask[i] = new dataType[nx];
}
// }
// if (dataMap==NULL) {
dataMap=new int*[ny];
for(int i = 0; i < ny; i++) {
dataMap[i] = new int[nx];
}
// }
// if (dataROIMask==NULL) {
dataROIMask=new int*[ny];
for(int i = 0; i < ny; i++) {
dataROIMask[i] = new int[nx];
for (int j=0; j<nx; j++)
dataROIMask[i][j]=1;
}
// }
for (int ip=0; ip<dsize/sizeof(dataType); ip++){
xmap[ip]=-1;
ymap[ip]=-1;
}
setDataMap(dMap);
setDataMask(dMask);
setDataROIMask(dROI);
};
virtual ~slsDetectorData() {
for(int i = 0; i < ny; i++) {
delete [] dataMap[i];
delete [] dataMask[i];
delete [] dataROIMask[i];
}
delete [] dataMap;
delete [] dataMask;
delete [] dataROIMask;
delete [] xmap;
delete [] ymap;
};
/**
defines the data map (as offset) - no error checking if datasize and offsets are compatible!
\param dMap array of size nx*ny storing the pointers to the data in the dataset (as offset). If NULL (default),the data are arranged as if read out row by row (dataMap[iy][ix]=(iy*nx+ix)*sizeof(dataType);)
*/
void setDataMap(int **dMap=NULL) {
int ip=0;
int ix, iy;
if (dMap==NULL) {
for (iy=0; iy<ny; iy++) {
for (ix=0; ix<nx; ix++) {
dataMap[iy][ix]=(iy*nx+ix)*sizeof(dataType);
}
}
} else {
//cout << "set dmap "<< dataMap << " " << dMap << endl;
for (iy=0; iy<ny; iy++){
// cout << iy << endl;
for (ix=0; ix<nx; ix++) {
dataMap[iy][ix]=dMap[iy][ix];
// cout << ix << " " << iy << endl;
/*ip=dataMap[ix][iy]/sizeof(dataType);
xmap[ip]=ix;
ymap[ip]=iy;Annaa*/
}
}
}
for (iy=0; iy<ny; iy++){
for (ix=0; ix<nx; ix++) {
ip=dataMap[iy][ix]/sizeof(dataType);
xmap[ip]=ix;
ymap[ip]=iy;
}
}
// cout << "nx:" <<nx << " ny:" << ny << endl;
};
/**
defines the data mask i.e. the polarity of the data
\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)
*/
void setDataMask(dataType **dMask=NULL){
if (dMask!=NULL) {
for (int iy=0; iy<ny; iy++)
for (int ix=0; ix<nx; ix++)
dataMask[iy][ix]=dMask[iy][ix];
} else {
for (int iy=0; iy<ny; iy++)
for (int ix=0; ix<nx; ix++)
dataMask[iy][ix]=0;
}
};
/**
defines the region of interest and/or the bad channels mask
\param dROI Array of size nx*ny. The lements are 1s if the channel is good or in the ROI, 0 is bad or out of the ROI. NULL (default) means all 1s.
*/
void setDataROIMask(int **dROI=NULL){
if (dROI!=NULL) {
for (int iy=0; iy<ny; iy++)
for (int ix=0; ix<nx; ix++)
dataROIMask[iy][ix]=dROI[iy][ix];
} else {
for (int iy=0; iy<ny; iy++)
for (int ix=0; ix<nx; ix++)
dataROIMask[iy][ix]=1;
}
};
/**
Define bad channel or roi mask for a single channel
\param ix channel x coordinate
\param iy channel y coordinate (1 for strips)
\param i 1 if pixel is good (or in the roi), 0 if bad
\returns 1 if pixel is good, 0 if it's bad, -1 if pixel is out of range
*/
int setGood(int ix, int iy, int i=1) { if (ix>=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) {
dataType **data;
int ix,iy;
data=new dataType*[ny];
for(int i = 0; i < ny; i++) {
data[i]=new dataType[nx];
}
if (dsize<=0 || dsize>dataSize) dsize=dataSize;
for (int ip=0; ip<(dsize/sizeof(dataType)); ip++) {
getPixel(ip,ix,iy);
if (ix>=0 && ix<nx && iy>=0 && iy<ny) {
data[iy][ix]=getChannel(ptr,ix,iy);
}
}
return data;
};
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];
}
if (dsize<=0 || dsize>dataSize) dsize=dataSize;
for (int ip=0; ip<(dsize/sizeof(dataType)); ip++) {
getPixel(ip,ix,iy);
if (ix>=0 && ix<nx && iy>=0 && iy<ny) {
data[iy][ix]=getValue(ptr,ix,iy);
}
}
return data;
};
/**
Returns the value of the selected channel for the given dataset. Virtual function, can be overloaded.
\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
*/
virtual dataType getChannel(char *data, int ix, int iy=0) {
dataType m=0, d=0;
if (ix>=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];
d=*((dataType*)(data+dataMap[iy][ix]));
}
return d^m;
};
/**
Returns the value of the selected channel for the given dataset. Virtual function, can be overloaded.
\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 or -1 if its a missing packet
*/
virtual int getChannelwithMissingPackets(char *data, int ix, int iy) {
return 0;
};
/**
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;*/
return (double)getChannel(data, ix, iy);
};
/**
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)=0;
/**
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)=0;
/**
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)=0;
};
#endif

View File

@@ -0,0 +1,238 @@
#ifndef SLSRECEIVERDATA_H
#define SLSRECEIVERDATA_H
#include "slsDetectorData.h"
#include <cstring>
#include <stdlib.h> // exit()
template <class dataType>
class slsReceiverData : public slsDetectorData<dataType> {
public:
/**
slsReceiver data structure. Works for data acquired using the slsDetectorReceiver subdivided in different packets with headers and footers.
Inherits and implements slsDetectorData.
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<dataType>(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 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 getPacketNumber(char *buff){return (*(int*)buff)&0xff;};
/**
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 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:"<<fn<<" pnum:"<<pnum<<" np:"<< np << "\t";
if (pnum<1 || pnum>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:"<<fn<<" pnum:"<<pnum<<" np:"<< np << "\t";
// cout << pnum << " " << fn << " " << np << " " << dd << " " << dsize << endl;
if (np==nPackets){
if (pnum==nPackets) {
//cprintf(BG_GREEN, "Frame Found\n");
// cout << "Frame found!" << endl;
break;
} else {
//cprintf(BG_RED, "Too many packets for this frame! fnum:%d, pnum:%d np:%d\n",fnum,pnum,np);
cout << "Too many packets for this frame! "<< fnum << " " << pnum << endl;//cprintf(BG_RED,"Exiting\n");exit(-1);
retval=NULL;
}
}
}
if (np<nPackets) {
if (np>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 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 *readNextFrame(ifstream &filebin) {
char *data=new char[packetSize*nPackets];
char *retval=0;
int np=0, nd;
if (filebin.is_open()) {
while (filebin.read(data+np*packetSize,packetSize)) {
if (np==(nPackets-1)) {
retval=findNextFrame(data,nd,packetSize*nPackets);
np=nd/packetSize;
// cout << np << endl;
if (retval==data && np==nPackets) {
// cout << "-" << endl;
return data;
} else if (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);
}
} else if (np>nPackets) {
cout << "*******too many packets!!!!!!!!!!" << endl;
delete [] data;
return NULL;
} else {
// cout << "." << endl;;
np++;
}
}
}
delete [] data;
return NULL;
};
/**
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
*/
virtual char *readNextFrame(ifstream &filebin, int& fnum) {
char *data=new char[packetSize*nPackets];
char *retval=0;
int np=0, nd;
fnum = -1;
if (filebin.is_open()) {
while (filebin.read(data+np*packetSize,packetSize)) {
if (np==(nPackets-1)) {
fnum=getFrameNumber(data); //cout << "fnum:"<<fnum<<endl;
retval=findNextFrame(data,nd,packetSize*nPackets);
np=nd/packetSize;
// cout << np << endl;
if (retval==data && np==nPackets) {
// cout << "-" << endl;
return data;
} else if (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);
}
} else if (np>nPackets) {
cout << "*******too many packets!!!!!!!!!!" << endl;
delete [] data;
return NULL;
} else {
// cout << "." << endl;;
np++;
//cout<<"np:"<<np<<endl;
}
}
}
delete [] data;
return NULL;
};
virtual int* readNextFramewithMissingPackets(ifstream &filebin, int& fnum) {return NULL;}
virtual void getChannelArray(double* data, char* buffer){};
virtual int* readNextFrameOnlyData(ifstream &filebin, int& fnum) {return NULL;};
virtual int* decodeData(int* datain) {return NULL;};
virtual int getPacketNumber(int x, int y) {return 0;};
protected:
const int nPackets; /**<number of UDP packets constituting one frame */
const int packetSize; /**< size of a udp packet */
};
#endif

View File

@@ -0,0 +1,85 @@
# If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
# documentation are documented, even if no documentation was available.
# Private class members and static file members will be hidden unless
# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES
EXTRACT_ALL = YES
# If the EXTRACT_PRIVATE tag is set to YES all private members of a class
# will be included in the documentation.
EXTRACT_PRIVATE = NO
# If the EXTRACT_STATIC tag is set to YES all static members of a file
# will be included in the documentation.
EXTRACT_STATIC = YES
# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs)
# defined locally in source files will be included in the documentation.
# If set to NO only classes defined in header files are included.
EXTRACT_LOCAL_CLASSES = YES
# This flag is only useful for Objective-C code. When set to YES local
# methods, which are defined in the implementation section but not in
# the interface are included in the documentation.
# If set to NO (the default) only methods in the interface are included.
EXTRACT_LOCAL_METHODS = YES
# If this flag is set to YES, the members of anonymous namespaces will be
# extracted and appear in the documentation as a namespace called
# 'anonymous_namespace{file}', where file will be replaced with the base
# name of the file that contains the anonymous namespace. By default
# anonymous namespace are hidden.
EXTRACT_ANON_NSPACES = NO
# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all
# undocumented members of documented classes, files or namespaces.
# If set to NO (the default) these members will be included in the
# various overviews, but no documentation section is generated.
# This option has no effect if EXTRACT_ALL is enabled.
HIDE_UNDOC_MEMBERS = NO
# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all
# undocumented classes that are normally visible in the class hierarchy.
# If set to NO (the default) these classes will be included in the various
# overviews. This option has no effect if EXTRACT_ALL is enabled.
HIDE_UNDOC_CLASSES = NO
# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all
# friend (class|struct|union) declarations.
# If set to NO (the default) these declarations will be included in the
# documentation.
HIDE_FRIEND_COMPOUNDS = NO
INTERNAL_DOCS = NO
SHOW_INCLUDE_FILES = NO
SHOW_FILES = NO
SHOW_NAMESPACES = NO
COMPACT_LATEX = YES
PAPER_TYPE = a4
PDF_HYPERLINKS = YES
USE_PDFLATEX = YES
LATEX_HIDE_INDICES = YES
PREDEFINED = __cplusplus
INPUT = MovingStat.h slsDetectorData.h slsReceiverData.h moench02ModuleData.h pedestalSubtraction.h commonModeSubtraction.h moenchCommonMode.h singlePhotonDetector.h energyCalibration.h moenchReadData.C single_photon_hit.h chiptestBoardData.h jungfrau02Data.h jungfrauReadData.C jungfrau02CommonMode.h
OUTPUT_DIRECTORY = docs

View File

@@ -0,0 +1,462 @@
#ifndef ENERGYCALIBRATION_H
#define ENERGYCALIBRATION_H
#ifdef __CINT__
#define MYROOT
#endif
#ifdef G__ROOT
#define MYROOT
#endif
#ifdef __MAKECINT__
#define MYROOT
#endif
#ifdef ROOT_VERSION
#define MYROOT
#endif
#define MYROOT
#ifdef MYROOT
#include <TROOT.h>
#include <TF1.h>
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 */
/**
\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 ;-).
* \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.
*
* @short Energy calibration functions
* @author Anna Bergamaschi
* @version 0.1alpha
*/
/**
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);};
/** 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)
*/
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
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);
/**
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])
*/
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 spectrum(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);
/** 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;
};
/**
class alowing the energy calibration of photon counting and anlogue detectors
*/
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
*/
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)
*/
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
*/
int setChargeSharing(int p=-1);
void fixParameter(int ip, Double_t val);
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);
/** 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;};
/** 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);
/** 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 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);
/**
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);
/**
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 *fitSpectrumPixel(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);};
#endif
private:
#ifdef MYROOT
/**
calculates gain and offset for the set of energies
\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
\param integral 1 is an s-curve set (default), 0 spectra
\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);
/**
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);
/**
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);
#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 */
TF1 *fscurve; /**< function with which the s-curve will be fitted */
TF1 *fspectrum; /**< 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 */
};
#endif

View File

@@ -0,0 +1,14 @@
slsReceiver --rx_tcpport 1954 &
slsReceiver --rx_tcpport 1955 &
./gotthard25umZmq pc8829 30003 129.129.202.98 40003 &
slsDetectorGui -f examples/bchip2modules_pc8829.config &
sls_detector_put settings veryhighgain
sls_detector_put exptime 0.000005
sls_detector_put period 0.01
sls_detector_put vhighvoltage 90

View File

@@ -0,0 +1,275 @@
#ifndef INTERPOLATINGDETECTOR_H
#define INTERPOLATINGDETECTOR_H
#include "singlePhotonDetector.h"
#include "slsInterpolation.h"
//#define M015
#ifdef MYROOT1
#include <TTree.h>
#endif
#include <iostream>
using namespace std;
class interpolatingDetector : public singlePhotonDetector {
/** @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
*/
interpolatingDetector(slsDetectorData<uint16_t> *d, slsInterpolation *inte,
double nsigma=5,
int sign=1,
commonModeSubtraction *cm=NULL,
int nped=1000,
int nd=100, int nnx=-1, int nny=-1) :
singlePhotonDetector(d, 3,nsigma,sign, cm, nped, nd, nnx, nny) , 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
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);
}
}
void clearImage() {
if (interp) {
pthread_mutex_lock(fi);
interp->clearInterpolatedImage();
pthread_mutex_unlock(fi);
} else
singlePhotonDetector::clearImage();
};
int getImageSize(int &nnx, int &nny, int &ns) {
if (interp)
return interp->getImageSize(nnx, nny, ns);
else
return analogDetector<uint16_t>::getImageSize(nnx, nny, ns);
};
#ifdef MYROOT1
virtual TH2F *getImage()
#endif
#ifndef MYROOT1
virtual int *getImage()
#endif
{
// cout << "image " << endl;
if (interp)
return interp->getInterpolatedImage();
else
return analogDetector<uint16_t>::getImage();
}
#ifdef MYROOT1
virtual TH2F *addToInterpolatedImage(char *data, int *val, int &nph)
#endif
#ifndef MYROOT1
virtual int *addToInterpolatedImage(char *data, int *val, int &nph)
#endif
{
nph=addFrame(data,val,0);
if (interp)
return interp->getInterpolatedImage();
else
singlePhotonDetector::getImage();
//return NULL;
};
#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;
};
void *writeImage(const char * imgname) {
// cout << id << "=" << imgname<< endl;
if (interp)
interp->writeInterpolatedImage(imgname);
else
analogDetector<uint16_t>::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; 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<uint16_t>::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);
}
}
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

View File

@@ -0,0 +1,403 @@
#ifndef ETA2_INTERPOLATION_BASE_H
#define ETA2_INTERPOLATION_BASE_H
#ifdef MYROOT1
#include <TObject.h>
#include <TTree.h>
#include <TH2D.h>
#include <TH2F.h>
#endif
#include "etaInterpolationBase.h"
class eta2InterpolationBase : public virtual etaInterpolationBase {
public:
eta2InterpolationBase(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) {
/* if (etamin>=etamax) { */
/* etamin=-1; */
/* etamax=2; */
/* // cout << ":" <<endl; */
/* } */
/* etastep=(etamax-etamin)/nbeta; */
};
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,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;
};
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;
};
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, 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:
;
}
double etax, etay;
if (nSubPixels>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, 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:
;
}
double etax, etay;
if (nSubPixels>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 (nSubPixels>2) {
ex=(etax-etamin)/etastep;
ey=(etay-etamin)/etastep;
if (ex<0) {
cout << "x*"<< ex << endl;
ex=0;
}
if (ex>=nbeta) {
cout << "x?"<< ex << endl;
ex=nbeta-1;
}
if (ey<0) {
cout << "y*"<< ey << endl;
ey=0;
}
if (ey>=nbeta) {
cout << "y?"<< ey << endl;
ey=nbeta-1;
}
xpos_eta=(((double)hhx[(ey*nbeta+ex)]))+dX ;///((double)nSubPixels);
ypos_eta=(((double)hhy[(ey*nbeta+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, 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]=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, 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]=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 <<"******"<<totquad << " " << quad << endl; */
/* cout << cc[0][0]<< " " << cc[0][1] << endl; */
/* cout << cc[1][0]<< " " << cc[1][1] << endl; */
//calcMyEta(totquad,quad,cl,etax, etay);
calcEta(totquad, cc,etax, etay);
// cout <<"******"<< etax << " " << etay << endl;
return addToFlatField(etax,etay);
}
//////////////////////////////////////////////////////////////////////////////////////
virtual int addToFlatField(double *cluster, double &etax, double &etay){
double sDum[2][2];
double tot, totquad;
int corner;
corner=calcQuad(cluster, tot, totquad, sDum);
double xpos_eta,ypos_eta;
double dX,dY;
calcEta(totquad, sDum, etax, etay);
return addToFlatField(etax,etay);
};
virtual int addToFlatField(int *cluster, double &etax, double &etay){
double sDum[2][2];
double tot, totquad;
int corner;
corner=calcQuad(cluster, tot, totquad, sDum);
double xpos_eta,ypos_eta;
double dX,dY;
calcEta(totquad, sDum, etax, etay);
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)/etastep;
ey=(etay-etamin)/etastep;
if (ey<nbeta && ex<nbeta && ex>=0 && ey>=0)
heta[ey*nbeta+ex]++;
#endif
return 0;
};
virtual int *getInterpolatedImage(){
int ipx, ipy;
// cout << "ff" << endl;
calcDiff(1, hhx, hhy); //get flat
double avg=0;
for (ipx=0; ipx<nSubPixels; ipx++)
for (ipy=0; ipy<nSubPixels; ipy++)
avg+=flat[ipx+ipy*nSubPixels];
avg/=nSubPixels*nSubPixels;
for (int ibx=0 ; ibx<nSubPixels*nPixelsX; ibx++) {
ipx=ibx%nSubPixels-nSubPixels/2;
if (ipx<0) ipx=nSubPixels+ipx;
for (int iby=0 ; iby<nSubPixels*nPixelsY; iby++) {
ipy=iby%nSubPixels-nSubPixels/2;
if (ipy<0) ipy=nSubPixels+ipy;
// cout << ipx << " " << ipy << " " << ibx << " " << iby << endl;
if (flat[ipx+ipy*nSubPixels]>0)
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;
};
/* 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

View File

@@ -0,0 +1,294 @@
#ifndef ETA3_INTERPOLATION_BASE_H
#define ETA3_INTERPOLATION_BASE_H
#ifdef MYROOT1
#include <TObject.h>
#include <TTree.h>
#include <TH2D.h>
#include <TH2F.h>
#endif
#include "etaInterpolationBase.h"
class eta3InterpolationBase : public virtual etaInterpolationBase {
public:
eta3InterpolationBase(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) {
// cout << "e3ib " << nb << " " << emin << " " << emax << endl;
/* if (nbeta<=0) { */
/* nbeta=nSubPixels*10; */
/* } */
if (etamin>=etamax) {
etamin=-1;
etamax=1;
}
etastep=(etamax-etamin)/nbeta;
#ifdef MYROOT1
delete heta;
delete hhx;
delete hhy;
heta=new TH2D("heta","heta",nbeta,etamin,etamax,nbeta,etamin,etamax);
hhx=new TH2D("hhx","hhx",nbeta,etamin,etamax,nbeta,etamin,etamax);
hhy=new TH2D("hhy","hhy",nbeta,etamin,etamax,nbeta,etamin,etamax);
#endif
#ifndef MYROOT1
/* delete [] heta; */
/* delete [] hhx; */
/* delete [] hhy; */
/* heta=new int[nbeta*nbeta]; */
/* hhx=new float[nbeta*nbeta]; */
/* hhy=new float[nbeta*nbeta]; */
#endif
// cout << nbeta << " " << etamin << " " << etamax << endl;
};
eta3InterpolationBase(eta3InterpolationBase *orig): etaInterpolationBase(orig){ };
/* virtual eta3InterpolationBase* Clone()=0; */
// virtual void prepareInterpolation(int &ok){};
//////////////////////////////////////////////////////////////////////////////
//////////// /*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, totquad;
double etax,etay;
int corner=calcEta3(data,etax,etay, totquad);
getInterpolatedPosition(x,y,etax,etay,corner,int_x,int_y);
return;
};
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=calcEta3(data,etax,etay, totquad);
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 (nSubPixels>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 (nSubPixels>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 (nSubPixels>2) {
#ifdef MYROOT1
xpos_eta=(hhx->GetBinContent(hhx->GetXaxis()->FindBin(etax),hhy->GetYaxis()->FindBin(etay)))/((double)nSubPixels);
ypos_eta=(hhy->GetBinContent(hhx->GetXaxis()->FindBin(etax),hhy->GetYaxis()->FindBin(etay)))/((double)nSubPixels);
#endif
#ifndef MYROOT1
ex=(etax-etamin)/etastep;
ey=(etay-etamin)/etastep;
if (ex<0) {
/* cout << etax << " " << etamin << " "; */
/* cout << "3x*"<< ex << endl; */
ex=0;
}
if (ex>=nbeta) {
/* cout << etax << " " << etamin << " "; */
/* cout << "3x?"<< ex << endl; */
ex=nbeta-1;
}
if (ey<0) {
/* cout << etay << " " << etamin << " "; */
/* cout << "3y*"<< ey << endl; */
ey=0;
}
if (ey>=nbeta) {
/* cout << etay << " " << etamin << " "; */
/* cout << "3y?"<< ey << endl; */
ey=nbeta-1;
}
xpos_eta=(((double)hhx[(ey*nbeta+ex)]));///((double)nSubPixels);
ypos_eta=(((double)hhy[(ey*nbeta+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)/etastep;
ey=(etay-etamin)/etastep;
if (ey<nbeta && ex<nbeta && ex>=0 && ey>=0)
heta[ey*nbeta+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

View File

@@ -0,0 +1,285 @@
#ifndef ETA_INTERPOLATION_ADAPTIVEBINS_H
#define ETA_INTERPOLATION_ADAPTIVEBINS_H
#include <cmath>
#include "tiffIO.h"
//#include "etaInterpolationBase.h"
#include "etaInterpolationPosXY.h"
class etaInterpolationAdaptiveBins : public etaInterpolationPosXY {
// protected:
private:
virtual void iterate(float *newhhx, float *newhhy) {
double bsize=1./nSubPixels;
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++) {
for (ipy=0; ipy<nSubPixels; ipy++) {
for (int ibx=0; ibx<nbeta; ibx++) {
hx[ipy][ibx]=0;
hy[ipy][ibx]=0;
}
}
// 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];
}
}
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++) {
for (int ibx=0; ibx<nbeta; ibx++) {
for (int iby=0; iby<nbeta; iby++) {
// if ( hhy[ibx+iby*nbeta]>=((ipy)*bsize) && hhy[ibx+iby*nbeta]<=((ipy+1)*bsize)) {
ipy=hhy[ibx+iby*nbeta]*nSubPixels;
if (ipy<0) ipy=0;
if (ipy>=nSubPixels) ipy=nSubPixels-1;
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;
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;
// }
}
}
// }
}
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];
};
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, int nint)
{
ok=1;
///*Eta Distribution Rebinning*///
double bsize=1./nSubPixels; //precision
// cout<<"nPixelsX = "<<nPixelsX<<" nPixelsY = "<<nPixelsY<<" nSubPixels = "<<nSubPixels<<endl;
double tot_eta=0;
double tot_eta_x=0;
double tot_eta_y=0;
for (int ip=0; ip<nbeta*nbeta; ip++)
tot_eta+=heta[ip];
if (tot_eta<=0) {ok=0; return;};
double hx[nbeta]; //profile x
double hy[nbeta]; //profile y
double hix[nbeta]; //integral of projection x
double hiy[nbeta]; //integral of projection y
int ii=0;
/** initialize distribution to linear interpolation */
// for (int ibx=0; ibx<nbeta; ibx++) {
// for (int ib=0; ib<nbeta; ib++) {
// hhx[ibx+ib*nbeta]=((float)ibx)/((float)nbeta);
// hhy[ibx+ib*nbeta]=((float)ib)/((float)nbeta);
// }
// }
etaInterpolationPosXY::prepareInterpolation(ok);
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
cout << "Iteration "<< iint << " Chi2: " << old_diff << endl; //" Best: "<< best_diff << " RMS: "<< rms<< endl;
while (iint<nint && best_diff > rms) {
/* #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) << ")"<<endl;
if (new_diff<best_diff) {
best_diff=new_diff;
besthhx=newhhx;
besthhy=newhhy;
}
if (hhx!=besthhx)
delete [] hhx;
if (hhy!=besthhy)
delete [] hhy;
hhx=newhhx;
hhy=newhhy;
#ifdef SAVE_ALL
if (new_diff<=best_diff) {
debugSaveAll(iint);
}
#endif
newhhx=new float[nbeta*nbeta]; //profile x
newhhy=new float[nbeta*nbeta]; //profile y
/* if (new_diff<old_diff){ */
/* cout << "best difference at iteration "<< iint << " (" << new_diff << " < " << old_diff << ")"<< "Best: "<< best_diff << " RMS: "<< sqrt(tot_eta) << endl; */
/* ; */
/* } else { */
// break;
// }
old_diff=new_diff;
iint++;
cout << "Iteration "<< iint << " Chi2: " << new_diff << endl; //" Best: "<< best_diff << " RMS: "<< rms<< endl;
}
delete [] newhhx;
delete [] newhhy;
if (hhx!=besthhx)
delete [] hhx;
if (hhy!=besthhy)
delete [] hhy;
hhx=besthhx;
hhy=besthhy;
cout << "Iteration "<< iint << " Chi2: " << best_diff << endl; //" Best: "<< best_diff << " RMS: "<< rms<< endl;
#ifdef SAVE_ALL
debugSaveAll(iint);
#endif
return ;
}
};
class eta2InterpolationAdaptiveBins : public virtual eta2InterpolationBase, public virtual etaInterpolationAdaptiveBins {
public:
eta2InterpolationAdaptiveBins(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),etaInterpolationAdaptiveBins(nx,ny,ns, nb, emin,emax){
cout << "NSUBPIX is " << ns << " " << nSubPixels << endl;
// cout << "e2pxy " << nb << " " << emin << " " << emax << endl;
};
eta2InterpolationAdaptiveBins(eta2InterpolationAdaptiveBins *orig): etaInterpolationBase(orig), etaInterpolationAdaptiveBins(orig) {};
virtual eta2InterpolationAdaptiveBins* Clone() { return new eta2InterpolationAdaptiveBins(this);};
};
class eta3InterpolationAdaptiveBins : public virtual eta3InterpolationBase, public virtual etaInterpolationAdaptiveBins {
public:
eta3InterpolationAdaptiveBins(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), etaInterpolationAdaptiveBins(nx,ny,ns, nb, emin,emax){
cout << "e3pxy " << nbeta << " " << etamin << " " << etamax << " " << nSubPixels<< endl;
};
eta3InterpolationAdaptiveBins(eta3InterpolationAdaptiveBins *orig): etaInterpolationBase(orig), etaInterpolationAdaptiveBins(orig) {};
virtual eta3InterpolationAdaptiveBins* Clone() { return new eta3InterpolationAdaptiveBins(this);};
};
#endif

View File

@@ -0,0 +1,369 @@
#ifndef ETA_INTERPOLATION_BASE_H
#define ETA_INTERPOLATION_BASE_H
#ifdef MYROOT1
#include <TObject.h>
#include <TTree.h>
#include <TH2D.h>
#include <TH2F.h>
#endif
#include "slsInterpolation.h"
#include "tiffIO.h"
class etaInterpolationBase : public slsInterpolation {
public:
etaInterpolationBase(int nx=400, int ny=400, int ns=25, int nb=-1, double emin=1, double emax=0) : slsInterpolation(nx,ny,ns), hhx(NULL), hhy(NULL), heta(NULL), nbeta(nb), etamin(emin), etamax(emax) {
// cout << "eb " << nb << " " << emin << " " << emax << endl;
// cout << nb << " " << etamin << " " << etamax << endl;
if (nbeta<=0) {
//cout << "aaa:" <<endl;
nbeta=nSubPixels*10;
}
if (etamin>=etamax) {
etamin=-1;
etamax=2;
}
etastep=(etamax-etamin)/nbeta;
heta=new int[nbeta*nbeta];
hhx=new float[nbeta*nbeta];
hhy=new float[nbeta*nbeta];
rangeMin=etamin;
rangeMax=etamax;
flat= new double[nSubPixels*nSubPixels];
hintcorr=new int [nSubPixels*nSubPixels*nPixelsX*nPixelsY];
};
etaInterpolationBase(etaInterpolationBase *orig): slsInterpolation(orig){
nbeta=orig->nbeta;
etamin=orig->etamin;
etamax=orig->etamax;
rangeMin=orig->rangeMin;
rangeMax=orig->rangeMax;
etastep=(etamax-etamin)/nbeta;
heta=new int[nbeta*nbeta];
memcpy(heta,orig->heta,nbeta*nbeta*sizeof(int));
hhx=new float[nbeta*nbeta];
memcpy(hhx,orig->hhx,nbeta*nbeta*sizeof(float));
hhy=new float[nbeta*nbeta];
memcpy(hhy,orig->hhy,nbeta*nbeta*sizeof(float));
hintcorr=new int [nSubPixels*nSubPixels*nPixelsX*nPixelsY];
};
virtual void resetFlatField() {
for (int ibx=0; ibx<nbeta*nbeta; ibx++) {
heta[ibx]=0;
hhx[ibx]=0;
hhy[ibx]=0;
}
};
int *setEta(int *h, int nb=-1, double emin=1, double emax=0)
{
if (h) {
if (heta) delete [] heta;
heta=h;
nbeta=nb;
if (nb<=0) nbeta=nSubPixels*10;
etamin=emin;
etamax=emax;
if (etamin>=etamax) {
etamin=-1;
etamax=2;
}
rangeMin=etamin;
rangeMax=etamax;
etastep=(etamax-etamin)/nbeta;
}
return heta;
};
int *setFlatField(int *h, int nb=-1, double emin=1, double emax=0)
{
return setEta(h, nb, emin, emax);
};
int *getFlatField(){return setEta(NULL);};
int *getFlatField(int &nb, double &emin, double &emax){
nb=nbeta;
emin=etamin;
emax=etamax;
return getFlatField();
};
void *writeFlatField(const char * imgname) {
float *gm=NULL;
gm=new float[nbeta*nbeta];
for (int ix=0; ix<nbeta; ix++) {
for (int iy=0; iy<nbeta; iy++) {
gm[iy*nbeta+ix]=heta[iy*nbeta+ix];
}
}
WriteToTiff(gm, imgname, nbeta, nbeta);
delete [] gm;
return NULL;
};
int readFlatField(const char * imgname, double emin=1, double emax=0) {
if (emax>=1) etamax=emax;
if (emin<=0) etamin=emin;
if (etamin>=etamax) {
etamin=-1;
etamax=2;
}
etastep=(etamax-etamin)/nbeta;
uint32 nnx;
uint32 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;
}
nbeta=nnx;
if (gm) {
if (heta) {
delete [] heta;
delete [] hhx;
delete [] hhy;
}
heta=new int[nbeta*nbeta];
hhx=new float[nbeta*nbeta];
hhy=new float[nbeta*nbeta];
for (int ix=0; ix<nbeta; ix++) {
for (int iy=0; iy<nbeta; iy++) {
heta[iy*nbeta+ix]=gm[iy*nbeta+ix];
}
}
delete [] gm;
return 1;
}
return 0;
};
float *gethhx()
{
// hhx->Scale((double)nSubPixels);
return hhx;
};
float *gethhy()
{
// hhy->Scale((double)nSubPixels);
return hhy;
};
virtual int addToFlatField(double etax, double etay){
int ex,ey;
ex=(etax-etamin)/etastep;
ey=(etay-etamin)/etastep;
if (ey<nbeta && ex<nbeta && ex>=0 && ey>=0)
heta[ey*nbeta+ex]++;
return 0;
};
// virtual void prepareInterpolation(int &ok)=0;
void debugSaveAll(int ind=0) {
int ib, ibx, iby;
char tit[10000];
float tot_eta=0;
float *etah=new float[nbeta*nbeta];
int etabins=nbeta;
int ibb=0;
for (int ii=0; ii<etabins*etabins; ii++) {
etah[ii]=heta[ii];
tot_eta+=heta[ii];
}
sprintf(tit,"/scratch/eta.tiff",ind);
WriteToTiff(etah, tit, etabins, etabins);
for (int ii=0; ii<etabins*etabins; ii++) {
ibb=(hhx[ii]*nSubPixels);
etah[ii]=ibb;
}
sprintf(tit,"/scratch/eta_hhx_%d.tiff",ind);
WriteToTiff(etah, tit, etabins, etabins);
for (int ii=0; ii<etabins*etabins; ii++) {
ibb=hhy[ii]*nSubPixels;
etah[ii]=ibb;
}
sprintf(tit,"/scratch/eta_hhy_%d.tiff",ind);
WriteToTiff(etah, tit, etabins, etabins);
float *ftest=new float[nSubPixels*nSubPixels];
for (int ib=0; ib<nSubPixels*nSubPixels; ib++) ftest[ib]=0;
//int ibx=0, iby=0;
for (int ii=0; ii<nbeta*nbeta; ii++) {
ibx=nSubPixels*hhx[ii];
iby=nSubPixels*hhy[ii];
if (ibx<0) ibx=0;
if (iby<0) iby=0;
if (ibx>=nSubPixels) ibx=nSubPixels-1;
if (iby>=nSubPixels) iby=nSubPixels-1;
if (ibx>=0 && ibx<nSubPixels && iby>=0 && iby<nSubPixels) {
//
// if (ibx>0 && iby>0) cout << ibx << " " << iby << " " << ii << endl;
ftest[ibx+iby*nSubPixels]+=heta[ii];
} else
cout << "Bad interpolation "<< ii << " " << ibx << " " << iby<< endl;
}
sprintf(tit,"/scratch/ftest_%d.tiff",ind);
WriteToTiff(ftest, tit, nSubPixels, nSubPixels);
//int ibx=0, iby=0;
tot_eta/=nSubPixels*nSubPixels;
int nbad=0;
for (int ii=0; ii<etabins*etabins; ii++) {
ibx=nSubPixels*hhx[ii];
iby=nSubPixels*hhy[ii];
if (ftest[ibx+iby*nSubPixels]<tot_eta*0.5) {
etah[ii]=1;
nbad++;
} else if(ftest[ibx+iby*nSubPixels]>tot_eta*2.){
etah[ii]=2;
nbad++;
} else
etah[ii]=0;
}
sprintf(tit,"/scratch/eta_bad_%d.tiff",ind);
WriteToTiff(etah, tit, etabins, etabins);
// cout << "Index: " << ind << "\t Bad bins: "<< nbad << endl;
//int ibx=0, iby=0;
delete [] ftest;
delete [] etah;
}
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[nSubPixels], p_tot_y[nSubPixels], p_tot[nSubPixels*nSubPixels];
double maxdiff=0, mindiff=avg*nSubPixels*nSubPixels;
int ipx, ipy;
for (ipy=0; ipy<nSubPixels; ipy++) {
for (ipx=0; ipx<nSubPixels; ipx++) {
p_tot[ipx+ipy*nSubPixels]=0;
}
p_tot_y[ipy]=0;
p_tot_x[ipy]=0;
}
for (int ibx=0; ibx<nbeta; ibx++) {
for (int iby=0; iby<nbeta; iby++) {
ipx=hx[ibx+iby*nbeta]*nSubPixels;
if (ipx<0) ipx=0;
if (ipx>=nSubPixels) ipx=nSubPixels-1;
ipy=hy[ibx+iby*nbeta]*nSubPixels;
if (ipy<0) ipy=0;
if (ipy>=nSubPixels) ipy=nSubPixels-1;
p_tot[ipx+ipy*nSubPixels]+=heta[ibx+iby*nbeta];
p_tot_y[ipy]+=heta[ibx+iby*nbeta];
p_tot_x[ipx]+=heta[ibx+iby*nbeta];
}
}
// cout << endl << endl;
for (ipy=0; ipy<nSubPixels; ipy++) {
cout.width(5);
//flat_y[ipy]=p_tot_y[ipy];//avg/nSubPixels;
for (ipx=0; ipx<nSubPixels; ipx++) {
// flat_x[ipx]=p_tot_x[ipx];///avg/nSubPixels;
flat[ipx+nSubPixels*ipy]=p_tot[ipx+nSubPixels*ipy];///avg;
d=p_tot[ipx+nSubPixels*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; ipx<nSubPixels; ipx++) { */
/* cout << setprecision(4) << flat_x[ipx] << " "; */
/* } */
//cout << "**" << endl; cout.width(5);
//cout << "Min diff: " << mindiff/sqrt(avg) << " Max diff: " << maxdiff/sqrt(avg) << " Nbad: " << nbad << endl;
// cout << "Bad pixels: " << 100.*(float)nbad/((float)(nSubPixels*nSubPixels)) << " %" << endl;
return sqrt(diff);
}
int *heta;
float *hhx;
float *hhy;
int nbeta;
double etamin, etamax, etastep;
double rangeMin, rangeMax;
double *flat;
int *hintcorr;
};
#endif

View File

@@ -0,0 +1,263 @@
#ifndef ETA_INTERPOLATION_CLEVER_ADAPTIVEBINS_H
#define ETA_INTERPOLATION_CLEVER_ADAPTIVEBINS_H
#include <cmath>
#include "tiffIO.h"
//#include "etaInterpolationBase.h"
#include "etaInterpolationAdaptiveBins.h"
//#define HSIZE 1
class etaInterpolationCleverAdaptiveBins : public etaInterpolationAdaptiveBins {
private:
// double *gradientX, *gradientY, *gradientXY;
virtual void iterate(float *newhhx, float *newhhy) {
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];
double mean=0;
double maxflat=0, minflat=0, maxgradX=0, mingradX=0, maxgradY=0, mingradY=0, maxgr=0, mingr=0;
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];
//for (int ipy=0; ipy<nSubPixels; ipy++) {
for (ipy=0; ipy<nSubPixels; ipy++) {
for (ipx=0; ipx<nSubPixels; ipx++) {
// cout << ipx << " " << ipy << endl;
mean+=flat[ipx+nSubPixels*ipy]/((double)(nSubPixels*nSubPixels));
}
}
// cout << "Mean is " << mean << endl;
/*** Find local minima and maxima within the staistical uncertainty **/
for (ipy=0; ipy<nSubPixels; ipy++) {
for (ipx=0; ipx<nSubPixels; ipx++) {
if (flat[ipx+nSubPixels*ipy]<mean-3.*sqrt(mean))maskMin[ipx+nSubPixels*ipy]=1; else maskMin[ipx+nSubPixels*ipy]=0;
if (flat[ipx+nSubPixels*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);
}
}
}
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); */
/* }; */
};
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) {};
virtual eta2InterpolationCleverAdaptiveBins* Clone() { return new eta2InterpolationCleverAdaptiveBins(this);};
// 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; ipx<nSubPixels; ipx++) */
/* for (ipy=0; ipy<nSubPixels; ipy++) */
/* avg+=flat[ipx+ipy*nSubPixels]; */
/* avg/=nSubPixels*nSubPixels; */
/* for (int ibx=0 ; ibx<nSubPixels*nPixelsX; ibx++) { */
/* ipx=ibx%nSubPixels-nSubPixels; */
/* if (ipx<0) ipx=nSubPixels+ipx; */
/* for (int iby=0 ; iby<nSubPixels*nPixelsY; iby++) { */
/* ipy=iby%nSubPixels-nSubPixels; */
/* if (ipy<0) ipy=nSubPixels+ipy; */
/* if (flat[ipx+ipy*nSubPixels]>0) */
/* 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; */
/* }; */
};
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) {};
virtual eta3InterpolationCleverAdaptiveBins* Clone() { return new eta3InterpolationCleverAdaptiveBins(this);};
};
#endif

View File

@@ -0,0 +1,85 @@
#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){};
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());
#endif
///*Eta Distribution Rebinning*///
double bsize=1./nSubPixels; //precision
// cout<<"nPixelsX = "<<nPixelsX<<" nPixelsY = "<<nPixelsY<<" nSubPixels = "<<nSubPixels<<endl;
double tot_eta=0;
for (int ip=0; ip<nbeta*nbeta; ip++)
tot_eta+=heta[ip];
cout << "total eta entries is :"<< tot_eta << endl;
if (tot_eta<=0) {ok=0; return;};
double hx[nbeta]; //projection x
double hy[nbeta]; //projection y
for (int ibx=0; ibx<nbeta; ibx++) {
for (int iby=0; iby<nbeta; iby++) {
hx[ibx]=hx[ibx]+heta[ibx+iby*nbeta];
hy[iby]=hx[iby]+heta[ibx+iby*nbeta];
}
}
double hix[nbeta]; //integral of projection x
double hiy[nbeta]; //integral of projection y
hix[0]=hx[0];
hiy[0]=hy[0];
for (int ib=1; ib<nbeta; ib++) {
hix[ib]=hix[ib-1]+hx[ib];
hiy[ib]=hiy[ib-1]+hx[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;
#endif
}
}
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;
#endif
}
}
return ;
};
};
#endif

View File

@@ -0,0 +1,184 @@
#ifndef ETA_INTERPOLATION_POSXY_H
#define ETA_INTERPOLATION_POSXY_H
//#include "tiffIO.h"
#include "etaInterpolationBase.h"
#include "eta2InterpolationBase.h"
#include "eta3InterpolationBase.h"
class etaInterpolationPosXY : public virtual etaInterpolationBase{
public:
etaInterpolationPosXY(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){
// cout << "epxy " << nb << " " << emin << " " << emax << endl; cout << nbeta << " " << etamin << " " << etamax << endl;
};
etaInterpolationPosXY(etaInterpolationPosXY *orig): etaInterpolationBase(orig) {};
virtual etaInterpolationPosXY* Clone()=0; /* { */
/* return new etaInterpolationPosXY(this); */
/* }; */
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());
#endif
///*Eta Distribution Rebinning*///
double bsize=1./nSubPixels; //precision
// cout<<"nPixelsX = "<<nPixelsX<<" nPixelsY = "<<nPixelsY<<" nSubPixels = "<<nSubPixels<<endl;
double tot_eta=0;
double tot_eta_x=0;
double tot_eta_y=0;
for (int ip=0; ip<nbeta*nbeta; ip++)
tot_eta+=heta[ip];
cout << "total eta entries is :"<< tot_eta << endl;
if (tot_eta<=0) {ok=0; return;};
double hx[nbeta]; //profile x
double hy[nbeta]; //profile y
double hix[nbeta]; //integral of projection x
double hiy[nbeta]; //integral of projection y
int ii=0;
double etax, etay;
for (int ib=0; ib<nbeta; ib++) {
tot_eta_x=0;
tot_eta_y=0;
for (int iby=0; iby<nbeta; iby++) {
etax=etamin+iby*etastep;
//cout << etax << endl;
if (etax>=0 && etax<=1)
hx[iby]=heta[iby+ib*nbeta];
else {
hx[iby]=0;
}
// tot_eta_x+=hx[iby];
if (etax>=0 && etax<=1)
hy[iby]=heta[ib+iby*nbeta];
else
hy[iby]=0;
// tot_eta_y+=hy[iby];
}
hix[0]=hx[0];
hiy[0]=hy[0];
for (int iby=1; iby<nbeta; iby++) {
hix[iby]=hix[iby-1]+hx[iby];
hiy[iby]=hiy[iby-1]+hy[iby];
}
ii=0;
tot_eta_x=hix[nbeta-1]+1;
tot_eta_y=hiy[nbeta-1]+1;
for (int ibx=0; ibx<nbeta; ibx++) {
if (tot_eta_x<=0) {
hhx[ibx+ib*nbeta]=-1;
//ii=(ibx)/nbeta;
} else //if (hix[ibx]>(ii+1)*tot_eta_x*bsize)
{
//if (hix[ibx]>tot_eta_x*(ii+1)/nSubPixels) ii++;
hhx[ibx+ib*nbeta]=hix[ibx]/tot_eta_x;
}
}
/* if (ii!=(nSubPixels-1)) */
/* cout << ib << " x " << tot_eta_x << " " << (ii+1)*tot_eta_x*bsize << " " << ii << " " << hix[nbeta-1]<< endl; */
ii=0;
for (int ibx=0; ibx<nbeta; ibx++) {
if (tot_eta_y<=0) {
hhy[ib+ibx*nbeta]=-1;
//ii=(ibx*nSubPixels)/nbeta;
} else {
//if (hiy[ibx]>tot_eta_y*(ii+1)/nSubPixels) ii++;
hhy[ib+ibx*nbeta]=hiy[ibx]/tot_eta_y;
}
}
}
int ibx, iby, ib;
iby=0;
while (hhx[iby*nbeta+nbeta/2]<0) iby++;
for (ib=0; ib<iby;ib++) {
for (ibx=0; ibx<nbeta;ibx++)
hhx[ibx+nbeta*ib]=hhx[ibx+nbeta*iby];
}
iby=nbeta-1;
while (hhx[iby*nbeta+nbeta/2]<0) iby--;
for (ib=iby+1; ib<nbeta;ib++) {
for (ibx=0; ibx<nbeta;ibx++)
hhx[ibx+nbeta*ib]=hhx[ibx+nbeta*iby];
}
iby=0;
while (hhy[nbeta/2*nbeta+iby]<0) iby++;
for (ib=0; ib<iby;ib++) {
for (ibx=0; ibx<nbeta;ibx++)
hhy[ib+nbeta*ibx]=hhy[iby+nbeta*ibx];
}
iby=nbeta-1;
while (hhy[nbeta/2*nbeta+iby]<0) iby--;
for (ib=iby+1; ib<nbeta;ib++) {
for (ibx=0; ibx<nbeta;ibx++)
hhy[ib+nbeta*ibx]=hhy[iby+nbeta*ibx];
}
#ifdef SAVE_ALL
debugSaveAll();
#endif
return ;
}
};
class eta2InterpolationPosXY : public virtual eta2InterpolationBase, public virtual etaInterpolationPosXY {
public:
eta2InterpolationPosXY(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),etaInterpolationPosXY(nx,ny,ns, nb, emin,emax){
// cout << "e2pxy " << nb << " " << emin << " " << emax << endl;
};
eta2InterpolationPosXY(eta2InterpolationPosXY *orig): etaInterpolationBase(orig), etaInterpolationPosXY(orig) {};
virtual eta2InterpolationPosXY* Clone() { return new eta2InterpolationPosXY(this);};
};
class eta3InterpolationPosXY : public virtual eta3InterpolationBase, public virtual etaInterpolationPosXY {
public:
eta3InterpolationPosXY(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), etaInterpolationPosXY(nx,ny,ns, nb, emin,emax){
cout << "e3pxy " << nbeta << " " << etamin << " " << etamax << " " << nSubPixels<< endl;
};
eta3InterpolationPosXY(eta3InterpolationPosXY *orig): etaInterpolationBase(orig), etaInterpolationPosXY(orig) {};
virtual eta3InterpolationPosXY* Clone() { return new eta3InterpolationPosXY(this);};
};
#endif

View File

@@ -0,0 +1,417 @@
#ifndef ETA_INTERPOLATION_RANDOMBINS_H
#define ETA_INTERPOLATION_RANDOMBINS_H
#include "tiffIO.h"
//#include "etaInterpolationBase.h"
#include "etaInterpolationPosXY.h"
#include <cstdlib>
#include <algorithm>
//#include <math>
#include <cmath> // std::abs
#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<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";
}
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;
int p0;
int vx[(nSubPixels+1)*(nSubPixels+1)], vy[(nSubPixels+1)*(nSubPixels+1)];
int arrx[nSubPixels+1], arry[nSubPixels+1];
int bad=1;
int isby, isbx;
int ii=0;
// using default comparison (operator <):
// std::sort (myvector.begin(), myvector.begin()+4); //(12 32 45 71)26 80 53 33
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) {
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;
}
sort(arrx,arrx+(nSubPixels+1)/2+1);
sort(arry,arry+(nSubPixels+1)/2+1);
// cout << "*****"<< endl;
// cout << endl;
for (int isbx=0; isbx<(nSubPixels+1)/2+1; isbx++) {
vx[isby*(nSubPixels+1)+isbx]=arrx[isbx];
vy[isbx*(nSubPixels+1)+isby]=arry[isbx];
vx[(nSubPixels-isby)*(nSubPixels+1)+(nSubPixels-isbx)]=nbeta-arrx[isbx];
vy[(nSubPixels-isbx)*(nSubPixels+1)+(nSubPixels-isby)]=nbeta-arry[isbx];
vx[isby*(nSubPixels+1)+(nSubPixels-isbx)]=nbeta-arrx[isbx];
vy[isbx*(nSubPixels+1)+(nSubPixels-isby)]=arry[isbx];
vx[(nSubPixels-isby)*(nSubPixels+1)+(isbx)]=arrx[isbx];
vy[(nSubPixels-isbx)*(nSubPixels+1)+(isby)]=nbeta-arry[isbx];
}
}
/* for (isby=0; isby<nSubPixels+1; isby++) { */
/* for (isbx=0; isbx<nSubPixels+1; isbx++) { */
/* cout << "("<< vx[isby*(nSubPixels+1)+isbx] << " " << vy[isby*(nSubPixels+1)+isbx] << ")\t";//<< endl; */
/* } */
/* cout << endl; */
/* } */
bad=0;
for (isby=1; isby<(nSubPixels+1)/2+1; isby++) {
for (isbx=1; isbx<(nSubPixels+1)/2+1; isbx++) {
if (heta[vx[isby*(nSubPixels+1)+isbx]+vy[isby*(nSubPixels+1)+isbx]*nbeta]<avg*(nSubPixels*nSubPixels)/(nbeta*nbeta)) {
// cout << ii << " " << isbx << " " << isby << " " << vx[isby*(nSubPixels+1)+isbx] << " " << vy[isby*(nSubPixels+1)+isbx] << " " << heta[vx[isby*(nSubPixels+1)+isbx]+vy[isby*(nSubPixels+1)+isbx]*nbeta] << endl;
if (nSubPixels%2==0 && isbx==nSubPixels/2)
;
else
vx[isby*(nSubPixels+1)+isbx]=rand()%(nbeta/2);
if (nSubPixels%2==0 && isbx==nSubPixels/2)
;
else
vy[isby*(nSubPixels+1)+isbx]=rand()%(nbeta/2);
if (bad==0)
ii++;
bad=1;
// break;
}
}
//if (bad) break;
}
// cout << "sort" << endl;
}
cout << ii << " sub iteractions " << avg*(nSubPixels*nSubPixels)/(nbeta*nbeta) << endl;
double m,q;
int in_quad;
int p[4];
int p1x,p2x, p1y, p2y;
// cout << nbeta << endl;
double angle;
double dtheta,theta1,theta2;
for (int ibx=0; ibx<nbeta; ibx++) {
for (int iby=0; iby<nbeta; iby++) {
in_quad=0;
/* 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; */
/* 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; */
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;
while (dtheta > PI)
dtheta -= TWOPI;
while (dtheta < -PI)
dtheta += TWOPI;
angle += dtheta;
}
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);
}
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){};
etaInterpolationRandomBins(etaInterpolationRandomBins *orig): etaInterpolationPosXY(orig){};
virtual etaInterpolationRandomBins* Clone() {
return new etaInterpolationRandomBins(this);
};
virtual void prepareInterpolation(int &ok)
{
ok=1;
cout << "Adaptive bins" << endl;
///*Eta Distribution Rebinning*///
double bsize=1./nSubPixels; //precision
// cout<<"nPixelsX = "<<nPixelsX<<" nPixelsY = "<<nPixelsY<<" nSubPixels = "<<nSubPixels<<endl;
double tot_eta=0;
for (int ip=0; ip<nbeta*nbeta; ip++)
tot_eta+=heta[ip];
if (tot_eta<=0) {ok=0; return;};
int ii=0;
int nint=1000;
double thr=1./((double)nSubPixels);
double avg=tot_eta/((double)(nSubPixels*nSubPixels));
cout << "total eta entries is :"<< tot_eta << " avg: "<< avg << endl;
cout << "Start " << endl;
double old_diff=-1, new_diff=-1;
// cout << " diff= " << new_diff << endl;
etaInterpolationPosXY::prepareInterpolation(ok);
old_diff=calcDiff(avg, hhx, hhy);
cout << " diff= " << old_diff << endl;
int iint=0;
float *newhhx=new float[nbeta*nbeta]; //profile x
float *newhhy=new float[nbeta*nbeta]; //profile y
int igood=0, ibad=0;
#ifdef SAVE_ALL
int etabins=nbeta;
float *etah=new float[nbeta*nbeta];
char tit[1000];
#endif
while (iint<nint) {
cout << "Iteration " << iint << endl;
new_diff=iterate(newhhx,newhhy, avg);
//new_diff=calcDiff(avg, newhhx, newhhy);
cout << " diff= " << new_diff << " ( " << old_diff<< " ) " << endl;
/* #ifdef SAVE_ALL */
/* for (int ii=0; ii<etabins*etabins; ii++) { */
/* etah[ii]=newhhx[ii]; */
/* if (etah[ii]>1 || 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; ii<etabins*etabins; ii++) { */
/* etah[ii]=newhhy[ii]; */
/* if (etah[ii]>1 || etah[ii]<0 ) cout << "***"<< ii << etah[ii] << endl; */
/* } */
/* sprintf(tit,"/scratch/randeta_hhy_%d.tiff",iint); */
/* WriteToTiff(etah, tit, etabins, etabins); */
/* #endif */
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++;
iint++;
}
delete [] newhhx;
delete [] newhhy;
cout << "performed " << iint << " iterations of which " << igood << " positive " << endl;
/* #ifdef SAVE_ALL */
/* for (int ii=0; ii<etabins*etabins; ii++) { */
/* etah[ii]=hhx[ii]; */
/* } */
/* sprintf(tit,"/scratch/eta_hhx_%d.tiff",id); */
/* WriteToTiff(etah, tit, etabins, etabins); */
/* for (int ii=0; ii<etabins*etabins; ii++) { */
/* etah[ii]=hhy[ii]; */
/* } */
/* sprintf(tit,"/scratch/eta_hhy_%d.tiff",id); */
/* WriteToTiff(etah, tit, etabins, etabins); */
/* for (int ii=0; ii<etabins*etabins; ii++) { */
/* etah[ii]=heta[ii]; */
/* } */
/* sprintf(tit,"/scratch/eta_%d.tiff",id); */
/* WriteToTiff(etah, tit, etabins, etabins); */
/* delete [] etah; */
/* #endif */
return ;
}
};
#endif

View File

@@ -0,0 +1,678 @@
#include <TH1D.h>
#include <TH2D.h>
#include <TPad.h>
#include <TDirectory.h>
#include <TEntryList.h>
#include <TFile.h>
#include <TMath.h>
#include <TTree.h>
#include <TChain.h>
#include <THStack.h>
#include <TCanvas.h>
#include <TF1.h>
#include <TLegend.h>
#include <stdio.h>
#include <iostream>
#include <deque>
#include <list>
#include <queue>
#include <fstream>
#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.
*/
int etabins = 25;
int nEtas = 25;
Double_t dum[3][3];
Int_t x,y,f,q;
int counter[5];
int remoteCounter[5];
//TH2D *sum = new TH2D("sum","sum",3,-0.1,2.1,3,-0.1,2.1);
//TH2F *subPos = new TH2F("subPos","subPos", 100, -1.,1. ,100, -1.,1.);
TH2D *subPosAEta = new TH2D("subPosAEta","subPosAEta", 50, -.5,1.5 ,50, -.5,1.5);
TH2D *subPosBEta = new TH2D("subPosBEta","subPosBEta", 50, -.5,1.5 ,50, -.5,1.5);
TH1D *cE = new TH1D("clusterEnergy","clusterEnergy",400, 0.,4000.);
//TH1D *cES = new TH1D("clusterEnergyS","clusterEnergyS",400, 0.,4000.);
TH2D *cES3vs2 = new TH2D("clusterEnergy3vs2","clusterEnergy3vs2",800, 0.,8000.,600,0.,6000.);
TH2D *cES3vs2S = new TH2D("clusterEnergy3vs2S","clusterEnergy3vs2S",800, 0.,8000.,600,0.,6000.);
double th = 0.99;
double sigmas = 1.0;
TH2D *imgRLR = new TH2D("imgRLR","imgRLR",160,0.0,160.0 ,160 ,0.0,160.0);
TH2D *imgLR = new TH2D("imgLR","imgLR",160*2,0.0,160.0 ,160*2 ,0.0,160.0);
TH2D *clusHist= new TH2D("clusHist","clusHist",3,-0.5,2.5,3,-0.5,2.5);
TH2D *clusHistC= new TH2D("clusHistC","clusHistC",3,-0.5,2.5,3,-0.5,2.5);
int **imgArray;
int findShape(Double_t cluster[3][3], double sDum[2][2]){
int corner = -1;
double sum = cluster[0][0] + cluster[1][0] + cluster[2][0] + cluster[0][1] + cluster[1][1] + cluster[2][1] + cluster[0][2] + cluster[1][2] + cluster[2][2];
double sumTL = cluster[0][0] + cluster[1][0] + cluster[0][1] + cluster[1][1]; //2 ->BL
double sumTR = cluster[1][0] + cluster[2][0] + cluster[2][1] + cluster[1][1]; //0 ->TL
double sumBL = cluster[0][1] + cluster[0][2] + cluster[1][2] + cluster[1][1]; //3 ->BR
double sumBR = cluster[1][2] + cluster[2][1] + cluster[2][2] + cluster[1][1]; //1 ->TR
double sumMax = 0;
//double **sDum = subCluster;
Double_t ssDum[2][2];
// if(sumTL >= sumMax){
sDum[0][0] = cluster[0][0]; sDum[1][0] = cluster[1][0];
sDum[0][1] = cluster[0][1]; sDum[1][1] = cluster[1][1];
ssDum[0][0] = cluster[0][0]; ssDum[1][0] = cluster[0][1];
ssDum[0][1] = cluster[1][0]; ssDum[1][1] = cluster[1][1];
corner = 2;
sumMax=sumTL;
// }
if(sumTR >= sumMax){
sDum[0][0] = cluster[1][0]; sDum[1][0] = cluster[2][0];
sDum[0][1] = cluster[1][1]; sDum[1][1] = cluster[2][1];
ssDum[0][0] = cluster[2][0]; ssDum[1][0] = cluster[2][1];
ssDum[0][1] = cluster[1][0]; ssDum[1][1] = cluster[1][1];
corner = 0;
sumMax=sumTR;
}
if(sumBL >= sumMax){
sDum[0][0] = cluster[0][1]; sDum[1][0] = cluster[1][1];
sDum[0][1] = cluster[0][2]; sDum[1][1] = cluster[1][2];
ssDum[0][0] = cluster[0][2]; ssDum[1][0] = cluster[0][1];
ssDum[0][1] = cluster[1][2]; ssDum[1][1] = cluster[1][1];
corner = 3;
sumMax=sumBL;
}
if(sumBR >= sumMax){
sDum[0][0] = cluster[1][1]; sDum[1][0] = cluster[2][1];
sDum[0][1] = cluster[1][2]; sDum[1][1] = cluster[2][2];
ssDum[0][0] = cluster[2][2]; ssDum[1][0] = cluster[2][1];
ssDum[0][1] = cluster[1][2]; ssDum[1][1] = cluster[1][1];
corner = 1;
sumMax=sumBR;
}
switch(corner){
case 0:
cES3vs2->Fill(sum,sumTR); break;
case 1:
cES3vs2->Fill(sum,sumBR); break;
case 2:
cES3vs2->Fill(sum,sumTL); break;
case 3:
cES3vs2->Fill(sum,sumBL); break;
}
counter[corner]++;
remoteCounter[q]++;
// cout << "local corner is: " << corner << " remote corner is: " << q << endl;
return corner;
}
int placePhoton( TH2D *img, double subCluster[2][2], int cX, int cY, int corner, double *sX, double *sY, double *scX, double *scY){
double tot = subCluster[0][0] + subCluster[0][1] + subCluster[1][0] + subCluster[1][1];
double t = subCluster[1][0] + subCluster[1][1];
double r = subCluster[0][1] + subCluster[1][1];
double xHitC = r/tot;
double yHitC = t/tot;
imgRLR->Fill(cX,cY);
cE->Fill(tot);
double dX, dY;
//before looking at annas code
/* if(corner == 0){ dX=-1.; dY=-1.; }
if(corner == 1){ dX=-1.; dY=+1.; }
if(corner == 2){ dX=+1.; dY=-1.; }
if(corner == 3){ dX=+1.; dY=+1.; }*/
if(corner == 0){ dX=-1.; dY=+1.; } //top left
if(corner == 1){ dX=+1.; dY=+1.; } //top right
if(corner == 2){ dX=-1.; dY=-1.; } //bottom left
if(corner == 3){ dX=+1.; dY=-1.; } //bottom right
imgLR->Fill(cX+0.25*dX,cY+0.25*dY);
double posX = ((double)cX) + 0.5*dX + xHitC;
double posY = ((double)cY) + 0.5*dY + yHitC;
subPosBEta->Fill(xHitC ,yHitC);
if(img){
img->Fill(posX,posY);
}
if(xHitC < 0.02&& yHitC < 0.02){
cES3vs2S->Fill(dum[0][0]+dum[0][1]+dum[0][2]+dum[1][0]+dum[1][1]+dum[1][2]+dum[2][0]+dum[2][1]+dum[2][2],subCluster[0][0]+subCluster[0][1]+subCluster[1][0]+subCluster[1][1]);
}
if(sX && sY && scX && scY){
*sX = xHitC; //0.5 + 0.5*dX + xHitC;
*sY = yHitC; //0.5 + 0.5*dY + yHitC;
*scX = ((double)cX) + 0.5*dX;
*scY = ((double)cY) + 0.5*dY;
}
return 1;
}
void placePhotonCorr(TH2D *img, EtaVEL *e,double sX, double sY, double scX, double scY){
int bin = e->findBin(sX,sY);
if(bin <= 0) return;
double subX = ((double)(e->getXBin(bin))+.5)/((double)e->getNPixels());
double subY = ((double)(e->getYBin(bin))+.5)/((double)e->getNPixels());
if(img!=NULL){
img->Fill(scX+ subX , scY+ subY);
}
subPosAEta->Fill(subX,subY);
int iscx = scX;
int iscy = scY;
if(iscx >=nx || iscx<0 || iscy >=ny || iscy<0) return;
//cout << iscx*e->getNPixels()+e->getXBin(bin) << " " << iscy*e->getNPixels()+e->getXBin(bin) << endl;
if(img==NULL) return;
imgArray[iscx*e->getNPixels()+e->getXBin(bin)][iscy*e->getNPixels()+e->getYBin(bin)]++;
}
void gainCorrection(Double_t corrected[3][3], TH2D *gainMap){
for(int xx = 0; xx < 3; xx++)
for(int yy = 0; yy < 3; yy++){
if(gainMap && gainMap->GetBinContent(x+xx+2,y+yy+2) != 0){
corrected[xx][yy] = dum[xx][yy] / gainMap->GetBinContent(x+xx+2,y+yy+2);
clusHistC->Fill(xx,yy,corrected[xx][yy]);
}
else
corrected[xx][yy] = dum[xx][yy];
clusHist->Fill(xx,yy,dum[xx][yy]);
}
}
EtaVEL *plotEtaDensity(TChain* tree2, TEntryList *el, EtaVEL *oldEta = NULL, TH2D **img = NULL, TH2D *gainMap=NULL, int nPixels=25) {
EtaVEL *newEta = new EtaVEL(25,-0.02,1.02);
Long64_t listEntries=el->GetN();
Long64_t treeEntry;
Long64_t chainEntry;
Int_t treenum=0;
tree2->SetEntryList(el);
double gainCorrC[3][3];
double subCluster[2][2];
double sX, sY, scX, scY;
cout << "Events: " << listEntries << endl;
if(oldEta == NULL){ cout << "Old Eta is NULL " << endl; }
for(int i = 0; i<4; i++){ counter[i] = 0; remoteCounter[i] = 0; }
for (Long64_t il =0; il<listEntries;il++) {
treeEntry = el->GetEntryAndTree(il,treenum);
chainEntry = treeEntry+tree2->GetTreeOffset()[treenum];
if (tree2->GetEntry(chainEntry)) {
gainCorrection(gainCorrC,gainMap);
//cout << gainCorrC[1][1] << endl;
//finds corner
int corner = findShape(gainCorrC,subCluster);
int validEvent;
if(img){
validEvent = placePhoton(img[0],subCluster,x,y, corner, &sX, &sY, &scX, &scY);
}else{
//calc etaX, etaY
validEvent = placePhoton(NULL,subCluster,x,y, corner, &sX, &sY, &scX, &scY);
}
//fill etavel
newEta->fill(sX,sY);
if(oldEta && img && img[1]){
placePhotonCorr(img[1],oldEta, sX,sY, scX, scY);
}else{
placePhotonCorr(NULL,newEta,sX,sY,scX,scY);
}
}
//cout << il << endl;
int ssize = 500000;
if(il % ssize == 0 && il != 0 && oldEta==NULL){
cout << " -------------- "<< endl;
newEta->updatePixelPos();
//newEta->resolveSelfIntersect();
char tit[1000];
/* TFile *ff = new TFile("/scratch/Spider.root","UPDATE");
sprintf(tit,"subPosAEta%i",newEta->getIt()); subPosAEta->SetName(tit);
subPosAEta->Write(); subPosAEta->Reset();
sprintf(tit,"subPosBEta%i",newEta->getIt()); subPosBEta->SetName(tit);
subPosBEta->Write(); subPosBEta->Reset();
sprintf(tit,"Eta%i",newEta->getIt()); newEta->Write(tit);
ff->Close(); */
//il = 0;
}
if(il % ssize == ssize-1){
double prog = (double)il/(double)listEntries*100.;
cout << prog << "%" << endl;
//if(prog > 19.) return newEta;
if(newEta->converged == 1){ cout << "converged ... " << endl; return newEta; }
}
}
cout << "local corners: " ;
for(int i = 0; i<4; i++) cout << i << ": " << counter[i] << " || " ;
cout << endl;
//cout << "remote corners: " ;
//for(int i = 0; i<4; i++) cout << i << ": " << remoteCounter[i] << " || " ;
//cout << endl;
return newEta;
}
TChain *openTree(char *tname, char *fname,double lEc, double hEc, double rms=5., char *chainName=">>thischan"){
TChain *tree2;
// TH1D **etaDI;
char cut[1000];
tree2=new TChain(tname);
tree2->Add(fname);
tree2->Print();
//sprintf(cut,"(x<=40) && (data[%d][%d]>%f*rms) && Sum$(data)<%f && Sum$(data)>%f",1,1,rms, hEc, lEc);
// sprintf(cut,"(x<=40) && (data[%d][%d]>%f*rms)",1,1,rms);// && Sum$(data)<%f && Sum$(data)>%f",1,1,rms, hEc, lEc);
sprintf(cut,"(x<=40) && Sum$(data)<%f && Sum$(data)>%f", hEc, lEc);
// sprintf(cut,"");
cout << cut << endl;
tree2->Draw(chainName, cut, "entrylist");
tree2->SetBranchAddress("iFrame",&f);
tree2->SetBranchAddress("x",&x);
tree2->SetBranchAddress("y",&y);
tree2->SetBranchAddress("data",dum);
//tree2->SetBranchAddress("q",&q);
cout << "openTree : end" << endl;
return tree2;
}
EtaVEL *etaDensity(char *tname, char *fname, double lEc = 1000, double hEc=3000, TH2D *gainMap=NULL, int nPixels=25) {
/** open tree and make selection */
TChain *tree2 = openTree(tname,fname,lEc,hEc);
TEntryList *elist = (TEntryList*)gDirectory->Get("thischan");
if(elist == NULL) { cout << "could not open tree " << endl; return NULL; }
EtaVEL *etaDen = plotEtaDensity(tree2,elist,NULL,NULL,gainMap,nPixels);
//etaDen->Draw("colz");
cout << "done" << endl;
return etaDen;
}
void interpolate(char *tname, char *fname, EtaVEL *etaDI, double lEc = 1000, double hEc=3000, TH2D *gainMap=NULL) {
TChain *tree2 = openTree(tname,fname,lEc,hEc,5.,">>intChain");
TEntryList *elist = (TEntryList*)gDirectory->Get("intChain");
if(elist == NULL) { cout << "could not open tree " << endl; return; }
double nPixels = (double)etaDI->getNPixels();
TH2D **img = new TH2D*[3];
img[0] = new TH2D("img","img",nPixels*160,0.0,160.0 ,nPixels*160 ,0.0,160.0);
img[1] = new TH2D("imgE","imgE",nPixels*160,0.0,160.0 ,nPixels*160 ,0.0,160.0);
int inPixels = etaDI->getNPixels();
imgArray = new int*[inPixels*160];
for(int i = 0; i < inPixels*160; i++){
imgArray[i] = new int[inPixels*160];
for(int j = 0; j < inPixels*160; j++){
imgArray[i][j] = 0;
}
}
cout << "starting" << endl;
plotEtaDensity(tree2,elist, etaDI,img,gainMap);
//img->Draw("colz");
}
TH2D *createGainMap(char *tname, char *fname, double lEc = 0,double hEc=10000){
char name[100];
TH1D *avgSpec3 = new TH1D("avgSpec3", "avgSpec3",hEc/20,0,hEc);
TH1D ***specs3 = new TH1D**[160];
TH1D ***specs1 = new TH1D**[160];
for(int xx = 0; xx < 160; xx++){
specs3[xx] = new TH1D*[160];
specs1[xx] = new TH1D*[160];
for(int yy = 0; yy < 160; yy++){
sprintf(name,"S3x%iy%i",xx,yy);
specs3[xx][yy] = new TH1D(name,name,hEc/20,0,hEc);
sprintf(name,"S1x%iy%i",xx,yy);
specs1[xx][yy] = new TH1D(name,name,hEc/20,0,hEc);
}
}
TChain *tree2 = openTree(tname,fname,0,hEc,5.,">>gainChan");
TEntryList *elist = (TEntryList*)gDirectory->Get("gainChan");
if(elist == NULL) { cout << "could not open tree " << endl; return NULL; }
Long64_t listEntries=elist->GetN();
Long64_t treeEntry;
Long64_t chainEntry;
Int_t treenum=0;
tree2->SetEntryList(elist);
cout << "Events: " << listEntries << endl;
for(int i = 0; i<4; i++) counter[i] = 0;
for (Long64_t il =0; il<listEntries;il++) {
treeEntry = elist->GetEntryAndTree(il,treenum);
chainEntry = treeEntry+tree2->GetTreeOffset()[treenum];
if (tree2->GetEntry(chainEntry)) {
double sum = 0;
for(int xx = 0; xx < 3; xx++)
for(int yy = 0; yy < 3; yy++)
sum += dum[xx][yy];
specs3[x][y]->Fill(sum);
specs1[x][y]->Fill(dum[1][1]);
avgSpec3->Fill(sum);
}
}
TH2D *gainMap3 = new TH2D("gainMap3","gainMap3",160,-0.5,160.-0.5,160,-.5,160.-.5);
TH2D *gainMap1 = new TH2D("gainMap1","gainMap1",160,-0.5,160.-0.5,160,-.5,160.-.5);
for(int xx = 0; xx < 160; xx++){
for(int yy = 0; yy < 160; yy++){
TF1 *gf3 = new TF1("gf3","gaus", lEc, hEc);
specs3[xx][yy]->Fit(gf3,"Q");
double e3 = gf3->GetParameter(1);
gainMap3->Fill(xx,yy,e3);
TF1 *gf1 = new TF1("gf1","gaus", lEc, hEc);
specs1[xx][yy]->Fit(gf1,"Q");
double e1 = gf1->GetParameter(1);
gainMap1->Fill(xx,yy,e1);
}
}
return gainMap3;
}
void writeMatlab2DHisto(int xx, int yy,char *outFileName){
ofstream outFile;
outFile.open (outFileName);
cout << "create matlab file with " << xx << " xbins and " << yy << " ybins" << endl;
for(int y = 0; y < yy; y++){
for(int x = 0; x < xx; x++){
outFile << imgArray[x][y] << "\t";
}
outFile << endl;
}
outFile.close();
}
//COMPLETE STUFF
void createImage(char *tdir, char *tname, char *ftname, char *ifname = NULL, int useGM=0, double lEth=-1., double hEth=-1.){
imgRLR->Reset();
imgLR->Reset();
char fname[1000];
char inFName[1000];
char outFName[1000];
char moutFName[1000];
if(ifname == NULL){
sprintf(fname,"%s/%s_*.root",tdir,tname);
}else{
sprintf(fname,"%s",ifname);
}
if(useGM) sprintf(inFName,"%s/%s-PlotsWGMVEL.root",tdir,ftname);
else sprintf(inFName,"%s/%s-PlotsVEL.root",tdir,ftname);
sprintf(outFName,"%s/%s-ImgVEL.root",tdir,tname);
sprintf(moutFName,"%s/%s-ImgVEL.mf",tdir,tname);
TFile *inFile = new TFile(inFName,"READ");
cout << "Image Tree File Name: " << fname << endl;
cout << "Eta File Name: " << inFName << endl;
cout << "Out File Name: " << outFName << endl;
cout << "Matlab Out File Name: " << moutFName << endl;
TH2D *gm = NULL;
if(useGM){
cout << "Load gain map" << endl;
gm = (TH2D *)gDirectory->Get("gainMap");
if(gm == NULL){ cout << "can not find gainMap in file" << endl; return; }
}
cout << "Load eta" << endl;
EtaVEL *ee = (EtaVEL *)gDirectory->Get("etaDist");
cout << "Select Energy BW" << endl;
TH1D *spec = (TH1D *)gDirectory->Get("avgSpec3");
if(spec == NULL){ cout << "can not find avgSpec3" << endl; return; }
TF1 *gf3 = new TF1("gf3","gaus", 0, 10000);
spec->Fit(gf3,"Q");
double avgE = gf3->GetParameter(1);
double sigE = gf3->GetParameter(2);
cout << "avgE: " << avgE << " sigE: " << sigE << endl;
cout << endl;
if(lEth == -1.) lEth = avgE-5.*sigE;
if(hEth == -1.) hEth = avgE+5.*sigE;
cout << lEth << " < E < " << hEth << " (eV)" << endl;
cout << "start with interpolation" << endl;
interpolate( tname, fname, ee,lEth,hEth ,gm);
TH2D *img = (TH2D *)gDirectory->Get("img");
if(img == NULL){ cout << "could not find 2d-histogram: img " << endl; return; }
TH2D *imgE = (TH2D *)gDirectory->Get("imgE");
if(imgE == NULL){ cout << "could not find 2d-histogram: imgE " << endl; return; }
//TH2D *imgEOM = (TH2D *)gDirectory->Get("imgEOM");
//if(imgEOM == NULL){ cout << "could not find 2d-histogram: imgEOM " << endl; return; }
TFile *outFile = new TFile(outFName,"UPDATE");
imgLR->Write();
imgRLR->Write();
imgE->Write();
//imgEOM->Write();
img->Write();
outFile->Close();
inFile->Close();
cout << "writing matlab file: " << moutFName << endl;
writeMatlab2DHisto(160*ee->getNPixels(),160*ee->getNPixels(),moutFName);
cout << "Done : " << outFName << endl;
}
/**
\par tdir input tree directory
\par tname input tree name
\par ifname input file name if different than tdir/tname_*.root
\par useGM use gain map
\par maxExpEinEv spectrum maximum
\par nPixels sub-pixels bins
\par lEth low threshold
\par hEth high threshold
*/
EtaVEL *createGainAndEtaFile(char *tdir, char *tname, char *ifname=NULL, int useGM=0, double maxExpEinEv=25000., int nPixels =25, double lEth=-1., double hEth=-1.){
char fname[1000];
char outFName[1000];
if(ifname == NULL){
sprintf(fname,"%s/%s_*.root",tdir,tname);
}else{
sprintf(fname,"%s",ifname);
}
if(useGM) sprintf(outFName,"%s/%s-PlotsWGVEL.root",tdir,tname);
else sprintf(outFName,"%s/%s-PlotsVEL.root",tdir,tname);
cout << "Tree File Name: " << fname << endl;
cout << "Output File Name: " << outFName << endl;
/** creates gain map and 3x3 spectrum */
cout << "Creating gain map: " << endl;
TH2D *gm = createGainMap(tname,fname,0,maxExpEinEv/10.);
gm->SetName("gainMap");
/** gets average 3x3 spectrum and fits it with a gaus */
TH1D *spec = (TH1D *)gDirectory->Get("avgSpec3");
if(spec == NULL){ cout << "can not find avgSpec3" << endl; return NULL; }
TF1 *gf3 = new TF1("gf3","gaus", 0, maxExpEinEv/10.);
spec->Fit(gf3,"Q");
double avgE = gf3->GetParameter(1);
double sigE = gf3->GetParameter(2);
cout << "avgE: " << avgE << " sigE: " << sigE << endl;
cout << endl;
/** sets high and low threshold if not given by the user */
if(lEth == -1.) lEth = avgE-5.*sigE;
if(hEth == -1.) hEth = avgE+5.*sigE;
cout << lEth << " < E < " << hEth << " (eV)" << endl;
cout << "calculating eta stuff" << endl;
EtaVEL *newEta;
if(useGM) newEta = etaDensity(tname,fname,lEth,hEth,gm,nPixels);
else newEta = etaDensity(tname,fname,lEth,hEth,NULL,nPixels);
cout << "writing to file " << outFName << endl;
TFile *outFile = new TFile(outFName,"UPDATE");
newEta->Write("etaDist");
gm->Write();
spec->Write();
subPosAEta->Write();
cES3vs2->Write();
outFile->Close();
cout << "Done : " << outFName << endl;
return newEta;
}
void exportSpec(char *tdir, char *tname){
char tfname[1000];
char ofname[1000];
char cleanName[1000];
for(int p = 0; p < strlen(tname);p++){
cleanName[p+1] = '\0';
cleanName[p] = tname[p];
if(tname[p] == '-') cleanName[p] = '_';
}
sprintf(tfname,"%s/%s-PlotsVEL.root",tdir,tname);
sprintf(ofname,"%s/%s_SpecVEL.m",tdir,cleanName);
TFile *tf = new TFile(tfname);
TH1D *spec = (TH1D *)gDirectory->Get("avgSpec3");
ofstream outFile;
outFile.open (ofname);
if(outFile.fail()){
cout << "Could not open file : " << ofname << endl;
return;
}
cout << "create matlab file with with spec " << ofname << endl;
outFile << cleanName << " = [ " << endl;
for(int i = 0; i < spec->GetNbinsX(); i++){
outFile << i << " " << spec->GetBinCenter(i) << " " << spec->GetBinContent(i) << " ; " << endl;
}
outFile << " ] ; " << endl;
outFile.close();
}

View File

@@ -0,0 +1,679 @@
#include "EtaVEL.h"
#include <iomanip>
// ClassImp(EtaVEL);
// double Median(const TH1D * histo1) {
// int numBins = histo1->GetXaxis()->GetNbins();
// Double_t *x = new Double_t[numBins];
// Double_t* y = new Double_t[numBins];
// for (int i = 0; i < numBins; i++) {
// x[i] = histo1->GetBinCenter(i);
// y[i] = histo1->GetBinContent(i);
// }
// 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)];
//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;
}
int EtaVEL::findBin(double xx, double yy){
double tlX,tlY,trX,trY,blX,blY,brX,brY;
/********Added by anna ******/
// if (xx<min) xx=min+1E-6;
// if (xx>max) xx=max-1E-6;
// if (yy<min) yy=min+1E-6;
// if (yy>max) 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 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);
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;
}
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)];
}
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);
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;
cout << "linear sys stuff" << endl;
double minELength = 100000000000000; int minX=-1, minY=-1;
for(int y = 0; y < nPixels+1; y++){
for(int x = 0; x < nPixels+1; x++){
double bx = 0, by = 0;
//boundary conditions
if((x == 0 && y % 5 == 0) ||
(x == nPixels && y % 5 == 0) ||
(y == 0 && x % 5 == 0) ||
(y == nPixels && x % 5 == 0)){
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++;
}
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)];
/*cout << "Corner X:" <<x << " Y: " << y ;
cout << " C# " << getCorner(x,y);
cout << " eXl " << getEdgeX(x-1,y) << "(C# " << getCorner(x-1,y) << " ) ";
cout << " eXr " << getEdgeX(x,y) << "(C# " << getCorner(x+1,y) << " ) ";
cout << " eYb " << getEdgeY(x,y-1) << "(C# " << getCorner(x,y-1) << " ) ";
cout << " eYt " << getEdgeY(x,y) << "(C# " << getCorner(x,y+1) << " ) " << endl; */
//" totW: " << tot << " totE: " << eLength << endl;
if(eLength < minELength & tot == 4){
minELength = eLength;
minX = x; minY = y;
}
//matrixes updated
if(x != 0) posMat[y*(nPixels+1)*cols+x*cols+getCorner(x-1,y)-1] = -edgeL[getEdgeX(x-1,y)]/eLength;
if(y != 0) posMat[y*(nPixels+1)*cols+x*cols+getCorner(x,y-1)-1] = -edgeL[getEdgeY(x,y-1)]/eLength;;
if(x != nPixels) posMat[y*(nPixels+1)*cols+x*cols+getCorner(x+1,y)-1] = -edgeL[getEdgeX(x,y)]/eLength;;
if(y != nPixels) posMat[y*(nPixels+1)*cols+x*cols+getCorner(x,y+1)-1] = -edgeL[getEdgeY(x,y)]/eLength;;
posMat[y*(nPixels+1)*cols+x*cols+getCorner(x,y)-1] = 1.;
rVx[getCorner(x,y)-1] = 0.;
rVy[getCorner(x,y)-1] = 0.;
}
}
cout << "Min Corner X: " <<minX << " Y: " << minY << " C# " << getCorner(minX,minY) << " length " << minELength << endl;
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
Bool_t ok;
TDecompSVD *s = new TDecompSVD(*k);
s->Solve(*fx);
s->Solve(*fy);
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
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;
cout << "update edge lengths" << endl;
for(int x = 0; x < nPixels; x++)
for(int y = 0; y < nPixels; y++){
/*cout << "Pixel X:" <<x << " Y: " << y << " P# " << getBin(x,y) << " eXb " << getEdgeX(x,y);
cout << " eXt " << getEdgeX(x,y+1) << " eYl " << getEdgeY(x,y) << " eYr " << getEdgeY(x+1,y) << endl;
*/
edgeL[getEdgeX(x,y)] *= chMap[getBin(x,y)];
edgeL[getEdgeX(x,y+1)] *= chMap[getBin(x,y)];
edgeL[getEdgeY(x,y)] *= chMap[getBin(x,y)];
edgeL[getEdgeY(x+1,y)] *= chMap[getBin(x,y)];
//cout << "Pixel x: " << x << " y: " << y << " Ch: " << chMap[getBin(x,y)] << " counts: " << binCont[getBin(x,y)] << endl;
//cout << "BE " << getEdgeX(x,y) << endl;
//cout << "TE " << getEdgeX(x,y+1) << endl;
//cout << "LE " << getEdgeY(x,y) << endl;
//cout << "RE " << getEdgeY(x+1,y) << endl;
binCont[getBin(x,y)] = 0;
}
updatePixelCorner();
//double *pSize = getSizeMap();
double totEdgeLength = 0;
for(int e = 1; e < 2*nPixels*(nPixels+1)+1; e++){
totEdgeLength += edgeL[e];
}
cout << "tot edge Length: " << totEdgeLength << endl;
totCont = 0.;
}
double *EtaVEL::getSizeMap(){
double tlX,tlY,trX,trY,blX,blY,brX,brY;
double *szMap = new double[nPixels*nPixels+1];
for(int x = 1; x < nPixels-1; x++)
for(int y = 1; y < nPixels-1; 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];
//double area = dtl * dtr / 2. + dtr * dbr / 2. + dbr * dbl / 2. + dbl * dtl / 2.;
//http://en.wikipedia.org/wiki/Shoelace_formula
double sl1 = tlX * trY + trX * brY + brX * blY + blX * tlY;
double sl2 = tlY * trX + trY * brX + brY * blX + blY * tlX;
double area = 1./2. * (- sl1 + sl2);
if(area < 0.){
cout << "negative area: X " << x << " Y " << y << " area " << endl;
edgeL[getEdgeX(x,y)] *= 2.;
edgeL[getEdgeX(x,y+1)] *= 2.;
edgeL[getEdgeY(x,y)] *= 2.;
edgeL[getEdgeY(x+1,y)] *= 2.;
}
szMap[getBin(x,y)] = area / (max - min) / (max - min) * nPixels * nPixels;
delete[] c;
}
return szMap;
}
double *EtaVEL::getChangeMap(){
double *chMap = new double[nPixels*nPixels+1];
double avg = totCont/(double)(nPixels*nPixels);
// TH1D *hmed=getCounts();
// double med = Median(hmed);
// delete hmed;
double acc = TMath::Sqrt(avg);
cout << "totC: " << totCont << " avg " << avg << " acc: " << acc << endl;//<< " med " << med
double totOffAcc = 0.;
int totInRange03s = 0;
int totInRange07s = 0;
int totInRange12s = 0;
int totInRange20s = 0;
int totInRange25s = 0;
double dd;
int totInBins = 0;
//double
chi_sq=0;
int maxC = 0, maxX=-1, maxY=-1;
double minC = 1000000000000000, minX, minY;
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.;
}
//if(r < avg + 2*acc && r > avg - 2*acc){ totInRange++;}// 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++; }
*/
//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;
// 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;
}
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(){
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;
}
}
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];
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);
}
}
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;
}
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;
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];
cout << "d";
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;
b >> min;
b >> max;
b >> ds;
b >> nPixels;
b >> it;
b >> totCont;
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++){
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;
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++){
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];
}
}
}
}

View File

@@ -0,0 +1,164 @@
#include <iostream>
#include <TGraph.h>
#include <TAxis.h>
#include <TMultiGraph.h>
#include <TH2D.h>
#include <TMath.h>
#include <TObject.h>
#include <TBuffer.h>
#include <TMatrixD.h>
#include <TDecompSVD.h>
//#include <TDecompQRH.h>
#include <TH1.h>
#include <TMath.h>
#include <vector>
#include <ostream>
#include <istream>
using namespace std;
#ifndef ETAVPS
#define ETAVPS
typedef struct {
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;
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 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];
}
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;
}
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;
}
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;
}
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 getIt(){ return it; };
int getNPixels(){ return nPixels; }
double *getXPPos(){ return xPPos; }
double *getYPPos(){ return yPPos; }
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();
void serialize(ostream &o);
void deserialize(istream &is);
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-;
};
#endif

View File

@@ -0,0 +1,393 @@
import numpy as np
import math
maxf = 2
minf = 0.5
class EtaVELTr:
def __init__(self, numberOfPixels = 25, minn=0., maxx=1.):
self.nPixels = numberOfPixels
self.nCorners = self.nPixels + 1
self.minEta = minn
self.maxEta = maxx
#self.corners = []
self.edgesX = []
self.edgesY = []
self.edgesE = []
self.edgesF = []
self.edgesG = []
self.edgesH = []
self.counts = []
self.pOffset = (self.maxEta-self.minEta)/self.nPixels
self.cPosX = []
self.cPosY = []
self.zPosX = []
self.zPosY = []
self.sqSums = []
self.cIteration = 0
self.bSqSum = 0
self.initGrid()
#self.calculatePixelCorners()
self.update()
def initGrid(self):
dd = 1 / math.sqrt(2)
#self.corners = [ [self.minEta + x * pOffset, self.minEta + y * pOffset] for y in range(self.nPixels)] for x in range(self.nPixels)
self.cPosX = [ [self.minEta + x * self.pOffset for x in range(self.nCorners)] for y in range(self.nCorners) ]
self.cPosY = [ [self.minEta + y * self.pOffset for x in range(self.nCorners)] for y in range(self.nCorners) ]
self.counts = [ [ [0,0,0,0] for x in range(self.nPixels) ] for y in range(self.nPixels) ]
self.edgesX = [ [ 1 for x in range(self.nCorners) ] for y in range(self.nCorners + 1) ]
self.edgesY = [ [ 1 for x in range(self.nCorners+1) ] for y in range(self.nCorners) ]
self.edgesE = [ [ dd for x in range(self.nPixels) ] for y in range(self.nPixels) ]
self.edgesF = [ [ dd for x in range(self.nPixels) ] for y in range(self.nPixels) ]
self.edgesG = [ [ dd for x in range(self.nPixels) ] for y in range(self.nPixels) ]
self.edgesH = [ [ dd for x in range(self.nPixels) ] for y in range(self.nPixels) ]
def update(self):
self.normalizeEdgeLengths()
self.calculateEdgeLengths2()
self.calculatePixelCorners2()
conv = False
out = 0
outList = []
tot = self.nPixels*self.nPixels*4
sqSum = 0
avg = self.getAvgCounts()
avgPS = self.getAvgCounts() + 1*math.sqrt(self.getAvgCounts())
avgMS = self.getAvgCounts() - 1*math.sqrt(self.getAvgCounts())
for y in range(self.nPixels):
for x in range(self.nPixels):
for t in range(4):
sqSum += (avg -self.counts[y][x][t]) * (avg -self.counts[y][x][t])
if self.counts[y][x][t] > avgPS or self.counts[y][x][t] < avgMS:
out += 1
outList.append([y,x,t,self.counts[y][x][t]])
outList = sorted(outList,key=lambda t: abs(self.counts[t[0]][t[1]][t[2]]/self.getAvgCounts()))
self.counts = [ [ [0,0,0,0] for x in range(self.nPixels) ] for y in range(self.nPixels) ]
print("There are {} of {} triangles out of 1 std ({} %)".format(out,tot,out/tot*100))
print("Total Sq Err: {}".format(sqSum))
self.sqSums.append(sqSum)
if len(self.sqSums) > 2 and np.diff(self.sqSums)[-1] > 0:
print("converged after {} steps: sqSums {} diff(sqSums) {}".format(self.cIteration,self.sqSums,np.diff(self.sqSums)))
conv = True
self.bSqSum = self.sqSums[-2]
self.cIteration += 1
return [conv,outList,sqSum]
def normalizeEdgeLengths(self):
sumL = 0
sumL += sum(map(sum,zip(*self.edgesX)))
sumL += sum(map(sum,zip(*self.edgesY)))
sumL += sum(map(sum,zip(*self.edgesE)))
sumL += sum(map(sum,zip(*self.edgesF)))
sumL += sum(map(sum,zip(*self.edgesG)))
sumL += sum(map(sum,zip(*self.edgesH)))
avgL = sumL/(4*self.nPixels*self.nPixels+2*self.nCorners*(self.nCorners+1))
print("total Sum is {} avg: {}".format(sumL,avgL))
self.edgesX = [ [ x/avgL for x in y ] for y in self.edgesX ]
self.edgesY = [ [ x/avgL for x in y ] for y in self.edgesY ]
self.edgesE = [ [ x/avgL for x in y ] for y in self.edgesE ]
self.edgesF = [ [ x/avgL for x in y ] for y in self.edgesF ]
self.edgesG = [ [ x/avgL for x in y ] for y in self.edgesG ]
self.edgesH = [ [ x/avgL for x in y ] for y in self.edgesH ]
def _shapeF(self,f):
f = (f - 1) * 0.6 + 1
if f > maxf:
return maxf
if f < minf:
return minf
return f
def calculateEdgeLengths2(self):
if self.getTotalCounts() == 0:
return
avg = self.getAvgCounts()
for y in range(self.nPixels):
for x in range(self.nPixels):
for t in range(4):
pc = self.counts[y][x][t]
if pc == 0:
f = maxf
else:
f = math.sqrt(avg/pc)
if pc > avg-math.sqrt(avg) and pc < avg+math.sqrt(avg):
f = 1.
sf = self._shapeF(f)
if t == 0:
self.edgesX[y][x] = self.edgesX[y][x] / sf
self.edgesE[y][x] = self.edgesE[y][x] / sf
self.edgesF[y][x] = self.edgesF[y][x] / sf
if t == 1:
self.edgesY[y][x+1] = self.edgesY[y][x+1] / sf
self.edgesF[y][x] = self.edgesF[y][x] / sf
self.edgesH[y][x] = self.edgesH[y][x] / sf
if t == 2:
self.edgesX[y+1][x] = self.edgesX[y+1][x] / sf
self.edgesH[y][x] = self.edgesH[y][x] / sf
self.edgesG[y][x] = self.edgesG[y][x] / sf
if t == 3:
self.edgesY[y][x] = self.edgesY[y][x] / sf
self.edgesG[y][x] = self.edgesG[y][x] / sf
self.edgesE[y][x] = self.edgesE[y][x] / sf
def calculatePixelCorners2(self):
w = 20
posMat = []
CrVx = np.zeros((self.nCorners,self.nCorners))
CrVy = np.zeros((self.nCorners,self.nCorners))
ZrVx = np.zeros((self.nPixels,self.nPixels))
ZrVy = np.zeros((self.nPixels,self.nPixels))
#boundary conditions matrix/vectors
BCposMatX = []
BCposMatY = []
BCrVx = []
BCrVy = []
for y in range(self.nCorners):
for x in range(self.nCorners):
BClineX = np.zeros((self.nCorners,self.nCorners))
BClineY = np.zeros((self.nCorners,self.nCorners))
if (x == 0 and y == 0) or \
(x == 0 and y == self.nPixels) or \
(x == self.nPixels and y == 0) or \
(x == self.nPixels and y == self.nPixels):
BClineX[y][x] = w
BClineY[y][x] = w
BCrVx.append(self.getCornerPos(y,x)[0] * w)
BCrVy.append(self.getCornerPos(y,x)[1] * w)
#print("bclinex shape {} zeros shape {}".format( BClineX.reshape((self.nCorners*self.nCorners,)).shape , np.zeros((self.nPixels*self.nPixels)).shape ))
BCposMatX.append(np.hstack((BClineX.reshape((self.nCorners*self.nCorners,)),np.zeros((self.nPixels*self.nPixels,)) )) )
BCposMatY.append(np.hstack((BClineY.reshape((self.nCorners*self.nCorners,)),np.zeros((self.nPixels*self.nPixels,)) )) )
elif x == 0 or x == self.nPixels:
BClineX[y][x] = w
#BClineY[y][x] = 1
BCrVx.append(self.getCornerPos(y,x)[0] * w)
#BCrVy.append(self.getCornerPos(y,x)[1])
BCposMatX.append(np.hstack((BClineX.reshape((self.nCorners*self.nCorners,)),np.zeros((self.nPixels*self.nPixels,)) )) )
#BCposMatY.append(np.hstack((BClineY.reshape((self.nCorners*self.nCorners,)),np.zeros((self.nPixels*self.nPixels,)) )) )
elif y == 0 or y == self.nPixels:
#BClineX[y][x] = 1
BClineY[y][x] = w
#BCrVx.append(self.getCornerPos(y,x)[0])
BCrVy.append(self.getCornerPos(y,x)[1] * w)
#BCposMatX.append(np.hstack((BClineX.reshape((self.nCorners*self.nCorners,)),np.zeros((self.nPixels*self.nPixels,)) )) )
BCposMatY.append(np.hstack((BClineY.reshape((self.nCorners*self.nCorners,)),np.zeros((self.nPixels*self.nPixels,)) )) )
eLength = 0
if x != 0:
eLength += self.edgesX[y][x-1]
if y != 0:
eLength += self.edgesY[y-1][x]
if x != self.nPixels:
eLength += self.edgesX[y][x]
if y != self.nPixels:
eLength += self.edgesY[y][x]
if y != 0 and x != 0:
eLength += self.edgesH[y-1][x-1]
if y != self.nPixels and x != 0:
eLength += self.edgesF[y][x-1]
if y != 0 and x != self.nPixels:
eLength += self.edgesG[y-1][x]
if y != self.nPixels and x != self.nPixels:
eLength += self.edgesE[y][x]
line = np.zeros((self.nCorners,self.nCorners))
lineZ = np.zeros((self.nPixels,self.nPixels))
if x != 0:
line[y][x-1] = - self.edgesX[y][x-1]/eLength
if y != 0:
line[y-1][x] = - self.edgesY[y-1][x]/eLength
if x != self.nPixels:
line[y][x+1] = - self.edgesX[y][x]/eLength
if y != self.nPixels:
line[y+1][x] = - self.edgesY[y][x]/eLength
if y != 0 and x != 0:
lineZ[y-1][x-1] = -self.edgesH[y-1][x-1]/eLength
if y != self.nPixels and x != 0:
lineZ[y][x-1] = -self.edgesF[y][x-1]/eLength
if y != 0 and x != self.nPixels:
lineZ[y-1][x] = -self.edgesG[y-1][x]/eLength
if y != self.nPixels and x != self.nPixels:
lineZ[y][x] = -self.edgesE[y][x]/eLength
line[y][x] = 1
CrVx[y][x] = 0
CrVy[y][x] = 0
posMat.append( \
np.hstack(( \
line.reshape((self.nCorners*self.nCorners,)), \
lineZ.reshape((self.nPixels*self.nPixels,)) \
)) \
)
for y in range(self.nPixels):
for x in range(self.nPixels):
line = np.zeros((self.nCorners,self.nCorners))
lineZ = np.zeros((self.nPixels,self.nPixels))
eLength = self.edgesE[y][x] + self.edgesF[y][x] +self.edgesG[y][x] +self.edgesH[y][x]
line[y][x] = -self.edgesE[y][x] / eLength
line[y][x+1] = -self.edgesF[y][x] / eLength
line[y+1][x] = -self.edgesG[y][x] / eLength
line[y+1][x+1] = -self.edgesH[y][x] / eLength
lineZ[y][x] = 1
ZrVx[y][x] = 0
ZrVy[y][x] = 0
posMat.append( \
np.hstack(( \
line.reshape((self.nCorners*self.nCorners,)), \
lineZ.reshape((self.nPixels*self.nPixels,)) \
)) \
)
CrVxFlat = CrVx.reshape((self.nCorners*self.nCorners,))
CrVyFlat = CrVy.reshape((self.nCorners*self.nCorners,))
ZrVxFlat = ZrVx.reshape((self.nPixels*self.nPixels,))
ZrVyFlat = ZrVy.reshape((self.nPixels*self.nPixels,))
posMat = np.asarray(posMat)
BCrVyFlat = np.asarray(BCrVy)
BCrVxFlat = np.asarray(BCrVx)
BCposMatX = np.asarray(BCposMatX)
BCposMatY = np.asarray(BCposMatY)
print ("BCposMatY vy {} shape posMat {}".format(BCposMatY.shape,posMat.shape))
FinalrVy = np.hstack((CrVyFlat,ZrVyFlat,BCrVyFlat))
FinalrVx = np.hstack((CrVxFlat,ZrVxFlat,BCrVxFlat))
FinalposMatX = np.vstack((posMat,BCposMatX))
FinalposMatY = np.vstack((posMat,BCposMatY))
print("posMat shape {}".format(posMat.shape))
print("posMatX shape {}".format(FinalposMatX.shape))
print("rVxFlat shape {}".format(FinalrVx.shape))
#print("posMat {}".format(FinalposMat))
#print("rVxFlat {}".format(FinalrVx))
xPos = np.linalg.lstsq(FinalposMatX,FinalrVx)[0]
yPos = np.linalg.lstsq(FinalposMatY,FinalrVy)[0]
print("xPosShape {} cutXPosShape {}".format(xPos.shape,xPos[:self.nCorners][:self.nCorners].shape))
self.cPosX = xPos[:self.nCorners*self.nCorners].reshape((self.nCorners,self.nCorners))
self.cPosY = yPos[:self.nCorners*self.nCorners].reshape((self.nCorners,self.nCorners))
self.zPosX = xPos[self.nCorners*self.nCorners:].reshape((self.nPixels,self.nPixels))
self.zPosY = yPos[self.nCorners*self.nCorners:].reshape((self.nPixels,self.nPixels))
def fill(self,yy,xx,count = 1):
[y,x,t] = self.getPixel(yy,xx)
self.counts[y][x][t] += count
def getCountDist(self):
c = []
for y in range(self.nPixels):
for x in range(self.nPixels):
c.append(self.counts[y][x])
return c
def getPixel(self,yy,xx, debug = False):
for y in range(self.nPixels):
for x in range(self.nPixels):
for t in range(4):
[v1x,v1y,v2x,v2y,v3x,v3y] = self.getTriangleCorner(y,x,t)
if self.pointInTriangle([xx,yy],[v1x,v1y],[v2x,v2y],[v3x,v3y]):
return [y,x,t]
if not debug:
raise Exception("not inside a pixel")
else:
print("no pixel found")
return [0,0]
#http://stackoverflow.com/questions/2049582/how-to-determine-a-point-in-a-2d-triangle
def trSign (self, p1, p2, p3):
return (p1[0] - p3[0]) * (p2[1] - p3[1]) - (p2[0] - p3[0]) * (p1[1] - p3[1]);
def pointInTriangle (self,pt, v1, v2, v3):
b1 = self.trSign(pt, v1, v2) < 0.0
b2 = self.trSign(pt, v2, v3) < 0.0
b3 = self.trSign(pt, v3, v1) < 0.0
return ((b1 == b2) and (b2 == b3));
def getAvgCounts(self):
return self.getTotalCounts() / self.nPixels/self.nPixels/4.
def getTotalCounts(self):
tot = 0
for y in range(self.nPixels):
for x in range(self.nPixels):
for t in range(4):
tot += self.counts[y][x][t]
return tot
#tl tr bl br
def getPixelCorners(self,iy,ix):
return self.getCornerPos(iy,ix) + self.getCornerPos(iy,ix+1) + self.getCornerPos(iy+1,ix) + self.getCornerPos(iy+1,ix+1)
def getTriangleCorner(self,iy,ix,tr):
if tr == 0:
return self.getCornerPos(iy,ix) + self.getCornerPos(iy,ix+1) + [self.zPosX[iy][ix],self.zPosY[iy][ix]]
if tr == 1:
return self.getCornerPos(iy,ix+1) + self.getCornerPos(iy+1,ix+1) + [self.zPosX[iy][ix],self.zPosY[iy][ix]]
if tr == 2:
return self.getCornerPos(iy+1,ix+1) + self.getCornerPos(iy+1,ix) + [self.zPosX[iy][ix],self.zPosY[iy][ix]]
if tr == 3:
return self.getCornerPos(iy+1,ix) + self.getCornerPos(iy,ix) + [self.zPosX[iy][ix],self.zPosY[iy][ix]]
def getCornerPos(self,iy,ix):
return [self.cPosX[iy][ix],self.cPosY[iy][ix]]
def getXEdgePos(self,iy,ix):
p1 = self.getCornerPos(iy,ix)
p2 = self.getCornerPos(iy,ix+1)
return [p1[0],p1[1],p2[0],p2[1]]
def getYEdgePos(self,iy,ix):
p1 = self.getCornerPos(iy,ix)
p2 = self.getCornerPos(iy+1,ix)
return [p1[0],p1[1],p2[0],p2[1]]
def getEEdgePos(self,iy,ix):
p1 = self.getCornerPos(iy,ix)
return [p1[0],p1[1],self.zPosX[iy][ix],self.zPosY[iy][ix]]
def getFEdgePos(self,iy,ix):
p1 = self.getCornerPos(iy,ix+1)
return [p1[0],p1[1],self.zPosX[iy][ix],self.zPosY[iy][ix]]
def getGEdgePos(self,iy,ix):
p1 = self.getCornerPos(iy+1,ix)
return [p1[0],p1[1],self.zPosX[iy][ix],self.zPosY[iy][ix]]
def getHEdgePos(self,iy,ix):
p1 = self.getCornerPos(iy+1,ix+1)
return [p1[0],p1[1],self.zPosX[iy][ix],self.zPosY[iy][ix]]

View File

@@ -0,0 +1,134 @@
#include "interpolation_EtaVEL.h"
#include "TH2F.h"
#include "TCanvas.h"
#include "TROOT.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.
*/
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;
}
void interpolation_EtaVEL::prepareInterpolation(int &ok, int maxit) {
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 etax, Double_t etay) {
// newEta->fill(etaX,etaY);
heta->Fill(etax,etay);
return 0;
}
void interpolation_EtaVEL::iterate() {
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();
}
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];
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;
};
// void interpolation_EtaVEL::Streamer(TBuffer &b){newEta->Streamer(b);};
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);
};

View File

@@ -0,0 +1,55 @@
#ifndef INTERPOLATION_ETAVEL_H
#define INTERPOLATION_ETAVEL_H
#include <slsInterpolation.h>
#include "EtaVEL.h"
//#include "TH2F.h"
//#include "EtaVEL.cpp"
//class EtaVEL;
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);
//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);
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();};
protected:
EtaVEL *newEta;
// TH2F *heta;
int plot;
// ClassDefNV(interpolation_EtaVEL,1);
// #pragma link C++ class interpolation_EtaVEL-;
};
#endif

View File

@@ -0,0 +1,234 @@
#ifndef LINEAR_INTERPOLATION_H
#define LINEAR_INTERPOLATION_H
//#include <TObject.h>
//#include <TTree.h>
//#include <TH2F.h>
#include "slsInterpolation.h"
class linearInterpolation : public slsInterpolation{
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 linearInterpolation* Clone() {
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);
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);
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);
}
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;
}
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;
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) {};
protected:
;
};
#endif

View File

@@ -0,0 +1,104 @@
#ifndef NO_INTERPOLATION_H
#define NO_INTERPOLATION_H
/* #ifdef MYROOT1 */
/* #include <TObject.h> */
/* #include <TTree.h> */
/* #include <TH2F.h> */
/* #include <TROOT.h> */
/* #include <TRandom.h> */
/* #endif */
#include <cstdlib>
#include "slsInterpolation.h"
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 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, 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 totquad,int quad,double *cl,double &etax, double &etay){
getInterpolatedPosition(x, y, (double*)NULL, etax, etay);
};
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 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 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-;
};
#endif

View File

@@ -0,0 +1,503 @@
#ifndef SLS_INTERPOLATION_H
#define SLS_INTERPOLATION_H
#include <cstdlib>
#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
};
#endif
#include <memory.h>
#include <stdio.h>
#include <iostream>
using namespace std;
//#ifdef MYROOT1
//: public TObject
//#endif
class slsInterpolation
{
public:
slsInterpolation(int nx=400, int ny=400, int ns=25) :nPixelsX(nx), nPixelsY(ny), nSubPixels(ns), id(0) {
hint=new int[ns*nx*ns*ny];
};
slsInterpolation(slsInterpolation *orig){
nPixelsX=orig->nPixelsX;
nPixelsY=orig->nPixelsY;
nSubPixels=orig->nSubPixels;
hint=new int[nSubPixels*nPixelsX*nSubPixels*nPixelsY];
memcpy(hint, orig->hint,nSubPixels*nPixelsX*nSubPixels*nPixelsY*sizeof(int));
};
virtual int setId(int i) {id=i; return id;};
virtual slsInterpolation* Clone() =0; /*{
return new slsInterpolation(this);
}*/
int getNSubPixels() {return nSubPixels;};
int setNSubPixels(int ns) {
if (ns>0 && ns!=nSubPixels) {
delete [] hint;
nSubPixels=ns;
hint=new int[nSubPixels*nPixelsX*nSubPixels*nPixelsY];
}
return nSubPixels;
}
int getImageSize(int &nnx, int &nny, int &ns) {
nnx=nSubPixels*nPixelsX;
nny=nSubPixels*nPixelsY;
ns=nSubPixels;
return nSubPixels*nSubPixels*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<nSubPixels* nSubPixels* nPixelsX*nPixelsY; i++) { */
/* cout << i << " " << hint[i] << endl; */
/* } */
return hint;
};
void *writeInterpolatedImage(const char * imgname) {
//cout << "!" <<endl;
float *gm=NULL;
int *dummy=getInterpolatedImage();
gm=new float[ nSubPixels* nSubPixels* nPixelsX*nPixelsY];
if (gm) {
for (int ix=0; ix<nPixelsX*nSubPixels; ix++) {
for (int iy=0; iy<nPixelsY*nSubPixels; iy++) {
gm[iy*nPixelsX*nSubPixels+ix]=dummy[iy*nPixelsX*nSubPixels+ix];
}
}
WriteToTiff(gm, imgname,nSubPixels* nPixelsX ,nSubPixels* nPixelsY);
delete [] gm;
} else cout << "Could not allocate float image " << endl;
return NULL;
}
//return position inside the pixel for the given photon
virtual void getInterpolatedPosition(int x, int y, double *data, double &int_x, double &int_y)=0;
virtual void getInterpolatedPosition(int x, int y, int *data, double &int_x, double &int_y)=0;
//return position inside the pixel for the given photon
virtual void getInterpolatedPosition(int x, int y, double etax, double etay, int quad, double &int_x, double &int_y)=0;
virtual void getInterpolatedPosition(int x, int y, double totquad,int quad,int *cluster,double &etax, double &etay)=0;
virtual void getInterpolatedPosition(int x, int y, double totquad,int quad,double *cluster,double &etax, double &etay)=0;
//return position inside the pixel for the given photon
virtual void clearInterpolatedImage() {
for (int ix=0; ix<nPixelsX*nSubPixels; ix++) {
for (int iy=0; iy<nPixelsY*nSubPixels; iy++) {
hint[iy*nPixelsX*nSubPixels+ix]=0;
}
}
};
virtual int *addToImage(double int_x, double int_y){
int iy=((double)nSubPixels)*int_y;
int ix=((double)nSubPixels)*int_x;
if (ix>=0 && ix<(nPixelsX*nSubPixels) && iy<(nSubPixels*nPixelsY) && iy>=0 ){
// cout << int_x << " " << int_y << " " << " " << ix << " " << iy << " " << ix+iy*nPixelsX*nSubPixels << " " << hint[ix+iy*nPixelsX*nSubPixels];
(*(hint+ix+iy*nPixelsX*nSubPixels))+=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;
double sumBL=0;
double sumTL=0;
double sumBR=0;
double sumTR=0;
int xoff=0, yoff=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;
totquad=sumBL;
xoff=0;
yoff=0;
if(sumTL >= totquad){
/* sDum[0][0] = cluster[1][0]; sDum[1][0] = cluster[2][0]; */
/* sDum[0][1] = cluster[1][1]; sDum[1][1] = cluster[2][1]; */
corner = TOP_LEFT;
totquad=sumTL;
xoff=0;
yoff=1;
}
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]; */
xoff=1;
yoff=0;
corner = BOTTOM_RIGHT;
totquad=sumBR;
}
if(sumTR >= totquad){
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;
}
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;
}
/* if (etax<-1 || etax>1 || etay<-1 || etay>1) { */
/* cout << "**********" << etax << " " << etay << endl; */
/* for (int ix=0; ix<3; ix++) { */
/* for (int iy=0; iy<3; iy++) { */
/* cout << cl[iy+3*ix] << "\t" ; */
/* } */
/* cout << endl; */
/* } */
/* cout << sum << " " << l << " " << r << " " << t << " " << b << endl; */
/* } */
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 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(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 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 nSubPixels;
int id;
int *hint;
};
#endif

View File

@@ -0,0 +1,45 @@
#ifndef MOENCH03COMMONMODE_H
#define MOENCH03COMMONMODE_H
#include "commonModeSubtraction.h"
class moench03CommonMode : 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
*/
moench03CommonMode(int nn=1000) : commonModeSubtraction(nn,32){} ;
/** 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
*/
virtual void addToCommonMode(double val, int ix=0, int iy=0) {
// (void) iy;
int isc=ix/25+(iy/200)*16;
if (isc>=0 && isc<nROI) {
cmPed[isc]+=val;
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;
\param ix pixel coordinate in the x direction
\param iy pixel coordinate in the y direction
\returns common mode value
*/
virtual double getCommonMode(int ix=0, int iy=0) {
(void) iy;
int isc=ix/25+(iy/200)*16;
if (isc>=0 && isc<nROI) {
if (nCm[isc]>0) return cmPed[isc]/nCm[isc]-cmStat[isc].Mean();
}
return 0;
};
};
#endif

View File

@@ -0,0 +1,45 @@
#ifndef MOENCHCOMMONMODE_H
#define MOENCHCOMMONMODE_H
#include "commonModeSubtraction.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
*/
moenchCommonMode(int nn=1000) : commonModeSubtraction(nn,4){} ;
/** 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
*/
virtual void addToCommonMode(double val, int ix=0, int iy=0) {
(void) iy;
int isc=ix/40;
if (isc>=0 && isc<nROI) {
cmPed[isc]+=val;
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;
\param ix pixel coordinate in the x direction
\param iy pixel coordinate in the y direction
\returns common mode value
*/
virtual double getCommonMode(int ix=0, int iy=0) {
(void) iy;
int isc=ix/40;
if (isc>=0 && isc<nROI) {
if (nCm[isc]>0) return cmPed[isc]/nCm[isc]-cmStat[isc].Mean();
}
return 0;
};
};
#endif

View File

@@ -0,0 +1,34 @@
#module add CBFlib/0.9.5
INCDIR=-I. -I../ -I../interpolations -I../interpolations/etaVEL -I../dataStructures -I../../slsSupportLib/include/ -I../../slsReceiverSoftware/include/
LDFLAG= ../tiffIO.cpp -L/usr/lib64/ -lpthread -lm -lstdc++ -pthread -lrt -ltiff -O3 -std=c++11
MAIN=moench03ClusterFinder.cpp
all: moenchClusterFinder moenchMakeEta moenchInterpolation moenchNoInterpolation moenchPhotonCounter moenchAnalog
moenchClusterFinder: moench03ClusterFinder.cpp $(INCS) clean
g++ -o moenchClusterFinder moench03ClusterFinder.cpp $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) -DSAVE_ALL -DNEWRECEIVER
moenchMakeEta: moench03Interpolation.cpp $(INCS) clean
g++ -o moenchMakeEta moench03Interpolation.cpp $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) -DFF
moenchInterpolation: moench03Interpolation.cpp $(INCS) clean
g++ -o moenchInterpolation moench03Interpolation.cpp $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF)
moenchNoInterpolation: moench03NoInterpolation.cpp $(INCS) clean
g++ -o moenchNoInterpolation moench03NoInterpolation.cpp $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF)
moenchPhotonCounter: moenchPhotonCounter.cpp $(INCS) clean
g++ -o moenchPhotonCounter moenchPhotonCounter.cpp $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) -DNEWRECEIVER
moenchAnalog: moenchPhotonCounter.cpp $(INCS) clean
g++ -o moenchAnalog moenchPhotonCounter.cpp $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) -DNEWRECEIVER -DANALOG
clean:
rm -f moenchClusterFinder moenchMakeEta moenchInterpolation moenchNoInterpolation moenchPhotonCounter moenchAnalog

View File

@@ -0,0 +1,16 @@
INCDIR= -I. -I../dataStructures ../tiffIO.cpp -I../ -I../interpolations/ -I../../slsSupportLib/include/ -I../../slsReceiverSoftware/include/
LDFLAG= -L/usr/lib64/ -lpthread -lm -lstdc++ -lzmq -pthread -lrt -ltiff -O3 -g -std=c++11
#-L../../bin -lhdf5 -L.
#DESTDIR?=../bin
all: moenchZmqProcess
moenchZmqProcess: moenchZmqProcess.cpp clean
g++ -o moenchZmqProcess moenchZmqProcess.cpp $(LDFLAG) $(INCDIR) $(LIBHDF5) $(LIBRARYCBF) -DNEWZMQ -DINTERP
clean:
rm -f moenchZmqProcess

View File

@@ -0,0 +1,237 @@
//#include "ansi.h"
#include <iostream>
//#include "moench03T1ZmqData.h"
#ifdef NEWRECEIVER
#ifndef RECT
#include "moench03T1ReceiverDataNew.h"
#endif
#ifdef RECT
#include "moench03T1ReceiverDataNewRect.h"
#endif
#endif
#ifdef CSAXS_FP
#include "moench03T1ReceiverData.h"
#endif
#ifdef OLDDATA
#include "moench03Ctb10GbT1Data.h"
#endif
#ifdef REORDERED
#include "moench03T1ReorderedData.h"
#endif
// #include "interpolatingDetector.h"
//#include "etaInterpolationPosXY.h"
// #include "linearInterpolation.h"
// #include "noInterpolation.h"
#include "multiThreadedAnalogDetector.h"
#include "singlePhotonDetector.h"
//#include "interpolatingDetector.h"
#include <stdio.h>
#include <map>
#include <fstream>
#include <sys/stat.h>
#include <ctime>
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;
#ifdef NEWRECEIVER
#ifdef RECT
cout << "Should be rectangular!" <<endl;
#endif
moench03T1ReceiverDataNew *decoder=new moench03T1ReceiverDataNew();
cout << "RECEIVER DATA WITH ONE HEADER!"<<endl;
#endif
#ifdef CSAXS_FP
moench03T1ReceiverData *decoder=new moench03T1ReceiverData();
cout << "RECEIVER DATA WITH ALL HEADERS!"<<endl;
#endif
#ifdef OLDDATA
moench03Ctb10GbT1Data *decoder=new moench03Ctb10GbT1Data();
cout << "OLD RECEIVER DATA!"<<endl;
#endif
#ifdef REORDERED
moench03T1ReorderedData *decoder=new moench03T1ReorderedData();
cout << "REORDERED DATA!"<<endl;
#endif
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;
// 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();
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];
// 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;
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; 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 << "*"<<ifr++<<"*"<<ff<< endl;
// cout << ff << " " << np << endl;
// //push
// for (int ix=0; ix<400; ix++)
// for (int iy=0; iy<400; iy++) {
// if (decoder->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;
}

View File

@@ -0,0 +1,249 @@
#include "ansi.h"
#include <iostream>
//#include "moench03T1ZmqData.h"
//#define DOUBLE_SPH
//#define MANYFILES
#ifdef DOUBLE_SPH
#include "single_photon_hit_double.h"
#endif
#ifndef DOUBLE_SPH
#include "single_photon_hit.h"
#endif
//#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 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;
#endif
#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);
#endif
#ifndef DOUBLE_SPH
single_photon_hit cl(3,3);
#endif
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);
#endif
#ifdef NOINTERPOLATION
noInterpolation *interp=new noInterpolation(NC, NR, nsubpix);
#endif
#ifndef FF
#ifndef NOINTERPOLATION
cout << "read ff " << argv[2] << endl;
sprintf(fname,"%s",argv[2]);
interp->readFlatField(fname);
interp->prepareInterpolation(ok);//, MAX_ITERATIONS);
#endif
// return 0;
#endif
#ifdef FF
cout << "Will write eta file " << argv[2] << endl;
#endif
int *img;
float *totimg=new float[NC*NR*nsubpix*nsubpix];
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)]=0;
}
}
}
}
#ifdef FF
sprintf(outfname,argv[2]);
#endif
int irun;
for (irun=runmin; irun<runmax; irun++) {
sprintf(infname,argv[1],irun);
#ifndef FF
sprintf(outfname,argv[3],irun);
#endif
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;
}
#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);
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);
#endif
cout << "Filled " << nph << " (/"<< totph <<") " << endl;
return 0;
}

View File

@@ -0,0 +1,170 @@
#include "ansi.h"
#include <iostream>
#include "single_photon_hit.h"
#include "noInterpolation.h"
using namespace std;
#define NC 400
#define NR 400
int main(int argc, char *argv[]) {
/**
* 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;
}
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;
int ix, iy, isx, isy;
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);
// interp->readFlatField(argv[2]);
// interp->prepareInterpolation(ok);
int *img;
float *totimg=new float[NC*NR*nsubpix*nsubpix];
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)]=0;
}
}
}
}
#ifdef FF
float ff[nsubpix*nsubpix];
float *ffimg=new float[NC*NR*nsubpix*nsubpix];
float totff=0;
#endif
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; 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) {
cout << "ff: " << totff << endl;
for (isx=0; isx<nsubpix; isx++) {
for (isy=0; isy<nsubpix; isy++) {
ff[isy*nsubpix+isx]/=totff;
cout << ff[isy*nsubpix+isx] << "\t";
}
cout << endl;
}
for (ix=0; ix<NC; ix++) {
for (iy=0; iy<NR; iy++) {
for (isx=0; isx<nsubpix; isx++) {
for (isy=0; isy<nsubpix; isy++) {
ffimg[ix*nsubpix+isx+(iy*nsubpix+isy)*(NC*nsubpix)]=img[ix*nsubpix+isx+(iy*nsubpix+isy)*(NC*nsubpix)]/ff[isy*nsubpix+isx];
totimg[ix*nsubpix+isx+(iy*nsubpix+isy)*(NC*nsubpix)]+=ffimg[ix*nsubpix+isx+(iy*nsubpix+isy)*(NC*nsubpix)];
}
}
}
}
WriteToTiff(ffimg, outfname,NC*nsubpix,NR*nsubpix);
}
#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)];
}
}
}
}
#endif
interp->clearInterpolatedImage();
}
}
sprintf(outfname,argv[3],11111);
WriteToTiff(totimg, outfname,NC*nsubpix,NR*nsubpix);
return 0;
}

Some files were not shown because too many files have changed in this diff Show More