FSMainWindow.cpp 26.5 KB
Newer Older
Jérémie Dudouet's avatar
Jérémie Dudouet committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
#include "FSMainWindow.h"

#include <sys/stat.h>
#include <time.h>

/// Root includes

#include "TGMenu.h"
#include "TG3DLine.h"
#include "TGLabel.h"
#include "TGTextEntry.h"
#include "TStyle.h"
#include "TApplication.h"
#include "TGMsgBox.h"
#include "TFrame.h"
#include "TGTab.h"
#include "TGStatusBar.h"
#include "TGFileDialog.h"
#include "KeySymbols.h"
#include "TH1.h"
#include "TObjArray.h"
#include "TROOT.h"
#include "TCanvas.h"
#include "TSystem.h"
#include "TMath.h"

#include "FSTab.h"
#include "FSPad.h"
#include "FSShutter.h"

/// AGAPRO includes

33
FSMainWindow::FSMainWindow(const TGWindow *p, UInt_t w, UInt_t h, TString RunInit) :
Jérémie Dudouet's avatar
Jérémie Dudouet committed
34 35
    TGMainFrame(p, w, h)
{
36 37
    fLastRun = RunInit;
    if(fLastRun.Atoi()>0) INFO_MESS<<"Starting using run "<<fLastRun<<" as initializer"<<ENDL;
Jérémie Dudouet's avatar
Jérémie Dudouet committed
38 39 40
    INFO_MESS<<"Reading data from: "<<getenv("FSRawDataDir")<<ENDL;
    if(getenv("FSShiftTrackDir")) INFO_MESS<<"Shift track folder: "<<getenv("FSShiftTrackDir")<<ENDL;

Jérémie Dudouet's avatar
Jérémie Dudouet committed
41 42 43 44 45 46 47
    ReadLUT();
    ReadCal();
    InitParameters();
    LoadMainWindow();
    ReadHistograms();
    DoCalMode(0);

Jérémie Dudouet's avatar
Jérémie Dudouet committed
48
    map<Int_t, TH1D*>::iterator itr;
Jérémie Dudouet's avatar
Jérémie Dudouet committed
49
    for (itr = fListOfSpectra.begin(); itr != fListOfSpectra.end(); ++itr) {
Jérémie Dudouet's avatar
Jérémie Dudouet committed
50
        TH1D *hist = itr->second;
Jérémie Dudouet's avatar
Jérémie Dudouet committed
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
        fShutter->SetSpectrum(hist);
    }
}

FSMainWindow::~FSMainWindow()
{
}

void FSMainWindow::InitParameters()
{
    /// TSyle
    gStyle->SetPalette(1);
}

void FSMainWindow::LoadMainWindow()
{
    fMainFrame = new TGHorizontalFrame(this,GetWidth(),GetHeight());

    LoadMenuFile();
    LoadToolBar();

    LoadLeftSide();
    LoadRightSide();

    fVFLeft->SetWidth(GetWidth()*0.25);

    AddFrame(fMainFrame, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY) );

    // What to clean up in destructor
    SetCleanup(kDeepCleanup);

    // Set a name to the main frame
    const char* FIPPSSpy_version = (char*) FIPPSSpy_VERSION;

    SetWindowName(Form("FIPPSSpy v%s", FIPPSSpy_version ) );
    //    SetIconPixmap("AgaSpy.png");
    SetIconName("FIPPSSpy");

    MapSubwindows();
    Layout();
    MapWindow();
}

void FSMainWindow::LoadMenuFile()
{
    fFSMenuBar = new FSMenuBar(this, 1, 1, kHorizontalFrame);
    AddFrame(fFSMenuBar, new TGLayoutHints(kLHintsExpandX));

    TGHorizontal3DLine *fline = new TGHorizontal3DLine(this);
    AddFrame(fline,new TGLayoutHints(kLHintsExpandX));
}

void FSMainWindow::LoadToolBar()
{
    fFSToolBar = new FSToolBar(this);
    AddFrame(fFSToolBar, new TGLayoutHints(kLHintsExpandX));

    TGHorizontal3DLine *fline = new TGHorizontal3DLine(this);
    AddFrame(fline,new TGLayoutHints(kLHintsExpandX));
}

void FSMainWindow::LoadLeftSide()
{
    fVFLeft = new TGVerticalFrame(fMainFrame, 10, 10, kFixedWidth);
    fMainFrame->AddFrame(fVFLeft, new TGLayoutHints(kLHintsLeft | kLHintsExpandY));

    TGVerticalFrame *fV1 = new TGVerticalFrame(fVFLeft, 10, 50, kFixedHeight);
    fVFLeft->AddFrame(fV1, new TGLayoutHints(kLHintsTop | kLHintsExpandX | kLHintsExpandY));

    fMainTabL = new TGTab(fV1);
    fV1->AddFrame(fMainTabL, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsExpandX | kLHintsExpandY, 0, 4, 0, 0));
    fLetfTab = fMainTabL->AddTab("Visu Tools");

    fShutter = new FSShutter(fLetfTab, this);
    fLetfTab->AddFrame(fShutter, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsExpandX | kLHintsExpandY, 0, 4, 0, 0));
    fLetfTab->MapSubwindows();
    fLetfTab->MapWindow();

    /////////////////////
    ///*** SPLITER ***///
    /////////////////////

    fVSplitter = new TGVSplitter(fMainFrame,2,2);
    fVSplitter->SetFrame(fVFLeft, kTRUE);
    fMainFrame->AddFrame(fVSplitter, new TGLayoutHints(kLHintsLeft | kLHintsExpandY));
}

