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

Last change on this file since 9212 was 9191, checked in by tbretz, 16 years ago
*** empty log message ***
File size: 40.1 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, 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", runstart, runstop,
513 fTelescopeNumber);
514
515 TSQLResult *res = Query(query);
516 if (!res)
517 return 2;
518
519 const Int_t cnt = res->GetRowCount();
520
521 Int_t rc = kTRUE;
522 if (cnt==1)
523 {
524 TSQLRow *row=res->Next();
525 const Int_t check = CheckSequence(runstart, runstop);
526 if (check==kTRUE)
527 {
528 cout << " - Identical sequence already existing." << endl;
529 delete res;
530 return kTRUE;
531 }
532 if (check==2)
533 rc=2;
534 else
535 {
536 cout << " - Deleting quasi-identical sequence " << atoi((*row)[0]) << endl;
537 if (DeleteSequence(atoi((*row)[0]))==2)
538 rc = 2;
539 }
540 }
541 else
542 {
543 TSQLRow *row=0;
544 while ((row=res->Next()))
545 {
546 cout << " - Deleting overlapping sequence " << atoi((*row)[0]) << endl;
547 if (DeleteSequence(atoi((*row)[0]))==2)
548 rc = 2;
549 }
550 }
551
552 delete res;
553
554 if (rc==2)
555 return 2;
556
557 if (!InsertSequence(runstart, runstop))
558 return 2;
559
560 return kTRUE;
561 }
562
563 Bool_t ReadResources(const char *fname)
564 {
565 // Check for the section header
566 TPRegexp regexp("^\\[(Transition|Regexp):?[0-9 ]*\\]$");
567 // Check if section header contains a number
568 TPRegexp regnum("[0-9]");
569 // Check if section header contains the telescope number
570 TPRegexp regtel(Form("[^0-9]0*%d[^0-9]", fTelescopeNumber));
571
572 ifstream fin(fname);
573 if (!fin)
574 {
575 cout << "Cannot open file " << fname << ": ";
576 cout << strerror(errno) << endl;
577 return kFALSE;
578 }
579
580 Int_t section = 0;
581
582 TString key;
583 while (1)
584 {
585 TString txt;
586 txt.ReadLine(fin);
587 if (!fin)
588 break;
589
590 txt = txt.Strip(TString::kBoth);
591
592 if (txt[0]=='#' || txt.IsNull())
593 continue;
594
595 if (txt[0]=='[')
596 {
597 TString sec = txt(regexp);
598 if (!sec.IsNull())
599 {
600 // Skip sections with the wrong telescope number
601 // (If section contains numbers but not the tel num)
602 if (!sec(regnum).IsNull() && sec(regtel).IsNull())
603 continue;
604
605 // Check which section we are in
606 if (sec.BeginsWith("[Transition"))
607 section = 1;
608 if (sec.BeginsWith("[Regexp"))
609 section = 2;
610
611 continue;
612 }
613
614 if (section!=2)
615 {
616 cout << "WARNING - Line starts with [ but we are not in the Regexp section." << endl;
617 cout << txt << endl;
618 continue;
619 }
620 }
621
622
623 TObjArray *arr = txt.Tokenize(" ");
624
625 if (arr->GetEntries()>0)
626 switch (section)
627 {
628 case 1:
629 {
630 TString key = arr->At(0)->GetName();
631 key.Prepend("f");
632 key.Append("KEY");
633
634 CheckList *list = dynamic_cast<CheckList*>(fMap.GetValue(key));
635 if (!list)
636 {
637 //cout << key << endl;
638 list = new CheckList;
639 fMap.Add(new TObjString(key), list);
640 }
641
642 if (arr->GetEntries()>1)
643 {
644 //cout << key << " ";
645 list->Add(new CheckMatch(*arr, 1));
646 }
647 }
648 break;
649 case 2:
650 fListRegexp.Add(new Rule(*arr));
651 break;
652 }
653
654 delete arr;
655 }
656
657 return kTRUE;
658 }
659
660 TString GetELT(const char *col, TSQLResult *res, TList &regexp)
661 {
662 TObjArray names; // array with old names (including regexp)
663
664 // Add to array and expand the array if necessary
665 TSQLRow *row=0;
666 while ((row=res->Next()))
667 names.AddAtAndExpand(new TObjString((*row)[1]), atoi((*row)[0]));
668
669 // Now a LUT is build which converts the keys for
670 // the names including the regexp into keys for
671 // the names excluding the regexp
672 TString elt(Form("ELT(RunData.f%sKEY+1", col));
673
674 // loop over all entries in the list
675 const Int_t n = names.GetSize();
676 for (int i=0; i<n; i++)
677 {
678 // For all entries which are not in the list
679 // write an undefined value into the LUT
680 TObject *o = names.UncheckedAt(i);
681 if (!o)
682 {
683 elt += ",0";
684 continue;
685 }
686
687 // Remove the regexp from the string which includes it
688 TString name = o->GetName();
689
690 TIter NextR(&regexp);
691 TObject *obj=0;
692 while ((obj=NextR()))
693 {
694 TPRegexp reg(obj->GetName());
695 const Ssiz_t pos = name.Index(reg, 0);
696 if (pos>0)
697 {
698 name.Remove(pos);
699 name += "-W";
700 break;
701 }
702 }
703
704 // Check if such a Key exists, if not insert it
705 const Int_t key = QueryKeyOfName(col, name);
706
707 // RESOLVE return code!!!
708 //if (key<0)
709 // return "";
710
711 // add index to the LUT
712 elt += Form(",%d", key);
713 }
714
715 // close LUT expression
716 // elt += ") AS Elt";
717 // elt += col;
718
719 elt += ") AS f";
720 elt += col;
721 elt += "KEY";
722
723 // return result
724 return elt;
725 }
726
727 TString GetELT(const char *col, TSQLResult *res, TString regexp)
728 {
729 TList list;
730 list.SetOwner();
731 list.Add(new TObjString(regexp));
732 return GetELT(col, res, list);
733 }
734
735 TString GetELTQuery(const char *col, const char *cond) const
736 {
737 return Form("SELECT RunData.f%sKEY, f%sName FROM RunData "
738 "LEFT JOIN %s USING (f%sKEY) WHERE %s GROUP BY f%sName",
739 col, col, col, col, cond, col);
740 }
741
742 TString GetELTSource(const char *cond)
743 {
744 //query all sources observed in this night
745 TSQLResult *resx = Query(GetELTQuery("Source", cond));
746 if (!resx)
747 return "";
748
749 // In the case there is only a single source
750 // do not replace the source key by the ELT
751 if (resx->GetRowCount()==1)
752 return "fSourceKEY";
753
754 TString elts = GetELT("Source", resx, "\\-?W[1-9][ abc]?$");
755 delete resx;
756
757 return elts;
758 }
759
760 TString GetELTProject(const char *cond)
761 {
762 //query all project names observed in this night
763 TSQLResult *resx = Query(GetELTQuery("Project", cond));
764 if (!resx)
765 return "";
766
767 // In the case there is only a single project
768 // do not replace the project key by the ELT
769 if (resx->GetRowCount()==1)
770 return "fProjectKEY";
771
772 TList regexp;
773 regexp.Add(new TObjString("\\-?W[1-9][abc]?$"));
774 regexp.Add(new TObjString("\\-W[0-9]\\.[0-9][0-9]\\+[0-9][0-9][0-9]$"));
775
776 TString eltp2 = GetELT("Project", resx, regexp);
777 delete resx;
778 regexp.Delete();
779
780 return eltp2;
781 }
782
783 Bool_t HasAtLeastOne(TString src, TString chk) const
784 {
785 src.ToLower();
786 chk.ToLower();
787
788 for (int i=0; i<chk.Length(); i++)
789 if (src.First(chk[i])<0)
790 return kFALSE;
791
792 return kTRUE;
793 }
794
795 TString PrepareString(TSQLResult &res, TArrayI &runs)
796 {
797 // Number of result rows
798 const Int_t rows = res.GetRowCount();
799
800 runs.Set(rows); // initialize size of array for run numbers
801
802 TArrayD start(rows); // instantiate array for start times
803 TArrayD stop(rows); // instantiate array for stop times
804
805 TString str; // result string
806
807 Int_t idx=0;
808 TSQLRow *row=0;
809 while ((row=res.Next()))
810 {
811 runs[idx] = atoi((*row)[0]); // run number
812
813 const TString tstart = ((*row)[2]); // start time
814 const TString tstop = ((*row)[3]); // stop time
815
816 start[idx] = MTime(tstart).GetMjd(); // convert to double
817 stop[idx] = MTime(tstop).GetMjd(); // convert to double
818
819 // This is a workaround for broken start-times
820 if (tstart=="0000-00-00 00:00:00")
821 start[idx] = stop[idx];
822
823 // Add a run-type character for this run to the string
824 str += RunType((*row)[1]);
825
826 // Increase index
827 idx++;
828 }
829
830 // Now the P- and D- runs are classified by the time-distance
831 // to the next or previous C-Run
832 Double_t lastc = -1;
833 Double_t nextc = -1;
834 for (int i=0; i<str.Length(); i++)
835 {
836 if (str[i]=='C')
837 {
838 // Remember stop time of C-Run as time of last C-run
839 lastc = stop[i];
840
841 // Calculate start time of next C-Run
842 const TString residual = str(i+1, str.Length());
843 const Int_t pos = residual.First('C');
844
845 // No C-Run found anymore. Finished...
846 if (pos<0)
847 break;
848
849 // Remember start time of C-Run as time of next C-run
850 nextc = start[i+1+pos];
851 continue;
852 }
853
854 // Check whether the identifying character should
855 // be converted to lower case
856 if (start[i]-lastc>nextc-stop[i])
857 str[i] = tolower(str[i]);
858 }
859 //cout << str << endl;
860 return str;
861 }
862
863 void PrintResidual(Int_t runstart, Int_t runstop, TString residual, const char *descr)
864 {
865 residual.ToLower();
866
867 // Count number of unsequences "characters"
868 const Int_t nump = residual.CountChar('p');
869 const Int_t numd = residual.CountChar('d');
870 const Int_t numc = residual.CountChar('c');
871
872 // Print some information to the output steram
873 if (nump+numc+numd==0)
874 return;
875
876 cout << " ! " << runstart << "-" << runstop << " [" << setw(3) << 100*residual.Length()/(runstop-runstart+1) << "%]: " << descr << " not sequenced: P=" << nump << " C=" << numc << " D=" << numd;
877 if (numd>0)
878 cout << " (DATA!)";
879
880 if (nump==0 || numc==0 || numd==0)
881 cout << " Missing";
882 if (numd==0)
883 cout << " D";
884 if (nump==0)
885 cout << " P";
886 if (numc==0)
887 cout << " C";
888
889 cout << endl;
890 }
891
892 Int_t SplitBlock(Int_t runstart, Int_t runstop, const TString &cond)
893 {
894 // Request data necessary to split block into sequences
895 /*const*/ TString query=
896 Form("SELECT fRunNumber*1000+fFileNumber AS Id, fRunTypeKEY, fRunStart, fRunStop"
897 " FROM RunData "
898 " WHERE fRunNumber*1000+fFileNumber BETWEEN %d AND %d AND "
899 /*" fExcludedFDAKEY=1 AND (fRunTypeKEY BETWEEN 2 AND 4)"
900 " ORDER BY Id"*/, runstart, runstop);
901
902 query += cond;
903 query += " ORDER BY Id";
904
905
906 // Send query
907 TSQLResult *res = Query(query);
908 if (!res)
909 return 2;
910
911 // Get String containing the sequence of P-,C- and D-Runs
912 // and an array with the corresponding run-numbers
913 TArrayI runs;
914 const TString str = PrepareString(*res, runs);
915
916 delete res;
917
918 // Check if the prepared string at least contains one run of each type
919 if (!HasAtLeastOne(str, "PCD"))
920 {
921 PrintResidual(runstart, runstop, str, "Block");
922 return kTRUE;
923 }
924
925 // Start the sequence building
926 // ---------------------------
927
928 Int_t pos = 0; // Position in the string
929 TExMap map; // Map for resulting sequences
930 TString residual; // Unsequences "characters"
931
932 // Step through the string one character by one
933 cout << " ";
934 while (pos<str.Length())
935 {
936 Bool_t found = kFALSE;
937
938 // Loop over the predefined regular expressions
939 TIter Next(&fListRegexp);
940 Rule *obj = 0;
941 while ((obj=(Rule*)Next()))
942 {
943 // Check if regular expressions matchs
944 const Ssiz_t len = obj->Match(str, pos, runs[pos]);
945 if (len>0)
946 {
947 // In case of match get the substring which
948 // defines the sequence and print it
949 TString sub = str(pos, len);
950 sub.ToUpper();
951 cout << runs[pos]<<":"<< sub << "|";
952
953 // Add the first and last run of the sequence to the map
954 map.Add(runs[pos], runs[pos+len-1]);
955
956 // A sequence was found...
957 found = kTRUE;
958
959 // step forward in the string by the length of the sequence
960 pos += len;
961 break;
962 }
963 }
964
965 // If a sequence was found go on...
966 if (found)
967 continue;
968
969 // print unsequenced characters
970 cout << (char)tolower(str[pos]);
971
972 // Count the number of "characters" not sequenced
973 residual += str[pos];
974
975 // step one character forward
976 pos++;
977 }
978 cout << endl;
979
980 PrintResidual(runstart, runstop, residual, "Runs ");
981
982 // Create all sequences which were previously found
983 Long_t first, last;
984 TExMapIter iter(&map);
985 while (iter.Next(first, last))
986 if (CreateSequence(first, last)==2)
987 return 2;
988
989 return kTRUE;
990 }
991
992 Char_t RunType(Int_t n) const
993 {
994 switch (n)
995 {
996 case 2: return 'D';
997 case 3: return 'P';
998 case 4: return 'C';
999 }
1000 return '-';
1001 }
1002 Char_t RunType(const char *str) const
1003 {
1004 return RunType(atoi(str));
1005 }
1006
1007 Int_t BuildBlocks(TSQLResult *res, TExMap &blocks, const TString &cond)
1008 {
1009 // col key content
1010 // -----------------------------
1011 // 0 - runnumber
1012 // 1 0 RunTypeKEY
1013 // 2 1 source
1014 // 3 2 project
1015 // . .
1016 // . .
1017 // . . from transition.txt
1018 //
1019
1020 //build blocks of runs, which have the same values
1021 //for each block the first and the last run are stored in a TExMap
1022 //the values are checked with the help of an array of TStrings
1023 Long_t runstart = -1;
1024 Long_t runstop = -1;
1025
1026 const UInt_t ncols = res->GetFieldCount();
1027
1028 TString keys[ncols]; // Index 0 is not used (Index 1: RunType)
1029
1030 // Loop over runs
1031 TSQLRow *row=0;
1032 while ((row=res->Next()))
1033 {
1034 // This is the runnumber of the first run in the new block
1035 if (runstart<0)
1036 runstart=atoi((*row)[0]);
1037
1038 // Check which transitions might be allowed for this run and
1039 // which are not. Check also which attributes should be ignored
1040 // for this run. The information about it is stored in the map.
1041 Int_t rc[ncols];
1042 for (UInt_t i=2; i<ncols; i++)
1043 rc[i] = CheckTransition(*res, keys, *row, i);
1044
1045 for (UInt_t i=2; i<ncols; i++)
1046 {
1047 switch (rc[i])
1048 {
1049 case kTRUE: // Transition allowed, switch to new attribute
1050 keys[i] = (*row)[i];
1051 continue;
1052
1053 case -1: // Ignore attribute, continue with next one
1054 //if (keys[i] == (*row)[i])
1055 // break; // Only ignore it if it is really different
1056 continue;
1057
1058 case kFALSE: // No decision (nothing matching found in map)
1059 break; // go on checking
1060
1061 }
1062
1063 // If past-attribute is not yet initialized, do it now.
1064 if (keys[i].IsNull())
1065 keys[i] = (*row)[i];
1066
1067 // Check whether key has changed for this run
1068 // (this condition is never true for the first run)
1069 // This condition in only reached if keys[i] was initialized
1070 if (keys[i] == (*row)[i])
1071 continue;
1072
1073 // Found one block with unique keys, fill values into TExMap
1074 // (except if this is the first run processed)
1075 cout << endl;
1076 cout << " - Identical conditions from " << runstart << " to " << runstop << endl;
1077 blocks.Add((ULong_t)blocks.GetSize(), runstart, runstop);
1078 if (SplitBlock(runstart, runstop, cond)==2)
1079 return 2;
1080 cout << " - Transition from " << RunType(keys[1]) << ":";
1081 cout << QueryNameOfKey(res->GetFieldName(i), keys[i]) << " <" << keys[i] << "> to " << RunType((*row)[1]) << ":";
1082 cout << QueryNameOfKey(res->GetFieldName(i), (*row)[i]) << " <" << (*row)[i] << ">";
1083 cout << " in " << res->GetFieldName(i) << " of " << (*row)[0] << endl;
1084
1085 // This is already the first run of the new block
1086 runstart=atoi((*row)[0]);
1087
1088 // These are the keys corresponding to the first run
1089 // in the new block. All following runs should have
1090 // identical keys. Do not set the attribute if for
1091 // this attribute the transition check evaluated
1092 // to "ignore".
1093 for (UInt_t j=2; j<ncols; j++)
1094 keys[j] = rc[j]==-1 ? "" : (*row)[j];
1095
1096 break;
1097 }
1098
1099 keys[1] = (*row)[1]; // Remember run type for next run
1100
1101 // This is the new runnumber of the last run in this block
1102 runstop=atoi((*row)[0]);
1103 }
1104
1105 // If runstart==-1 a possible block would contain a single run...
1106 if (runstart>0 && runstart!=runstop)
1107 {
1108 cout << " - Identical conditions from " << runstart << " to " << runstop << " (last run)" << endl;
1109 //fill values into TExMap (last value)
1110 blocks.Add((ULong_t)blocks.GetSize(), runstart, runstop);
1111 if (SplitBlock(runstart, runstop, cond)==2)
1112 return 2;
1113 }
1114 cout << "Done." << endl << endl;
1115
1116 return kTRUE;
1117 }
1118
1119public:
1120 SequenceBuild(Int_t tel=1, const char *rc="sql.rc") : MSQLMagic(rc), fTelescopeNumber(tel)
1121 {
1122 fListRegexp.SetOwner();
1123
1124 // FIXME: THIS IS NOT YET HANDLED
1125 if (ReadResources("resources/sequences.rc"))
1126 return;
1127 }
1128
1129 SequenceBuild(TEnv &env, Int_t tel=1) : MSQLMagic(env), fTelescopeNumber(tel)
1130 {
1131 fListRegexp.SetOwner();
1132
1133 // FIXME: THIS IS NOT YET HANDLED
1134 if (ReadResources("resources/sequences.rc"))
1135 return;
1136 }
1137 ~SequenceBuild()
1138 {
1139 fMap.DeleteAll();
1140 }
1141
1142 void SetPathRawData(const char *path) { fPathRawData=path; }
1143 void SetPathSequences(const char *path) { fPathSequences=path; }
1144
1145 int Build(TString day)
1146 {
1147 cout << endl;
1148 cout << "Night of sunrise at " << day << ":" << endl;
1149
1150 day += " 13:00:00";
1151 const TString cond =
1152 Form("(fRunStart>ADDDATE(\"%s\", INTERVAL -1 DAY) AND fRunStart<\"%s\") "
1153 "AND fExcludedFDAKEY=1 AND fRunTypeKEY BETWEEN 2 AND 4 "
1154 "AND fTelescopeNumber=%d ",
1155 day.Data(), day.Data(), fTelescopeNumber);
1156
1157 //query all sources observed in this night
1158 const TString elts = GetELTSource(cond);
1159 if (elts.IsNull())
1160 return 2;
1161
1162 //query all project names observed in this night
1163 const TString eltp2 = GetELTProject(cond);
1164 if (elts.IsNull())
1165 return 2;
1166
1167 // Setup query to get all values from the database,
1168 // that are relevant for building sequences
1169 TString query("SELECT fRunNumber*1000+fFileNumber AS Id, fRunTypeKEY, ");
1170 query += elts;
1171 query += ", ";
1172 query += eltp2;
1173
1174 // Now add all entries from the transition table to the query
1175 TIter NextPair(&fMap);
1176 TObject *mapkey = 0;
1177 while ((mapkey=(TPair*)NextPair()))
1178 if (!query.Contains(mapkey->GetName()))
1179 {
1180 query += ", ";
1181 query += mapkey->GetName();
1182 }
1183 query += Form(" FROM RunData WHERE %s ORDER BY Id", cond.Data());
1184
1185 TSQLResult *res = Query(query);
1186 if (!res)
1187 return 2;
1188
1189 TExMap blocks;
1190 const Int_t rc = BuildBlocks(res, blocks, cond);
1191 delete res;
1192
1193 return rc;
1194 }
1195
1196 Int_t Build()
1197 {
1198 //get all dates from the database
1199 TSQLResult *res = Query("SELECT fDate FROM SequenceBuildStatus ORDER BY fDate DESC");
1200 if (!res)
1201 return 2;
1202
1203 //execute buildsequenceentries for all dates
1204 TSQLRow *row=0;
1205 while ((row=res->Next()))
1206 Build((*row)[0]);
1207
1208 delete res;
1209
1210 return 1;
1211 }
1212 ClassDef(SequenceBuild, 0)
1213};
1214
1215ClassImp(SequenceBuild);
1216
1217int buildsequenceentries(TString day, TString datapath, TString sequpath, Int_t tel=1, Bool_t dummy=kTRUE)
1218{
1219 SequenceBuild serv(tel, "sql.rc");
1220 if (!serv.IsConnected())
1221 {
1222 cout << "ERROR - Connection to database failed." << endl;
1223 return 0;
1224 }
1225
1226 cout << "buildsequenceentries" << endl;
1227 cout << "--------------------" << endl;
1228 cout << endl;
1229 cout << "Connected to " << serv.GetName() << endl;
1230 if (!datapath.IsNull())
1231 cout << "DataPath: " << datapath << endl;
1232 if (!sequpath.IsNull())
1233 cout << "SeqPath: " << sequpath << endl;
1234 cout << "Day: " << day << endl;
1235 cout << "Telescope: " << tel << endl;
1236 cout << endl;
1237
1238 serv.SetIsDummy(dummy);
1239 serv.SetPathRawData(datapath);
1240 serv.SetPathSequences(sequpath);
1241 return serv.Build(day);
1242}
1243
1244//
1245// Build Sequences for all Nights
1246//
1247int buildsequenceentries(TString datapath, TString sequpath, Int_t tel=1, Bool_t dummy=kTRUE)
1248{
1249 SequenceBuild serv(tel, "sql.rc");
1250 if (!serv.IsConnected())
1251 {
1252 cout << "ERROR - Connection to database failed." << endl;
1253 return 0;
1254 }
1255
1256 cout << "buildsequenceentries" << endl;
1257 cout << "--------------------" << endl;
1258 cout << endl;
1259 cout << "Connected to " << serv.GetName() << endl;
1260 cout << "DataPath: " << datapath << endl;
1261 cout << "SeqPath: " << sequpath << endl;
1262 cout << "Telescope: " << tel << endl;
1263 cout << endl;
1264
1265 serv.SetIsDummy(dummy);
1266 serv.SetPathRawData(datapath);
1267 serv.SetPathSequences(sequpath);
1268 return serv.Build();
1269}
1270
1271int buildsequenceentries(Int_t tel=1, Bool_t dummy=kTRUE)
1272{
1273 return buildsequenceentries("", "", tel, dummy);
1274}
1275
1276int buildsequenceentries(TString day, Int_t tel=1, Bool_t dummy=kTRUE)
1277{
1278 return buildsequenceentries(day, "", "", tel, dummy);
1279}
Note: See TracBrowser for help on using the repository browser.