source: trunk/FACT++/src/calcsource.cc@ 19177

Last change on this file since 19177 was 19156, checked in by tbretz, 6 years ago
Enclose table names.
File size: 32.9 KB
Line 
1#include "Database.h"
2
3#include "pal.h"
4#include "nova.h"
5#include "tools.h"
6#include "Time.h"
7#include "Configuration.h"
8
9#include <TROOT.h>
10#include <TVector3.h>
11#include <TRotation.h>
12
13using namespace std;
14
15// ------------------------------------------------------------------------
16
17void SetupConfiguration(Configuration &conf)
18{
19 po::options_description control("Calcsource options");
20 control.add_options()
21 ("uri,u", var<string>()
22#if BOOST_VERSION >= 104200
23 ->required()
24#endif
25 , "Database link as in\n\tuser:password@server[:port]/database[?compress=0|1].")
26 //("source-key", var<uint32_t>(5), "")
27 //("source-name", var<string>(""), "")
28 ("file", var<uint32_t>(uint32_t(0)),"FileId (YYMMDDXXX), defined the events to be processed (if omitted (=0), a list of possible numbers is printed)")
29 ("table.events", var<string>("Events"), "Name of the table where the events are stored")
30 ("table.runinfo", var<string>("RunInfo"), "Name of the table where the run-info data is stored")
31 ("table.source", var<string>("Source"), "Name of the table where the sources are stored")
32 ("table.position", var<string>("Position"), "Name of the table where the calculated posiiton will be stored")
33 ("engine", var<string>(""), "Database engine to be used when a new table is created")
34 ("row-format", var<string>(""), "Defines the ROW_FORMAT keyword for table creation")
35 ("ignore-errors", po_switch(), "Adds the IGNORE keyword to the INSERT query (turns errors into warnings, ignores rows with errors)")
36 ("force", po_switch(), "Force processing even if there is no database connection")
37 ("drop", po_switch(), "Drop the table (implies create)")
38 ("create", po_switch(), "Create the table if it does not yet exist")
39 ("update", po_switch(), "Uses the ON DUPLICATE KEY to update already existing extries")
40 ("ra", var<double>(), "Right ascension of the source (use together with --dec)")
41 ("dec", var<double>(), "Declination of the source (use together with --ra)")
42 ("focal-dist", var<double>(4889.), "Focal distance of the camera in millimeter")
43 ;
44
45 po::options_description debug("Debug options");
46 debug.add_options()
47 ("no-insert", po_switch(), "Does not insert or update any data to any table")
48 ("dry-run", po_switch(), "Skip any query which changes the databse (might result in consecutive failures)")
49 ("print-meta", po_switch(), "Print meta-queries (DROP, CREATE, DELETE, SELECT)")
50 ("print-insert", po_switch(), "Print the INSERT/UPDATE queries")
51 ("verbose,v", var<uint16_t>(1), "Verbosity (0: quiet, 1: default, 2: more, 3, ...)")
52 ;
53
54 po::positional_options_description p;
55 p.add("file", 1); // The 1st positional options (n=1)
56
57 conf.AddOptions(control);
58 conf.AddOptions(debug);
59 conf.SetArgumentPositions(p);
60}
61
62void PrintUsage()
63{
64 cout <<
65 "calcsource - Fill a table with source positions\n"
66 "\n"
67 "This tool is to calculate the source position in the camera and fill "
68 "it into a database table for all events which come from a single run. "
69 "The run is idetified by its FileId (YYMMDDXXX), where YYMMDD is "
70 "its date and XXX is the run-number. For this run the corresponding "
71 "source key `fSourceKey` is obtained from the RunInfo table "
72 "(--table.runinfo) and the corresponding fRightAscension and fDeclination "
73 "from the Source table (--table.source). If --ra and --dec was specified "
74 "by the user, this step is skipped and these two values are used instead."
75 "\n\n"
76 "Then for each event with the given FileId, its pointing position "
77 "(`Ra`, `Dec`), its time (`MJD`, `MilliSec`) and its event number "
78 "(`EvtNumber`) are requested from the table given by --table.events. "
79 "Based on this information and the focal distance (--focal-distance) the "
80 "`X` and `Y` coordinate of the source in the camera plane is calculated. "
81 "The result can then be filled into a database."
82 "\n\n"
83 "The table to be filled or updated should contain the following columns:\n"
84 " - FileId INT UNSIGNED NOT NULL\n"
85 " - EvtNumber INT UNSIGNED NOT NULL\n"
86 " - X FLOAT NOT NULL\n"
87 " - Y FLOAT NOT NULL\n"
88 "\n"
89 "If the table does not exist, it can be created automatically specifying "
90 "the --crate option. If a table already exists and it should be dropped "
91 "before creation, the --drop option can be used:\n"
92 "\n"
93 " calcsource 170909009 --create\n"
94 "\n"
95 "Process the data from the run 009 from 09/09/2017. If no table exists "
96 "a table with the name given by --table.position is created.\n"
97 "\n"
98 " calcsource 170909009 --create --drop\n"
99 "\n"
100 "Same as before, but if a table with the name given by --table.position "
101 "exists, it is dropped before.\n"
102 "\n"
103 "For each event, a new row is inserted. If existing rows should be updated, "
104 "use:\n"
105 "\n"
106 " calcsource 170909009 --updated\n"
107 "\n"
108 "The --create option is compatible with that. The --drop option is ignored.\n"
109 "\n"
110 "To avoid failure in case an entry does already exist, you can add the IGNORE "
111 "keyword to the INSERT query by --ignore-errors, which essentially ignores "
112 "all errors and turns them into warnings which are printed after the query "
113 "succeeded.\n"
114 "\n"
115 "\n"
116 "For debugging purposes several print options and options to avoid irreversible "
117 "changes to the database exist."
118 "\n\n"
119 "Usage: calcsource YYMMDDXXX [-u URI] [options]\n"
120 "\n"
121 ;
122 cout << endl;
123}
124
125class MRotation : public TRotation
126{
127public:
128 MRotation() : TRotation(1, 0, 0, 0, -1, 0, 0, 0, 1)
129 {
130 }
131};
132
133
134int main(int argc, const char* argv[])
135{
136 Time start;
137
138 gROOT->SetBatch();
139
140 Configuration conf(argv[0]);
141 conf.SetPrintUsage(PrintUsage);
142 SetupConfiguration(conf);
143
144 if (!conf.DoParse(argc, argv))
145 return 127;
146
147 // ----------------------------- Evaluate options --------------------------
148 if (conf.Has("ra")^conf.Has("dec"))
149 throw runtime_error("--ra and --dec can only be used together");
150
151 const bool has_radec = conf.Has("ra") && conf.Has("dec");
152
153 double source_ra = conf.Has("ra") ? conf.Get<double>("ra") : 0;
154 double source_dec = conf.Has("dec") ? conf.Get<double>("dec") : 0;
155
156 //string source_name = conf.Get<string>("source-name");
157 //uint32_t source_key = conf.Has("source-key") ? conf.Get<uint32_t>("source-key") : 0;
158
159 const string uri = conf.Get<string>("uri");
160 const string tab_events = conf.Get<string>("table.events");
161 const string tab_runinfo = conf.Get<string>("table.runinfo");
162 const string tab_source = conf.Get<string>("table.source");
163 const string tab_position = conf.Get<string>("table.position");
164
165 const string engine = conf.Get<string>("engine");
166 const string row_format = conf.Get<string>("row-format");
167 const bool ignore_errors = conf.Get<bool>("ignore-errors");
168
169 const uint32_t file = conf.Get<uint32_t>("file");
170
171 const double focal_dist = conf.Get<double>("focal-dist");
172
173 const bool print_meta = conf.Get<bool>("print-meta");
174 const bool print_insert = conf.Get<bool>("print-insert");
175
176 const bool force = conf.Get<bool>("force");
177 const bool drop = conf.Get<bool>("drop");
178 const bool create = conf.Get<bool>("create") || drop;
179 const bool update = conf.Get<bool>("update");
180 const bool noinsert = conf.Get<bool>("no-insert");
181 const bool dry_run = conf.Get<bool>("dry-run");
182 const uint16_t verbose = conf.Get<uint16_t>("verbose");
183
184 // -------------------------------------------------------------------------
185 // Checking for database connection
186
187 Database connection(uri); // Keep alive while fetching rows
188
189 try
190 {
191 if (!force)
192 connection.connected();
193 }
194 catch (const exception &e)
195 {
196 cerr << "SQL connection failed: " << e.what() << endl;
197 return 1;
198 }
199
200 // -------------------------------------------------------------------------
201 // list file-ids in the events table
202
203 if (file==0)
204 {
205 const string query =
206 "SELECT FileId FROM `"+tab_events+"` GROUP BY FileId";
207
208 if (print_meta)
209 cout << query << endl;
210
211 const mysqlpp::StoreQueryResult res =
212 connection.query(query).store();
213
214 for (size_t i=0; i<res.num_rows(); i++)
215 cout << "calcsource " << res[i][0] << '\n';
216 cout << endl;
217
218 return 0;
219 }
220
221 // -------------------------------------------------------------------------
222 // retrieve source from the database
223
224 if (verbose>0)
225 {
226 cout << "\n------------------------- Evaluating source ------------------------" << endl;
227 cout << "Requesting coordinates from " << tab_runinfo << "/" << tab_source << " table for 20" << file/1000 << "/" << file%1000 << endl;
228 }
229
230 if (!has_radec)
231 {
232 const string query =
233 "SELECT `"+tab_source+"`.fRightAscension, `"+tab_source+"`.fDeclination, `"+tab_source+"`.fSourceName"
234 " FROM `"+tab_runinfo+"`"+
235 " LEFT JOIN `"+tab_source+"`"+
236 " USING (fSourceKey)"
237 " WHERE fNight=20"+to_string(file/1000)+
238 " AND fRunID="+to_string(file%1000);
239
240 if (print_meta)
241 cout << query << endl;
242
243 try
244 {
245 const mysqlpp::StoreQueryResult res =
246 connection.query(query).store();
247
248 if (res.num_rows()!=1)
249 {
250 cerr << "No coordinates from " << tab_runinfo << " for " << file << endl;
251 return 2;
252 }
253
254 source_ra = res[0][0];
255 source_dec = res[0][1];
256
257 if (verbose>0)
258 cout << "Using coordinates " << source_ra << "h / " << source_dec << " deg for '" << res[0][2] << "'" << endl;
259 }
260 catch (const exception &e)
261 {
262 cerr << query << "\n";
263 cerr << "SQL query failed:\n" << e.what() << endl;
264 return 3;
265 }
266 }
267 else
268 if (verbose>0)
269 cout << "Using coordinates " << source_ra << "h / " << source_dec << " deg from resources." << endl;
270
271/*
272 if (!source_name.empty())
273 {
274 cout << "Requesting coordinates for '" << source_name << "'" << endl;
275
276 const mysqlpp::StoreQueryResult res =
277 connection.query("SELECT `Ra`, `Dec` WHERE fSourceName='"+source_name+"'").store();
278
279 if (res.num_rows()!=1)
280 {
281 cerr << "No " << (res.num_rows()>1?"unique ":"") << "coordinates found for '" << source_name << "'" << endl;
282 return 1;
283 }
284
285 source_ra = res[0][0];
286 source_dec = res[0][1];
287 }
288*/
289
290 // -------------------------------------------------------------------------
291 // create INSERT/UPDATE query (calculate positions)
292
293 if (verbose>0)
294 {
295 cout << "\n-------------------------- Evaluating file ------------------------";
296 cout << "\nRequesting data from table `" << tab_events << "`" << endl;
297 }
298
299 const string query =
300 "SELECT `Ra`, `Dec`, MJD, MilliSec, NanoSec, Zd, Az, EvtNumber"
301 " FROM `"+tab_events+"`"
302 " WHERE FileId="+to_string(file);
303
304 if (print_meta)
305 cout << query << endl;
306
307 const mysqlpp::UseQueryResult res1 =
308 connection.query(query).use();
309
310 Nova::RaDecPosn source(source_ra, source_dec);
311
312 source_ra *= M_PI/12;
313 source_dec *= M_PI/180;
314
315 auto obs = Nova::kORM;
316
317 obs.lng *= M_PI/180;
318 obs.lat *= M_PI/180;
319
320 //const double mm2deg = 1.17193246260285378e-02;
321
322 ostringstream ins;
323 ins << setprecision(16);
324
325 size_t count = 0;
326 while (auto row=res1.fetch_row())
327 {
328 count++;
329
330 double point_ra = row[0];
331 double point_dec = row[1];
332 uint32_t mjd = row[2];
333 int64_t millisec = row[3];
334 //uint32_t nanosec = row[4];
335 //double zd = row[5];
336 //double az = row[6];
337 uint32_t event = row[7];
338
339 Nova::RaDecPosn point(point_ra, point_dec);
340
341 point_ra *= M_PI/12;
342 point_dec *= M_PI/180;
343
344 /*
345 // ============================ Mars ================================
346
347 TVector3 pos; // pos: source position
348 TVector3 pos0; // pos: source position
349
350 pos.SetMagThetaPhi(1, M_PI/2-source_dec, source_ra);
351 pos0.SetMagThetaPhi(1, M_PI/2-point_dec, point_ra);
352
353 const double ut = (nanosec/1e6+millisec)/(24*3600000);
354
355 // Julian centuries since J2000.
356 const double t = (ut -(51544.5-mjd)) / 36525.0;
357
358 // GMST at this UT1
359 const double r1 = 24110.54841+(8640184.812866+(0.093104-6.2e-6*t)*t)*t;
360 const double r2 = 86400.0*ut;
361
362 const double sum = (r1+r2)/(3600*24);
363
364 double gmst = fmod(sum, 1) * 2*M_PI;
365
366 MRotation conv;
367 conv.RotateZ(gmst + obs.lng);
368 conv.RotateY(obs.lat-M_PI/2);
369 conv.RotateZ(M_PI);
370
371 pos *= conv;
372 pos0 *= conv;
373
374 pos.RotateZ(-pos0.Phi());
375 pos.RotateY(-pos0.Theta());
376 pos.RotateZ(-M_PI/2); // exchange x and y
377 pos *= -focal_dist/pos.Z();
378
379 TVector2 v = pos.XYvector();
380
381 //if (fDeviation)
382 // v -= fDeviation->GetDevXY()/fGeom->GetConvMm2Deg();
383
384 //cout << v.X() << " " << v.Y() << " " << v.Mod()*mm2deg << '\n';
385 */
386
387 // ================================= Nova ===============================
388
389 Nova::ZdAzPosn ppos = Nova::GetHrzFromEqu(source, 2400000.5+mjd+millisec/1000./3600/24);
390 Nova::ZdAzPosn ppos0 = Nova::GetHrzFromEqu(point, 2400000.5+mjd+millisec/1000./3600/24);
391
392 TVector3 pos;
393 TVector3 pos0;
394 pos.SetMagThetaPhi( 1, ppos.zd *M_PI/180, ppos.az *M_PI/180);
395 pos0.SetMagThetaPhi(1, ppos0.zd*M_PI/180, ppos0.az*M_PI/180);
396
397 pos.RotateZ(-pos0.Phi());
398 pos.RotateY(-pos0.Theta());
399 pos.RotateZ(-M_PI/2); // exchange x and y
400 pos *= -focal_dist/pos.Z();
401
402 TVector2 v = pos.XYvector();
403
404 //cout << v.X() << " " << v.Y() << " " << v.Mod()*mm2deg << '\n';
405
406 /*
407 // =============================== Slalib ==========================
408 const double height = 2200;
409 const double temp = 10;
410 const double hum = 0.25;
411 const double press = 780;
412
413 const double _mjd = mjd+millisec/1000./3600/24;
414
415 const double dtt = palDtt(_mjd); // 32.184 + 35
416
417 const double tdb = _mjd + dtt/3600/24;
418 const double dut = 0;
419
420 // prepare calculation: Mean Place to geocentric apperent
421 // (UTC would also do, except for the moon?)
422 double fAmprms[21];
423 palMappa(2000.0, tdb, fAmprms); // Epoche, TDB
424
425 // prepare: Apperent to observed place
426 double fAoprms[14];
427 palAoppa(_mjd, dut, // mjd, Delta UT=UT1-UTC
428 obs.lng, obs.lat, height, // long, lat, height
429 0, 0, // polar motion x, y-coordinate (radians)
430 273.155+temp, press, hum, // temp, pressure, humidity
431 0.40, 0.0065, // wavelength, tropo lapse rate
432 fAoprms);
433
434 // ---- Mean to apparent ----
435 double r=0, d=0;
436 palMapqkz(point_ra, point_dec, fAmprms, &r, &d);
437
438 double _zd, _az, ha, ra, dec;
439 // -- apparent to observed --
440 palAopqk(r, d, fAoprms,
441 &_az, // observed azimuth (radians: N=0,E=90) [-pi, pi]
442 &_zd, // observed zenith distance (radians) [-pi/2, pi/2]
443 &ha, // observed hour angle (radians)
444 &dec, // observed declination (radians)
445 &ra); // observed right ascension (radians)
446
447 //cout << _zd*180/M_PI << " " << _az*180/M_PI << endl;
448
449 pos0.SetMagThetaPhi(1, _zd, _az);
450
451 r=0, d=0;
452 palMapqkz(source_ra, source_dec, fAmprms, &r, &d);
453
454 // -- apparent to observed --
455 palAopqk(r, d, fAoprms,
456 &_az, // observed azimuth (radians: N=0,E=90) [-pi, pi]
457 &_zd, // observed zenith distance (radians) [-pi/2, pi/2]
458 &ha, // observed hour angle (radians)
459 &dec, // observed declination (radians)
460 &ra); // observed right ascension (radians)
461
462 pos.SetMagThetaPhi(1, _zd, _az);
463
464 //cout << _zd*180/M_PI << " " << _az*180/M_PI << endl;
465
466 pos.RotateZ(-pos0.Phi());
467 pos.RotateY(-pos0.Theta());
468 pos.RotateZ(-M_PI/2); // exchange x and y
469 pos *= -focal_dist/pos.Z();
470
471 v = pos.XYvector();
472
473 //cout << v.X() << " " << v.Y() << " " << v.Mod()*mm2deg << '\n';
474 */
475
476 ins << "( " << file << ", " << event << ", " << v.X() << ", " << v.Y() << " ),\n";
477 }
478
479 if (connection.errnum())
480 {
481 cerr << "SQL error fetching row: " << connection.error() << endl;
482 return 4;
483 }
484
485 if (verbose>0)
486 cout << "Processed " << count << " events.\n" << endl;
487
488 if (count==0)
489 {
490 if (verbose>0)
491 cout << "Total execution time: " << Time().UnixTime()-start.UnixTime() << "s\n" << endl;
492 return 0;
493 }
494
495 // -------------------------------------------------------------------------
496 // drop table if requested
497
498 if (drop)
499 {
500 try
501 {
502 if (verbose>0)
503 cout << "Dropping table `" << tab_position << "`" << endl;
504
505 if (!dry_run)
506 connection.query("DROP TABLE `"+tab_position+"`").execute();
507
508 if (verbose>0)
509 cout << "Table `" << tab_position << "` dropped.\n" << endl;
510 }
511 catch (const exception &e)
512 {
513 cerr << "DROP TABLE `" << tab_position << "`\n\n";
514 cerr << "SQL query failed:\n" << e.what() << endl;
515 return 5;
516 }
517 }
518
519 // -------------------------------------------------------------------------
520 // crate table if requested
521
522 if (create)
523 {
524 if (verbose>0)
525 cout << "Creating table `" << tab_position << "`" << endl;
526
527 string query2 =
528 "CREATE TABLE IF NOT EXISTS `"+tab_position+"`\n"
529 "(\n"
530 " FileId INT UNSIGNED NOT NULL,\n"
531 " EvtNumber INT UNSIGNED NOT NULL,\n"
532 " X FLOAT NOT NULL,\n"
533 " Y FLOAT NOT NULL,\n"
534 " PRIMARY KEY (FileId, EvtNumber)\n"
535 ")\n"
536 "DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci\n";
537 if (!engine.empty())
538 query2 += "ENGINE="+engine+"\n";
539 if (!row_format.empty())
540 query2 += "ROW_FORMAT="+row_format+"\n";
541 query2 += "COMMENT='created by "+conf.GetName()+"'\n";
542
543 try
544 {
545 if (!dry_run)
546 connection.query(query2).execute();
547 }
548 catch (const exception &e)
549 {
550 cerr << query2 << "\n\n";
551 cerr << "SQL query failed:\n" << e.what() << endl;
552 return 6;
553 }
554
555 if (print_meta)
556 cout << query2 << endl;
557
558 if (verbose>0)
559 cout << "Table `" << tab_position << "` created.\n" << endl;
560 }
561
562 // -------------------------------------------------------------------------
563 // delete old entries from table
564
565 if (!drop)
566 {
567 if (verbose>0)
568 cout << "Deleting old entries from table `" << tab_position << "`" << endl;
569
570 const string query2 =
571 "DELETE FROM `"+tab_position+"` WHERE FileId="+to_string(file);
572
573 try
574 {
575 if (!dry_run)
576 {
577 const mysqlpp::SimpleResult res =
578 connection.query(query2).execute();
579
580 if (verbose>0)
581 cout << res.rows() << " row(s) affected.\n" << endl;
582 }
583 }
584 catch (const exception &e)
585 {
586 cerr << query2 << "\n\n";
587 cerr << "SQL query failed:\n" << e.what() << endl;
588 return 7;
589 }
590
591 if (print_meta)
592 cout << query2 << endl;
593 }
594
595 // -------------------------------------------------------------------------
596 // insert data into table
597
598 if (verbose>0)
599 cout << "Inserting data into table " << tab_position << "." << endl;
600
601 string query2 = "INSERT ";
602 if (ignore_errors)
603 query2 += "IGNORE ";
604 query2 += "`"+tab_position+"` (FileId, EvtNumber, X, Y) VALUES\n"+
605 ins.str().substr(0, ins.str().size()-2)+
606 "\n";
607 if (update)
608 query2 += "ON DUPLICATE KEY UPDATE X=VALUES(X), Y=VALUES(Y)\n";
609
610 try
611 {
612 if (!noinsert)
613 {
614 const mysqlpp::SimpleResult res =
615 connection.query(query2).execute();
616
617 if (verbose>0)
618 cout << res.info() << '\n' << endl;
619 }
620 }
621 catch (const exception &e)
622 {
623 cerr << query2 << "\n\n";
624 cerr << "SQL query (" << query2.length() << " bytes) failed:\n" << e.what() << endl;
625 return 8;
626 }
627
628 if (print_insert)
629 cout << query2 << endl;
630
631 if (verbose>0)
632 {
633 const auto sec = Time().UnixTime()-start.UnixTime();
634 cout << "Total execution time: " << sec << "s ";
635 cout << "(" << Tools::Fractional(sec/count) << "s/row)\n";
636
637 try
638 {
639 const auto resw =
640 connection.query("SHOW WARNINGS").store();
641
642 for (size_t i=0; i<resw.num_rows(); i++)
643 {
644 const mysqlpp::Row &roww = resw[i];
645
646 cout << roww["Level"] << '[' << roww["Code"] << "]: ";
647 cout << roww["Message"] << '\n';
648 }
649 cout << endl;
650
651 }
652 catch (const exception &e)
653 {
654 cerr << "\nSHOW WARNINGS\n\n";
655 cerr << "SQL query failed:\n" << e.what() << '\n' <<endl;
656 return 8;
657 }
658 }
659
660 return 0;
661}
662
663/*
664 TRotation & TRotation::RotateX(Double_t a) {
665 //rotate around x
666 Double_t c = TMath::Cos(a);
667 Double_t s = TMath::Sin(a);
668 Double_t x = fyx, y = fyy, z = fyz;
669 fyx = c*x - s*fzx;
670 fyy = c*y - s*fzy;
671 fyz = c*z - s*fzz;
672 fzx = s*x + c*fzx;
673 fzy = s*y + c*fzy;
674 fzz = s*z + c*fzz;
675 return *this;
676}
677
678TRotation & TRotation::RotateY(Double_t a){
679 //rotate around y
680 Double_t c = TMath::Cos(a);
681 Double_t s = TMath::Sin(a);
682 Double_t x = fzx, y = fzy, z = fzz;
683 fzx = c*x - s*fxx;
684 fzy = c*y - s*fxy;
685 fzz = c*z - s*fxz;
686 fxx = s*x + c*fxx;
687 fxy = s*y + c*fxy;
688 fxz = s*z + c*fxz;
689 return *this;
690}
691
692TRotation & TRotation::RotateZ(Double_t a) {
693 //rotate around z
694 Double_t c = TMath::Cos(a);
695 Double_t s = TMath::Sin(a);
696 Double_t x = fxx, y = fxy, z = fxz;
697 fxx = c*x - s*fyx;
698 fxy = c*y - s*fyy;
699 fxz = c*z - s*fyz;
700 fyx = s*x + c*fyx;
701 fyy = s*y + c*fyy;
702 fyz = s*z + c*fyz;
703 return *this;
704}
705
706 */
707
708
709// Reuired:
710// pointing_ra[8]
711// pointing_dec[8]
712// fNanoSec[4], fTime[fMiliSec,8], fMjd[4]
713// source_ra -> rc
714// source_dec -> rc
715// fLong, fLat -> rc
716// fCameraDist -> rc
717// 32 byte per row, 1 Monat = 4mio rows => 120 MB
718
719/*
720
721void TVector3::SetThetaPhi(Double_t theta, Double_t phi)
722{
723 //setter with mag, theta, phi
724 fX = TMath::Sin(theta) * TMath::Cos(phi);
725 fY = TMath::Sin(theta) * TMath::Sin(phi);
726 fZ = TMath::Cos(theta);
727}
728
729
730 // Set Sky coordinates of source, taken from container "MSourcePos"
731 // of type MPointingPos. The sky coordinates must be J2000, as the
732 // sky coordinates of the camera center that we get from the container
733 // "MPointingPos" filled by the Drive.
734 //MVector3 pos; // pos: source position
735 //pos.SetRaDec(fSourcePos->GetRaRad(), fSourcePos->GetDecRad());
736
737 TVector3 pos; // pos: source position
738 pos.SetMagThetaPhi(1, TMath::Pi()/2-source_dec, source_ra);
739
740 // Set sky coordinates of camera center in pos0 (for details see below)
741 //MVector3 pos0; // pos0: camera center
742 //pos0.SetRaDec(fPointPos->GetRaRad(), fPointPos->GetDecRad());
743
744 TVector3 pos0; // pos: source position
745 pos0.SetMagThetaPhi(1, TMath::Pi()/2-pointing_dec, pointing_ra);
746
747 // Convert sky coordinates of source to local coordinates. Warning! These are not the "true" local
748 // coordinates, since this transformation ignores precession and nutation effects.
749
750 //const MAstroSky2Local conv(*fTime, *fObservatory);
751 //pos *= conv;
752
753 const Double_t ut = (Double_t)(fNanoSec/1e6+(Long_t)fTime)/kDay;
754
755 // Julian centuries since J2000.
756 const Double_t t = (ut -(51544.5-fMjd)) / 36525.0;
757
758 // GMST at this UT1
759 const Double_t r1 = 24110.54841+(8640184.812866+(0.093104-6.2e-6*t)*t)*t;
760 const Double_t r2 = 86400.0*ut;
761
762 const Double_t sum = (r1+r2)/kDaySec;
763
764 double gmst = fmod(sum, 1)*TMath::TwoPi();
765
766 // TRotation::TRotation(Double_t mxx, Double_t mxy, Double_t mxz,
767 // Double_t myx, Double_t myy, Double_t myz,
768 // Double_t mzx, Double_t mzy, Double_t mzz)
769 // : fxx(mxx), fxy(mxy), fxz(mxz),
770 // fyx(myx), fyy(myy), fyz(myz),
771 // fzx(mzx), fzy(mzy), fzz(mzz) {}
772
773 TRotation conv(1, 0, 0, 0, -1, 0, 0, 0, 1);
774 conv.RotateZ(gmst + obs.GetElong());
775 conv.RotateY(obs.GetPhi()-TMath::Pi()/2);
776 conv.RotateZ(TMath::Pi());
777
778 // TVector3 & TVector3::operator *= (const TRotation & m){
779 // return *this = m * (*this);
780 // }
781
782 // inline TVector3 TRotation::operator * (const TVector3 & p) const {
783 // return TVector3(fxx*p.X() + fxy*p.Y() + fxz*p.Z(),
784 // fyx*p.X() + fyy*p.Y() + fyz*p.Z(),
785 // fzx*p.X() + fzy*p.Y() + fzz*p.Z());
786 // }
787
788 // Convert sky coordinates of camera center convert to local.
789 // Same comment as above. These coordinates differ from the true
790 // local coordinates of the camera center that one could get from
791 // "MPointingPos", calculated by the Drive: the reason is that the Drive
792 // takes into account precession and nutation corrections, while
793 // MAstroSky2Local (as of Jan 27 2005 at least) does not. Since we just
794 // want to get the source position on the camera from the local
795 // coordinates of the center and the source, it does not matter that
796 // the coordinates contained in pos and pos0 ignore precession and
797 // nutation... since the shift would be the same in both cases. What
798 // would be wrong is to set in pos0 directly the local coordinates
799 // found in MPointingPos!
800 pos0 *= conv;
801
802 if (fDeviation)
803 {
804 // Position at which the starguider camera is pointing in real:
805 // pointing position = nominal position - dev
806 //
807 //vx = CalcXYinCamera(pos0, pos)*fGeom->GetCameraDist()*1000;
808 pos0.SetZdAz(pos0.Theta()-fDeviation->GetDevZdRad(),
809 pos0.Phi() -fDeviation->GetDevAzRad());
810 }
811
812 // Calculate source position in camera, and convert to mm:
813 TVector2 v = MAstro::GetDistOnPlain(pos0, pos, -fGeom->GetCameraDist()*1000);
814
815 pos.RotateZ(-pos0.Phi());
816 pos.RotateY(-pos0.Theta());
817 pos.RotateZ(-TMath::Pi()/2); // exchange x and y
818 pos *= -fGeom->GetCameraDist()*1000/pos.Z();
819
820 TVector2 v = pos.XYvector();
821
822 if (fDeviation)
823 v -= fDeviation->GetDevXY()/fGeom->GetConvMm2Deg();
824
825 SetSrcPos(v);
826
827 // ================================================
828
829 if (fMode==kWobble)
830 {
831 // The trick here is that the anti-source position in case
832 // of the off-source regions is always the on-source positon
833 // thus a proper anti-source cut is possible.
834 fSrcPosAnti->SetXY(v);
835 if (fCallback)
836 v = Rotate(v, fCallback->GetNumPass(), fCallback->GetNumPasses());
837 else
838 v *= -1;
839 fSrcPosCam->SetXY(v);
840 }
841 else
842 {
843 // Because we don't process this three times like in the
844 // wobble case we have to find another way to determine which
845 // off-source region is the right anti-source position
846 // We do it randomly.
847 fSrcPosCam->SetXY(v);
848 if (fNumRandomOffPositions>1)
849 v = Rotate(v, gRandom->Integer(fNumRandomOffPositions), fNumRandomOffPositions);
850 else
851 v *= -1;
852 fSrcPosAnti->SetXY(v);
853 }
854
855
856
857 */
858
859
860
861
862/*
863 PointingData CalcPointingPos(const PointingSetup &setup, double _mjd, const Weather &weather, uint16_t timeout, bool tpoint=false)
864 {
865 PointingData out;
866 out.mjd = _mjd;
867
868 const double elong = Nova::kORM.lng * M_PI/180;
869 const double lat = Nova::kORM.lat * M_PI/180;
870 const double height = 2200;
871
872 const bool valid = weather.time+boost::posix_time::seconds(timeout) > Time();
873
874 const double temp = valid ? weather.temp : 10;
875 const double hum = valid ? weather.hum : 0.25;
876 const double press = valid ? weather.press : 780;
877
878 const double dtt = palDtt(_mjd); // 32.184 + 35
879
880 const double tdb = _mjd + dtt/3600/24;
881 const double dut = 0;
882
883 // prepare calculation: Mean Place to geocentric apperent
884 // (UTC would also do, except for the moon?)
885 double fAmprms[21];
886 palMappa(2000.0, tdb, fAmprms); // Epoche, TDB
887
888 // prepare: Apperent to observed place
889 double fAoprms[14];
890 palAoppa(_mjd, dut, // mjd, Delta UT=UT1-UTC
891 elong, lat, height, // long, lat, height
892 0, 0, // polar motion x, y-coordinate (radians)
893 273.155+temp, press, hum, // temp, pressure, humidity
894 0.40, 0.0065, // wavelength, tropo lapse rate
895 fAoprms);
896
897 out.source.ra = setup.source.ra * M_PI/ 12;
898 out.source.dec = setup.source.dec * M_PI/180;
899
900 if (setup.planet!=kENone)
901 {
902 // coordinates of planet: topocentric, equatorial, J2000
903 // One can use TT instead of TDB for all planets (except the moon?)
904 double ra, dec, diam;
905 palRdplan(tdb, setup.planet, elong, lat, &ra, &dec, &diam);
906
907 // ---- apparent to mean ----
908 palAmpqk(ra, dec, fAmprms, &out.source.ra, &out.source.dec);
909 }
910
911 if (setup.wobble_offset<=0 || tpoint)
912 {
913 out.pointing.dec = out.source.dec;
914 out.pointing.ra = out.source.ra;
915 }
916 else
917 {
918 const double dphi =
919 setup.orbit_period==0 ? 0 : 2*M_PI*(_mjd-setup.start)/setup.orbit_period;
920
921 const double phi = setup.wobble_angle + dphi;
922
923 const double cosdir = cos(phi);
924 const double sindir = sin(phi);
925 const double cosoff = cos(setup.wobble_offset);
926 const double sinoff = sin(setup.wobble_offset);
927 const double cosdec = cos(out.source.dec);
928 const double sindec = sin(out.source.dec);
929
930 const double sintheta = sindec*cosoff + cosdec*sinoff*cosdir;
931
932 const double costheta = sintheta>1 ? 0 : sqrt(1 - sintheta*sintheta);
933
934 const double cosdeltara = (cosoff - sindec*sintheta)/(cosdec*costheta);
935 const double sindeltara = sindir*sinoff/costheta;
936
937 out.pointing.dec = asin(sintheta);
938 out.pointing.ra = atan2(sindeltara, cosdeltara) + out.source.ra;
939 }
940
941 // ---- Mean to apparent ----
942 double r=0, d=0;
943 palMapqkz(out.pointing.ra, out.pointing.dec, fAmprms, &r, &d);
944
945 //
946 // Doesn't work - don't know why
947 //
948 // slaMapqk (radec.Ra(), radec.Dec(), rdpm.Ra(), rdpm.Dec(),
949 // 0, 0, (double*)fAmprms, &r, &d);
950 //
951
952 // -- apparent to observed --
953 palAopqk(r, d, fAoprms,
954 &out.sky.az, // observed azimuth (radians: N=0,E=90) [-pi, pi]
955 &out.sky.zd, // observed zenith distance (radians) [-pi/2, pi/2]
956 &out.apparent.ha, // observed hour angle (radians)
957 &out.apparent.dec, // observed declination (radians)
958 &out.apparent.ra); // observed right ascension (radians)
959
960 // ----- fix ambiguity -----
961 if (out.sky.zd<0)
962 {
963 out.sky.zd = -out.sky.zd;
964 out.sky.az += out.sky.az<0 ? M_PI : -M_PI;
965 }
966
967 // Star culminating behind zenith and Az between ~90 and ~180deg
968 if (out.source.dec<lat && out.sky.az>0)
969 out.sky.az -= 2*M_PI;
970
971 out.mount = SkyToMount(out.sky);
972
973 return out;
974 }
975};
976
977*/
Note: See TracBrowser for help on using the repository browser.