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

Last change on this file since 9108 was 9108, 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, 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)
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 // Send query
903 TSQLResult *res = Query(query);
904 if (!res)
905 return 2;
906
907 // Get String containing the sequence of P-,C- and D-Runs
908 // and an array with the corresponding run-numbers
909 TArrayI runs;
910 const TString str = PrepareString(*res, runs);
911
912 delete res;
913
914 // Check if the prepared string at least contains one run of each type
915 if (!HasAtLeastOne(str, "PCD"))
916 {
917 PrintResidual(runstart, runstop, str, "Block");
918 return kTRUE;
919 }
920
921 // Start the sequence building
922 // ---------------------------
923
924 Int_t pos = 0; // Position in the string
925 TExMap map; // Map for resulting sequences
926 TString residual; // Unsequences "characters"
927
928 // Step through the string one character by one
929 cout << " ";
930 while (pos<str.Length())
931 {
932 Bool_t found = kFALSE;
933
934 // Loop over the predefined regular expressions
935 TIter Next(&fListRegexp);
936 Rule *obj = 0;
937 while ((obj=(Rule*)Next()))
938 {
939 // Check if regular expressions matchs
940 const Ssiz_t len = obj->Match(str, pos, runs[pos]);
941 if (len>0)
942 {
943 // In case of match get the substring which
944 // defines the sequence and print it
945 TString sub = str(pos, len);
946 sub.ToUpper();
947 cout << runs[pos]<<":"<< sub << "|";
948
949 // Add the first and last run of the sequence to the map
950 map.Add(runs[pos], runs[pos+len-1]);
951
952 // A sequence was found...
953 found = kTRUE;
954
955 // step forward in the string by the length of the sequence
956 pos += len;
957 break;
958 }
959 }
960
961 // If a sequence was found go on...
962 if (found)
963 continue;
964
965 // print unsequenced characters
966 cout << (char)tolower(str[pos]);
967
968 // Count the number of "characters" not sequenced
969 residual += str[pos];
970
971 // step one character forward
972 pos++;
973 }
974 cout << endl;
975
976 PrintResidual(runstart, runstop, residual, "Runs ");
977
978 // Create all sequences which were previously found
979 Long_t first, last;
980 TExMapIter iter(&map);
981 while (iter.Next(first, last))
982 if (CreateSequence(first, last)==2)
983 return 2;
984
985 return kTRUE;
986 }
987
988 Char_t RunType(Int_t n) const
989 {
990 switch (n)
991 {
992 case 2: return 'D';
993 case 3: return 'P';
994 case 4: return 'C';
995 }
996 return '-';
997 }
998 Char_t RunType(const char *str) const
999 {
1000 return RunType(atoi(str));
1001 }
1002
1003 Int_t BuildBlocks(TSQLResult *res, TExMap &blocks)
1004 {
1005 // col key content
1006 // -----------------------------
1007 // 0 - runnumber
1008 // 1 0 RunTypeKEY
1009 // 2 1 source
1010 // 3 2 project
1011 // . .
1012 // . .
1013 // . . from transition.txt
1014 //
1015
1016 //build blocks of runs, which have the same values
1017 //for each block the first and the last run are stored in a TExMap
1018 //the values are checked with the help of an array of TStrings
1019 Long_t runstart = -1;
1020 Long_t runstop = -1;
1021
1022 const UInt_t ncols = res->GetFieldCount();
1023
1024 TString keys[ncols]; // Index 0 is not used (Index 1: RunType)
1025
1026 // Loop over runs
1027 TSQLRow *row=0;
1028 while ((row=res->Next()))
1029 {
1030 // This is the runnumber of the first run in the new block
1031 if (runstart<0)
1032 runstart=atoi((*row)[0]);
1033
1034 // Check which transitions might be allowed for this run and
1035 // which are not. Check also which attributes should be ignored
1036 // for this run. The information about it is stored in the map.
1037 Int_t rc[ncols];
1038 for (UInt_t i=2; i<ncols; i++)
1039 rc[i] = CheckTransition(*res, keys, *row, i);
1040
1041 for (UInt_t i=2; i<ncols; i++)
1042 {
1043 switch (rc[i])
1044 {
1045 case kTRUE: // Transition allowed, switch to new attribute
1046 keys[i] = (*row)[i];
1047 continue;
1048
1049 case -1: // Ignore attribute, continue with next one
1050 //if (keys[i] == (*row)[i])
1051 // break; // Only ignore it if it is really different
1052 continue;
1053
1054 case kFALSE: // No decision (nothing matching found in map)
1055 break; // go on checking
1056
1057 }
1058
1059 // If past-attribute is not yet initialized, do it now.
1060 if (keys[i].IsNull())
1061 keys[i] = (*row)[i];
1062
1063 // Check whether key has changed for this run
1064 // (this condition is never true for the first run)
1065 // This condition in only reached if keys[i] was initialized
1066 if (keys[i] == (*row)[i])
1067 continue;
1068
1069 // Found one block with unique keys, fill values into TExMap
1070 // (except if this is the first run processed)
1071 cout << endl;
1072 cout << " - Identical conditions from " << runstart << " to " << runstop << endl;
1073 blocks.Add((ULong_t)blocks.GetSize(), runstart, runstop);
1074 if (SplitBlock(runstart, runstop)==2)
1075 return 2;
1076 cout << " - Transition from " << RunType(keys[1]) << ":";
1077 cout << QueryNameOfKey(res->GetFieldName(i), keys[i]) << " <" << keys[i] << "> to " << RunType((*row)[1]) << ":";
1078 cout << QueryNameOfKey(res->GetFieldName(i), (*row)[i]) << " <" << (*row)[i] << ">";
1079 cout << " in " << res->GetFieldName(i) << " of " << (*row)[0] << endl;
1080
1081 // This is already the first run of the new block
1082 runstart=atoi((*row)[0]);
1083
1084 // These are the keys corresponding to the first run
1085 // in the new block. All following runs should have
1086 // identical keys. Do not set the attribute if for
1087 // this attribute the transition check evaluated
1088 // to "ignore".
1089 for (UInt_t j=2; j<ncols; j++)
1090 keys[j] = rc[j]==-1 ? "" : (*row)[j];
1091
1092 break;
1093 }
1094
1095 keys[1] = (*row)[1]; // Remember run type for next run
1096
1097 // This is the new runnumber of the last run in this block
1098 runstop=atoi((*row)[0]);
1099 }
1100
1101 // If runstart==-1 a possible block would contain a single run...
1102 if (runstart>0 && runstart!=runstop)
1103 {
1104 cout << " - Identical conditions from " << runstart << " to " << runstop << " (last run)" << endl;
1105 //fill values into TExMap (last value)
1106 blocks.Add((ULong_t)blocks.GetSize(), runstart, runstop);
1107 if (SplitBlock(runstart, runstop)==2)
1108 return 2;
1109 }
1110 cout << "Done." << endl << endl;
1111
1112 return kTRUE;
1113 }
1114
1115public:
1116 SequenceBuild(Int_t tel=1, const char *rc="sql.rc") : MSQLMagic(rc), fTelescopeNumber(tel)
1117 {
1118 fListRegexp.SetOwner();
1119
1120 // FIXME: THIS IS NOT YET HANDLED
1121 if (ReadResources("resources/sequences.rc"))
1122 return;
1123 }
1124
1125 SequenceBuild(TEnv &env, Int_t tel=1) : MSQLMagic(env), fTelescopeNumber(tel)
1126 {
1127 fListRegexp.SetOwner();
1128
1129 // FIXME: THIS IS NOT YET HANDLED
1130 if (ReadResources("resources/sequences.rc"))
1131 return;
1132 }
1133 ~SequenceBuild()
1134 {
1135 fMap.DeleteAll();
1136 }
1137
1138 void SetPathRawData(const char *path) { fPathRawData=path; }
1139 void SetPathSequences(const char *path) { fPathSequences=path; }
1140
1141 int Build(TString day)
1142 {
1143 cout << endl;
1144 cout << "Night of sunrise at " << day << ":" << endl;
1145
1146 day += " 13:00:00";
1147 const TString cond =
1148 Form("(fRunStart>ADDDATE(\"%s\", INTERVAL -1 DAY) AND fRunStart<\"%s\") "
1149 "AND fExcludedFDAKEY=1 AND fRunTypeKEY BETWEEN 2 AND 4 "
1150 "AND fTelescopeNumber=%d ",
1151 day.Data(), day.Data(), fTelescopeNumber);
1152
1153 //query all sources observed in this night
1154 const TString elts = GetELTSource(cond);
1155 if (elts.IsNull())
1156 return 2;
1157
1158 //query all project names observed in this night
1159 const TString eltp2 = GetELTProject(cond);
1160 if (elts.IsNull())
1161 return 2;
1162
1163 // Setup query to get all values from the database,
1164 // that are relevant for building sequences
1165 TString query("SELECT fRunNumber*1000+fFileNumber AS Id, fRunTypeKEY, ");
1166 query += elts;
1167 query += ", ";
1168 query += eltp2;
1169
1170 // Now add all entries from the transition table to the query
1171 TIter NextPair(&fMap);
1172 TObject *mapkey = 0;
1173 while ((mapkey=(TPair*)NextPair()))
1174 if (!query.Contains(mapkey->GetName()))
1175 {
1176 query += ", ";
1177 query += mapkey->GetName();
1178 }
1179 query += Form(" FROM RunData WHERE %s ORDER BY Id", cond.Data());
1180
1181 TSQLResult *res = Query(query);
1182 if (!res)
1183 return 2;
1184
1185 TExMap blocks;
1186 const Int_t rc = BuildBlocks(res, blocks);
1187 delete res;
1188
1189 return rc;
1190 }
1191
1192 Int_t Build()
1193 {
1194 //get all dates from the database
1195 TSQLResult *res = Query("SELECT fDate FROM SequenceBuildStatus ORDER BY fDate DESC");
1196 if (!res)
1197 return 2;
1198
1199 //execute buildsequenceentries for all dates
1200 TSQLRow *row=0;
1201 while ((row=res->Next()))
1202 Build((*row)[0]);
1203
1204 delete res;
1205
1206 return 1;
1207 }
1208 ClassDef(SequenceBuild, 0)
1209};
1210
1211ClassImp(SequenceBuild);
1212
1213int buildsequenceentries(TString day, TString datapath, TString sequpath, Int_t tel=1, Bool_t dummy=kTRUE)
1214{
1215 SequenceBuild serv(tel, "sql.rc");
1216 if (!serv.IsConnected())
1217 {
1218 cout << "ERROR - Connection to database failed." << endl;
1219 return 0;
1220 }
1221
1222 cout << "buildsequenceentries" << endl;
1223 cout << "--------------------" << endl;
1224 cout << endl;
1225 cout << "Connected to " << serv.GetName() << endl;
1226 if (!datapath.IsNull())
1227 cout << "DataPath: " << datapath << endl;
1228 if (!sequpath.IsNull())
1229 cout << "SeqPath: " << sequpath << endl;
1230 cout << "Day: " << day << endl;
1231 cout << "Telescope: " << tel << endl;
1232 cout << endl;
1233
1234 serv.SetIsDummy(dummy);
1235 serv.SetPathRawData(datapath);
1236 serv.SetPathSequences(sequpath);
1237 return serv.Build(day);
1238}
1239
1240//
1241// Build Sequences for all Nights
1242//
1243int buildsequenceentries(TString datapath, TString sequpath, Int_t tel=1, Bool_t dummy=kTRUE)
1244{
1245 SequenceBuild serv(tel, "sql.rc");
1246 if (!serv.IsConnected())
1247 {
1248 cout << "ERROR - Connection to database failed." << endl;
1249 return 0;
1250 }
1251
1252 cout << "buildsequenceentries" << endl;
1253 cout << "--------------------" << endl;
1254 cout << endl;
1255 cout << "Connected to " << serv.GetName() << endl;
1256 cout << "DataPath: " << datapath << endl;
1257 cout << "SeqPath: " << sequpath << endl;
1258 cout << "Telescope: " << tel << endl;
1259 cout << endl;
1260
1261 serv.SetIsDummy(dummy);
1262 serv.SetPathRawData(datapath);
1263 serv.SetPathSequences(sequpath);
1264 return serv.Build();
1265}
1266
1267int buildsequenceentries(Int_t tel=1, Bool_t dummy=kTRUE)
1268{
1269 return buildsequenceentries("", "", tel, dummy);
1270}
1271
1272int buildsequenceentries(TString day, Int_t tel=1, Bool_t dummy=kTRUE)
1273{
1274 return buildsequenceentries(day, "", "", tel, dummy);
1275}
Note: See TracBrowser for help on using the repository browser.