void FSMainWindow::LoadRightSide()
{
    fVFRight = new TGVerticalFrame(fMainFrame, 10, 10);
    fMainFrame->AddFrame(fVFRight, new TGLayoutHints(kLHintsExpandX | kLHintsExpandY));

    TGHorizontalFrame *fH3 = new TGHorizontalFrame(fVFRight, 10, 50, kFixedHeight);
    fVFRight->AddFrame(fH3, new TGLayoutHints(kLHintsTop | kLHintsExpandX | kLHintsExpandY));

    fListOfCanvases = new TList;

    fCanvasTab = new FSTab(fH3,this);
    fH3->AddFrame(fCanvasTab, new TGLayoutHints(kLHintsTop | kLHintsLeft | kLHintsExpandX | kLHintsExpandY, 0, 4, 0, 0));

    fCanvasTab->Connect("CloseTab(Int_t)", "FSTab", fCanvasTab, "RemoveTab(Int_t)");
    fCanvasTab->Connect("Selected(Int_t)", "FSTab", fCanvasTab, "cd()");

    // status bar
    Int_t parts[] = {20 , 20 , 20 , 20 ,20};
    fStatusBar = new TGStatusBar(fVFRight,50,10,kHorizontalFrame);
    fStatusBar->SetParts(parts,5);
    fStatusBar->Draw3DCorner(kFALSE);
    fVFRight->AddFrame(fStatusBar, new TGLayoutHints(kLHintsBottom | kLHintsLeft | kLHintsExpandX, 0, 0, 2, 0));

Jérémie Dudouet's avatar
Jérémie Dudouet committed
161
    //    NewTab();
Jérémie Dudouet's avatar
Jérémie Dudouet committed
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
}

void FSMainWindow::NewTab(TString name, Int_t npx, Int_t npy)
{
    gErrorIgnoreLevel = kFatal;

    TString TabName = name;

    if(TabName == "")
        TabName = Form("Tab_%d",fCanvasTab->GetNumberOfTabs());

    Bool_t IsInc = false;
    TObjArray *arr = TabName.Tokenize("_");
    if(((TString)arr->Last()->GetName()).IsDec())
        IsInc = true;

    if(IsInc==false && fCanvasTab->GetTabTab(TabName.Copy().Append("_1"))) {
        IsInc = true;
        TabName.Append("_1");
        delete arr;
        arr = TabName.Tokenize("_");
    }

    Int_t n;

    TString BaseName="";

    if(IsInc) {
        n = ((TString)arr->Last()->GetName()).Atoi();

        for(int i=0 ; i<arr->GetEntries()-1 ; i++)
            BaseName += Form("%s_",arr->At(i)->GetName());
    }

    while(fCanvasTab->GetTabTab(TabName) != nullptr) {
        if(IsInc) {
            TabName = BaseName.Copy().Append(Form("%d",n++));
        }
        else
            TabName.Append("_1");
    }

    delete arr;

    fActiveTab = fCanvasTab->AddTab(TabName, npx, npy);
    fCanvasTab->GetTabTab(TabName)->ShowClose();
    gErrorIgnoreLevel = kPrint;
}

Jérémie Dudouet's avatar
Jérémie Dudouet committed
211 212
void FSMainWindow::CloseWindow()
{
213 214
    UnmapWindow();
    DeleteWindow();//  launch a delete but after a short time like a thread.
Jérémie Dudouet's avatar
Jérémie Dudouet committed
215

216
    cout << " Bye Bye FIPPSSpy!" <<endl;
Jérémie Dudouet's avatar
Jérémie Dudouet committed
217

218 219
    gApplication->SetReturnFromRun(false);
    gApplication->Terminate(false);
Jérémie Dudouet's avatar
Jérémie Dudouet committed
220 221 222 223 224 225
}

TPad* FSMainWindow::GetSelectedPad()
{
    //return the current seletected pad
    TPad *Selected_pad = (TPad *) gROOT->GetSelectedPad();
Jérémie Dudouet's avatar
Jérémie Dudouet committed
226
    if (Selected_pad && !(Selected_pad->InheritsFrom("TPad"))) {
Jérémie Dudouet's avatar
Jérémie Dudouet committed
227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265
        int retval = 0;
        EMsgBoxIcon icontype = kMBIconStop;
        new TGMsgBox(gClient->GetRoot(), this, "Warning", "No seleted Pad", icontype, 1, &retval);
    }
    return Selected_pad;
}

