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

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