-
Notifications
You must be signed in to change notification settings - Fork 45
/
ephem0.cpp
5647 lines (5124 loc) · 217 KB
/
ephem0.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ephem0.cpp: low-level funcs for ephemerides & pseudo-MPECs
Copyright (C) 2010, Project Pluto
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA. */
#if defined( _WIN32) || defined( __WATCOMC__)
#include <direct.h> /* for _mkdir() definition */
#else
#include <sys/stat.h>
#include <sys/types.h>
#endif
#ifdef __linux
#include <linux/limits.h>
#endif
#include <sys/types.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <ctype.h>
#include <assert.h>
#include <stdbool.h>
#include "watdefs.h"
#include "afuncs.h"
#include "lunar.h"
#include "date.h"
#include "comets.h"
#include "mpc_func.h"
#include "mpc_obs.h"
#include "vislimit.h"
#include "brentmin.h"
#include "stackall.h"
#include "expcalc.h"
#include "rgb_defs.h"
#include "stringex.h"
#include "constant.h"
#define LOG_10 2.3025850929940456840179914546843642076011014886287729760333279009675726
#define LIGHT_YEAR_IN_KM (365.25 * seconds_per_day * SPEED_OF_LIGHT)
int generic_message_box( const char *message, const char *box_type);
double centralize_ang( double ang); /* elem_out.cpp */
double vector_to_polar( double *lon, double *lat, const double *vector);
char *fgets_trimmed( char *buff, size_t max_bytes, FILE *ifile); /*elem_out.c*/
int parallax_to_lat_alt( const double rho_cos_phi, const double rho_sin_phi,
double *lat, double *ht_in_meters, const int planet_idx); /* ephem0.c */
double calc_obs_magnitude( const double obj_sun,
const double obj_earth, const double earth_sun, double *phase_ang);
int lat_alt_to_parallax( const double lat, const double ht_in_meters,
double *rho_cos_phi, double *rho_sin_phi, const int planet_idx);
int write_residuals_to_file( const char *filename, const char *ast_filename,
const int n_obs, const OBSERVE FAR *obs_data, const int format);
void light_time_lag( const double jde, const double *orbit, /* orb_func.c */
const double *observer, double *result, const int is_heliocentric);
int make_pseudo_mpec( const char *mpec_filename, const char *obj_name);
/* ephem0.cpp */
int earth_lunar_posn( const double jd, double FAR *earth_loc,
double FAR *lunar_loc);
bool nighttime_only( const char *mpc_code); /* mpc_obs.cpp */
double get_planet_mass( const int planet_idx); /* orb_func.c */
void remove_trailing_cr_lf( char *buff); /* ephem0.cpp */
const char *get_environment_ptr( const char *env_ptr); /* mpc_obs.cpp */
void set_environment_ptr( const char *env_ptr, const char *new_value);
uint64_t parse_bit_string( const char *istr); /* miscell.cpp */
void format_dist_in_buff( char *buff, const double dist_in_au); /* ephem0.c */
int debug_printf( const char *format, ...) /* mpc_obs.cpp */
#ifdef __GNUC__
__attribute__ (( format( printf, 1, 2)))
#endif
;
int calc_derivatives( const double jd, const double *ival, double *oval,
const int reference_planet); /* runge.cpp */
char *iso_time( char *buff, const double jd, const int precision); /* elem_out.c */
double mag_band_shift( const char mag_band, int *err_code); /* elem_out.c */
char *get_file_name( char *filename, const char *template_file_name);
double utc_from_td( const double jdt, double *delta_t); /* ephem0.cpp */
double diameter_from_abs_mag( const double abs_mag, /* ephem0.cpp */
const double optical_albedo);
double shadow_check( const double *planet_loc, /* ephem0.cpp */
const double *obs_posn,
const double planet_radius_in_au);
int get_object_name( char *obuff, const char *packed_desig); /* mpc_obs.c */
int get_residual_data( const OBSERVE *obs, double *xresid, double *yresid);
int setup_planet_elem( ELEMENTS *elem, const int planet_idx,
const double t_cen); /* moid4.c */
void calc_approx_planet_orientation( const int planet, /* runge.cpp */
const int system_number, const double jde, double *matrix);
char *mpc_station_name( char *station_data); /* mpc_obs.cpp */
FILE *fopen_ext( const char *filename, const char *permits); /* miscell.cpp */
static void put_residual_into_text( char *text, const double resid,
const int resid_format); /* ephem0.cpp */
FILE *open_json_file( char *filename, const char *env_ptr, const char *default_name,
const char *packed_desig, const char *permits); /* ephem0.cpp */
void shellsort_r( void *base, const size_t n_elements, const size_t elem_size,
int (*compare)(const void *, const void *, void *), void *context);
const char *default_observe_filename = "observe.txt";
const char *observe_filename = default_observe_filename;
const char *residual_filename = "residual.txt";
const char *ephemeris_filename = "ephemeri.txt";
bool is_default_ephem = true;
const char *elements_filename = "elements.txt";
static expcalc_config_t exposure_config;
extern int n_orbit_params;
/* Returns parallax constants (rho_cos_phi, rho_sin_phi) in AU. */
int lat_alt_to_parallax( const double lat, const double ht_in_meters,
double *rho_cos_phi, double *rho_sin_phi, const int planet_idx)
{
const double axis_ratio = planet_axis_ratio( planet_idx);
const double major_axis_in_meters = planet_radius_in_meters( planet_idx);
const double u = atan( sin( lat) * axis_ratio / cos( lat));
*rho_sin_phi = axis_ratio * sin( u) +
(ht_in_meters / major_axis_in_meters) * sin( lat);
*rho_cos_phi = cos( u) + (ht_in_meters / major_axis_in_meters) * cos( lat);
*rho_sin_phi *= major_axis_in_meters / AU_IN_METERS;
*rho_cos_phi *= major_axis_in_meters / AU_IN_METERS;
return( 0);
}
/* Parallax constants (rho_cos_phi, rho_sin_phi) should be in units of the
planet's equatorial radius. */
int parallax_to_lat_alt( const double rho_cos_phi, const double rho_sin_phi,
double *lat, double *ht_in_meters, const int planet_idx)
{
double talt = 0.;
const double tlat = point_to_ellipse( 1., planet_axis_ratio( planet_idx),
rho_cos_phi, rho_sin_phi, &talt);
if( lat)
*lat = tlat;
if( ht_in_meters)
*ht_in_meters = talt * planet_radius_in_meters( planet_idx);
return( 0);
}
/* format_dist_in_buff() formats the input distance (in AU) into a
seven-byte buffer. It does this by choosing suitable units: kilometers
if the distance is less than a million km, AU out to 10000 AU, then
light-years. In actual use, light-years indicates some sort of error,
but I wanted the program to handle that problem without just crashing.
28 Dec 2009: To help puzzle out a strange bug, I extended things so
that distances beyond 10000 light-years could be shown in kilo-light-years
(KLY), mega, giga, etc. units, making up prefixes after 'yocto'. Thus,
one "ALY" = 10^78 light-years. Since the universe is 13.7 billion years
old, and nothing can be seen beyond that point, such distances are
physically unreasonable by a factor of roughly 10^68. But for debugging
purposes, display of these distances was useful. The bug is now fixed,
so with any luck, nobody should see such distances again.
2012 Feb 13: there's some interest in determining orbits of _very_
close objects, such as tennis balls. To address this, short distances
are now shown in millimeters, centimeters, meters, or .1 km,
as appropriate.
NOTE: It used to be that I followed MPC practice in showing all distances
between .01 and ten AU in the form d.dddd , but now, that's only true for
one to ten AU. For distances less than 1 AU, I'm using .ddddd, thereby
getting an extra digit displayed. */
static void show_dist_in_au( char *buff, const double dist_in_au)
{
const char *fmt;
if( dist_in_au > 999.999)
fmt = "%7.1f"; /* " 1234.5" */
else if( dist_in_au > 99.999)
fmt = "%7.2f"; /* " 123.45" */
else if( dist_in_au > 9.999)
fmt = "%7.3f"; /* " 12.345" */
else if( dist_in_au > .99) /* used to be .01 */
fmt = "%7.4f"; /* " 1.2345" */
else
fmt = "%7.5f"; /* " .12345" */
snprintf_err( buff, 8, fmt, dist_in_au);
*buff = ' '; /* remove leading zero for small amounts */
}
static const char *si_prefixes = "kMGTPEZYRQXWVUSONLJIHFDCBA";
static bool use_au_only = false;
/* Given a non-negative value, this gives a four-character output
such as '3.14', '.314', '3145', '314k', '3.1M', etc. */
static void show_packed_with_si_prefixes( char *buff, double ival)
{
*buff = '\0';
if( ival > 999.e+21)
strcpy( buff, "!!!!");
else if( ival > 9999.)
{
unsigned count = 0;
*buff = '\0';
while( !*buff)
{
ival /= 1000.;
if( ival < 9.9)
snprintf_err( buff, 5, "%3.1f%c", ival, si_prefixes[count]);
else if( ival < 999.)
snprintf_err( buff, 5, "%3u%c", (unsigned)ival, si_prefixes[count]);
count++;
}
}
else if( ival > 99.9)
snprintf_err( buff, 5, "%4u", (unsigned)( ival + .5));
else if( ival > 9.99)
snprintf_err( buff, 5, "%4.1f", ival);
else if( ival > .99)
snprintf_err( buff, 5, "%4.2f", ival);
else
{
char tbuff[7];
snprintf_err( tbuff, sizeof( tbuff), "%5.2f", ival);
strcpy( buff, tbuff + 1); /* store value without leading 0 */
}
}
void format_dist_in_buff( char *buff, const double dist_in_au)
{
if( dist_in_au < 0.)
strcpy( buff, " <NEG!>");
else if( use_au_only == true)
show_dist_in_au( buff, dist_in_au);
else
{
const double dist_in_km = dist_in_au * AU_IN_KM;
const char *fmt;
/* for objects within a million km (about 2.5 times */
/* the distance to the moon), switch to km/m/cm/mm: */
if( dist_in_km < .0099) /* 0 to 9900 millimeters: */
snprintf_err( buff, 8, "%5.0fmm", dist_in_km * 1e+6); /* " NNNNmm" */
else if( dist_in_km < .099) /* 990 to 9900 centimeters: */
snprintf_err( buff, 8, "%5.0fcm", dist_in_km * 1e+5); /* " NNNNcm" */
else if( dist_in_km < 99.) /* 99 to 99000 meters: */
snprintf_err( buff, 8, "%6.0fm", dist_in_km * 1e+3); /* " NNNNNm" */
else if( dist_in_km < 999.) /* 99.0 to 999.9 kilometers: */
snprintf_err( buff, 8, "%6.1fk", dist_in_km); /* " NNN.Nk" */
else if( dist_in_km < 999999.) /* 999.9 to 999999 km: */
snprintf_err( buff, 8, "%7.0f", dist_in_km);
else if( dist_in_au > 9999.999)
{
double dist_in_light_years =
dist_in_au * AU_IN_KM / LIGHT_YEAR_IN_KM;
if( dist_in_light_years > 9999.9)
{
int idx = 0;
dist_in_light_years /= 1000;
for( idx = 0; si_prefixes[idx] && dist_in_light_years > 999.; idx++)
dist_in_light_years /= 1000;
if( !si_prefixes[idx]) /* can't represent this even in our */
strcpy( buff, " <HUGE>"); /* largest made-up units */
else
{
if( dist_in_light_years < 9.9)
snprintf_err( buff, 8, "%4.1fxLY", dist_in_light_years);
else
snprintf_err( buff, 8, "%4.0fxLY", dist_in_light_years);
buff[4] = si_prefixes[idx];
}
}
else
{
if( dist_in_light_years > 99.999) /* " 1234LY" */
fmt = "%5.0fLY";
else if( dist_in_light_years > 9.999) /* " 12.3LY" */
fmt = "%5.1fLY";
else if( dist_in_light_years > .999)
fmt = "%5.2fLY"; /* " 1.23LY" */
else
fmt = "%5.3fLY"; /* " .123LY" */
snprintf_err( buff, 8, fmt, dist_in_light_years);
}
}
else
show_dist_in_au( buff, dist_in_au);
*buff = ' '; /* remove leading zero for small amts */
}
}
/* Input velocity is in km/s. If it's greater than about */
/* three times the speed of light, we show it in units of c. */
/* Of course, this will never happen with real objects; I */
/* added it for debugging purposes. */
static void format_velocity_in_buff( char *buff, double vel)
{
const char *format;
if( vel < 9.999 && vel > -9.999)
format = "%7.3f";
else if( vel < 99.999 && vel > -99.999)
format = "%7.2f";
else if( vel < 999.9 && vel > -999.9)
format = "%7.1f";
else if( vel < 999999. && vel > -999999.)
format = "%7.0f";
else /* show velocity in terms of speed of light. */
{
vel /= SPEED_OF_LIGHT;
if( vel < 99.999 && vel > -99.999)
format = "%6.1fc";
else if( vel < 999999. && vel > -999999.)
format = "%6.0fc";
else /* we give up; it's too fast */
format = " !!!!!!";
}
snprintf_err( buff, 8, format, vel);
}
static void ra_dec_to_alt_az_2( const int planet, const DPT *ra_dec, DPT *alt_az,
const DPT *latlon, const double jd_utc, double *hour_angle)
{
double matrix[9], vect[3], vect_out[3];
polar3_to_cartesian( vect, -ra_dec->x, ra_dec->y);
calc_planet_orientation( planet, 0, jd_utc, matrix);
spin_matrix( matrix, matrix + 3, latlon->x);
if( hour_angle)
*hour_angle = atan2( -dot_product( vect, matrix + 3), dot_product( vect, matrix));
spin_matrix( matrix, matrix + 6, PI / 2. - latlon->y);
precess_vector( matrix, vect, vect_out);
alt_az->x = atan2( vect_out[1], vect_out[0]);
alt_az->y = asine( vect_out[2]);
}
/* Rob Matson asked about having the program produce ECF (Earth-Centered
Fixed) coordinates, in geometric lat/lon/altitude form. This 'ground
track' option in ephemerides has since been expanded to allow geodetic
output, with the possibility of creating such ephemerides from other
planets as well. */
double find_lat_lon_alt( const double ut, const double *ivect,
const int planet_no, double *lat_lon, const bool geometric);
/* 'get_step_size' parses input text to get a step size in days, so that */
/* '4h' becomes .16667 days, '30m' becomes 1/48 day, and '10s' becomes */
/* 10/(24*60*60) days. The units (days, hours, minutes, or seconds) are */
/* returned in 'step_units' if the input pointer is non-NULL. The number */
/* of digits necessary is returned in 'step_digits' if that pointer is */
/* non-NULL. Both are used to ensure correct time format in ephemeris */
/* output; that is, if the step size is (say) .05d, the output times */
/* ought to be in a format such as '2009 Mar 8.34', two places in days. */
double get_step_size( const char *stepsize, char *step_units, int *step_digits)
{
double step = 0.;
char units = 'd';
if( !strncmp( stepsize, "Obs", 3) || *stepsize == 't') /* dummy value */
step = 1e-6;
if( *stepsize == 'a')
{
step = 1e-6;
if( step_digits)
*step_digits = 0;
}
if( sscanf( stepsize, "%lf%c", &step, &units) >= 1)
if( step)
{
if( step_digits)
{
const char *tptr = strchr( stepsize, '.');
*step_digits = 0;
if( tptr)
{
tptr++;
while( isdigit( *tptr++))
(*step_digits)++;
}
#ifdef OBSOLETE_METHOD
double tval = fabs( step);
for( *step_digits = 0; tval < .999; (*step_digits)++)
tval *= 10.;
#endif
}
units = tolower( units);
if( step_units)
*step_units = units;
switch( units)
{
case 'd':
break;
case 'h':
step /= hours_per_day;
break;
case 'm':
step /= minutes_per_day;
break;
case 's':
step /= seconds_per_day;
break;
case 'w':
step *= 7.;
break;
case 'y':
step *= 365.25;
break;
}
}
return( step);
}
static double centralize_ang_around_zero( double ang)
{
ang = fmod( ang, PI + PI);
if( ang > PI)
ang -= PI + PI;
else if( ang <= -PI)
ang += PI + PI;
return( ang);
}
typedef struct
{
double ra, dec, jd, r;
double sun_obj, sun_earth;
} obj_location_t;
static void setup_obj_loc( obj_location_t *p, double *orbit,
const size_t n_orbits, const double epoch_jd, const char *mpc_code)
{
size_t i, j;
mpc_code_t cinfo;
double obs_posn[3];
int planet_no = 3;
assert( p->jd > 2e+6);
assert( p->jd < 3e+6);
assert( mpc_code);
planet_no = get_observer_data( mpc_code, NULL, &cinfo);
compute_observer_loc( p->jd, planet_no, cinfo.rho_cos_phi, cinfo.rho_sin_phi,
cinfo.lon, obs_posn);
for( i = 0; i < n_orbits; i++)
{
double topo[3], time_lag;
if( !mpc_code)
p[i].r = 0.;
assert( p[i].r >= 0.);
assert( p[i].r < 100.);
integrate_orbit( orbit, epoch_jd, p->jd);
time_lag = p[i].r / AU_PER_DAY;
for( j = 0; j < 3; j++)
topo[j] = orbit[j] - obs_posn[j] - time_lag * orbit[j + 3];
ecliptic_to_equatorial( topo);
p[i].ra = atan2( topo[1], topo[0]);
p[i].r = vector3_length( topo);
p[i].dec = asin( topo[2] / p[i].r);
p[i].sun_earth = vector3_length( obs_posn);
p[i].sun_obj = vector3_length( orbit);
orbit += n_orbit_params;
}
}
/* Here, we take the computed sky brightness from the Schaefer-Krisciunas
model and add in the contribution from another source, such as light
pollution and/or galactic background. For both of those, I don't really
have a good concept of the adjustment for each band; the 'multipliers'
are somewhat ad hoc. */
static void adjust_sky_brightness_for_added_light_source(
BRIGHTNESS_DATA *bdata, const double mags_per_arcsec_squared)
{
const double brightness =
exp( -0.4 * LOG_10 * (11.055 + mags_per_arcsec_squared));
size_t i;
const double multipliers[5] = { .01, .01, .2, 1.0, 1.0 };
for( i = 0; i < 5; i++)
bdata->brightness[i] += brightness * multipliers[i];
}
#pragma pack( 1)
typedef struct
{
double ra, dec, jd;
double height, width, tilt;
uint32_t file_offset;
char obscode[4];
char file_number;
} field_location_t;
typedef struct
{
double height, width;
double min_jd, max_jd;
char obscode[4], file_number;
} field_group_t;
#pragma pack( )
/* In searching for fields, we may be interested in fields _within_ a certain
range of dates, or those _outside_ that range. We signal the former with
max_jd > min_jd. We signal the latter by reversing them (min_jd > max_jd.) */
static inline bool jd_is_in_range( const double jd, const double min_jd,
const double max_jd)
{
if( max_jd > min_jd) /* looking for fields _within_ this range */
return( jd > min_jd && jd < max_jd);
else /* looking for fields _outside_ this range */
return( jd < min_jd || jd > max_jd);
}
static int put_ephemeris_posn_angle_sigma( char *obuff, const double dist,
const double posn_ang, const bool computer_friendly)
{
int integer_posn_ang =
(int)( floor( -posn_ang * 180. / PI + .5)) % 180;
const double dist_in_arcsec = dist * 3600. * 180. / PI;
char resid_buff[9];
if( integer_posn_ang < 0)
integer_posn_ang += 180;
if( computer_friendly)
snprintf_err( resid_buff, sizeof( resid_buff), " %6u",
(unsigned)dist_in_arcsec);
else
{
put_residual_into_text( resid_buff, dist_in_arcsec,
RESIDUAL_FORMAT_OVERPRECISE);
resid_buff[5] = '\0';
}
snprintf_err( obuff, 13, "%s %3d", resid_buff + 1, integer_posn_ang);
return( integer_posn_ang);
}
/* Old MSVCs and OpenWATCOM lack erf() and many other math functions: */
#if defined( _MSC_VER) && (_MSC_VER < 1800) || defined( __WATCOMC__)
double erf( double x); /* orb_fun2.cpp */
#endif
#define SWAP( A, B, TEMP) { TEMP = A; A = B; B = TEMP; }
/* At present, this assumes a 'nominal' position in p[0] and a one-sigma
variant in p[1]. We figure out the range, in sigmas, of that line within
the rectangle defined by 'field' (keeping in mind that the line may miss
the rectangle entirely, and usually does). But if the line of variation
_does_ go through the triangle, running from sigma1 to sigma2, then we
evaluate the probability that the object is on that field as the area
under the normal curve between sigma1 and sigma2, and return that.
For cases where we don't have variant orbits (n_objs == 1), we just
set up a really low difference and are basically just checking to see if
the nominal position is on the field. (Which, with one orbit, is all
we can do anyway.)
For objects with low positional uncertainty, that probability will
usually be essentially 1 or 0. If the uncertainty is close to the field
size, you'll start to see "maybe it's on the field and maybe it isn't"
cases.
TO BE DONE: figure out how to extend this to non-covariance (SR) cases.
I've ideas for this... but first, the (more common) covariance case. */
static double precovery_in_field( const field_location_t *field,
const obj_location_t *p, const unsigned n_objs,
const double margin)
{
double sigma1 = -10., sigma2 = 10.;
const double d_ra = (n_objs > 1 ? p[1].ra - p[0].ra : 1e-8);
const double d_dec = (n_objs > 1 ? p[1].dec - p[0].dec : 1e-8);
double sig1, sig2, temp, size;
const double sqrt_2 =
1.414213562373095048801688724209698078569671875376948073176679737990732;
size = (field->width / 2. + margin) / cos( field->dec);
sig1 = centralize_ang_around_zero( field->ra + size - p[0].ra) / d_ra;
sig2 = sig1 - 2 * size / d_ra;
if( sig1 > sig2)
SWAP( sig1, sig2, temp);
if( sigma1 < sig1)
sigma1 = sig1;
if( sigma2 > sig2)
sigma2 = sig2;
size = field->height / 2. + margin;
sig1 = (field->dec + size - p[0].dec) / d_dec;
sig2 = (field->dec - size - p[0].dec) / d_dec;
if( sig1 > sig2)
SWAP( sig1, sig2, temp);
if( sigma1 < sig1)
sigma1 = sig1;
if( sigma2 > sig2)
sigma2 = sig2;
if( sigma1 >= sigma2)
return( 0.);
else
return( (erf( sigma2 / sqrt_2) - erf( sigma1 / sqrt_2)) * .5);
}
static void show_precovery_extent( char *obuff, const obj_location_t *objs,
const int n_objs)
{
*obuff = '\0';
if( n_objs == 2)
{
double dist, posn_ang;
calc_dist_and_posn_ang( &objs[0].ra, &objs[1].ra,
&dist, &posn_ang);
put_ephemeris_posn_angle_sigma( obuff, dist, posn_ang, true);
}
}
/* See 'precover.txt' for information on what's going on here. */
#define FIELD_BUFF_N 1024
#define COMPRESSED_FIELD_SIZE 18
static void extract_field( field_location_t *field, const char *buff,
const field_group_t *groups)
{
int32_t array[4];
assert( buff[16] >= 0);
assert( strlen( groups->obscode) == 3);
groups += buff[16];
assert( strlen( groups->obscode) == 3);
memcpy( array, buff, 4 * sizeof( int32_t));
field->ra = (double)array[0] * 2. * PI / 2e+9;
field->dec = (double)array[1] * PI / 2e+9;
field->jd = groups->min_jd + (groups->max_jd - groups->min_jd)
* (double)array[2] / 2e+9;
field->file_offset = array[3];
field->tilt = (double)buff[17] * PI / 256.;
field->height = groups->height;
field->width = groups->width;
field->file_number = groups->file_number;
strlcpy_error( field->obscode, groups->obscode);
}
static int find_precovery_plates( OBSERVE *obs, const int n_obs,
const char *idx_filename,
FILE *ofile, const double *orbit,
const int n_orbits, double epoch_jd,
const double min_jd, const double max_jd,
const double limiting_mag)
{
FILE *ifile, *original_file = NULL;
int current_file_number = -1;
double *orbi, stepsize = 1., max_jd_available, min_jd_available;
obj_location_t *p1, *p2, *p3;
int n_fields_read, n;
const double abs_mag = calc_absolute_magnitude( obs, n_obs);
char *buff;
/* Slightly easier to work with 'bit set means included' : */
const int inclusion = atoi( get_environment_ptr( "FIELD_INCLUSION")) ^ 3;
const bool show_base_60 = (*get_environment_ptr( "FIELD_DEBUG") != '\0');
size_t n_groups;
field_group_t *groups;
if( !ofile)
return( -1);
ifile = fopen_ext( idx_filename, "crb");
if( !ifile)
{
debug_printf( "Couldn't open %s\n", idx_filename);
return( -2);
}
p1 = (obj_location_t *)calloc( 3 * n_orbits, sizeof( obj_location_t));
p2 = p1 + n_orbits;
p3 = p2 + n_orbits;
buff = (char *)calloc( FIELD_BUFF_N, COMPRESSED_FIELD_SIZE);
assert( buff);
if( !fgets( buff, 100, ifile))
return( -4);
n_groups = (size_t)atoi( buff);
assert( n_groups);
groups = (field_group_t *)calloc( n_groups, sizeof( field_group_t));
assert( groups);
if( fread( groups, sizeof( field_group_t), n_groups, ifile) != n_groups)
return( -3);
orbi = (double *)malloc( 2 * n_orbit_params * n_orbits * sizeof( double));
memcpy( orbi, orbit, n_orbit_params * n_orbits * sizeof( double));
while( (n_fields_read = (int)fread( buff, COMPRESSED_FIELD_SIZE, FIELD_BUFF_N, ifile)) > 0)
for( n = 0; n < n_fields_read; n++)
{
field_location_t field;
extract_field( &field, buff + n * COMPRESSED_FIELD_SIZE, groups);
if( jd_is_in_range( field.jd, min_jd, max_jd))
{
double fraction, mag;
double margin = .1;
const double jdt = field.jd + td_minus_utc( field.jd) / seconds_per_day;
bool possibly_within_field = false;
double prob;
int i;
while( jdt < p1->jd || jdt > p2->jd)
{
const double new_p2_jd = ceil( (jdt - .5) / stepsize) * stepsize + .5;
const double scale_factor = 2.;
if( new_p2_jd == p1->jd)
memcpy( p2, p1, n_orbits * sizeof( obj_location_t));
else if( new_p2_jd != p2->jd)
{
p2->jd = new_p2_jd;
setup_obj_loc( p2, orbi, n_orbits, epoch_jd, "500");
epoch_jd = p2->jd;
}
while( stepsize > p2->r * scale_factor)
stepsize /= 2.;
while( stepsize < p2->r * scale_factor)
stepsize *= 2.;
p1->jd = new_p2_jd - stepsize;
setup_obj_loc( p1, orbi, n_orbits, epoch_jd, "500");
epoch_jd = p1->jd;
}
fraction = (jdt - p1->jd) / stepsize;
for( i = 0; i < n_orbits; i++) /* compute approx RA/decs */
{
const double delta_ra = p2[i].ra - p1[i].ra;
p3[i].ra = p1[i].ra + fraction * centralize_ang_around_zero( delta_ra);
p3[i].dec = p1[i].dec + fraction * (p2[i].dec - p1[i].dec);
}
margin += EARTH_RADIUS_IN_AU / p1->r;
mag = abs_mag + calc_obs_magnitude(
p2->sun_obj, p2->r, p2->sun_earth, NULL);
if( mag < limiting_mag && precovery_in_field( &field, p3, n_orbits, margin) > .01)
{ /* approx posn is on plate; compute */
double *temp_orbit = orbi + n_orbit_params * n_orbits;
memcpy( temp_orbit, orbi, n_orbit_params * n_orbits * sizeof( double));
memcpy( p3, p2, n_orbits * sizeof( obj_location_t));
p3->jd = jdt;
setup_obj_loc( p3, temp_orbit, n_orbits, epoch_jd, field.obscode);
possibly_within_field = true;
}
if( mag < limiting_mag && possibly_within_field
&& (prob = precovery_in_field( &field, p3, n_orbits, 0.)) > .1)
{
char time_buff[40], buff[200];
bool matches_an_observation = false;
bool show_it = true;
double obj_ra = p3->ra, obj_dec = p3->dec;
full_ctime( time_buff, field.jd, FULL_CTIME_YMD
| FULL_CTIME_LEADING_ZEROES
| FULL_CTIME_MONTHS_AS_DIGITS | FULL_CTIME_TENTHS_SEC);
obj_ra = centralize_ang( obj_ra);
for( i = 0; i < n_obs; i++)
if( fabs( obs[i].jd - jdt) < 1.e-3
&& !strcmp( field.obscode, obs[i].mpc_code))
matches_an_observation = true;
if( matches_an_observation)
show_it = ((inclusion & 2) != 0);
else
show_it = ((inclusion & 1) != 0);
if( show_it)
{
obj_ra *= 180. / PI;
obj_dec *= 180. / PI;
if( !show_base_60)
snprintf_err( buff, sizeof( buff), "%8.4f %8.4f",
obj_ra, obj_dec);
else
{
output_angle_to_buff( buff, obj_ra / 15., 3);
buff[12] = ' ';
output_signed_angle_to_buff( buff + 13, obj_dec, 2);
}
fprintf( ofile, "%c %s %4.1f %s %s",
(matches_an_observation ? '*' : ' '), buff, mag,
time_buff, field.obscode);
if( current_file_number != field.file_number)
{
char filename[20];
current_file_number = field.file_number;
snprintf_err( filename, sizeof( filename), "css_%d.csv",
current_file_number);
if( original_file)
fclose( original_file);
original_file = fopen_ext( filename, "crb");
if( !original_file)
fprintf( ofile, "'%s' not opened\n", filename);
}
show_precovery_extent( buff, p1, n_orbits);
snprintf_append( buff, sizeof( buff), " %.3f ", prob);
fprintf( ofile, "%s", buff);
if( original_file)
{
fseek( original_file, field.file_offset, SEEK_SET);
if( fgets_trimmed( buff, sizeof( buff), original_file))
{
for( i = 0; buff[i]; i++)
if( buff[i] == ',')
buff[i] = ' ';
fprintf( ofile, " %s", buff);
}
else
fprintf( ofile, "File %d: seeked to %ld and failed",
(int)field.file_number, (long)field.file_offset);
}
fprintf( ofile, "\n");
}
}
}
}
fclose( ifile);
max_jd_available = 0.;
min_jd_available = 3e+7;
for( size_t i = 0; i < n_groups; i++)
{
if( max_jd_available < groups[i].max_jd)
max_jd_available = groups[i].max_jd;
if( min_jd_available > groups[i].min_jd)
min_jd_available = groups[i].min_jd;
}
full_ctime( buff, min_jd_available, 0);
full_ctime( buff + 80, max_jd_available, 0);
fprintf( ofile, "Pointing data covers %s to %s\n", buff, buff + 80);
free( buff);
free( groups);
if( original_file)
fclose( original_file);
free( orbi);
free( p1);
return( 0);
}
/* In the following, I'm assuming an object with H=0 and albedo=100% to
have a diameter of 1300 km. Return value is in meters. */
double diameter_from_abs_mag( const double abs_mag,
const double optical_albedo)
{
return( 1300. * 1000. * pow( .1, abs_mag / 5.) / sqrt( optical_albedo));
}
#define RADAR_DATA struct radar_data
RADAR_DATA
{
double power_in_watts;
double system_temp_deg_k;
double gain, radar_constant;
double altitude_limit;
};
static inline int get_radar_data( const char *mpc_code, RADAR_DATA *rdata)
{
char tbuff[20];
const char *tptr;
int rval = -1;
memset( rdata, 0, sizeof( RADAR_DATA));
snprintf_err( tbuff, sizeof( tbuff), "RADAR_%.3s", mpc_code);
tptr = get_environment_ptr( tbuff);
if( tptr)
if( sscanf( tptr, "%lf,%lf,%lf,%lf,%lf",
&rdata->power_in_watts, &rdata->system_temp_deg_k,
&rdata->gain, &rdata->altitude_limit,
&rdata->radar_constant) == 5)
rval = 0;
rdata->altitude_limit *= PI / 180.;
return( rval);
}
/* In computing radar SNR, we need to either measure the rotation period
(if we're lucky, and somebody does a light curve) or take an educated guess
at it, as a function of absolute magnitude. In general, smaller rocks
spin faster than bigger rocks.
I asked about this, and Mike Nolan replied : "I tend to use 4h for
larger than H=21, 1 for H=21-25, and .25 for H > 25. We don't really know
the distribution for the small stuff, as the biases are pretty big." To
which Lance Benner replied : "We've been adopting a somewhat more
conservative value of P = 2.1 h for objects with H < 22. This is based
on the observed distribution of NEA rotation periods (although there are a
couple of exceptions). For smaller objects, a similar cutoff doesn't seem
to exist, but rapid rotators are relatively common, so we adopt P = 0.5h."
In the following, I went with a three-hour period for H<=21 and a .3
hour period for H>=25, linearly interpolating for 21 < H < 25.
Fortunately, SNR/day in the formula below depends on the square root of
the period. If we're out by a factor of two on our guess, it'll mess up the
SNR/day by a factor of the square root of two. I'd guess that errors due to
under- or over-estimating the albedo or H probably cause much more trouble.
*/
static double guessed_rotation_period_in_hours( const double abs_mag)
{
double rval;
const double big_limit = 21., big_period = 3.; /* H=21 rocks spin in 3h */
const double small_limit = 25., small_period = 0.3;
/* little H=25 rocks spin in a mere 18 minutes */
if( abs_mag < big_limit)
rval = big_period;
else if( abs_mag < small_limit)
rval = small_period +
(big_period - small_period) * (small_limit - abs_mag) / (small_limit - big_limit);
else /* small, fast-spinning rocks */
rval = small_period;
return( rval);
}
/* In a private communication, Lance Benner wrote:
"...The signal-to-noise ratio is proportional to:
[(Ptx)(radar albedo)(D^3/2)(P^1/2)(t^1/2)] <-- numerator
------------------------------------------
[(r^4)*(Tsys)] <-- denominator
where Ptx is the transmitter power, the radar albedo is the radar cross section
divided by the projected area of the object, D is the diameter, P is the
rotation period, t is the integration time, r is the distance from the
telescope, and Tsys is the system temperature."
Implicitly, this is also all multiplied by a gain factor, and a
constant known in this code as 'radar_constant'.
He also mentioned that Arecibo operates at about 500 kW, Tsys = 25 K,
gain = 10 K/Jy; Goldstone at 450 kW, Tsys = 15, gain = 0.94. These
values are enshrined in the RADAR_251 and RADAR_253 lines in
'environ.dat', along with the 'radar_constant' values. I got those
essentially by guessing, then scaling them until they matched values in
radar planning documents. (Unfortunately, Arecibo is now at 350 kW and
gain=7 K/Jy due to Maria damage.)
See also Lance's comments at
https://groups.io/g/mpml/message/28412
and an excellent page on the subject at
http://www.naic.edu/~pradar/detect.php
Lance also noted that there's also a more subtle dependence due to the subradar
latitude (you get a better echo if the pole is pointing straight at the radar).
Jean-Luc Margot's page:
http://www2.ess.ucla.edu/~jlm/research/NEAs/intro.html
has a graphic showing this dependence. A 20-meter object with a four-hour
period and albedo=.1, at a distance of .1 AU, has SNR/day = 1.
For Goldstone, the SNR is about 1/20 of this (from JLM's page; I think
this assumes Arecibo going at 900 kW.) The same page shows a dropoff in SNR
due to declination: the above formula holds at dec=+18, but SNR drops to
zero at dec=-1 or dec=37. In reality, it should be a drop in _altitude_ :
i.e., Arecibo sees "perfectly" at the zenith, and degrades as you drop from
there. Mike Nolan tells me (private e-mail communication) that the width is
about 19.5 degrees, so that Arecibo can "see" down to about altitude = 70.5
degrees. The drop factor isn't given (and is probably empirically derived),
but it looks a lot like
SNR( alt) = SNR( zenith) * ((90 - alt)/19.5) ^ .25, 70.5 < alt < 90
Or something like that, perhaps with a different exponent: a function
equal to one at alt=90 degrees and zero at alt=70.5 degrees, with roughly
the right behavior in between.
See further comments in 'environ.def'.
Other quantities of interest for radar: the 'number of runs', i.e.,
for the time the object is above the horizon, you'll start by transmitting
power for the entire round-trip time to the object. Then you shut off and
listen for the returning data for an equal time. Then you switch back to