Bool_t FSMainWindow::DoTab(TString TabName)
{
    if(fCanvasTab->GetTabTab(TabName)) {
        fCanvasTab->SetTab(TabName);
        fCanvasTab->cd();
        return true;
    }
    else return false;
}

void FSMainWindow::ZoomOnPad(FSPad* origin, bool same)
{
    if(DoTab("Zoom") == false)
        NewTab("Zoom",1,1);

    FSPad *pad = dynamic_cast<FSPad*>( GetSelectedPad() );
    pad->GetCanvas()->Connect("ProcessedEvent(Int_t, Int_t, Int_t, TObject*)", "FSMainWindow", this, "HandleZoom(Int_t,Int_t,Int_t, TObject*)");

    Int_t xmin = -1;
    Int_t xmax = -1;

    if(origin->GetHisto()==nullptr)
        return;

    xmin = origin->GetHisto()->GetXaxis()->GetFirst();
    xmax = origin->GetHisto()->GetXaxis()->GetLast();

    for(int i=0 ; i<origin->GetListOfPrimitives()->GetEntries() ; i++) {
        TObject *o = origin->GetListOfPrimitives()->At(i);
        if(same && o->InheritsFrom(TH1::Class()))
            o->Draw("hist same");
        else if(!same)
Jérémie Dudouet's avatar
Jérémie Dudouet committed
266
            o->Draw(((TString)o->GetDrawOption()).ReplaceAll("same",""));
Jérémie Dudouet's avatar
Jérémie Dudouet committed
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
    }

    pad->GetHisto()->GetXaxis()->SetRange(xmin,xmax);
    pad->GetFrame()->SetBit(kCannotPick);
}

void FSMainWindow::HandleZoom(Int_t EventType, Int_t EventX, Int_t EventY, TObject *selected)
{
    //        cout<<EventType<<" "<<EventX<<" "<<EventY<<" "<<selected<<endl;

    if(EventType==kArrowKeyRelease && fLastEventX != -1)
    {
        TList *listofids_in = new TList;
        listofids_in->SetOwner(false);
        TList *listofids_out = new TList;
        listofids_out->SetOwner(false);

        FSPad *pad = static_cast<FSPad*>(gPad);

        Int_t xmin = -1;
        Int_t xmax = -1;

        TH1 *hist = pad->GetHisto();

        if(hist==nullptr) return;

        xmin = hist->GetXaxis()->GetFirst();
        xmax = hist->GetXaxis()->GetLast();

        Bool_t left = (EventX<fLastEventX || EventY<fLastEventY);

        TH1 *hist2 = GetNextHist(hist,left);

        if(hist2) {
            hist2->Draw();
            hist2->GetXaxis()->SetRange(xmin,xmax);
            pad->Modified();
            pad->Update();
            pad->GetFrame()->SetBit(kCannotPick);
        }
    }

    fLastEventX = EventX;
    fLastEventY = EventY;
}

TH1 *FSMainWindow::GetNextHist(TH1 *hist_in, bool previous)
{
    CanvasTypes type = kUndef;
    Int_t Num=-1;
    fShutter->GetType(hist_in,type,Num);

    FSGlobalCanvas *c = static_cast<FSGlobalCanvas*>(fShutter->GetListOfCanvases()->FindObject(fNames[type]));

    if(c == nullptr) {
        WARN_MESS<<"Canvas "<<fNames[type]<<" not found"<<ENDL;
        return nullptr;
    }

    TH1 *histnext = nullptr;

    TList *list = c->GetListOfSpectra();
    Int_t idx = list->IndexOf(hist_in);
    if(previous && idx>0) idx--;
    else if(!previous && idx<(list->GetEntries()-1)) idx++;

    histnext = (TH1*)list->At(idx);
    return histnext;
}

void FSMainWindow::SaveTabAs()
{
    TCanvas *c = GetTabPage()->GetCurrentCanvas();

    const char* SaveAsTypes[] = {
        "PDF",          "*.pdf",
        //        "PostScript",   "*.ps",
        "Encapsulated PostScript", "*.eps",
        //        "SVG",          "*.svg",
        //        "TeX",          "*.tex",
        //        "GIF",          "*.gif",
        "ROOT macros",  "*.C",
        "ROOT files",   "*.root",
        //        "XML",          "*.xml",
        "PNG",          "*.png",
        "XPM",          "*.xpm",
        "JPEG",         "*.jpg",
        //        "TIFF",         "*.tiff",
        //        "XCF",          "*.xcf",
        //        "All files",    "*",
        0,              0
    };

    TString workdir = gSystem->WorkingDirectory();
    static TString dir(".");
    static Int_t typeidx = 0;
    static Bool_t overwr = kFALSE;
    TGFileInfo fi;
    fi.fFileTypes   = SaveAsTypes;
    fi.fIniDir      = StrDup(dir);
    fi.fFileTypeIdx = typeidx;
    fi.fOverwrite   = overwr;
    new TGFileDialog(gClient->GetDefaultRoot(), gClient->GetDefaultRoot(), kFDSave, &fi);
    gSystem->ChangeDirectory(workdir.Data());
    if (!fi.fFilename) return;
    TString fn = fi.fFilename;
    dir     = fi.fIniDir;
    typeidx = fi.fFileTypeIdx;
    overwr  = fi.fOverwrite;

    if(fn.EndsWith(".root")) {
        cout<<"needs to be implemented"<<endl;
    }
    else
        c->SaveAs(fn);

    fSavedAs = fn;
}

