forked from Bill-Gray/find_orb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathorb_func.cpp
4430 lines (4003 loc) · 164 KB
/
orb_func.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
/* orb_func.cpp: basic orbital element/numerical integration funcs
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. */
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include <stdio.h>
#include <time.h>
#include "watdefs.h"
#include "comets.h"
#include "mpc_obs.h"
#include "lsquare.h"
#include "date.h"
#include "afuncs.h"
#include "lunar.h"
#include "monte0.h"
#ifndef _MSC_VER
/* All non-Microsoft builds are for the console */
#define CONSOLE
#endif
#ifdef CONSOLE
/* In the console version of Find_Orb, the following two functions */
/* get remapped to Curses functions. In the non-interactive one, */
/* they're mapped to 'do-nothings'. See fo.cpp & find_orb.cpp. */
void refresh_console( void);
void move_add_nstr( const int col, const int row, const char *msg, const int n_bytes);
#endif
/* MS only got around to adding 'isfinite' in VS2013 : */
#if defined( _MSC_VER) && (_MSC_VER < 1800)
#include <float.h>
#define isfinite _finite
#endif
unsigned perturbers = 0;
int integration_method = 0;
extern int debug_level;
int generic_message_box( const char *message, const char *box_type);
#define AUTOMATIC_PERTURBERS 1
#define J2000 2451545.
#define JD_TO_YEAR( jd) (2000. + ((jd) - J2000) / 365.25)
#define MAX_CONSTRAINTS 5
#define PI 3.1415926535897932384626433832795028841971693993751058209749445923078
#define GAUSS_K .01720209895
#define SOLAR_GM (GAUSS_K * GAUSS_K)
/* GAUSS_K is a fixed constant. SOLAR_GM = 0.0002959122082855911025, */
/* in AU^3/day^2; = 1.3271243994E+11 km3/s2 */
const double SRP1AU = 2.3e-7;
/* "Solar radiation pressure at 1 AU", in kg*AU^3 / (m^2*d^2), */
/* from a private communication from Steve Chesley. This means */
/* that if you had a one-kilogram object showing one square */
/* meter of surface area to the sun, and it was one AU from the */
/* sun, and it absorbed all the solar radiation (and re-radiated */
/* it isotropically; i.e., the re-radiated photons didn't cause */
/* any net force), then that object would accelerate away from */
/* the sun at 2.3e-7 AU/day^2 (a.k.a. 4.562e-6 m/s^2). */
/* */
/* One can derive SRP1AU from basic principles. The 'solar */
/* constant' is C = 1367.6 AU^2*W/m^2; i.e., if you set up a */
/* one square meter solar panel with 100% efficiency one AU from */
/* the Sun, pointed straight at the sun, it would generate */
/* 1367.6 watts. To get the above number, one uses */
/* */
/* SRP1AU = C * d^2 / (meters_per_AU * c) */
/* */
/* C = 1367.6 AU^2*W/m^2 = 1367.6 AU^2*kg/s^3 */
/* d = 86400 seconds/day */
/* meters_per_AU = 1495978707 m/AU */
/* c = 299792458 m/s */
/* */
/* The result indicates that if the solar panel in question */
/* had a mass of one kilogram, it would accelerate away from the */
/* sun at 2.27636e-7 AU/day^2. I think Steve rounded off with a */
/* one-percent error because that's a decent match to the accuracy */
/* you can expect with real-world objects that reflect and re-radiate */
/* photons, instead of politely absorbing them and then re-radiating */
/* them isotropically. */
/* */
/* Interestingly, this also means that an object with area/mass = */
/* 1286 m^2/kg would have SRP balancing the sun's gravity. Which */
/* would make it big and light. Solar sails aren't easy. */
int n_extra_params = 0, setting_outside_of_arc = 1;
double solar_pressure[MAX_N_NONGRAV_PARAMS], uncertainty_parameter = 99.;
int available_sigmas = NO_SIGMAS_AVAILABLE;
int available_sigmas_hash = 0;
static bool fail_on_hitting_planet = false;
double gaussian_random( void); /* monte0.c */
int get_residual_data( const OBSERVE *obs, double *xresid, double *yresid);
int debug_printf( const char *format, ...) /* runge.cpp */
#ifdef __GNUC__
__attribute__ (( format( printf, 1, 2)))
#endif
;
double initial_orbit( OBSERVE FAR *obs, int n_obs, double *orbit);
int adjust_herget_results( OBSERVE FAR *obs, int n_obs, double *orbit);
int find_trial_orbit( double *orbit, OBSERVE FAR *obs, int n_obs,
const double r1, const double angle_param); /* orb_func.cpp */
int search_for_trial_orbit( double *orbit, OBSERVE FAR *obs, int n_obs,
const double r1, double *angle_param); /* orb_func.cpp */
int set_locs( const double *orbit, double t0, OBSERVE FAR *obs, int n_obs);
int find_best_fit_planet( const double jd, const double *ivect,
double *rel_vect); /* runge.cpp */
const char *get_environment_ptr( const char *env_ptr); /* mpc_obs.cpp */
static int evaluate_limited_orbit( const double *orbit,
const int planet_orbiting, const double epoch,
const char *limited_orbit, double *constraints);
void remove_trailing_cr_lf( char *buff); /* ephem0.cpp */
int find_relative_orbit( const double jd, const double *ivect,
ELEMENTS *elements, const int ref_planet); /* runge.cpp */
void format_dist_in_buff( char *buff, const double dist_in_au); /* ephem0.c */
static inline void look_for_best_subarc( const OBSERVE FAR *obs,
const int n_obs, const double max_arc_len, int *start, int *end);
int check_for_perturbers( const double t_cen, const double *vect); /* sm_vsop*/
int get_idx1_and_idx2( const int n_obs, const OBSERVE FAR *obs,
int *idx1, int *idx2); /* elem_out.c */
void set_distance( OBSERVE FAR *obs, double r); /* orb_func.c */
double find_r_given_solar_r( const OBSERVE FAR *obs, const double solar_r);
static void attempt_extensions( OBSERVE *obs, const int n_obs, double *orbit);
double *get_asteroid_mass( const int astnum); /* bc405.cpp */
char *get_file_name( char *filename, const char *template_file_name);
int compute_observer_loc( const double jde, const int planet_no,
const double rho_cos_phi, /* mpc_obs.cpp */
const double rho_sin_phi, const double lon, double FAR *offset);
int compute_observer_vel( const double jde, const int planet_no,
const double rho_cos_phi, /* mpc_obs.cpp */
const double rho_sin_phi, const double lon, double FAR *vel);
void get_relative_vector( const double jd, const double *ivect,
double *relative_vect, const int planet_orbiting); /* orb_func.c */
double get_planet_mass( const int planet_idx); /* orb_func.c */
int compute_available_sigmas_hash( const OBSERVE FAR *obs, const int n_obs,
const double epoch, const unsigned perturbers, const int central_obj);
double vector3_dist( const double *a, const double *b); /* orb_func.c */
double euler_function( const OBSERVE FAR *obs1, const OBSERVE FAR *obs2);
double evaluate_initial_orbit( const OBSERVE FAR *obs, /* orb_func.c */
const int n_obs, const double *orbit);
static int find_transfer_orbit( double *orbit, OBSERVE FAR *obs1,
OBSERVE FAR *obs2,
const int already_have_approximate_orbit);
double observation_rms( const OBSERVE FAR *obs); /* elem_out.cpp */
double compute_weighted_rms( const OBSERVE FAR *obs, const int n_obs,
int *n_resids); /* orb_func.cpp */
double find_epoch_shown( const OBSERVE *obs, const int n_obs); /* elem_out */
FILE *fopen_ext( const char *filename, const char *permits); /* miscell.cpp */
int snprintf_append( char *string, const size_t max_len, /* ephem0.cpp */
const char *format, ...)
#ifdef __GNUC__
__attribute__ (( format( printf, 3, 4)))
#endif
;
void set_obs_vect( OBSERVE FAR *obs); /* mpc_obs.h */
double improve_along_lov( double *orbit, const double epoch, const double *lov,
const unsigned n_params, unsigned n_obs, OBSERVE *obs);
void adjust_error_ellipse_for_timing_error( double *sigma_a, double *sigma_b,
double *angle, const double vx, const double vy); /* errors.cpp */
void compute_error_ellipse_adjusted_for_motion( double *sigma1, double *sigma2,
double *posn_angle, const OBSERVE *obs,
const MOTION_DETAILS *m); /* orb_func.cpp */
double n_nearby_obs( const OBSERVE FAR *obs, const unsigned n_obs,
const unsigned idx, const double time_span); /* orb_func.cpp */
double find_parabolic_minimum_point( const double x[3], const double y[3]);
int orbital_monte_carlo( const double *orbit, OBSERVE *obs, const int n_obs,
const double curr_epoch, const double epoch_shown); /* orb_func.cpp */
void set_distance( OBSERVE FAR *obs, double r)
{
int i;
obs->r = r;
for( i = 0; i < 3; i++)
obs->obj_posn[i] = obs->obs_posn[i] + r * obs->vect[i];
obs->solar_r = vector3_length( obs->obj_posn);
}
static double dot_prod( const double *a, const double *b)
{
return( a[0] * b[0] + a[1] * b[1] + a[2] * b[2]);
}
double vector3_dist( const double *a, const double *b)
{
const double dx = a[0] - b[0];
const double dy = a[1] - b[1];
const double dz = a[2] - b[2];
return( sqrt( dx * dx + dy * dy + dz * dz));
}
/* Euler found that for a parabolic orbit starting at distance r1 from
the sun, ending up at a distance r2, with a straight-line distance s
between them, the time required can be found from
(r1 + r2 + s) ^ 1.5 +/- (r1 + r2 - s) ^ 1.5 = 6kt
(minus sign if you're taking the "short route" -- sun isn't in the arc
you travel -- or positive sign if you go around the sun instead.)
Our interest is in the "short route". If the time for a transfer orbit
is less than that time, only a hyperbolic orbit will get you from A to B
quickly enough. Otherwise, an elliptical orbit is possible. (Similarly,
the time for the "long route" can tell you if an elliptical orbit taking
more than half a revolution is possible.) */
double euler_function( const OBSERVE FAR *obs1, const OBSERVE FAR *obs2)
{
const double s = vector3_dist( obs1->obj_posn, obs2->obj_posn);
const double temp1 = obs1->solar_r + obs2->solar_r + s;
const double temp2 = obs1->solar_r + obs2->solar_r - s;
const double t1 = obs1->jd - obs1->r / AU_PER_DAY;
const double t2 = obs2->jd - obs2->r / AU_PER_DAY;
const double rval = temp1 * sqrt( temp1) - temp2 * sqrt( temp2)
- 6. * GAUSS_K * (t2 - t1);
return( rval);
}
double find_r_given_solar_r( const OBSERVE FAR *obs, const double solar_r)
{
double r_dot_v = 0., r_dot_r = 0., b, c, discr, rval = -1.;
int i;
for( i = 0; i < 3; i++)
{
r_dot_r += obs->obs_posn[i] * obs->obs_posn[i];
r_dot_v += obs->obs_posn[i] * obs->vect[i];
}
b = 2. * r_dot_v;
c = r_dot_r - solar_r * solar_r;
discr = b * b - 4 * c;
if( discr > 0.)
rval = (-b + sqrt( discr)) / 2.;
return( rval);
}
static double get_euler_value( const OBSERVE FAR *obs1, OBSERVE FAR *obs2,
const double r2)
{
set_distance( obs2, r2);
return( euler_function( obs1, obs2));
}
/* The following function finds a zero of the quadratic passing through
the three points (x[0], y[0]), (x[1], y[1]), and (x[2], y[2]). To do
this, we first shift by x[0] along the x-axis, to find the quadratic
y=ax^2 + bx + c that fits (0, y[0]), (x[1] - x[0], y[1]),
and (x[2] - x[0], y[2]). By inspection, in this scheme, c = y[0].
Using the notation of the following function, then,
dy1 = a * dx1^2 + b * dx1
dy2 = a * dx2^2 + b * dx2
dy1 / dx1 = z1 = a * dx1 + b
dy2 / dx2 = z2 = a * dx2 + b
We then solve the resulting quadratic, going for the positive sign
if dir != 0. */
static double find_quadratic_zero( const double *x, const double *y,
const int dir)
{
const double dx1 = x[1] - x[0], dy1 = y[1] - y[0];
const double dx2 = x[2] - x[0], dy2 = y[2] - y[0];
const double z1 = dy1 / dx1, z2 = dy2 / dx2;
const double a = (z1 - z2) / (dx1 - dx2);
const double b = z1 - a * dx1;
const double c = y[0];
const double discriminant = b * b - 4. * a * c;
double rval = -b;
if( discriminant > 0.)
rval += (dir ? 1. : -1.) * sqrt( discriminant);
return( x[0] + rval / (2. * a));
}
int find_parabolic_orbit( OBSERVE FAR *obs, const int n_obs,
double *orbit, const int direction)
{
double r[3], y[3];
int i, iter, rval = 0;
OBSERVE FAR *obs2 = obs + n_obs - 1;
const double thresh = 1e-10;
for( i = 0; i < 3; i++)
{
r[i] = obs->r * (.9 + .1 * (double)i);
y[i] = get_euler_value( obs, obs2, r[i]);
}
for( iter = 0; fabs( r[1] - r[0]) > thresh && iter < 20; iter++)
{
const double new_r = find_quadratic_zero( r, y, direction);
r[2] = r[1];
r[1] = r[0];
r[0] = new_r;
y[2] = y[1];
y[1] = y[0];
y[0] = get_euler_value( obs, obs2, new_r);
}
if( find_transfer_orbit( orbit, obs, obs2, 0))
rval = -3;
else if( set_locs( orbit, obs->jd, obs, n_obs))
rval = -4;
return( rval);
}
int calc_derivatives( const double jd, const double *ival, double *oval,
const int reference_planet);
double take_rk_step( const double jd, ELEMENTS *ref_orbit,
const double *ival, double *ovals,
const int n_vals, const double step); /* runge.cpp */
double take_pd89_step( const double jd, ELEMENTS *ref_orbit,
const double *ival, double *ovals,
const int n_vals, const double step); /* runge.cpp */
int symplectic_6( double jd, ELEMENTS *ref_orbit, double *vect,
const double dt);
static int is_unreasonable_orbit( const double *orbit); /* orb_func.cpp */
double integration_tolerance = 1.e-12;
double minimum_jd = 77432.5; /* 1 Jan -4500 */
double maximum_jd = 4277757.5; /* 1 Jan +7000 */
char *runtime_message;
int show_runtime_messages = 1;
// static int reference_planet = 0;
static unsigned perturbers_automatically_found;
static int reset_auto_perturbers( const double jd, const double *orbit)
{
extern int forced_central_body; /* and include asteroid perts */
unsigned mask;
const int perturbing_planet = check_for_perturbers(
(jd - J2000) / 36525., orbit);
mask = (1 << perturbing_planet);
if( perturbing_planet == 3) /* add in the moon, too: */
mask |= (1 << 10);
else if( perturbing_planet == 10) /* or vice versa: */
mask |= (1 << 3);
if( forced_central_body == 100)
mask |= (1 << 20);
if( perturbing_planet)
perturbers_automatically_found |= mask;
if( forced_central_body == 100)
perturbers_automatically_found |= (1 << 20);
if( perturbers & AUTOMATIC_PERTURBERS)
perturbers = mask | AUTOMATIC_PERTURBERS;
return( perturbing_planet);
}
clock_t integration_timeout = (clock_t)0;
#define STEP_INCREMENT 2
#define INTEGRATION_TIMED_OUT -3
#define HIT_A_PLANET -4
int integrate_orbit( double *orbit, const double t0, const double t1)
{
static double stepsize = 2.;
static double fixed_stepsize = -1.;
const double chicken = .9;
int reset_of_elements_needed = 1;
const double step_increase = chicken * integration_tolerance
/ pow( STEP_INCREMENT, (integration_method ? 9. : 5.));
static int use_encke = -1;
double t = t0;
#ifdef CONSOLE
static time_t real_time = (time_t)0;
double prev_t = t, last_err = 0.;
#endif
int n_rejects = 0, rval;
unsigned saved_perturbers = perturbers;
int n_steps = 0, prev_n_steps = 0;
int going_backward = (t1 < t0);
static int n_changes;
ELEMENTS ref_orbit;
assert( fabs( t0) < 1e+9);
assert( fabs( t1) < 1e+9);
if( use_encke == -1)
use_encke = atoi( get_environment_ptr( "ENCKE"));
if( t0 > maximum_jd || t1 > maximum_jd
|| t0 < minimum_jd || t0 < minimum_jd)
{
char buff[200];
sprintf( buff, "Integrating from %.4f to %.4f runs outside\n",
JD_TO_YEAR( t0), JD_TO_YEAR( t1));
strcat( buff, "Find_Orb's default time range. See\n\n");
strcat( buff, "https://www.projectpluto.com/find_orb.htm#time_range\n\n");
strcat( buff, "for instructions on how to extend the range.\n");
generic_message_box( buff, "o");
exit( -1);
}
if( debug_level > 7)
debug_printf( "Integrating %f to %f\n", t0, t1);
rval = is_unreasonable_orbit( orbit);
if( rval)
{
debug_printf( "Unreasonable %d\n", rval);
return( -1);
}
ref_orbit.central_obj = -1;
if( fixed_stepsize < 0.)
fixed_stepsize = atof( get_environment_ptr( "FIXED_STEPSIZE"));
stepsize = fabs( stepsize);
if( fixed_stepsize > 0.)
stepsize = fixed_stepsize;
if( going_backward)
stepsize = -stepsize;
while( t != t1 && !rval)
{
double delta_t, new_t = ceil( (t - .5) / stepsize + .5) * stepsize + .5;
reset_auto_perturbers( t, orbit);
if( reset_of_elements_needed || !(n_steps % 50))
if( use_encke)
{
extern int best_fit_planet;
find_relative_orbit( t, orbit, &ref_orbit, best_fit_planet);
reset_of_elements_needed = 0;
}
n_steps++;
#ifdef CONSOLE
if( !(n_steps % 500) && show_runtime_messages && time( NULL) != real_time)
{
char buff[80];
extern int best_fit_planet, n_posns_cached;
extern int64_t planet_ns;
extern double best_fit_planet_dist;
// #define TEST_PLANET_CACHING_HASH_FUNCTION
#ifdef TEST_PLANET_CACHING_HASH_FUNCTION
extern long total_n_searches, total_n_probes, max_probes_required;
#endif
if( runtime_message)
move_add_nstr( 9, 10, runtime_message, -1);
sprintf( buff, "t = %.5f; %.5f to %.5f; step ",
JD_TO_YEAR( t), JD_TO_YEAR( t0), JD_TO_YEAR( t1));
if( fabs( stepsize) > .1)
snprintf_append( buff, sizeof( buff), "%.3f ", stepsize);
else if( fabs( stepsize) > .91)
snprintf_append( buff, sizeof( buff), "%.3fm ",
stepsize * minutes_per_day);
else
snprintf_append( buff, sizeof( buff), "%.3fs ",
stepsize * seconds_per_day);
if( prev_n_steps) /* i.e., not our first time through here */
snprintf_append( buff, sizeof( buff), "%d step/sec ",
n_steps - prev_n_steps);
move_add_nstr( 10, 10, buff, -1);
prev_n_steps = n_steps;
real_time = time( NULL);
sprintf( buff, " %02d:%02d:%02d; %f; %d cached ",
(int)( (real_time / 3600) % 24L),
(int)( (real_time / 60) % 60),
(int)( real_time % 60), t - prev_t,
n_posns_cached);
prev_t = t;
move_add_nstr( 11, 10, buff, -1);
sprintf( buff, "%d steps; %d rejected", n_steps, n_rejects);
if( best_fit_planet_dist)
{
snprintf_append( buff, sizeof( buff), "; center %d, ",
best_fit_planet);
format_dist_in_buff( buff + strlen( buff), best_fit_planet_dist);
}
if( planet_ns)
sprintf( buff + strlen( buff), " tp:%ld.%09ld",
(long)( planet_ns / (int64_t)1000000000),
(long)( planet_ns % (int64_t)1000000000));
strcat( buff, " ");
move_add_nstr( 12, 10, buff, -1);
sprintf( buff, "last err: %.3e/%.3e n changes: %d ",
last_err, step_increase, n_changes);
move_add_nstr( 13, 10, buff, -1);
if( use_encke)
{
sprintf( buff, "e = %.5f; q = ", ref_orbit.ecc);
format_dist_in_buff( buff + strlen( buff), ref_orbit.q);
strcat( buff, " ");
move_add_nstr( 18, 10, buff, -1);
}
sprintf( buff, "Pos: %11.6f %11.6f %11.6f",
orbit[0], orbit[1], orbit[2]);
move_add_nstr( 14, 10, buff, -1);
sprintf( buff, "Vel: %11.6f %11.6f %11.6f",
orbit[3], orbit[4], orbit[5]);
move_add_nstr( 15, 10, buff, -1);
#ifdef TEST_PLANET_CACHING_HASH_FUNCTION
if( total_n_searches)
{
sprintf( buff, "%ld searches; avg %.2f max %ld ",
total_n_searches,
(double)total_n_probes / (double)total_n_searches,
max_probes_required);
move_add_nstr( 16, 10, buff, -1);
}
#endif
refresh_console( );
}
#endif
/* Make sure we don't step completely past */
/* the time t1 we want to stop at! */
if( (!going_backward && new_t > t1) || (going_backward && new_t < t1))
new_t = t1;
delta_t = new_t - t;
switch( integration_method)
{
case 1:
symplectic_6( t, &ref_orbit, orbit, delta_t);
break;
default:
{
double new_vals[6];
static double min_stepsize;
const double err = (integration_method ?
take_pd89_step( t, &ref_orbit, orbit, new_vals, 6, delta_t) :
take_rk_step( t, &ref_orbit, orbit, new_vals, 6, delta_t));
if( !min_stepsize)
{
min_stepsize = atof( get_environment_ptr( "MIN_STEPSIZE"))
/ seconds_per_day;
if( !min_stepsize)
min_stepsize = 1e-5; /* 1e-5 day = 0.864 seconds */
}
if( !stepsize)
exit( 0);
// if( err >= integration_tolerance && fabs( stepsize) < min_stepsize)
// debug_printf( "Err %f x tolerance; stepsize %f seconds\n",
// err / integration_tolerance, delta_t * seconds_per_day);
if( err < integration_tolerance || fixed_stepsize > 0.
|| fabs( stepsize) < min_stepsize) /* it's good! */
{
memcpy( orbit, new_vals, 6 * sizeof( double));
if( err < step_increase && !fixed_stepsize)
if( fabs( delta_t - stepsize) < fabs( stepsize * .01))
{
n_changes++;
stepsize *= STEP_INCREMENT;
}
}
else /* failed: try again with a smaller step */
{
n_rejects++;
new_t = t;
stepsize /= STEP_INCREMENT;
reset_of_elements_needed = 1;
}
#ifdef CONSOLE
last_err = err;
#endif
}
break;
}
t = new_t;
rval = is_unreasonable_orbit( orbit);
if( rval)
{
debug_printf( "Unreasonable %d at %.5g (%.5f to %.5f)\n",
rval, t - t0, t0, t1);
debug_printf( "Stepsize %g\n", stepsize);
}
else if( integration_timeout && !(n_steps % 100))
if( clock( ) > integration_timeout)
rval = INTEGRATION_TIMED_OUT;
if( fail_on_hitting_planet)
{
extern int planet_hit;
if( planet_hit != -1)
rval = HIT_A_PLANET;
}
if( debug_level && n_steps % 10000 == 0)
{
extern int best_fit_planet;
ELEMENTS elems;
find_relative_orbit( t, orbit, &elems, best_fit_planet);
debug_printf( "At %f, step %g near planet %d\n", t, stepsize, best_fit_planet);
debug_printf( "q = %f km; e = %f\n", elems.q * AU_IN_KM, elems.ecc);
debug_printf( "Posn: %f %f %f\n", orbit[0], orbit[1], orbit[2]);
debug_printf( "Posn: %f %f %f\n", orbit[3], orbit[4], orbit[5]);
}
}
if( debug_level > 7)
debug_printf( "Integration done: %d\n", rval);
perturbers = saved_perturbers;
return( rval);
}
/* At times, the orbits generated by 'full steps' or Herget or other methods
are completely unreasonable. The exact definition of 'unreasonable'
is pretty darn fuzzy. The following function says that if at the epoch,
an object is more than one light-year from the Sun (about 60000 AU) or
is travelling at faster than 5% of the speed of light, the orbit is
"unreasonable".
I'm sure this definition could be tightened a lot without any real
trouble. The fastest natural objects in the solar system are comets
impacting the Sun, which they do at the escape speed of about 600 km/s,
or .2% of the speed of light. (With the limit being a lot tighter than
that as one gets away from the sun; for example, near the earth's
orbit, nothing goes much faster than about 70 km/s.) And the furthest
objects seen orbiting the sun are of the order of 100 AU away, as
opposed to the 60000 AU distance given below. */
static const double max_reasonable_dist = 1.0 * 365.25 * AU_PER_DAY;
static const double max_reasonable_speed = AU_PER_DAY * .05;
bool all_reasonable = false;
#define UNREASONABLE_TOO_FAR 0x100
#define UNREASONABLE_TOO_FAST 0x200
#define UNREASONABLE_ZERO_R 0x400
#define UNREASONABLE_ZERO_V 0x800
static int is_unreasonable_orbit( const double *orbit)
{
int rval = 0, i;
double r, v;
if( all_reasonable)
return( 0);
r = vector3_length( orbit);
v = vector3_length( orbit + 3);
if( r > max_reasonable_dist)
rval = UNREASONABLE_TOO_FAR;
else if( !r)
rval = UNREASONABLE_ZERO_R;
if( v > max_reasonable_speed)
rval |= UNREASONABLE_TOO_FAST;
else if( !v)
rval |= UNREASONABLE_ZERO_V;
for( i = 0; i < 6; i++)
if( !isfinite( orbit[i]))
rval |= (1 << i);
return( rval);
}
/* See Explanatory Supplement, 3.26, p. 135, "Gravitational Light
Bending." For our purposes, what matters is the difference between
how much the object's light is bent and how much the light of
background stars is bent. So we compute phi1 = angle between
observer, sun, and 'result'; and phi2 = angle between observer,
sun, and background stars = 180 minus elongation of the object as
seen by 'observer'. */
static void light_bending( const double *observer, double *result)
{
const double bend_factor = 2. * SOLAR_GM / (AU_PER_DAY * AU_PER_DAY)
* (1. + atof( get_environment_ptr( "BENDING")));
size_t i;
double p[3], plen, xprod[3], dir[3], dlen;
const double olen = vector3_length( observer);
const double rlen = vector3_length( result);
double phi1, phi2, bending;
for( i = 0; i < 3; i++)
p[i] = result[i] - observer[i];
plen = vector3_length( p);
vector_cross_product( xprod, observer, result);
vector_cross_product( dir, xprod, p);
dlen = vector3_length( dir);
for( i = 0; i < 3; i++)
dir[i] /= dlen;
/* "dir" is now a unit vector perpendicular to p, aimed away */
/* from the sun */
phi1 = acos( dot_prod( result, observer) / (rlen * olen));
phi2 = acos( -dot_prod( p, observer) / (plen * olen));
bending = bend_factor * (tan( phi1 / 2.) - tan( phi2 / 2.));
bending *= plen;
for( i = 0; i < 3; i++)
result[i] += bending * dir[i];
}
static void light_time_lag( const double *orbit, const double *observer, double *result)
{
const double solar_r = vector3_length( orbit);
unsigned iter;
memcpy( result, orbit, 3 * sizeof( double));
for( iter = 0; iter < 4; iter++)
{
const double r = vector3_dist( result, observer);
const double dt = -r / AU_PER_DAY;
const double afact = -SOLAR_GM * dt / (solar_r * solar_r * solar_r);
unsigned i;
for( i = 0; i < 3; i++)
{
result[i] = orbit[i] + (.5 * afact * orbit[i] + orbit[i + 3]) * dt;
result[i + 3] = orbit[i + 3] + afact * orbit[i];
}
// debug_printf( "iter %d: r = %.15f\n", iter, r);
}
light_bending( observer, result);
}
static void set_solar_r( OBSERVE FAR *ob)
{
ob->solar_r = vector3_length( ob->obj_posn);
}
/* In integrating an orbit to compute locations for each observation, a
little bit of trickery is used to improve performance. First (pass = 0),
we set observations made _before_ the epoch t0, integrating _backwards_.
If we instead, say, integrated from the epoch t0 to the first observation,
then integrated to each observation in order, it would simplify the code
a bit; but we'd sometimes be integrating (say) from an epoch in 2010 back
to 2003, then forward again to observations made up to 2013. That would
mean integrating over a total span of 17 years when we really only needed
to do ten years. It would also allow numerical integration error to
build up more.
To make matters worse, while the initial state vector may be for 2010,
we may also want a state vector for an epoch in, say, 2018. (Perhaps
that's the epoch we're displaying, or the semimajor axis is constrained
to a particular value for sometime in 2018.) 'set_locs_extended' is
bright enough to compute that second-epoch state vector at the optimal
time; in the above case, that would mean that after integrating forward
to 2013, it should continue to 2018. If the second epoch were between
2010 and 2013, it would find the second-epoch state vector while getting
locations for the last part of the observed arc. And so on.
All of this does a good job of avoiding unnecessary integration and
accumulated error, but it does make the code more opaque than would
otherwise be the case.
If we don't actually need a state vector for a second epoch, then
we can set orbit2 = NULL. Or use plain ol' set_locs(), which -- as
you can see below -- basically just calls set_locs_extended() with a
NULL orbit2. */
#define is_between( t1, t2, t3) ((t2 - t1) * (t3 - t2) >= 0.)
static int set_locs_extended( const double *orbit, const double epoch_jd,
OBSERVE FAR *obs, const int n_obs,
const double epoch2, double *orbit2)
{
int i, pass, rval = 0;
if( is_unreasonable_orbit( orbit))
{
if( debug_level)
debug_printf( "Unreasonable orbit provided to set_locs_extended: %s\n",
obs->packed_id);
return( -9);
}
for( i = 0; i < n_obs && obs[i].jd < epoch_jd; i++)
;
/* set obs[0...i-1] on pass=0, obs[i...n_obs-1] on pass=1: */
for( pass = 0; pass < 2; pass++)
{
int j = (pass ? i : i - 1);
double curr_orbit[6];
double curr_t = epoch_jd;
memcpy( curr_orbit, orbit, 6 * sizeof( double));
while( j < n_obs && j >= 0)
{
double light_lagged_orbit[6];
OBSERVE FAR *optr = obs + j;
if( orbit2 && is_between( curr_t, epoch2, optr->jd))
{
rval = integrate_orbit( curr_orbit, curr_t, epoch2);
if( rval)
return( rval);
memcpy( orbit2, curr_orbit, 6 * sizeof( double));
curr_t = epoch2;
}
rval = integrate_orbit( curr_orbit, curr_t, optr->jd);
if( rval)
return( rval);
curr_t = optr->jd;
light_time_lag( curr_orbit, optr->obs_posn, light_lagged_orbit);
FMEMCPY( optr->obj_posn, light_lagged_orbit, 3 * sizeof( double));
FMEMCPY( optr->obj_vel, light_lagged_orbit + 3, 3 * sizeof( double));
j += (pass ? 1 : -1);
}
if( orbit2)
if( (!pass && curr_t >= epoch2) || (pass && curr_t <= epoch2))
{
rval = integrate_orbit( curr_orbit, curr_t, epoch2);
if( rval)
return( rval);
memcpy( orbit2, curr_orbit, 6 * sizeof( double));
}
}
/* We've now set the object heliocentric positions and */
/* velocities, in ecliptic J2000, for each observation */
/* time. Now let's go back and find observer-centric */
/* computed RA/decs and distances to the object at those */
/* times. */
for( i = 0; i < n_obs; i++)
{
double loc[3], ra, dec, temp, r = 0.;
const double sin_obliq_2000 = 0.397777155931913701597179975942380896684;
const double cos_obliq_2000 = 0.917482062069181825744000384639406458043;
int j;
for( j = 0; j < 3; j++)
{
loc[j] = obs[i].obj_posn[j] - obs[i].obs_posn[j];
r += loc[j] * loc[j];
}
r = sqrt( r);
obs[i].r = r;
temp = loc[1] * cos_obliq_2000 - loc[2] * sin_obliq_2000;
loc[2] = loc[2] * cos_obliq_2000 + loc[1] * sin_obliq_2000;
loc[1] = temp;
ra = atan2( loc[1], loc[0]);
if( r > 100000. || r <= 0.)
debug_printf( "???? bad r: %f %f %f: %s\n",
loc[0], loc[1], loc[2], obs->packed_id);
if( r)
dec = asine( loc[2] / r);
else
dec = 0.;
while( ra - obs[i].ra > PI)
ra -= 2. * PI;
while( ra - obs[i].ra < -PI)
ra += 2. * PI;
obs[i].computed_ra = ra;
obs[i].computed_dec = dec;
set_solar_r( obs + i);
}
return( 0);
}
int set_locs( const double *orbit, const double t0, OBSERVE FAR *obs,
const int n_obs)
{
return( set_locs_extended( orbit, t0, obs, n_obs, t0, NULL));
}
double observation_rms( const OBSERVE FAR *obs)
{
const double d_dec = obs->computed_dec - obs->dec;
const double d_ra = (obs->computed_ra - obs->ra) * cos( obs->computed_dec);
return( sqrt( d_dec * d_dec + d_ra * d_ra) * 3600. * 180. / PI);
}
/* 2010 Nov 4: revised so that RMS residuals are computed as
root-mean-square of RA and dec treated separately, meaning the
previous results needed to be multipled by sqrt(.5) (Gareth
Williams kindly steered me the right way on this). */
double compute_rms( const OBSERVE FAR *obs, const int n_obs)
{
double rval = 0.;
int i, n_included = 0;
for( i = n_obs; i; i--, obs++)
if( obs->is_included && obs->note2 != 'R')
{
const double obs_rms = observation_rms( obs);
rval += obs_rms * obs_rms;
n_included++;
}
return( sqrt( rval / (double)(n_included * 2)));
}
double compute_weighted_rms( const OBSERVE FAR *obs, const int n_obs, int *n_resids)
{
double rval = 0;
int i, n = 0;
for( i = n_obs; i; i--, obs++)
if( obs->is_included)
{
double xresid, yresid;
n += get_residual_data( obs, &xresid, &yresid);
rval += xresid * xresid + yresid * yresid;
}
if( n_resids)
*n_resids = n;
return( sqrt( rval / (double)n));
}
static double eval_3x3_determinant( const double *a, const double *b,
const double *c)
{
return( a[0] * (b[1] * c[2] - c[1] * b[2])
+ b[0] * (c[1] * a[2] - a[1] * c[2])
+ c[0] * (a[1] * b[2] - b[1] * a[2]));
}
/* 'find_transfer_orbit' finds the state vector that can get an object
from the location/time described at 'obs1' to that described at 'obs2'.
It does this with the logic given in 'herget.htm#sund_xplns'. */
/* 2011 May 8: Realized this code is responsible for much of the time
it takes to initially compute an orbit. One simple speed-up is to
take advantage of the fact that in the method of Herget, we're
often tweaking a "nearby" orbit, i.e., we already have an
approximate orbit; using this as our starting estimate ought to
result in faster convergence. */
#define XFER_TOO_FAR_AWAY -1
#define XFER_TOO_FAST -2
#define XFER_TOO_MANY_ITERATIONS -3
#define XFER_INTEGRATION_FAILED -4
#define XFER_OK 0
clock_t t_transfer;
static int find_transfer_orbit( double *orbit, OBSERVE FAR *obs1,
OBSERVE FAR *obs2,
const int already_have_approximate_orbit)
{
double r = 0.;
const double jd1 = obs1->jd - obs1->r / AU_PER_DAY;
const double jd2 = obs2->jd - obs2->r / AU_PER_DAY;
const double delta_t = jd2 - jd1;
double deriv[6];
double orbit2[6];
double diff_squared = 999.;
/* Iterate until the error is less than 1e-8 of the object */
/* distance. This corresponds to an error of about .002 arcsec */
/* in the actual position (with the '+ .01' allowing for */
/* some margin for very close objects, such as artsats). */
/* Assume a maximum of ten iterations, just to be safe */
const double target_diff = 1.e-8 * (obs2->r + .01);
unsigned i, max_iterations = 10;
clock_t t0 = clock( );
assert( fabs( obs1->jd) < 1e+9);
assert( fabs( obs2->jd) < 1e+9);
assert( fabs( jd1) < 1e+9);
assert( fabs( jd2) < 1e+9);
if( obs1->r > max_reasonable_dist || obs2->r > max_reasonable_dist)
{
debug_printf( "Bad xfer: %f %f\n", obs1->r, obs2->r);
return( XFER_TOO_FAR_AWAY);
}
set_distance( obs1, obs1->r);
set_distance( obs2, obs2->r);
if( !already_have_approximate_orbit)
{
double speed_squared = 0., speed;
const int saved_perturbers = perturbers;
double deriv2[6];
unsigned pass;
for( i = 0; i < 3; i++)
{
orbit[i + 3] = (obs2->obj_posn[i] - obs1->obj_posn[i]) / delta_t;
speed_squared += orbit[i + 3] * orbit[i + 3];
}
if( speed_squared > max_reasonable_speed * max_reasonable_speed)
return( XFER_TOO_FAST);
/* speed_squared is in (AU/day)^2, speed in km/second: */
speed = sqrt( speed_squared) * AU_IN_KM / seconds_per_day;
if( debug_level > 3)
debug_printf( "Speed = %f km/s; radii %f, %f\n", speed, obs1->r, obs2->r);
for( pass = 0; pass < 2; pass++)
{
OBSERVE FAR *obs = (pass ? obs2 : obs1);
const double jd = (pass ? jd2 : jd1);