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

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