void FSMainWindow::ReadCal()
{
    if(getenv("FSCalFile") == nullptr) {
        ERR_MESS<<"Environment variable: FSCalFile needs to be define ==> ignored"<<ENDL;
        return;
    }

    cout<<endl;
    std::cout<<"\e[0;3;92m";
    cout<<"****************************"<<endl;
    cout<<"*     Reading Cal File     *"<<endl;
    cout<<"****************************"<<endl;
    cout<<"File: "<<getenv("FSCalFile")<<endl;
    cout<<ENDL;

    TString Buffer;
    string line;

    std::ifstream FileConf;
    FileConf.open(getenv("FSCalFile"), std::ifstream::in);

    if(!FileConf){
        ERR_MESS<<getenv("FSCalFile")<<" not found ==> Exit"<<ENDL;
        return;
    }

    Int_t linenb=0;
    Int_t Order = 0;

    while(FileConf){
        getline(FileConf,line);
        linenb++;
        Buffer = line;

        if(Buffer.BeginsWith("#") || Buffer.Length()==0 ) continue;

        TObjArray *loa=Buffer.ReplaceAll("\t"," ").Tokenize(" ");

        if(Order==0)
            Order = loa->GetEntries()-1;

        fCalOrder = Order;

        if((loa->GetEntries()-1) != Order) {
            WARN_MESS<<"Error in ECal.txt at line "<<linenb<<" ; bad number of parameters(" << (loa->GetEntries()-1)<< "instead of " << Order << ") ==> skipped"<<ENDL;
            delete loa;
            continue;
        }

        Int_t id = ((TString)Buffer = loa->At(0)->GetName()).Atoi();

437
        for(int i=1 ; i<loa->GetEntries() ; i++)
Jérémie Dudouet's avatar
Jérémie Dudouet committed
438
            fListOfCal[id][i-1] = ((TString)loa->At(i)->GetName()).Atof();
439 440

        if(fListOfCal[id][1] == 0.) fListOfCal[id][1] = 0.00001;
Jérémie Dudouet's avatar
Jérémie Dudouet committed
441 442 443

        delete loa;
    }
Jérémie Dudouet's avatar
Jérémie Dudouet committed
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504

    fCurrentCalFile = getenv("FSCalFile");
}

void FSMainWindow::GetLastShiftTrack()
{
    if(getenv("FSShiftTrackDir") == nullptr) return;

    TString FSShiftTrackDir = getenv("FSShiftTrackDir");

    Int_t Run=0;
    TString File="";
    TString FileName="";

    if(fLastShiftTrackRun==0) {
        TString Command = Form("ls -ltr %s/r_*.txt | grep ^- | tail -1 | awk '{ print $(NF) }'",FSShiftTrackDir.Data());
        File = GetStdoutFromCommand(Command.Data());

        TObjArray *arr = File.Tokenize("/");
        File = arr->Last()->GetName();
        delete arr;

        Run = File.Copy().ReplaceAll("r_","").ReplaceAll(".txt","").Atoi();
        FileName = Form("%s/%s",FSShiftTrackDir.Data(),File.Data());
        fLastShiftTrackRun = Run;
    }
    else {
        bool ok = true;
        Int_t Test=fLastShiftTrackRun;
        while(ok){
            Test++;
            FileName = Form("%s/r_%.06d.txt",FSShiftTrackDir.Data(),Test);
            ok = gSystem->IsFileInIncludePath(FileName);
        }
        Test=Test-1;
        fLastShiftTrackRun = Test;
        FileName = Form("%s/r_%.06d.txt",FSShiftTrackDir.Data(),fLastShiftTrackRun);
    }


    if(!gSystem->IsFileInIncludePath(FileName)) {
        WARN_MESS<<"Shift track file "<<FileName<<" not found"<<ENDL;
        return;
    }

    INFO_MESS << "Shift track of run "<< fLastShiftTrackRun <<" used  " << ENDL;

    TString Buffer;
    string line;

    std::ifstream FileConf;
    FileConf.open(FileName, std::ifstream::in);

    Int_t linenb=0;
    while(FileConf){
        getline(FileConf,line);
        linenb++;
        Buffer = line;
        if(Buffer.BeginsWith("#") || Buffer.Length()==0 ) continue;

        TObjArray *loa=Buffer.ReplaceAll("\t"," ").Tokenize(" ");
505 506 507 508 509 510 511 512 513 514 515 516 517 518

        if(loa->GetEntries() == 2) {
            fListOfShiftTrack[linenb-1][0] = ((TString)loa->At(0)->GetName()).Atof();
            fListOfShiftTrack[linenb-1][1] = ((TString)loa->At(1)->GetName()).Atof();

            if(fListOfShiftTrack[linenb-1][1] == 0.) fListOfShiftTrack[linenb-1][1] = 0.00001;
        }
        else if(loa->GetEntries() == 3) {
            Int_t Id = ((TString)loa->At(0)->GetName()).Atoi();
            fListOfShiftTrack[Id][0] = ((TString)loa->At(1)->GetName()).Atof();
            fListOfShiftTrack[Id][1] = ((TString)loa->At(2)->GetName()).Atof();

            if(fListOfShiftTrack[Id][1] == 0.) fListOfShiftTrack[Id][1] = 0.00001;
        }
Jérémie Dudouet's avatar
Jérémie Dudouet committed
519
        else {
Jérémie Dudouet's avatar
Jérémie Dudouet committed
520 521 522 523 524 525 526 527 528 529 530
            WARN_MESS<<"Error in "<< FileName << " at line "<<linenb<<" ; bad number of parameters ==> file ignored"<<ENDL;
            FileConf.close();
            return;
        }

        delete loa;
    }

    FileConf.close();

    fCurrentShiftTrackFile = FileName;
Jérémie Dudouet's avatar
Jérémie Dudouet committed
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
}

