source: trunk/MagicSoft/Mars/datacenter/macros/buildsequenceentries.C@ 9052

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