]> jspc29.x-matter.uni-frankfurt.de Git - radhard.git/commitdiff
run analyzer: Before Mi19 integration, after new PC
authorBenjamin Linnik <blinnik@jspc61.x-matter.uni-frankfurt.de>
Thu, 14 Jul 2016 18:06:36 +0000 (20:06 +0200)
committerBenjamin Linnik <blinnik@jspc61.x-matter.uni-frankfurt.de>
Thu, 14 Jul 2016 18:06:36 +0000 (20:06 +0200)
MABS_run_analyzer/ChargeSpektrum.c
MABS_run_analyzer/ChargeSpektrumFunctions.c
MABS_run_analyzer/HistogramType.c
MABS_run_analyzer/HistogramType.h
MABS_run_analyzer/Run.c
MABS_run_analyzer/Run.h
MABS_run_analyzer/help.h
bot/Chips/Pegasus.au3 [new file with mode: 0755]
bot/Mimosa_Autorun_Pegasus.au3 [new file with mode: 0755]

index 7f9d629df4b83efc40081cff6aec327292dbf6d7..55b0a95c33e7c4e5704aee27a9ecaa772562d9f5 100644 (file)
@@ -7,6 +7,8 @@
  *
  */
 
+Bool_t isBatch = kFALSE;
+
 #include "MAPS.c"
 #include "Run.c"
 #include "CSVRow.h"
@@ -16,7 +18,6 @@
 
 Run** runs;
 Int_t numberRuns;
-Bool_t isBatch = kFALSE;
 TString savepathresults = "./results/";
 
 #include "ChargeSpektrumFunctions.c"
@@ -31,7 +32,8 @@ void ChargeSpektrum(TString runnumber = "")
     numberRuns=0;
     std::vector<int> runList;
     std::vector<Bool_t> runListForceAnalysis;
-    std::vector<TString> sumuprunList;
+    std::vector<TString> runListCustomTitle;
+    std::vector<TString> sumuprunList; // not used yet, add runs to each other, combine statistics
     if (runnumber.Length() > 0)
     {
         if (runnumber.Contains("-")) {
@@ -74,7 +76,7 @@ void ChargeSpektrum(TString runnumber = "")
             }
 
         } else {
-            TObjArray* runarray = runnumber.Tokenize(",");
+            TObjArray* runarray = runnumber.Tokenize(","); // seperate run numbers by ','
             if (runarray->GetEntries()>0)
             {
                 TObjString* tempstrobj;
@@ -89,14 +91,21 @@ void ChargeSpektrum(TString runnumber = "")
                         for (Int_t j=0; j < sumrunarray->GetEntries(); j++)
                         {
                             sumuprunsstrobj=static_cast<TObjString*>(sumrunarray->At(j));
-                            Int_t tempint = sumuprunsstrobj->GetString().Atoi();
+                            TString currunnumberstr = sumuprunsstrobj->GetString();
+                            Int_t tempint = currunnumberstr.Atoi();
                             if (tempint > 0)
                             {
                                 runList.push_back(tempint);
-                                if (sumuprunsstrobj->GetString().Contains("!"))
+                                if (currunnumberstr.Contains("!"))
                                     runListForceAnalysis.push_back(kTRUE);
                                 else
                                     runListForceAnalysis.push_back(kFALSE);
+                                if (currunnumberstr.Contains("=")) {
+                                    cout << colorcyan << currunnumberstr << endlr;
+                                    runListCustomTitle.push_back(currunnumberstr(currunnumberstr.Index('=')+1,currunnumberstr.Length()-currunnumberstr.Index('=')-1));                                    
+                                } else {
+                                    runListCustomTitle.push_back("");
+                                }
                                 sumrunsstr.Append(Form("%d,",tempint));
                                 numberRuns++;
                             }
@@ -157,9 +166,17 @@ void ChargeSpektrum(TString runnumber = "")
                 {
                     runs[runi]->error = false;
                     runs[runi]->error=runs[runi]->analyzeRun(true);
-                }
+                }                
                 if (!runs[runi]->error)
-                {
+                {                    
+                    if (runListCustomTitle.size() >= (unsigned)runi+1)
+                    {
+                        if (runListCustomTitle[runi].Length()>0)
+                        {
+                            runs[runi]->setLabel(runListCustomTitle[runi]);
+                        }
+                    }
+                    
                     //         gROOT->SetBatch(kTRUE);
                     if (!isBatch)
                         gROOT->SetBatch(kFALSE);
@@ -170,27 +187,37 @@ void ChargeSpektrum(TString runnumber = "")
 //                     runs[runi]->plotCompareHistograms();
 //                        runs[runi]->plotAllHistograms(runs[runi]->histogramthreshold);
                     compareHistogramClassVector.push_back(runs[runi]->histogramthreshold->normalized);
-                    compareHistogramVector.push_back(runs[runi]->histogramthreshold->normalized->Seed);
+                    compareHistogramVector.push_back(runs[runi]->histogramthreshold->normalized->calibrated->Seed);
+                    compareHistogramVector2.push_back(runs[runi]->histogramthreshold->normalized->Seed);
                     //compareHistogramClassVector.push_back(runs[runi]->histogram);
                     //                      runs[runi]->plot1DHistogram(runs[runi]->histogramthreshold, runs[runi]->histogramthreshold->Veto, "gaus");
-//                      runs[runi]->plot1DHistogram(runs[runi]->histogramthreshold, runs[runi]->histogramthreshold->normalized->Sum, "gaus", 1);
-//                      runs[runi]->plot1DHistogram(runs[runi]->histogramthreshold, runs[runi]->histogramthreshold->normalized->Veto, "GaussTail", 1);
-//                     compareHistogramVector.push_back(runs[runi]->histogramthreshold->calibrated->normalized->Veto);
-                     runs[runi]->writeAllHistogramsToFile();
+                      runs[runi]->plot1DHistogram(runs[runi]->histogramthreshold, runs[runi]->histogramthreshold->normalized->Sum, "gaus", 1);
+                      runs[runi]->plot1DHistogram(runs[runi]->histogramthreshold, runs[runi]->histogramthreshold->normalized->Veto, "GaussTail", 1);
+  //                   compareHistogramVector.push_back(runs[runi]->histogramthreshold->calibrated->normalized->Veto);
+                    runs[runi]->writeAllHistogramsToFile();
                 }
                 //cout << runs[runi]->histogram
             }
         }
     }
+    
+    
+    
+    
 //     if (numberRuns>0)
-//         runs[0]->setLabel("33x33 #mum, S(D)=8 #mum^2, F(D)=15 #mum^2");
+//         runs[0]->setLabel("Not irradiated");
+// //         runs[0]->setLabel("33x33 #mum, S(D)=8 #mum^2, F(D)=15 #mum^2");
 //     if (numberRuns>1)
+//         runs[1]->setLabel("10^{13} n_{eq}/cm^{2}");
+//     if (numberRuns>2)
+//         runs[2]->setLabel("10^{14} n_{eq}/cm^{2}");
 //            runs[1]->setLabel("66x33 #mum, S(D)=8 #mum^2, F(D)=15 #mum^2");
 //     if (numberRuns>2)
 //         runs[2]->setLabel("33x33 #mum, S(D)=11 #mum^2, F(D)=11 #mum^2");
 //     runs[3]->setLabel("HR18, P13, 5.0 V");
 printSummaryTable(&compareHistogramClassVector);
-CompareHistograms(&compareHistogramVector);
+// CompareHistograms(&compareHistogramVector);
+CompareHistograms(&compareHistogramVector2);
 plotAllRuns(&compareHistogramClassVector);
 //    plotAllRuns(&compareHistogramClassVector2);
 //     plotAllRuns(&compareHistogramClassVector3);
index 1d72227b8b2579cc710b1769feaa7f641dc3e22a..3a0776b1f80c3a2c522b2e372094f5089c5762cd 100644 (file)
@@ -12,6 +12,7 @@
 #include <TLatex.h>
 #include <THStack.h>
 #include <TCanvas.h>
+#include <TH2C.h>
 
 #include "help.h"
 using namespace std;
@@ -57,6 +58,7 @@ Bool_t testifMixingCalibration(vector<HistogramType*>*);
 /** @brief Turns a value into a string with fixed precision */
 string to_str_w_prec(const Float_t a_value, int precision = 1);
 vector<TH1F*> compareHistogramVector;
+vector<TH1F*> compareHistogramVector2;
 TString ownpath = "";
 
 void setCustomPath(TString setOwnpath)