void FSMainWindow::ReadLUT()
{
    cout<<endl;
    std::cout<<"\e[0;3;92m";
    cout<<"****************************"<<endl;
    cout<<"*     Reading LUT File     *"<<endl;
    cout<<"****************************"<<endl;
    cout<<"File: "<<getenv("FSLUTFile")<<endl;
    cout<<ENDL;

    std::ifstream FileConf;
    FileConf.open(getenv("FSLUTFile"), std::ifstream::in);

    if(!FileConf){
        ERR_MESS<<getenv("FSLUTFile")<<" not found ==> Exit"<<ENDL;
        return;
    }

    TString Buffer;
    string line;

    Int_t linenb=0;
    while(FileConf){
        getline(FileConf,line);
        linenb++;
        Buffer = line;

        if(Buffer.BeginsWith("#") || Buffer.Length()==0 ) continue;

        TObjArray *loa=Buffer.ReplaceAll("\t"," ").Tokenize(" ");
        if(loa->GetEntries() != 5) {
            ERR_MESS<<"Error in LUT.txt at line "<<linenb<<" ; skipped"<<ENDL;
            delete loa;
            continue;
        }
        Int_t adcval = ((TString)loa->At(0)->GetName()).Atoi();
        Int_t globdetid = ((TString)loa->At(1)->GetName()).Atoi();
        Int_t detid = ((TString)loa->At(2)->GetName()).Atoi();
        Int_t type = ((TString)loa->At(3)->GetName()).Atoi();
        Int_t clover = ((TString)loa->At(4)->GetName()).Atoi();
        delete loa;

        if(globdetid<0) continue;

        DetDef *det = new DetDef;
        fDetectors[adcval] = det;
        det->Type = type;
        det->adc = adcval;
        det->Id = detid;
        det->GlobId = globdetid;

        for(int i=0 ; i<10 ; i++) {
            if(i==1) fListOfCal[globdetid][i] = 1.;
            else fListOfCal[globdetid][i] = 0.;
        }
Jérémie Dudouet's avatar
Jérémie Dudouet committed
588 589
        fListOfShiftTrack[globdetid][0] = 0.;
        fListOfShiftTrack[globdetid][1] = 1.;
Jérémie Dudouet's avatar
Jérémie Dudouet committed
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
    }

    INFO_MESS<<fDetectors.size()<<" entries Read in the LUT"<<ENDL;

    FileConf.close();

    return;
}

TString FSMainWindow::GetStdoutFromCommand(string cmd)
{
    string data;
    FILE * stream;
    const int max_buffer = 256;
    char buffer[max_buffer];
    cmd.append(" 2>&1");

    stream = popen(cmd.c_str(), "r");
    if (stream) {
        while (!feof(stream))
            if (fgets(buffer, max_buffer, stream) != NULL) data.append(buffer);
        pclose(stream);
    }
    TString FileName = data;
    FileName.ReplaceAll("\n","");

    return FileName;
}

