source: tags/Mars-V1.1/datacenter/macros/buildsequenceentries.C

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