@@ -153,7 +155,7 @@ Bool_t CompareHistograms(vector<TH1F*>* ptCompareHistogramVector, TString titles
         Float_t height = ptCompareHistogramVector->size() * 0.03;
         TLegend* leg1 = new TLegend(0.3,0.89-height,0.95,0.89);//(0.6,0.7,0.89,0.89);
         leg1->SetTextSize(0.025);
-        leg1->SetFillStyle(0);
+        leg1->SetFillStyle(1001);
         leg1->SetTextFont(132);
         leg1->SetFillColor(0); leg1->SetBorderSize(0);
         TString  legendEntry;
@@ -167,7 +169,7 @@ Bool_t CompareHistograms(vector<TH1F*>* ptCompareHistogramVector, TString titles
         
         Float_t lastbin1=0;   
         Float_t heighestval1=0; 
-        TString canvastitle = Form("Compare");
+        TString canvastitle = Form("Compare_%s", trimRunnumberAtBegin(ptCompareHistogramVector->at(0)->GetName()).Data());
         TTimeStamp* time = new TTimeStamp(); 
         TString canvasname = Form("%d",time->GetNanoSec());        
         for (UInt_t histogrami=0; histogrami < ptCompareHistogramVector->size(); histogrami++)
@@ -178,6 +180,11 @@ Bool_t CompareHistograms(vector<TH1F*>* ptCompareHistogramVector, TString titles
             canvastitle+= Form("_%s",getRunnumberAtBegin(curhistogramclone->GetName()).Data());        
         }        
         TCanvas* canvas = new TCanvas(canvasname, canvastitle, 1200, 800);
+        TPad *grid = new TPad("grid","",0,0,1,1);
+        grid->Draw();
+        grid->cd();
+        grid->SetGrid();
+        grid->SetFillStyle(4000);  
         
         for (UInt_t histogrami=0; histogrami < ptCompareHistogramVector->size(); histogrami++)
         {
@@ -185,10 +192,14 @@ Bool_t CompareHistograms(vector<TH1F*>* ptCompareHistogramVector, TString titles
             if (titlestr.Length() > 0) curhistogramclone->SetName(titlestr);
             if (YAxisTitle.Length() > 0) curhistogramclone->SetYTitle(YAxisTitle);
             curhistogramclone->SetLineColor(rootcolors[histogrami%13]);   
+            curhistogramclone->SetLineWidth(curhistogramclone->GetLineWidth()+1);   
             curhistogramclone->Draw("SAME");
-            legendEntry = Form("%s %s", getRunnumberAtBegin(curhistogramclone->GetName()).Data(), curhistogramclone->GetTitle());
+            
+//             legendEntry = Form("%s %s", getRunnumberAtBegin(curhistogramclone->GetName()).Data(), curhistogramclone->GetTitle());
+            legendEntry = Form("%s", curhistogramclone->GetTitle());
             leg1->AddEntry(curhistogramclone, legendEntry, "l");
             leg1->Draw("SAME");
+           
             curhistogramclone->SetAxisRange(0,lastbin1*1.1,"X");
             curhistogramclone->GetYaxis()->SetRangeUser(5,heighestval1*4);
             gPad->SetLogy(1);
@@ -197,6 +208,7 @@ Bool_t CompareHistograms(vector<TH1F*>* ptCompareHistogramVector, TString titles
             owntitle->Draw("SAME");
         }
         canvas->Update();
+        MSaveBigPNG(canvas, savepathresults + "/" + canvastitle + ".png");
         
         TImageDump *img = new TImageDump(savepathresults + "/" + canvastitle + ".png");
         canvas->Paint();
@@ -205,10 +217,9 @@ Bool_t CompareHistograms(vector<TH1F*>* ptCompareHistogramVector, TString titles
         TFile *f = new TFile(savepathresults + "/" + canvastitle + ".root","RECREATE");
         f->cd();
         f->Append(canvas);
-        f->Append(img);
+        //f->Append(img);
         f->Write();
         
-        MSaveBigPNG(savepathresults + "/" + canvastitle + ".png");
         return 0;
     }
     return 1;
@@ -297,13 +308,17 @@ Bool_t plotAllRuns(vector<HistogramType*>* ptCompareHistogramClassVector)
         {
             HistogramType* curhistogramclassp = ptCompareHistogramClassVector->at(histogrami);
             TH1F* curhistogramclone = (TH1F*) curhistogramclassp->Seed->Clone();
-            heighestval1 = (curhistogramclone->GetMaximum()>heighestval1?curhistogramclone->GetMaximum():heighestval1);            
+            heighestval1 = (curhistogramclone->GetMaximum()>heighestval1?curhistogramclone->GetMaximum():heighestval1);  
+            lastbin1 = (curhistogramclone->GetBinCenter(curhistogramclone->FindLastBinAbove(2,1))>lastbin1)?curhistogramclone->GetBinCenter(curhistogramclone->FindLastBinAbove(2,1)):lastbin1;       
+//             cout << "Last bin: " << colorcyan << lastbin1 << endlr;
             
             curhistogramclone = (TH1F*) curhistogramclassp->Sum->Clone();
             heighestval2 = (curhistogramclone->GetMaximum()>heighestval2?curhistogramclone->GetMaximum():heighestval2);
+            lastbin2 = (curhistogramclone->GetBinCenter(curhistogramclone->FindLastBinAbove(2,1))>lastbin2)?curhistogramclone->GetBinCenter(curhistogramclone->FindLastBinAbove(2,1)):lastbin2;
             
             curhistogramclone = (TH1F*) curhistogramclassp->Veto->Clone();
             heighestval3 = (curhistogramclone->GetMaximum()>heighestval3?curhistogramclone->GetMaximum():heighestval3);
+            lastbin3 = (curhistogramclone->GetBinCenter(curhistogramclone->FindLastBinAbove(2,1))>lastbin3)?curhistogramclone->GetBinCenter(curhistogramclone->FindLastBinAbove(2,1)):lastbin3;
             
             curhistogramclone = (TH1F*) curhistogramclassp->Noise->Clone();
             heighestval4 = (curhistogramclone->GetMaximum()>heighestval4?curhistogramclone->GetMaximum():heighestval4);
@@ -322,12 +337,12 @@ Bool_t plotAllRuns(vector<HistogramType*>* ptCompareHistogramClassVector)
             curhistogramclone->SetLineColor(rootcolors[histogrami%13]);    
             //curhistogramclone->GetXaxis()->SetRange(0,curhistogramclone->GetXaxis()->GetNbins());
             curhistogramclone->Draw("SAME");
-            legendEntry = Form("%d %s", curhistogramclassp->labbook->runnumber, curhistogramclone->GetTitle());
+//             legendEntry = Form("%d %s", curhistogramclassp->labbook->runnumber, curhistogramclone->GetTitle());
+            legendEntry = Form("%s", curhistogramclone->GetTitle());
             leg1->AddEntry(curhistogramclone, legendEntry, "l");
             leg1->Draw("SAME");
-            lastbin1 = (curhistogramclone->GetBinCenter(curhistogramclone->FindLastBinAbove(0,1))>lastbin1)?curhistogramclone->GetBinCenter(curhistogramclone->FindLastBinAbove(0,1)):lastbin1;
             curhistogramclone->SetAxisRange(0,lastbin1*1.1,"X");
-            curhistogramclone->GetYaxis()->SetRangeUser(5,heighestval1*4);
+            curhistogramclone->GetYaxis()->SetRangeUser(1,heighestval1*4);
             gPad->SetLogy(1);
             owntitle->Clear();
             owntitle->AddText(trimRunnumberAtBegin(curhistogramclone->GetName()));
@@ -341,10 +356,9 @@ Bool_t plotAllRuns(vector<HistogramType*>* ptCompareHistogramClassVector)
             leg2->AddEntry(curhistogramclone, legendEntry, "l");
             leg2->Draw("SAME");
 //             hs->Add(leg1);
-            lastbin2 = (curhistogramclone->GetBinCenter(curhistogramclone->FindLastBinAbove(1,1))>lastbin2)?curhistogramclone->GetBinCenter(curhistogramclone->FindLastBinAbove(1,1)):lastbin2;
             curhistogramclone->SetAxisRange(0,lastbin2*1.1,"X");
 //             heighestval2 = (curhistogramclone->GetMaximum()>heighestval2?curhistogramclone->GetMaximum():heighestval2);
-            curhistogramclone->GetYaxis()->SetRangeUser(5,heighestval2*4);
+            curhistogramclone->GetYaxis()->SetRangeUser(1,heighestval2*4);
             curhistogramclone->Draw("SAME");
             gPad->SetLogy(1);
             owntitle2->Clear();
@@ -358,7 +372,6 @@ Bool_t plotAllRuns(vector<HistogramType*>* ptCompareHistogramClassVector)
             curhistogramclone->Draw("SAME");
             leg3->AddEntry(curhistogramclone, legendEntry, "l");
             leg3->Draw("SAME");
-            lastbin3 = (curhistogramclone->GetBinCenter(curhistogramclone->FindLastBinAbove(0,1))>lastbin3)?curhistogramclone->GetBinCenter(curhistogramclone->FindLastBinAbove(0,1)):lastbin3;
             curhistogramclone->SetAxisRange(1,lastbin3*1.1,"X");            
 //             heighestval3 = (curhistogramclone->GetMaximum()>heighestval3?curhistogramclone->GetMaximum():heighestval3);
             curhistogramclone->GetYaxis()->SetRangeUser(0,heighestval3*1.2);
@@ -373,16 +386,17 @@ Bool_t plotAllRuns(vector<HistogramType*>* ptCompareHistogramClassVector)
             legendEntry = Form("%d Noise: %.2f + %.2f - %.2f",curhistogramclassp->labbook->runnumber, curhistogramclassp->avgNoise, curhistogramclassp->avgNoisePlus, curhistogramclassp->avgNoiseMinus);
             leg4->AddEntry(curhistogramclone, legendEntry, "l");
             leg4->Draw();            
-//             heighestval4 = (curhistogramclone->GetMaximum()>heighestval4?curhistogramclone->GetMaximum():heighestval4);
             curhistogramclone->GetYaxis()->SetRangeUser(0,heighestval4*1.4);
             owntitle4->Clear();
             owntitle4->AddText(trimRunnumberAtBegin(curhistogramclone->GetName()));
             owntitle4->Draw("SAME");
         }
+        canvas->cd(0);
         //TText T; T.SetTextFont(42); T.SetTextAlign(21);
 //                 canvas->cd(2); hs->Draw("nostack same");// T.DrawTextNDC(.5,.95,"Option \"nostack\"");
 //         canvas->BuildLegend();
         canvas->Update();
+        MSaveBigPNG(canvas,savepathresults + "/" + canvastitle + ".png");
         
         TImageDump *img = new TImageDump(savepathresults + "/" + canvastitle + ".png");
         canvas->Paint();
@@ -391,10 +405,9 @@ Bool_t plotAllRuns(vector<HistogramType*>* ptCompareHistogramClassVector)
         TFile *f = new TFile(savepathresults + "/" + canvastitle + ".root","RECREATE");
         f->cd();
         f->Append(canvas);
-        f->Append(img);
+        //f->Append(img);
         f->Write();
         
-        MSaveBigPNG(savepathresults + "/" + canvastitle + ".png");
 //         gROOT->SetStyle("RadHard_AutoTitle");
         return 0;
     }
@@ -455,6 +468,7 @@ Bool_t printSummaryTable(vector<HistogramType*>* ptCompareHistogramClassVector)
         cout << left << setw(width) << setfill(' ') << "Seed Peak"; filecontent += Form("Seed Peak\t");
         cout << left << setw(width) << setfill(' ') << "Veto Peak"; filecontent += Form("Veto Peak\t");
         cout << left << setw(width+2) << setfill(' ') << "Veto Integral"; filecontent += Form("Veto Integral\t");
+        cout << left << setw(width+2) << setfill(' ') << "Sum Integral"; filecontent += Form("Veto Integral\t");
         cout << left << setw(width-2) << setfill(' ') << "Noise"; filecontent += Form("Noise\t");
         cout << left << setw(width) << setfill(' ') << "Noise threshold"; filecontent += Form("Noise threshold\t");
         cout << endl; filecontent += Form("\n");
@@ -477,6 +491,7 @@ Bool_t printSummaryTable(vector<HistogramType*>* ptCompareHistogramClassVector)
             cout << left << setw(width) << setfill(' ') << printTableElement(curhistogramclassp->posSeed,ptCompareHistogramClassVector->at(0)->posSeed); filecontent += Form("%s\t", printTableElement(curhistogramclassp->posSeed,ptCompareHistogramClassVector->at(0)->posSeed).c_str());
             cout << left << setw(width) << setfill(' ') << printTableElement(curhistogramclassp->posVeto,ptCompareHistogramClassVector->at(0)->posVeto); filecontent += Form("%s\t", printTableElement(curhistogramclassp->posVeto,ptCompareHistogramClassVector->at(0)->posVeto).c_str());
             cout << left << setw(width+2) << setfill(' ') << printTableElement(curhistogramclassp->integralVeto,ptCompareHistogramClassVector->at(0)->integralVeto,2); filecontent += Form("%s\t", printTableElement(curhistogramclassp->integralVeto,ptCompareHistogramClassVector->at(0)->integralVeto,4).c_str());
+            cout << left << setw(width+2) << setfill(' ') << printTableElement(curhistogramclassp->integralSum,ptCompareHistogramClassVector->at(0)->integralSum,2); filecontent += Form("%s\t", printTableElement(curhistogramclassp->integralSum,ptCompareHistogramClassVector->at(0)->integralSum,4).c_str());
             cout << left << setw(width-2) << setfill(' ') << printTableElement(curhistogramclassp->avgNoise,ptCompareHistogramClassVector->at(0)->avgNoise); filecontent += Form("%s\t", printTableElement(curhistogramclassp->avgNoise,ptCompareHistogramClassVector->at(0)->avgNoise).c_str());
             cout << left << setw(width) << setfill(' ') << printTableElement(curhistogramclassp->noisethresholdborder,ptCompareHistogramClassVector->at(0)->noisethresholdborder); filecontent += Form("%s\t", printTableElement(curhistogramclassp->noisethresholdborder,ptCompareHistogramClassVector->at(0)->noisethresholdborder).c_str());
             cout << "" << endl; filecontent += Form("\n");
index dd08494e80850986f3921b05634983af01f5c660..e3b49ee0e545f89c1da44ec85230ddd402b653cf 100644 (file)
@@ -101,6 +101,7 @@ Bool_t HistogramType::calibrateHistograms( Float_t gotgain ) {
     calibrated->posSum = posSum * gain;
     calibrated->posVeto = posVeto * gain;
     calibrated->integralVeto = integralVeto * gain;
+    calibrated->integralSum = integralVeto * gain;
     calibrated->posSeedPerc = posSeedPerc;
     calibrated->sigmaSeedPerc = sigmaSeedPerc;
     calibrated->avgNoise = avgNoise * gain;
@@ -167,13 +168,14 @@ Bool_t HistogramType::normalizeHistograms( Int_t got_frames_found ) {
     if (Sum != 0) normalizeHistogram(normalized->Sum, Sum);
     if (Veto != 0) normalizeHistogram(normalized->Veto, Veto);
     if (SeedPerc != 0) normalized->SeedPerc = SeedPerc;
-    normalized->Noise = (TH1F*)Noise->Clone();
-    normalized->histAvgCluster = (TH2F*)histAvgCluster->Clone();
+    if (normalized->Noise != 0)normalized->Noise = (TH1F*)Noise->Clone();
+    if (normalized->histAvgCluster != 0) normalized->histAvgCluster = (TH2F*)histAvgCluster->Clone();
     normalized->frames_found = frames_found;
     normalized->posSeed = posSeed;
     normalized->posSum = posSum;
     normalized->posVeto = posVeto;
-    normalized->integralVeto= integralVeto;
+    normalized->integralVeto= integralVeto/frames_found*pow10(6);
+    normalized->integralSum = integralSum/frames_found*pow10(6);
     normalized->posSeedPerc = posSeedPerc;
     normalized->sigmaSeedPerc = sigmaSeedPerc;
     normalized->noisethresholdborder = noisethresholdborder;
@@ -193,7 +195,7 @@ Bool_t HistogramType::normalizeHistograms( Int_t got_frames_found ) {
 
 void HistogramType::normalizeHistogram(TH1F* &histogrampointernew, TH1F* &histogrampointerold) {
     histogrampointernew = (TH1F*)histogrampointerold->Clone();
-    histogrampointernew->SetName(Form("%s, norm.", histogrampointerold->GetName()));
+    histogrampointernew->SetName(Form("%s norm", histogrampointerold->GetName()));
     histogrampointernew->SetTitle(Form("%s, norm.", histogrampointerold->GetTitle())); 
     int nbins = histogrampointernew->GetXaxis()->GetNbins();    
     for(int x=0; x <= nbins; x++){
@@ -216,13 +218,16 @@ Double_t* HistogramType::FitPerform(TH1F* histogrampointer, TString fitFuncType,
         noiseborder = noisethresholdborder;
 //         cout << "noisethresholdborder: " << noisethresholdborder << endl; }
     
+    
+//     cout << colorred << "    " << histogrampointer->GetName() << "   : " << endlr;
+    
     if (fitFuncType.EqualTo("gaus")) 
     {
         histogrampointer->GetXaxis()->SetRange(histogrampointer->GetXaxis()->FindBin(noiseborder),histogrampointer->GetXaxis()->FindBin(posMaxValHist));   // look only for maxima with x greater than noiseborder, cut away noise        
         //         Int_t xValMax = histogrampointer->GetBinCenter(histogrampointer->GetMaximumBin());
         TF1* fitFunc = new TF1("fitFunc",fitFuncType,noiseborder,posMaxValHist);
         
-        if (TString(histogrampointer->GetName()).Contains("Veto")) 
+        if (TString(histogrampointer->GetName()).Contains("Veto")) // not used any more
         {
 //              if (verbose)
 //                  cout << "Range: " << histogrampointer->GetXaxis()->FindBin(noiseborder) << " to " << histogrampointer->GetXaxis()->FindBin(posMaxValHist) << endl;
@@ -285,17 +290,19 @@ Double_t* HistogramType::FitPerform(TH1F* histogrampointer, TString fitFuncType,
               fitFunc->DrawCopy("same");
         } else {
             histogrampointer->Fit(fitFunc, "N,Q,W", "", noiseborder, posMaxValHist);
+            noiseborder = FindBorderToPeak(histogrampointer, noiseborder,fitFunc->GetParameter(1), verbose); // starting point of histogram integration
             integralPeak = histogrampointer->Integral(histogrampointer->GetXaxis()->FindBin(noiseborder), histogrampointer->GetXaxis()->FindBin(posMaxValHist));
             posMax = fitFunc->GetMaximumX(); // Methode 2
             if (verbose)
                 fitFunc->Draw("SAME");
         }
-        parameters = (Double_t *)calloc(4, sizeof(Double_t));
+        parameters = (Double_t *)calloc(5, sizeof(Double_t));
         for (Int_t pari=0; pari<3; pari++) {
             //cout << colorcyan << fitFunc->GetParameter(pari) << endlr;
             parameters[pari]=fitFunc->GetParameter(pari);
         }
         parameters[3]=integralPeak;
+        parameters[4] = noiseborder;
         Float_t sigma = fitFunc->GetParameter(2);
         posMax2 = fitFunc->GetMaximumX(); // Methode 2
 //         if (verbose)
@@ -439,15 +446,17 @@ Double_t* HistogramType::FitPerform(TH1F* histogrampointer, TString fitFuncType,
         histogrampointer->GetXaxis()->SetRange(noiseborder,posMaxValHist);   // look only for maxima with x greater than noiseborder, cut away noise
 //         histogrampointer->GetXaxis()->SetRangeUser(noiseborder,posMaxValHist);
         TF1* fitFunc = new TF1("fitFunc",GaussTail,noiseborder,posMaxValHist,6);
-        parameters = (Double_t *)calloc(6, sizeof(Double_t));  
+        parameters = (Double_t *)calloc(8, sizeof(Double_t));  
         const Double_t def_amplitude=459.951;
         const Double_t def_peakcenter=histogrampointer->GetBinCenter(histogrampointer->GetMaximumBin());
-//         cout << colorcyan << "def_peakcenter: " << def_peakcenter << endlr;
+        //         cout << colorcyan << "def_peakcenter: " << def_peakcenter << endlr;
         const Double_t def_gausssig=-8.68052;
         const Double_t def_distgauss=20.4;
         const Double_t def_bgslope=0;
         const Double_t def_bgoffs=histogrampointer->GetBinContent(histogrampointer->FindBin((noiseborder+def_peakcenter)/2));
+//         cout << colorcyan << "histogrampointer->FindBin((noiseborder+def_peakcenter)/2): " << histogrampointer->FindBin((noiseborder+def_peakcenter)/2) << endlr;
         
+                
         fitFunc->SetLineWidth(4);
         fitFunc->SetLineColor(kGreen);
         // set start values for some parameters
@@ -467,12 +476,24 @@ Double_t* HistogramType::FitPerform(TH1F* histogrampointer, TString fitFuncType,
         fitFunc->SetParName(5,"background offset");
         fitFunc->SetParameter(5,def_bgoffs);
 //         fitFunc->SetParLimits(5,def_bgoffs*0.8,def_bgoffs*1.2);
-//         cout << "def_bgoffs from " << def_bgoffs*0.8 << " to " << def_bgoffs*1.2 << endl;
         
+        parameters = (Double_t *)calloc(8, sizeof(Double_t));
         int fittries = 0;
         do {
             //                cout << fittries <<  ": New range: " <<  histogrampointer->GetXaxis()->GetBinCenter(min+fittries*min/20) << " to " << posMaxValHist << endl;
-            histogrampointer->Fit(fitFunc, "N,M,Q,W", "", noiseborder, posMaxValHist);
+            histogrampointer->Fit(fitFunc, "N,M,W,Q", "", noiseborder, posMaxValHist);
+//             cout << colorcyan << " AFTER fit " << endlr;   
+            if (gMinuit == nullptr) { 
+                cout << colorred << "  Could not find " << histogrampointer->GetName() << " peak" << endlr;
+                parameters = (Double_t *)calloc(8, sizeof(Double_t));
+                return parameters;
+            }
+            if (gMinuit->fCstatu == "NOT POSDEF") {
+                cout << colorred << "  Could not find " << histogrampointer->GetName() << " peak" << endlr;
+                parameters = (Double_t *)calloc(8, sizeof(Double_t));
+                return parameters;
+            }
+           
             if (gMinuit->fCstatu.Contains("FAILED")) {
                 fitFunc->SetParameter(0,def_amplitude*(1.0-0.1*++fittries));
                 fitFunc->SetParameter(3,def_distgauss*(exp(-fittries/2.0)));
@@ -481,20 +502,26 @@ Double_t* HistogramType::FitPerform(TH1F* histogrampointer, TString fitFuncType,
                 fitFunc->SetParameter(4,def_bgslope);
                 fitFunc->SetParameter(5,def_bgoffs);
             }
-//             cout << colorred << gMinuit->fCstatu.Data() << " fit tries: " << fittries << endlr;            
-        } while (gMinuit->fCstatu.Contains("FAILED") && fittries < 10);
+//             cout << colorcyan << gMinuit->fCstatu.Data() << " fit tries: " << fittries << endlr;            
+        } while (gMinuit->fCstatu.Contains("FAILED") && fittries < 10 && gMinuit->fCstatu == "NOT POSDEF");
          
-        parameters = (Double_t *)calloc(6, sizeof(Double_t));
         for (Int_t pari=0; pari<6; pari++)
         {
             parameters[pari]=fitFunc->GetParameter(pari);
 //             fitFunc->SetParameter(pari,parameters[pari]);            
         }
-        fitFunc->FixParameter(1,parameters[1]+histogrampointer->GetBinWidth(0));            
-        histogrampointer->Fit(fitFunc, "N,M,W,Q", "", noiseborder, posMaxValHist);   
+//         fitFunc->FixParameter(1,parameters[1]+histogrampointer->GetBinWidth(0));            
+//         histogrampointer->Fit(fitFunc, "N,M,W,Q", "", noiseborder, posMaxValHist);           
+//         for (Int_t pari=0; pari<6; pari++)
+//             parameters[pari]=fitFunc->GetParameter(pari);     
+        parameters[1] = parameters[1] + histogrampointer->GetBinWidth(0);
+
         
-        for (Int_t pari=0; pari<6; pari++)
-            parameters[pari]=fitFunc->GetParameter(pari);     
+        parameters[7] = FindBorderToPeak(histogrampointer, noiseborder,def_peakcenter, verbose); // starting point of histogram integration
+        parameters[6] = histogrampointer->Integral(histogrampointer->FindBin(parameters[7]), histogrampointer->GetXaxis()->FindBin(posMaxValHist)); // integral value of histogram (NOT fit)
+//         cout << colorcyan << "Integral from bin : " << histogrampointer->FindBin(parameters[7])  << " to " << histogrampointer->GetXaxis()->FindBin(posMaxValHist) << endlr;  
+//         cout << colorcyan << "Integral from val : " << parameters[7] << " to " << histogrampointer->GetBinCenter(histogrampointer->GetXaxis()->FindBin(posMaxValHist)) << endlr;  
+//         cout << colorcyan << "Integral value: " << parameters[6] << endlr;            
 
 //             DEBUG
 //         TCanvas* canvas = new TCanvas(histogrampointer->GetName(), histogrampointer->GetName(), 900, 700);
@@ -514,12 +541,12 @@ Bool_t HistogramType::calculteCCE(Bool_t verbose) {
         CCE_in_Perc_1 = posSeed / posVeto * 100.0;
     if (posSum > 0 && posVeto > 0)
         CCE_in_Perc_25 = posSum / posVeto * 100.0;
-    if (CCE_in_Perc_1 > 0 || CCE_in_Perc_25 > 0)
-        return 0;
     if (verbose) {
         cout << "   CCE Seed: " << colorgreen << CCE_in_Perc_1 << " %" << endlr;
         cout << "   CCE Sum:  " << colorgreen << CCE_in_Perc_25 << " %" << endlr;
     }
+    if (CCE_in_Perc_1 > 0 || CCE_in_Perc_25 > 0)
+        return 0;
     return 1;
 }
 
@@ -601,6 +628,62 @@ Bool_t HistogramType::FindNoisethresholdborder(TH1F* histogrampointer, Bool_t ov
     return 1;
 }
 
+
+Double_t HistogramType::FindBorderToPeak(TH1F* histogrampointer, Double_t startVal, Double_t endVal, Bool_t verbose) {        
+    Double_t borderval=0;
+    Double_t peakval=0;
+    TH1F* smoothedcurce = (TH1F*)histogrampointer->Clone();
+    
+    Int_t rebinningfactor = 2;
+    smoothedcurce->RebinX(rebinningfactor);    
+    smoothedcurce->SetAxisRange(startVal,histogrampointer->GetBinCenter(histogrampointer->GetNbinsX()));
+    smoothedcurce->Smooth(2);
+    peakval = smoothedcurce->GetBinContent(smoothedcurce->GetMaximumBin());
+    
+    if (endVal == 0)
+        endVal = smoothedcurce->GetBinContent(smoothedcurce->GetNbinsX());
+    
+    
+    if (verbose) {
+         cout << colorcyan << "max value: " << peakval << endlr;
+         cout << colorwhite << histogrampointer->GetName() << endlr;
+         TString canvastitle = Form("%s border search", histogrampointer->GetName());
+         TString canvasname =  Form("%s border search", histogrampointer->GetName());
+//          TCanvas* canvas = new TCanvas(canvasname, canvastitle, 900, 700);
+//          smoothedcurce->SetLineColor(color+1);
+//          smoothedcurce->Draw("SAME");
+//          histogrampointer->Draw("SAME");
+//          canvas->Update();
+     }
+    Int_t bini = smoothedcurce->FindBin(startVal);
+    Int_t rising = 0;
+    Int_t bincurcandidate = bini;
+    do {
+        Float_t curval=smoothedcurce->GetBinContent(bini++);
+        if (curval*0.97+1 <= smoothedcurce->GetBinContent(bini) && smoothedcurce->GetBinContent(bini) > peakval*0.1+2)
+        {
+            rising++;
+            if (verbose)
+                cout << "rising at bin " << bini << ":" <<  smoothedcurce->GetXaxis()->GetBinCenter(bini) << "   as " << curval  << " < " << smoothedcurce->GetBinContent(bini) << endl; // debug
+        }
+        else
+        {
+            rising = 0;
+            bincurcandidate = bini;
+            if (verbose)
+                cout << "falling at bin " << bini << ":" <<  smoothedcurce->GetXaxis()->GetBinCenter(bini) << "   as " << curval  << " < " << smoothedcurce->GetBinContent(bini) << endl; // debug
+        }
+    } while (rising < 5 && bini<smoothedcurce->FindBin(endVal));
+    bincurcandidate *= rebinningfactor;
+    
+    borderval = histogrampointer->GetXaxis()->GetBinUpEdge(bincurcandidate);
+    if (verbose) {
+        cout << "     Border at " << borderval << endl;
+    }
+    return borderval;
+}
+
+
 Bool_t HistogramType::integrateSr90Spectra(TH1F* histogrampointer, Int_t frames_found, Float_t thresholdborder, Bool_t verbose) {
 
     Int_t thresholdbincurcandidate = 0;
@@ -692,7 +775,7 @@ Double_t HistogramType::GaussTail(Double_t *x, Double_t *par) {
     // par[0] = amplitude of peak
     // par[1] = peak centroid
     // par[2] = Gaussian sigma
-    // par[3] = Distance before par[3] where shape deviates from Gaussian
+    // par[3] = Distance under par[3] where shape deviates from Gaussian
     // par[4] = background slope
     // par[5] = background offset
     Double_t bg, offset, rgauss, rtail, rtn;
index 9e27c0755cd135113bdbe609e52735ef854fe8f0..a1cd1991fae0be2666369a2985e9f3b3f4d143e7 100644 (file)
@@ -127,9 +127,11 @@ public:
     Float_t posSeed=0;
     /// fitted position of the most probable value in the over cluster summed spectrum
     Float_t posSum=0;
+    /// fintegral over the sum peak, normalized to number of events
+    Double_t integralSum=0;
     /// fitted position of the calibration peak of Fe55-beta-photons in the seed spectrum, from a run best suited to the current
     Float_t posVeto=0;
-    /// fitted position of the calibration peak of Fe55-beta-photons in the seed spectrum, from a run best suited to the current
+    /// fintegral over the veto peak, normalized to number of events
     Double_t integralVeto=0;
     
     /// Average Noise value
@@ -236,6 +238,15 @@ public:
      */
     Bool_t FindNoisethresholdborder(TH1F* histogrampointer, Bool_t overwrite=false, Bool_t verbose=false);
     
+    
+    /**
+     * @brief Tries to find a beginning of a peak
+     *      
+     * @return the value found
+     * 
+     */
+    Double_t FindBorderToPeak(TH1F* histogrampointer, Double_t startVal=0, Double_t endVal=0, Bool_t verbose=false);      
+    
     /**
      * @brief calculates StoN ratio, if beta source was used
      * 
index 19c1419790000b60e242c726ffd4010b1687f94f..4a6ccf047a66f1cf0c9f1a618c3bb17f9b10ba79 100644 (file)
@@ -29,7 +29,7 @@ Run::Run(Int_t runnumber)
     Run(runnumber, 0);
 }
 
-Run::Run(Int_t runnumber, Int_t loopi)
+Run::Run(Int_t runnumber, Int_t loopi, TString customtitle)
 {
     plotStyle = loopi%13;
     gethostname(hostname, 1024);
@@ -50,6 +50,8 @@ Run::Run(Int_t runnumber, Int_t loopi)
             labbook.temp = (rowsql->GetField(1) != NULL)?atof(rowsql->GetField(1)):-272;
             labbook.tempSens = (rowsql->GetField(2) != NULL)?atof(rowsql->GetField(2)):-272;
             labbook.chip = (rowsql->GetField(4) != NULL)?std::string(rowsql->GetField(4)):"";
+            if (customtitle.Length() > 0)
+                labbook.chip = customtitle;
             labbook.source = (rowsql->GetField(5) != NULL)?std::string(rowsql->GetField(5)):"";
             labbook.matrix = (rowsql->GetField(6) != NULL)?std::string(rowsql->GetField(6)):"";
             labbook.clock = (rowsql->GetField(7) != NULL)?atoi(rowsql->GetField(7)):100;
@@ -158,8 +160,8 @@ Run::Run(Int_t runnumber, Int_t loopi)
             histogramthreshold = new HistogramType(" Threshold", &cursystemparam, &cursensorinfo, humanreadablestr, &labbook, rootcolors[plotStyle], rootlinestyle[plotStyle] );
             HistogramClassVector.push_back(histogramthreshold);
             // fixed threshold cut
-            histogramfixedthreshold = new HistogramType(" fixed Threshold", &cursystemparam, &cursensorinfo, humanreadablestr, &labbook, rootcolors[plotStyle], rootlinestyle[plotStyle] );
-            HistogramClassVector.push_back(histogramfixedthreshold);
+//             histogramfixedthreshold = new HistogramType(" fixed Threshold", &cursystemparam, &cursensorinfo, humanreadablestr, &labbook, rootcolors[plotStyle], rootlinestyle[plotStyle] );
+//             HistogramClassVector.push_back(histogramfixedthreshold);
             
             debugDBreadout();
         }
@@ -391,8 +393,8 @@ Bool_t Run::analyzeRun(Bool_t force)
 //         processed->plotPixSignal(0,10000000,351);
         cout << colorwhite << "binSeedSumVeto():" << endlr;
         binSeedSumVeto(); 
-        cout << colorwhite << "binCluster():" << endlr;
-        binCluster();
+//         cout << colorwhite << "binCluster():" << endlr;
+//         binCluster();
         cout << "---------- loop over all classes --------" << endl;
         for (vector<HistogramType*>::iterator curHistogramClass = HistogramClassVector.begin(); curHistogramClass != HistogramClassVector.end(); curHistogramClass++)  {
             cout << "Processing histograms in class: <" << colorwhite << (*curHistogramClass)->histogramdescription << colorreset << " >" << endlr;
@@ -408,7 +410,7 @@ Bool_t Run::analyzeRun(Bool_t force)
             }
             if (labbook.source.Contains("Fe")||labbook.source.Contains("Cd")) {
                 cout << colorwhite << " calculateCCE():" << endlr;
-                (*curHistogramClass)->calculteCCE(true);
+                (*curHistogramClass)->calculteCCE(false);
             }
             if (labbook.source.Contains("Sr90")) {
                 //cout << colorwhite << " integrateSr90Spectra():" << endlr;
@@ -421,7 +423,8 @@ Bool_t Run::analyzeRun(Bool_t force)
         if (labbook.source.Contains("Sr90")) {
             cout << colorwhite << "integrateSr90Spectra():" << endlr;
             histogramthreshold->integrateSr90Spectra(histogramthreshold->Seed, frames_found, -1, true);
-            histogramfixedthreshold->integrateSr90Spectra(histogramfixedthreshold->Seed, frames_found, 0);
+            if (histogramfixedthreshold != 0)
+                histogramfixedthreshold->integrateSr90Spectra(histogramfixedthreshold->Seed, frames_found, 0);
         }
         cout << colorwhite << "normalizeHistogramClasses():" << endlr;
         normalizeHistogramClasses();
@@ -747,24 +750,26 @@ void Run::updateDatabase() {
     
     
     string sqlupdatequery = "";
-    constructUpdateString(&sqlupdatequery, "Gain",       histogram->gain);
-    constructUpdateString(&sqlupdatequery, "SumPeak",    histogram->posSum, 4);
-    constructUpdateString(&sqlupdatequery, "SeedPeak",   histogram->posSeed, 4);
-    constructUpdateString(&sqlupdatequery, "VetoPeak",   histogram->posVeto, 4);
-    constructUpdateString(&sqlupdatequery, "VetoIntegral",   histogram->integralVeto, 10);
-    if (histogram->calibrated != 0)
-        constructUpdateString(&sqlupdatequery, "Avg.Noise",  histogram->calibrated->avgNoise);
-    if (histogram->calibrated != 0)
-        constructUpdateString(&sqlupdatequery, "Avg.Noise+", histogram->calibrated->avgNoisePlus, 2);
-    if (histogram->calibrated != 0)
-        constructUpdateString(&sqlupdatequery, "Avg.Noise-", histogram->calibrated->avgNoiseMinus, 2);
-    constructUpdateString(&sqlupdatequery, "CCE_1",      histogram->CCE_in_Perc_1);
-    constructUpdateString(&sqlupdatequery, "CCE_25",     histogram->CCE_in_Perc_25);
-    constructUpdateString(&sqlupdatequery, "StoN",     histogram->StoN, 3);
-       constructUpdateString(&sqlupdatequery, "Avg.NoiseADC",  histogram->avgNoise);
+    constructUpdateString(&sqlupdatequery, "Gain",       histogramthreshold->normalized->gain);
+    constructUpdateString(&sqlupdatequery, "SumPeak",    histogramthreshold->normalized->posSum, 4);
+    constructUpdateString(&sqlupdatequery, "SeedPeak",   histogramthreshold->normalized->posSeed, 4);
+    constructUpdateString(&sqlupdatequery, "VetoPeak",   histogramthreshold->normalized->posVeto, 4);
+    constructUpdateString(&sqlupdatequery, "VetoIntegral",   histogramthreshold->normalized->integralVeto, 10);
+    constructUpdateString(&sqlupdatequery, "SumIntegral",   histogramthreshold->normalized->integralSum, 10);
+    if (histogramthreshold->normalized->calibrated != 0)
+        constructUpdateString(&sqlupdatequery, "Avg.Noise",  histogramthreshold->normalized->calibrated->avgNoise);
+    if (histogramthreshold->normalized->calibrated != 0)
+        constructUpdateString(&sqlupdatequery, "Avg.Noise+", histogram->normalized->calibrated->avgNoisePlus, 2);
+    if (histogramthreshold->normalized->calibrated != 0)
+        constructUpdateString(&sqlupdatequery, "Avg.Noise-", histogramthreshold->normalized->calibrated->avgNoiseMinus, 2);
+    constructUpdateString(&sqlupdatequery, "CCE_1",      histogramthreshold->normalized->CCE_in_Perc_1);
+    constructUpdateString(&sqlupdatequery, "CCE_25",     histogramthreshold->normalized->CCE_in_Perc_25);
+    constructUpdateString(&sqlupdatequery, "StoN",     histogramthreshold->normalized->StoN, 3);
+    constructUpdateString(&sqlupdatequery, "Avg.NoiseADC",  histogramthreshold->normalized->avgNoise);
     constructUpdateString(&sqlupdatequery, "Frames_found", frames_found,100000000);
-    if (histogram->calibrated != 0)
-        constructUpdateString(&sqlupdatequery, "Sr90IntegralVal", histogramfixedthreshold->calibrated->sr90IntegralVal,1000000000);
+    if (histogramthreshold->normalized->calibrated != 0)
+        if (histogramfixedthreshold != 0)
+            constructUpdateString(&sqlupdatequery, "Sr90IntegralVal", histogramfixedthreshold->normalized->calibrated->sr90IntegralVal,1000000000);
   
     if (sqlupdatequery.length()>0)
     {
@@ -890,17 +895,19 @@ Bool_t Run::binSeedSumVeto()
                             histogramthreshold->Veto->Fill(processed->fFrameInfo.p[12][hiti]);    // histogram with the single pixel
                     }
                     
-                    if (processed->fFrameInfo.pixelfixedthreshold[hiti]>0)
-                    {
-                        histogramfixedthreshold->numberofhits++;
-                        
-                        histogramfixedthreshold->Seed->Fill(processed->fFrameInfo.p[12][hiti]);
-                        histogramfixedthreshold->Sum->Fill(pixelSum);
-                        histogramfixedthreshold->SeedPerc->Fill(processed->fFrameInfo.p[12][hiti]/pixelSum*100);  
-                        if (TMath::Abs(notSeedSum) < cursystemparam.vetothreshold && (labbook.source.Contains("Fe")||labbook.source.Contains("Cd")))
-                            histogramfixedthreshold->Veto->Fill(processed->fFrameInfo.p[12][hiti]);    // histogram with the single pixel
+                    if (histogramfixedthreshold != 0) {
+                        cout << colorred << "NOT NULL! " << endlr;
+                        if (processed->fFrameInfo.pixelfixedthreshold[hiti]>0)
+                        {
+                            histogramfixedthreshold->numberofhits++;
+                            
+                            histogramfixedthreshold->Seed->Fill(processed->fFrameInfo.p[12][hiti]);
+                            histogramfixedthreshold->Sum->Fill(pixelSum);
+                            histogramfixedthreshold->SeedPerc->Fill(processed->fFrameInfo.p[12][hiti]/pixelSum*100);  
+                            if (TMath::Abs(notSeedSum) < cursystemparam.vetothreshold && (labbook.source.Contains("Fe")||labbook.source.Contains("Cd")))
+                                histogramfixedthreshold->Veto->Fill(processed->fFrameInfo.p[12][hiti]);    // histogram with the single pixel
+                        }
                     }
-                    
                 }
             }
         }
@@ -908,18 +915,23 @@ Bool_t Run::binSeedSumVeto()
 //     gROOT->SetBatch(kTRUE);
 
     for (vector<HistogramType*>::iterator curHistogramClass = HistogramClassVector.begin(); curHistogramClass != HistogramClassVector.end(); curHistogramClass++)  {
-        Double_t* parameters = (Double_t *)calloc(6, sizeof(Double_t));
+        Double_t* parameters = (Double_t *)calloc(8, sizeof(Double_t));
         (*curHistogramClass)->FindNoisethresholdborder((*curHistogramClass)->Seed, false, false);
+        if (labbook.runnumber == 343056)
+            (*curHistogramClass)->noisethresholdborder = 34;
         if (labbook.source.Contains("Fe")||labbook.source.Contains("Cd")) {
             parameters = (*curHistogramClass)->FitPerform((*curHistogramClass)->Veto, "GaussTail");
             (*curHistogramClass)->posVeto = parameters[1];
-//             cout << (*curHistogramClass)->histogramdescription << ": " << colorcyan <<  parameters[1] << endlr;
+            if (labbook.runnumber == 343056)
+                (*curHistogramClass)->posVeto = 234;
+            //             cout << (*curHistogramClass)->histogramdescription << ": " << colorcyan <<  parameters[1] << endlr;
+            (*curHistogramClass)->integralVeto = parameters[6];
         }
-        (*curHistogramClass)->integralVeto = parameters[3]/frames_found;
         parameters = (*curHistogramClass)->FitPerform((*curHistogramClass)->Seed, "landau");
         (*curHistogramClass)->posSeed = parameters[1];
         parameters = (*curHistogramClass)->FitPerform((*curHistogramClass)->Sum, "gaus");
         (*curHistogramClass)->posSum = parameters[1];
+        (*curHistogramClass)->integralSum = parameters[3];
         
         parameters =(*curHistogramClass)->FitPerform((*curHistogramClass)->SeedPerc, "landau");
         (*curHistogramClass)->posSeedPerc = parameters[1];
@@ -933,7 +945,9 @@ Bool_t Run::binSeedSumVeto()
             (*curHistogramClass)->SeedPerc->SetBinContent(bini,(*curHistogramClass)->SeedPerc->GetBinContent(bini)/0.01/((*curHistogramClass)->SeedPerc->GetEntries()));
         }
     }
-    histogramfixedthreshold->noisethresholdborder=0;
+    if (histogramfixedthreshold != 0) {
+        histogramfixedthreshold->noisethresholdborder=0;
+    }
     //     gROOT->SetBatch(kFALSE);    
     return 0;
 }
@@ -1000,8 +1014,9 @@ Bool_t Run::binCluster()
                             histogram->histAvgCluster->Fill(xcoord,ycoord,processed->fFrameInfo.p[clusteri][hiti]);
                             if (processed->fFrameInfo.pixelthreshold[hiti]>0)
                                 histogramthreshold->histAvgCluster->Fill(xcoord,ycoord,processed->fFrameInfo.p[clusteri][hiti]);
-                            if (processed->fFrameInfo.pixelfixedthreshold[hiti]>0)
-                                histogramfixedthreshold->histAvgCluster->Fill(xcoord,ycoord,processed->fFrameInfo.p[clusteri][hiti]);
+                            if (histogramfixedthreshold != 0)
+                                if (processed->fFrameInfo.pixelfixedthreshold[hiti]>0)
+                                    histogramfixedthreshold->histAvgCluster->Fill(xcoord,ycoord,processed->fFrameInfo.p[clusteri][hiti]);
                         } 
                     }
                     else // Diode sitzt unten im SeedPixel, da nach PitchY angeordnet
@@ -1031,8 +1046,9 @@ Bool_t Run::binCluster()
                             histogram->histAvgCluster->Fill(xcoord,ycoord,processed->fFrameInfo.p[clusteri][hiti]);
                             if (processed->fFrameInfo.pixelthreshold[hiti]>0)
                                 histogramthreshold->histAvgCluster->Fill(xcoord,ycoord,processed->fFrameInfo.p[clusteri][hiti]);
-                            if (processed->fFrameInfo.pixelfixedthreshold[hiti]>0)
-                                histogramfixedthreshold->histAvgCluster->Fill(xcoord,ycoord,processed->fFrameInfo.p[clusteri][hiti]);
+                            if (histogramfixedthreshold != 0)
+                                if (processed->fFrameInfo.pixelfixedthreshold[hiti]>0)
+                                    histogramfixedthreshold->histAvgCluster->Fill(xcoord,ycoord,processed->fFrameInfo.p[clusteri][hiti]);
                         }
                     }
                 }
@@ -1044,7 +1060,8 @@ Bool_t Run::binCluster()
         for (Int_t clustery = 1; clustery <=histogram->histAvgCluster->GetYaxis()->GetNbins();clustery++) {
             histogram->histAvgCluster->SetBinContent(clusterx,clustery,histogram->histAvgCluster->GetBinContent(clusterx,clustery)/histogram->numberofhits);
             histogramthreshold->histAvgCluster->SetBinContent(clusterx,clustery,histogramthreshold->histAvgCluster->GetBinContent(clusterx,clustery)/histogramthreshold->numberofhits);
-            histogramfixedthreshold->histAvgCluster->SetBinContent(clusterx,clustery,histogramfixedthreshold->histAvgCluster->GetBinContent(clusterx,clustery)/histogramfixedthreshold->numberofhits);
+            if (histogramfixedthreshold != 0)
+                histogramfixedthreshold->histAvgCluster->SetBinContent(clusterx,clustery,histogramfixedthreshold->histAvgCluster->GetBinContent(clusterx,clustery)/histogramfixedthreshold->numberofhits);
         }
     }
     
@@ -1484,31 +1501,6 @@ Bool_t Run::plotClusterDistribution(HistogramType* HistogramTypepointer)
 }
 
 
-void Run::plotVerticalLine(TH1F* histogrampointer, Float_t xVal) {
-    if (xVal > 0)
-    {
-        Float_t posMaxValue = 0;
-        posMaxValue = histogrampointer->GetXaxis()->FindBin(xVal);
-        posMaxValue = histogrampointer->GetBinContent(posMaxValue);
-        TLine *l = new TLine(xVal,0.5,xVal,posMaxValue);
-        l->SetLineColor(kRed);
-        l->SetLineStyle(2); // dashed
-        l->Draw("same"); 
-
-        TString  legendEntry;
-        if (abs(xVal) < 1)
-            legendEntry = TString(Form("peak position: %.2f",xVal ));
-        else    
-            legendEntry = TString(Form("peak position: %.1f",xVal ));
-        TLegend* leg = new TLegend(0.65,0.65,0.80,0.80);//(0.6,0.7,0.89,0.89);
-        leg->SetFillColor(0);
-        leg->SetBorderSize(0);
-        leg->SetFillStyle(0);
-        leg->AddEntry((TObject*) 0, legendEntry, "");
-        leg->SetTextSize(0.025);
-        leg->Draw();
-    }
-}
 
 TCanvas* Run::plot1DHistogram(HistogramType* HistogramTypepointer, TH1F* onehistogram, TString fitFuncType, Bool_t verbose, Float_t fitstart, TString titlestr, TString legendstr)
 {
@@ -1522,13 +1514,16 @@ TCanvas* Run::plot1DHistogram(HistogramType* HistogramTypepointer, TH1F* onehist
         TCanvas* canvas = new TCanvas(canvasname, canvastitle, 900, 700);
         onehistogram->SetTitle(titlestr);
         onehistogram->Draw();
-        Double_t* parameters = (Double_t *)calloc(6, sizeof(Double_t)); // allocate 7 parameters for safety, maximum 6 used at the moment
+        Double_t* parameters = (Double_t *)calloc(9, sizeof(Double_t)); // allocate 9 parameters for safety, maximum 8 used at the moment
         parameters = HistogramTypepointer->FitPerform(onehistogram, fitFuncType, verbose, fitstart);
         Float_t maxValue = parameters[1];
         plotVerticalLine(onehistogram, maxValue);
+        
         Float_t startvalue = onehistogram->GetBinLowEdge(onehistogram->FindFirstBinAbove(0));
-        Float_t endrange = onehistogram->GetBinCenter(onehistogram->FindLastBinAbove(0));
+        Float_t endrange = onehistogram->GetBinCenter(onehistogram->FindLastBinAbove(1));
+        Float_t endrangeY = onehistogram->GetMaximum();
         onehistogram->GetXaxis()->SetRangeUser(startvalue,endrange);
+        onehistogram->GetYaxis()->SetRangeUser(0,endrangeY*1.4);
         TLegend* leg = new TLegend(0.2,0.85,0.89,0.89);//(0.6,0.7,0.89,0.89);
         leg->SetFillColor(0);
         leg->SetBorderSize(0);
@@ -1538,8 +1533,31 @@ TCanvas* Run::plot1DHistogram(HistogramType* HistogramTypepointer, TH1F* onehist
             
         leg->SetTextSize(0.025);
         leg->Draw();
+//         canvas->Draw();
+//         canvas->Update();;
+                
+        if (fitFuncType=="GaussTail")
+        {
+            Float_t integralstart = parameters[7];
+            Float_t integralval = parameters[6];
+            TString integrallbl = Form("Integral: %.0f", integralval);
+//             cout << colorcyan << "  " << HistogramTypepointer->histogramdescription << endlr;
+//             cout << colorcyan << ": " << parameters[7] << endlr;
+            plotVerticalLineHeigher(onehistogram, integralstart);
+            plotTextAtVal(onehistogram, maxValue, integrallbl);
+        }      
+        if (fitFuncType=="gaus")
+        {
+            Float_t integralstart = parameters[4];
+            Float_t integralval = parameters[3];
+            TString integrallbl = Form("Integral: %.0f", integralval);
+//             cout << colorcyan << "  " << HistogramTypepointer->histogramdescription << endlr;
+//             cout << colorcyan << ": " << parameters[4] << endlr;
+            plotVerticalLineHeigher(onehistogram, integralstart);
+            plotTextAtVal(onehistogram, maxValue, integrallbl);
+        }
         
-        canvas -> SaveAs( savepathresults + "/" + runcode + " " + onehistogram->GetName() + ".eps");
+//         canvas -> SaveAs( savepathresults + "/" + runcode + " " + onehistogram->GetName() + ".eps");
             
         TImageDump *img = new TImageDump(savepathresults + "/" + runcode + " " + onehistogram->GetName() + ".png");
         canvas->Paint();
index 18496726cc2ceed733903c2158534392ef931f66..a360e863b6d06a81cbee071fbea161ffac9c543e 100644 (file)
@@ -158,15 +158,6 @@ private:
     
     /// A string representing the current run database information in a human readable format
     TString humanreadablestr="";
-    
-    /**
-     * @brief Plots vertical dotted red line from x-axis to graph at place x
-     * 
-     * @param histogrampointer histogram pointer to calculate vertical line end
-     * @param xVal position of the vertical line at x-axis
-     * 
-     */
-    void plotVerticalLine(TH1F* histogrampointer, Float_t xVal);
                          
     /**
      * @brief Checks if a file exists
@@ -227,7 +218,7 @@ public:
     /** @brief default constructor */
     Run    ( Int_t );
     /** @brief default constructor */
-    Run    ( Int_t, Int_t );
+    Run    ( Int_t, Int_t , TString customtitle = "");
     /** @brief writes values back to the database, destroys the #MAPS object */
     ~Run   (void);
 
@@ -359,9 +350,9 @@ public:
     /** @brief calls #Run::setSubMatrixBorders() with the correct boundaries for FSBB submatrix A0 or A1 */
     void selectSubMatrixFSBB(TString matrixname);
     
-    HistogramType* histogram;
-    HistogramType* histogramthreshold;
-    HistogramType* histogramfixedthreshold;
+    HistogramType* histogram = 0;
+    HistogramType* histogramthreshold = 0;
+    HistogramType* histogramfixedthreshold = 0;
     
     /// 
     /** @brief A vector able to hold pointer of type #Run::histogramstruct
index 96c0809d2cb2ea7e6e7d9b5a8cbf038d23e636a4..4ee3e07903f52f783a12a9b96c589d703ded6153 100644 (file)
@@ -13,6 +13,8 @@
 #include <TCanvas.h>
 #include <Rtypes.h>
 #include <TString.h>
+#include <TTimeStamp.h>
+#include <TLegend.h>
 
 #define MAXHITS                        1000000
 //####################################################################
@@ -254,11 +256,9 @@ void preparecanvas() {
 //     return 0;
 }
 
-void MSaveBigPNG(TString filename="", double scale=2) {
-    TCanvas* old_canv = gPad->GetCanvas();
-    
+void MSaveBigPNG(TCanvas* old_canv, TString filename="", double scale=1) {    
     gROOT->SetBatch(kTRUE);
-    gROOT->ForceStyle(kTRUE);
+//     gROOT->ForceStyle(kTRUE);
     
     Int_t orig_msz = gStyle->GetMarkerSize();
     Int_t orig_mst = gStyle->GetMarkerStyle();
@@ -281,7 +281,9 @@ void MSaveBigPNG(TString filename="", double scale=2) {
     Int_t new_width = old_width * scale;
     Int_t new_height= old_height* scale;
     
-    TCanvas* temp_canvas = new TCanvas("temp", "", new_width, new_height);
+    TTimeStamp* time = new TTimeStamp(); 
+    TString canvasname = Form("%d",time->GetNanoSec());  
+    TCanvas* temp_canvas = new TCanvas(canvasname, "", new_width, new_height);
     old_canv->DrawClonePad();
     
     temp_canvas->Draw();
@@ -294,12 +296,20 @@ void MSaveBigPNG(TString filename="", double scale=2) {
     gStyle->SetHistLineWidth(orig_lt);
     gStyle->SetFuncWidth(orig_lt);
     
-    gROOT->ForceStyle(kFALSE);
-    gROOT->SetBatch(kFALSE);
+    if (!isBatch) {
+//         gROOT->ForceStyle(kFALSE);
+        gROOT->SetBatch(kFALSE);
+    }
     
     return;
 }
 
+void MSaveBigPNG(TString filename="", double scale=2) {    
+    cout << colorcyan << "MSaveBigPNG: " << gPad->GetCanvas()->GetTitle() << endlr;
+    TCanvas* old_canvas = gPad->GetCanvas();
+    MSaveBigPNG(old_canvas);  
+}
+
 TString trimRunnumberAtBegin(TString str) {
     size_t i = 0;
     while(isdigit(str(i++)));
@@ -312,5 +322,107 @@ TString getRunnumberAtBegin(TString str) {
     return str(0, i-1);
 }
 
+
+/**
+ * @brief Plots vertical dotted red line from x-axis to graph at place x
+ * 
+ * @param histogrampointer histogram pointer to calculate vertical line end
+ * @param xVal position of the vertical line at x-axis
+ * 
+ */
+void plotVerticalLine(TH1F* histogrampointer, Float_t xVal) {
+    if (xVal > 0)
+    {
+        Float_t posMaxValue = 0;
+        posMaxValue = histogrampointer->GetXaxis()->FindBin(xVal);
+        posMaxValue = histogrampointer->GetBinContent(posMaxValue);
+        TLine *l = new TLine(xVal,0.5,xVal,posMaxValue);
+        l->SetLineColor(kRed);
+        l->SetLineStyle(2); // dashed
+        l->Draw("same"); 
+        
+        TString  legendEntry;
+        if (abs(xVal) < 1)
+            legendEntry = TString(Form("peak position: %.2f",xVal ));
+        else    
+            legendEntry = TString(Form("peak position: %.1f",xVal ));
+        TLegend* leg = new TLegend(0.65,0.65,0.80,0.80);//(0.6,0.7,0.89,0.89);
+        leg->SetFillColor(0);
+        leg->SetBorderSize(0);
+        leg->SetFillStyle(0);
+        leg->AddEntry((TObject*) 0, legendEntry, "");
+        leg->SetTextSize(0.025);
+        leg->Draw();
+    }
+}
+
+
+/**
+ * @brief Plots vertical dotted gray line from x-axis to graph at place x
+ * 
+ * @param histogrampointer histogram pointer to calculate vertical line end
+ * @param xVal position of the vertical line at x-axis
+ */
+void plotVerticalLineHeigher(TH1F* histogrampointer, Float_t xVal) {
+    if (xVal > 0)
+    {        
+        Double_t gPadX2 = histogrampointer->GetBinCenter(histogrampointer->GetXaxis()->GetLast());
+        Double_t gPadY2 = histogrampointer->GetMaximum();
+        //         cout << gPadX2 << endl;
+        //         cout << gPadY2 << endl;  
+        
+        Float_t posMaxValue = 0;
+        posMaxValue = histogrampointer->GetXaxis()->FindBin(xVal);
+        posMaxValue = histogrampointer->GetBinContent(posMaxValue);
+        TLine *l = new TLine(xVal,0.5,xVal,posMaxValue+gPadY2*0.1);
+        l->SetLineColor(12);
+        l->SetLineStyle(9); // dashed
+        l->SetLineWidth(2);
+        l->Draw("same"); 
+        
+        TString  legendEntry;
+        if (abs(xVal) < 1)
+            legendEntry = TString(Form("integral from: %.2f",xVal ));
+        else    
+            legendEntry = TString(Form("integral from: %.1f",xVal ));
+        //         TLegend* leg = new TLegend(xVal*0.9/gPadX2,posMaxValue*1.05/gPadY2,xVal*1.2/gPadX2,posMaxValue*1.1/gPadY2, "", "");//(0.6,0.7,0.89,0.89);
+        TLegend* leg = new TLegend(xVal/gPadX2-0.25,posMaxValue/gPadY2+0.15,xVal/gPadX2+0.1,posMaxValue/gPadY2+0.25);//(0.6,0.7,0.89,0.89);
+        leg->SetFillColor(0);
+        leg->SetBorderSize(0);
+        leg->SetFillStyle(0);
+        leg->AddEntry((TObject*) 0, legendEntry, "");
+        leg->SetTextSize(0.025);
+        leg->Draw();
+    }
+}
+
+
+/**
+ * @brief Plots a label with a text next to the coordinate x
+ * 
+ * @param histogrampointer histogram pointer to calculate vertical line end
+ * @param xVal position of the vertical line at x-axis
+ * 
+ */
+void plotTextAtVal(TH1F* histogrampointer, Float_t xVal, TString legendEntry) {
+    if (xVal > 0)
+    {
+        Double_t gPadX2 = histogrampointer->GetBinCenter(histogrampointer->GetXaxis()->GetLast());
+        Double_t gPadY2 = histogrampointer->GetMaximum()*1.4;
+        
+        Float_t posMaxValue = 0;
+        posMaxValue = histogrampointer->GetXaxis()->FindBin(xVal);
+        posMaxValue = histogrampointer->GetBinContent(posMaxValue);
+        
+        TLegend* leg = new TLegend(xVal/gPadX2-0.43,posMaxValue/gPadY2-0.2,xVal/gPadX2,posMaxValue/gPadY2+0.1);//(0.6,0.7,0.89,0.89);
+        leg->SetFillColor(0);
+        leg->SetBorderSize(0);
+        leg->SetFillStyle(0);
+        leg->AddEntry((TObject*) 0, legendEntry, "");
+        leg->SetTextSize(0.025);
+        leg->Draw();
+    }
+}
+
 //####################################################################
 #endif
\ No newline at end of file
diff --git a/bot/Chips/Pegasus.au3 b/bot/Chips/Pegasus.au3
new file mode 100755 (executable)
index 0000000..5651782
--- /dev/null
@@ -0,0 +1,64 @@
+#include-once
+Global $system = "Pegasus"
+Global $hWnd
+Global $hCounter
+$savedir = "O:\pegasus"
+$temperaturebefore = -10000
+
+Func GetCounter()
+   Return ControlGetText($hWnd, "", $hCounter)
+EndFunc   ;==>GetCounter
+
+Func StopRun()
+       ControlClick($hWnd, "", "[TEXT:Stop Run;CLASS:TButton]")
+EndFunc
+
+Func StartRun()
+       ControlClick($hWnd, "", "[TEXT:Start Run;CLASS:TButton]")
+EndFunc
+
+Func TestSystem()
+       WinWait("Debug")
+       ControlClick("Debug", "", "[TEXT:Messages Clear]")
+       Sleep(100)
+       ControlClick("Debug", "", "[TEXT:Board Testing]")
+       Sleep(2000)
+       $i = 0
+       Do
+               $text = WinGetText("[CLASS:TDebugFrm]", "")
+               $texthex = _StringToHex($text)
+               If ($texthex == "4D657373616765730A5072696E7420426F6172647320526567730A0D0A3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D0D0A426F6172642049643D302074657374207374617274696E67202E2E2E0D0A3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D0D0A0D0A53746F70206163717569736974696F6E202E2E2E0D0A41445220434F554E54455220412074657374696E67202E2E2E0D0A41445220434F554E54455220412030204572726F72730D0A52414D20412074657374696E67202E2E2E0D0A52414D20412030204572726F72730D0A52414D20422074657374696E67202E2E2E0D0A52414D20422030204572726F72730D0A52414D20432074657374696E67202E2E2E0D0A52414D20432030204572726F72730D0A52414D20442074657374696E67202E2E2E0D0A52414D20442030204572726F72730D0A0D0A3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D0D0A426F6172642049643D312074657374207374617274696E67202E2E2E0D0A3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D3D0D0A0D0A53746F70206163717569736974696F6E202E2E2E0D0A41445220434F554E54455220412074657374696E67202E2E2E0D0A41445220434F554E54455220412030204572726F72730D0A52414D20412074657374696E67202E2E2E0D0A52414D20412030204572726F72730D0A52414D20422074657374696E67202E2E2E0D0A52414D20422030204572726F72730D0A52414D20432074657374696E67202E2E2E0D0A52414D20432030204572726F72730D0A52414D20442074657374696E67202E2E2E0D0A52414D20442030204572726F72730D0A0A555342322042616E647769647468204D65617375726D656E740A426F6172642054657374696E670A536F66747761726520496E697469616C697A6174696F6E0A4D6573736167657320436C6561720A") Then
+                       ExitLoop
+               EndIf
+               Sleep(500)
+               $i = $i + 1
+               If ($i > 20) Then
+                       RefreshGUISendNtfct("USB Boards could be not OK! Please turn them on and off.")
+                       ;Run(@AutoItExe & ' /AutoIt3ExecuteScript "' & @ScriptDir & '\Functions\RefreshGUISendNtfct.au3" "' & $system & '" "' & $completelog & '" "USB Boards could be not OK! Please turn them on and off."')
+                       MsgBox(16, "Message", "USB Boards could be not OK! Please check the Debug output.")
+                       Return 1
+               EndIf
+       Until 0
+       If StringRegExp($text, "[1-9]+ Errors") Then ; double check, will remove it later
+               RefreshGUISendNtfct("USB Boards could be not OK! Please turn them on and off.")
+               ;Run(@AutoItExe & ' /AutoIt3ExecuteScript "' & @ScriptDir & '\Functions\RefreshGUISendNtfct.au3" "' & $system & '" "' & $completelog & '" "USB Boards could be not OK! Please turn them on and off."')
+               MsgBox(16, "Message", "USB Boards could be not OK! Please check the Debug output.")
+               Return 1
+       EndIf
+       WinClose("Debug")
+       WinWaitClose("Debug", 1000)
+       Return 0
+EndFunc
+
+Func GetAverage()
+       Return ControlGetText($hWnd, "", "[TEXT:DispAvg;CLASS:TEdit]")
+EndFunc
+
+Func Pegasus_GetVref()
+
+EndFunc   ;==>Mi34_GetVref
+
+Func Pegasus_SetVref($vref)
+
+EndFunc   ;==>Mi34_SetVref
+
diff --git a/bot/Mimosa_Autorun_Pegasus.au3 b/bot/Mimosa_Autorun_Pegasus.au3
new file mode 100755 (executable)
index 0000000..532bc23
--- /dev/null
@@ -0,0 +1,163 @@
+;
+; AutoIt Version: 3.0
+; Language:    English
+; Platform:       Win9x/NT
+; Author:         Benny Linnik (b.linnik@gsi.de)
+;
+; Script Function:
+;   Automatically runs the USB or PXI system with data gathered from an Excel sheet
+$configfile = @ScriptDir & "\config_Pegasus.ini"
+#include "Functions\Header.au3"
+#include "Chips\Pegasus.au3"
+#include "Functions\SetChipClock.au3"
+#include "Functions\CommonFunctions.au3"
+#include "Functions\Checkdata.au3"
+Global $vref = 650 ; Initial vref, will be adjusted during runtime
+
+;create virtual functions
+Func GetVref()
+       Return Call($chipversion & "_GetVref")
+EndFunc   ;==>GetVref
+Func SetVref($vref)
+       Call($chipversion & "_SetVref", $vref)
+EndFunc   ;==>SetVref
+Func _GetAverage($hWnd)
+       If $chipversion <> "Mi29" Then
+               Return GetAverage()
+       Else ; mimosa 29 ausnahme
+               Return Call($chipversion & "_GetAverage", $hWnd)
+       EndIf
+EndFunc   ;==>_GetAverage
+Func _TestSystem()
+       TestSystem()
+EndFunc   ;==>_TestSystem
+
+If (Not @error) Then ; Check again if everything went well
+       $totalruns = ReturnNumSuitRuns($chipversion, $chipinstalled, $radSource, "Pegasus")
+;      ReturnSuitRuns($chipversion, $chipinstalled, $radSource, "Pegasus",$totalruns)
+       
+       
+       If $totalruns > 0 Then ; Check if we retrieved any data
+               Local $answer = MsgBox(4, "Total runs", "Number of suitable runs found at the moment: " & $totalruns)
+               If $answer = 7 Then
+                       Exit
+                EndIf           
+               RefreshGUISendNtfct("Starting with " & $totalruns & " runs.")
+               Run(@AutoItExe & ' /AutoIt3ExecuteScript "' & @ScriptDir & '\Functions\RefreshGUI.au3" "' & $completelog & '"')
+               If ProcessExists("daq.exe") = True Then
+                       ProcessClose("daq.exe")
+                       ProcessWaitClose("daq.exe")
+               EndIf
+               Local $sTitle = "CMOS USB DAQ V3.5.8"
+               Run("C:\ccmos_daq\v3.5.7__5_boards\daq_v3.5.7__5_boards.bat", "C:\ccmos_daq\v3.5.7__5_boards\")
+               If _TestSystem() Then Exit
+               WinWait($sTitle)
+               $hWnd = WinGetHandle($sTitle)
+               $hTab = ControlGetHandle($hWnd, "", "TPageControl1")
+               $hCounter = ControlGetHandle($hWnd, "", "TEdit42")
+               $starttimetotal = _NowCalc()
+               $suitrun = ReturnSuitRun($chipversion, $chipinstalled, $radSource, "Pegasus")
+               While Not $suitrun[0] = "" ; Do runs, until no new run found
+                       #include "Functions\ReadAndSaveSQLParameters.au3"
+                       #include "Functions\WaitForTemperature.au3"
+                       _GUICtrlTab_SetCurFocus($hTab, 2) ; Go to "Run parameter" tab
+                       Sleep(200)
+                       ControlSetText($hWnd, "", "TEdit16", "")
+                       Sleep(100)
+                       ControlFocus($hWnd, "", "TEdit16")
+                       ControlSend($hWnd, "", "TEdit16", $savedir)
+                       Sleep(100)
+                       ControlSetText($hWnd, "", "TEdit15", "")
+                       Sleep(100)
+                       ControlFocus($hWnd, "", "TEdit15")
+                       ControlSend($hWnd, "", "TEdit15", $runnumber)
+                       Sleep(100)
+                       ControlSetText($hWnd, "", "TEdit14", "")
+                       Sleep(100)
+                       ControlFocus($hWnd, "", "TEdit14")
+                       ControlSend($hWnd, "", "TEdit14", $events)
+                       Sleep(100)
+                       ControlFocus($hWnd, "", "TEdit15")
+                       Sleep(1000)
+                       $starttime = _NowCalc()
+                       StartRun()
+                       Sleep(1000)
+                       If (WinExists("Avertissement")) Then
+                               RefreshGUISendNtfct("Skipped run " & $runnumber & " could overwrite data.")
+                               _ArrayAdd($skippedruns, $runnumber)
+                               $comment = "Skipped: Could overwrite data."
+                               #include "Functions/SaveToSQL.au3"
+                               Run(@AutoItExe & ' /AutoIt3ExecuteLine "MsgBox(48, ''Warning'', ''Skipped run ' & $runnumber & ', could overwrite data!'')"')
+                               ControlClick("Avertissement", "", "TButton1")
+                               ContinueLoop
+                       EndIf
+                       $avg = _GetAverage($hWnd)
+
+;~                     Sleep(200)
+;~                     $j = 0
+;~                     If ($avg > 2300 Or $avg < 1700) Then
+;~                             Do
+;~                                     ControlClick($hWnd, "", "[TEXT:Stop Run;CLASS:TButton]")
+;~                                     $vref = GetVref()
+;~                                     $diff = $avg - 2000
+;~                                     Select
+;~                                             Case Abs($diff) > 600
+;~                                                     $vref = $vref + SGN($diff) * 100
+;~                                             Case Else
+;~                                                     $vref = $vref + SGN($diff) * 50
+;~                                     EndSelect
+;~                                     If ($vref > 1000 Or $vref < 300) Then
+;~                                             StopRun()
+;~                                             RefreshGUISendNtfct("Skipped run " & $runnumber & ", vref value could not be set properly. Frequency: " & $clock)
+;~                                             _ArrayAdd($skippedruns, $runnumber)
+;~                                             Run(@AutoItExe & ' /AutoIt3ExecuteLine "MsgBox(48, ''Warning'', ''Skipped run ' & $runnumber & ', vref value needs to be too low (<300) or too high (>1000), please check manually!'')"')
+;~                                             FileDelete($savedir & "/" & $runnumber & "/*")
+;~                                             $vref = 650
+;~                                             ContinueLoop 2
+;~                                     EndIf
+;~                                     SetVref($vref)
+;~                                     _ProgramMi()
+;~                                     WinWait($hWnd)
+;~                                     ;_GUICtrlTab_SetCurFocus($hTab, 2) ; Go to "Run parameter" tab
+;~                                     StartRun()
+;~                                     WinWait("Avertissement")
+;~                                     ControlClick("Avertissement", "", "TButton2")
+;~                                     Sleep(1000)
+;~                                     $avg = ControlGetText($hWnd, "", "[TEXT:DispAvg;CLASS:TEdit]")
+;~                                     Sleep(100)
+;~                                     $j = $j + 1
+;~                                     If ($j > 10) Then
+;~                                             StopRun()
+;~                                             RefreshGUISendNtfct("Skipped run " & $runnumber & ", vref value could not be set properly. Clock: " & $clock & " Mhz")
+;~                                             _ArrayAdd($skippedruns, $runnumber)
+;~                                             Run(@AutoItExe & ' /AutoIt3ExecuteLine "MsgBox(48, ''Warning'', ''Skipped run ' & $runnumber & ', vref value needs to be too low (<300) or too high (>1000), please check manually!'')"')
+;~                                             FileDelete($savedir & "/" & $runnumber & "/*")
+;~                                             $vref = 650
+;~                                             ContinueLoop 2
+;~                                     EndIf
+;~                             Until ($avg < 2300 And $avg > 1700)
+;~                     EndIf
+                       #include "Functions\Watchrun.au3"
+                       _GUICtrlTab_SetCurFocus($hTab, 2) ; Go to "Run parameter" tab
+                       Sleep(100)
+                       StopRun()
+                       #include "Functions\SaveToSQL.au3"
+                       $totalrealruns = $totalrealruns + 1
+                       $completelog &= _NowCalc() & " Completed run " & $runnumber & ", " & $percentoverall & "% (" & $totalrealruns & "/" & $totalruns & ")" & @CRLF
+                       Run(@AutoItExe & ' /AutoIt3ExecuteScript "' & @ScriptDir & '\Functions\RefreshGUI.au3" "' & $completelog & '"')
+                       $suitrun = ReturnSuitRun($chipversion, $chipinstalled, $radSource, "Pegasus")
+                       ConsoleWrite($suitrun[0])
+               WEnd
+               #include "Functions\PrintSucessMessage.au3"
+       Else
+               MsgBox(16, "SQL Data Test", "No suitable runs found")
+       EndIf
+Else
+       MsgBox(16, "Server fail", "Error: Could not open connection to mySQL server.")
+EndIf
+Func SGN($i)
+       Return ($i > 0) - ($i < 0)
+EndFunc   ;==>SGN
+Func CheckValues($vref, $matrix, $runnumber, $events, $clock)
+       Return 0
+EndFunc   ;==>CheckValues