source: tags/Mars-V0.10.2/datacenter/macros/buildsequenceentries.C

Last change on this file was 8065, checked in by tbretz, 18 years ago
*** empty log message ***
File size: 37.6 KB
Line 
1/* ======================================================================== *\
2!
3! *
4! * This file is part of MARS, the MAGIC Analysis and Reconstruction
5! * Software. It is distributed to you in the hope that it can be a useful
6! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
7! * It is distributed WITHOUT ANY WARRANTY.
8! *
9! * Permission to use, copy, modify and distribute this software and its
10! * documentation for any purpose is hereby granted without fee,
11! * provided that the above copyright notice appear in all copies and
12! * that both that copyright notice and this permission notice appear
13! * in supporting documentation. It is provided "as is" without express
14! * or implied warranty.
15! *
16!
17!
18! Author(s): Thomas Bretz, 08/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
19! Author(s): Daniela Dorner, 08/2004 <mailto:dorner@astro.uni-wuerzburg.de>
20!
21! Copyright: MAGIC Software Development, 2000-2006
22!
23!
24\* ======================================================================== */
25
26/////////////////////////////////////////////////////////////////////////////
27//
28// buildsequenceentries.C
29// ======================
30//
31// to group the runs of one night into sequences, this marco:
32// - reads the runinformation of one night from the database
33// - group the runs into sets of following runs with the same conditions
34// - groups the runs in this sets to sequences such that each run belongs
35// to the nearest (in time) calibration run
36// - check if the runs with the same runtype have the same calibration script
37// and the same trigger tables
38// if sequence is okay:
39// - check if in the range of the runnumbers of this sequence other sequences
40// exist in the database
41// if there are no sequences, insert the new sequence, else:
42// - delete overlaping sequences
43// if there's only one sequence in the same runnumber range:
44// - check if the new and the old sequence are identical
45// if they are identical, do nothing, if not, delete the old sequence and
46// insert the new one
47//
48// remark: deleting sequences includes the following steps:
49// - delete entries from the tables Sequences, SequenceProcessStatus,
50// Calibration and Star
51// - updating the sequence number (fSequenceFirst) in the table RunData
52// - remove the Sequence File, the calibrated data and the image files from
53// the disk
54//
55// the macro can be executed either for all nights or for one single night
56// .x buildsequenceentries.C+( "datapath", "sequpath", Bool_t dummy=kTRUE)
57// .x buildsequenceentries.C+( "night", "datapath", "sequpath")
58//
59// the Bool_t dummy:
60// kTRUE: dummy-mode, i.e. nothing is inserted into the database, but the
61// commands, that would be executed are returned
62// kFALSE: the information is inserted into the database and the files of
63// removed sequences is deleted
64// be careful with this option - for tests use always kTRUE
65//
66// TString datapath, TString sequpath:
67// datapath: path, where the processed data is stored in the datacenter
68// sequpath: path, where the sequence files are stored in the datacenter
69// the datapath (standard: /magic/data/) and the sequencepath (standard:
70// /magic/sequences) have to be given, that the sequence file, the
71// calibrated data and the star files can be removed, when an old sequence
72// has to be removed from the database
73//
74// If nothing failes 1 is returned. In the case of an error 2 and if
75// there's no connection to the database 0 is returned.
76// This is needed for the scripts that execute the macro.
77//
78/////////////////////////////////////////////////////////////////////////////
79#include <iostream>
80#include <iomanip>
81#include <fstream>
82
83#include <TSQLRow.h>
84#include <TSQLResult.h>
85
86#include <TEnv.h>
87#include <TMap.h>
88#include <TMath.h>
89#include <TExMap.h>
90#include <TArrayI.h>
91#include <TArrayD.h>
92#include <TPRegexp.h>
93#include <TSystem.h>
94#include <TObjString.h>
95#include <TObjArray.h>
96
97#include "MTime.h"
98#include "MDirIter.h"
99
100#include "MSQLMagic.h"
101
102using namespace std;
103
104
105class Rule : public TObject
106{
107private:
108 TPRegexp fRegexp;
109
110 UInt_t fMin;
111 UInt_t fMax;
112
113public:
114 Rule(const char *regexp, UInt_t min=0, UInt_t max=(UInt_t)-1) :
115 fRegexp(Form("^%s", regexp)), fMin(min), fMax(max)
116 {
117 }
118
119 Rule(TObjArray &arr) :
120 fRegexp(arr.GetEntries()>0?Form("^%s", arr[0]->GetName()):""),
121 fMin(0), fMax((UInt_t)-1)
122 {
123 if (arr.GetEntries()>1)
124 fMin = atoi(arr[1]->GetName());
125 if (arr.GetEntries()>2)
126 fMax = atoi(arr[2]->GetName());
127
128 //cout << "Regexp: " << (arr.GetEntries()>0?Form("^%s", arr[0]->GetName()):"") << " " << fMin << " " << fMax << endl;
129 }
130
131 Ssiz_t Match(const TString &str, Int_t idx, Int_t run=-1)
132 {
133 if (!IsValid(run))
134 return 0;
135
136 TString mods;
137 TArrayI pos;
138 fRegexp.Match(str.Data()+idx, mods, 0, str.Length()*10, &pos);
139
140 return pos.GetSize()<2 ? 0 : pos[1]-pos[0];
141 }
142
143 Bool_t IsValid(UInt_t run) const { return run<0 || (run>=fMin && run<=fMax); }
144 ClassDef(Rule, 0)
145};
146ClassImp(Rule);
147
148class CheckMatch : public TObject
149{
150private:
151 TPRegexp fRunType1;
152 TPRegexp fRunType2;
153
154 TPRegexp fRegexp1;
155 TPRegexp fRegexp2;
156
157 UInt_t fMin;
158 UInt_t fMax;
159
160 void Init(const TObjArray &arr, Int_t idx=0)
161 {
162 const Int_t n = arr.GetEntries();
163
164 const Bool_t isminus = n>idx && TString(arr[idx]->GetName())=="-";
165
166 for (int i=0; i<n-idx; i++)
167 {
168 //cout << arr[i+idx]->GetName() << " ";
169
170 TString str(arr[i+idx]->GetName());
171 if (str=="*")
172 str = ".*";
173
174 switch (isminus && i>1 ? i+1 : i)
175 {
176 case 0: fRunType1 = TPRegexp(Form(isminus?"-":"^%s$", str.Data())); break;
177 case 1: fRunType2 = TPRegexp(Form("^%s$", str.Data())); break;
178 case 2: fRegexp1 = TPRegexp(Form("^%s$", str.Data())); break;
179 case 3: fRegexp2 = TPRegexp(Form("^%s$", str.Data())); break;
180 case 4: fMin = str.Atoi(); break;
181 case 5: fMax = str.Atoi(); break;
182 }
183 }
184 //cout << endl;
185 }
186
187public:
188 CheckMatch() : fRunType1(""), fRunType2(""), fRegexp1(""), fRegexp2("") {}
189
190 CheckMatch(const TString &txt) : fRunType1(""), fRunType2(""), fRegexp1(""), fRegexp2(""), fMin(0), fMax((UInt_t)-1)
191 {
192 TObjArray *arr = txt.Tokenize(" ");
193 Init(*arr);
194 delete arr;
195 }
196
197 CheckMatch(TObjArray &arr, Int_t idx=0) : fRunType1(""), fRunType2(""), fRegexp1(""), fRegexp2(""), fMin(0), fMax((UInt_t)-1)
198 {
199 Init(arr, idx);
200 }
201
202 CheckMatch(const char *from, const char *to, Int_t min=0, Int_t max=-1)
203 : fRunType1(".*"), fRunType2(".*"), fRegexp1(Form("^%s$", from)), fRegexp2(Form("^%s$", to)), fMin(min), fMax(max)
204 {
205 }
206
207 Int_t Matches(const TString &rt1, const TString &rt2, const TString &lc1, const TString &lc2, UInt_t run=0)
208 {
209 if (run>0)
210 {
211 if (run<fMin || run>fMax)
212 return kFALSE;
213 }
214
215 const TString test("X-"); // FIXME:STUPID!
216
217 //if (test.Index(fRunType2)==1)
218 // return -(!rt1(fRunType1).IsNull() && !lc1(fRegexp1).IsNull());
219
220 if (test.Index(fRunType1,0)==1)
221 return -(!rt2(fRunType2).IsNull() && !lc2(fRegexp2).IsNull());
222
223 return !rt1(fRunType1).IsNull() && !rt2(fRunType2).IsNull() && !lc1(fRegexp1).IsNull() && !lc2(fRegexp2).IsNull();
224 }
225 ClassDef(CheckMatch,0)
226};
227ClassImp(CheckMatch);
228
229class CheckList : public TList
230{
231public:
232 CheckList() { SetOwner(); }
233 Int_t Matches(const TString &rt1, const TString &rt2, const TString &lc1, const TString &lc2, Int_t run=-1) const
234 {
235 TIter Next(this);
236
237 CheckMatch *check = 0;
238
239 while ((check=(CheckMatch*)Next()))
240 {
241 const Int_t rc = check->Matches(rt1, rt2, lc1, lc2, run);
242 if (rc)
243 return rc;
244 }
245
246 return kFALSE;
247 }
248 ClassDef(CheckList,0)
249};
250ClassImp(CheckList);
251
252class SequenceBuild : public MSQLMagic
253{
254private:
255 TString fPathRawData;
256 TString fPathSequences;
257
258 TMap fMap;
259 TList fListRegexp;
260
261 Int_t CheckTransition(TSQLResult &res, const TString *keys, TSQLRow &row, Int_t i)
262 {
263 // Get the name of the column from result table
264 const TString key = res.GetFieldName(i);
265
266 // Get the list with the allowed attributed from the map
267 CheckList *list = dynamic_cast<CheckList*>(fMap.GetValue(key));
268 if (!list)
269 return kFALSE;
270
271 // Check whether the current run (row[0]) with the current attribute
272 // (row[i]) and the current run-type (row[1]) matches the attribute
273 // of the last run (keys[i] with run-type row[i])
274 return list->Matches(keys[1], row[1], keys[i], row[i], atoi(row[0]));
275 }
276
277 Bool_t InsertSequence(Int_t from, Int_t to)
278 {
279 cout << " - Inserting Sequence into database." << endl;
280
281 // ========== Request number of events ==========
282
283 const TString runtime =
284 "SUM(if(TIME_TO_SEC(fRunStop)-TIME_TO_SEC(fRunStart)<0,"
285 " TIME_TO_SEC(fRunStop)-TIME_TO_SEC(fRunStart)+24*60*60,"
286 " TIME_TO_SEC(fRunStop)-TIME_TO_SEC(fRunStart))), ";
287
288 const TString where = Form("(fRunNumber BETWEEN %d AND %d) AND fExcludedFDAKEY=1",
289 from, to);
290
291 TString query;
292 query = "SELECT SUM(fNumEvents), ";
293 query += runtime;
294 query += " MIN(fZenithDistance), MAX(fZenithDistance), ";
295 query += " MIN(fAzimuth), MAX(fAzimuth), ";
296 query += " MIN(fRunStart), MAX(fRunStop), ";
297 query += " ELT(MAX(FIELD(fLightConditionsKEY, 1, 2, 7, 5, 8)), 1, 2, 7, 5, 8) ";
298 query += " FROM RunData WHERE ";
299 query += where;
300 query += " AND fRunTypeKEY=2";
301
302 TSQLResult *res = Query(query);
303 if (!res)
304 return kFALSE;
305
306 TSQLRow *row = res->Next();
307 if (!row || res->GetFieldCount()!=9)
308 {
309 cout << "ERROR - Wrong result from query: " << query << endl;
310 return kFALSE;
311 }
312
313 const TString nevts = (*row)[0];
314 const TString secs = (*row)[1];
315 const TString zdmin = (*row)[2];
316 const TString zdmax = (*row)[3];
317 const TString azmin = (*row)[4];
318 const TString azmax = (*row)[5];
319 const TString start = (*row)[6];
320 const TString stop = (*row)[7];
321 const TString light = (*row)[8];
322
323 delete res;
324
325 const TString elts = GetELTSource(where);
326 if (elts.IsNull())
327 return kFALSE;
328
329 const TString eltp = GetELTProject(where);
330 if (eltp.IsNull())
331 return kFALSE;
332
333 // ========== Request data of sequence ==========
334 query = "SELECT ";
335 query += elts;
336 query += ", ";
337 query += eltp;
338 query += ", fL1TriggerTableKEY, fL2TriggerTableKEY,"
339 " fHvSettingsKEY, fDiscriminatorThresholdTableKEY,"
340 " fTriggerDelayTableKEY, fObservationModeKEY "
341 " FROM RunData WHERE fRunTypeKEY=2 AND ";
342 query += where;
343 query += " LIMIT 1";
344
345 res = Query(query);
346 if (!res)
347 return kFALSE;
348
349 row = res->Next();
350 if (!row || res->GetFieldCount()!=8)
351 {
352 cout << "ERROR - No result from query: " << query << endl;
353 return kFALSE;
354 }
355
356 const TString set = Form("fSequenceFirst=%d ", from);
357
358 TString query1;
359 query1 += set;
360 query1 += Form(",fSequenceLast=%d,", to);
361 query1 += Form(" fSourceKEY=%s,", (*row)[0]);
362 query1 += Form(" fProjectKEY=%s,", (*row)[1]);
363 query1 += Form(" fNumEvents=%s,", nevts.Data());
364 query1 += Form(" fRunTime=%s,", secs.Data());
365 query1 += Form(" fRunStart=\"%s\",", start.Data());
366 query1 += Form(" fRunStop=\"%s\",", stop.Data());
367 query1 += Form(" fZenithDistanceMin=%s,", zdmin.Data());
368 query1 += Form(" fZenithDistanceMax=%s,", zdmax.Data());
369 query1 += Form(" fAzimuthMin=%s,", azmin.Data());
370 query1 += Form(" fAzimuthMax=%s,", azmax.Data());
371 query1 += Form(" fL1TriggerTableKEY=%s,", (*row)[2]);
372 query1 += Form(" fL2TriggerTableKEY=%s,", (*row)[3]);
373 query1 += Form(" fHvSettingsKEY=%s,", (*row)[4]);
374 query1 += Form(" fDiscriminatorThresholdTableKEY=%s,", (*row)[5]);
375 query1 += Form(" fTriggerDelayTableKEY=%s,", (*row)[6]);
376 query1 += Form(" fLightConditionsKEY=%s,", light.Data());
377 query1 += Form(" fObservationModeKEY=%s, ", (*row)[7]);
378 query1 += "fManuallyChangedKEY=1";
379
380 delete res;
381
382 const TString where2 = Form("(fRunTypeKEY BETWEEN 2 AND 4) AND %s",
383 where.Data());
384
385 if (!Insert("Sequences", query1))
386 {
387 cout << "ERROR - Could not insert Sequence into Sequences." << endl;
388 return kFALSE;
389 }
390
391 if (!Update("RunData", set, where))
392 {
393 cout << "ERROR - Could not update RunData." << endl;
394 return kFALSE;
395 }
396
397 if (!Insert("SequenceProcessStatus", set))
398 {
399 cout << "ERROR - Could not insert Sequence into SequenceProcessStatus." << endl;
400 return kFALSE;
401 }
402
403 return kTRUE;
404 }
405
406 Bool_t DeleteSequence(Int_t sequ)
407 {
408 if (fPathRawData.IsNull() || fPathSequences.IsNull())
409 {
410 cout << " + Deletion " << sequ << " skipped due to missing path." << endl;
411 return kTRUE;
412 }
413
414 //queries to delete information from the database
415 const TString query(Form("fSequenceFirst=%d", sequ));
416
417 //commands to delete files from the disk
418 const TString fname(Form("%s/%04d/sequence%08d.txt", fPathSequences.Data(),sequ/10000, sequ));
419 const TString cmd1(Form("rm -rf %s/callisto/%04d/%08d/", fPathRawData.Data(), sequ/10000, sequ));
420 const TString cmd2(Form("rm -rf %s/star/%04d/%08d/", fPathRawData.Data(), sequ/10000, sequ));
421
422 if (!Delete("Calibration", query))
423 return 2;
424
425 if (!Delete("Star", query))
426 return 2;
427
428 if (!Delete("SequenceProcessStatus", query))
429 return 2;
430
431 if (!Delete("Sequences", query))
432 return 2;
433
434 if (!Update("RunData", "fSequenceFirst=0", query))
435 return 2;
436
437 if (IsDummy())
438 {
439 cout << " + unlink " << fname << endl;
440 cout << " + " << cmd1 << endl;
441 cout << " + " << cmd2 << endl;
442 return kTRUE;
443 }
444
445 gSystem->Unlink(fname);
446
447 gSystem->Exec(cmd1);
448 gSystem->Exec(cmd2);
449
450 return kTRUE;
451 }
452
453 Int_t CheckSequence(Int_t runstart, Int_t runstop)
454 {
455 const char *fmt1 = "SELECT fRunNumber FROM RunData WHERE";
456 const char *fmt2 = "AND fExcludedFDAKEY=1 AND (fRunTypeKEY BETWEEN 2 AND 4) ORDER BY fRunNumber";
457
458 const TString query1 = Form("%s fSequenceFirst=%d %s", fmt1, runstart, fmt2);
459 const TString query2 = Form("%s fRunNumber BETWEEN %d AND %d %s", fmt1, runstart, runstop, fmt2);
460
461 TSQLResult *res1 = Query(query1);
462 if (!res1)
463 return 2;
464
465 TSQLResult *res2 = Query(query2);
466 if (!res2)
467 {
468 delete res1;
469 return 2;
470 }
471
472 while (1)
473 {
474 TSQLRow *row1 = res1->Next();
475 TSQLRow *row2 = res2->Next();
476
477 if (!row1 && !row2)
478 return kTRUE;
479
480 if (!row1 || !row2)
481 return kFALSE;
482
483 if (atoi((*row1)[0])!=atoi((*row2)[0]))
484 return kFALSE;
485 }
486
487 return kFALSE;
488 }
489
490 Int_t CreateSequence(Int_t runstart, Int_t runstop)
491 {
492 cout << " * Creating Sequence " << runstart << "-" << runstop << ":" << endl;
493
494 TString query=
495 Form("SELECT fSequenceFirst FROM RunData "
496 " WHERE fRunNumber BETWEEN %d AND %d AND "
497 " fSequenceFirst>0 AND "
498 " fExcludedFDAKEY=1 AND (fRunTypeKEY BETWEEN 2 AND 4)"
499 " GROUP BY fSequenceFirst", runstart, runstop);
500
501 TSQLResult *res = Query(query);
502 if (!res)
503 return 2;
504
505 const Int_t cnt = res->GetRowCount();
506
507 Int_t rc = kTRUE;
508 if (cnt==1)
509 {
510 TSQLRow *row=res->Next();
511 const Int_t check = CheckSequence(runstart, runstop);
512 if (check==kTRUE)
513 {
514 cout << " - Identical sequence already existing." << endl;
515 delete res;
516 return kTRUE;
517 }
518 if (check==2)
519 rc=2;
520 else
521 {
522 cout << " - Deleting quasi-identical sequence " << atoi((*row)[0]) << endl;
523 if (DeleteSequence(atoi((*row)[0]))==2)
524 rc = 2;
525 }
526 }
527 else
528 {
529 TSQLRow *row=0;
530 while ((row=res->Next()))
531 {
532 cout << " - Deleting overlapping sequence " << atoi((*row)[0]) << endl;
533 if (DeleteSequence(atoi((*row)[0]))==2)
534 rc = 2;
535 }
536 }
537
538 delete res;
539
540 if (rc==2)
541 return 2;
542
543 if (!InsertSequence(runstart, runstop))
544 return 2;
545
546 return kTRUE;
547 }
548
549 Bool_t ReadResources(const char *fname)
550 {
551 TPRegexp regexp("^\\[.*\\]$");
552
553 ifstream fin(fname);
554 if (!fin)
555 {
556 cout << "Cannot open file " << fname << ": ";
557 cout << strerror(errno) << endl;
558 return kFALSE;
559 }
560
561 Int_t section = 0;
562
563 TString key;
564 while (1)
565 {
566 TString txt;
567 txt.ReadLine(fin);
568 if (!fin)
569 break;
570
571 txt = txt.Strip(TString::kBoth);
572
573 if (txt[0]=='#' || txt.IsNull())
574 continue;
575
576 if (txt[0]=='[' && section!=2)
577 {
578 //cout << txt << endl;
579 section = 0;
580 if (txt(regexp)=="[Transition]")
581 section = 1;
582 if (txt(regexp)=="[Regexp]")
583 section = 2;
584 continue;
585 }
586
587 TObjArray *arr = txt.Tokenize(" ");
588
589 if (arr->GetEntries()>0)
590 switch (section)
591 {
592 case 1:
593 {
594 TString key = arr->At(0)->GetName();
595 key.Prepend("f");
596 key.Append("KEY");
597
598 CheckList *list = dynamic_cast<CheckList*>(fMap.GetValue(key));
599 if (!list)
600 {
601 //cout << key << endl;
602 list = new CheckList;
603 fMap.Add(new TObjString(key), list);
604 }
605
606 if (arr->GetEntries()>1)
607 {
608 //cout << key << " ";
609 list->Add(new CheckMatch(*arr, 1));
610 }
611 }
612 break;
613 case 2:
614 fListRegexp.Add(new Rule(*arr));
615 break;
616 }
617
618 delete arr;
619 }
620
621 return kTRUE;
622 }
623
624 TString GetELT(const char *col, TSQLResult *res, TList &regexp)
625 {
626 TObjArray names; // array with old names (including regexp)
627
628 // Add to array and expand the array if necessary
629 TSQLRow *row=0;
630 while ((row=res->Next()))
631 names.AddAtAndExpand(new TObjString((*row)[1]), atoi((*row)[0]));
632
633 // Now a LUT is build which converts the keys for
634 // the names including the regexp into keys for
635 // the names excluding the regexp
636 TString elt(Form("ELT(RunData.f%sKEY+1", col));
637
638 // loop over all entries in the list
639 const Int_t n = names.GetSize();
640 for (int i=0; i<n; i++)
641 {
642 // For all entries which are not in the list
643 // write an undefined value into the LUT
644 TObject *o = names.UncheckedAt(i);
645 if (!o)
646 {
647 elt += ",0";
648 continue;
649 }
650
651 // Remove the regexp from the string which includes it
652 TString name = o->GetName();
653
654 TIter NextR(&regexp);
655 TObject *reg=0;
656 while ((reg=NextR()))
657 {
658 TPRegexp reg(reg->GetName());
659 const Ssiz_t pos = name.Index(reg, 0);
660 if (pos>0)
661 {
662 name.Remove(pos);
663 name += "-W";
664 break;
665 }
666 }
667
668 // Check if such a Key exists, if not insert it
669 const Int_t key = QueryKeyOfName(col, name);
670
671 // RESOLVE return code!!!
672 //if (key<0)
673 // return "";
674
675 // add index to the LUT
676 elt += Form(",%d", key);
677 }
678
679 // close LUT expression
680 // elt += ") AS Elt";
681 // elt += col;
682
683 elt += ") AS f";
684 elt += col;
685 elt += "KEY";
686
687 // return result
688 return elt;
689 }
690
691 TString GetELT(const char *col, TSQLResult *res, TString regexp)
692 {
693 TList list;
694 list.SetOwner();
695 list.Add(new TObjString(regexp));
696 return GetELT(col, res, list);
697 }
698
699 TString GetELTQuery(const char *col, const char *cond) const
700 {
701 return Form("SELECT RunData.f%sKEY, f%sName FROM RunData "
702 "LEFT JOIN %s ON RunData.f%sKEY=%s.f%sKEY "
703 "WHERE %s GROUP BY f%sName",
704 col, col, col, col, col, col, cond, col);
705 }
706
707 TString GetELTSource(const char *cond)
708 {
709 //query all sources observed in this night
710 TSQLResult *resx = Query(GetELTQuery("Source", cond));
711 if (!resx)
712 return "";
713
714 // In the case there is only a single source
715 // do not replace the source key by the ELT
716 if (resx->GetRowCount()==1)
717 return "fSourceKEY";
718
719 TString elts = GetELT("Source", resx, "\\-?W[1-9][ abc]?$");
720 delete resx;
721
722 return elts;
723 }
724
725 TString GetELTProject(const char *cond)
726 {
727 //query all project names observed in this night
728 TSQLResult *resx = Query(GetELTQuery("Project", cond));
729 if (!resx)
730 return "";
731
732 // In the case there is only a single project
733 // do not replace the project key by the ELT
734 if (resx->GetRowCount()==1)
735 return "fProjectKEY";
736
737 TList regexp;
738 regexp.Add(new TObjString("\\-?W[1-9][abc]?$"));
739 regexp.Add(new TObjString("\\-W[0-9]\\.[0-9][0-9]\\+[0-9][0-9][0-9]$"));
740
741 TString eltp2 = GetELT("Project", resx, regexp);
742 delete resx;
743 regexp.Delete();
744
745 return eltp2;
746 }
747
748 Bool_t HasAtLeastOne(TString src, TString chk) const
749 {
750 src.ToLower();
751 chk.ToLower();
752
753 for (int i=0; i<chk.Length(); i++)
754 if (src.First(chk[i])<0)
755 return kFALSE;
756
757 return kTRUE;
758 }
759
760 TString PrepareString(TSQLResult &res, TArrayI &runs)
761 {
762 // Number of result rows
763 const Int_t rows = res.GetRowCount();
764
765 runs.Set(rows); // initialize size of array for run numbers
766
767 TArrayD start(rows); // instantiate array for start times
768 TArrayD stop(rows); // instantiate array for stop times
769
770 TString str; // result string
771
772 Int_t idx=0;
773 TSQLRow *row=0;
774 while ((row=res.Next()))
775 {
776 runs[idx] = atoi((*row)[0]); // run number
777
778 const TString tstart = ((*row)[2]); // start time
779 const TString tstop = ((*row)[3]); // stop time
780
781 start[idx] = MTime(tstart).GetMjd(); // convert to double
782 stop[idx] = MTime(tstop).GetMjd(); // convert to double
783
784 // This is a workaround for broken start-times
785 if (tstart=="0000-00-00 00:00:00")
786 start[idx] = stop[idx];
787
788 // Add a run-type character for this run to the string
789 str += RunType((*row)[1]);
790
791 // Increase index
792 idx++;
793 }
794
795 // Now the P- and D- runs are classified by the time-distance
796 // to the next or previous C-Run
797 Double_t lastc = -1;
798 Double_t nextc = -1;
799 for (int i=0; i<str.Length(); i++)
800 {
801 if (str[i]=='C')
802 {
803 // Remember stop time of C-Run as time of last C-run
804 lastc = stop[i];
805
806 // Calculate start time of next C-Run
807 const TString residual = str(i+1, str.Length());
808 const Int_t pos = residual.First('C');
809
810 // No C-Run found anymore. Finished...
811 if (pos<0)
812 break;
813
814 // Remember start time of C-Run as time of next C-run
815 nextc = start[i+1+pos];
816 continue;
817 }
818
819 // Check whether the identifying character should
820 // be converted to lower case
821 if (start[i]-lastc>nextc-stop[i])
822 str[i] = tolower(str[i]);
823 }
824 //cout << str << endl;
825 return str;
826 }
827
828 void PrintResidual(Int_t runstart, Int_t runstop, TString residual, const char *descr)
829 {
830 residual.ToLower();
831
832 // Count number of unsequences "characters"
833 const Int_t nump = residual.CountChar('p');
834 const Int_t numd = residual.CountChar('d');
835 const Int_t numc = residual.CountChar('c');
836
837 // Print some information to the output steram
838 if (nump+numc+numd==0)
839 return;
840
841 cout << " ! " << runstart << "-" << runstop << " [" << setw(3) << 100*residual.Length()/(runstop-runstart+1) << "%]: " << descr << " not sequenced: P=" << nump << " C=" << numc << " D=" << numd;
842 if (numd>0)
843 cout << " (DATA!)";
844
845 if (nump==0 || numc==0 || numd==0)
846 cout << " Missing";
847 if (numd==0)
848 cout << " D";
849 if (nump==0)
850 cout << " P";
851 if (numc==0)
852 cout << " C";
853
854 cout << endl;
855 }
856
857 Int_t SplitBlock(Int_t runstart, Int_t runstop)
858 {
859 // Request data necessary to split block into sequences
860 const TString query=
861 Form("SELECT fRunNumber, fRunTypeKEY, fRunStart, fRunStop"
862 " FROM RunData "
863 " WHERE fRunNumber BETWEEN %d AND %d AND "
864 " fExcludedFDAKEY=1 AND (fRunTypeKEY BETWEEN 2 AND 4)"
865 " ORDER BY fRunNumber", runstart, runstop);
866
867 // Send query
868 TSQLResult *res = Query(query);
869 if (!res)
870 return 2;
871
872 // Get String containing the sequence of P-,C- and D-Runs
873 // and an array with the corresponding run-numbers
874 TArrayI runs;
875 const TString str = PrepareString(*res, runs);
876
877 delete res;
878
879 // Check if the prepared string at least contains one run of each type
880 if (!HasAtLeastOne(str, "PCD"))
881 {
882 PrintResidual(runstart, runstop, str, "Block");
883 return kTRUE;
884 }
885
886 // Start the sequence building
887 // ---------------------------
888
889 Int_t pos = 0; // Position in the string
890 TExMap map; // Map for resulting sequences
891 TString residual; // Unsequences "characters"
892
893 // Step through the string one character by one
894 cout << " ";
895 while (pos<str.Length())
896 {
897 Bool_t found = kFALSE;
898
899 // Loop over the predefined regular expressions
900 TIter Next(&fListRegexp);
901 Rule *obj = 0;
902 while ((obj=(Rule*)Next()))
903 {
904 // Check if regular expressions matchs
905 const Ssiz_t len = obj->Match(str, pos, runs[pos]);
906 if (len>0)
907 {
908 // In case of match get the substring which
909 // defines the sequence and print it
910 TString sub = str(pos, len);
911 sub.ToUpper();
912 cout << runs[pos]<<":"<< sub << "|";
913
914 // Add the first and last run of the sequence to the map
915 map.Add(runs[pos], runs[pos+len-1]);
916
917 // A sequence was found...
918 found = kTRUE;
919
920 // step forward in the string by the length of the sequence
921 pos += len;
922 break;
923 }
924 }
925
926 // If a sequence was found go on...
927 if (found)
928 continue;
929
930 // print unsequenced characters
931 cout << (char)tolower(str[pos]);
932
933 // Count the number of "characters" not sequenced
934 residual += str[pos];
935
936 // step one character forward
937 pos++;
938 }
939 cout << endl;
940
941 PrintResidual(runstart, runstop, residual, "Runs ");
942
943 // Create all sequences which were previously found
944 Long_t first, last;
945 TExMapIter iter(&map);
946 while (iter.Next(first, last))
947 if (CreateSequence(first, last)==2)
948 return 2;
949
950 return kTRUE;
951 }
952
953 Char_t RunType(Int_t n) const
954 {
955 switch (n)
956 {
957 case 2: return 'D';
958 case 3: return 'P';
959 case 4: return 'C';
960 }
961 return '-';
962 }
963 Char_t RunType(const char *str) const
964 {
965 return RunType(atoi(str));
966 }
967
968 Int_t BuildBlocks(TSQLResult *res, TExMap &blocks)
969 {
970 // col key content
971 // -----------------------------
972 // 0 - runnumber
973 // 1 0 RunTypeKEY
974 // 2 1 source
975 // 3 2 project
976 // . .
977 // . .
978 // . . from transition.txt
979 //
980
981 //build blocks of runs, which have the same values
982 //for each block the first and the last run are stored in a TExMap
983 //the values are checked with the help of an array of TStrings
984 Long_t runstart = -1;
985 Long_t runstop = -1;
986
987 const UInt_t ncols = res->GetFieldCount();
988
989 TString keys[ncols]; // Index 0 is not used (Index 1: RunType)
990
991 // Loop over runs
992 TSQLRow *row=0;
993 while ((row=res->Next()))
994 {
995 // This is the runnumber of the first run in the new block
996 if (runstart<0)
997 runstart=atoi((*row)[0]);
998
999 // Check which transitions might be allowed for this run and
1000 // which are not. Check also which attributes should be ignored
1001 // for this run. The information about it is stored in the map.
1002 Int_t rc[ncols];
1003 for (UInt_t i=2; i<ncols; i++)
1004 rc[i] = CheckTransition(*res, keys, *row, i);
1005
1006 for (UInt_t i=2; i<ncols; i++)
1007 {
1008 switch (rc[i])
1009 {
1010 case kTRUE: // Transition allowed, switch to new attribute
1011 keys[i] = (*row)[i];
1012 continue;
1013
1014 case -1: // Ignore attribute, continue with next one
1015 //if (keys[i] == (*row)[i])
1016 // break; // Only ignore it if it is really different
1017 continue;
1018
1019 case kFALSE: // No decision (nothing matching found in map)
1020 break; // go on checking
1021
1022 }
1023
1024 // If past-attribute is not yet initialized, do it now.
1025 if (keys[i].IsNull())
1026 keys[i] = (*row)[i];
1027
1028 // Check whether key has changed for this run
1029 // (this condition is never true for the first run)
1030 // This condition in only reached if keys[i] was initialized
1031 if (keys[i] == (*row)[i])
1032 continue;
1033
1034 // Found one block with unique keys, fill values into TExMap
1035 // (except if this is the first run processed)
1036 cout << endl;
1037 cout << " - Identical conditions from " << runstart << " to " << runstop << endl;
1038 blocks.Add((ULong_t)blocks.GetSize(), runstart, runstop);
1039 if (SplitBlock(runstart, runstop)==2)
1040 return 2;
1041 cout << " - Transition from " << RunType(keys[1]) << ":";
1042 cout << QueryNameOfKey(res->GetFieldName(i), keys[i]) << " <" << keys[i] << "> to " << RunType((*row)[1]) << ":";
1043 cout << QueryNameOfKey(res->GetFieldName(i), (*row)[i]) << " <" << (*row)[i] << ">";
1044 cout << " in " << res->GetFieldName(i) << " of " << (*row)[0] << endl;
1045
1046 // This is already the first run of the new block
1047 runstart=atoi((*row)[0]);
1048
1049 // These are the keys corresponding to the first run
1050 // in the new block. All following runs should have
1051 // identical keys. Do not set the attribute if for
1052 // this attribute the transition check evaluated
1053 // to "ignore".
1054 for (UInt_t j=2; j<ncols; j++)
1055 keys[j] = rc[j]==-1 ? "" : (*row)[j];
1056
1057 break;
1058 }
1059
1060 keys[1] = (*row)[1]; // Remember run type for next run
1061
1062 // This is the new runnumber of the last run in this block
1063 runstop=atoi((*row)[0]);
1064 }
1065
1066 // If runstart==-1 a possible block would contain a single run...
1067 if (runstart>0 && runstart!=runstop)
1068 {
1069 cout << " - Identical conditions from " << runstart << " to " << runstop << " (last run)" << endl;
1070 //fill values into TExMap (last value)
1071 blocks.Add((ULong_t)blocks.GetSize(), runstart, runstop);
1072 if (SplitBlock(runstart, runstop)==2)
1073 return 2;
1074 }
1075 cout << "Done." << endl << endl;
1076
1077 return kTRUE;
1078 }
1079
1080public:
1081 SequenceBuild(TEnv &env) : MSQLMagic(env)
1082 {
1083 cout << "buildsequences" << endl;
1084 cout << "--------------" << endl;
1085 cout << endl;
1086 cout << "Connected to " << GetName() << endl;
1087
1088 fListRegexp.SetOwner();
1089
1090 // FIXME: THIS IS NOT YET HANDLED
1091 if (ReadResources("resources/sequences.rc"))
1092 return;
1093 }
1094 SequenceBuild()
1095 {
1096 fMap.DeleteAll();
1097 }
1098
1099 void SetPathRawData(const char *path) { fPathRawData=path; }
1100 void SetPathSequences(const char *path) { fPathSequences=path; }
1101
1102 int Build(TString day)
1103 {
1104 cout << endl;
1105 cout << "Night of sunrise at " << day << ":" << endl;
1106
1107 day += " 13:00:00";
1108 const TString cond =
1109 Form("(fRunStart>ADDDATE(\"%s\", INTERVAL -1 DAY) AND fRunStart<\"%s\") "
1110 "AND fExcludedFDAKEY=1 AND fRunTypeKEY BETWEEN 2 AND 4 ",
1111 day.Data(), day.Data());
1112
1113 //query all sources observed in this night
1114 const TString elts = GetELTSource(cond);
1115 if (elts.IsNull())
1116 return 2;
1117
1118 //query all project names observed in this night
1119 const TString eltp2 = GetELTProject(cond);
1120 if (elts.IsNull())
1121 return 2;
1122
1123 // Setup query to get all values from the database,
1124 // that are relevant for building sequences
1125 TString query("SELECT fRunNumber, fRunTypeKEY, ");
1126 query += elts;
1127 query += ", ";
1128 query += eltp2;
1129
1130 // Now add all entries from the transition table to the query
1131 TIter NextPair(&fMap);
1132 TObject *mapkey = 0;
1133 while ((mapkey=(TPair*)NextPair()))
1134 if (!query.Contains(mapkey->GetName()))
1135 {
1136 query += ", ";
1137 query += mapkey->GetName();
1138 }
1139 query += Form(" FROM RunData WHERE %s ORDER BY fRunNumber", cond.Data());
1140
1141 TSQLResult *res = Query(query);
1142 if (!res)
1143 return 2;
1144
1145 TExMap blocks;
1146 const Int_t rc = BuildBlocks(res, blocks);
1147 delete res;
1148
1149 return rc;
1150 }
1151
1152 Int_t Build()
1153 {
1154 //get all dates from the database
1155 TSQLResult *res = Query("SELECT fDate FROM SequenceBuildStatus ORDER BY fDate DESC");
1156 if (!res)
1157 return 2;
1158
1159 //execute buildsequenceentries for all dates
1160 TSQLRow *row=0;
1161 while ((row=res->Next()))
1162 Build((*row)[0]);
1163
1164 delete res;
1165
1166 return 1;
1167 }
1168 ClassDef(SequenceBuild, 0)
1169};
1170
1171ClassImp(SequenceBuild);
1172
1173int buildsequenceentries(TString day, TString datapath, TString sequpath, Bool_t dummy=kTRUE)
1174{
1175 TEnv env("sql.rc");
1176
1177 SequenceBuild serv(env);
1178 if (!serv.IsConnected())
1179 {
1180 cout << "ERROR - Connection to database failed." << endl;
1181 return 0;
1182 }
1183
1184 serv.SetIsDummy(dummy);
1185 serv.SetPathRawData(datapath);
1186 serv.SetPathSequences(sequpath);
1187 return serv.Build(day);
1188}
1189
1190//
1191// Build Sequences for all Nights
1192//
1193int buildsequenceentries(TString datapath, TString sequpath, Bool_t dummy=kTRUE)
1194{
1195 TEnv env("sql.rc");
1196
1197 SequenceBuild serv(env);
1198 if (!serv.IsConnected())
1199 {
1200 cout << "ERROR - Connection to database failed." << endl;
1201 return 0;
1202 }
1203
1204 serv.SetIsDummy(dummy);
1205 serv.SetPathRawData(datapath);
1206 serv.SetPathSequences(sequpath);
1207 return serv.Build();
1208}
1209
1210int buildsequenceentries(Bool_t dummy=kTRUE)
1211{
1212 return buildsequenceentries("", "", dummy);
1213}
1214
1215int buildsequenceentries(TString day, Bool_t dummy=kTRUE)
1216{
1217 return buildsequenceentries(day, "", "", dummy);
1218}
Note: See TracBrowser for help on using the repository browser.