void FSMainWindow::ReadHistograms()
{
621 622
    const char* FIPPSSpy_version = (char*) FIPPSSpy_VERSION;
    
Jérémie Dudouet's avatar
Jérémie Dudouet committed
623
    TString DataDir = getenv("FSRawDataDir");
624 625 626 627 628 629 630
    TString FileName;
    TString Run;
    
    if(fLastRun.Atoi()==0){
        TString Command = Form("ls -ltr %s | grep ^- | tail -1 | awk '{ print $(NF) }'",DataDir.Data());
        Run = GetStdoutFromCommand(Command.Data());
        Run.ReplaceAll(".lst","");
Jérémie Dudouet's avatar
Jérémie Dudouet committed
631
        FileName = Form("%s/%s",getenv("FSRawDataDir"),Run.Data());
632 633
    }
    else {
Jérémie Dudouet's avatar
Jérémie Dudouet committed
634 635 636 637 638 639 640
        bool ok = true;
        Int_t Test=fLastRun.Atoi();
        while(ok){
            Test++;
            FileName = Form("%s/%.06d",getenv("FSRawDataDir"),Test);
            ok = gSystem->IsFileInIncludePath(FileName);
        }
641 642
        if(getenv("FSModeLastRun")) Test=Test-2;
        else Test=Test-1;
Jérémie Dudouet's avatar
Jérémie Dudouet committed
643 644
        Run=Form("%.06d",Test);
        FileName = Form("%s/%s",getenv("FSRawDataDir"),Run.Data());
645 646
    }
    
Jérémie Dudouet's avatar
Jérémie Dudouet committed
647 648 649 650 651
    ifstream file(FileName.Data());
    if(!file){
        ERR_MESS<<FileName<<" not found"<<ENDL;
        return;
    }
Jérémie Dudouet's avatar
Jérémie Dudouet committed
652 653 654 655
    else {
        INFO_MESS<<"Reading run: "<<Run<<ENDL;
        INFO_MESS<<"File: "<<FileName<<ENDL;
    }
Jérémie Dudouet's avatar
Jérémie Dudouet committed
656 657 658

    struct stat result;
    if(stat(FileName.Data(), &result)==0) {
659
        TString date = Form("%s",asctime(localtime(&result.st_mtime)));
Jérémie Dudouet's avatar
Jérémie Dudouet committed
660 661
        date.ReplaceAll("\n","");
        INFO_MESS<<"Run  date: "<<date<<ENDL;
662
        fCurrentDate = date;
Jérémie Dudouet's avatar
Jérémie Dudouet committed
663 664 665 666
    }
    else {
        WARN_MESS<<"Unable to get file time modification"<<ENDL;
        fCurrentDate = "Undef";
Jérémie Dudouet's avatar
Jérémie Dudouet committed
667 668
        SetWindowName(Form("FIPPSSpy v%s: Run %s - %s !! Disk not Available !!", FIPPSSpy_version,Run.Data(),fCurrentDate.Data()));
        return;
Jérémie Dudouet's avatar
Jérémie Dudouet committed
669 670
    }

Jérémie Dudouet's avatar
Jérémie Dudouet committed
671 672 673 674 675 676 677
    // Check Last ShiftTrackFile

    GetLastShiftTrack();

    // Reset spectra

    map<Int_t, TH1D*>::iterator itr;
Jérémie Dudouet's avatar
Jérémie Dudouet committed
678
    for (itr = fListOfSpectra.begin(); itr != fListOfSpectra.end(); ++itr) {
Jérémie Dudouet's avatar
Jérémie Dudouet committed
679
        TH1D *h = itr->second;
Jérémie Dudouet's avatar
Jérémie Dudouet committed
680 681 682 683 684 685 686
        h->Reset();
    }

    TString Buffer;
    string line;
    TObjArray *arr;

Jérémie Dudouet's avatar
Jérémie Dudouet committed
687 688
    Int_t test=0;
    Bool_t ok=false;
Jérémie Dudouet's avatar
Jérémie Dudouet committed
689
    while(ok == false && test<200) {
Jérémie Dudouet's avatar
Jérémie Dudouet committed
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711

        if(!file) file.open(FileName.Data());
        Int_t NHistRead = 0;

        getline(file,line);getline(file,line);getline(file,line);
        Buffer=line;
        Buffer.ReplaceAll("FIPPintern    ","");
        while(Buffer.EndsWith(" ")) Buffer.Remove(Buffer.Length()-1);

        while(file) {
            getline(file,line);Buffer=line;
            while(!Buffer.BeginsWith("SSS") && file) {getline(file,line);Buffer=line;}
            if(!file) break;
            getline(file,line);Buffer=line;
            arr = Buffer.ReplaceAll("\t"," ").Tokenize(" ");
            Int_t adc = ((TString)arr->First()->GetName()).Atoi()-1;
            delete arr;
            if(fDetectors.count(adc)==0) continue;

            getline(file,line);getline(file,line);Buffer=line;
            arr = Buffer.Tokenize(" ");
            Int_t NBins = ((TString)arr->First()->GetName()).Atoi();
Jérémie Dudouet's avatar
Jérémie Dudouet committed
712 713
            Double_t Array[NBins+2];
            Double_t Val;
Jérémie Dudouet's avatar
Jérémie Dudouet committed
714 715 716 717 718 719 720 721 722 723 724 725
            delete arr;
            Array[0] = 0;
            Array[NBins+1]=0;
            for(int i=0 ; i<NBins ; i++) {
                file>>Val; Array[i+1] = Val;
            }
            Int_t id = fDetectors[adc]->GlobId;
            Int_t type=CanvasTypes::kUndef;
            Int_t DetNum=-1;
            DetDef *det = fDetectors[adc];
            if(det->IsFIPPS()) {
                type = CanvasTypes::kFIPPS;
Jérémie Dudouet's avatar
Jérémie Dudouet committed
726 727
                DetNum = det->Id;
            }
Jérémie Dudouet's avatar
Jérémie Dudouet committed
728 729 730
            else if(det->IsIFIN()) {
                type = CanvasTypes::kIFIN;
                DetNum = det->Id;
Jérémie Dudouet's avatar
Jérémie Dudouet committed
731
            }
Jérémie Dudouet's avatar
Jérémie Dudouet committed
732 733 734
            else if(det->IsTAG()) {
                type = CanvasTypes::kTAG;
                DetNum = det->Id;
Jérémie Dudouet's avatar
Jérémie Dudouet committed
735
            }
Jérémie Dudouet's avatar
Jérémie Dudouet committed
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
            else if(det->IsAC()) {
                if(det->Type == 3) {
                    type = CanvasTypes::kIFIN_AC;
                    DetNum = det->Id;
                }
                else if(det->Type == 5) {
                    type = CanvasTypes::kFIPPS_ACB;
                    DetNum = det->Id/3;
                }
                else if(det->Type == 6) {
                    type = CanvasTypes::kFIPPS_ACF;
                    DetNum = det->Id/3;
                }
                else if(det->Type == 7) {
                    type = CanvasTypes::kFIPPS_ACS;
                    DetNum = det->Id/3;
                }
Jérémie Dudouet's avatar
Jérémie Dudouet committed
753
            }
Jérémie Dudouet's avatar
Jérémie Dudouet committed
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769
            TString HistName = Form("ADC%d_%s_%d",adc,fNames[type].Data(),DetNum);

            if(fListOfSpectra.count(id)==0) {
                if(type == CanvasTypes::kTAG) {
                    fListOfSpectra[id] = new TH1D(HistName,HistName,NBins/2,0,NBins);
                }
                else
                    fListOfSpectra[id] = new TH1D(HistName,HistName,NBins,0,NBins);
            }

            if(type == CanvasTypes::kTAG)
                for(int ibin=1 ; ibin<NBins/2 ; ibin++) {
                    fListOfSpectra[id]->SetBinContent(ibin,Array[ibin]);
                }
            else
                memcpy(((TH1D*)fListOfSpectra[id])->fArray,Array,sizeof(Array));
Jérémie Dudouet's avatar
Jérémie Dudouet committed
770

Jérémie Dudouet's avatar
Jérémie Dudouet committed
771 772 773 774 775 776
            fListOfSpectra[id]->SetEntries(fListOfSpectra[id]->Integral());
            NHistRead++;
        }
        if(NHistRead == fDetectors.size()) ok = true;
        else {
            test++;
Jérémie Dudouet's avatar
Jérémie Dudouet committed
777
            WARN_MESS<<"Unable to read the full file: read "<<NHistRead<<" histograms, wainting:"<<fDetectors.size()<<", retry num"<<test<<ENDL;
778
            //            sleep(1);
Jérémie Dudouet's avatar
Jérémie Dudouet committed
779 780
        }
        file.close();
Jérémie Dudouet's avatar
Jérémie Dudouet committed
781
    }
782
    INFO_MESS << fDetectors.size() << "read spectra ==> Done" << ENDL;
783 784 785 786
    
    fLastRun = Run;
    
    SetWindowName(Form("FIPPSSpy v%s: Run %s - %s", FIPPSSpy_version,fLastRun.Data(),fCurrentDate.Data()));
Jérémie Dudouet's avatar
Jérémie Dudouet committed
787 788 789 790
}

