BmnRoot 26.10.0-233-gb9bbe585
Software framework of the BM@N experiment
Loading...
Searching...
No Matches
TangoData.cxx
Go to the documentation of this file.
1#include "TangoData.h"
2
3#include "TColor.h"
4#include "TROOT.h"
5#include "TRandom.h"
6#include "TangoConnection.h"
7#include "UniRun.h"
8
9#include <TAxis.h>
10#include <TCanvas.h>
11#include <TGraph.h>
12#include <TGraph2D.h>
13#include <TH2D.h>
14#include <TLegend.h>
15#include <TMultiGraph.h>
16#include <TSQLServer.h>
17#include <TSQLStatement.h>
18#include <TStyle.h>
19#include <algorithm>
20#include <cctype>
21#include <cmath>
22#include <fstream>
23#include <iostream>
24using namespace std;
25
26// Tango Database connection based on MySQL before 2020-03-24
27const char* const TANGO_DB_USERNAME_b2020 = "tango";
28const char* const TANGO_DB_PASSWORD_b2020 = "tangompd";
29const char* const TANGO_DB_HOST_b2020 = "10.18.11.66";
30const char* const TANGO_DB_NAME_b2020 = "hdbpp";
31
33
39
40// Copy constructor
49
51
53
54TangoTimeInterval::TangoTimeInterval(TDatime start_time_interval, TDatime end_time_interval)
55{
56 start_time = start_time_interval;
57 end_time = end_time_interval;
58}
59
61
62/**
63 * TangoData CLASS IMPLEMENTATION
64 **/
65
66/** Single Constructor: fill Tango data array according to the given parameters
67 * Tango database connection is defined in the 'tango_db_settings.h' file
68 * Parameters:
69 * start_date - time from which to start reading the parameter, format: "YYYY-MM-DD HH:MM:SS"
70 * (e.g. "2015-03-13 23:00:00")
71 * end_date - end time of reading the parameter, the same format (e.g. "2015-03-13 24:00:00")
72 * system_name - name of the system, i.e. Tango domain (e.g. "magnet", "fhcal" or "gem")
73 * parameter_name - name of hardware parameter stored in Tango, i.e. Tango attribute
74 * (e.g. "vch_2_1" for FHCal or "vmon_0" for GEM)
75 * member_name - name of the Tango member, i.e. device (e.g. "hv_1" for FHCal or "mod_0" for GEM),
76 * it can be given with the Tango family as "family/member" if the member name is not unique
77 * in the domain (e.g. "caen_232/mod_2" for CSC or "plane1_top/adcsc_7_temp" for FSD),
78 * empty string - the member is not used
79 **/
80TangoData::TangoData(const char* start_date,
81 const char* end_date,
82 const char* system_name,
83 const char* parameter_name,
84 const char* member_name,
85 int verbose)
86 : strSystemName(system_name)
87 , strParameterName(parameter_name)
88 , strMemberName(member_name)
89 , strUserName("")
90 , strStartDate(start_date)
91 , strEndDate(end_date)
92 , iVerbose(verbose)
93{
95}
96
97/** Run Range Constructor: fill Tango data array for the time interval from the start time of the first run
98 * to the end time of the last run of the given range (the gaps between runs are included)
99 * The run times are taken from the Unified Condition Database (UniRun)
100 * Parameters:
101 * period_number - period (session) number of the runs (e.g. 8)
102 * start_run - number of the first run of the range (e.g. 6000)
103 * end_run - number of the last run of the range (set equal to start_run to read a single run)
104 * system_name, parameter_name, member_name, verbose - the same as in the time interval constructor
105 * Use GetRunAverageTangoData() to average the parameter only over the time of the runs
106 **/
107TangoData::TangoData(int period_number,
108 int start_run,
109 int end_run,
110 const char* system_name,
111 const char* parameter_name,
112 const char* member_name,
113 int verbose)
114 : strSystemName(system_name)
115 , strParameterName(parameter_name)
116 , strMemberName(member_name)
117 , strUserName("")
118 , iVerbose(verbose)
119 , iPeriodNumber(period_number)
120 , iStartRun(start_run)
121 , iEndRun(end_run)
122{
123 if (SetRunRangeDates(period_number, start_run, end_run) == 0)
125}
126
128{
129 if (arrTangoData != nullptr) {
130 arrTangoData->Delete();
131 delete arrTangoData;
132 }
133}
134
136{
137 TString strFullName = strSystemName + ":" + strParameterName;
138 if (strMemberName != "")
139 strFullName += " (" + strMemberName + ")";
140
141 return strFullName;
142}
143
144// non-user function SetRunRangeDates sets strStartDate and strEndDate to the start time of the first run
145// and the end time of the last run existing in the given run range of the period,
146// and fills vecRunIntervals with the time intervals of the runs (runs without end time are skipped)
147// Returns: 0 - in case of the success, < 0 - if an error occured
148// the last successfully read run range is cached to avoid repeated requests to the Unified Database,
149// e.g. when many Tango parameters are read for the same runs
152static vector<TangoTimeInterval> cached_run_intervals;
153
154int TangoData::SetRunRangeDates(int period_number, int start_run, int end_run)
155{
156 vecRunIntervals.clear();
157 if (start_run > end_run) {
158 cout << "ERROR: start run (" << start_run << ") cannot be greater than end run (" << end_run << ")" << endl;
159 return -1;
160 }
161
162 if ((period_number == cached_period) && (start_run == cached_start_run) && (end_run == cached_end_run)) {
166 if (iVerbose)
167 cout << "Run range " << period_number << ":" << start_run << "-" << end_run
168 << " (from the cache) corresponds"
169 << " to the time " << strStartDate << " - " << strEndDate << endl;
170 return 0;
171 }
172
173 // get runs existing in the database for the given range (run numbers can have gaps)
174 UniqueRunNumber* run_numbers = nullptr;
175 int run_count = UniRun::GetRunNumbers(run_numbers, period_number, start_run, period_number, end_run);
176 if (run_count < 0) {
177 cout << "ERROR: getting run numbers from the Unified Database has been failed" << endl;
178 return -2;
179 }
180 if (run_count == 0) {
181 delete[] run_numbers;
182 cout << "ERROR: there are no runs in the range " << period_number << ":" << start_run << "-" << end_run
183 << " in the Unified Database" << endl;
184 return -3;
185 }
186 int first_run = run_numbers[0].run_number, last_run = run_numbers[run_count - 1].run_number;
187
188 // get start and end times of every run in the range
189 TString start_date, end_date;
190 for (int i = 0; i < run_count; i++) {
191 int run_number = run_numbers[i].run_number;
192 UniRun* pRun = UniRun::GetRun(period_number, run_number);
193 if (pRun == nullptr) {
194 cout << "ERROR: run " << period_number << ":" << run_number << " was not found in the Unified Database"
195 << endl;
196 delete[] run_numbers;
197 vecRunIntervals.clear();
198 return -4;
199 }
200 TDatime run_start = pRun->GetStartDatetime();
201 TDatime* run_end = pRun->GetEndDatetime();
202 delete pRun;
203 if (i == 0)
204 start_date = run_start.AsSQLString();
205
206 if (run_end == nullptr) {
207 // the end time of the last run defines the end of the whole time interval
208 if (i == run_count - 1) {
209 cout << "ERROR: there is no end time for the last run " << period_number << ":" << run_number
210 << " in the Unified Database" << endl;
211 delete[] run_numbers;
212 vecRunIntervals.clear();
213 return -5;
214 }
215 cout << "WARNING: there is no end time for the run " << period_number << ":" << run_number
216 << " in the Unified Database, it is excluded from the run time intervals" << endl;
217 continue;
218 }
219 if (i == run_count - 1)
220 end_date = run_end->AsSQLString();
221
222 vecRunIntervals.push_back(TangoTimeInterval(run_start, *run_end));
223 delete run_end;
224 }
225 delete[] run_numbers;
226
227 strStartDate = start_date;
228 strEndDate = end_date;
229 if (iVerbose)
230 cout << "Run range " << period_number << ":" << first_run << "-" << last_run << " (" << run_count
231 << " runs) corresponds to the time " << strStartDate << " - " << strEndDate << endl;
232
233 cached_period = period_number, cached_start_run = start_run, cached_end_run = end_run;
236
237 return 0;
238}
239
240// non-user function InitTangoData selects the Tango database (MySQL before 2020-03-25, PgSQL after)
241// by the start date and fills the Tango data array
243{
244 if (strcmp(strStartDate.Data(), "2020-03-25") < 0) {
245 IsOldMySQL = true;
246 if (iVerbose)
247 cout << "Old MySQL Database is used to get Tango data" << endl;
248 } else if (iVerbose)
249 cout << "PostgreSQL Database is used to get Tango data" << endl;
250
252}
253
254// non-user function GetTangoParameter gets hardware data from the Tango database and write to the arrTangoData
255// First, name of the target table with required parameter is extracted from the Tango Base Table,
256// then required data are selected from the target table corresponding the given time interval.
257// Returns: 0 - in case of the success, < 0 - if an error occured
259{
260 if (iVerbose)
261 cout << "Input Start Date = " << strStartDate.Data() << endl;
262 if (iVerbose)
263 cout << "Input End Date = " << strEndDate.Data() << endl;
264 if ((strStartDate == "") || (strEndDate == "")) {
265 cout << "ERROR: start datetime and end datetime should not be empty!" << endl;
266 return -1;
267 }
268 if (strStartDate < "2000-01-01") {
269 cout << "ERROR: start date cannot be less than 2000 year" << endl;
270 return -2;
271 }
272
273 // new start and end datetime with time zone if PgSQL
274 TString start_date_new(strStartDate), end_date_new(strEndDate);
275 if (!IsOldMySQL)
276 start_date_new += " Europe/Moscow", end_date_new += " Europe/Moscow";
277
278 // TANGO database connection (MySQL before 2020-03-24 and PgSQL after)
279 TangoConnection* connDb = nullptr;
280 if (IsOldMySQL)
283 else
284 connDb = TangoConnection::Open();
285 if (connDb == nullptr)
286 return -3;
287 TSQLServer* db_server = connDb->GetSQLServer();
288 if (db_server == nullptr)
289 return -4;
290
291 if (db_server->GetTables(db_server->GetDB()) == nullptr)
292 return -5;
293
294 // searching for a table name with corresponding parametter type, where the parameter with given system and
295 // parameter names is stored Statement returns parameter ID and parameter table
296 TString strStatement;
297 if (IsOldMySQL)
298 strStatement = TString::Format(
299 "SELECT att_conf_id, data_type "
300 "FROM att_conf ac join att_conf_data_type acdt on ac.att_conf_data_type_id = acdt.att_conf_data_type_id "
301 "WHERE family='%s' and name='%s' ",
302 strSystemName.Data(), strParameterName.Data());
303 else {
304 strStatement = TString::Format("SELECT att_conf_id, table_name "
305 "FROM att_conf "
306 "WHERE domain='%s' and name='%s' ",
307 strSystemName.Data(), strParameterName.Data());
308 // the member name can be given with the family as "family/member" if the member name is not unique
309 // in the domain (e.g. "caen_232/mod_2" and "caen_240/mod_2" for CSC)
310 TString family_name(""), member_name(strMemberName);
311 Ssiz_t slash_pos = strMemberName.First('/');
312 if (slash_pos != kNPOS) {
313 family_name = strMemberName(0, slash_pos);
314 member_name = strMemberName(slash_pos + 1, strMemberName.Length() - slash_pos - 1);
315 }
316 if (family_name != "")
317 strStatement += TString::Format("and family = '%s' ", family_name.Data());
318 if (member_name != "")
319 strStatement += TString::Format("and member = '%s' ", member_name.Data());
320 strStatement += "ORDER BY att_conf_id";
321 }
322
323 if (iVerbose)
324 cout << "Processing the following SQL request to get info on the Tango parameter:" << endl
325 << strStatement << endl;
326 TSQLStatement* stmt_select = db_server->Statement(strStatement);
327 if (!stmt_select->Process()) {
328 cout << "ERROR: getting info on parameter from Tango has been failed: " << GetFullName() << endl;
329 delete stmt_select;
330 return -6;
331 }
332
333 stmt_select->StoreResult();
334 if (!stmt_select->NextResultRow()) {
335 cout << "ERROR: There is no Tango parameter '" << GetFullName() << endl;
336 delete stmt_select;
337 return -7;
338 }
339 // Tango team duplicated (old MySQL solution) parameters for every Nuclotron session
340 if ((IsOldMySQL) && (stmt_select->GetNumAffectedRows() > 1) && (strcmp(strEndDate.Data(), "2018-01-01") > 0)) {
341 if (!stmt_select->NextResultRow()) {
342 cout << "ERROR: There is no second row for parameter '" << strParameterName << "' for " << strSystemName
343 << " detector" << endl;
344 delete stmt_select;
345 return -8;
346 }
347 }
348
349 int parameter_id = stmt_select->GetInt(0);
350 TString table_name(stmt_select->GetString(1));
351 // several Tango parameters can correspond to the given names, e.g. the same member name in different families
352 if ((!IsOldMySQL) && (stmt_select->NextResultRow()))
353 cout << "WARNING: several Tango parameters correspond to '" << GetFullName()
354 << "', the first one is used. Specify the family in the member name as \"family/member\"" << endl;
355 if (IsOldMySQL)
356 table_name = TString::Format("att_%s", table_name.Data());
357 if (iVerbose)
358 cout << "Found Data Table name = " << table_name << ". Parameter ID = " << parameter_id << endl;
359 delete stmt_select;
360
361 // parse parameter type. current support for att_array_devdouble, att_array_devboolean, att_scalar_devdouble,
362 // att_scalar_devboolean and integer types read as numeric values: att_scalar_devshort, att_scalar_devlong,
363 // att_scalar_devlong64 and att_scalar_devstate
364 Tango_Parameter_Type par_type;
365 if (table_name.Contains("array_devdouble"))
366 par_type = Tango_Double_Array;
367 else if (table_name.Contains("array_devboolean"))
368 par_type = Tango_Bool_Array;
369 else if (table_name.Contains("scalar_devdouble") || table_name.Contains("scalar_devshort")
370 || table_name.Contains("scalar_devlong") || table_name.Contains("scalar_devstate"))
371 par_type = Tango_Double;
372 else if (table_name.Contains("scalar_devboolean"))
373 par_type = Tango_Bool;
374 else {
375 cout << "ERROR: This Tango type is not supported: '" << table_name << "'" << endl;
376 return -9;
377 }
378
379 // getting data from the table found by the attribute type
380 TString array_columns = (par_type > 10) ? ", dim_x_r, dim_x_w, idx" : ""; // if the parameter is an array
381 TString query_data;
382 if (IsOldMySQL) {
383 query_data = "SELECT date_format(data_time, '%Y-%m-%d %H:%i:%S'), value_r" + array_columns + " ";
384 // add a new point with the previous value (<=date_start)
385 query_data +=
386 TString::Format("FROM %s "
387 "WHERE att_conf_id='%d' and ((data_time > '%s' and data_time <= '%s') "
388 "or (data_time = (SELECT max(data_time) FROM %s WHERE att_conf_id='%d' and data_time "
389 "<= '%s' and value_r is not null))) "
390 "and value_r is not null ",
391 table_name.Data(), parameter_id, start_date_new.Data(), end_date_new.Data(),
392 table_name.Data(), parameter_id, start_date_new.Data());
393 } else {
394 // the values of the time interval and the previous value (<=date_start) are selected by two separate parts
395 // joined by UNION ALL: if both conditions are joined by 'or' in one query (even with LIMIT 1 instead of
396 // max(data_time)), the PgSQL server unpacks the whole compressed history of the parameter (~1.4 s).
397 // The previous value is found by 'ORDER BY data_time DESC LIMIT 1', but without a lower time limit the server
398 // unpacks the whole history before date_start (~0.27 s), so the value is searched first within one day
399 // before date_start (~0.05 s for the whole query), and the search without the limit is executed by COALESCE
400 // only if there is no value within the day. COALESCE is wrapped in a subquery, because the condition
401 // 'data_time = COALESCE(...)' prevents the server from excluding the chunks of the table (~1.4 s again)
402 const int search_window_sec = 24 * 3600;
403 TDatime search_start(TDatime(strStartDate.Data()).Convert() - search_window_sec);
404 TString search_start_date = TString(search_start.AsSQLString()) + " Europe/Moscow";
405 TString prev_time_query = TString::Format("SELECT data_time FROM %s WHERE att_conf_id='%d' and data_time <= "
406 "'%s' and value_r is not null ",
407 table_name.Data(), parameter_id, start_date_new.Data());
408 query_data = TString::Format(
409 "SELECT to_char(data_time, 'YYYY-MM-DD HH24:MI:SS.MS'), value_r%s "
410 "FROM ((SELECT data_time, value_r%s FROM %s "
411 "WHERE att_conf_id='%d' and value_r is not null and data_time = (SELECT COALESCE("
412 "(%sand data_time > '%s' ORDER BY data_time DESC LIMIT 1), "
413 "(%sORDER BY data_time DESC LIMIT 1)))) "
414 "UNION ALL "
415 "(SELECT data_time, value_r%s FROM %s "
416 "WHERE att_conf_id='%d' and value_r is not null and data_time > '%s' and data_time <= '%s')) "
417 "AS tango_values ",
418 array_columns.Data(), array_columns.Data(), table_name.Data(), parameter_id, prev_time_query.Data(),
419 search_start_date.Data(), prev_time_query.Data(), array_columns.Data(), table_name.Data(), parameter_id,
420 start_date_new.Data(), end_date_new.Data());
421 }
422
423 if (par_type > 10) // if the parameter is stored as array of values
424 query_data += "ORDER BY data_time,idx";
425 else
426 query_data += "ORDER BY data_time";
427
428 if (iVerbose)
429 cout << "Query data with the following SQL request:" << endl << query_data << endl;
430 stmt_select = db_server->Statement(query_data);
431 if (!stmt_select->Process()) {
432 cout << "ERROR: getting parameter values from Tango has been failed" << endl;
433 delete stmt_select;
434 return -10;
435 }
436
437 stmt_select->StoreResult();
438
439 Int_t cur_num = 0;
440 TangoTimeParameter* par = nullptr;
441 // create Tango data array and write data to it
442 arrTangoData = new TObjArray();
443 arrTangoData->SetName(
444 TString::Format("'%s' parameter for %s detector", strParameterName.Data(), strSystemName.Data()));
445 arrTangoData->SetOwner(kTRUE);
446 while (stmt_select->NextResultRow()) {
447 const char* pc_datetime = stmt_select->GetString(0);
448 TDatime datetime(pc_datetime);
449 // shift the previous time va;ue to the date_start position
450 if ((cur_num == 0) && (strcmp(pc_datetime, strStartDate) < 0))
451 datetime.Set(strStartDate);
452
453 int i_par_len = 1;
454 if (par_type > 10)
455 i_par_len = stmt_select->GetInt(2);
456 if (i_par_len == 0) {
457 cout << "ERROR: Parameter length cannot be equal 0" << endl;
458 delete stmt_select;
460 return -11;
461 }
462
463 int i_real_par_len = 1;
464 if (par_type > 10)
465 i_real_par_len = stmt_select->GetInt(3);
466 if (i_real_par_len == 0) {
467 cout << "ERROR: Real parameter length cannot be equal 0" << endl;
468 delete stmt_select;
470 return -12;
471 }
472
473 par = new TangoTimeParameter(datetime, par_type);
474 // cout<<par.parameter_time.AsString()<<endl;
475 for (int ind = 0; ind < i_par_len; ind++) {
476 if (ind > 0)
477 stmt_select->NextResultRow();
478
479 int i_idx = 0;
480 if (par_type > 10)
481 i_idx = stmt_select->GetInt(4);
482 // cout<<"idx:ind - "<<idx<<":"<<ind<<endl;
483 if (i_idx != ind) {
484 cout << "ERROR: idx should be equal index of the parameter array" << endl;
485 delete stmt_select;
487 return -13;
488 }
489
490 if (ind >= i_real_par_len)
491 continue;
492
493 if ((par_type == Tango_Bool_Array) || (par_type == Tango_Bool)) {
494 // boolean value is returned as a number by MySQL and as "t" or "f" by PgSQL
495 TString str_val = stmt_select->GetString(1);
496 bool b_val = (str_val == "t") || (str_val == "true") || (str_val.Atoi() != 0);
497 par->bool_parameter_value.push_back(b_val);
498 par->double_parameter_value.push_back(b_val);
499 // cout<<par.bool_parameter_value[par.bool_parameter_value.size()-1]<<endl;
500 } else {
501 double d_val = stmt_select->GetDouble(1);
502 par->double_parameter_value.push_back(d_val);
503 // cout<<par.double_parameter_value[par.double_parameter_value.size()-1]<<endl;
504 }
505 }
506 if (iVerbose)
507 cout << "Boolean parameter value size = " << par->bool_parameter_value.size() << endl;
508 if (iVerbose)
509 cout << "Double parameter value size = " << par->double_parameter_value.size() << endl;
510
511 arrTangoData->Add(par);
512 cur_num++;
513 }
514 delete stmt_select;
515
516 // add date_end point (if not exists) equal to the the previous value
517 // (the last archived value is extended even if the archiving was stopped before date_end)
518 if ((par != nullptr) && (strcmp(par->parameter_time.AsSQLString(), strEndDate.Data()) < 0)) {
519 TangoTimeParameter* par_last = new TangoTimeParameter(*par);
520 par_last->parameter_time.Set(strEndDate);
521 arrTangoData->Add(par_last);
522 }
523
524 return 0;
525}
526
527// Function displays hardware data obtained from Tango, e.g. FHCal voltage in time interval, in console
529{
530 if (arrTangoData == nullptr) {
531 cout << "ERROR: Tango parameter has not been obtained" << endl;
532 return;
533 }
534
535 int def_precision = cout.precision();
536 cout.precision(17);
537
538 int par_length = 0;
539 for (int i = 0; i < arrTangoData->GetEntriesFast(); i++) {
541 cout << pParameter->parameter_time.AsSQLString() << endl;
542
543 // cout<<TD->dataArray[i].parameter_length<<endl;
544 par_length = pParameter->double_parameter_value.size();
545 for (int j = 0; j < par_length; j++)
546 cout << pParameter->double_parameter_value[j] << " ";
547 cout << "" << endl << endl;
548 }
549
550 cout.precision(def_precision);
551 return;
552}
553
554// Function displays a set of "simple" parameters obtained from Tango, e.g. GEMs high voltages voltage, in console
555void TangoData::PrintTangoArrayConsole(vector<TangoData*> vecTangoData)
556{
557 for (const auto& tango_data : vecTangoData) {
558 cout << "The current parameter: " << tango_data->GetFullName() << endl;
559 tango_data->PrintTangoDataConsole();
560 }
561}
562
563// non-user function GetSourceName returns "domain_member" of the Tango parameter or "domain" if the member is not set
564static TString GetSourceName(TangoData* pTangoData)
565{
566 TString source_name = pTangoData->GetSystemName();
567 if (pTangoData->GetMemberName() != "")
568 source_name += "_" + pTangoData->GetMemberName();
569 return source_name;
570}
571
572// non-user function GetRangeSuffix returns the range of the Tango parameter:
573// for the Run Range Constructor - the period and run range "_p<period>_r<start>_<end>"
574// (e.g. "_p9_r9696_9730", or "_p9_r9696" for a single run),
575// for the time interval - the start and end dates "_t<YYYYMMDD>_<HHMM>_<YYYYMMDD>_<HHMM>"
576// (e.g. "_t20250301_1000_20250301_1600")
578{
579 if (pTangoData->GetPeriodNumber() >= 0) {
580 TString run_suffix = TString::Format("_p%d_r%d", pTangoData->GetPeriodNumber(), pTangoData->GetStartRun());
581 if (pTangoData->GetEndRun() != pTangoData->GetStartRun())
582 run_suffix += TString::Format("_%d", pTangoData->GetEndRun());
583 return run_suffix;
584 }
585
586 if ((pTangoData->GetStartDate() == "") || (pTangoData->GetEndDate() == ""))
587 return "";
588 TDatime start_date(pTangoData->GetStartDate()), end_date(pTangoData->GetEndDate());
589 return TString::Format("_t%d_%04d_%d_%04d", start_date.GetDate(), start_date.GetTime() / 100, end_date.GetDate(),
590 end_date.GetTime() / 100);
591}
592
593// non-user function GetDataName returns the name of the Tango parameter used in the canvas names:
594// "domain_member_attribute" with the run range or time interval (e.g. "fhcal_hv_1_vch_2_1_p9_r9696_9730")
595static TString GetDataName(TangoData* pTangoData)
596{
597 return GetSourceName(pTangoData) + "_" + pTangoData->GetParameterName() + GetRangeSuffix(pTangoData);
598}
599
600// non-user function GetArrayDataName returns the name of the set of Tango parameters used in the canvas names:
601// the name of the first parameter + "_to_" + the name of the last one; if domain, member and ranges of the parameters
602// are the same, only the attribute of the last one is added, e.g. "fhcal_hv_1_vch_2_1_to_vch_2_10_p9_r9696_9730"
603static TString GetArrayDataName(vector<TangoData*>& vecTangoData)
604{
605 TangoData *pFirst = vecTangoData.front(), *pLast = vecTangoData.back();
606 if (vecTangoData.size() == 1)
607 return GetDataName(pFirst);
608
609 if ((GetSourceName(pFirst) == GetSourceName(pLast)) && (GetRangeSuffix(pFirst) == GetRangeSuffix(pLast)))
610 return GetSourceName(pFirst) + "_" + pFirst->GetParameterName() + "_to_" + pLast->GetParameterName()
611 + GetRangeSuffix(pFirst);
612
613 return GetDataName(pFirst) + "_to_" + GetDataName(pLast);
614}
615
616// non-user function GetArrayTitle returns the title of the set of Tango parameters for the graphs:
617// the full names of the first and last parameters and the number of the parameters,
618// e.g. "fhcal:vch_2_1 - vch_2_10 (hv_1), 10 channels" if the system and member are the same,
619// or "gem:vmon_0 (mod_0) - gem:vmon_11 (mod_2), 24 channels"
620static TString GetArrayTitle(vector<TangoData*>& vecTangoData)
621{
622 TangoData *pFirst = vecTangoData.front(), *pLast = vecTangoData.back();
623 if (vecTangoData.size() == 1)
624 return pFirst->GetFullName();
625
626 TString title;
627 if ((pFirst->GetSystemName() == pLast->GetSystemName()) && (pFirst->GetMemberName() == pLast->GetMemberName())) {
628 title = pFirst->GetSystemName() + ":" + pFirst->GetParameterName() + " - " + pLast->GetParameterName();
629 if (pFirst->GetMemberName() != "")
630 title += " (" + pFirst->GetMemberName() + ")";
631 } else
632 title = pFirst->GetFullName() + " - " + pLast->GetFullName();
633
634 return title + TString::Format(", %zu channels", vecTangoData.size());
635}
636
637// non-user function CreateTangoCanvas creates a canvas named by the displayed data and the kind of visualization,
638// e.g. "fhcal_hv_1_vch_2_1_multigraph3d"; a canvas with the same name (the same data and view) is replaced
639static TCanvas* CreateTangoCanvas(TString data_name, TString view_name)
640{
641 TString canvas_name = data_name + "_" + view_name;
642 // only letters, digits and underscores to use the canvas name in the ROOT interpreter
643 for (Ssiz_t i = 0; i < canvas_name.Length(); i++)
644 if (!isalnum(canvas_name[i]))
645 canvas_name[i] = '_';
646
647 return new TCanvas(canvas_name, canvas_name, 800, 600);
648}
649
650// Function displays hardware vector data obtained from Tango, e.g. FHCal voltage in time interval, graphically as 2D
651// Surface Graph Parameter: y_axis - label of Y axis
652void TangoData::PrintTangoDataSurface(const char* y_axis)
653{
654 if (arrTangoData == nullptr) {
655 cout << "ERROR: Tango parameter has not been obtained" << endl;
656 return;
657 }
658
659 TCanvas* c1 = CreateTangoCanvas(GetDataName(this), "surface");
660 TGraph2D* tango_graph = new TGraph2D();
661 tango_graph->SetTitle(arrTangoData->GetName());
662
663 int par_length = 0;
664 for (int i = 0; i < arrTangoData->GetEntriesFast(); i++) {
666
667 par_length = pParameter->double_parameter_value.size();
668 // cout<<"Parameter length = "<<par_length<<endl;
669 for (int j = 0; j < par_length; j++) {
670 int cur_time = pParameter->parameter_time.Convert();
671 double value = pParameter->double_parameter_value[j];
672 // cout<<x<<" "<<y<<" "<<z<<endl;
673 tango_graph->SetPoint(i * par_length + j, cur_time, j + 1, value);
674 }
675 }
676
677 tango_graph->Draw("SURF1");
678 gPad->Update();
679
680 tango_graph->GetXaxis()->SetTitle("time");
681 tango_graph->GetXaxis()->CenterTitle();
682 tango_graph->GetXaxis()->SetTitleOffset(1.9);
683 tango_graph->GetXaxis()->SetLabelSize(0.025);
684 tango_graph->GetXaxis()->SetLabelOffset(0.009);
685 tango_graph->GetXaxis()->SetNdivisions(-503);
686
687 tango_graph->GetYaxis()->SetTitle(y_axis);
688 tango_graph->GetYaxis()->CenterTitle();
689 tango_graph->GetYaxis()->SetTitleOffset(1.9);
690 tango_graph->GetYaxis()->SetLabelSize(0.025);
691 tango_graph->GetYaxis()->SetLabelOffset(0.001);
692 tango_graph->GetYaxis()->CenterLabels();
693 tango_graph->GetYaxis()->SetNdivisions(par_length + 1, 0, 0);
694
695 tango_graph->GetZaxis()->SetLabelSize(0.025);
696
697 // form X-axis with time ticks
698 tango_graph->GetXaxis()->SetTimeDisplay(1);
699 tango_graph->GetXaxis()->SetTimeFormat("%Y.%m.%d %H:%M");
700 tango_graph->GetXaxis()->SetTimeOffset(0, "local");
701
702 c1->Modified();
703
704 return;
705}
706
707// non-user function AddStepPoint adds a new point to the graph drawn as steps: Tango time points are transitions
708// to new values, so the previous value is held (horizontal line) up to the time point of the new value
709static void AddStepPoint(TGraph& graph, double x, double y)
710{
711 int n = graph.GetN();
712 if ((n > 0) && (graph.GetY()[n - 1] != y)) {
713 double previous_y = graph.GetY()[n - 1];
714 graph.SetPoint(n, x, previous_y);
715 n++;
716 }
717 graph.SetPoint(n, x, y);
718}
719
720// Function PrintTangoDataMulti3D display hardware vector data obtained from Tango, e.g. FHCal voltage in time interval,
721// graphically as a set of Line Graphs Parameter: tango_data - TObjArray with TangoTimeParameter objects obtained from
722// 'GetTangoParameter' function
723int TangoData::PrintTangoDataMultiGraph(const char* y_axis, bool is3D)
724{
725 if (arrTangoData == nullptr) {
726 cout << "ERROR: Tango parameter has not been obtained" << endl;
727 return -1;
728 }
729
730 if (arrTangoData->GetEntries() < 1) {
731 cout << "WARNING: There are no elements in the Tango array" << endl;
732 return -2;
733 }
734
735 TCanvas* c1 = CreateTangoCanvas(GetDataName(this), is3D ? "multigraph3d" : "multigraph");
736
737 // cout<<"Tango data array size = "<<arrTangoData->GetEntries()<<endl;
738 int par_length = ((TangoTimeParameter*)arrTangoData->At(0))->double_parameter_value.size();
739 // cout<<"par_length = "<<par_length<<endl;
740 TGraph* tango_graphs = new TGraph[par_length]();
741 gRandom->SetSeed();
742 for (int j = 0; j < par_length; j++) {
743 Int_t color = gRandom->Integer(50);
744 if ((color == 0) || (color == 10) || ((color > 16) && (color < 20)))
745 color += 20;
746 tango_graphs[j].SetLineColor(color);
747 }
748
749 // the 3D view does not support time display, so time is shown in hours from the start date
750 UInt_t start_time = TDatime(strStartDate).Convert();
751 for (int i = 0; i < arrTangoData->GetEntriesFast(); i++) {
753 par_length = pParameter->double_parameter_value.size();
754 for (int j = 0; j < par_length; j++) {
755 UInt_t cur_time = pParameter->parameter_time.Convert();
756 double x = is3D ? ((double)cur_time - start_time) / 3600 : cur_time;
757 double value = pParameter->double_parameter_value[j];
758 AddStepPoint(tango_graphs[j], x, value);
759 }
760 }
761
762 TMultiGraph* tango_multi = new TMultiGraph();
763 tango_multi->SetTitle(arrTangoData->GetName());
764 for (int j = 0; j < par_length; j++) {
765 tango_multi->Add(&tango_graphs[j]);
766 tango_graphs[j].SetTitle(TString::Format("%d", j));
767 tango_graphs[j].SetLineWidth(3);
768 }
769
770 TString draw_par = "AL";
771 if (is3D)
772 draw_par += "3D";
773 tango_multi->Draw(draw_par.Data());
774 gPad->Update();
775
776 if (!is3D) {
777 tango_multi->GetXaxis()->SetTitle("time");
778 tango_multi->GetXaxis()->CenterTitle();
779 tango_multi->GetXaxis()->SetTitleOffset(1.3);
780 tango_multi->GetXaxis()->SetLabelSize(0.025);
781 tango_multi->GetXaxis()->SetLabelOffset(0.009);
782 tango_multi->GetXaxis()->SetNdivisions(-503);
783 // form X-axis with time ticks
784 tango_multi->GetXaxis()->SetTimeDisplay(1);
785 tango_multi->GetXaxis()->SetTimeFormat("%Y.%m.%d %H:%M");
786 tango_multi->GetXaxis()->SetTimeOffset(0, "local");
787
788 tango_multi->GetYaxis()->SetTitle(y_axis);
789 tango_multi->GetYaxis()->CenterTitle();
790 tango_multi->GetYaxis()->SetTitleOffset(1.3);
791 tango_multi->GetYaxis()->SetLabelSize(0.025);
792 tango_multi->GetYaxis()->SetLabelOffset(0.001);
793 tango_multi->GetYaxis()->CenterLabels();
794 // gr->GetYaxis()->SetNdivisions(10, 0, 0);
795 }
796 // the titles are passed to the 3D frame: X axis title - to the time axis, Y axis title - to the value axis
797 else
798 {
799 tango_multi->GetXaxis()->SetTitle(TString::Format("time, hours from %s", strStartDate.Data()));
800 tango_multi->GetYaxis()->SetTitle(y_axis);
801 }
802
803 TLegend* pLegend = c1->BuildLegend(0.92, 0.77, 0.99, 0.98, "");
804 pLegend->SetMargin(0.80);
805
806 c1->Modified();
807 return 0;
808}
809
810// Function displays a set of "simple" parameters obtained from Tango, e.g. GEMs high voltages voltage, graphically as a
811// set of Line Graphs
812int TangoData::PrintTangoArrayMultiGraph(vector<TangoData*> vecTangoData, const char* y_axis, bool is3D)
813{
814 if (vecTangoData.size() < 1) {
815 cout << "WARNING: There are no parameters in the specified array" << endl;
816 return -1;
817 }
818
819 // check all the parameters before drawing
820 for (const auto& current_parameter : vecTangoData) {
821 if ((current_parameter->GetTangoData() == nullptr) || (current_parameter->GetTangoData()->IsEmpty())) {
822 cout << "ERROR: There are no elements in the parameter (" << current_parameter->GetFullName() << ")"
823 << endl;
824 return -2;
825 }
826
827 if ((((TangoTimeParameter*)current_parameter->GetTangoData()->At(0))->double_parameter_value.size()) != 1) {
828 cout << "ERROR: the parameter " << current_parameter->GetFullName() << " must have single value" << endl;
829 return -3;
830 }
831 }
832
833 // cout<<"Tango data array size = "<<vecTangoData.size()<<endl;
834 int par_length = vecTangoData.size();
835 // cout<<"par_length = "<<par_length<<endl;
836
837 TCanvas* c1 = CreateTangoCanvas(GetArrayDataName(vecTangoData), is3D ? "multigraph3d" : "multigraph");
838 TGraph* tango_graphs = new TGraph[par_length]();
839 gRandom->SetSeed();
840 int j;
841 for (j = 0; j < par_length; j++) {
842 Int_t color = gRandom->Integer(50);
843 if ((color == 0) || (color == 10) || ((color > 16) && (color < 20)))
844 color += 20;
845 tango_graphs[j].SetLineColor(color);
846 }
847
848 // the 3D view does not support time display, so time is shown in hours from the start date of the first parameter
849 TString start_date = vecTangoData[0]->GetStartDate();
850 UInt_t start_time = TDatime(start_date).Convert();
851 j = 0;
852 for (const auto& current_parameter : vecTangoData) {
853 TObjArray* arrTangoData = current_parameter->GetTangoData();
854 for (int i = 0; i < arrTangoData->GetEntriesFast(); i++) {
855 UInt_t cur_time = ((TangoTimeParameter*)arrTangoData->At(i))->parameter_time.Convert();
856 double x = is3D ? ((double)cur_time - start_time) / 3600 : cur_time;
857 double value = ((TangoTimeParameter*)arrTangoData->At(i))->double_parameter_value[0];
858 AddStepPoint(tango_graphs[j], x, value);
859 }
860 j++;
861 }
862
863 TMultiGraph* tango_multi = new TMultiGraph();
864 tango_multi->SetTitle(GetArrayTitle(vecTangoData));
865 for (j = 0; j < par_length; j++) {
866 tango_multi->Add(&tango_graphs[j]);
867 tango_graphs[j].SetTitle(TString::Format("%d", j));
868 tango_graphs[j].SetLineWidth(3);
869 }
870
871 TString draw_par = "AL";
872 if (is3D)
873 draw_par += "3D";
874 tango_multi->Draw(draw_par.Data());
875 gPad->Update();
876
877 if (!is3D) {
878 tango_multi->GetXaxis()->SetTitle("time");
879 tango_multi->GetXaxis()->CenterTitle();
880 tango_multi->GetXaxis()->SetTitleOffset(1.3);
881 tango_multi->GetXaxis()->SetLabelSize(0.025);
882 tango_multi->GetXaxis()->SetLabelOffset(0.009);
883 tango_multi->GetXaxis()->SetNdivisions(-503);
884 // form X-axis with time ticks
885 tango_multi->GetXaxis()->SetTimeDisplay(1);
886 tango_multi->GetXaxis()->SetTimeFormat("%Y.%m.%d %H:%M");
887 tango_multi->GetXaxis()->SetTimeOffset(0, "local");
888
889 tango_multi->GetYaxis()->SetTitle(y_axis);
890 tango_multi->GetYaxis()->CenterTitle();
891 tango_multi->GetYaxis()->SetTitleOffset(1.3);
892 tango_multi->GetYaxis()->SetLabelSize(0.025);
893 tango_multi->GetYaxis()->SetLabelOffset(0.001);
894 tango_multi->GetYaxis()->CenterLabels();
895 // gr->GetYaxis()->SetNdivisions(10, 0, 0);
896 }
897 // the titles are passed to the 3D frame: X axis title - to the time axis, Y axis title - to the value axis
898 else
899 {
900 tango_multi->GetXaxis()->SetTitle(TString::Format("time, hours from %s", start_date.Data()));
901 tango_multi->GetYaxis()->SetTitle(y_axis);
902 }
903
904 TLegend* pLegend = c1->BuildLegend(0.92, 0.77, 0.99, 0.98, "");
905 pLegend->SetMargin(0.80);
906
907 c1->Modified();
908 return 0;
909}
910
911/** Function displays a set of "simple" parameters obtained from Tango, e.g. FHCal or GEM high voltages, graphically
912 * as 2D Surface (X - time, Y - channel, i.e. index of the parameter in the array, Z - value of the parameter)
913 * The time interval of the first parameter is divided into equal time bins, and every bin is filled with
914 * the time-weighted average value of the channel in the bin (every value is valid up to the next time point)
915 * Parameters:
916 * z_axis - label of Z axis (parameter values), y_axis - label of Y axis (channels)
917 * draw_option - draw option of the 2D histogram: "SURF1" - surface (default), "LEGO2" - columns,
918 * "COLZ" - 2D color map, etc.
919 * time_bins - number of the time bins
920 * Returns: 0 - in case of the success, < 0 - if an error occured
921 **/
922int TangoData::PrintTangoArraySurface(vector<TangoData*> vecTangoData,
923 const char* z_axis,
924 const char* y_axis,
925 const char* draw_option,
926 int time_bins)
927{
928 if (vecTangoData.size() < 1) {
929 cout << "WARNING: There are no parameters in the specified array" << endl;
930 return -1;
931 }
932 if (time_bins < 1) {
933 cout << "ERROR: the number of time bins should be greater than 0" << endl;
934 return -2;
935 }
936
937 // check all the parameters before drawing
938 for (const auto& current_parameter : vecTangoData) {
939 if ((current_parameter->GetTangoData() == nullptr) || (current_parameter->GetTangoData()->IsEmpty())) {
940 cout << "ERROR: There are no elements in the parameter (" << current_parameter->GetFullName() << ")"
941 << endl;
942 return -3;
943 }
944
945 if ((((TangoTimeParameter*)current_parameter->GetTangoData()->At(0))->double_parameter_value.size()) != 1) {
946 cout << "ERROR: the parameter " << current_parameter->GetFullName() << " must have single value" << endl;
947 return -4;
948 }
949 }
950
951 // the time interval is taken from the first parameter
952 UInt_t start_time = TDatime(vecTangoData[0]->GetStartDate()).Convert();
953 UInt_t end_time = TDatime(vecTangoData[0]->GetEndDate()).Convert();
954 if (end_time <= start_time) {
955 cout << "ERROR: the end time should be greater than the start time of the parameters" << endl;
956 return -5;
957 }
958 int channel_count = vecTangoData.size();
959 double bin_width = (double)(end_time - start_time) / time_bins;
960
961 // the histogram is not added to the current directory to avoid replacing of the previous one
962 bool add_directory = TH1::AddDirectoryStatus();
964 TH2D* tango_hist = new TH2D("tango_surface", GetArrayTitle(vecTangoData), time_bins, start_time, end_time,
965 channel_count, -0.5, channel_count - 0.5);
966 TH1::AddDirectory(add_directory);
967
968 vector<double> bin_sum(time_bins), bin_sec(time_bins);
969 for (int j = 0; j < channel_count; j++) {
970 TangoData* current_parameter = vecTangoData[j];
971 TObjArray* arrParameterData = current_parameter->GetTangoData();
972 UInt_t data_start = TDatime(current_parameter->GetStartDate()).Convert();
973 UInt_t data_end = TDatime(current_parameter->GetEndDate()).Convert();
974 fill(bin_sum.begin(), bin_sum.end(), 0);
975 fill(bin_sec.begin(), bin_sec.end(), 0);
976 for (int i = 0; i < arrParameterData->GetEntriesFast(); i++) {
977 UInt_t value_start, value_end;
978 current_parameter->GetValuePeriod(i, data_start, data_end, value_start, value_end);
979 double value = ((TangoTimeParameter*)arrParameterData->At(i))->double_parameter_value[0];
980
981 // add the value weighted by its time overlapped with every time bin
982 int first_bin = max(0, (int)floor(((double)value_start - start_time) / bin_width));
983 int last_bin = min(time_bins - 1, (int)floor(((double)value_end - start_time) / bin_width));
984 for (int b = first_bin; b <= last_bin; b++) {
985 double bin_start = start_time + b * bin_width, bin_end = bin_start + bin_width;
986 double overlap = min((double)value_end, bin_end) - max((double)value_start, bin_start);
987 if (overlap <= 0)
988 continue;
989 bin_sum[b] += value * overlap;
990 bin_sec[b] += overlap;
991 }
992 }
993
994 for (int b = 0; b < time_bins; b++)
995 if (bin_sec[b] > 0)
996 tango_hist->SetBinContent(b + 1, j + 1, bin_sum[b] / bin_sec[b]);
997 }
998
999 // the view name is the draw option, e.g. "surf1" or "lego2"
1000 TString view_name(draw_option);
1001 view_name.ToLower();
1002 TCanvas* c1 = CreateTangoCanvas(GetArrayDataName(vecTangoData), view_name);
1003 tango_hist->SetStats(kFALSE);
1004 if (tango_hist->GetMinimum() > 0)
1005 tango_hist->SetMinimum(0);
1006
1007 // 3D view ("SURF", "LEGO") or 2D view (e.g. "COLZ" color map), where the right margin is used for the palette
1008 bool is3D = view_name.Contains("surf") || view_name.Contains("lego");
1009 if (!is3D)
1010 c1->SetRightMargin(0.15);
1011
1012 tango_hist->GetXaxis()->SetTitle("time");
1013 tango_hist->GetXaxis()->CenterTitle();
1014 tango_hist->GetXaxis()->SetTitleOffset(is3D ? 1.9 : 1.2);
1015 tango_hist->GetXaxis()->SetLabelSize(0.025);
1016 tango_hist->GetXaxis()->SetNdivisions(-503);
1017 // form X-axis with time ticks
1018 tango_hist->GetXaxis()->SetTimeDisplay(1);
1019 tango_hist->GetXaxis()->SetTimeFormat("%Y.%m.%d %H:%M");
1020 tango_hist->GetXaxis()->SetTimeOffset(0, "local");
1021
1022 tango_hist->GetYaxis()->SetTitle(y_axis);
1023 tango_hist->GetYaxis()->CenterTitle();
1024 tango_hist->GetYaxis()->SetTitleOffset(is3D ? 1.9 : 1.0);
1025 tango_hist->GetYaxis()->SetLabelSize(0.025);
1026
1027 tango_hist->GetZaxis()->SetTitle(z_axis);
1028 tango_hist->GetZaxis()->CenterTitle();
1029 tango_hist->GetZaxis()->SetTitleOffset(is3D ? 1.5 : 1.2);
1030 tango_hist->GetZaxis()->SetLabelSize(0.025);
1031
1032 tango_hist->Draw(draw_option);
1033 c1->Modified();
1034 return 0;
1035}
1036
1037// Function calculates and returns average value for Tango data array (result vector with size > 1 is used in case of
1038// many channels)
1040{
1041 vector<double> result;
1042 if (arrTangoData == nullptr) {
1043 cout << "ERROR: Tango parameter has not been obtained" << endl;
1044 return result;
1045 }
1046
1047 if (iVerbose)
1048 cout << "strStartDateAvg = " << strStartDate.Data() << endl;
1049 if (iVerbose)
1050 cout << "strEndDateAvg = " << strEndDate.Data() << endl;
1051 int time_count = arrTangoData->GetEntriesFast();
1052 TDatime start_date(strStartDate), end_date(strEndDate);
1053
1054 // get arithmetic average value
1055 if ((IsOldMySQL) || (time_count < 2)) {
1056 for (int i = 0; i < time_count; i++) {
1058 // cycle for Tango parameter array (from 1 to array size)
1059 for (size_t j = 0; j < pParameter->double_parameter_value.size(); j++) {
1060 if (i == 0)
1061 result.push_back(pParameter->double_parameter_value[j]);
1062 else
1063 result[j] += pParameter->double_parameter_value[j];
1064 }
1065 }
1066
1067 for (size_t j = 0; j < result.size(); j++)
1068 result[j] /= time_count;
1069 }
1070 // get time-weighted average value over the whole time interval (for the new architecture of the Tango database)
1071 else
1072 result = GetTimeWeightedAverage(vector<TangoTimeInterval>{TangoTimeInterval(start_date, end_date)});
1073
1074 return result;
1075}
1076
1077// Function calculates and returns time-weighted average value for Tango data array only over the time of the runs,
1078// i.e. the gaps between runs are excluded (result vector with size > 1 is used in case of many channels)
1079// Every Tango value is considered valid from its time point to the next one
1080// It is available only if the object was created by the Run Range Constructor
1082{
1083 if (arrTangoData == nullptr) {
1084 cout << "ERROR: Tango parameter has not been obtained" << endl;
1085 return vector<double>();
1086 }
1087 if (vecRunIntervals.empty()) {
1088 cout << "ERROR: there are no run time intervals, the object should be created by the Run Range Constructor"
1089 << endl;
1090 return vector<double>();
1091 }
1092
1094}
1095
1096// non-user function GetTimeWeightedAverage calculates average value for Tango data array over the given time
1097// intervals, where every value is weighted by the length of its validity period inside the intervals
1098// Every Tango time point is a transition to a new value: the value is valid from its time point to the next one,
1099// the first value is also used from the start date, the last one - up to the end date
1100// Returns empty vector in case of errors
1101vector<double> TangoData::GetTimeWeightedAverage(const vector<TangoTimeInterval>& time_intervals)
1102{
1103 vector<double> result;
1104 int time_count = arrTangoData->GetEntriesFast();
1105 if (time_count == 0) {
1106 cout << "ERROR: there are no elements in the Tango array" << endl;
1107 return result;
1108 }
1109
1110 size_t channel_count = ((TangoTimeParameter*)arrTangoData->At(0))->double_parameter_value.size();
1111 result.assign(channel_count, 0);
1112 UInt_t data_start = TDatime(strStartDate).Convert(), data_end = TDatime(strEndDate).Convert();
1113 double total_sec = 0;
1114 for (int i = 0; i < time_count; i++) {
1116 if (pParameter->double_parameter_value.size() != channel_count) {
1117 cout << "ERROR: channel count of the Tango parameter is not constant during the time interval" << endl;
1118 result.clear();
1119 return result;
1120 }
1121
1122 UInt_t value_start, value_end;
1123 GetValuePeriod(i, data_start, data_end, value_start, value_end);
1124
1125 // add the value weighted by its time overlapped with every interval
1126 for (const auto& time_interval : time_intervals) {
1127 UInt_t overlap_start = max(value_start, time_interval.start_time.Convert());
1128 UInt_t overlap_end = min(value_end, time_interval.end_time.Convert());
1129 if (overlap_end <= overlap_start)
1130 continue;
1131
1132 UInt_t sec = overlap_end - overlap_start;
1133 for (size_t j = 0; j < channel_count; j++)
1134 result[j] += pParameter->double_parameter_value[j] * sec;
1135 total_sec += sec;
1136 }
1137 }
1138
1139 if (total_sec == 0) {
1140 cout << "ERROR: the total time of the intervals for the average value is equal 0" << endl;
1141 result.clear();
1142 return result;
1143 }
1144 if (iVerbose)
1145 cout << "Total time of " << time_intervals.size() << " interval(s) used for the average value = " << total_sec
1146 << " s" << endl;
1147
1148 for (size_t j = 0; j < channel_count; j++)
1149 result[j] /= total_sec;
1150
1151 return result;
1152}
1153
1154// non-user function GetValuePeriod gets the time period where the value of the i-th Tango time point is valid:
1155// from its time point to the next one, the first value is also used from the start date (data_start),
1156// the last one - up to the end date (data_end)
1157void TangoData::GetValuePeriod(int i, UInt_t data_start, UInt_t data_end, UInt_t& value_start, UInt_t& value_end)
1158{
1159 value_start = ((TangoTimeParameter*)arrTangoData->At(i))->parameter_time.Convert();
1160 value_end = data_end;
1161 if ((i == 0) && (data_start < value_start))
1162 value_start = data_start;
1163 if (i < arrTangoData->GetEntriesFast() - 1)
1164 value_end = ((TangoTimeParameter*)arrTangoData->At(i + 1))->parameter_time.Convert();
1165}
1166
1167/** Function SearchTangoIntervals gets time intervals for defined condition on the parameter values
1168 * NOTE: it works only if channel count is constant during given time period
1169 * Parameters:
1170 * condition - condition of time interval sampling, default: conditionEqual (the possible list is presented above in
1171 * 'enumConditions', except conditionLike, conditionNull and conditionNotNull)
1172 * value - numeric value for the condition with which the comparison is performed, default: 1 (true);
1173 * boolean values of the parameter are compared as 0 (false) and 1 (true)
1174 * mapChannel - vector of integer values (map) to change the order of result TObjArray-s in the common result array,
1175 * if, for example, channels go in a different sequence; nullptr - if not used
1176 * Returns common TObjArray with TObjArray objects containing TangoTimeInterval for every channel
1177 * (i.e. conditionally TObjArray<TObjArray<TangoTimeInterval*>>). If there are no intervals found, it returns
1178 * an empty TObjArray with zero elements. In case of errors it returns nullptr
1179 **/
1180TObjArray* TangoData::SearchTangoIntervals(enumConditions condition, double value, vector<int>* mapChannel)
1181{
1182 if (arrTangoData == nullptr) {
1183 cout << "ERROR: Tango parameter has not been obtained" << endl;
1184 return nullptr;
1185 }
1186 if ((condition == conditionLike) || (condition == conditionNull) || (condition == conditionNotNull)) {
1187 cout << "ERROR: comparison operator in the searching of intervals is not supported" << endl;
1188 return nullptr;
1189 }
1190
1191 TObjArray* pTimeIntervals = new TObjArray();
1192 pTimeIntervals->SetOwner(kTRUE);
1193
1194 // if there is no points in the Tango period then return empty common TObjArray (without any elements)
1195 int time_count = arrTangoData->GetEntriesFast();
1196 if (time_count == 0)
1197 return pTimeIntervals;
1198
1199 // TObjArray with the found time intervals for every channel
1200 size_t channel_count = ((TangoTimeParameter*)arrTangoData->At(0))->double_parameter_value.size();
1201 for (size_t j = 0; j < channel_count; j++) {
1202 TObjArray* pChannel = new TObjArray();
1203 pChannel->SetOwner(kTRUE);
1204 pTimeIntervals->Add(pChannel);
1205 }
1206
1207 // add the found time interval of the channel to the result array considering the channel map
1208 auto AddInterval = [&](size_t j, TDatime start_interval, TDatime end_interval) {
1209 int real_channel = j;
1210 if (mapChannel != nullptr) {
1211 if (mapChannel->size() > j) {
1212 real_channel = mapChannel->at(j);
1213 if (pTimeIntervals->GetEntriesFast() <= real_channel) {
1214 cout << "CRITICAL WARNING: Tango array size is less than the corrected channel: " << real_channel
1215 << endl;
1216 return;
1217 }
1218 } else
1219 cout << "CRITICAL WARNING: map channel size is less than the current channel: " << j << endl;
1220 }
1221 ((TObjArray*)pTimeIntervals->At(real_channel))->Add(new TangoTimeInterval(start_interval, end_interval));
1222 };
1223 // start time of the interval beginning at the given time point (the middle between the points for old MySQL)
1224 auto GetStartTime = [&](int start_i) {
1225 TDatime start_interval = ((TangoTimeParameter*)arrTangoData->At(start_i))->parameter_time;
1226 if ((start_i > 0) && (IsOldMySQL)) {
1227 TDatime previous_time = ((TangoTimeParameter*)arrTangoData->At(start_i - 1))->parameter_time;
1228 start_interval.Set((start_interval.Convert() + previous_time.Convert()) / 2);
1229 }
1230 return start_interval;
1231 };
1232
1233 // start indices of the current intervals satisfying the condition for every channel (-1 - no interval)
1234 vector<int> vecStart(channel_count, -1);
1235 for (int i = 0; i < time_count; i++) {
1237 if (pParameter->double_parameter_value.size() != channel_count) {
1238 cout << "ERROR: channel count of the Tango parameter is not constant during the time interval" << endl;
1239 delete pTimeIntervals;
1240 return nullptr;
1241 }
1242
1243 // cycle for array parameter data (if the parameter is an array) and checking the given condition
1244 for (size_t j = 0; j < channel_count; j++) {
1245 double cur_value = pParameter->double_parameter_value[j];
1246 bool isCondition = false;
1247 switch (condition) {
1248 case conditionLess:
1249 isCondition = cur_value < value;
1250 break;
1252 isCondition = cur_value <= value;
1253 break;
1254 case conditionEqual:
1255 isCondition = cur_value == value;
1256 break;
1257 case conditionNotEqual:
1258 isCondition = cur_value != value;
1259 break;
1260 case conditionGreater:
1261 isCondition = cur_value > value;
1262 break;
1264 isCondition = cur_value >= value;
1265 break;
1266 default:
1267 break;
1268 }
1269
1270 // save the start index of a new interval satisfying the condition
1271 if (isCondition) {
1272 if (vecStart[j] < 0)
1273 vecStart[j] = i;
1274 }
1275 // the interval has ended: write it (the end is just before the current time point)
1276 else if (vecStart[j] >= 0)
1277 {
1278 UInt_t uiEndTime = pParameter->parameter_time.Convert();
1279 TDatime end_interval(uiEndTime - 1);
1280 if (IsOldMySQL)
1281 end_interval.Set(
1282 (uiEndTime + ((TangoTimeParameter*)arrTangoData->At(i - 1))->parameter_time.Convert()) / 2);
1283 AddInterval(j, GetStartTime(vecStart[j]), end_interval);
1284 vecStart[j] = -1;
1285 }
1286 } // for (size_t j = 0; j < channel_count; j++)
1287 } // for (int i = 0; i < time_count; i++)
1288
1289 // write the intervals lasting up to the end of the time period
1290 TDatime end_time = ((TangoTimeParameter*)arrTangoData->At(time_count - 1))->parameter_time;
1291 for (size_t j = 0; j < channel_count; j++)
1292 if (vecStart[j] >= 0)
1293 AddInterval(j, GetStartTime(vecStart[j]), end_time);
1294
1295 return pTimeIntervals;
1296}
1297
1298/** Function displays (in console) time intervals obtained from Tango for a defined condition
1299 * Parameters:
1300 * tango_intervals - TObjArray with TObjArray objects containing TangoTimeInterval objects obtained from
1301 *'SearchTangoIntervals' function channel_name - name of the dimension to display on the screen, default: Channel
1302 * isShowOnlyExists - if true, print only intervals which satisfy the condition (skip empty intervals)
1303 **/
1304void TangoData::PrintTangoIntervalConsole(TObjArray* tango_intervals, TString channel_name, bool isShowOnlyExists)
1305{
1306 for (int i = 0; i < tango_intervals->GetEntriesFast(); i++) {
1307 TObjArray* pChannel = (TObjArray*)tango_intervals->At(i);
1308 if (pChannel->GetEntriesFast() == 0) {
1309 if (!isShowOnlyExists)
1310 cout << channel_name.Data() << " " << i << ":" << endl
1311 << " No intervals correspond to the specified conditions" << endl;
1312 continue;
1313 } else
1314 cout << channel_name.Data() << " " << i << ":" << endl;
1315 for (int j = 0; j < pChannel->GetEntriesFast(); j++) {
1316 TangoTimeInterval* pInterval = (TangoTimeInterval*)pChannel->At(j);
1317 cout << " " << pInterval->start_time.AsSQLString();
1318 cout << " - ";
1319 cout << pInterval->end_time.AsSQLString();
1320 }
1321 cout << endl;
1322 }
1323
1324 return;
1325}
1326
1327// delete Tango parameter
1329{
1330 IsOldMySQL = false;
1332 iPeriodNumber = -1, iStartRun = -1, iEndRun = -1;
1333 vecRunIntervals.clear();
1334 if (arrTangoData != nullptr) {
1335 arrTangoData->Delete();
1336 delete arrTangoData;
1337 arrTangoData = nullptr;
1338 }
1339}
int i
Definition P4_F32vec4.h:22
friend F32vec4 min(const F32vec4 &a, const F32vec4 &b)
Definition P4_F32vec4.h:30
friend F32vec4 max(const F32vec4 &a, const F32vec4 &b)
Definition P4_F32vec4.h:31
int Int_t
int Ssiz_t
constexpr Bool_t kFALSE
constexpr Ssiz_t kNPOS
constexpr Bool_t kTRUE
R__EXTERN TRandom * gRandom
#define gPad
static int cached_end_run
const char *const TANGO_DB_USERNAME_b2020
Definition TangoData.cxx:27
static TString GetRangeSuffix(TangoData *pTangoData)
static TString cached_end_date
const char *const TANGO_DB_NAME_b2020
Definition TangoData.cxx:30
const char *const TANGO_DB_PASSWORD_b2020
Definition TangoData.cxx:28
static void AddStepPoint(TGraph &graph, double x, double y)
const char *const TANGO_DB_HOST_b2020
Definition TangoData.cxx:29
static int cached_period
static TString GetArrayDataName(vector< TangoData * > &vecTangoData)
static TString GetArrayTitle(vector< TangoData * > &vecTangoData)
static TString cached_start_date
static TString GetSourceName(TangoData *pTangoData)
static TString GetDataName(TangoData *pTangoData)
static vector< TangoTimeInterval > cached_run_intervals
static int cached_start_run
static TCanvas * CreateTangoCanvas(TString data_name, TString view_name)
Tango_Parameter_Type
Definition TangoData.h:18
@ Tango_Bool
Definition TangoData.h:19
@ Tango_Bool_Array
Definition TangoData.h:24
@ Tango_Double
Definition TangoData.h:20
@ Tango_Double_Array
Definition TangoData.h:26
virtual void SetTitleOffset(Float_t offset=1)
virtual void SetLabelSize(Float_t size=0.04)
virtual void SetLabelOffset(Float_t offset=0.005)
virtual void SetNdivisions(Int_t n1, Int_t n2, Int_t n3, Bool_t optim=kTRUE)
virtual void SetLineWidth(Width_t lwidth)
virtual void SetLineColor(Color_t lcolor)
virtual void SetRightMargin(Float_t rightmargin)
virtual void SetTimeOffset(Double_t toffset, Option_t *option="local")
void CenterLabels(Bool_t center=kTRUE)
virtual void SetTimeDisplay(Int_t value)
void CenterTitle(Bool_t center=kTRUE)
virtual void SetTimeFormat(const char *format="")
virtual void SetOwner(Bool_t enable=kTRUE)
Int_t GetDate() const
const char * AsSQLString() const
void Set()
UInt_t Convert(Bool_t toGMT=kFALSE) const
Int_t GetTime() const
TAxis * GetZaxis() const
void SetTitle(const char *title="") override
TAxis * GetYaxis() const
virtual void SetPoint(Int_t point, Double_t x, Double_t y, Double_t z)
void Draw(Option_t *option="P0") override
TAxis * GetXaxis() const
virtual void SetPoint(Int_t i, Double_t x, Double_t y)
Double_t * GetY() const
Int_t GetN() const
void SetTitle(const char *title="") override
TAxis * GetZaxis()
static void AddDirectory(Bool_t add=kTRUE)
TAxis * GetXaxis()
TAxis * GetYaxis()
void Draw(Option_t *option="") override
virtual void SetMinimum(Double_t minimum=-1111)
virtual Double_t GetMinimum(Double_t minval=-FLT_MAX) const
static Bool_t AddDirectoryStatus()
virtual void SetStats(Bool_t stats=kTRUE)
void SetBinContent(Int_t bin, Double_t content) override
void SetMargin(Float_t margin)
virtual void Add(TGraph *graph, Option_t *chopt="")
void Draw(Option_t *chopt="") override
TAxis * GetYaxis()
TAxis * GetXaxis()
virtual void SetTitle(const char *title="")
Int_t GetEntriesFast() const
TObject * At(Int_t idx) const override
void Add(TObject *obj) override
TLegend * BuildLegend(Double_t x1=0.3, Double_t y1=0.21, Double_t x2=0.3, Double_t y2=0.21, const char *title="", Option_t *option="") override
void Modified(Bool_t flag=true) override
const char * GetDB() const
virtual TSQLResult * GetTables(const char *dbname, const char *wild=nullptr)=0
virtual TSQLStatement * Statement(const char *, Int_t=100)
virtual const char * GetString(Int_t)
virtual Bool_t NextResultRow()=0
virtual Int_t GetNumAffectedRows()
virtual Int_t GetInt(Int_t)
virtual Bool_t Process()=0
virtual Double_t GetDouble(Int_t)
virtual Bool_t StoreResult()=0
Ssiz_t Length() const
void ToLower()
Int_t Atoi() const
const char * Data() const
static TString Format(const char *fmt,...)
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
TSQLServer * GetSQLServer()
static TangoConnection * Open()
TString strMemberName
Definition TangoData.h:228
TString GetEndDate()
Definition TangoData.h:144
TString GetSystemName()
Definition TangoData.h:145
void GetValuePeriod(int i, UInt_t data_start, UInt_t data_end, UInt_t &value_start, UInt_t &value_end)
int iStartRun
Definition TangoData.h:233
TString GetFullName()
int GetEndRun()
Definition TangoData.h:151
std::vector< double > GetAverageTangoData()
TString strParameterName
Definition TangoData.h:228
TObjArray * SearchTangoIntervals(enumConditions condition=conditionEqual, double value=1, std::vector< int > *mapChannel=nullptr)
Function SearchTangoIntervals gets time intervals for defined condition on the parameter values (e....
std::vector< double > GetRunAverageTangoData()
static void PrintTangoArrayConsole(std::vector< TangoData * > vecTangoData)
int GetStartRun()
Definition TangoData.h:150
TString strEndDate
Definition TangoData.h:229
int SetRunRangeDates(int period_number, int start_run, int end_run)
void PrintTangoDataConsole()
void InitTangoData()
TString strStartDate
Definition TangoData.h:228
TString GetStartDate()
Definition TangoData.h:143
@ conditionGreaterOrEqual
Definition TangoData.h:94
@ conditionNotNull
Definition TangoData.h:97
@ conditionNull
Definition TangoData.h:96
@ conditionLike
Definition TangoData.h:95
@ conditionEqual
Definition TangoData.h:91
@ conditionGreater
Definition TangoData.h:93
@ conditionLessOrEqual
Definition TangoData.h:90
@ conditionLess
Definition TangoData.h:89
@ conditionNotEqual
Definition TangoData.h:92
std::vector< double > GetTimeWeightedAverage(const std::vector< TangoTimeInterval > &time_intervals)
int iEndRun
Definition TangoData.h:233
int GetTangoParameter()
TObjArray * arrTangoData
Definition TangoData.h:230
void DeleteTangoParameter()
virtual ~TangoData()
std::vector< TangoTimeInterval > vecRunIntervals
Definition TangoData.h:234
bool IsOldMySQL
Definition TangoData.h:227
static int PrintTangoArraySurface(std::vector< TangoData * > vecTangoData, const char *z_axis="parameter", const char *y_axis="channel", const char *draw_option="SURF1", int time_bins=100)
Function displays a set of "simple" parameters obtained from Tango, e.g.
TString strUserName
Definition TangoData.h:228
void PrintTangoDataSurface(const char *y_axis="tango parameter")
TObjArray * GetTangoData()
Definition TangoData.h:141
TString strSystemName
Definition TangoData.h:228
static int PrintTangoArrayMultiGraph(std::vector< TangoData * > vecTangoData, const char *y_axis="parameter", bool is3D=false)
int PrintTangoDataMultiGraph(const char *y_axis="parameter", bool is3D=false)
TString GetParameterName()
Definition TangoData.h:146
int iVerbose
Definition TangoData.h:231
TangoData(const char *start_date, const char *end_date, const char *system_name, const char *parameter_name, const char *member_name="", int verbose=0)
Time Range Constructor: fill Tango data array according to the given parameters Tango database connec...
Definition TangoData.cxx:80
TString GetMemberName()
Definition TangoData.h:147
int GetPeriodNumber()
Definition TangoData.h:149
void PrintTangoIntervalConsole(TObjArray *tango_intervals, TString channel_name="Channel", bool isShowOnlyExists=false)
Function displays (in console) time intervals obtained from Tango for a defined condition Parameters:...
int iPeriodNumber
Definition TangoData.h:233
TangoTimeInterval()
Default constructor.
Definition TangoData.cxx:52
TDatime start_time
Definition TangoData.h:61
virtual ~TangoTimeInterval()
Destructor.
Definition TangoData.cxx:60
std::vector< double > double_parameter_value
Definition TangoData.h:41
Tango_Parameter_Type parameter_type
Definition TangoData.h:37
TangoTimeParameter()
Default constructor.
Definition TangoData.cxx:32
std::vector< bool > bool_parameter_value
Definition TangoData.h:40
TDatime parameter_time
Definition TangoData.h:35
virtual ~TangoTimeParameter()
Destructor.
Definition TangoData.cxx:50
UniRun.h Class for the table: run_.
Definition UniRun.h:21
static UniRun * GetRun(int period_number, int run_number)
get run from the database
Definition UniRun.cxx:161
TDatime * GetEndDatetime()
get end datetime of the current run
Definition UniRun.h:101
TDatime GetStartDatetime()
get start datetime of the current run
Definition UniRun.h:99
static int GetRunNumbers(UniqueRunNumber *&run_numbers, int start_period, int start_run=0, int end_period=-1, int end_run=-1)
get numbers of runs stored in the Database for a selected range
Definition UniRun.cxx:804
RVec< PromoteType< T > > floor(const RVec< T > &v)