Changeset 18436 for trunk/FACT++/src


Ignore:
Timestamp:
02/14/16 16:54:44 (9 years ago)
Author:
tbretz
Message:
Added options and code to allow to enter a schedule into the Schedule database.
File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/FACT++/src/makeschedule.cc

    r18418 r18436  
    11#include "externals/Prediction.h"
    22
    3 //#include <unordered_map>
    43#include <boost/algorithm/string/join.hpp>
    54
     
    109#include "Configuration.h"
    1110
    12 /*
    13 #include <TROOT.h>
    14 #include <TH1.h>
    15 #include <TGraph.h>
    16 #include <TCanvas.h>
    17 #include <TLegend.h>
    18 */
    19 
    2011using namespace std;
    2112using namespace Nova;
    2213
    2314// -----------------------------------------------------------------------
    24 
    25 /*
    26 void CheckForGap(TCanvas &c, TGraph &g, double axis)
    27 {
    28     if (g.GetN()==0 || axis-g.GetX()[g.GetN()-1]<450)
    29         return;
    30 
    31     c.cd();
    32     ((TGraph*)g.DrawClone("C"))->SetBit(kCanDelete);
    33     while (g.GetN())
    34         g.RemovePoint(0);
    35 }
    36 
    37 void DrawClone(TCanvas &c, TGraph &g)
    38 {
    39     if (g.GetN()==0)
    40         return;
    41 
    42     c.cd();
    43     ((TGraph*)g.DrawClone("C"))->SetBit(kCanDelete);
    44 }
    45 */
    46 
    47 // ========================================================================
    48 // ========================================================================
    49 // ========================================================================
    5015
    5116void SetupConfiguration(Configuration &conf)
     
    5520        ("date", var<string>(), "SQL time (UTC), e.g. '2016-12-24'")
    5621        ("source-database", var<string>(""), "Database link as in\n\tuser:password@server[:port]/database.")
     22        ("schedule-database", var<string>(""), "Database link as in\n\tuser:password@server[:port]/database.")
    5723        ("max-current", var<double>(90), "Global maximum current limit in uA")
    5824        ("max-zd", var<double>(75), "Global zenith distance limit in degree")
     
    6329        ("data-taking.start", var<double>(-12), "Begin of data-taking in degree of sun below horizon")
    6430        ("data-taking.end", var<double>(-13.75), "End of data-taking in degree of sun below horizon")
     31        ("enter-schedule-into-database", var<bool>(), "Enter schedule into database (required schedule-database, false: dry-run)")
    6532        ;
    6633
     
    471438}
    472439
     440int FillSql(Database &db, int enter, const vector<Source> &obs, double startup_offset)
     441{
     442    const string query0 = "SELECT COUNT(*) FROM Schedule WHERE DATE(ADDTIME(fStart, '-12:00')) = '"+Time(obs[0].begin).GetAsStr("%Y-%m-%d")+"'";
     443
     444    const mysqlpp::StoreQueryResult res0 = db.query(query0).store();
     445
     446    if (res0.num_rows()!=1)
     447    {
     448        cout << "Check for schedule size failed." << endl;
     449        return 10;
     450    }
     451
     452    if (uint32_t(res0[0][0])!=0)
     453    {
     454        cout << "Schedule not empty." << endl;
     455        return 11;
     456    }
     457
     458    const mysqlpp::StoreQueryResult res1 = db.query("SELECT fSourceName, fSourceKEY FROM Source").store();
     459
     460    map<string, uint32_t> keys;
     461    for (const auto &row: res1)
     462        keys.emplace(string(row[0]), uint32_t(row[1]));
     463
     464    const mysqlpp::StoreQueryResult res2 = db.query("SELECT fMeasurementTypeName, fMeasurementTypeKEY FROM MeasurementType").store();
     465
     466    map<string, uint32_t> types;
     467    for (const auto &row: res2)
     468        types.emplace(string(row[0]), uint32_t(row[1]));
     469
     470    ostringstream str;
     471    str << "INSERT INTO Schedule (fStart, fUser, fMeasurementID, fMeasurementTypeKEY, fSourceKEY) VALUES\n";
     472
     473    str << "('" << Time(obs[0].begin-startup_offset).GetAsStr() << "', auto, 0, " << types["Startup"] << ", NULL), [Startup]\n";
     474    for (const auto& src: obs)
     475    {
     476        string tm = Time(src.begin).GetAsStr();
     477
     478        /*
     479         if (src.preobs.size()>0)
     480         {
     481         for (const auto& pre: src.preobs)
     482         {
     483         str << tm << "  " << pre << "\n";
     484         tm = "                   ";
     485         }
     486         }*/
     487
     488        if (src.name!="SLEEP")
     489            str << "('" << tm << "', auto, 0, " << types["Data"] << ", " << keys[src.name] << "), [Data: " << src.name << "]\n";
     490        else
     491            str << "('" << tm << "', auto, 0, " << types["Sleep"] << ", NULL), [Sleep]\n";
     492    }
     493
     494    str << "('" << Time(obs.back().end).GetAsStr() << "', auto, 0, " << types["Shutdown"] << ", NULL) [Shutdown]";
     495
     496    if (enter<0)
     497    {
     498        cout << str.str() << endl;
     499        return 0;
     500    }
     501
     502    db.query(str.str());
     503
     504    cout << "Schedule entered successfully into database." << endl;
     505    return 0;
     506}
     507
    473508int main(int argc, const char* argv[])
    474509{
     
    484519    // ------------------ Eval config ---------------------
    485520
     521    const int enter = conf.Has("enter-schedule-into-database") ? (conf.Get<bool>("enter-schedule-into-database") ? 1 : -1) : 0;
     522    if (enter && !conf.Has("schedule-database"))
     523        throw runtime_error("enter-schedule-into-database required schedule-database.");
     524
    486525    Time time;
    487526    if (conf.Has("date"))
    488         time.SetFromStr(conf.Get<string>("date")+" 12:00:00");
     527        time.SetFromStr(conf.Get<string>("date"));
     528
     529    if (enter && floor(time.JD())<ceil(Time().JD()))
     530        throw runtime_error("Only future schedules can be entered into the database.");
    489531
    490532    Source::max_current = conf.Get<double>("max-current");
     
    508550    // Sun set with the same date than th provided date
    509551    // Sun rise on the following day
    510     const RstTime sun_set  = GetSolarRst(time.JD()-0.5, angle_sun_set);
    511     const RstTime sun_rise = GetSolarRst(time.JD()+0.5, angle_sun_rise);
     552    const RstTime sun_set  = GetSolarRst(floor(time.JD())-0.5, angle_sun_set);
     553    const RstTime sun_rise = GetSolarRst(floor(time.JD())+0.5, angle_sun_rise);
    512554
    513555    const double sunset  = ceil(sun_set.set*24*60)/24/60;
     
    530572        query += " AND fSourceName IN ('" + boost::algorithm::join(sourcenames, "', '")+"')";
    531573
    532     const string fDatabase = conf.Get<string>("source-database");
     574    const string sourcedb = conf.Get<string>("source-database");
    533575    const mysqlpp::StoreQueryResult res =
    534         Database(fDatabase).query(query).store();
     576        Database(sourcedb).query(query).store();
    535577
    536578    // ------------------ Eval config ---------------------
     
    609651    {
    610652        cout << "No source found." << endl;
    611         return 0;
     653        return 1;
    612654    }
    613655
     
    637679    // ---------------------------------------------------------------------
    638680
    639     return 1;
    640 
    641     // ------------- Create canvases and frames ---------------------
    642 /*
    643     // It is important to use an offset which is larger than
    644     // 1970-01-01 00:00:00. This one will not work if your
    645     // local time zone is positive!
    646     TH1S hframe("", "", 1, Time(sunset).Mjd()*24*3600, Time(sunrise).Mjd()*24*3600);
    647     hframe.SetStats(kFALSE);
    648     hframe.GetXaxis()->SetTimeFormat("%Hh%M%F1995-01-01 00:00:00 GMT");
    649     hframe.GetXaxis()->SetTitle((Time(jd).GetAsStr("%d/%m/%Y")+"  -  "+Time(jd+1).GetAsStr("%d/%m/%Y")+"  [UTC]").c_str());
    650     hframe.GetXaxis()->CenterTitle();
    651     hframe.GetYaxis()->CenterTitle();
    652     hframe.GetXaxis()->SetTimeDisplay(true);
    653     hframe.GetYaxis()->SetTitleSize(0.040);
    654     hframe.GetXaxis()->SetTitleSize(0.040);
    655     hframe.GetXaxis()->SetTitleOffset(1.1);
    656     hframe.GetYaxis()->SetLabelSize(0.040);
    657     hframe.GetXaxis()->SetLabelSize(0.040);
    658 
    659     TCanvas c1;
    660     c1.SetFillColor(kWhite);
    661     c1.SetBorderMode(0);
    662     c1.SetFrameBorderMode(0);
    663     c1.SetLeftMargin(0.085);
    664     c1.SetRightMargin(0.01);
    665     c1.SetTopMargin(0.03);
    666     c1.SetGrid();
    667     hframe.GetYaxis()->SetTitle("Altitude [deg]");
    668     hframe.SetMinimum(15);
    669     hframe.SetMaximum(90);
    670     hframe.DrawCopy();
    671 
    672     TCanvas c2;
    673     c2.SetFillColor(kWhite);
    674     c2.SetBorderMode(0);
    675     c2.SetFrameBorderMode(0);
    676     c2.SetLeftMargin(0.085);
    677     c2.SetRightMargin(0.01);
    678     c2.SetTopMargin(0.03);
    679     c2.SetGrid();
    680     hframe.GetYaxis()->SetTitle("Predicted Current [#muA]");
    681     hframe.SetMinimum(0);
    682     hframe.SetMaximum(100);
    683     hframe.DrawCopy();
    684 
    685     TCanvas c3;
    686     c3.SetFillColor(kWhite);
    687     c3.SetBorderMode(0);
    688     c3.SetFrameBorderMode(0);
    689     c3.SetLeftMargin(0.085);
    690     c3.SetRightMargin(0.01);
    691     c3.SetTopMargin(0.03);
    692     c3.SetGrid();
    693     c3.SetLogy();
    694     hframe.GetYaxis()->SetTitle("Estimated relative threshold");
    695     hframe.GetYaxis()->SetMoreLogLabels();
    696     hframe.SetMinimum(0.9);
    697     hframe.SetMaximum(11);
    698     hframe.DrawCopy();
    699 
    700     TCanvas c4;
    701     c4.SetFillColor(kWhite);
    702     c4.SetBorderMode(0);
    703     c4.SetFrameBorderMode(0);
    704     c4.SetLeftMargin(0.085);
    705     c4.SetRightMargin(0.01);
    706     c4.SetTopMargin(0.03);
    707     c4.SetGrid();
    708     hframe.GetYaxis()->SetTitle("Distance to moon [deg]");
    709     hframe.SetMinimum(0);
    710     hframe.SetMaximum(180);
    711     hframe.DrawCopy();
    712     Int_t color[] = { kBlack, kRed, kBlue, kGreen, kCyan, kMagenta };
    713     Int_t style[] = { kSolid, kDashed, kDotted };
    714 
    715     //    TLegend leg(0, 0, 1, 1);
    716 
    717     // ------------- Loop over sources ---------------------
    718 
    719     for (vector<mysqlpp::Row>::const_iterator v=res.begin(); v<res.end(); v++, cnt++)
    720     {
    721         // Eval row
    722         const string name = (*v)[0].c_str();
    723 
    724         EquPosn pos;
    725         pos.ra  = double((*v)[1])*15;
    726         pos.dec = double((*v)[2]);
    727 
    728         // Loop over 24 hours
    729         for (double h=0; h<1; h+=1./(24*12))
    730         {
    731             const SolarObjects so(jd+h);
    732 
    733             // get local position of source
    734             const HrzPosn hrz = GetHrzFromEqu(pos, so.fJD);
    735 
    736             if (v==res.begin())
    737                 cout << Time(so.fJD) <<" " << 90-so.fMoonHrz.alt <<  endl;
    738 
    739             const double cur = FACT::PredictI(so, pos);
    740 
    741             // Relative  energy threshold prediction
    742             const double ratio = pow(cos((90-hrz.alt)*M_PI/180), -2.664);
    743 
    744             // Add points to curve
    745             const double axis = Time(so.fJD).Mjd()*24*3600;
    746 
    747             // If there is a gap of more than one bin, start a new curve
    748 
    749             // Add data
    750             if (no_limits || cur<max_current)
    751                 g1.SetPoint(g1.GetN(), axis, hrz.alt);
    752 
    753             if (no_limits || 90-hrz.alt<max_zd)
    754                 g2.SetPoint(g2.GetN(), axis, cur);
    755 
    756             if (no_limits || (cur<max_current && 90-hrz.alt<max_zd))
    757                 g3.SetPoint(g3.GetN(), axis, ratio*pow(cur/6.2, 0.394));
    758 
    759             if (no_limits || (cur<max_current && 90-hrz.alt<max_zd))
    760             {
    761                 const double angle = GetAngularSeparation(so.fMoonEqu, pos);
    762                 g4.SetPoint(g4.GetN(), axis, angle);
    763             }
    764 
    765             if (cnt==0)
    766                 gm.SetPoint(gm.GetN(), axis, so.fMoonHrz.alt);
    767         }
    768     }
    769 
    770     // Save three plots
    771     TCanvas c5;
    772     c5.SetFillColor(kWhite);
    773     c5.SetBorderMode(0);
    774     c5.SetFrameBorderMode(0);
    775     leg.Draw();
    776 
    777     const string t = Time(jd).GetAsStr("%Y%m%d");
    778 
    779     c1.SaveAs((t+"-ZenithDistance.eps").c_str());
    780     c2.SaveAs((t+"-PredictedCurrent.eps").c_str());
    781     c3.SaveAs((t+"-RelativeThreshold.eps").c_str());
    782     c4.SaveAs((t+"-MoonDist.eps").c_str());
    783     c5.SaveAs((t+"-Legend.eps").c_str());
    784 
    785     c1.SaveAs((t+"-ZenithDistance.root").c_str());
    786     c2.SaveAs((t+"-PredictedCurrent.root").c_str());
    787     c3.SaveAs((t+"-RelativeThreshold.root").c_str());
    788     c4.SaveAs((t+"-MoonDist.root").c_str());
    789 
    790     c1.Print((t+".pdf(").c_str(), "pdf");
    791     c2.Print((t+".pdf" ).c_str(), "pdf");
    792     c3.Print((t+".pdf" ).c_str(), "pdf");
    793     c4.Print((t+".pdf" ).c_str(), "pdf");
    794     c5.Print((t+".pdf)").c_str(), "pdf");
    795 */
    796 }
     681    if (!enter)
     682        return 0;
     683
     684    const string scheduledb = conf.Get<string>("schedule-database");
     685
     686    Database db(scheduledb);
     687
     688    if (enter>0)
     689        db.query("LOCK TABLES Schedule WRITE");
     690
     691    const int rc = FillSql(db, enter, obs, startup_offset);
     692
     693    if (enter>0)
     694        db.query("UNLOCK TABLES");
     695
     696    // ---------------------------------------------------------------------
     697
     698    return rc;
     699}
Note: See TracChangeset for help on using the changeset viewer.