void FSMainWindow::DoCalMode(Bool_t on)
{
Jérémie Dudouet's avatar
Jérémie Dudouet committed
791
    map<Int_t, TH1D*>::iterator itr;
Jérémie Dudouet's avatar
Jérémie Dudouet committed
792
    for (itr = fListOfSpectra.begin(); itr != fListOfSpectra.end(); ++itr) {
Jérémie Dudouet's avatar
Jérémie Dudouet committed
793
        TH1D *h = itr->second;
Jérémie Dudouet's avatar
Jérémie Dudouet committed
794 795 796 797 798 799 800 801 802 803 804 805

        if(on) {
            h->GetXaxis()->SetTitle("Energy (keV)");
            h->GetYaxis()->SetTitle(Form("Counts (1 Chanel/bin)"));
        }
        else {
            h->GetXaxis()->SetTitle("Ampliture (Chanel)");
            h->GetYaxis()->SetTitle(Form("Counts (1 Chanel/bin)"));
        }

        Double_t Bins[h->GetNbinsX()+1];
        for(int i=0 ;i<=h->GetNbinsX() ; i++) {
Jérémie Dudouet's avatar
Jérémie Dudouet committed
806
            if(on == false) Bins[i] = i*h->GetBinWidth(1);
Jérémie Dudouet's avatar
Jérémie Dudouet committed
807
            else {
Jérémie Dudouet's avatar
Jérémie Dudouet committed
808 809
                Double_t ERaw = fListOfShiftTrack[itr->first][0] + fListOfShiftTrack[itr->first][1]*((Double_t)i*h->GetBinWidth(1));
                Double_t ECal = 0;
Jérémie Dudouet's avatar
Jérémie Dudouet committed
810
                for(int j=0 ; j<fCalOrder ; j++)
Jérémie Dudouet's avatar
Jérémie Dudouet committed
811 812
                    ECal += fListOfCal[itr->first][j]*TMath::Power(ERaw,j);
                Bins[i] = ECal;
Jérémie Dudouet's avatar
Jérémie Dudouet committed
813 814 815 816 817 818 819 820 821
            }
        }

        h->GetXaxis()->Set(h->GetNbinsX(),Bins);
    }

    fCanvasTab->RefreshTab();
}

Jérémie Dudouet's avatar
Jérémie Dudouet committed
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
void FSMainWindow::PrintShiftTrack()
{
    if(fFSToolBar->IsFullMode()) {
        INFO_MESS << "Shift track values of run: " << fLastShiftTrackRun << endl;
        cout<<"File: "<<fCurrentShiftTrackFile<<endl;
        cout<<left<<setw(10)<<"Det id"<<setw(15)<<"Offset"<<setw(15)<<"Gain"<<endl;
        map<Int_t, Double_t[2]>::iterator itr;
        for (itr = fListOfShiftTrack.begin(); itr != fListOfShiftTrack.end(); ++itr) {
            cout<<left<<setw(10)<<itr->first<<setw(15)<<itr->second[0]<<setw(15)<<itr->second[1]<<endl;
        }
        cout<<ENDL;
    }
    else {
        FSPad *pad = dynamic_cast<FSPad*>( GetSelectedPad() );
        if(pad == nullptr) return;
        TH1 *h = pad->GetHisto();
        if(h==nullptr) return;
        TString Name = h->GetName();
        TObjArray *arr = Name.Tokenize("_");
        Name=arr->First()->GetName();
        delete arr;
        Name.ReplaceAll("ADC","");
        Int_t adc = Name.Atoi();
        DetDef *det = fDetectors[adc];
        Int_t Id = det->GlobId;
        INFO_MESS << "Shift track values for Det: "<<Id<<" of run: " << fLastShiftTrackRun << endl;
        cout<<"File: "<<fCurrentShiftTrackFile<<endl;
        cout<<left<<setw(10)<<"Det id"<<setw(15)<<"Offset"<<setw(15)<<"Gain"<<endl;
        cout<<left<<setw(10)<<Id<<setw(15)<<fListOfShiftTrack[Id][0]<<setw(15)<<fListOfShiftTrack[Id][1]<<endl;
        cout<<ENDL;
    }
}


void FSMainWindow::PrintCal()
{
    if(fFSToolBar->IsFullMode()) {
        INFO_MESS << "Calibration values:"<< endl;
        cout<<"File: "<<fCurrentCalFile<<endl;
        cout<<left<<setw(10)<<"Det id";
        for(int i=0 ; i<fCalOrder ; i++) cout<<setw(15)<<Form("a%d",i);
        cout<<endl;
        map<Int_t, Double_t[10]>::iterator itr;
        for (itr = fListOfCal.begin(); itr != fListOfCal.end(); ++itr) {
            cout<<left<<setw(10)<<itr->first;
            for(int i=0 ; i<fCalOrder ; i++) cout<<setw(15)<<fListOfCal[itr->first][i];
            cout<<endl;
        }
        cout<<ENDL;
    }
    else {
        FSPad *pad = dynamic_cast<FSPad*>( GetSelectedPad() );
        if(pad == nullptr) return;
        TH1 *h = pad->GetHisto();
        if(h==nullptr) return;
        TString Name = h->GetName();
        TObjArray *arr = Name.Tokenize("_");
        Name=arr->First()->GetName();
        delete arr;
        Name.ReplaceAll("ADC","");
        Int_t adc = Name.Atoi();
        DetDef *det = fDetectors[adc];
        Int_t Id = det->GlobId;
        INFO_MESS << "Calibration values:"<< endl;
        cout<<"File: "<<fCurrentCalFile<<endl;
        cout<<left<<setw(10)<<"Det id";
        for(int i=0 ; i<fCalOrder ; i++) cout<<setw(15)<<Form("a%d",i);
        cout<<endl;
        cout<<left<<setw(10)<<Id;
        for(int i=0 ; i<fCalOrder ; i++) cout<<setw(15)<<fListOfCal[Id][i];
        cout<<endl;
        cout<<ENDL;
    }
}

Jérémie Dudouet's avatar
Jérémie Dudouet committed
897
ClassImp( FSMainWindow)