commit b74d278c8eba0b1f393920850ac697c2018a9f25 Author: ztimson Date: Wed Oct 21 19:32:02 2026 -0400 init diff --git a/data/tle/stations.tle b/data/tle/stations.tle new file mode 100644 index 0000000..c859f4a --- /dev/null +++ b/data/tle/stations.tle @@ -0,0 +1,51 @@ +ISS (ZARYA) +1 25544U 98067A 26294.04791053 .00009575 00000+0 18188-3 0 9996 +2 25544 51.6327 37.2623 0006759 289.5321 70.4938 15.48967427591263 +POISK +1 36086U 09060A 26294.04791053 .00009575 00000+0 18188-3 0 9994 +2 36086 51.6327 37.2623 0006759 289.5321 70.4938 15.48967427586484 +CSS (TIANHE) +1 48274U 21035A 26294.25846467 .00030091 00000+0 35038-3 0 9995 +2 48274 41.4687 276.1937 0002031 190.5094 169.5703 15.61026916312853 +ISS (NAUKA) +1 49044U 21066A 26294.04791053 .00009575 00000+0 18188-3 0 9992 +2 49044 51.6327 37.2623 0006759 289.5321 70.4938 15.48967427586527 +FREGAT DEB +1 49271U 11037PF 26292.86068782 .00010680 00000+0 14889-1 0 9996 +2 49271 51.6485 345.9436 0940020 202.8908 152.7302 12.45374907240561 +CSS (WENTIAN) +1 53239U 22085A 26294.25846467 .00030091 00000+0 35038-3 0 9998 +2 53239 41.4687 276.1937 0002031 190.5094 169.5703 15.61026916288234 +CSS (MENGTIAN) +1 54216U 22143A 26294.25846467 .00030091 00000+0 35038-3 0 9999 +2 54216 41.4687 276.1937 0002031 190.5094 169.5703 15.61026916308086 +SZ-21 MODULE +1 66515U 25246C 26294.22802189 .00131005 13520-4 39861-3 0 9992 +2 66515 41.4681 234.9893 0012983 217.8317 142.1621 15.91235557 53715 +DUPLEX +1 66906U 98067XT 26294.21739889 .00087112 00000+0 60248-3 0 9998 +2 66906 51.6239 8.2935 0005169 333.1895 26.8836 15.73765430 50420 +KNACKSAT-2 +1 67683U 98067YA 26294.23849680 .00126976 00000+0 84569-3 0 9998 +2 67683 51.6243 14.4676 0009852 333.8147 26.2353 15.74432101 40030 +GXIBA-1 +1 67685U 98067YC 26294.23381720 .00198887 00000+0 98256-3 0 9994 +2 67685 51.6190 10.6184 0011279 337.3691 22.6813 15.80874177 40080 +UITMSAT-2 +1 67686U 98067YD 26293.27790080 .03059098 11989-4 11168-2 0 9993 +2 67686 51.6061 4.7855 0010166 350.7558 9.3273 16.23807297 40070 +LEOPARD +1 67687U 98067YE 26294.22233459 .00713598 22293-3 18935-2 0 9999 +2 67687 51.6147 9.8036 0013002 350.0326 10.0421 15.93899698 40011 +HMU-SAT2 +1 67688U 98067YF 26294.20241447 .00414307 77386-4 11821-2 0 9991 +2 67688 51.6195 5.8753 0010290 344.6935 15.3759 15.92614788 40069 +PROGRESS-MS 34 +1 68837U 26093A 26294.04791053 .00009575 00000+0 18188-3 0 9998 +2 68837 51.6327 37.2623 0006759 289.5321 70.4938 15.48967427587451 +TIANZHOU-10 +1 69049U 26102A 26294.25846467 .00030091 00000+0 35038-3 0 9998 +2 69049 41.4687 276.1937 0002031 190.5094 169.5703 15.61026916311024 +SHENZHOU-23 (SZ-23) +1 69180U 26113A 26294.25846467 .00030091 00000+0 35038-3 0 9996 +2 69180 41.4687 276.1937 0002031 190.5094 169.5703 15.61026916307902 diff --git a/data/tle/visual.tle b/data/tle/visual.tle new file mode 100644 index 0000000..25a16e6 --- /dev/null +++ b/data/tle/visual.tle @@ -0,0 +1,465 @@ +ATLAS CENTAUR 2 +1 00694U 63047A 26294.56101685 .00002576 00000+0 29898-3 0 9992 +2 00694 30.3591 12.5187 0544654 272.2554 81.5810 14.12859964163586 +THOR AGENA D R/B +1 00733U 64002A 26294.30136440 .00000121 00000+0 60327-4 0 9994 +2 00733 99.1093 319.8069 0032160 322.8889 37.0070 14.34104978270630 +SL-3 R/B +1 00877U 64053B 26294.51523957 .00000234 00000+0 69680-4 0 9991 +2 00877 65.0788 29.0938 0074004 220.6204 138.9362 14.61481505299793 +SL-8 R/B +1 02802U 67045B 26294.23409436 .00000170 00000+0 54709-4 0 9994 +2 02802 74.0094 286.8215 0065348 240.4721 118.9912 14.45730904121615 +SL-8 R/B +1 03230U 68040B 26294.49258764 .00002378 00000+0 17237-3 0 9996 +2 03230 74.0307 211.8620 0024606 327.5937 32.3739 15.04368628123955 +OAO 2 +1 03597U 68110A 26294.50312536 .00000165 00000+0 49508-4 0 9999 +2 03597 34.9927 84.3502 0005835 215.5980 144.4322 14.47391459 51837 +ISIS 1 +1 03669U 69009A 26294.49194491 .00000102 00000+0 68259-4 0 9998 +2 03669 88.4316 130.5092 1707004 353.3017 4.7579 11.30455333374045 +SERT 2 +1 04327U 70009A 26294.33933006 .00000000 00000+0 56942-4 0 9991 +2 04327 99.2922 225.3083 0004358 318.8185 199.9837 13.58748563810531 +SL-3 R/B +1 05118U 71028B 26294.16090038 .00137395 00000+0 54759-3 0 9993 +2 05118 81.2224 129.0235 0007329 180.7902 179.3355 15.86191662 24099 +ASTEX 1 +1 05560U 71089A 26294.21419375 .00000488 00000+0 12372-3 0 9993 +2 05560 92.7166 224.5323 0017274 48.2220 312.0459 14.50935156895004 +SL-8 R/B +1 05730U 71119B 26294.24000555 .00006899 00000+0 35210-3 0 9993 +2 05730 73.8834 112.9882 0536964 32.8816 330.4563 14.40856893687948 +OAO 3 (COPERNICUS) +1 06153U 72065A 26294.14876516 .00000280 00000+0 61614-4 0 9997 +2 06153 35.0037 92.6434 0006899 211.4386 316.3107 14.60118887879166 +ATLAS CENTAUR R/B +1 06155U 72065B 26294.05892625 .00001236 00000+0 17001-3 0 9990 +2 06155 35.0009 64.5075 0032636 108.0164 252.4097 14.78100388874629 +SL-8 R/B +1 08459U 75112B 26294.07641126 .00000130 00000+0 51207-4 0 9994 +2 08459 74.0606 324.2692 0015795 353.8293 6.2664 14.38290401664270 +SL-3 R/B +1 10114U 77057B 26294.24700653 .00015195 00000+0 26969-3 0 9998 +2 10114 97.5866 117.1779 0006444 176.2330 183.8971 15.50301719703226 +SEASAT 1 +1 10967U 78064A 26294.26126382 .00000331 00000+0 13062-3 0 9992 +2 10967 108.0112 238.9084 0002626 282.9298 77.1555 14.46311937539127 +SL-14 R/B +1 11267U 79011B 26294.12007023 .00000589 00000+0 55282-4 0 9990 +2 11267 82.5235 242.6317 0016732 29.4145 330.8013 14.92105915562393 +SL-8 R/B +1 11574U 79089B 26294.29366548 .00000206 00000+0 70126-4 0 9994 +2 11574 74.0710 33.4017 0015020 151.2736 208.9251 14.42449487468631 +SL-14 R/B +1 11672U 80005B 26294.01336570 .00000561 00000+0 53889-4 0 9996 +2 11672 82.5114 93.4751 0016834 128.4682 231.8050 14.91120181510061 +SL-8 R/B +1 12139U 81003B 26294.12759279 .00028338 00000+0 63788-3 0 9991 +2 12139 82.9328 80.3648 0237016 109.5922 253.1068 15.18683164348807 +SL-3 R/B +1 12465U 81046B 26294.18985731 .00013767 00000+0 27420-3 0 9993 +2 12465 81.2324 17.9798 0016053 312.4179 47.5707 15.46625166473234 +SL-3 R/B +1 12904U 81103B 26294.22228109 .00003915 00000+0 16463-3 0 9998 +2 12904 81.1567 308.4582 0011490 241.5519 118.4556 15.23121464 7554 +SL-3 R/B +1 13068U 82013B 26294.22371036 .00004221 00000+0 17459-3 0 9996 +2 13068 81.1718 256.0324 0022670 134.8965 225.4114 15.23496062438676 +SL-3 R/B +1 13154U 82039B 26294.33527760 .00002769 00000+0 16251-3 0 9993 +2 13154 81.1507 315.3258 0029958 294.6783 65.1324 15.11054370415702 +SL-3 R/B +1 13403U 82079B 26294.25313995 .00005384 00000+0 20209-3 0 9992 +2 13403 81.1430 286.2552 0024853 119.2619 241.1104 15.26723012412099 +SL-14 R/B +1 13553U 82092B 26293.96636237 .00000417 00000+0 43966-4 0 9995 +2 13553 82.5646 290.6041 0018673 274.0970 115.8758 14.86821133362403 +SL-3 R/B +1 13819U 83010B 26294.14380510 .00018335 00000+0 29989-3 0 9998 +2 13819 81.0983 84.4792 0013790 336.7509 23.3113 15.52273997392850 +SL-3 R/B +1 14208U 83075B 26294.32089952 .00011556 00000+0 26536-3 0 9991 +2 14208 97.6104 308.1892 0020927 135.7527 224.5398 15.42639408364890 +COSMOS 1536 +1 14699U 84013A 26294.28606415 .00007210 00000+0 27624-3 0 9993 +2 14699 82.5427 243.1282 0012735 199.6447 160.4302 15.26279903307009 +SL-14 R/B +1 14820U 84027B 26294.26054980 .00000377 00000+0 40162-4 0 9996 +2 14820 82.5442 33.4590 0016676 309.5364 50.4378 14.86131564281133 +SL-8 R/B +1 15483U 85006B 26294.24643130 .00000181 00000+0 68533-4 0 9994 +2 15483 74.0462 206.0772 0017260 63.5131 100.8516 14.37878570186449 +SL-12 R/B(2) +1 15772U 85042D 26294.14134787 .00000108 00000+0 69934-4 0 9992 +2 15772 71.1087 331.4022 0033429 137.5471 247.6980 14.22027261146444 +SL-14 R/B +1 15945U 85069B 26294.17608976 .00000319 00000+0 33148-4 0 9994 +2 15945 82.5285 172.8823 0019137 160.8339 199.3602 14.86589607206336 +SL-16 R/B +1 16182U 85097B 26294.23232751 .00000230 00000+0 13935-3 0 9993 +2 16182 71.0051 25.7110 0009780 272.2527 114.8353 14.16622922119170 +SL-14 R/B +1 16496U 86006B 26294.29039982 .00000656 00000+0 66835-4 0 9999 +2 16496 82.5283 47.4159 0074844 244.0734 115.2757 14.87041078182736 +COSMOS 1743 +1 16719U 86034A 26294.12877806 .00127340 00000+0 61222-3 0 9999 +2 16719 82.5235 193.4905 0005564 116.8516 243.3322 15.82275405215590 +SL-14 R/B +1 16792U 86046B 26294.23125326 .00000406 00000+0 43766-4 0 9995 +2 16792 82.4828 227.0671 0022400 198.6083 161.4317 14.85745170159894 +SL-14 R/B +1 16882U 86055B 26293.42945654 .00000456 00000+0 49590-4 0 9995 +2 16882 82.5173 275.3776 0017629 311.9347 207.3823 14.85795696152736 +AJISAI (EGS) +1 16908U 86061A 26294.32308455 -.00000069 00000+0 20409-3 0 9991 +2 16908 50.0065 119.5286 0011424 140.6282 43.4000 12.44517827496099 +SL-14 R/B +1 17567U 87024B 26294.24999466 .00000418 00000+0 44613-4 0 9993 +2 17567 82.5278 240.7518 0016885 230.5706 129.4017 14.86287319121634 +COSMOS 1833 +1 17589U 87027A 26294.18432040 -.00000007 00000+0 21778-4 0 9995 +2 17589 70.9156 212.0275 0025379 226.4965 133.4047 14.13038349 42171 +SL-16 R/B +1 17590U 87027B 26294.06704182 -.00000205 00000+0 -77812-4 0 9994 +2 17590 71.0020 161.5628 0003843 164.1692 195.9553 14.17187883 47275 +SL-14 R/B +1 17912U 87038B 26294.15931650 .00000454 00000+0 49629-4 0 9995 +2 17912 82.4989 84.4015 0020235 136.1059 224.1769 14.85516185112707 +COSMOS 1844 +1 17973U 87041A 26294.25958998 -.00000003 00000+0 23675-4 0 9995 +2 17973 70.8985 278.3742 0029259 39.6902 320.6354 14.14594795 35487 +SL-14 R/B +1 18153U 87055B 26294.29841810 .00000332 00000+0 35335-4 0 9999 +2 18153 82.4973 136.3561 0020356 351.7670 8.3209 14.85777631103435 +COSMOS 1867 +1 18187U 87060A 26294.30155787 -.00000060 00000+0 15261-4 0 9990 +2 18187 65.0125 34.8631 0019228 279.6183 80.2729 14.31527061 52239 +SL-14 R/B +1 18749U 88001B 26294.10692514 .00000315 00000+0 33516-4 0 9997 +2 18749 82.5145 343.2937 0017242 208.4591 151.5686 14.85678766 75497 +COSMOS 1933 +1 18958U 88020A 26294.24791172 .00003488 00000+0 16324-3 0 9996 +2 18958 82.5153 27.5089 0005225 124.0604 236.1127 15.19421982 84465 +SL-3 R/B +1 19046U 88032B 26294.27064488 .00004404 00000+0 19605-3 0 9998 +2 19046 97.5406 277.3653 0025511 162.5809 197.6308 15.21711122 86394 +SL-16 R/B +1 19120U 88039B 26294.03608271 .00000043 00000+0 42968-4 0 9990 +2 19120 71.0142 312.0473 0022249 348.0279 12.0314 14.19640800990363 +COSMOS 1953 +1 19210U 88050A 26294.05193265 .00008197 00000+0 26793-3 0 9992 +2 19210 82.5042 290.9622 0011841 54.3397 305.8945 15.31491381 72247 +SL-8 R/B +1 19257U 88053B 26293.77898947 .00000179 00000+0 66363-4 0 9993 +2 19257 74.0480 57.5380 0020083 185.4423 283.7756 14.39010557 8862 +COSMOS 1975 +1 19573U 88093A 26293.91870757 .00008212 00000+0 27462-3 0 9995 +2 19573 82.5166 251.0905 0013155 93.5987 266.6759 15.30741044 53832 +SL-14 R/B +1 19574U 88093B 26294.29279010 .00000381 00000+0 40800-4 0 9994 +2 19574 82.5338 190.2547 0021061 15.6501 124.1693 14.85811637 34516 +SL-16 R/B +1 19650U 88102B 26294.29893222 -.00000161 00000+0 -57215-4 0 9993 +2 19650 71.0018 36.7810 0013447 17.6045 342.5542 14.16178709958839 +INTERCOSMOS 24 +1 20261U 89080A 26294.30039529 .00000382 00000+0 10330-3 0 9992 +2 20261 82.6042 317.5605 1187932 129.1241 242.1687 12.59762048695209 +SL-14 R/B +1 20262U 89080C 26294.25005201 .00000138 00000+0 34618-4 0 9992 +2 20262 82.5970 28.3168 1230200 29.1921 337.2544 12.50614866688341 +DELTA 1 R/B +1 20323U 89089B 26294.22933088 .00000361 00000+0 97512-4 0 9999 +2 20323 97.0669 105.6621 0070040 128.8032 231.9449 14.50798015928433 +ARIANE 40 R/B +1 20443U 90005H 26294.09424480 .00000173 00000+0 68480-4 0 9991 +2 20443 98.2810 347.7000 0009071 242.7083 117.3183 14.39976157925245 +COSMOS 2058 +1 20465U 90010A 26294.24712406 .00003861 00000+0 21928-3 0 9998 +2 20465 82.4696 184.9850 0007630 279.7266 80.3103 15.12632758976326 +SL-14 R/B +1 20466U 90010B 26294.28368385 .00000411 00000+0 46747-4 0 9991 +2 20466 82.5028 55.4969 0018228 276.7781 83.1359 14.83711824961938 +SL-14 R/B +1 20511U 90018B 26294.18125476 .00000316 00000+0 36482-4 0 9990 +2 20511 82.5245 12.3158 0017472 72.1176 288.1943 14.82283562955984 +HST +1 20580U 90037B 26294.30934801 .00007548 00000+0 22957-3 0 9996 +2 20580 28.4737 297.7404 0002158 117.4266 242.6550 15.32029197807923 +SL-16 R/B +1 20625U 90046B 26294.13145192 -.00000252 00000+0 -10531-3 0 9996 +2 20625 70.9995 184.4335 0015971 315.0159 44.9669 14.15038641880288 +COSMOS 2084 +1 20663U 90055A 26294.25792321 .00002715 00000+0 19538-3 0 9993 +2 20663 62.7890 285.6424 0023108 356.7392 3.3554 15.06556923970290 +SL-6 R/B(2) +1 20666U 90055D 26294.15909047 .00002369 00000+0 17694-3 0 9996 +2 20666 62.7822 206.5630 0060102 20.9119 339.4419 15.04407183972107 +SL-8 R/B +1 20775U 90078B 26294.29034957 .00013826 00000+0 38055-3 0 9990 +2 20775 82.9019 47.3274 0335937 330.6802 27.5923 14.95752071842958 +SL-8 R/B +1 21088U 91006B 26294.15169935 .00000037 00000+0 21498-4 0 9994 +2 21088 82.9461 2.3099 0023689 121.9838 265.6896 13.77526194795114 +OKEAN-3 +1 21397U 91039A 26293.95126074 .00001979 00000+0 13447-3 0 9997 +2 21397 82.5137 118.3940 0012733 282.6573 77.3230 15.05796323898924 +COSMOS 2151 +1 21422U 91042A 26294.22290472 .00001900 00000+0 14761-3 0 9999 +2 21422 82.4975 226.0200 0012971 23.9043 336.2780 15.00730995897014 +SL-14 R/B +1 21423U 91042B 26294.21464806 .00000304 00000+0 35395-4 0 9997 +2 21423 82.4961 8.6868 0016083 215.7171 144.2969 14.81964135886472 +ERS-1 +1 21574U 91050A 26294.31804735 .00000271 00000+0 10125-3 0 9999 +2 21574 98.7738 318.0697 0030874 252.0137 107.7684 14.39583492848190 +ARIANE 40 R/B +1 21610U 91050F 26294.11125504 .00000291 00000+0 99135-4 0 9999 +2 21610 98.1733 337.5353 0004338 106.0238 254.1431 14.43018386851507 +INTERCOSMOS 25 +1 21819U 91086A 26294.13656242 .00002184 00000+0 42577-3 0 9999 +2 21819 82.6063 173.6394 1484901 350.7474 6.8764 12.12444658524007 +SL-8 R/B +1 21876U 92008B 26293.93489035 -.00000005 00000+0 -20511-4 0 9995 +2 21876 82.9231 100.2884 0033834 224.1070 247.6718 13.75991264740396 +SL-8 R/B +1 21938U 92020B 26293.91496560 .00000017 00000+0 19700-5 0 9997 +2 21938 82.9329 346.4668 0029672 31.6535 141.2048 13.75562168732099 +USA 81 +1 21949U 92023A 26294.15460056 .00000136 00000+0 42977-4 0 9993 +2 21949 85.0115 1.3018 0002501 76.8614 283.2858 14.32425447127068 +COSMOS 2219 +1 22219U 92076A 26294.17347810 .00000319 00000+0 19174-3 0 9991 +2 22219 71.0594 266.6899 0019416 220.7513 139.2158 14.14117006750254 +SL-16 R/B +1 22220U 92076B 26294.32267781 -.00000198 00000+0 -74873-4 0 9993 +2 22220 70.9996 73.0686 0010605 115.1482 263.3207 14.16885871753797 +COSMOS 2221 +1 22236U 92080A 26294.29652594 .00001841 00000+0 15810-3 0 9990 +2 22236 82.5031 62.8966 0014875 149.1191 211.0910 14.96836038814537 +SL-16 R/B +1 22285U 92093B 26294.17478562 -.00000182 00000+0 -68634-4 0 9998 +2 22285 71.0212 250.8959 0006209 304.8474 55.2065 14.15478174745066 +COSMOS 2228 +1 22286U 92094A 26294.28821973 .00001721 00000+0 14350-3 0 9993 +2 22286 82.5209 21.2028 0016171 260.9185 99.0208 14.97929501809822 +SL-16 R/B +1 22566U 93016B 26294.16827520 .00000275 00000+0 16554-3 0 9991 +2 22566 71.0048 101.6040 0011256 329.3389 30.7075 14.15324108734079 +COSMOS 2242 +1 22626U 93024A 26294.30616331 .00001708 00000+0 14512-3 0 9993 +2 22626 82.5194 50.8305 0014614 265.3740 94.5813 14.97220590814140 +SL-16 R/B +1 22803U 93059B 26294.19291922 -.00000090 00000+0 -20553-4 0 9998 +2 22803 70.9895 255.5675 0018947 231.7896 128.1523 14.17262744711486 +ARIANE 40 R/B +1 22830U 93061H 26294.17370659 .00000143 00000+0 68098-4 0 9997 +2 22830 98.4684 358.3255 0010193 342.3114 17.7715 14.32947975726395 +COSMOS 2278 +1 23087U 94023A 26293.77927596 -.00000038 00000+0 48023-5 0 9995 +2 23087 71.0526 64.1501 0007439 32.5573 327.6007 14.14406436676634 +SL-16 R/B +1 23088U 94023B 26294.07855335 -.00000145 00000+0 -50046-4 0 9998 +2 23088 71.0004 317.5447 0005505 296.7581 63.2978 14.15037295677977 +SL-16 R/B +1 23343U 94074B 26294.13746782 .00000349 00000+0 53193-4 0 9990 +2 23343 97.6921 315.5709 0006074 194.2103 206.4809 14.79588635720585 +SL-16 R/B +1 23405U 94077B 26294.25505914 .00000068 00000+0 59009-4 0 9995 +2 23405 70.9818 237.9267 0003564 222.2211 137.8638 14.15581383648154 +ARIANE 40+ R/B +1 23561U 95021B 26294.24599633 .00000242 00000+0 90797-4 0 9991 +2 23561 98.4287 2.4190 0006845 176.3773 221.0466 14.39889499651704 +SL-16 R/B +1 23705U 95058B 26294.13154227 .00000220 00000+0 13650-3 0 9993 +2 23705 71.0210 66.9306 0011156 143.7619 216.4262 14.15517375599752 +SL-16 R/B +1 24298U 96051B 26294.30076034 .00000131 00000+0 97343-4 0 9996 +2 24298 70.7716 57.7875 0016646 174.9726 185.1564 14.12491644553507 +ORBVIEW 2 (SEASTAR) +1 24883U 97037A 26293.47621168 .00000203 00000+0 86721-4 0 9990 +2 24883 98.8796 104.0721 0003185 109.9485 250.2043 14.35604599540722 +SL-16 R/B +1 25400U 98043G 26294.30376364 .00000069 00000+0 47922-4 0 9992 +2 25400 98.8541 249.6414 0010905 81.3944 278.8470 14.26086199471141 +SL-16 R/B +1 25407U 98045B 26294.31428760 -.00000108 00000+0 -30535-4 0 9998 +2 25407 71.0114 67.0779 0006286 23.8158 336.3255 14.16217596459040 +ISS (ZARYA) +1 25544U 98067A 26294.04791053 .00009575 00000+0 18188-3 0 9996 +2 25544 51.6327 37.2623 0006759 289.5321 70.4938 15.48967427591263 +CZ-4B R/B +1 25732U 99025C 26294.33719284 .00000025 00000+0 32507-4 0 9991 +2 25732 98.6350 332.9185 0037991 56.6196 315.2278 14.18299802420159 +OKEAN-O +1 25860U 99039A 26294.12249620 .00000534 00000+0 76347-4 0 9992 +2 25860 97.9164 351.3772 0001128 69.3361 290.7972 14.80585599467745 +SL-16 R/B +1 25861U 99039B 26294.16291072 .00000428 00000+0 60734-4 0 9990 +2 25861 97.9686 352.5668 0013524 242.9352 117.0481 14.81946268470255 +DELTA 2 R/B +1 25876U 99041E 26294.21996411 .00000244 00000+0 77391-4 0 9997 +2 25876 51.7636 120.1286 0499789 294.2377 60.7111 14.12282111394890 +HELIOS 1B +1 25977U 99064A 26293.98227581 .00001297 00000+0 14671-3 0 9992 +2 25977 98.1512 202.6979 0002371 69.2953 290.8517 14.88275821718767 +TERRA +1 25994U 99068A 26294.29679579 .00000306 00000+0 71201-4 0 9991 +2 25994 97.9307 338.7498 0002445 159.0733 268.7650 14.61181212428028 +SL-16 R/B +1 26070U 00006B 26294.17611755 .00000287 00000+0 16980-3 0 9990 +2 26070 71.0040 343.7103 0017395 205.4030 154.6240 14.15848864380472 +TITAN 4B R/B +1 26474U 00047B 26294.27087755 .00002861 00000+0 17734-3 0 9999 +2 26474 67.9867 125.5144 0038393 154.0237 206.2851 15.10759282426970 +ENVISAT +1 27386U 02009A 26294.32593939 .00000102 00000+0 47067-4 0 9993 +2 27386 98.3992 242.9149 0001382 86.2548 79.9859 14.39089594291625 +IDEFIX & ARIANE 42P R/B +1 27422U 02021B 26293.83843639 .00000205 00000+0 94201-4 0 9994 +2 27422 98.6037 230.0004 0010699 243.3867 116.6221 14.31130535276223 +AQUA +1 27424U 02022A 26294.24047668 .00000750 00000+0 15869-3 0 9998 +2 27424 98.4457 266.1542 0000789 81.3616 335.0903 14.62246479301690 +CZ-4B R/B +1 27432U 02024C 26294.13671150 .00000020 00000+0 32977-4 0 9996 +2 27432 98.8547 346.0449 0051127 102.2464 283.3267 14.14579456261114 +MIDORI II (ADEOS-II) +1 27597U 02056A 26294.13845917 .00000242 00000+0 11288-3 0 9994 +2 27597 98.8059 254.5703 0002095 72.0178 288.1231 14.29404617242504 +H-2A R/B +1 27601U 02056E 26294.16899731 .00000215 00000+0 89983-4 0 9994 +2 27601 98.3487 246.3466 0069360 209.1838 161.8114 14.33878371246428 +CZ-4B R/B +1 28059U 03049C 26294.27226115 .00000305 00000+0 81421-4 0 9996 +2 28059 98.6961 298.1879 0046924 263.2025 96.3830 14.55172956219404 +SL-16 R/B +1 28353U 04021B 26293.95726368 -.00000220 00000+0 -89411-4 0 9998 +2 28353 70.9989 119.7419 0003435 30.4791 329.6531 14.14625344154694 +CZ-4B R/B +1 28415U 04035C 26294.04505285 .00008329 00000+0 26717-3 0 9991 +2 28415 97.3265 325.7652 0027986 244.7460 115.0881 15.32201368214386 +CZ-2C R/B +1 28480U 04046B 26294.18880881 .00000077 00000+0 43779-4 0 9998 +2 28480 98.1821 195.0065 0138623 207.4318 151.9498 14.27060009140660 +ARIANE 5 R/B +1 28499U 04049H 26294.22278216 .00000555 00000+0 67469-4 0 9992 +2 28499 98.2789 111.4444 0083249 340.9887 18.8224 14.85595290179270 +CZ-2D R/B +1 28738U 05024B 26294.04569555 .00170858 00000+0 58992-3 0 9995 +2 28738 97.3349 321.2776 0002064 160.6930 199.4421 15.89107542175184 +ALOS (DAICHI) +1 28931U 06002A 26294.13821038 .00001169 00000+0 20193-3 0 9994 +2 28931 98.1493 249.4287 0000923 52.5954 307.5336 14.70290243106601 +H-2A R/B +1 28932U 06002B 26294.01776783 .00009893 00000+0 45362-3 0 9995 +2 28932 98.2688 101.5112 0048730 191.9517 168.0564 15.19614932128623 +RESURS-DK 1 +1 29228U 06021A 26293.94460919 .00002095 00000+0 12234-3 0 9996 +2 29228 69.9344 13.9115 0001857 145.8949 214.2337 15.13634042121602 +CZ-4B R/B +1 29507U 06046C 26294.07270437 .00004527 00000+0 21936-3 0 9993 +2 29507 97.5316 338.2621 0031393 202.0720 157.9165 15.18622980 94237 +CZ-2C R/B +1 31114U 07010B 26294.23275336 .00000052 00000+0 42845-4 0 9995 +2 31114 98.4169 36.4615 0058876 359.7408 0.3729 14.20300750 11728 +COSMO-SKYMED 1 +1 31598U 07023A 26294.30274207 .00002593 00000+0 22714-3 0 9993 +2 31598 97.8808 127.2592 0001782 83.9370 276.2055 14.97581828 48668 +COSMOS 2428 +1 31792U 07029A 26293.87466733 -.00000205 00000+0 -84202-4 0 9994 +2 31792 70.9406 90.6209 0012682 282.9421 77.0284 14.12972285995904 +SL-16 R/B +1 31793U 07029B 26294.30042625 -.00000005 00000+0 22289-4 0 9998 +2 31793 70.9768 58.1179 0002429 283.3242 99.3377 14.14870320997287 +KORONAS-FOTON +1 33504U 09003A 26294.01701681 .00015829 00000+0 29765-3 0 9990 +2 33504 82.4302 40.7173 0010519 63.5967 296.6361 15.48363595980559 +CZ-2C R/B +1 37731U 11030B 26293.86025463 .00001321 00000+0 17083-3 0 9990 +2 37731 97.8826 247.0952 0051591 339.0207 74.4718 14.81693047823431 +H-2A R/B +1 38341U 12025E 26294.03922116 .00002916 00000+0 26039-3 0 9996 +2 38341 98.4977 279.7084 0042104 295.7561 63.9315 14.96198069781903 +SHIJIAN-16 (SJ-16) +1 39358U 13057A 26294.30712525 .00000308 00000+0 32557-4 0 9998 +2 39358 74.9707 117.7740 0016729 282.8340 77.0979 14.92835903705165 +SL-4 R/B +1 39679U 14021B 26294.33679588 .00015465 00000+0 29158-3 0 9992 +2 39679 51.6045 311.5576 0084330 208.8775 150.7531 15.44832468691092 +ALOS-2 +1 39766U 14029A 26294.27444758 .00001011 00000+0 14222-3 0 9997 +2 39766 97.9227 29.6317 0001439 95.8521 264.2855 14.79469593670220 +YAOGAN-29 +1 41038U 15069A 26294.33955167 .00000157 00000+0 25824-4 0 9996 +2 41038 97.9952 323.1207 0001668 29.8734 330.2575 14.83165418589324 +ASTRO-H (HITOMI) +1 41337U 16012A 26294.16089214 .00002314 00000+0 12951-3 0 9992 +2 41337 30.9998 340.2923 0009420 82.1891 277.9816 15.10999113586351 +HXMT (HUIYAN) +1 42758U 17034A 26294.19381274 .00005174 00000+0 24781-3 0 9990 +2 42758 43.0134 200.9015 0032345 227.0757 132.7376 15.19415588516825 +SAOCOM 1A +1 43641U 18076A 26293.70563936 .00000253 00000+0 38360-4 0 9994 +2 43641 97.8882 118.6571 0001540 83.6506 276.4883 14.82166739434690 +H-2A R/B +1 43682U 18084L 26294.22095835 .00035644 00000+0 63059-3 0 9998 +2 43682 98.8391 201.0204 0018723 318.5042 41.4782 15.50048384440615 +SAOCOM 1B +1 46265U 20059A 26294.27701272 .00000503 00000+0 69729-4 0 9994 +2 46265 97.8875 118.3204 0001401 86.6576 273.4798 14.82150573332163 +CSS (TIANHE) +1 48274U 21035A 26294.25846467 .00030091 00000+0 35038-3 0 9995 +2 48274 41.4687 276.1937 0002031 190.5094 169.5703 15.61026916312853 +COSMOS 2550 +1 48865U 21056A 26294.26593659 .00005766 00000+0 18089-3 0 9995 +2 48865 67.1420 78.5160 0008356 269.5446 90.4751 15.33842010298055 +CZ-2C R/B +1 52794U 22058K 26294.21535187 .00082714 00000+0 59237-3 0 9999 +2 52794 50.1805 223.0674 0026929 88.9328 271.4735 15.72446712245401 +CZ-2C R/B +1 54039U 22132E 26294.00447575 .00234852 23273-4 62243-3 0 9991 +2 54039 97.2810 308.3797 0003381 332.0024 28.1069 15.94659215225828 +GSLV R/B +1 54149U 22138AN 26294.14659811 .00002004 00000+0 16776-3 0 9992 +2 54149 87.3731 90.6054 0023139 55.0936 305.2466 14.97702774217660 +XRISM +1 57800U 23137A 26294.26863262 .00005489 00000+0 29450-3 0 9992 +2 57800 31.0022 262.3157 0007616 159.4646 200.6300 15.13378384171970 +ACS3 +1 59588U 24077B 26294.15446671 .00016687 00000+0 11432-1 0 9991 +2 59588 97.2537 185.7246 0055915 12.4986 347.7555 13.98811813125623 +SPACEMOBILE-003 +1 61045U 24163A 26293.75464403 -.00001138 00000+0 -36856-4 0 9993 +2 61045 52.9706 92.1585 0006545 125.8552 234.3051 15.20289716116877 +SPACEMOBILE-005 +1 61046U 24163B 26294.13337173 .00002573 00000+0 13140-3 0 9992 +2 61046 52.9803 90.4331 0009987 124.9536 235.2397 15.20370604116927 +SPACEMOBILE-001 +1 61047U 24163C 26293.73782963 -.00000334 00000+0 -28569-6 0 9998 +2 61047 52.9754 91.9124 0007715 126.2538 233.9170 15.20332074116869 +SPACEMOBILE-002 +1 61048U 24163D 26293.78790289 .00015439 00000+0 71334-3 0 9999 +2 61048 52.9748 91.7680 0007035 115.3506 244.8217 15.20360596116871 +SPACEMOBILE-004 +1 61049U 24163E 26293.63881022 .00016281 00000+0 75183-3 0 9992 +2 61049 52.9685 92.2050 0008174 150.7184 209.4270 15.20331535116854 +CZ-8A R/B +1 66004U 25231K 26294.17425587 .00000019 00000+0 65100-4 0 9996 +2 66004 50.0047 223.2832 0116769 307.9803 51.0612 14.30194669 52977 +SZ-21 MODULE +1 66515U 25246C 26294.22802189 .00131005 13520-4 39861-3 0 9992 +2 66515 41.4681 234.9893 0012983 217.8317 142.1621 15.91235557 53715 +SPACEMOBILE-006 +1 67232U 25309A 26293.79566921 .00002943 00000+0 15370-3 0 9992 +2 67232 52.9950 116.0791 0011496 152.3089 207.8519 15.19052812 45685 +SPACEMOBILE-008 +1 69589U 26139A 26294.31718713 .00001568 00000+0 10443-3 0 9996 +2 69589 52.9961 49.8238 0003612 12.0577 348.0500 15.13083337 19070 +SPACEMOBILE-009 +1 69590U 26139B 26293.59929539 .00000948 00000+0 69967-4 0 9994 +2 69590 52.9942 53.1631 0003674 359.7665 0.3323 15.12974974 18966 +SPACEMOBILE-010 +1 69591U 26139C 26293.81017468 .00002922 00000+0 18114-3 0 9990 +2 69591 52.9943 52.3473 0003542 352.9751 7.1190 15.12844296 19004 diff --git a/lib/errors.mjs b/lib/errors.mjs new file mode 100644 index 0000000..ded8e18 --- /dev/null +++ b/lib/errors.mjs @@ -0,0 +1,10 @@ +/** Error intended to be returned by the HTTP API. */ +export class ServiceError extends Error { + constructor(code, message, status = 500, details = undefined) { + super(message); + this.name = 'ServiceError'; + this.code = code; + this.status = status; + if (details !== undefined) this.details = details; + } +} diff --git a/lib/geo.mjs b/lib/geo.mjs new file mode 100644 index 0000000..c498db5 --- /dev/null +++ b/lib/geo.mjs @@ -0,0 +1,41 @@ +export const rad = (degrees) => (degrees * Math.PI) / 180; +export const deg = (radians) => (radians * 180) / Math.PI; +export const wrap360 = (degrees) => ((degrees % 360) + 360) % 360; +export const wrap180 = (degrees) => ((degrees + 180) % 360 + 360) % 360 - 180; + +/** Convert azimuth clockwise from north and altitude above the horizon to a unit ENU vector. */ +export function azAltToVec(az, alt) { + const a = rad(az), e = rad(alt), ce = Math.cos(e); + return [ce * Math.sin(a), ce * Math.cos(a), Math.sin(e)]; +} + +/** Convert an east/north/up vector to azimuth clockwise from north and altitude. */ +export function vecToAzAlt(vector) { + const [east, north, up] = vector; + const horizontal = Math.hypot(east, north); + return { az: wrap360(deg(Math.atan2(east, north))), alt: deg(Math.atan2(up, horizontal)) }; +} + +/** Quaternion [x,y,z,w] conjugate. */ +export function quatConj([x, y, z, w]) { + return [-x, -y, -z, w]; +} + +/** Rotate a 3D vector by quaternion [x,y,z,w]. */ +export function quatRotate([x, y, z, w], [vx, vy, vz]) { + const tx = 2 * (y * vz - z * vy); + const ty = 2 * (z * vx - x * vz); + const tz = 2 * (x * vy - y * vx); + return [ + vx + w * tx + (y * tz - z * ty), + vy + w * ty + (z * tx - x * tz), + vz + w * tz + (x * ty - y * tx), + ]; +} + +/** Great-circle angular separation of two azimuth/altitude positions, in degrees. */ +export function angularSeparation(az1, alt1, az2, alt2) { + const a1 = rad(alt1), a2 = rad(alt2), da = rad(wrap180(az2 - az1)); + const cosSep = Math.sin(a1) * Math.sin(a2) + Math.cos(a1) * Math.cos(a2) * Math.cos(da); + return deg(Math.acos(Math.max(-1, Math.min(1, cosSep)))); +} diff --git a/lib/stars.mjs b/lib/stars.mjs new file mode 100644 index 0000000..3af10d9 --- /dev/null +++ b/lib/stars.mjs @@ -0,0 +1,24 @@ +// Bright-star catalogue: J2000 right ascension (hours) and declination (degrees). +// Values are approximate and intended for telescope target selection, not astrometry. +export const STARS = { + sirius: { label: 'Sirius', ra: 6.75248, dec: -16.7161 }, + canopus: { label: 'Canopus', ra: 6.39920, dec: -52.6957 }, + arcturus: { label: 'Arcturus', ra: 14.26102, dec: 19.1825 }, + vega: { label: 'Vega', ra: 18.61565, dec: 38.7837 }, + capella: { label: 'Capella', ra: 5.27816, dec: 45.9980 }, + rigel: { label: 'Rigel', ra: 5.24230, dec: -8.2016 }, + procyon: { label: 'Procyon', ra: 7.65503, dec: 5.2250 }, + betelgeuse: { label: 'Betelgeuse', ra: 5.91953, dec: 7.4071 }, + achernar: { label: 'Achernar', ra: 1.62857, dec: -57.2368 }, + hadar: { label: 'Hadar', ra: 14.06373, dec: -60.3730 }, + altair: { label: 'Altair', ra: 19.84639, dec: 8.8683 }, + acrux: { label: 'Acrux', ra: 12.44330, dec: -63.0991 }, + aldebaran: { label: 'Aldebaran', ra: 4.59868, dec: 16.5093 }, + antares: { label: 'Antares', ra: 16.49013, dec: -26.4320 }, + spica: { label: 'Spica', ra: 13.41988, dec: -11.1613 }, + pollux: { label: 'Pollux', ra: 7.75526, dec: 28.0262 }, + regulus: { label: 'Regulus', ra: 10.13953, dec: 11.9672 }, + deneb: { label: 'Deneb', ra: 20.69053, dec: 45.2803 }, + polaris: { label: 'Polaris', ra: 2.53030, dec: 89.2641 }, + castor: { label: 'Castor', ra: 7.57667, dec: 31.8883 }, +}; diff --git a/mpu.py b/mpu.py new file mode 100644 index 0000000..6ab668f --- /dev/null +++ b/mpu.py @@ -0,0 +1,118 @@ +import sys +import json +import time +import math +import board +import busio +from adafruit_bno08x.i2c import BNO08X_I2C +from adafruit_bno08x import BNO_REPORT_ROTATION_VECTOR + +POLL_INTERVAL = 0.1 # seconds between output lines +REPORT_INTERVAL_US = 50000 # sensor report rate (20 Hz) +STUCK_TIMEOUT = 10.0 # re-init if quaternion is bit-identical this long +MAX_CONSECUTIVE_ERRORS = 10 + + +def quaternion_to_euler(x, y, z, w): + """Adafruit BNO08X quaternion (x, y, z, w) -> yaw, pitch, roll in degrees.""" + sinr_cosp = 2.0 * (w * x + y * z) + cosr_cosp = 1.0 - 2.0 * (x * x + y * y) + roll = math.atan2(sinr_cosp, cosr_cosp) + + sinp = max(-1.0, min(1.0, 2.0 * (w * y - z * x))) + pitch = math.asin(sinp) + + siny_cosp = 2.0 * (w * z + x * y) + cosy_cosp = 1.0 - 2.0 * (y * y + z * z) + yaw = math.atan2(siny_cosp, cosy_cosp) + + return math.degrees(yaw), math.degrees(pitch), math.degrees(roll) + + +def valid_quaternion(quat): + """Return a normalized (x, y, z, w) tuple, or None if the data is garbage.""" + if not quat or len(quat) != 4: + return None + if any(v is None or math.isnan(v) or math.isinf(v) for v in quat): + return None + norm = math.sqrt(sum(v * v for v in quat)) + # A healthy unit quaternion has norm ~1. Corrupt I2C reads usually don't. + if norm < 0.9 or norm > 1.1: + return None + return tuple(v / norm for v in quat) + + +def init_sensor(i2c): + bno = BNO08X_I2C(i2c, address=0x4B) + try: + bno.enable_feature(BNO_REPORT_ROTATION_VECTOR, REPORT_INTERVAL_US) + except TypeError: + # Older library versions don't accept a report interval + bno.enable_feature(BNO_REPORT_ROTATION_VECTOR) + time.sleep(0.5) + return bno + + +def main(): + try: + i2c = busio.I2C(board.SCL, board.SDA) + bno = init_sensor(i2c) + + last_quat = None + last_change = time.time() + errors = 0 + + while True: + try: + raw = bno.quaternion # (x, y, z, w) from rotation vector + quat = valid_quaternion(raw) + if quat is None: + raise ValueError("invalid quaternion") + + errors = 0 + + # Stuck-sensor detection + if raw != last_quat: + last_quat = raw + last_change = time.time() + elif time.time() - last_change > STUCK_TIMEOUT: + raise RuntimeError("sensor output frozen") + + yaw, pitch, roll = quaternion_to_euler(*quat) + if yaw < 0: + yaw += 360.0 + + print(json.dumps({ + "yaw": round(yaw, 2), + "pitch": round(pitch, 2), + "roll": round(roll, 2), + })) + sys.stdout.flush() + + except (ValueError, TypeError, IndexError, KeyError, OSError, + RuntimeError) as e: + errors += 1 + frozen = isinstance(e, RuntimeError) + if frozen or errors >= MAX_CONSECUTIVE_ERRORS: + print(json.dumps({"warning": f"re-initializing sensor ({e})"}), + file=sys.stderr) + sys.stderr.flush() + try: + bno = init_sensor(i2c) + except Exception as init_err: + print(json.dumps({"warning": f"re-init failed: {init_err}"}), + file=sys.stderr) + time.sleep(1.0) + errors = 0 + last_quat = None + last_change = time.time() + + time.sleep(POLL_INTERVAL) + + except Exception as e: + print(json.dumps({"error": str(e)}), file=sys.stderr) + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..5f58336 --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,25 @@ +{ + "name": "eye-spy", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/astronomy-engine": { + "version": "2.1.19", + "resolved": "https://registry.npmjs.org/astronomy-engine/-/astronomy-engine-2.1.19.tgz", + "integrity": "sha512-8yWKNf7UeNbH458h3sAJ6ZgAjE5jTXp/mNNRFoC20j2SHwZIjAQeEsBB2Q3uCFRaTCCJRv33K2XhkhZQMXoX6w==", + "license": "MIT" + }, + "node_modules/geomagnetism": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/geomagnetism/-/geomagnetism-0.2.0.tgz", + "integrity": "sha512-dO8HJrXqah244nMe+pU5m52L90SMoi4lDA0AV3xunRxogloYV+s3aYWCW72VMMfiYis+YSAlhoKktw8aLMiJbw==", + "license": "Apache-2.0" + }, + "node_modules/satellite.js": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/satellite.js/-/satellite.js-6.0.2.tgz", + "integrity": "sha512-XWKxtqVF5xiJ1xAeiYeT/oSSzsukoCLWvk6nO/WFy4un0M3g4djAU9TAtOCqJLtYW9vxx9pkPJ1L9ITOc607GA==", + "license": "MIT" + } + } +} diff --git a/node_modules/astronomy-engine/README.md b/node_modules/astronomy-engine/README.md new file mode 100644 index 0000000..d5f75f0 --- /dev/null +++ b/node_modules/astronomy-engine/README.md @@ -0,0 +1,3408 @@ +# Astronomy Engine (JavaScript / TypeScript) + +[![npm](https://img.shields.io/npm/v/astronomy-engine.svg)](https://www.npmjs.com/package/astronomy-engine) + +This is the complete programming reference for the JavaScript version +of Astronomy Engine. It supports client side programming +in the browser, and backend use of [Node.js](https://nodejs.org). + +[Astronomy Engine is available as an npm package](https://www.npmjs.com/package/astronomy-engine). + +Both the browser and backend versions of the JavaScript code are generated from +[TypeScript](https://www.typescriptlang.org/) code in `astronomy.ts`, +which is also provided here for those who want to use it directly. + +Other programming languages are supported also. +See the [home page](https://github.com/cosinekitty/astronomy) for more info. + +--- + +## Quick Start +To use Astronomy Engine in your own project, you can use the TypeScript file `astronomy.ts` +from this directory. + +For convenience, this directory also contains human-readable JavaScript files `astronomy.js` +and minified versions for the browser (`astronomy.browser.min.js`) and Node.js (`astronomy.min.js`). +These JavaScript sources are all compiled from the TypeScript source `astronomy.ts`. + +To get started quickly, here are some [browser scripting examples](../../demo/browser/) +and some [Node.js examples](../../demo/nodejs/). + +--- + +## Topic Index + +### Position of Sun, Moon, and planets + +| Function | Description | +| -------- | ----------- | +| [HelioVector](#HelioVector) | Calculates body position vector with respect to the center of the Sun. | +| [GeoVector](#GeoVector) | Calculates body position vector with respect to the center of the Earth. | +| [Equator](#Equator) | Calculates right ascension and declination. | +| [Ecliptic](#Ecliptic) | Converts J2000 mean equator (EQJ) coordinates to true ecliptic of date (ECT) coordinates. | +| [EclipticLongitude](#EclipticLongitude) | Calculates true ecliptic of date (ECT) longitude for a body. | +| [Horizon](#Horizon) | Calculates horizontal coordinates (azimuth, altitude) for a given observer on the Earth. | +| [PairLongitude](#PairLongitude) | Calculates the difference in apparent ecliptic longitude between two bodies, as seen from the Earth. | +| [BaryState](#BaryState) | Calculates the barycentric position and velocity vectors of the Sun or a planet. | + +### Geographic helper functions + +| Function | Description | +| -------- | ----------- | +| [ObserverVector](#ObserverVector) | Calculates a vector from the center of the Earth to an observer on the Earth's surface. | +| [VectorObserver](#VectorObserver) | Calculates the geographic coordinates for a geocentric equatorial vector. | + +### Rise, set, and culmination times + +| Function | Description | +| -------- | ----------- | +| [SearchRiseSet](#SearchRiseSet) | Finds time of rise or set for a body as seen by an observer on the Earth. | +| [SearchAltitude](#SearchAltitude) | Finds time when a body reaches a given altitude above or below the horizon. Useful for finding civil, nautical, or astronomical twilight. | +| [SearchHourAngle](#SearchHourAngle) | Finds when body reaches a given hour angle for an observer on the Earth. Hour angle = 0 finds culmination, the highest point in the sky. | + +### Moon phases + +| Function | Description | +| -------- | ----------- | +| [MoonPhase](#MoonPhase) | Determines the Moon's phase expressed as an ecliptic longitude. | +| [SearchMoonQuarter](#SearchMoonQuarter) | Find the first quarter moon phase after a given date and time. | +| [NextMoonQuarter](#NextMoonQuarter) | Find the next quarter moon phase after a previous one that has been found. | + +### Eclipses and Transits + +| Function | Description | +| -------- | ----------- | +| [SearchLunarEclipse](#SearchLunarEclipse) | Search for the first lunar eclipse after a given date. | +| [NextLunarEclipse](#NextLunarEclipse) | Continue searching for more lunar eclipses. | +| [SearchGlobalSolarEclipse](#SearchGlobalSolarEclipse) | Search for the first solar eclipse after a given date that is visible anywhere on the Earth. | +| [NextGlobalSolarEclipse](#NextGlobalSolarEclipse) | Continue searching for solar eclipses visible anywhere on the Earth. | +| [SearchLocalSolarEclipse](#SearchLocalSolarEclipse) | Search for the first solar eclipse after a given date that is visible at a particular location on the Earth. | +| [NextLocalSolarEclipse](#NextLocalSolarEclipse) | Continue searching for solar eclipses visible at a particular location on the Earth. | +| [SearchTransit](#SearchTransit) | Search for the next transit of Mercury or Venus. | +| [NextTransit](#NextTransit) | Continue searching for transits of Mercury or Venus. | + +### Lunar perigee and apogee + +| Function | Description | +| -------- | ----------- | +| [SearchLunarApsis](#SearchLunarApsis) | Finds the next perigee or apogee of the Moon after a specified date. | +| [NextLunarApsis](#NextLunarApsis) | Given an already-found apsis, find the next perigee or apogee of the Moon. | + +### Planet perihelion and aphelion + +| Function | Description | +| -------- | ----------- | +| [SearchPlanetApsis](#SearchPlanetApsis) | Finds the next perihelion or aphelion of a planet after a specified date. | +| [NextPlanetApsis](#NextPlanetApsis) | Given an already-found apsis, find the next perihelion or aphelion of a planet. | + +### Visual magnitude and elongation + +| Function | Description | +| -------- | ----------- | +| [Illumination](#Illumination) | Calculates visual magnitude and phase angle of bodies as seen from the Earth. | +| [SearchPeakMagnitude](#SearchPeakMagnitude) | Searches for the date and time Venus will next appear brightest as seen from the Earth. | +| [AngleFromSun](#AngleFromSun) | Returns full angle seen from Earth between body and Sun. | +| [Elongation](#Elongation) | Calculates ecliptic longitude angle between a body and the Sun, as seen from the Earth. | +| [SearchMaxElongation](#SearchMaxElongation) | Searches for the next maximum elongation event for Mercury or Venus that occurs after the given date. | + +### Oppositions and conjunctions + +| Function | Description | +| -------- | ----------- | +| [SearchRelativeLongitude](#SearchRelativeLongitude) | Find oppositions and conjunctions of planets. | + +### Equinoxes and solstices + +| Function | Description | +| -------- | ----------- | +| [Seasons](#Seasons) | Finds the equinoxes and solstices for a given calendar year. | +| [SunPosition](#SunPosition) | Calculates the Sun's apparent true ecliptic of date (ECT) coordinates as seen from the Earth. | + +### Coordinate transforms + +The following orientation systems are supported. +Astronomy Engine can convert a vector from any of these orientations to any of the others. +It also allows converting from a vector to spherical (angular) coordinates and back, +within a given orientation. Note the 3-letter codes for each of the orientation systems; +these are used in function and type names. + +- **EQJ = J2000 Mean Equator**: Uses the Earth's mean equator (corrected for precession but ignoring nutation) on January 1, 2000, at noon UTC. This moment in time is called J2000. +- **EQD = True Equator of Date**: Uses the Earth's equator on a given date and time, adjusted for precession and nutation. +- **ECL = J2000 Mean Ecliptic**: Uses the plane of the Earth's orbit around the Sun at J2000. The x-axis is referenced against the J2000 mean equinox. +- **ECT = True Ecliptic of Date**: Uses the true (corrected for precession and nutation) orbital plane of the Earth on the given date. The x-axis is referenced against the true equinox for that date. +- **HOR = Horizontal**: Uses the viewpoint of an observer at a specific location on the Earth at a given date and time. +- **GAL = Galactic**: Based on the IAU 1958 definition of galactic coordinates. + +| Function | Description | +| -------- | ----------- | +| [RotateVector](#RotateVector) | Applies a rotation matrix to a vector, yielding a vector in another orientation system. | +| [InverseRotation](#InverseRotation) | Given a rotation matrix, finds the inverse rotation matrix that does the opposite transformation. | +| [CombineRotation](#CombineRotation) | Given two rotation matrices, returns a rotation matrix that combines them into a net transformation. | +| [IdentityMatrix](#IdentityMatrix) | Returns a 3x3 identity matrix, which can be used to form other rotation matrices. | +| [Pivot](#Pivot) | Transforms a rotation matrix by pivoting it around a given axis by a given angle. | +| [VectorFromSphere](#VectorFromSphere) | Converts spherical coordinates to Cartesian coordinates. | +| [SphereFromVector](#SphereFromVector) | Converts Cartesian coordinates to spherical coordinates. | +| [EquatorFromVector](#EquatorFromVector) | Given an equatorial vector, calculates equatorial angular coordinates. | +| [VectorFromHorizon](#VectorFromHorizon) | Given apparent angular horizontal coordinates, calculates horizontal vector. | +| [HorizonFromVector](#HorizonFromVector) | Given a vector in horizontal orientation, calculates horizontal angular coordinates. | +| [Rotation_EQD_EQJ](#Rotation_EQD_EQJ) | Calculates a rotation matrix from true equator of date (EQD) to J2000 mean equator (EQJ). | +| [Rotation_EQD_ECT](#Rotation_EQD_ECT) | Calculates a rotation matrix from true equator of date (EQD) to true ecliptic of date (ECT). | +| [Rotation_EQD_ECL](#Rotation_EQD_ECL) | Calculates a rotation matrix from true equator of date (EQD) to J2000 mean ecliptic (ECL). | +| [Rotation_EQD_HOR](#Rotation_EQD_HOR) | Calculates a rotation matrix from true equator of date (EQD) to horizontal (HOR). | +| [Rotation_EQJ_EQD](#Rotation_EQJ_EQD) | Calculates a rotation matrix from J2000 mean equator (EQJ) to true equator of date (EQD). | +| [Rotation_EQJ_ECT](#Rotation_EQJ_ECT) | Calculates a rotation matrix from J2000 mean equator (EQJ) to true ecliptic of date (ECT). | +| [Rotation_EQJ_ECL](#Rotation_EQJ_ECL) | Calculates a rotation matrix from J2000 mean equator (EQJ) to J2000 mean ecliptic (ECL). | +| [Rotation_EQJ_HOR](#Rotation_EQJ_HOR) | Calculates a rotation matrix from J2000 mean equator (EQJ) to horizontal (HOR). | +| [Rotation_ECT_EQD](#Rotation_ECT_EQD) | Calculates a rotation matrix from true ecliptic of date (ECT) to true equator of date (EQD). | +| [Rotation_ECT_EQJ](#Rotation_ECT_EQJ) | Calculates a rotation matrix from true ecliptic of date (ECT) J2000 mean equator (EQJ). | +| [Rotation_ECL_EQD](#Rotation_ECL_EQD) | Calculates a rotation matrix from J2000 mean ecliptic (ECL) to true equator of date (EQD). | +| [Rotation_ECL_EQJ](#Rotation_ECL_EQJ) | Calculates a rotation matrix from J2000 mean ecliptic (ECL) to J2000 mean equator (EQJ). | +| [Rotation_ECL_HOR](#Rotation_ECL_HOR) | Calculates a rotation matrix from J2000 mean ecliptic (ECL) to horizontal (HOR). | +| [Rotation_HOR_EQD](#Rotation_HOR_EQD) | Calculates a rotation matrix from horizontal (HOR) to true equator of date (EQD). | +| [Rotation_HOR_EQJ](#Rotation_HOR_EQJ) | Calculates a rotation matrix from horizontal (HOR) to J2000 mean equator (EQJ). | +| [Rotation_HOR_ECL](#Rotation_HOR_ECL) | Calculates a rotation matrix from horizontal (HOR) to J2000 mean ecliptic (ECL). | +| [Rotation_EQJ_GAL](#Rotation_EQJ_GAL) | Calculates a rotation matrix from J2000 mean equator (EQJ) to galactic (GAL). | +| [Rotation_GAL_EQJ](#Rotation_GAL_EQJ) | Calculates a rotation matrix from galactic (GAL) to J2000 mean equator (EQJ). | + +### Gravitational simulation of small bodies + +Astronomy Engine provides a [GravitySimulator](#GravitySimulator) class +that allows you to model the trajectories of one or more small bodies like asteroids, +comets, or coasting spacecraft. If you know an initial position vector +and velocity vector for a small body, the gravity simulator can incrementally +simulate the pull of gravity on it from the Sun and planets, to calculate its +movement through the Solar System. + +--- + +## API Reference + + + +## AstroTime +**Kind**: global class +**Brief**: The date and time of an astronomical observation. + +Objects of type `AstroTime` are used throughout the internals +of the Astronomy library, and are included in certain return objects. +Use the constructor or the [MakeTime](#MakeTime) function to create an `AstroTime` object. +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| date | Date | The JavaScript Date object for the given date and time. This Date corresponds to the numeric day value stored in the `ut` property. | +| ut | number | Universal Time (UT1/UTC) in fractional days since the J2000 epoch. Universal Time represents time measured with respect to the Earth's rotation, tracking mean solar days. The Astronomy library approximates UT1 and UTC as being the same thing. This gives sufficient accuracy for the precision requirements of this project. | +| tt | number | Terrestrial Time in fractional days since the J2000 epoch. TT represents a continuously flowing ephemeris timescale independent of any variations of the Earth's rotation, and is adjusted from UT using a best-fit piecewise polynomial model devised by [Espenak and Meeus](https://eclipse.gsfc.nasa.gov/SEhelp/deltatpoly2004.html). | + + +* * * + + + +### new AstroTime(date) + +| Param | Type | Description | +| --- | --- | --- | +| date | [FlexibleDateTime](#FlexibleDateTime) | A JavaScript Date object, a numeric UTC value expressed in J2000 days, or another AstroTime object. | + + +* * * + + + +### astroTime.toString() ⇒ string +Formats an `AstroTime` object as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) +date/time string in UTC, to millisecond resolution. +Example: `2018-08-17T17:22:04.050Z` + +**Kind**: instance method of [AstroTime](#AstroTime) + +* * * + + + +### astroTime.AddDays(days) ⇒ [AstroTime](#AstroTime) +Returns a new `AstroTime` object adjusted by the floating point number of days. +Does NOT modify the original `AstroTime` object. + +**Kind**: instance method of [AstroTime](#AstroTime) + +| Param | Type | Description | +| --- | --- | --- | +| days | number | The floating point number of days by which to adjust the given date and time. Positive values adjust the date toward the future, and negative values adjust the date toward the past. | + + +* * * + + + +### AstroTime.FromTerrestrialTime(tt) ⇒ [AstroTime](#AstroTime) +**Kind**: static method of [AstroTime](#AstroTime) +**Returns**: [AstroTime](#AstroTime) - An `AstroTime` object for the specified terrestrial time. +**Brief**: Creates an `AstroTime` value from a Terrestrial Time (TT) day value. + +This function can be used in rare cases where a time must be based +on Terrestrial Time (TT) rather than Universal Time (UT). +Most developers will want to invoke `new AstroTime(ut)` with a universal time +instead of this function, because usually time is based on civil time adjusted +by leap seconds to match the Earth's rotation, rather than the uniformly +flowing TT used to calculate solar system dynamics. In rare cases +where the caller already knows TT, this function is provided to create +an `AstroTime` value that can be passed to Astronomy Engine functions. + +| Param | Type | Description | +| --- | --- | --- | +| tt | number | The number of days since the J2000 epoch as expressed in Terrestrial Time. | + + +* * * + + + +## LibrationInfo +**Kind**: global class +**Brief**: Lunar libration angles, returned by [Libration](#Libration). +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| elat | number | Sub-Earth libration ecliptic latitude angle, in degrees. | +| elon | number | Sub-Earth libration ecliptic longitude angle, in degrees. | +| mlat | number | Moon's geocentric ecliptic latitude, in degrees. | +| mlon | number | Moon's geocentric ecliptic longitude, in degrees. | +| dist_km | number | Distance between the centers of the Earth and Moon in kilometers. | +| diam_deg | number | The apparent angular diameter of the Moon, in degrees, as seen from the center of the Earth. | + + +* * * + + + +## Vector +**Kind**: global class +**Brief**: A 3D Cartesian vector with a time attached to it. + +Holds the Cartesian coordinates of a vector in 3D space, +along with the time at which the vector is valid. +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| x | number | The x-coordinate expressed in astronomical units (AU). | +| y | number | The y-coordinate expressed in astronomical units (AU). | +| z | number | The z-coordinate expressed in astronomical units (AU). | +| t | [AstroTime](#AstroTime) | The time at which the vector is valid. | + + +* * * + + + +### vector.Length() ⇒ number +Returns the length of the vector in astronomical units (AU). + +**Kind**: instance method of [Vector](#Vector) + +* * * + + + +## StateVector +**Kind**: global class +**Brief**: A combination of a position vector, a velocity vector, and a time. + +Holds the state vector of a body at a given time, including its position, +velocity, and the time they are valid. +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| x | number | The position x-coordinate expressed in astronomical units (AU). | +| y | number | The position y-coordinate expressed in astronomical units (AU). | +| z | number | The position z-coordinate expressed in astronomical units (AU). | +| vx | number | The velocity x-coordinate expressed in AU/day. | +| vy | number | The velocity y-coordinate expressed in AU/day. | +| vz | number | The velocity z-coordinate expressed in AU/day. | +| t | [AstroTime](#AstroTime) | The time at which the vector is valid. | + + +* * * + + + +## Spherical +**Kind**: global class +**Brief**: Holds spherical coordinates: latitude, longitude, distance. + +Spherical coordinates represent the location of +a point using two angles and a distance. +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| lat | number | The latitude angle: -90..+90 degrees. | +| lon | number | The longitude angle: 0..360 degrees. | +| dist | number | Distance in AU. | + + +* * * + + + +## EquatorialCoordinates +**Kind**: global class +**Brief**: Holds right ascension, declination, and distance of a celestial object. +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| ra | number | Right ascension in sidereal hours: [0, 24). | +| dec | number | Declination in degrees: [-90, +90]. | +| dist | number | Distance to the celestial object expressed in astronomical units (AU). | +| vec | [Vector](#Vector) | The equatorial coordinates in cartesian form, using AU distance units. x = direction of the March equinox, y = direction of the June solstice, z = north. | + + +* * * + + + +## RotationMatrix +**Kind**: global class +**Brief**: Contains a rotation matrix that can be used to transform one coordinate system to another. +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| rot | Array.<Array.<number>> | A normalized 3x3 rotation matrix. For example, the identity matrix is represented as `[[1, 0, 0], [0, 1, 0], [0, 0, 1]]`. | + + +* * * + + + +## HorizontalCoordinates +**Kind**: global class +**Brief**: Represents the location of an object seen by an observer on the Earth. + +Holds azimuth (compass direction) and altitude (angle above/below the horizon) +of a celestial object as seen by an observer at a particular location on the Earth's surface. +Also holds right ascension and declination of the same object. +All of these coordinates are optionally adjusted for atmospheric refraction; +therefore the right ascension and declination values may not exactly match +those found inside a corresponding [EquatorialCoordinates](#EquatorialCoordinates) object. +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| azimuth | number | A horizontal compass direction angle in degrees measured starting at north and increasing positively toward the east. The value is in the range [0, 360). North = 0, east = 90, south = 180, west = 270. | +| altitude | number | A vertical angle in degrees above (positive) or below (negative) the horizon. The value is in the range [-90, +90]. The altitude angle is optionally adjusted upward due to atmospheric refraction. | +| ra | number | The right ascension of the celestial body in sidereal hours. The value is in the reange [0, 24). If `altitude` was adjusted for atmospheric reaction, `ra` is likewise adjusted. | +| dec | number | The declination of of the celestial body in degrees. The value in the range [-90, +90]. If `altitude` was adjusted for atmospheric reaction, `dec` is likewise adjusted. | + + +* * * + + + +## EclipticCoordinates +**Kind**: global class +**Brief**: Ecliptic coordinates of a celestial body. + +The origin and date of the coordinate system may vary depending on the caller's usage. +In general, ecliptic coordinates are measured with respect to the mean plane of the Earth's +orbit around the Sun. +Includes Cartesian coordinates `(ex, ey, ez)` measured in +astronomical units (AU) +and spherical coordinates `(elon, elat)` measured in degrees. +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| vec | [Vector](#Vector) | Ecliptic cartesian vector with components measured in astronomical units (AU). The x-axis is within the ecliptic plane and is oriented in the direction of the equinox. The y-axis is within the ecliptic plane and is oriented 90 degrees counterclockwise from the equinox, as seen from above the Sun's north pole. The z-axis is oriented perpendicular to the ecliptic plane, along the direction of the Sun's north pole. | +| elat | number | The ecliptic latitude of the body in degrees. This is the angle north or south of the ecliptic plane. The value is in the range [-90, +90]. Positive values are north and negative values are south. | +| elon | number | The ecliptic longitude of the body in degrees. This is the angle measured counterclockwise around the ecliptic plane, as seen from above the Sun's north pole. This is the same direction that the Earth orbits around the Sun. The angle is measured starting at 0 from the equinox and increases up to 360 degrees. | + + +* * * + + + +## Observer +**Kind**: global class +**Brief**: Represents the geographic location of an observer on the surface of the Earth. +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| latitude | number | The observer's geographic latitude in degrees north of the Earth's equator. The value is negative for observers south of the equator. Must be in the range -90 to +90. | +| longitude | number | The observer's geographic longitude in degrees east of the prime meridian passing through Greenwich, England. The value is negative for observers west of the prime meridian. The value should be kept in the range -180 to +180 to minimize floating point errors. | +| height | number | The observer's elevation above mean sea level, expressed in meters. | + + +* * * + + + +## JupiterMoonsInfo +**Kind**: global class +**Brief**: Holds the positions and velocities of Jupiter's major 4 moons. + +The [JupiterMoons](#JupiterMoons) function returns an object of this type +to report position and velocity vectors for Jupiter's largest 4 moons +Io, Europa, Ganymede, and Callisto. Each position vector is relative +to the center of Jupiter. Both position and velocity are oriented in +the EQJ system (that is, using Earth's equator at the J2000 epoch). +The positions are expressed in astronomical units (AU), +and the velocities in AU/day. +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| io | [StateVector](#StateVector) | The position and velocity of Jupiter's moon Io. | +| europa | [StateVector](#StateVector) | The position and velocity of Jupiter's moon Europa. | +| ganymede | [StateVector](#StateVector) | The position and velocity of Jupiter's moon Ganymede. | +| callisto | [StateVector](#StateVector) | The position and velocity of Jupiter's moon Callisto. | + + +* * * + + + +## IlluminationInfo +**Kind**: global class +**Brief**: Information about the apparent brightness and sunlit phase of a celestial object. +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| time | [AstroTime](#AstroTime) | The date and time pertaining to the other calculated values in this object. | +| mag | number | The apparent visual magnitude of the celestial body. | +| phase_angle | number | The angle in degrees as seen from the center of the celestial body between the Sun and the Earth. The value is always in the range 0 to 180. The phase angle provides a measure of what fraction of the body's face appears illuminated by the Sun as seen from the Earth. When the observed body is the Sun, the `phase` property is set to 0, although this has no physical meaning because the Sun emits, rather than reflects, light. When the phase is near 0 degrees, the body appears "full". When it is 90 degrees, the body appears "half full". And when it is 180 degrees, the body appears "new" and is very difficult to see because it is both dim and lost in the Sun's glare as seen from the Earth. | +| phase_fraction | number | The fraction of the body's face that is illuminated by the Sun, as seen from the Earth. Calculated from `phase_angle` for convenience. This value ranges from 0 to 1. | +| helio_dist | number | The distance between the center of the Sun and the center of the body in astronomical units (AU). | +| geo_dist | number | The distance between the center of the Earth and the center of the body in AU. | +| gc | [Vector](#Vector) | Geocentric coordinates: the 3D vector from the center of the Earth to the center of the body. The components are in expressed in AU and are oriented with respect to the J2000 equatorial plane. | +| hc | [Vector](#Vector) | Heliocentric coordinates: The 3D vector from the center of the Sun to the center of the body. Like `gc`, `hc` is expressed in AU and oriented with respect to the J2000 equatorial plane. | +| ring_tilt | number \| undefined | For Saturn, this is the angular tilt of the planet's rings in degrees away from the line of sight from the Earth. When the value is near 0, the rings appear edge-on from the Earth and are therefore difficult to see. When `ring_tilt` approaches its maximum value (about 27 degrees), the rings appear widest and brightest from the Earth. Unlike the JPL Horizons online tool, this library includes the effect of the ring tilt angle in the calculated value for Saturn's visual magnitude. For all bodies other than Saturn, the value of `ring_tilt` is `undefined`. | + + +* * * + + + +## MoonQuarter +**Kind**: global class +**Brief**: A quarter lunar phase, along with when it occurs. +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| quarter | number | An integer as follows: 0 = new moon, 1 = first quarter, 2 = full moon, 3 = third quarter. | +| time | [AstroTime](#AstroTime) | The date and time of the quarter lunar phase. | + + +* * * + + + +## AtmosphereInfo +**Kind**: global class +**Brief**: Information about idealized atmospheric variables at a given elevation. +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| pressure | number | Atmospheric pressure in pascals. | +| temperature | number | Atmospheric temperature in kelvins. | +| density | number | Atmospheric density relative to sea level. | + + +* * * + + + +## HourAngleEvent +**Kind**: global class +**Brief**: Horizontal position of a body upon reaching an hour angle. + +Returns information about an occurrence of a celestial body +reaching a given hour angle as seen by an observer at a given +location on the surface of the Earth. +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| time | [AstroTime](#AstroTime) | The date and time of the celestial body reaching the hour angle. | +| hor | [HorizontalCoordinates](#HorizontalCoordinates) | Topocentric horizontal coordinates for the body at the time indicated by the `time` property. | + + +* * * + + + +## SeasonInfo +**Kind**: global class +**Brief**: When the seasons change for a given calendar year. + +Represents the dates and times of the two solstices +and the two equinoxes in a given calendar year. +These four events define the changing of the seasons on the Earth. +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| mar_equinox | [AstroTime](#AstroTime) | The date and time of the March equinox in the given calendar year. This is the moment in March that the plane of the Earth's equator passes through the center of the Sun; thus the Sun's declination changes from a negative number to a positive number. The March equinox defines the beginning of spring in the northern hemisphere and the beginning of autumn in the southern hemisphere. | +| jun_solstice | [AstroTime](#AstroTime) | The date and time of the June solstice in the given calendar year. This is the moment in June that the Sun reaches its most positive declination value. At this moment the Earth's north pole is most tilted most toward the Sun. The June solstice defines the beginning of summer in the northern hemisphere and the beginning of winter in the southern hemisphere. | +| sep_equinox | [AstroTime](#AstroTime) | The date and time of the September equinox in the given calendar year. This is the moment in September that the plane of the Earth's equator passes through the center of the Sun; thus the Sun's declination changes from a positive number to a negative number. The September equinox defines the beginning of autumn in the northern hemisphere and the beginning of spring in the southern hemisphere. | +| dec_solstice | [AstroTime](#AstroTime) | The date and time of the December solstice in the given calendar year. This is the moment in December that the Sun reaches its most negative declination value. At this moment the Earth's south pole is tilted most toward the Sun. The December solstice defines the beginning of winter in the northern hemisphere and the beginning of summer in the southern hemisphere. | + + +* * * + + + +## ElongationEvent +**Kind**: global class +**Brief**: The viewing conditions of a body relative to the Sun. + +Represents the angular separation of a body from the Sun as seen from the Earth +and the relative ecliptic longitudes between that body and the Earth as seen from the Sun. +**See**: [Elongation](#Elongation) +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| time | [AstroTime](#AstroTime) | The date and time of the observation. | +| visibility | string | Either `"morning"` or `"evening"`, indicating when the body is most easily seen. | +| elongation | number | The angle in degrees, as seen from the center of the Earth, of the apparent separation between the body and the Sun. This angle is measured in 3D space and is not projected onto the ecliptic plane. When `elongation` is less than a few degrees, the body is very difficult to see from the Earth because it is lost in the Sun's glare. The elongation is always in the range [0, 180]. | +| ecliptic_separation | number | The absolute value of the difference between the body's ecliptic longitude and the Sun's ecliptic longitude, both as seen from the center of the Earth. This angle measures around the plane of the Earth's orbit (the ecliptic), and ignores how far above or below that plane the body is. The ecliptic separation is measured in degrees and is always in the range [0, 180]. | + + +* * * + + + +## Apsis +**Kind**: global class +**Brief**: A closest or farthest point in a body's orbit around its primary. + +For a planet orbiting the Sun, apsis is a perihelion or aphelion, respectively. +For the Moon orbiting the Earth, apsis is a perigee or apogee, respectively. +**See** + +- [SearchLunarApsis](#SearchLunarApsis) +- [NextLunarApsis](#NextLunarApsis) +- [SearchPlanetApsis](#SearchPlanetApsis) +- [NextPlanetApsis](#NextPlanetApsis) + +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| time | [AstroTime](#AstroTime) | The date and time of the apsis. | +| kind | [ApsisKind](#ApsisKind) | For a closest approach (perigee or perihelion), `kind` is `ApsisKind.Pericenter`. For a farthest distance event (apogee or aphelion), `kind` is `ApsisKind.Apocenter`. | +| dist_au | number | The distance between the centers of the two bodies in astronomical units (AU). | +| dist_km | number | The distance between the centers of the two bodies in kilometers. | + + +* * * + + + +## ConstellationInfo +**Kind**: global class +**Brief**: Reports the constellation that a given celestial point lies within. +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| symbol | string | 3-character mnemonic symbol for the constellation, e.g. "Ori". | +| name | string | Full name of constellation, e.g. "Orion". | +| ra1875 | number | Right ascension expressed in B1875 coordinates. | +| dec1875 | number | Declination expressed in B1875 coordinates. | + + +* * * + + + +## LunarEclipseInfo +**Kind**: global class +**Brief**: Returns information about a lunar eclipse. + +Returned by [SearchLunarEclipse](#SearchLunarEclipse) or [NextLunarEclipse](#NextLunarEclipse) +to report information about a lunar eclipse event. +When a lunar eclipse is found, it is classified as penumbral, partial, or total. +Penumbral eclipses are difficult to observe, because the Moon is only slightly dimmed +by the Earth's penumbra; no part of the Moon touches the Earth's umbra. +Partial eclipses occur when part, but not all, of the Moon touches the Earth's umbra. +Total eclipses occur when the entire Moon passes into the Earth's umbra. + +The `kind` field thus holds one of the enum values `EclipseKind.Penumbral`, `EclipseKind.Partial`, +or `EclipseKind.Total`, depending on the kind of lunar eclipse found. + +The `obscuration` field holds a value in the range [0, 1] that indicates what fraction +of the Moon's apparent disc area is covered by the Earth's umbra at the eclipse's peak. +This indicates how dark the peak eclipse appears. For penumbral eclipses, the obscuration +is 0, because the Moon does not pass through the Earth's umbra. For partial eclipses, +the obscuration is somewhere between 0 and 1. For total lunar eclipses, the obscuration is 1. + +Field `peak` holds the date and time of the peak of the eclipse, when it is at its peak. + +Fields `sd_penum`, `sd_partial`, and `sd_total` hold the semi-duration of each phase +of the eclipse, which is half of the amount of time the eclipse spends in each +phase (expressed in minutes), or 0 if the eclipse never reaches that phase. +By converting from minutes to days, and subtracting/adding with `peak`, the caller +may determine the date and time of the beginning/end of each eclipse phase. +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| kind | [EclipseKind](#EclipseKind) | The type of lunar eclipse found. | +| obscuration | number | The peak fraction of the Moon's apparent disc that is covered by the Earth's umbra. | +| peak | [AstroTime](#AstroTime) | The time of the eclipse at its peak. | +| sd_penum | number | The semi-duration of the penumbral phase in minutes. | +| sd_partial | number | The semi-duration of the penumbral phase in minutes, or 0.0 if none. | +| sd_total | number | The semi-duration of the penumbral phase in minutes, or 0.0 if none. | + + +* * * + + + +## GlobalSolarEclipseInfo +**Kind**: global class +**Brief**: Reports the time and geographic location of the peak of a solar eclipse. + +Returned by [SearchGlobalSolarEclipse](#SearchGlobalSolarEclipse) or [NextGlobalSolarEclipse](#NextGlobalSolarEclipse) +to report information about a solar eclipse event. + +The eclipse is classified as partial, annular, or total, depending on the +maximum amount of the Sun's disc obscured, as seen at the peak location +on the surface of the Earth. + +The `kind` field thus holds one of the values `EclipseKind.Partial`, `EclipseKind.Annular`, or `EclipseKind.Total`. +A total eclipse is when the peak observer sees the Sun completely blocked by the Moon. +An annular eclipse is like a total eclipse, but the Moon is too far from the Earth's surface +to completely block the Sun; instead, the Sun takes on a ring-shaped appearance. +A partial eclipse is when the Moon blocks part of the Sun's disc, but nobody on the Earth +observes either a total or annular eclipse. + +If `kind` is `EclipseKind.Total` or `EclipseKind.Annular`, the `latitude` and `longitude` +fields give the geographic coordinates of the center of the Moon's shadow projected +onto the daytime side of the Earth at the instant of the eclipse's peak. +If `kind` has any other value, `latitude` and `longitude` are undefined and should +not be used. + +For total or annular eclipses, the `obscuration` field holds the fraction (0, 1] +of the Sun's apparent disc area that is blocked from view by the Moon's silhouette, +as seen by an observer located at the geographic coordinates `latitude`, `longitude` +at the darkest time `peak`. The value will always be 1 for total eclipses, and less than +1 for annular eclipses. +For partial eclipses, `obscuration` is undefined and should not be used. +This is because there is little practical use for an obscuration value of +a partial eclipse without supplying a particular observation location. +Developers who wish to find an obscuration value for partial solar eclipses should therefore use +[SearchLocalSolarEclipse](#SearchLocalSolarEclipse) and provide the geographic coordinates of an observer. +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| kind | [EclipseKind](#EclipseKind) | One of the following enumeration values: `EclipseKind.Partial`, `EclipseKind.Annular`, `EclipseKind.Total`. | +| obscuration | number \| undefined | The peak fraction of the Sun's apparent disc area obscured by the Moon (total and annular eclipses only) | +| peak | [AstroTime](#AstroTime) | The date and time when the solar eclipse is darkest. This is the instant when the axis of the Moon's shadow cone passes closest to the Earth's center. | +| distance | number | The distance in kilometers between the axis of the Moon's shadow cone and the center of the Earth at the time indicated by `peak`. | +| latitude | number \| undefined | If `kind` holds `EclipseKind.Total`, the geographic latitude in degrees where the center of the Moon's shadow falls on the Earth at the time indicated by `peak`; otherwise, `latitude` holds `undefined`. | +| longitude | number \| undefined | If `kind` holds `EclipseKind.Total`, the geographic longitude in degrees where the center of the Moon's shadow falls on the Earth at the time indicated by `peak`; otherwise, `longitude` holds `undefined`. | + + +* * * + + + +## EclipseEvent +**Kind**: global class +**Brief**: Holds a time and the observed altitude of the Sun at that time. + +When reporting a solar eclipse observed at a specific location on the Earth +(a "local" solar eclipse), a series of events occur. In addition +to the time of each event, it is important to know the altitude of the Sun, +because each event may be invisible to the observer if the Sun is below +the horizon. + +If `altitude` is negative, the event is theoretical only; it would be +visible if the Earth were transparent, but the observer cannot actually see it. +If `altitude` is positive but less than a few degrees, visibility will be impaired by +atmospheric interference (sunrise or sunset conditions). +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| time | [AstroTime](#AstroTime) | The date and time of the event. | +| altitude | number | The angular altitude of the center of the Sun above/below the horizon, at `time`, corrected for atmospheric refraction and expressed in degrees. | + + +* * * + + + +## LocalSolarEclipseInfo +**Kind**: global class +**Brief**: Information about a solar eclipse as seen by an observer at a given time and geographic location. + +Returned by [SearchLocalSolarEclipse](#SearchLocalSolarEclipse) or [NextLocalSolarEclipse](#NextLocalSolarEclipse) +to report information about a solar eclipse as seen at a given geographic location. + +When a solar eclipse is found, it is classified by setting `kind` +to `EclipseKind.Partial`, `EclipseKind.Annular`, or `EclipseKind.Total`. +A partial solar eclipse is when the Moon does not line up directly enough with the Sun +to completely block the Sun's light from reaching the observer. +An annular eclipse occurs when the Moon's disc is completely visible against the Sun +but the Moon is too far away to completely block the Sun's light; this leaves the +Sun with a ring-like appearance. +A total eclipse occurs when the Moon is close enough to the Earth and aligned with the +Sun just right to completely block all sunlight from reaching the observer. + +The `obscuration` field reports what fraction of the Sun's disc appears blocked +by the Moon when viewed by the observer at the peak eclipse time. +This is a value that ranges from 0 (no blockage) to 1 (total eclipse). +The obscuration value will be between 0 and 1 for partial eclipses and annular eclipses. +The value will be exactly 1 for total eclipses. Obscuration gives an indication +of how dark the eclipse appears. + +There are 5 "event" fields, each of which contains a time and a solar altitude. +Field `peak` holds the date and time of the center of the eclipse, when it is at its peak. +The fields `partial_begin` and `partial_end` are always set, and indicate when +the eclipse begins/ends. If the eclipse reaches totality or becomes annular, +`total_begin` and `total_end` indicate when the total/annular phase begins/ends. +When an event field is valid, the caller must also check its `altitude` field to +see whether the Sun is above the horizon at the time indicated by the `time` field. +See [EclipseEvent](#EclipseEvent) for more information. +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| kind | [EclipseKind](#EclipseKind) | The type of solar eclipse found: `EclipseKind.Partial`, `EclipseKind.Annular`, or `EclipseKind.Total`. | +| obscuration | number | The fraction of the Sun's apparent disc area obscured by the Moon at the eclipse peak. | +| partial_begin | [EclipseEvent](#EclipseEvent) | The time and Sun altitude at the beginning of the eclipse. | +| total_begin | [EclipseEvent](#EclipseEvent) \| undefined | If this is an annular or a total eclipse, the time and Sun altitude when annular/total phase begins; otherwise undefined. | +| peak | [EclipseEvent](#EclipseEvent) | The time and Sun altitude when the eclipse reaches its peak. | +| total_end | [EclipseEvent](#EclipseEvent) \| undefined | If this is an annular or a total eclipse, the time and Sun altitude when annular/total phase ends; otherwise undefined. | +| partial_end | [EclipseEvent](#EclipseEvent) | The time and Sun altitude at the end of the eclipse. | + + +* * * + + + +## TransitInfo +**Kind**: global class +**Brief**: Information about a transit of Mercury or Venus, as seen from the Earth. + +Returned by [SearchTransit](#SearchTransit) or [NextTransit](#NextTransit) to report +information about a transit of Mercury or Venus. +A transit is when Mercury or Venus passes between the Sun and Earth so that +the other planet is seen in silhouette against the Sun. + +The calculations are performed from the point of view of a geocentric observer. +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| start | [AstroTime](#AstroTime) | The date and time at the beginning of the transit. This is the moment the planet first becomes visible against the Sun in its background. | +| peak | [AstroTime](#AstroTime) | When the planet is most aligned with the Sun, as seen from the Earth. | +| finish | [AstroTime](#AstroTime) | The date and time at the end of the transit. This is the moment the planet is last seen against the Sun in its background. | +| separation | number | The minimum angular separation, in arcminutes, between the centers of the Sun and the planet. This angle pertains to the time stored in `peak`. | + + +* * * + + + +## NodeEventInfo +**Kind**: global class +**Brief**: Information about an ascending or descending node of a body. + +This object is returned by [SearchMoonNode](#SearchMoonNode) and [NextMoonNode](#NextMoonNode) +to report information about the center of the Moon passing through the ecliptic plane. +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| kind | [NodeEventKind](#NodeEventKind) | Whether the node is ascending (south to north) or descending (north to south). | +| time | [AstroTime](#AstroTime) | The time when the body passes through the ecliptic plane. | + + +* * * + + + +## AxisInfo +**Kind**: global class +**Brief**: Information about a body's rotation axis at a given time. + +This structure is returned by [RotationAxis](#RotationAxis) to report +the orientation of a body's rotation axis at a given moment in time. +The axis is specified by the direction in space that the body's north pole +points, using angular equatorial coordinates in the J2000 system (EQJ). + +Thus `ra` is the right ascension, and `dec` is the declination, of the +body's north pole vector at the given moment in time. The north pole +of a body is defined as the pole that lies on the north side of the +[Solar System's invariable plane](https://en.wikipedia.org/wiki/Invariable_plane), +regardless of the body's direction of rotation. + +The `spin` field indicates the angular position of a prime meridian +arbitrarily recommended for the body by the International Astronomical +Union (IAU). + +The fields `ra`, `dec`, and `spin` correspond to the variables +α0, δ0, and W, respectively, from +[Report of the IAU Working Group on Cartographic Coordinates and Rotational Elements: 2015](https://astropedia.astrogeology.usgs.gov/download/Docs/WGCCRE/WGCCRE2015reprint.pdf). +The field `north` is a unit vector pointing in the direction of the body's north pole. +It is expressed in the J2000 mean equator system (EQJ). +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| ra | number | The J2000 right ascension of the body's north pole direction, in sidereal hours. | +| dec | number | The J2000 declination of the body's north pole direction, in degrees. | +| spin | number | Rotation angle of the body's prime meridian, in degrees. | +| north | [Vector](#Vector) | A J2000 dimensionless unit vector pointing in the direction of the body's north pole. | + + +* * * + + + +## GravitySimulator +**Kind**: global class +**Brief**: A simulation of zero or more small bodies moving through the Solar System. + +This class calculates the movement of arbitrary small bodies, +such as asteroids or comets, that move through the Solar System. +It does so by calculating the gravitational forces on the small bodies +from the Sun and planets. The user of this class supplies a +list of initial positions and velocities for the small bodies. +Then the class can update the positions and velocities over small +time steps. + +* * * + + + +### new GravitySimulator(originBody, date, bodyStates) + +| Param | Type | Description | +| --- | --- | --- | +| originBody | [Body](#Body) | Specifies the origin of the reference frame. All position vectors and velocity vectors will use `originBody` as the origin of the coordinate system. This origin applies to all the input vectors provided in the `bodyStates` parameter of this function, along with all output vectors returned by [Update](#GravitySimulator+Update). Most callers will want to provide one of the following: `Body.Sun` for heliocentric coordinates, `Body.SSB` for solar system barycentric coordinates, or `Body.Earth` for geocentric coordinates. Note that the gravity simulator does not correct for light travel time; all state vectors are tied to a Newtonian "instantaneous" time. | +| date | [FlexibleDateTime](#FlexibleDateTime) | The initial time at which to start the simulation. | +| bodyStates | [Array.<StateVector>](#StateVector) | An array of zero or more initial state vectors (positions and velocities) of the small bodies to be simulated. The caller must know the positions and velocities of the small bodies at an initial moment in time. Their positions and velocities are expressed with respect to `originBody`, using equatorial J2000 orientation (EQJ). Positions are expressed in astronomical units (AU). Velocities are expressed in AU/day. All the times embedded within the state vectors must exactly match `date`, or this constructor will throw an exception. | + + +* * * + + + +### gravitySimulator.OriginBody +**Kind**: instance property of [GravitySimulator](#GravitySimulator) +**Brief**: The body that was selected as the coordinate origin when this simulator was created. + +* * * + + + +### gravitySimulator.Time +**Kind**: instance property of [GravitySimulator](#GravitySimulator) +**Brief**: The time represented by the current step of the gravity simulation. + +* * * + + + +### gravitySimulator.Update(date) ⇒ [Array.<StateVector>](#StateVector) +Advances the gravity simulation by a small time step. + +Updates the simulation of the user-supplied small bodies +to the time indicated by the `date` parameter. +Returns an array of state vectors for the simulated bodies. +The array is in the same order as the original array that +was used to construct this simulator object. +The positions and velocities in the returned array are +referenced to the `originBody` that was used to construct +this simulator. + +**Kind**: instance method of [GravitySimulator](#GravitySimulator) +**Returns**: [Array.<StateVector>](#StateVector) - An array of state vectors, one for each simulated small body. + +| Param | Type | Description | +| --- | --- | --- | +| date | [FlexibleDateTime](#FlexibleDateTime) | A time that is a small increment away from the current simulation time. It is up to the developer to figure out an appropriate time increment. Depending on the trajectories, a smaller or larger increment may be needed for the desired accuracy. Some experimentation may be needed. Generally, bodies that stay in the outer Solar System and move slowly can use larger time steps. Bodies that pass into the inner Solar System and move faster will need a smaller time step to maintain accuracy. The `date` value may be after or before the current simulation time to move forward or backward in time. | + + +* * * + + + +### gravitySimulator.Swap() +Exchange the current time step with the previous time step. + +Sometimes it is helpful to "explore" various times near a given +simulation time step, while repeatedly returning to the original +time step. For example, when backdating a position for light travel +time, the caller may wish to repeatedly try different amounts of +backdating. When the backdating solver has converged, the caller +wants to leave the simulation in its original state. + +This function allows a single "undo" of a simulation, and does so +very efficiently. + +Usually this function will be called immediately after a matching +call to [Update](#GravitySimulator+Update). It has the effect of rolling +back the most recent update. If called twice in a row, it reverts +the swap and thus has no net effect. + +The constructor initializes the current state and previous +state to be identical. Both states represent the `time` parameter that was +passed into the constructor. Therefore, `Swap` will +have no effect from the caller's point of view when passed a simulator +that has not yet been updated by a call to [Update](#GravitySimulator+Update). + +**Kind**: instance method of [GravitySimulator](#GravitySimulator) + +* * * + + + +### gravitySimulator.SolarSystemBodyState(body) +Get the position and velocity of a Solar System body included in the simulation. + +In order to simulate the movement of small bodies through the Solar System, +the simulator needs to calculate the state vectors for the Sun and planets. + +If an application wants to know the positions of one or more of the planets +in addition to the small bodies, this function provides a way to obtain +their state vectors. This is provided for the sake of efficiency, to avoid +redundant calculations. + +The state vector is returned relative to the position and velocity +of the `originBody` parameter that was passed to this object's constructor. + +**Kind**: instance method of [GravitySimulator](#GravitySimulator) + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | The Sun, Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, or Neptune. | + + +* * * + + + +## C\_AUDAY +**Kind**: global variable +**Brief**: The speed of light in AU/day. + +* * * + + + +## KM\_PER\_AU +**Kind**: global variable +**Brief**: The number of kilometers per astronomical unit. + +* * * + + + +## AU\_PER\_LY +**Kind**: global variable +**Brief**: The number of astronomical units per light-year. + +* * * + + + +## DEG2RAD +**Kind**: global variable +**Brief**: The factor to convert degrees to radians = pi/180. + +* * * + + + +## HOUR2RAD +**Kind**: global variable +**Brief**: The factor to convert sidereal hours to radians = pi/12. + +* * * + + + +## RAD2DEG +**Kind**: global variable +**Brief**: The factor to convert radians to degrees = 180/pi. + +* * * + + + +## RAD2HOUR +**Kind**: global variable +**Brief**: The factor to convert radians to sidereal hours = 12/pi. + +* * * + + + +## JUPITER\_EQUATORIAL\_RADIUS\_KM +**Kind**: global variable +**Brief**: The equatorial radius of Jupiter, expressed in kilometers. + +* * * + + + +## JUPITER\_POLAR\_RADIUS\_KM +**Kind**: global variable +**Brief**: The polar radius of Jupiter, expressed in kilometers. + +* * * + + + +## JUPITER\_MEAN\_RADIUS\_KM +**Kind**: global variable +**Brief**: The volumetric mean radius of Jupiter, expressed in kilometers. + +* * * + + + +## IO\_RADIUS\_KM +**Kind**: global variable +**Brief**: The mean radius of Jupiter's moon Io, expressed in kilometers. + +* * * + + + +## EUROPA\_RADIUS\_KM +**Kind**: global variable +**Brief**: The mean radius of Jupiter's moon Europa, expressed in kilometers. + +* * * + + + +## GANYMEDE\_RADIUS\_KM +**Kind**: global variable +**Brief**: The mean radius of Jupiter's moon Ganymede, expressed in kilometers. + +* * * + + + +## CALLISTO\_RADIUS\_KM +**Kind**: global variable +**Brief**: The mean radius of Jupiter's moon Callisto, expressed in kilometers. + +* * * + + + +## Body : enum +**Kind**: global enum +**Brief**: String constants that represent the solar system bodies supported by Astronomy Engine. + +The following strings represent solar system bodies supported by various Astronomy Engine functions. +Not every body is supported by every function; consult the documentation for each function +to find which bodies it supports. + +"Sun", "Moon", "Mercury", "Venus", "Earth", "Mars", "Jupiter", +"Saturn", "Uranus", "Neptune", "Pluto", +"SSB" (Solar System Barycenter), +"EMB" (Earth/Moon Barycenter) + +You can also use enumeration syntax for the bodies, like +`Astronomy.Body.Moon`, `Astronomy.Body.Jupiter`, etc. + +* * * + + + +## ApsisKind : enum +**Kind**: global enum +**Brief**: The two kinds of apsis: pericenter (closest) and apocenter (farthest). + +`Pericenter`: The body is at its closest distance to the object it orbits. +`Apocenter`: The body is at its farthest distance from the object it orbits. + +* * * + + + +## EclipseKind : enum +**Kind**: global enum +**Brief**: The different kinds of lunar/solar eclipses.. + +`Penumbral`: A lunar eclipse in which only the Earth's penumbra falls on the Moon. (Never used for a solar eclipse.) +`Partial`: A partial lunar/solar eclipse. +`Annular`: A solar eclipse in which the entire Moon is visible against the Sun, but the Sun appears as a ring around the Moon. (Never used for a lunar eclipse.) +`Total`: A total lunar/solar eclipse. + +* * * + + + +## NodeEventKind : enum +**Kind**: global enum +**Brief**: Indicates whether a crossing through the ecliptic plane is ascending or descending. + +`Invalid` is a placeholder for an unknown or missing node. +`Ascending` indicates a body passing through the ecliptic plane from south to north. +`Descending` indicates a body passing through the ecliptic plane from north to south. + +* * * + + + +## AngleBetween(a, b) ⇒ number +**Kind**: global function +**Returns**: number - The angle between the two vectors expressed in degrees. + The value is in the range [0, 180]. +**Brief**: Calculates the angle in degrees between two vectors. + +Given a pair of vectors, this function returns the angle in degrees +between the two vectors in 3D space. +The angle is measured in the plane that contains both vectors. + +| Param | Type | Description | +| --- | --- | --- | +| a | [Vector](#Vector) | The first of a pair of vectors between which to measure an angle. | +| b | [Vector](#Vector) | The second of a pair of vectors between which to measure an angle. | + + +* * * + + + +## AngleFromSun(body, date) ⇒ number +**Kind**: global function +**Returns**: number - An angle in degrees in the range [0, 180]. +**Brief**: Calculates the angular separation between the Sun and the given body. + +Returns the full angle seen from +the Earth, between the given body and the Sun. +Unlike [PairLongitude](#PairLongitude), this function does not +project the body's "shadow" onto the ecliptic; +the angle is measured in 3D space around the plane that +contains the centers of the Earth, the Sun, and `body`. + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | The name of a supported celestial body other than the Earth. | +| date | [FlexibleDateTime](#FlexibleDateTime) | The time at which the angle from the Sun is to be found. | + + +* * * + + + +## Atmosphere(elevationMeters) ⇒ [AtmosphereInfo](#AtmosphereInfo) +**Kind**: global function +**Brief**: Calculates U.S. Standard Atmosphere (1976) variables as a function of elevation. + +This function calculates idealized values of pressure, temperature, and density +using the U.S. Standard Atmosphere (1976) model. +1. COESA, U.S. Standard Atmosphere, 1976, U.S. Government Printing Office, Washington, DC, 1976. +2. Jursa, A. S., Ed., Handbook of Geophysics and the Space Environment, Air Force Geophysics Laboratory, 1985. +See: +https://hbcp.chemnetbase.com/faces/documents/14_12/14_12_0001.xhtml +https://ntrs.nasa.gov/api/citations/19770009539/downloads/19770009539.pdf +https://www.ngdc.noaa.gov/stp/space-weather/online-publications/miscellaneous/us-standard-atmosphere-1976/us-standard-atmosphere_st76-1562_noaa.pdf + +| Param | Type | Description | +| --- | --- | --- | +| elevationMeters | number | The elevation above sea level at which to calculate atmospheric variables. Must be in the range -500 to +100000, or an exception will occur. | + + +* * * + + + +## BackdatePosition(date, observerBody, targetBody, aberration) ⇒ [Vector](#Vector) +**Kind**: global function +**Returns**: [Vector](#Vector) - The position vector at the solved backdated time. + The `t` field holds the time that light left the observed + body to arrive at the observer at the observation time. +**Brief**: Solve for light travel time correction of apparent position. + +When observing a distant object, for example Jupiter as seen from Earth, +the amount of time it takes for light to travel from the object to the +observer can significantly affect the object's apparent position. + +This function solves the light travel time correction for the apparent +relative position vector of a target body as seen by an observer body +at a given observation time. + +For geocentric calculations, [GeoVector](#GeoVector) also includes light +travel time correction, but the time `t` embedded in its returned vector +refers to the observation time, not the backdated time that light left +the observed body. Thus `BackdatePosition` provides direct +access to the light departure time for callers that need it. + +For a more generalized light travel correction solver, see [CorrectLightTravel](#CorrectLightTravel). + +| Param | Type | Description | +| --- | --- | --- | +| date | [FlexibleDateTime](#FlexibleDateTime) | The time of observation. | +| observerBody | [Body](#Body) | The body to be used as the observation location. | +| targetBody | [Body](#Body) | The body to be observed. | +| aberration | boolean | `true` to correct for aberration, or `false` to leave uncorrected. | + + +* * * + + + +## BaryState(body, date) ⇒ [StateVector](#StateVector) +**Kind**: global function +**Returns**: [StateVector](#StateVector) - An object that contains barycentric position and velocity vectors. +**Brief**: Calculates barycentric position and velocity vectors for the given body. + +Given a body and a time, calculates the barycentric position and velocity +vectors for the center of that body at that time. +The vectors are expressed in J2000 mean equator coordinates (EQJ). + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | The celestial body whose barycentric state vector is to be calculated. Supported values are `Body.Sun`, `Body.Moon`, `Body.EMB`, `Body.SSB`, and all planets: `Body.Mercury`, `Body.Venus`, `Body.Earth`, `Body.Mars`, `Body.Jupiter`, `Body.Saturn`, `Body.Uranus`, `Body.Neptune`, `Body.Pluto`. | +| date | [FlexibleDateTime](#FlexibleDateTime) | The date and time for which to calculate position and velocity. | + + +* * * + + + +## CombineRotation(a, b) ⇒ [RotationMatrix](#RotationMatrix) +**Kind**: global function +**Returns**: [RotationMatrix](#RotationMatrix) - The combined rotation matrix. +**Brief**: Creates a rotation based on applying one rotation followed by another. + +Given two rotation matrices, returns a combined rotation matrix that is +equivalent to rotating based on the first matrix, followed by the second. + +| Param | Type | Description | +| --- | --- | --- | +| a | [RotationMatrix](#RotationMatrix) | The first rotation to apply. | +| b | [RotationMatrix](#RotationMatrix) | The second rotation to apply. | + + +* * * + + + +## Constellation(ra, dec) ⇒ [ConstellationInfo](#ConstellationInfo) +**Kind**: global function +**Returns**: [ConstellationInfo](#ConstellationInfo) - An object that contains the 3-letter abbreviation and full name + of the constellation that contains the given (ra,dec), along with + the converted B1875 (ra,dec) for that point. +**Brief**: Determines the constellation that contains the given point in the sky. + +Given J2000 equatorial (EQJ) coordinates of a point in the sky, +determines the constellation that contains that point. + +| Param | Type | Description | +| --- | --- | --- | +| ra | number | The right ascension (RA) of a point in the sky, using the J2000 equatorial system. | +| dec | number | The declination (DEC) of a point in the sky, using the J2000 equatorial system. | + + +* * * + + + +## CorrectLightTravel(func, time) ⇒ AstroVector +Solve for light travel time of a vector function. + +When observing a distant object, for example Jupiter as seen from Earth, +the amount of time it takes for light to travel from the object to the +observer can significantly affect the object's apparent position. +This function is a generic solver that figures out how long in the +past light must have left the observed object to reach the observer +at the specified observation time. It requires passing in `func` +to express an arbitrary position vector as a function of time. + +`CorrectLightTravel` repeatedly calls `func`, passing a series of time +estimates in the past. Then `func` must return a relative position vector between +the observer and the target. `CorrectLightTravel` keeps calling +`func` with more and more refined estimates of the time light must have +left the target to arrive at the observer. + +For common use cases, it is simpler to use [BackdatePosition](#BackdatePosition) +for calculating the light travel time correction of one body observing another body. + +For geocentric calculations, [GeoVector](#GeoVector) also backdates the returned +position vector for light travel time, only it returns the observation time in +the returned vector's `t` field rather than the backdated time. + +**Kind**: global function +**Returns**: AstroVector - The position vector at the solved backdated time. + The `t` field holds the time that light left the observed + body to arrive at the observer at the observation time. + +| Param | Type | Description | +| --- | --- | --- | +| func | function | An arbitrary position vector as a function of time: function([AstroTime](#AstroTime)) => [Vector](#Vector). | +| time | [AstroTime](#AstroTime) | The observation time for which to solve for light travel delay. | + + +* * * + + + +## DefineStar(body, ra, dec, distanceLightYears) +**Kind**: global function +**Brief**: Assign equatorial coordinates to a user-defined star. + +Some Astronomy Engine functions allow their `body` parameter to +be a user-defined fixed point in the sky, loosely called a "star". +This function assigns a right ascension, declination, and distance +to one of the eight user-defined stars `Star1`..`Star8`. + +Stars are not valid until defined. Once defined, they retain their +definition until re-defined by another call to `DefineStar`. + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | One of the eight user-defined star identifiers: `Star1`, `Star2`, `Star3`, `Star4`, `Star5`, `Star6`, `Star7`, or `Star8`. | +| ra | number | The right ascension to be assigned to the star, expressed in J2000 equatorial coordinates (EQJ). The value is in units of sidereal hours, and must be within the half-open range [0, 24). | +| dec | number | The declination to be assigned to the star, expressed in J2000 equatorial coordinates (EQJ). The value is in units of degrees north (positive) or south (negative) of the J2000 equator, and must be within the closed range [-90, +90]. | +| distanceLightYears | number | The distance between the star and the Sun, expressed in light-years. This value is used to calculate the tiny parallax shift as seen by an observer on Earth. If you don't know the distance to the star, using a large value like 1000 will generally work well. The minimum allowed distance is 1 light-year, which is required to provide certain internal optimizations. | + + +* * * + + + +## Ecliptic(eqj) ⇒ [EclipticCoordinates](#EclipticCoordinates) +**Kind**: global function +**Brief**: Converts a J2000 mean equator (EQJ) vector to a true ecliptic of date (ETC) vector and angles. + +Given coordinates relative to the Earth's equator at J2000 (the instant of noon UTC +on 1 January 2000), this function converts those coordinates to true ecliptic coordinates +that are relative to the plane of the Earth's orbit around the Sun on that date. + +| Param | Type | Description | +| --- | --- | --- | +| eqj | [Vector](#Vector) | Equatorial coordinates in the EQJ frame of reference. You can call [GeoVector](#GeoVector) to obtain suitable equatorial coordinates. | + + +* * * + + + +## EclipticGeoMoon(date) ⇒ [Spherical](#Spherical) +**Kind**: global function +**Brief**: Calculates spherical ecliptic geocentric position of the Moon. + +Given a time of observation, calculates the Moon's geocentric position +in ecliptic spherical coordinates. Provides the ecliptic latitude and +longitude in degrees, and the geocentric distance in astronomical units (AU). + +The ecliptic angles are measured in "ECT": relative to the true ecliptic plane and +equatorial plane at the specified time. This means the Earth's equator +is corrected for precession and nutation, and the plane of the Earth's +orbit is corrected for gradual obliquity drift. + +This algorithm is based on the Nautical Almanac Office's Improved Lunar Ephemeris of 1954, +which in turn derives from E. W. Brown's lunar theories from the early twentieth century. +It is adapted from Turbo Pascal code from the book +Astronomy on the Personal Computer +by Montenbruck and Pfleger. + +To calculate a J2000 mean equator vector instead, use [GeoMoon](#GeoMoon). + +| Param | Type | Description | +| --- | --- | --- | +| date | [FlexibleDateTime](#FlexibleDateTime) | The date and time for which to calculate the Moon's position. | + + +* * * + + + +## EclipticLongitude(body, date) ⇒ number +**Kind**: global function +**Brief**: Calculates heliocentric ecliptic longitude of a body. + +This function calculates the angle around the plane of the Earth's orbit +of a celestial body, as seen from the center of the Sun. +The angle is measured prograde (in the direction of the Earth's orbit around the Sun) +in degrees from the true equinox of date. The ecliptic longitude is always in the range [0, 360). + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | A body other than the Sun. | +| date | [FlexibleDateTime](#FlexibleDateTime) | The date and time for which to calculate the ecliptic longitude. | + + +* * * + + + +## Elongation(body, date) ⇒ [ElongationEvent](#ElongationEvent) +**Kind**: global function +**Brief**: Calculates the viewing conditions of a body relative to the Sun. + +Calculates angular separation of a body from the Sun as seen from the Earth +and the relative ecliptic longitudes between that body and the Earth as seen from the Sun. +See the return type [ElongationEvent](#ElongationEvent) for details. + +This function is helpful for determining how easy +it is to view a planet away from the Sun's glare on a given date. +It also determines whether the object is visible in the morning or evening; +this is more important the smaller the elongation is. +It is also used to determine how far a planet is from opposition, conjunction, or quadrature. + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | The name of the observed body. Not allowed to be `Body.Earth`. | +| date | [FlexibleDateTime](#FlexibleDateTime) | The date and time of the observation. | + + +* * * + + + +## Equator(body, date, observer, ofdate, aberration) ⇒ [EquatorialCoordinates](#EquatorialCoordinates) +**Kind**: global function +**Returns**: [EquatorialCoordinates](#EquatorialCoordinates) - The topocentric coordinates of the body as adjusted for the given observer. +**Brief**: Calculates equatorial coordinates of a Solar System body at a given time. + +Returns topocentric equatorial coordinates (right ascension and declination) +in one of two different systems: J2000 or true-equator-of-date. +Allows optional correction for aberration. +Always corrects for light travel time (represents the object as seen by the observer +with light traveling to the Earth at finite speed, not where the object is right now). +Topocentric refers to a position as seen by an observer on the surface of the Earth. +This function corrects for +parallax +of the object between a geocentric observer and a topocentric observer. +This is most significant for the Moon, because it is so close to the Earth. +However, it can have a small effect on the apparent positions of other bodies. + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | The body for which to find equatorial coordinates. Not allowed to be `Body.Earth`. | +| date | [FlexibleDateTime](#FlexibleDateTime) | Specifies the date and time at which the body is to be observed. | +| observer | [Observer](#Observer) | The location on the Earth of the observer. | +| ofdate | bool | Pass `true` to return equatorial coordinates of date, i.e. corrected for precession and nutation at the given date. This is needed to get correct horizontal coordinates when you call [Horizon](#Horizon). Pass `false` to return equatorial coordinates in the J2000 system. | +| aberration | bool | Pass `true` to correct for aberration, or `false` to leave uncorrected. | + + +* * * + + + +## EquatorFromVector(vec) ⇒ [EquatorialCoordinates](#EquatorialCoordinates) +**Kind**: global function +**Returns**: [EquatorialCoordinates](#EquatorialCoordinates) - Angular coordinates expressed in the same equatorial system as `vec`. +**Brief**: Given an equatorial vector, calculates equatorial angular coordinates. + +| Param | Type | Description | +| --- | --- | --- | +| vec | [Vector](#Vector) | A vector in an equatorial coordinate system. | + + +* * * + + + +## GeoEmbState(date) ⇒ [StateVector](#StateVector) +**Kind**: global function +**Brief**: Calculates the geocentric position and velocity of the Earth/Moon barycenter. + +Given a time of observation, calculates the geocentric position and velocity vectors +of the Earth/Moon barycenter (EMB). +The position (x, y, z) components are expressed in AU (astronomical units). +The velocity (vx, vy, vz) components are expressed in AU/day. + +| Param | Type | Description | +| --- | --- | --- | +| date | [FlexibleDateTime](#FlexibleDateTime) | The date and time for which to calculate the EMB's geocentric state. | + + +* * * + + + +## GeoMoon(date) ⇒ [Vector](#Vector) +**Kind**: global function +**Brief**: Calculates equatorial geocentric Cartesian coordinates for the Moon. + +Given a time of observation, calculates the Moon's position as a vector. +The vector gives the location of the Moon's center relative to the Earth's center +with x-, y-, and z-components measured in astronomical units. +The coordinates are oriented with respect to the Earth's equator at the J2000 epoch. +In Astronomy Engine, this orientation is called EQJ. +Based on the Nautical Almanac Office's Improved Lunar Ephemeris of 1954, +which in turn derives from E. W. Brown's lunar theories. +Adapted from Turbo Pascal code from the book +Astronomy on the Personal Computer +by Montenbruck and Pfleger. + +| Param | Type | Description | +| --- | --- | --- | +| date | [FlexibleDateTime](#FlexibleDateTime) | The date and time for which to calculate the Moon's geocentric position. | + + +* * * + + + +## GeoMoonState(date) ⇒ [StateVector](#StateVector) +**Kind**: global function +**Brief**: Calculates equatorial geocentric position and velocity of the Moon at a given time. + +Given a time of observation, calculates the Moon's position and velocity vectors. +The position and velocity are of the Moon's center relative to the Earth's center. +The position (x, y, z) components are expressed in AU (astronomical units). +The velocity (vx, vy, vz) components are expressed in AU/day. +The coordinates are oriented with respect to the Earth's equator at the J2000 epoch. +In Astronomy Engine, this orientation is called EQJ. +If you need the Moon's position only, and not its velocity, +it is much more efficient to use [GeoMoon](#GeoMoon) instead. + +| Param | Type | Description | +| --- | --- | --- | +| date | [FlexibleDateTime](#FlexibleDateTime) | The date and time for which to calculate the Moon's geocentric state. | + + +* * * + + + +## GeoVector(body, date, aberration) ⇒ [Vector](#Vector) +**Kind**: global function +**Brief**: Calculates a vector from the center of the Earth to the given body at the given time. + +Calculates geocentric (i.e., with respect to the center of the Earth) +Cartesian coordinates in the J2000 equatorial system of a celestial +body at a specified time. The position is always corrected for light travel time: +this means the position of the body is "back-dated" based on how long it +takes light to travel from the body to an observer on the Earth. +Also, the position can optionally be corrected for aberration, an effect +causing the apparent direction of the body to be shifted based on +transverse movement of the Earth with respect to the rays of light +coming from that body. + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | One of the following values: `Body.Sun`, `Body.Moon`, `Body.Mercury`, `Body.Venus`, `Body.Earth`, `Body.Mars`, `Body.Jupiter`, `Body.Saturn`, `Body.Uranus`, `Body.Neptune`, or `Body.Pluto`. Also allowed to be a user-defined star created with [DefineStar](#DefineStar). | +| date | [FlexibleDateTime](#FlexibleDateTime) | The date and time for which the body's position is to be calculated. | +| aberration | boolean | Pass `true` to correct for aberration, or `false` to leave uncorrected. | + + +* * * + + + +## HelioDistance(body, date) ⇒ number +**Kind**: global function +**Returns**: number - The heliocentric distance in AU. +**Brief**: Calculates the distance between a body and the Sun at a given time. + +Given a date and time, this function calculates the distance between +the center of `body` and the center of the Sun. +For the planets Mercury through Neptune, this function is significantly +more efficient than calling [HelioVector](#HelioVector) followed by taking the length +of the resulting vector. + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | A body for which to calculate a heliocentric distance: the Sun, Moon, any of the planets, or a user-defined star. | +| date | [FlexibleDateTime](#FlexibleDateTime) | The date and time for which to calculate the heliocentric distance. | + + +* * * + + + +## HelioState(body, date) ⇒ [StateVector](#StateVector) +**Kind**: global function +**Returns**: [StateVector](#StateVector) - An object that contains heliocentric position and velocity vectors. +**Brief**: Calculates heliocentric position and velocity vectors for the given body. + +Given a body and a time, calculates the position and velocity +vectors for the center of that body at that time, relative to the center of the Sun. +The vectors are expressed in J2000 mean equator coordinates (EQJ). +If you need the position vector only, it is more efficient to call [HelioVector](#HelioVector). +The Sun's center is a non-inertial frame of reference. In other words, the Sun +experiences acceleration due to gravitational forces, mostly from the larger +planets (Jupiter, Saturn, Uranus, and Neptune). If you want to calculate momentum, +kinetic energy, or other quantities that require a non-accelerating frame +of reference, consider using [BaryState](#BaryState) instead. + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | The celestial body whose heliocentric state vector is to be calculated. Supported values are `Body.Sun`, `Body.Moon`, `Body.EMB`, `Body.SSB`, and all planets: `Body.Mercury`, `Body.Venus`, `Body.Earth`, `Body.Mars`, `Body.Jupiter`, `Body.Saturn`, `Body.Uranus`, `Body.Neptune`, `Body.Pluto`. Also allowed to be a user-defined star created by [DefineStar](#DefineStar). | +| date | [FlexibleDateTime](#FlexibleDateTime) | The date and time for which to calculate position and velocity. | + + +* * * + + + +## HelioVector(body, date) ⇒ [Vector](#Vector) +**Kind**: global function +**Brief**: Calculates a vector from the center of the Sun to the given body at the given time. + +Calculates heliocentric (i.e., with respect to the center of the Sun) +Cartesian coordinates in the J2000 equatorial system of a celestial +body at a specified time. The position is not corrected for light travel time or aberration. + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | One of the following values: `Body.Sun`, `Body.Moon`, `Body.Mercury`, `Body.Venus`, `Body.Earth`, `Body.Mars`, `Body.Jupiter`, `Body.Saturn`, `Body.Uranus`, `Body.Neptune`, `Body.Pluto`, `Body.SSB`, or `Body.EMB`. Also allowed to be a user-defined star created by [DefineStar](#DefineStar). | +| date | [FlexibleDateTime](#FlexibleDateTime) | The date and time for which the body's position is to be calculated. | + + +* * * + + + +## Horizon(date, observer, ra, dec, refraction) ⇒ [HorizontalCoordinates](#HorizontalCoordinates) +**Kind**: global function +**Brief**: Converts equatorial coordinates to horizontal coordinates. + +Given a date and time, a geographic location of an observer on the Earth, and +equatorial coordinates (right ascension and declination) of a celestial body, +returns horizontal coordinates (azimuth and altitude angles) for that body +as seen by that observer. Allows optional correction for atmospheric refraction. + +| Param | Type | Description | +| --- | --- | --- | +| date | [FlexibleDateTime](#FlexibleDateTime) | The date and time for which to find horizontal coordinates. | +| observer | [Observer](#Observer) | The location of the observer for which to find horizontal coordinates. | +| ra | number | Right ascension in sidereal hours of the celestial object, referred to the mean equinox of date for the J2000 epoch. | +| dec | number | Declination in degrees of the celestial object, referred to the mean equator of date for the J2000 epoch. Positive values are north of the celestial equator and negative values are south. | +| refraction | string | If omitted or has a false-like value (false, null, undefined, etc.) the calculations are performed without any correction for atmospheric refraction. If the value is the string `"normal"`, uses the recommended refraction correction based on Meeus "Astronomical Algorithms" with a linear taper more than 1 degree below the horizon. The linear taper causes the refraction to linearly approach 0 as the altitude of the body approaches the nadir (-90 degrees). If the value is the string `"jplhor"`, uses a JPL Horizons compatible formula. This is the same algorithm as `"normal"`, only without linear tapering; this can result in physically impossible altitudes of less than -90 degrees, which may cause problems for some applications. (The `"jplhor"` option was created for unit testing against data generated by JPL Horizons, and is otherwise not recommended for use.) | + + +* * * + + + +## HorizonFromVector(vector, refraction) ⇒ [Spherical](#Spherical) +**Kind**: global function +**Brief**: Converts Cartesian coordinates to horizontal coordinates. + +Given a horizontal Cartesian vector, returns horizontal azimuth and altitude. + +*IMPORTANT:* This function differs from [SphereFromVector](#SphereFromVector) in two ways: +- `SphereFromVector` returns a `lon` value that represents azimuth defined counterclockwise + from north (e.g., west = +90), but this function represents a clockwise rotation + (e.g., east = +90). The difference is because `SphereFromVector` is intended + to preserve the vector "right-hand rule", while this function defines azimuth in a more + traditional way as used in navigation and cartography. +- This function optionally corrects for atmospheric refraction, while `SphereFromVector` does not. + +The returned object contains the azimuth in `lon`. +It is measured in degrees clockwise from north: east = +90 degrees, west = +270 degrees. + +The altitude is stored in `lat`. + +The distance to the observed object is stored in `dist`, +and is expressed in astronomical units (AU). + +| Param | Type | Description | +| --- | --- | --- | +| vector | [Vector](#Vector) | Cartesian vector to be converted to horizontal coordinates. | +| refraction | string | `"normal"`: correct altitude for atmospheric refraction (recommended). `"jplhor"`: for JPL Horizons compatibility testing only; not recommended for normal use. `null`: no atmospheric refraction correction is performed. | + + +* * * + + + +## HourAngle(body, date, observer) ⇒ number +**Kind**: global function +**Brief**: Finds the hour angle of a body for a given observer and time. + +The *hour angle* of a celestial body indicates its position in the sky with respect +to the Earth's rotation. The hour angle depends on the location of the observer on the Earth. +The hour angle is 0 when the body's center reaches its highest angle above the horizon in a given day. +The hour angle increases by 1 unit for every sidereal hour that passes after that point, up +to 24 sidereal hours when it reaches the highest point again. So the hour angle indicates +the number of hours that have passed since the most recent time that the body has culminated, +or reached its highest point. + +This function returns the hour angle of the body as seen at the given time and geogrpahic location. +The hour angle is a number in the half-open range [0, 24). + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | The body whose observed hour angle is to be found. | +| date | [FlexibleDateTime](#FlexibleDateTime) | The date and time of the observation. | +| observer | [Observer](#Observer) | The geographic location where the observation takes place. | + + +* * * + + + +## IdentityMatrix() ⇒ [RotationMatrix](#RotationMatrix) +**Kind**: global function +**Returns**: [RotationMatrix](#RotationMatrix) - The identity matrix. +**Brief**: Creates an identity rotation matrix. + +Returns a rotation matrix that has no effect on orientation. +This matrix can be the starting point for other operations, +such as using a series of calls to [Pivot](#Pivot) to +create a custom rotation matrix. + +* * * + + + +## Illumination(body, date) ⇒ [IlluminationInfo](#IlluminationInfo) +**Kind**: global function +**Brief**: Calculates visual magnitude and related information about a body. + +Calculates the phase angle, visual magnitude, +and other values relating to the body's illumination +at the given date and time, as seen from the Earth. + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | The name of the celestial body being observed. Not allowed to be `Body.Earth`. | +| date | [FlexibleDateTime](#FlexibleDateTime) | The date and time for which to calculate the illumination data for the given body. | + + +* * * + + + +## InverseRefraction(refraction, bent_altitude) ⇒ number +**Kind**: global function +**Returns**: number - The angular adjustment in degrees to be added to the + altitude angle to correct for atmospheric lensing. + This will be less than or equal to zero. +**Brief**: Calculates the inverse of an atmospheric refraction angle. + +Given an observed altitude angle that includes atmospheric refraction, +calculates the negative angular correction to obtain the unrefracted +altitude. This is useful for cases where observed horizontal +coordinates are to be converted to another orientation system, +but refraction first must be removed from the observed position. + +| Param | Type | Description | +| --- | --- | --- | +| refraction | string | `"normal"`: correct altitude for atmospheric refraction (recommended). `"jplhor"`: for JPL Horizons compatibility testing only; not recommended for normal use. `null`: no atmospheric refraction correction is performed. | +| bent_altitude | number | The apparent altitude that includes atmospheric refraction. | + + +* * * + + + +## InverseRotation(rotation) ⇒ [RotationMatrix](#RotationMatrix) +**Kind**: global function +**Returns**: [RotationMatrix](#RotationMatrix) - The inverse rotation matrix. +**Brief**: Calculates the inverse of a rotation matrix. + +Given a rotation matrix that performs some coordinate transform, +this function returns the matrix that reverses that transform. + +| Param | Type | Description | +| --- | --- | --- | +| rotation | [RotationMatrix](#RotationMatrix) | The rotation matrix to be inverted. | + + +* * * + + + +## JupiterMoons(date) ⇒ [JupiterMoonsInfo](#JupiterMoonsInfo) +**Kind**: global function +**Returns**: [JupiterMoonsInfo](#JupiterMoonsInfo) - Position and velocity vectors of Jupiter's largest 4 moons. +**Brief**: Calculates jovicentric positions and velocities of Jupiter's largest 4 moons. + +Calculates position and velocity vectors for Jupiter's moons +Io, Europa, Ganymede, and Callisto, at the given date and time. +The vectors are jovicentric (relative to the center of Jupiter). +Their orientation is the Earth's equatorial system at the J2000 epoch (EQJ). +The position components are expressed in astronomical units (AU), and the +velocity components are in AU/day. + +To convert to heliocentric vectors, call [HelioVector](#HelioVector) +with `Astronomy.Body.Jupiter` to get Jupiter's heliocentric position, then +add the jovicentric vectors. Likewise, you can call [GeoVector](#GeoVector) +to convert to geocentric vectors. + +| Param | Type | Description | +| --- | --- | --- | +| date | [FlexibleDateTime](#FlexibleDateTime) | The date and time for which to calculate Jupiter's moons. | + + +* * * + + + +## LagrangePoint(point, date, major_body, minor_body) ⇒ [StateVector](#StateVector) +**Kind**: global function +**Returns**: [StateVector](#StateVector) - The position and velocity of the selected Lagrange point with respect to the major body's center. +**Brief**: Calculates one of the 5 Lagrange points for a pair of co-orbiting bodies. + +Given a more massive "major" body and a much less massive "minor" body, +calculates one of the five Lagrange points in relation to the minor body's +orbit around the major body. The parameter `point` is an integer that +selects the Lagrange point as follows: + +1 = the Lagrange point between the major body and minor body. +2 = the Lagrange point on the far side of the minor body. +3 = the Lagrange point on the far side of the major body. +4 = the Lagrange point 60 degrees ahead of the minor body's orbital position. +5 = the Lagrange point 60 degrees behind the minor body's orbital position. + +The function returns the state vector for the selected Lagrange point +in J2000 mean equator coordinates (EQJ), with respect to the center of the +major body. + +To calculate Sun/Earth Lagrange points, pass in `Body.Sun` for `major_body` +and `Body.EMB` (Earth/Moon barycenter) for `minor_body`. +For Lagrange points of the Sun and any other planet, pass in that planet +(e.g. `Body.Jupiter`) for `minor_body`. +To calculate Earth/Moon Lagrange points, pass in `Body.Earth` and `Body.Moon` +for the major and minor bodies respectively. + +In some cases, it may be more efficient to call [LagrangePointFast](#LagrangePointFast), +especially when the state vectors have already been calculated, or are needed +for some other purpose. + +| Param | Type | Description | +| --- | --- | --- | +| point | number | An integer 1..5 that selects which of the Lagrange points to calculate. | +| date | [FlexibleDateTime](#FlexibleDateTime) | The time at which the Lagrange point is to be calculated. | +| major_body | [Body](#Body) | The more massive of the co-orbiting bodies: `Body.Sun` or `Body.Earth`. | +| minor_body | [Body](#Body) | The less massive of the co-orbiting bodies. See main remarks. | + + +* * * + + + +## LagrangePointFast(point, major_state, major_mass, minor_state, minor_mass) ⇒ [StateVector](#StateVector) +**Kind**: global function +**Returns**: [StateVector](#StateVector) - The position and velocity of the selected Lagrange point with respect to the major body's center. +**Brief**: Calculates one of the 5 Lagrange points from body masses and state vectors. + +Given a more massive "major" body and a much less massive "minor" body, +calculates one of the five Lagrange points in relation to the minor body's +orbit around the major body. The parameter `point` is an integer that +selects the Lagrange point as follows: + +1 = the Lagrange point between the major body and minor body. +2 = the Lagrange point on the far side of the minor body. +3 = the Lagrange point on the far side of the major body. +4 = the Lagrange point 60 degrees ahead of the minor body's orbital position. +5 = the Lagrange point 60 degrees behind the minor body's orbital position. + +The caller passes in the state vector and mass for both bodies. +The state vectors can be in any orientation and frame of reference. +The body masses are expressed as GM products, where G = the universal +gravitation constant and M = the body's mass. Thus the units for +`major_mass` and `minor_mass` must be au^3/day^2. +Use [MassProduct](#MassProduct) to obtain GM values for various solar system bodies. + +The function returns the state vector for the selected Lagrange point +using the same orientation as the state vector parameters `major_state` and `minor_state`, +and the position and velocity components are with respect to the major body's center. + +Consider calling [LagrangePoint](#LagrangePoint), instead of this function, for simpler usage in most cases. + +| Param | Type | Description | +| --- | --- | --- | +| point | number | A value 1..5 that selects which of the Lagrange points to calculate. | +| major_state | [StateVector](#StateVector) | The state vector of the major (more massive) of the pair of bodies. | +| major_mass | number | The mass product GM of the major body. | +| minor_state | [StateVector](#StateVector) | The state vector of the minor (less massive) of the pair of bodies. | +| minor_mass | number | The mass product GM of the minor body. | + + +* * * + + + +## Libration(date) ⇒ [LibrationInfo](#LibrationInfo) +**Kind**: global function +**Brief**: Calculates the Moon's libration angles at a given moment in time. + +Libration is an observed back-and-forth wobble of the portion of the +Moon visible from the Earth. It is caused by the imperfect tidal locking +of the Moon's fixed rotation rate, compared to its variable angular speed +of orbit around the Earth. + +This function calculates a pair of perpendicular libration angles, +one representing rotation of the Moon in ecliptic longitude `elon`, the other +in ecliptic latitude `elat`, both relative to the Moon's mean Earth-facing position. + +This function also returns the geocentric position of the Moon +expressed in ecliptic longitude `mlon`, ecliptic latitude `mlat`, the +distance `dist_km` between the centers of the Earth and Moon expressed in kilometers, +and the apparent angular diameter of the Moon `diam_deg`. + +| Param | Type | Description | +| --- | --- | --- | +| date | [FlexibleDateTime](#FlexibleDateTime) | A Date object, a number of UTC days since the J2000 epoch (noon on January 1, 2000), or an AstroTime object. | + + +* * * + + + +## MakeRotation(rot) ⇒ [RotationMatrix](#RotationMatrix) +**Kind**: global function +**Brief**: Creates a rotation matrix that can be used to transform one coordinate system to another. + +This function verifies that the `rot` parameter is of the correct format: +a number[3][3] array. It throws an exception if `rot` is not of that shape. +Otherwise it creates a new [RotationMatrix](#RotationMatrix) object based on `rot`. + +| Param | Type | Description | +| --- | --- | --- | +| rot | Array.<Array.<number>> | An array [3][3] of numbers. Defines a rotation matrix used to premultiply a 3D vector to reorient it into another coordinate system. | + + +* * * + + + +## MakeTime(date) ⇒ [AstroTime](#AstroTime) +**Kind**: global function +**Brief**: Converts multiple date/time formats to `AstroTime` format. + +Given a Date object or a number days since noon (12:00) on January 1, 2000 (UTC), +this function creates an [AstroTime](#AstroTime) object. + +Given an [AstroTime](#AstroTime) object, returns the same object unmodified. +Use of this function is not required for any of the other exposed functions in this library, +because they all guarantee converting date/time parameters to `AstroTime` +as needed. However, it may be convenient for callers who need to understand +the difference between UTC and TT (Terrestrial Time). In some use cases, +converting once to `AstroTime` format and passing the result into multiple +function calls may be more efficient than passing in native JavaScript Date objects. + +| Param | Type | Description | +| --- | --- | --- | +| date | [FlexibleDateTime](#FlexibleDateTime) | A Date object, a number of UTC days since the J2000 epoch (noon on January 1, 2000), or an AstroTime object. See remarks above. | + + +* * * + + + +## MassProduct(body) ⇒ number +**Kind**: global function +**Returns**: number - The mass product of the given body in au^3/day^2. +**Brief**: Returns the product of mass and universal gravitational constant of a Solar System body. + +For problems involving the gravitational interactions of Solar System bodies, +it is helpful to know the product GM, where G = the universal gravitational constant +and M = the mass of the body. In practice, GM is known to a higher precision than +either G or M alone, and thus using the product results in the most accurate results. +This function returns the product GM in the units au^3/day^2. +The values come from page 10 of a +[JPL memorandum regarding the DE405/LE405 ephemeris](https://web.archive.org/web/20120220062549/http://iau-comm4.jpl.nasa.gov/de405iom/de405iom.pdf). + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | The body for which to find the GM product. Allowed to be the Sun, Moon, EMB (Earth/Moon Barycenter), or any planet. Any other value will cause an exception to be thrown. | + + +* * * + + + +## MoonPhase(date) ⇒ number +**Kind**: global function +**Returns**: number - A value in the range [0, 360) indicating the difference + in ecliptic longitude between the center of the Sun and the + center of the Moon, as seen from the center of the Earth. + Certain longitude values have conventional meanings: + +* 0 = new moon +* 90 = first quarter +* 180 = full moon +* 270 = third quarter +**Brief**: Determines the moon's phase expressed as an ecliptic longitude. + +| Param | Type | Description | +| --- | --- | --- | +| date | [FlexibleDateTime](#FlexibleDateTime) | The date and time for which to calculate the moon's phase. | + + +* * * + + + +## NextGlobalSolarEclipse(prevEclipseTime) ⇒ [GlobalSolarEclipseInfo](#GlobalSolarEclipseInfo) +**Kind**: global function +**Brief**: Searches for the next global solar eclipse in a series. + +After using [SearchGlobalSolarEclipse](#SearchGlobalSolarEclipse) to find the first solar eclipse +in a series, you can call this function to find the next consecutive solar eclipse. +Pass in the `peak` value from the [GlobalSolarEclipseInfo](#GlobalSolarEclipseInfo) returned by the +previous call to `SearchGlobalSolarEclipse` or `NextGlobalSolarEclipse` +to find the next solar eclipse. + +| Param | Type | Description | +| --- | --- | --- | +| prevEclipseTime | [FlexibleDateTime](#FlexibleDateTime) | A date and time near a new moon. Solar eclipse search will start at the next new moon. | + + +* * * + + + +## NextLocalSolarEclipse(prevEclipseTime, observer) ⇒ [LocalSolarEclipseInfo](#LocalSolarEclipseInfo) +**Kind**: global function +**Brief**: Searches for the next local solar eclipse in a series. + +After using [SearchLocalSolarEclipse](#SearchLocalSolarEclipse) to find the first solar eclipse +in a series, you can call this function to find the next consecutive solar eclipse. +Pass in the `peak` value from the [LocalSolarEclipseInfo](#LocalSolarEclipseInfo) returned by the +previous call to `SearchLocalSolarEclipse` or `NextLocalSolarEclipse` +to find the next solar eclipse. +This function finds the first solar eclipse that occurs after `startTime`. +A solar eclipse may be partial, annular, or total. +See [LocalSolarEclipseInfo](#LocalSolarEclipseInfo) for more information. + +| Param | Type | Description | +| --- | --- | --- | +| prevEclipseTime | [FlexibleDateTime](#FlexibleDateTime) | The date and time for starting the search for a solar eclipse. | +| observer | [Observer](#Observer) | The geographic location of the observer. | + + +* * * + + + +## NextLunarApsis(apsis) ⇒ [Apsis](#Apsis) +**Kind**: global function +**Returns**: [Apsis](#Apsis) - The successor apogee for the given perigee, or the successor perigee for the given apogee. +**Brief**: Finds the next lunar apsis (perigee or apogee) in a series. + +Given a lunar apsis returned by an initial call to [SearchLunarApsis](#SearchLunarApsis), +or a previous call to `NextLunarApsis`, finds the next lunar apsis. +If the given apsis is a perigee, this function finds the next apogee, and vice versa. + +| Param | Type | Description | +| --- | --- | --- | +| apsis | [Apsis](#Apsis) | A lunar perigee or apogee event. | + + +* * * + + + +## NextLunarEclipse(prevEclipseTime) ⇒ [LunarEclipseInfo](#LunarEclipseInfo) +**Kind**: global function +**Brief**: Searches for the next lunar eclipse in a series. + +After using [SearchLunarEclipse](#SearchLunarEclipse) to find the first lunar eclipse +in a series, you can call this function to find the next consecutive lunar eclipse. +Pass in the `peak` value from the [LunarEclipseInfo](#LunarEclipseInfo) returned by the +previous call to `SearchLunarEclipse` or `NextLunarEclipse` +to find the next lunar eclipse. + +| Param | Type | Description | +| --- | --- | --- | +| prevEclipseTime | [FlexibleDateTime](#FlexibleDateTime) | A date and time near a full moon. Lunar eclipse search will start at the next full moon. | + + +* * * + + + +## NextMoonNode(prevNode) ⇒ [NodeEventInfo](#NodeEventInfo) +**Kind**: global function +**Brief**: Searches for the next time when the Moon's center crosses through the ecliptic plane. + +Call [SearchMoonNode](#SearchMoonNode) to find the first of a series of nodes. +Then call `NextMoonNode` to find as many more consecutive nodes as desired. + +| Param | Type | Description | +| --- | --- | --- | +| prevNode | [NodeEventInfo](#NodeEventInfo) | The previous node found from calling [SearchMoonNode](#SearchMoonNode) or `NextMoonNode`. | + + +* * * + + + +## NextMoonQuarter(mq) ⇒ [MoonQuarter](#MoonQuarter) +**Kind**: global function +**Brief**: Finds the next quarter lunar phase in a series. + +Given a [MoonQuarter](#MoonQuarter) object, finds the next consecutive +quarter lunar phase. See remarks in [SearchMoonQuarter](#SearchMoonQuarter) +for explanation of usage. + +| Param | Type | Description | +| --- | --- | --- | +| mq | [MoonQuarter](#MoonQuarter) | The return value of a prior call to [MoonQuarter](#MoonQuarter) or `NextMoonQuarter`. | + + +* * * + + + +## NextPlanetApsis(body, apsis) ⇒ [Apsis](#Apsis) +**Kind**: global function +**Returns**: [Apsis](#Apsis) - Same as the return value for [SearchPlanetApsis](#SearchPlanetApsis). +**Brief**: Finds the next planetary perihelion or aphelion event in a series. + +This function requires an [Apsis](#Apsis) value obtained from a call +to [SearchPlanetApsis](#SearchPlanetApsis) or `NextPlanetApsis`. +Given an aphelion event, this function finds the next perihelion event, and vice versa. +See [SearchPlanetApsis](#SearchPlanetApsis) for more details. + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | The planet for which to find the next perihelion/aphelion event. Not allowed to be `Body.Sun` or `Body.Moon`. Must match the body passed into the call that produced the `apsis` parameter. | +| apsis | [Apsis](#Apsis) | An apsis event obtained from a call to [SearchPlanetApsis](#SearchPlanetApsis) or `NextPlanetApsis`. | + + +* * * + + + +## NextTransit(body, prevTransitTime) ⇒ [TransitInfo](#TransitInfo) +**Kind**: global function +**Brief**: Searches for the next transit of Mercury or Venus in a series. + +After calling [SearchTransit](#SearchTransit) to find a transit of Mercury or Venus, +this function finds the next transit after that. +Keep calling this function as many times as you want to keep finding more transits. + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | The planet whose transit is to be found. Must be `Body.Mercury` or `Body.Venus`. | +| prevTransitTime | [FlexibleDateTime](#FlexibleDateTime) | A date and time near the previous transit. | + + +* * * + + + +## ObserverGravity(latitude, height) ⇒ number +**Kind**: global function +**Returns**: number - The effective gravitational acceleration expressed in meters per second squared [m/s^2]. +**Brief**: Calculates the gravitational acceleration experienced by an observer on the Earth. + +This function implements the WGS 84 Ellipsoidal Gravity Formula. +The result is a combination of inward gravitational acceleration +with outward centrifugal acceleration, as experienced by an observer +in the Earth's rotating frame of reference. +The resulting value increases toward the Earth's poles and decreases +toward the equator, consistent with changes of the weight measured +by a spring scale of a fixed mass moved to different latitudes and heights +on the Earth. + +| Param | Type | Description | +| --- | --- | --- | +| latitude | number | The latitude of the observer in degrees north or south of the equator. By formula symmetry, positive latitudes give the same answer as negative latitudes, so the sign does not matter. | +| height | number | The height above the sea level geoid in meters. No range checking is done; however, accuracy is only valid in the range 0 to 100000 meters. | + + +* * * + + + +## ObserverState(date, observer, ofdate) ⇒ [StateVector](#StateVector) +**Kind**: global function +**Brief**: Calculates geocentric equatorial position and velocity of an observer on the surface of the Earth. + +This function calculates position and velocity vectors of an observer +on or near the surface of the Earth, expressed in equatorial +coordinates. It takes into account the rotation of the Earth at the given +time, along with the given latitude, longitude, and elevation of the observer. + +The caller may pass `ofdate` as `true` to return coordinates relative to the Earth's +equator at the specified time, or `false` to use the J2000 equator. + +The returned position vector has components expressed in astronomical units (AU). +To convert to kilometers, multiply the `x`, `y`, and `z` values by +the constant value [KM_PER_AU](#KM_PER_AU). +The returned velocity vector has components expressed in AU/day. + +| Param | Type | Description | +| --- | --- | --- | +| date | [FlexibleDateTime](#FlexibleDateTime) | The date and time for which to calculate the observer's position and velocity vectors. | +| observer | [Observer](#Observer) | The geographic location of a point on or near the surface of the Earth. | +| ofdate | boolean | Selects the date of the Earth's equator in which to express the equatorial coordinates. The caller may pass `false` to use the orientation of the Earth's equator at noon UTC on January 1, 2000, in which case this function corrects for precession and nutation of the Earth as it was at the moment specified by the `time` parameter. Or the caller may pass `true` to use the Earth's equator at `time` as the orientation. | + + +* * * + + + +## ObserverVector(date, observer, ofdate) ⇒ [Vector](#Vector) +**Kind**: global function +**Returns**: [Vector](#Vector) - An equatorial vector from the center of the Earth to the specified location + on (or near) the Earth's surface. +**Brief**: Calculates geocentric equatorial coordinates of an observer on the surface of the Earth. + +This function calculates a vector from the center of the Earth to +a point on or near the surface of the Earth, expressed in equatorial +coordinates. It takes into account the rotation of the Earth at the given +time, along with the given latitude, longitude, and elevation of the observer. + +The caller may pass `ofdate` as `true` to return coordinates relative to the Earth's +equator at the specified time, or `false` to use the J2000 equator. + +The returned vector has components expressed in astronomical units (AU). +To convert to kilometers, multiply the `x`, `y`, and `z` values by +the constant value [KM_PER_AU](#KM_PER_AU). + +The inverse of this function is also available: [VectorObserver](#VectorObserver). + +| Param | Type | Description | +| --- | --- | --- | +| date | [FlexibleDateTime](#FlexibleDateTime) | The date and time for which to calculate the observer's position vector. | +| observer | [Observer](#Observer) | The geographic location of a point on or near the surface of the Earth. | +| ofdate | boolean | Selects the date of the Earth's equator in which to express the equatorial coordinates. The caller may pass `false` to use the orientation of the Earth's equator at noon UTC on January 1, 2000, in which case this function corrects for precession and nutation of the Earth as it was at the moment specified by the `time` parameter. Or the caller may pass `true` to use the Earth's equator at `time` as the orientation. | + + +* * * + + + +## PairLongitude(body1, body2, date) ⇒ number +**Kind**: global function +**Returns**: number - An angle in the range [0, 360), expressed in degrees. +**Brief**: Returns one body's ecliptic longitude with respect to another, as seen from the Earth. + +This function determines where one body appears around the ecliptic plane +(the plane of the Earth's orbit around the Sun) as seen from the Earth, +relative to the another body's apparent position. +The function returns an angle in the half-open range [0, 360) degrees. +The value is the ecliptic longitude of `body1` relative to the ecliptic +longitude of `body2`. + +The angle is 0 when the two bodies are at the same ecliptic longitude +as seen from the Earth. The angle increases in the prograde direction +(the direction that the planets orbit the Sun and the Moon orbits the Earth). + +When the angle is 180 degrees, it means the two bodies appear on opposite sides +of the sky for an Earthly observer. + +Neither `body1` nor `body2` is allowed to be `Body.Earth`. +If this happens, the function throws an exception. + +| Param | Type | Description | +| --- | --- | --- | +| body1 | [Body](#Body) | The first body, whose longitude is to be found relative to the second body. | +| body2 | [Body](#Body) | The second body, relative to which the longitude of the first body is to be found. | +| date | [FlexibleDateTime](#FlexibleDateTime) | The date and time of the observation. | + + +* * * + + + +## Pivot(rotation, axis, angle) ⇒ [RotationMatrix](#RotationMatrix) +**Kind**: global function +**Returns**: [RotationMatrix](#RotationMatrix) - A pivoted matrix object. +**Brief**: Re-orients a rotation matrix by pivoting it by an angle around one of its axes. + +Given a rotation matrix, a selected coordinate axis, and an angle in degrees, +this function pivots the rotation matrix by that angle around that coordinate axis. + +For example, if you have rotation matrix that converts ecliptic coordinates (ECL) +to horizontal coordinates (HOR), but you really want to convert ECL to the orientation +of a telescope camera pointed at a given body, you can use `Astronomy_Pivot` twice: +(1) pivot around the zenith axis by the body's azimuth, then (2) pivot around the +western axis by the body's altitude angle. The resulting rotation matrix will then +reorient ECL coordinates to the orientation of your telescope camera. + +| Param | Type | Description | +| --- | --- | --- | +| rotation | [RotationMatrix](#RotationMatrix) | The input rotation matrix. | +| axis | number | An integer that selects which coordinate axis to rotate around: 0 = x, 1 = y, 2 = z. Any other value will cause an exception. | +| angle | number | An angle in degrees indicating the amount of rotation around the specified axis. Positive angles indicate rotation counterclockwise as seen from the positive direction along that axis, looking towards the origin point of the orientation system. Any finite number of degrees is allowed, but best precision will result from keeping `angle` in the range [-360, +360]. | + + +* * * + + + +## PlanetOrbitalPeriod(body) ⇒ number +**Kind**: global function +**Returns**: number - The approximate average time it takes for the planet to travel once around the Sun. + The value is expressed in days. +**Brief**: Returns the mean orbital period of a planet in days. + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | One of: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, or Pluto. | + + +* * * + + + +## Refraction(refraction, altitude) ⇒ number +**Kind**: global function +**Returns**: number - The angular adjustment in degrees to be added to the altitude angle to correct for atmospheric lensing. +**Brief**: Calculates the amount of "lift" to an altitude angle caused by atmospheric refraction. + +Given an altitude angle and a refraction option, calculates +the amount of "lift" caused by atmospheric refraction. +This is the number of degrees higher in the sky an object appears +due to the lensing of the Earth's atmosphere. +This function works best near sea level. +To correct for higher elevations, call [Atmosphere](#Atmosphere) for that +elevation and multiply the refraction angle by the resulting relative density. + +| Param | Type | Description | +| --- | --- | --- | +| refraction | string | `"normal"`: correct altitude for atmospheric refraction (recommended). `"jplhor"`: for JPL Horizons compatibility testing only; not recommended for normal use. `null`: no atmospheric refraction correction is performed. | +| altitude | number | An altitude angle in a horizontal coordinate system. Must be a value between -90 and +90. | + + +* * * + + + +## RotateState(rotation, state) ⇒ [StateVector](#StateVector) +**Kind**: global function +**Returns**: [StateVector](#StateVector) - A state vector in the orientation specified by `rotation`. +**Brief**: Applies a rotation to a state vector, yielding a rotated vector. + +This function transforms a state vector in one orientation to a vector +in another orientation. + +| Param | Type | Description | +| --- | --- | --- | +| rotation | [RotationMatrix](#RotationMatrix) | A rotation matrix that specifies how the orientation of the state vector is to be changed. | +| state | [StateVector](#StateVector) | The state vector whose orientation is to be changed. Both the position and velocity components are transformed. | + + +* * * + + + +## RotateVector(rotation, vector) ⇒ [Vector](#Vector) +**Kind**: global function +**Returns**: [Vector](#Vector) - A vector in the orientation specified by `rotation`. +**Brief**: Applies a rotation to a vector, yielding a rotated vector. + +This function transforms a vector in one orientation to a vector +in another orientation. + +| Param | Type | Description | +| --- | --- | --- | +| rotation | [RotationMatrix](#RotationMatrix) | A rotation matrix that specifies how the orientation of the vector is to be changed. | +| vector | [Vector](#Vector) | The vector whose orientation is to be changed. | + + +* * * + + + +## RotationAxis(body, date) ⇒ [AxisInfo](#AxisInfo) +**Kind**: global function +**Brief**: Calculates information about a body's rotation axis at a given time. +Calculates the orientation of a body's rotation axis, along with +the rotation angle of its prime meridian, at a given moment in time. + +This function uses formulas standardized by the IAU Working Group +on Cartographics and Rotational Elements 2015 report, as described +in the following document: + +https://astropedia.astrogeology.usgs.gov/download/Docs/WGCCRE/WGCCRE2015reprint.pdf + +See [AxisInfo](#AxisInfo) for more detailed information. + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | One of the following values: `Body.Sun`, `Body.Moon`, `Body.Mercury`, `Body.Venus`, `Body.Earth`, `Body.Mars`, `Body.Jupiter`, `Body.Saturn`, `Body.Uranus`, `Body.Neptune`, `Body.Pluto`. | +| date | [FlexibleDateTime](#FlexibleDateTime) | The time at which to calculate the body's rotation axis. | + + +* * * + + + +## Rotation\_ECL\_EQD(time) ⇒ [RotationMatrix](#RotationMatrix) +**Kind**: global function +**Returns**: [RotationMatrix](#RotationMatrix) - A rotation matrix that converts ECL to EQD. +**Brief**: Calculates a rotation matrix from J2000 mean ecliptic (ECL) to equatorial of-date (EQD). + +This is one of the family of functions that returns a rotation matrix +for converting from one orientation to another. +Source: ECL = ecliptic system, using equator at J2000 epoch. +Target: EQD = equatorial system, using equator of date. + +| Param | Type | Description | +| --- | --- | --- | +| time | [FlexibleDateTime](#FlexibleDateTime) | The date and time of the desired equator. | + + +* * * + + + +## Rotation\_ECL\_EQJ() ⇒ [RotationMatrix](#RotationMatrix) +**Kind**: global function +**Returns**: [RotationMatrix](#RotationMatrix) - A rotation matrix that converts ECL to EQJ. +**Brief**: Calculates a rotation matrix from J2000 mean ecliptic (ECL) to J2000 mean equator (EQJ). + +This is one of the family of functions that returns a rotation matrix +for converting from one orientation to another. +Source: ECL = ecliptic system, using equator at J2000 epoch. +Target: EQJ = equatorial system, using equator at J2000 epoch. + +* * * + + + +## Rotation\_ECL\_HOR(time, observer) ⇒ [RotationMatrix](#RotationMatrix) +**Kind**: global function +**Returns**: [RotationMatrix](#RotationMatrix) - A rotation matrix that converts ECL to HOR at `time` and for `observer`. + The components of the horizontal vector are: + x = north, y = west, z = zenith (straight up from the observer). + These components are chosen so that the "right-hand rule" works for the vector + and so that north represents the direction where azimuth = 0. +**Brief**: Calculates a rotation matrix from J2000 mean ecliptic (ECL) to horizontal (HOR). + +This is one of the family of functions that returns a rotation matrix +for converting from one orientation to another. +Source: ECL = ecliptic system, using equator at J2000 epoch. +Target: HOR = horizontal system. + +Use [HorizonFromVector](#HorizonFromVector) to convert the return value +to a traditional altitude/azimuth pair. + +| Param | Type | Description | +| --- | --- | --- | +| time | [FlexibleDateTime](#FlexibleDateTime) | The date and time of the desired horizontal orientation. | +| observer | [Observer](#Observer) | A location near the Earth's mean sea level that defines the observer's horizon. | + + +* * * + + + +## Rotation\_ECT\_EQD(time) ⇒ [RotationMatrix](#RotationMatrix) +**Kind**: global function +**Returns**: [RotationMatrix](#RotationMatrix) - A rotation matrix that converts ECT to EQD. +**Brief**: Calculates a rotation matrix from true ecliptic of date (ECT) to equator of date (EQD). + +This is one of the family of functions that returns a rotation matrix +for converting from one orientation to another. +Source: ECT = true ecliptic of date +Target: EQD = equator of date + +| Param | Type | Description | +| --- | --- | --- | +| time | [FlexibleDateTime](#FlexibleDateTime) | The date and time of the ecliptic/equator conversion. | + + +* * * + + + +## Rotation\_ECT\_EQJ(time) ⇒ [RotationMatrix](#RotationMatrix) +**Kind**: global function +**Returns**: [RotationMatrix](#RotationMatrix) - A rotation matrix that converts ECT to EQJ at `time`. +**Brief**: Calculates a rotation matrix from true ecliptic of date (ECT) to J2000 mean equator (EQJ). + +This is one of the family of functions that returns a rotation matrix +for converting from one orientation to another. +Source: ECT = ecliptic system, using true equinox of the specified date/time. +Target: EQJ = equatorial system, using equator at J2000 epoch. + +| Param | Type | Description | +| --- | --- | --- | +| time | [FlexibleDateTime](#FlexibleDateTime) | The date and time at which the Earth's equator defines the target orientation. | + + +* * * + + + +## Rotation\_EQD\_ECL(time) ⇒ [RotationMatrix](#RotationMatrix) +**Kind**: global function +**Returns**: [RotationMatrix](#RotationMatrix) - A rotation matrix that converts EQD to ECL. +**Brief**: Calculates a rotation matrix from equatorial of-date (EQD) to J2000 mean ecliptic (ECL). + +This is one of the family of functions that returns a rotation matrix +for converting from one orientation to another. +Source: EQD = equatorial system, using equator of date. +Target: ECL = ecliptic system, using equator at J2000 epoch. + +| Param | Type | Description | +| --- | --- | --- | +| time | [FlexibleDateTime](#FlexibleDateTime) | The date and time of the source equator. | + + +* * * + + + +## Rotation\_EQD\_ECT(time) ⇒ [RotationMatrix](#RotationMatrix) +**Kind**: global function +**Returns**: [RotationMatrix](#RotationMatrix) - A rotation matrix that converts EQD to ECT. +**Brief**: Calculates a rotation matrix from equator of date (EQD) to true ecliptic of date (ECT). + +This is one of the family of functions that returns a rotation matrix +for converting from one orientation to another. +Source: EQD = equator of date +Target: ECT = true ecliptic of date + +| Param | Type | Description | +| --- | --- | --- | +| time | [FlexibleDateTime](#FlexibleDateTime) | The date and time of the equator/ecliptic conversion. | + + +* * * + + + +## Rotation\_EQD\_EQJ(time) ⇒ [RotationMatrix](#RotationMatrix) +**Kind**: global function +**Returns**: [RotationMatrix](#RotationMatrix) - A rotation matrix that converts EQD at `time` to EQJ. +**Brief**: Calculates a rotation matrix from equatorial of-date (EQD) to J2000 mean equator (EQJ). + +This is one of the family of functions that returns a rotation matrix +for converting from one orientation to another. +Source: EQD = equatorial system, using equator of the specified date/time. +Target: EQJ = equatorial system, using equator at J2000 epoch. + +| Param | Type | Description | +| --- | --- | --- | +| time | [FlexibleDateTime](#FlexibleDateTime) | The date and time at which the Earth's equator defines the source orientation. | + + +* * * + + + +## Rotation\_EQD\_HOR(time, observer) ⇒ [RotationMatrix](#RotationMatrix) +**Kind**: global function +**Returns**: [RotationMatrix](#RotationMatrix) - A rotation matrix that converts EQD to HOR at `time` and for `observer`. + The components of the horizontal vector are: + x = north, y = west, z = zenith (straight up from the observer). + These components are chosen so that the "right-hand rule" works for the vector + and so that north represents the direction where azimuth = 0. +**Brief**: Calculates a rotation matrix from equatorial of-date (EQD) to horizontal (HOR). + +This is one of the family of functions that returns a rotation matrix +for converting from one orientation to another. +Source: EQD = equatorial system, using equator of the specified date/time. +Target: HOR = horizontal system. + +Use `HorizonFromVector` to convert the return value +to a traditional altitude/azimuth pair. + +| Param | Type | Description | +| --- | --- | --- | +| time | [FlexibleDateTime](#FlexibleDateTime) | The date and time at which the Earth's equator applies. | +| observer | [Observer](#Observer) | A location near the Earth's mean sea level that defines the observer's horizon. | + + +* * * + + + +## Rotation\_EQJ\_ECL() ⇒ [RotationMatrix](#RotationMatrix) +**Kind**: global function +**Returns**: [RotationMatrix](#RotationMatrix) - A rotation matrix that converts EQJ to ECL. +**Brief**: Calculates a rotation matrix from J2000 mean equator (EQJ) to J2000 mean ecliptic (ECL). + +This is one of the family of functions that returns a rotation matrix +for converting from one orientation to another. +Source: EQJ = equatorial system, using equator at J2000 epoch. +Target: ECL = ecliptic system, using equator at J2000 epoch. + +* * * + + + +## Rotation\_EQJ\_ECT(time) ⇒ [RotationMatrix](#RotationMatrix) +**Kind**: global function +**Returns**: [RotationMatrix](#RotationMatrix) - A rotation matrix that converts EQJ to ECT at `time`. +**Brief**: Calculates a rotation matrix from J2000 mean equator (EQJ) to true ecliptic of date (ECT). + +This is one of the family of functions that returns a rotation matrix +for converting from one orientation to another. +Source: EQJ = equatorial system, using equator at J2000 epoch. +Target: ECT = ecliptic system, using true equinox of the specified date/time. + +| Param | Type | Description | +| --- | --- | --- | +| time | [FlexibleDateTime](#FlexibleDateTime) | The date and time at which the Earth's equator defines the target orientation. | + + +* * * + + + +## Rotation\_EQJ\_EQD(time) ⇒ [RotationMatrix](#RotationMatrix) +**Kind**: global function +**Returns**: [RotationMatrix](#RotationMatrix) - A rotation matrix that converts EQJ to EQD at `time`. +**Brief**: Calculates a rotation matrix from J2000 mean equator (EQJ) to equatorial of-date (EQD). + +This is one of the family of functions that returns a rotation matrix +for converting from one orientation to another. +Source: EQJ = equatorial system, using equator at J2000 epoch. +Target: EQD = equatorial system, using equator of the specified date/time. + +| Param | Type | Description | +| --- | --- | --- | +| time | [FlexibleDateTime](#FlexibleDateTime) | The date and time at which the Earth's equator defines the target orientation. | + + +* * * + + + +## Rotation\_EQJ\_GAL() ⇒ [RotationMatrix](#RotationMatrix) +**Kind**: global function +**Returns**: [RotationMatrix](#RotationMatrix) - A rotation matrix that converts EQJ to GAL. +**Brief**: Calculates a rotation matrix from J2000 mean equator (EQJ) to galactic (GAL). + +This is one of the family of functions that returns a rotation matrix +for converting from one orientation to another. +Source: EQJ = equatorial system, using the equator at the J2000 epoch. +Target: GAL = galactic system (IAU 1958 definition). + +* * * + + + +## Rotation\_EQJ\_HOR(time, observer) ⇒ [RotationMatrix](#RotationMatrix) +**Kind**: global function +**Returns**: [RotationMatrix](#RotationMatrix) - A rotation matrix that converts EQJ to HOR at `time` and for `observer`. + The components of the horizontal vector are: + x = north, y = west, z = zenith (straight up from the observer). + These components are chosen so that the "right-hand rule" works for the vector + and so that north represents the direction where azimuth = 0. +**Brief**: Calculates a rotation matrix from J2000 mean equator (EQJ) to horizontal (HOR). + +This is one of the family of functions that returns a rotation matrix +for converting from one orientation to another. +Source: EQJ = equatorial system, using the equator at the J2000 epoch. +Target: HOR = horizontal system. + +Use [HorizonFromVector](#HorizonFromVector) to convert the return value +to a traditional altitude/azimuth pair. + +| Param | Type | Description | +| --- | --- | --- | +| time | [FlexibleDateTime](#FlexibleDateTime) | The date and time of the desired horizontal orientation. | +| observer | [Observer](#Observer) | A location near the Earth's mean sea level that defines the observer's horizon. | + + +* * * + + + +## Rotation\_GAL\_EQJ() ⇒ [RotationMatrix](#RotationMatrix) +**Kind**: global function +**Returns**: [RotationMatrix](#RotationMatrix) - A rotation matrix that converts GAL to EQJ. +**Brief**: Calculates a rotation matrix from galactic (GAL) to J2000 mean equator (EQJ). + +This is one of the family of functions that returns a rotation matrix +for converting from one orientation to another. +Source: GAL = galactic system (IAU 1958 definition). +Target: EQJ = equatorial system, using the equator at the J2000 epoch. + +* * * + + + +## Rotation\_HOR\_ECL(time, observer) ⇒ [RotationMatrix](#RotationMatrix) +**Kind**: global function +**Returns**: [RotationMatrix](#RotationMatrix) - A rotation matrix that converts HOR to ECL. +**Brief**: Calculates a rotation matrix from horizontal (HOR) to J2000 mean ecliptic (ECL). + +This is one of the family of functions that returns a rotation matrix +for converting from one orientation to another. +Source: HOR = horizontal system. +Target: ECL = ecliptic system, using equator at J2000 epoch. + +| Param | Type | Description | +| --- | --- | --- | +| time | [FlexibleDateTime](#FlexibleDateTime) | The date and time of the horizontal observation. | +| observer | [Observer](#Observer) | The location of the horizontal observer. | + + +* * * + + + +## Rotation\_HOR\_EQD(time, observer) ⇒ [RotationMatrix](#RotationMatrix) +**Kind**: global function +**Returns**: [RotationMatrix](#RotationMatrix) - A rotation matrix that converts HOR to EQD at `time` and for `observer`. +**Brief**: Calculates a rotation matrix from horizontal (HOR) to equatorial of-date (EQD). + +This is one of the family of functions that returns a rotation matrix +for converting from one orientation to another. +Source: HOR = horizontal system (x=North, y=West, z=Zenith). +Target: EQD = equatorial system, using equator of the specified date/time. + +| Param | Type | Description | +| --- | --- | --- | +| time | [FlexibleDateTime](#FlexibleDateTime) | The date and time at which the Earth's equator applies. | +| observer | [Observer](#Observer) | A location near the Earth's mean sea level that defines the observer's horizon. | + + +* * * + + + +## Rotation\_HOR\_EQJ(time, observer) ⇒ [RotationMatrix](#RotationMatrix) +**Kind**: global function +**Returns**: [RotationMatrix](#RotationMatrix) - A rotation matrix that converts HOR to EQJ at `time` and for `observer`. +**Brief**: Calculates a rotation matrix from horizontal (HOR) to J2000 equatorial (EQJ). + +This is one of the family of functions that returns a rotation matrix +for converting from one orientation to another. +Source: HOR = horizontal system (x=North, y=West, z=Zenith). +Target: EQJ = equatorial system, using equator at the J2000 epoch. + +| Param | Type | Description | +| --- | --- | --- | +| time | [FlexibleDateTime](#FlexibleDateTime) | The date and time of the observation. | +| observer | [Observer](#Observer) | A location near the Earth's mean sea level that defines the observer's horizon. | + + +* * * + + + +## Search(func, t1, t2, options) ⇒ [AstroTime](#AstroTime) \| null +**Kind**: global function +**Returns**: [AstroTime](#AstroTime) \| null - If the search is successful, returns the date and time of the solution. + If the search fails, returns `null`. +**Brief**: Finds the time when a function ascends through zero. + +Search for next time t (such that t is between `t1` and `t2`) +that `func(t)` crosses from a negative value to a non-negative value. +The given function must have "smooth" behavior over the entire inclusive range [`t1`, `t2`], +meaning that it behaves like a continuous differentiable function. +It is not required that `t1` < `t2`; `t1` > `t2` +allows searching backward in time. +Note: `t1` and `t2` must be chosen such that there is no possibility +of more than one zero-crossing (ascending or descending), or it is possible +that the "wrong" event will be found (i.e. not the first event after t1) +or even that the function will return `null`, indicating that no event was found. + +| Param | Type | Description | +| --- | --- | --- | +| func | function | The function to find an ascending zero crossing for. The function must accept a single parameter of type [AstroTime](#AstroTime) and return a numeric value: function([AstroTime](#AstroTime)) => `number` | +| t1 | [AstroTime](#AstroTime) | The lower time bound of a search window. | +| t2 | [AstroTime](#AstroTime) | The upper time bound of a search window. | +| options | [SearchOptions](#SearchOptions) \| undefined | Options that can tune the behavior of the search. Most callers can omit this argument. | + + +* * * + + + +## SearchAltitude(body, observer, direction, dateStart, limitDays, altitude) ⇒ [AstroTime](#AstroTime) \| null +**Kind**: global function +**Returns**: [AstroTime](#AstroTime) \| null - The date and time of the altitude event, or null if no such event + occurs within the specified time window. +**Brief**: Finds the next time the center of a body passes through a given altitude. + +Finds when the center of the given body ascends or descends through a given +altitude angle, as seen by an observer at the specified location on the Earth. +By using the appropriate combination of `direction` and `altitude` parameters, +this function can be used to find when civil, nautical, or astronomical twilight +begins (dawn) or ends (dusk). + +Civil dawn begins before sunrise when the Sun ascends through 6 degrees below +the horizon. To find civil dawn, pass +1 for `direction` and -6 for `altitude`. + +Civil dusk ends after sunset when the Sun descends through 6 degrees below the horizon. +To find civil dusk, pass -1 for `direction` and -6 for `altitude`. + +Nautical twilight is similar to civil twilight, only the `altitude` value should be -12 degrees. + +Astronomical twilight uses -18 degrees as the `altitude` value. + +By convention for twilight time calculations, the altitude is not corrected for +atmospheric refraction. This is because the target altitudes are below the horizon, +and refraction is not directly observable. + +`SearchAltitude` is not intended to find rise/set times of a body for two reasons: +(1) Rise/set times of the Sun or Moon are defined by their topmost visible portion, not their centers. +(2) Rise/set times are affected significantly by atmospheric refraction. +Therefore, it is better to use [SearchRiseSet](#SearchRiseSet) to find rise/set times, which +corrects for both of these considerations. + +`SearchAltitude` will not work reliably for altitudes at or near the body's +maximum or minimum altitudes. To find the time a body reaches minimum or maximum altitude +angles, use [SearchHourAngle](#SearchHourAngle). + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | The Sun, Moon, any planet other than the Earth, or a user-defined star that was created by a call to [DefineStar](#DefineStar). | +| observer | [Observer](#Observer) | Specifies the geographic coordinates and elevation above sea level of the observer. | +| direction | number | Either +1 to find when the body ascends through the altitude, or -1 for when the body descends through the altitude. Any other value will cause an exception to be thrown. | +| dateStart | [FlexibleDateTime](#FlexibleDateTime) | The date and time after which the specified altitude event is to be found. | +| limitDays | number | Limits how many days to search for the body reaching the altitude angle, and defines the direction in time to search. When `limitDays` is positive, the search is performed into the future, after `dateStart`. When negative, the search is performed into the past, before `dateStart`. To limit the search to the same day, you can use a value of 1 day. In cases where you want to find the altitude event no matter how far in the future (for example, for an observer near the south pole), you can pass in a larger value like 365. | +| altitude | number | The desired altitude angle of the body's center above (positive) or below (negative) the observer's local horizon, expressed in degrees. Must be in the range [-90, +90]. | + + +* * * + + + +## SearchGlobalSolarEclipse(startTime) ⇒ [GlobalSolarEclipseInfo](#GlobalSolarEclipseInfo) +**Kind**: global function +**Brief**: Searches for a solar eclipse visible anywhere on the Earth's surface. + +This function finds the first solar eclipse that occurs after `startTime`. +A solar eclipse may be partial, annular, or total. +See [GlobalSolarEclipseInfo](#GlobalSolarEclipseInfo) for more information. +To find a series of solar eclipses, call this function once, +then keep calling [NextGlobalSolarEclipse](#NextGlobalSolarEclipse) as many times as desired, +passing in the `peak` value returned from the previous call. + +| Param | Type | Description | +| --- | --- | --- | +| startTime | [FlexibleDateTime](#FlexibleDateTime) | The date and time for starting the search for a solar eclipse. | + + +* * * + + + +## SearchHourAngle(body, observer, hourAngle, dateStart, direction) ⇒ [HourAngleEvent](#HourAngleEvent) +**Kind**: global function +**Brief**: Searches for the time when the center of a body reaches a specified hour angle as seen by an observer on the Earth. + +The *hour angle* of a celestial body indicates its position in the sky with respect +to the Earth's rotation. The hour angle depends on the location of the observer on the Earth. +The hour angle is 0 when the body's center reaches its highest angle above the horizon in a given day. +The hour angle increases by 1 unit for every sidereal hour that passes after that point, up +to 24 sidereal hours when it reaches the highest point again. So the hour angle indicates +the number of hours that have passed since the most recent time that the body has culminated, +or reached its highest point. + +This function searches for the next or previous time a celestial body reaches the given hour angle +relative to the date and time specified by `dateStart`. +To find when a body culminates, pass 0 for `hourAngle`. +To find when a body reaches its lowest point in the sky, pass 12 for `hourAngle`. + +Note that, especially close to the Earth's poles, a body as seen on a given day +may always be above the horizon or always below the horizon, so the caller cannot +assume that a culminating object is visible nor that an object is below the horizon +at its minimum altitude. + +The function returns the date and time, along with the horizontal coordinates +of the body at that time, as seen by the given observer. + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | The Sun, Moon, any planet other than the Earth, or a user-defined star that was created by a call to [DefineStar](#DefineStar). | +| observer | [Observer](#Observer) | Specifies the geographic coordinates and elevation above sea level of the observer. | +| hourAngle | number | The hour angle expressed in sidereal hours for which the caller seeks to find the body attain. The value must be in the range [0, 24). The hour angle represents the number of sidereal hours that have elapsed since the most recent time the body crossed the observer's local meridian. This specifying `hourAngle` = 0 finds the moment in time the body reaches the highest angular altitude in a given sidereal day. | +| dateStart | [FlexibleDateTime](#FlexibleDateTime) | The date and time after which the desired hour angle crossing event is to be found. | +| direction | number | The direction in time to perform the search: a positive value searches forward in time, a negative value searches backward in time. The function throws an exception if `direction` is zero. | + + +* * * + + + +## SearchLocalSolarEclipse(startTime, observer) ⇒ [LocalSolarEclipseInfo](#LocalSolarEclipseInfo) +**Kind**: global function +**Brief**: Searches for a solar eclipse visible at a specific location on the Earth's surface. + +This function finds the first solar eclipse that occurs after `startTime`. +A solar eclipse may be partial, annular, or total. +See [LocalSolarEclipseInfo](#LocalSolarEclipseInfo) for more information. + +To find a series of solar eclipses, call this function once, +then keep calling [NextLocalSolarEclipse](#NextLocalSolarEclipse) as many times as desired, +passing in the `peak` value returned from the previous call. + +IMPORTANT: An eclipse reported by this function might be partly or +completely invisible to the observer due to the time of day. +See [LocalSolarEclipseInfo](#LocalSolarEclipseInfo) for more information about this topic. + +| Param | Type | Description | +| --- | --- | --- | +| startTime | [FlexibleDateTime](#FlexibleDateTime) | The date and time for starting the search for a solar eclipse. | +| observer | [Observer](#Observer) | The geographic location of the observer. | + + +* * * + + + +## SearchLunarApsis(startDate) ⇒ [Apsis](#Apsis) +**Kind**: global function +**Brief**: Finds the next perigee or apogee of the Moon. + +Finds the next perigee (closest approach) or apogee (farthest remove) of the Moon +that occurs after the specified date and time. + +| Param | Type | Description | +| --- | --- | --- | +| startDate | [FlexibleDateTime](#FlexibleDateTime) | The date and time after which to find the next perigee or apogee. | + + +* * * + + + +## SearchLunarEclipse(date) ⇒ [LunarEclipseInfo](#LunarEclipseInfo) +**Kind**: global function +**Brief**: Searches for a lunar eclipse. + +This function finds the first lunar eclipse that occurs after `startTime`. +A lunar eclipse may be penumbral, partial, or total. +See [LunarEclipseInfo](#LunarEclipseInfo) for more information. +To find a series of lunar eclipses, call this function once, +then keep calling [NextLunarEclipse](#NextLunarEclipse) as many times as desired, +passing in the `peak` value returned from the previous call. + +| Param | Type | Description | +| --- | --- | --- | +| date | [FlexibleDateTime](#FlexibleDateTime) | The date and time for starting the search for a lunar eclipse. | + + +* * * + + + +## SearchMaxElongation(body, startDate) ⇒ [ElongationEvent](#ElongationEvent) +**Kind**: global function +**Brief**: Finds the next time Mercury or Venus reaches maximum elongation. + +Searches for the next maximum elongation event for Mercury or Venus +that occurs after the given start date. Calling with other values +of `body` will result in an exception. +Maximum elongation occurs when the body has the greatest +angular separation from the Sun, as seen from the Earth. +Returns an `ElongationEvent` object containing the date and time of the next +maximum elongation, the elongation in degrees, and whether +the body is visible in the morning or evening. + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | Either `Body.Mercury` or `Body.Venus`. | +| startDate | [FlexibleDateTime](#FlexibleDateTime) | The date and time after which to search for the next maximum elongation event. | + + +* * * + + + +## SearchMoonNode(startTime) ⇒ [NodeEventInfo](#NodeEventInfo) +**Kind**: global function +**Brief**: Searches for a time when the Moon's center crosses through the ecliptic plane. + +Searches for the first ascending or descending node of the Moon after `startTime`. +An ascending node is when the Moon's center passes through the ecliptic plane +(the plane of the Earth's orbit around the Sun) from south to north. +A descending node is when the Moon's center passes through the ecliptic plane +from north to south. Nodes indicate possible times of solar or lunar eclipses, +if the Moon also happens to be in the correct phase (new or full, respectively). +Call `SearchMoonNode` to find the first of a series of nodes. +Then call [NextMoonNode](#NextMoonNode) to find as many more consecutive nodes as desired. + +| Param | Type | Description | +| --- | --- | --- | +| startTime | [FlexibleDateTime](#FlexibleDateTime) | The date and time for starting the search for an ascending or descending node of the Moon. | + + +* * * + + + +## SearchMoonPhase(targetLon, dateStart, limitDays) ⇒ [AstroTime](#AstroTime) \| null +**Kind**: global function +**Returns**: [AstroTime](#AstroTime) \| null - If successful, returns the date and time the moon reaches the phase specified by `targetlon`. + This function will return `null` if the phase does not occur within `limitDays` of `startTime`; + that is, if the search window is too small. +**Brief**: Searches for the date and time that the Moon reaches a specified phase. + +Lunar phases are defined in terms of geocentric ecliptic longitudes +with respect to the Sun. When the Moon and the Sun have the same ecliptic +longitude, that is defined as a new moon. When the two ecliptic longitudes +are 180 degrees apart, that is defined as a full moon. +To enumerate quarter lunar phases, it is simpler to call +[SearchMoonQuarter](#SearchMoonQuarter) once, followed by repeatedly calling +[NextMoonQuarter](#NextMoonQuarter). `SearchMoonPhase` is only +necessary for finding other lunar phases than the usual quarter phases. + +| Param | Type | Description | +| --- | --- | --- | +| targetLon | number | The difference in geocentric ecliptic longitude between the Sun and Moon that specifies the lunar phase being sought. This can be any value in the range [0, 360). Here are some helpful examples: 0 = new moon, 90 = first quarter, 180 = full moon, 270 = third quarter. | +| dateStart | [FlexibleDateTime](#FlexibleDateTime) | The beginning of the window of time in which to search. | +| limitDays | number | The floating point number of days away from `dateStart` that limits the window of time in which to search. If the value is negative, the search is performed into the past from `startTime`. Otherwise, the search is performed into the future from `startTime`. | + + +* * * + + + +## SearchMoonQuarter(dateStart) ⇒ [MoonQuarter](#MoonQuarter) +**Kind**: global function +**Brief**: Finds the first quarter lunar phase after the specified date and time. + +The quarter lunar phases are: new moon, first quarter, full moon, and third quarter. +To enumerate quarter lunar phases, call `SearchMoonQuarter` once, +then pass its return value to [NextMoonQuarter](#NextMoonQuarter) to find the next +`MoonQuarter`. Keep calling `NextMoonQuarter` in a loop, +passing the previous return value as the argument to the next call. + +| Param | Type | Description | +| --- | --- | --- | +| dateStart | [FlexibleDateTime](#FlexibleDateTime) | The date and time after which to find the first quarter lunar phase. | + + +* * * + + + +## SearchPeakMagnitude(body, startDate) ⇒ [IlluminationInfo](#IlluminationInfo) +**Kind**: global function +**Brief**: Searches for the date and time Venus will next appear brightest as seen from the Earth. + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | Currently only `Body.Venus` is supported. Mercury's peak magnitude occurs at superior conjunction, when it is impossible to see from Earth, so peak magnitude events have little practical value for that planet. The Moon reaches peak magnitude very close to full moon, which can be found using [SearchMoonQuarter](#SearchMoonQuarter) or [SearchMoonPhase](#SearchMoonPhase). The other planets reach peak magnitude very close to opposition, which can be found using [SearchRelativeLongitude](#SearchRelativeLongitude). | +| startDate | [FlexibleDateTime](#FlexibleDateTime) | The date and time after which to find the next peak magnitude event. | + + +* * * + + + +## SearchPlanetApsis(body, startTime) ⇒ [Apsis](#Apsis) +**Kind**: global function +**Returns**: [Apsis](#Apsis) - The next perihelion or aphelion that occurs after `startTime`. +**Brief**: Finds the next perihelion or aphelion of a planet. + +Finds the date and time of a planet's perihelion (closest approach to the Sun) +or aphelion (farthest distance from the Sun) after a given time. + +Given a date and time to start the search in `startTime`, this function finds the +next date and time that the center of the specified planet reaches the closest or farthest point +in its orbit with respect to the center of the Sun, whichever comes first +after `startTime`. + +The closest point is called *perihelion* and the farthest point is called *aphelion*. +The word *apsis* refers to either event. + +To iterate through consecutive alternating perihelion and aphelion events, +call `SearchPlanetApsis` once, then use the return value to call +[NextPlanetApsis](#NextPlanetApsis). After that, keep feeding the previous return value +from `NextPlanetApsis` into another call of `NextPlanetApsis` +as many times as desired. + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | The planet for which to find the next perihelion/aphelion event. Not allowed to be `Body.Sun` or `Body.Moon`. | +| startTime | [FlexibleDateTime](#FlexibleDateTime) | The date and time at which to start searching for the next perihelion or aphelion. | + + +* * * + + + +## SearchRelativeLongitude(body, targetRelLon, startDate) ⇒ [AstroTime](#AstroTime) +**Kind**: global function +**Returns**: [AstroTime](#AstroTime) - The time when the Earth and the body next reach the specified relative longitudes. +**Brief**: Searches for when the Earth and a given body reach a relative ecliptic longitude separation. + +Searches for the date and time the relative ecliptic longitudes of +the specified body and the Earth, as seen from the Sun, reach a certain +difference. This function is useful for finding conjunctions and oppositions +of the planets. For the opposition of a superior planet (Mars, Jupiter, ..., Pluto), +or the inferior conjunction of an inferior planet (Mercury, Venus), +call with `targetRelLon` = 0. The 0 value indicates that both +planets are on the same ecliptic longitude line, ignoring the other planet's +distance above or below the plane of the Earth's orbit. +For superior conjunctions, call with `targetRelLon` = 180. +This means the Earth and the other planet are on opposite sides of the Sun. + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | Any planet other than the Earth. | +| targetRelLon | number | The desired angular difference in degrees between the ecliptic longitudes of `body` and the Earth. Must be in the range (-180, +180]. | +| startDate | [FlexibleDateTime](#FlexibleDateTime) | The date and time after which to find the next occurrence of the body and the Earth reaching the desired relative longitude. | + + +* * * + + + +## SearchRiseSet(body, observer, direction, dateStart, limitDays, metersAboveGround) ⇒ [AstroTime](#AstroTime) \| null +**Kind**: global function +**Returns**: [AstroTime](#AstroTime) \| null - The date and time of the rise or set event, or null if no such event + occurs within the specified time window. +**Brief**: Searches for the next time a celestial body rises or sets as seen by an observer on the Earth. + +This function finds the next rise or set time of the Sun, Moon, or planet other than the Earth. +Rise time is when the body first starts to be visible above the horizon. +For example, sunrise is the moment that the top of the Sun first appears to peek above the horizon. +Set time is the moment when the body appears to vanish below the horizon. +Therefore, this function adjusts for the apparent angular radius of the observed body +(significant only for the Sun and Moon). + +This function corrects for a typical value of atmospheric refraction, which causes celestial +bodies to appear higher above the horizon than they would if the Earth had no atmosphere. +Astronomy Engine uses a correction of 34 arcminutes. Real-world refraction varies based +on air temperature, pressure, and humidity; such weather-based conditions are outside +the scope of Astronomy Engine. + +Note that rise or set may not occur in every 24 hour period. +For example, near the Earth's poles, there are long periods of time where +the Sun stays below the horizon, never rising. +Also, it is possible for the Moon to rise just before midnight but not set during the subsequent 24-hour day. +This is because the Moon sets nearly an hour later each day due to orbiting the Earth a +significant amount during each rotation of the Earth. +Therefore callers must not assume that the function will always succeed. + +| Param | Type | Default | Description | +| --- | --- | --- | --- | +| body | [Body](#Body) | | The Sun, Moon, any planet other than the Earth, or a user-defined star that was created by a call to [DefineStar](#DefineStar). | +| observer | [Observer](#Observer) | | Specifies the geographic coordinates and elevation above sea level of the observer. | +| direction | number | | Either +1 to find rise time or -1 to find set time. Any other value will cause an exception to be thrown. | +| dateStart | [FlexibleDateTime](#FlexibleDateTime) | | The date and time after which the specified rise or set time is to be found. | +| limitDays | number | | Limits how many days to search for a rise or set time, and defines the direction in time to search. When `limitDays` is positive, the search is performed into the future, after `dateStart`. When negative, the search is performed into the past, before `dateStart`. To limit a rise or set time to the same day, you can use a value of 1 day. In cases where you want to find the next rise or set time no matter how far in the future (for example, for an observer near the south pole), you can pass in a larger value like 365. | +| metersAboveGround | number | 0 | Defaults to 0.0 if omitted. Usually the observer is located at ground level. Then this parameter should be zero. But if the observer is significantly higher than ground level, for example in an airplane, this parameter should be a positive number indicating how far above the ground the observer is. An exception occurs if `metersAboveGround` is negative. | + + +* * * + + + +## SearchSunLongitude(targetLon, dateStart, limitDays) ⇒ [AstroTime](#AstroTime) \| null +**Kind**: global function +**Returns**: [AstroTime](#AstroTime) \| null - The date and time when the Sun reaches the apparent ecliptic longitude `targetLon` + within the range of times specified by `dateStart` and `limitDays`. + If the Sun does not reach the target longitude within the specified time range, or the + time range is excessively wide, the return value is `null`. + To avoid a `null` return value, the caller must pick a time window around + the event that is within a few days but not so small that the event might fall outside the window. +**Brief**: Searches for when the Sun reaches a given ecliptic longitude. + +Searches for the moment in time when the center of the Sun reaches a given apparent +ecliptic longitude, as seen from the center of the Earth, within a given range of dates. +This function can be used to determine equinoxes and solstices. +However, it is usually more convenient and efficient to call [Seasons](#Seasons) +to calculate equinoxes and solstices for a given calendar year. +`SearchSunLongitude` is more general in that it allows searching for arbitrary longitude values. + +| Param | Type | Description | +| --- | --- | --- | +| targetLon | number | The desired ecliptic longitude of date in degrees. This may be any value in the range [0, 360), although certain values have conventional meanings: When `targetLon` is 0, finds the March equinox, which is the moment spring begins in the northern hemisphere and the beginning of autumn in the southern hemisphere. When `targetLon` is 180, finds the September equinox, which is the moment autumn begins in the northern hemisphere and spring begins in the southern hemisphere. When `targetLon` is 90, finds the northern solstice, which is the moment summer begins in the northern hemisphere and winter begins in the southern hemisphere. When `targetLon` is 270, finds the southern solstice, which is the moment winter begins in the northern hemisphere and summer begins in the southern hemisphere. | +| dateStart | [FlexibleDateTime](#FlexibleDateTime) | A date and time known to be earlier than the desired longitude event. | +| limitDays | number | A floating point number of days, which when added to `dateStart`, yields a date and time known to be after the desired longitude event. | + + +* * * + + + +## SearchTransit(body, startTime) ⇒ [TransitInfo](#TransitInfo) +**Kind**: global function +**Brief**: Searches for the first transit of Mercury or Venus after a given date. + +Finds the first transit of Mercury or Venus after a specified date. +A transit is when an inferior planet passes between the Sun and the Earth +so that the silhouette of the planet is visible against the Sun in the background. +To continue the search, pass the `finish` time in the returned structure to +[NextTransit](#NextTransit). + +| Param | Type | Description | +| --- | --- | --- | +| body | [Body](#Body) | The planet whose transit is to be found. Must be `Body.Mercury` or `Body.Venus`. | +| startTime | [FlexibleDateTime](#FlexibleDateTime) | The date and time for starting the search for a transit. | + + +* * * + + + +## Seasons(year) ⇒ [SeasonInfo](#SeasonInfo) +**Kind**: global function +**Brief**: Finds the equinoxes and solstices for a given calendar year. + +| Param | Type | Description | +| --- | --- | --- | +| year | number \| [AstroTime](#AstroTime) | The integer value or `AstroTime` object that specifies the UTC calendar year for which to find equinoxes and solstices. | + + +* * * + + + +## SiderealTime(date) ⇒ number +**Kind**: global function +**Brief**: Calculates Greenwich Apparent Sidereal Time (GAST). + +Given a date and time, this function calculates the rotation of the +Earth, represented by the equatorial angle of the Greenwich prime meridian +with respect to distant stars (not the Sun, which moves relative to background +stars by almost one degree per day). +This angle is called Greenwich Apparent Sidereal Time (GAST). +GAST is measured in sidereal hours in the half-open range [0, 24). +When GAST = 0, it means the prime meridian is aligned with the of-date equinox, +corrected at that time for precession and nutation of the Earth's axis. +In this context, the "equinox" is the direction in space where the Earth's +orbital plane (the ecliptic) intersects with the plane of the Earth's equator, +at the location on the Earth's orbit of the (seasonal) March equinox. +As the Earth rotates, GAST increases from 0 up to 24 sidereal hours, +then starts over at 0. +To convert to degrees, multiply the return value by 15. + +| Param | Type | Description | +| --- | --- | --- | +| date | [FlexibleDateTime](#FlexibleDateTime) | The date and time for which to find GAST. | + + +* * * + + + +## SphereFromVector(vector) ⇒ [Spherical](#Spherical) +**Kind**: global function +**Returns**: [Spherical](#Spherical) - Spherical coordinates that are equivalent to the given vector. +**Brief**: Converts Cartesian coordinates to spherical coordinates. + +Given a Cartesian vector, returns latitude, longitude, and distance. + +| Param | Type | Description | +| --- | --- | --- | +| vector | [Vector](#Vector) | Cartesian vector to be converted to spherical coordinates. | + + +* * * + + + +## SunPosition(date) ⇒ [EclipticCoordinates](#EclipticCoordinates) +**Kind**: global function +**Brief**: Returns apparent geocentric true ecliptic coordinates of date for the Sun. + +This function is used for calculating the times of equinoxes and solstices. + +Geocentric means coordinates as the Sun would appear to a hypothetical observer +at the center of the Earth. +Ecliptic coordinates of date are measured along the plane of the Earth's mean +orbit around the Sun, using the +equinox +of the Earth as adjusted for precession and nutation of the Earth's +axis of rotation on the given date. + +| Param | Type | Description | +| --- | --- | --- | +| date | [FlexibleDateTime](#FlexibleDateTime) | The date and time at which to calculate the Sun's apparent location as seen from the center of the Earth. | + + +* * * + + + +## VectorFromHorizon(sphere, time, refraction) ⇒ [Vector](#Vector) +**Kind**: global function +**Returns**: [Vector](#Vector) - A vector in the horizontal system: `x` = north, `y` = west, and `z` = zenith (up). +**Brief**: Given apparent angular horizontal coordinates in `sphere`, calculate horizontal vector. + +| Param | Type | Description | +| --- | --- | --- | +| sphere | [Spherical](#Spherical) | A structure that contains apparent horizontal coordinates: `lat` holds the refracted altitude angle, `lon` holds the azimuth in degrees clockwise from north, and `dist` holds the distance from the observer to the object in AU. | +| time | [FlexibleDateTime](#FlexibleDateTime) | The date and time of the observation. This is needed because the returned vector object requires a valid time value when passed to certain other functions. | +| refraction | string | `"normal"`: correct altitude for atmospheric refraction (recommended). `"jplhor"`: for JPL Horizons compatibility testing only; not recommended for normal use. `null`: no atmospheric refraction correction is performed. | + + +* * * + + + +## VectorFromSphere(sphere, time) ⇒ [Vector](#Vector) +**Kind**: global function +**Returns**: [Vector](#Vector) - The vector form of the supplied spherical coordinates. +**Brief**: Converts spherical coordinates to Cartesian coordinates. + +Given spherical coordinates and a time at which they are valid, +returns a vector of Cartesian coordinates. The returned value +includes the time, as required by `AstroTime`. + +| Param | Type | Description | +| --- | --- | --- | +| sphere | [Spherical](#Spherical) | Spherical coordinates to be converted. | +| time | [FlexibleDateTime](#FlexibleDateTime) | The time that should be included in the returned vector. | + + +* * * + + + +## VectorObserver(vector, ofdate) ⇒ [Observer](#Observer) +**Kind**: global function +**Returns**: [Observer](#Observer) - The geographic latitude, longitude, and elevation above sea level + that corresponds to the given equatorial vector. +**Brief**: Calculates the geographic location corresponding to an equatorial vector. + +This is the inverse function of [ObserverVector](#ObserverVector). +Given a geocentric equatorial vector, it returns the geographic +latitude, longitude, and elevation for that vector. + +| Param | Type | Description | +| --- | --- | --- | +| vector | [Vector](#Vector) | The geocentric equatorial position vector for which to find geographic coordinates. The components are expressed in Astronomical Units (AU). You can calculate AU by dividing kilometers by the constant [KM_PER_AU](#KM_PER_AU). The time `vector.t` determines the Earth's rotation. | +| ofdate | boolean | Selects the date of the Earth's equator in which `vector` is expressed. The caller may select `false` to use the orientation of the Earth's equator at noon UTC on January 1, 2000, in which case this function corrects for precession and nutation of the Earth as it was at the moment specified by `vector.t`. Or the caller may select `true` to use the Earth's equator at `vector.t` as the orientation. | + + +* * * + + + +## FlexibleDateTime : Date \| number \| [AstroTime](#AstroTime) +**Kind**: global typedef +**Brief**: A `Date`, `number`, or `AstroTime` value that specifies the date and time of an astronomical event. + +`FlexibleDateTime` is a placeholder type that represents three different types +that may be passed to many Astronomy Engine functions: a JavaScript `Date` object, +a number representing the real-valued number of UT days since the J2000 epoch, +or an [AstroTime](#AstroTime) object. + +This flexibility is for convenience of outside callers. +Internally, Astronomy Engine always converts a `FlexibleDateTime` parameter +to an `AstroTime` object by calling [MakeTime](#MakeTime). + +* * * + + + +## SearchOptions : object +**Kind**: global typedef +**Brief**: Options for the [Search](#Search) function. +**Properties** + +| Name | Type | Description | +| --- | --- | --- | +| dt_tolerance_seconds | number \| undefined | The number of seconds for a time window smaller than which the search is considered successful. Using too large a tolerance can result in an inaccurate time estimate. Using too small a tolerance can cause excessive computation, or can even cause the search to fail because of limited floating-point resolution. Defaults to 1 second. | +| init_f1 | number \| undefined | As an optimization, if the caller of [Search](#Search) has already calculated the value of the function being searched (the parameter `func`) at the time coordinate `t1`, it can pass in that value as `init_f1`. For very expensive calculations, this can measurably improve performance. | +| init_f2 | number \| undefined | The same as `init_f1`, except this is the optional initial value of `func(t2)` instead of `func(t1)`. | +| iter_limit | number \| undefined | | + + +* * * + diff --git a/node_modules/astronomy-engine/astronomy.browser.js b/node_modules/astronomy-engine/astronomy.browser.js new file mode 100644 index 0000000..6ea86e8 --- /dev/null +++ b/node_modules/astronomy-engine/astronomy.browser.js @@ -0,0 +1,9810 @@ +(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Astronomy = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ +/** + * @fileoverview Astronomy calculation library for browser scripting and Node.js. + * @author Don Cross + * @license MIT + */ +'use strict'; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GeoEmbState = exports.GeoMoonState = exports.EclipticGeoMoon = exports.GeoMoon = exports.Ecliptic = exports.ObserverGravity = exports.VectorObserver = exports.ObserverState = exports.ObserverVector = exports.Equator = exports.SunPosition = exports.Observer = exports.Horizon = exports.EclipticCoordinates = exports.HorizontalCoordinates = exports.MakeRotation = exports.RotationMatrix = exports.EquatorialCoordinates = exports.Spherical = exports.StateVector = exports.Vector = exports.SiderealTime = exports.Libration = exports.LibrationInfo = exports.CalcMoonCount = exports.e_tilt = exports.MakeTime = exports.AstroTime = exports.SetDeltaTFunction = exports.DeltaT_JplHorizons = exports.DeltaT_EspenakMeeus = exports.PlanetOrbitalPeriod = exports.DefineStar = exports.Body = exports.AngleBetween = exports.MassProduct = exports.CALLISTO_RADIUS_KM = exports.GANYMEDE_RADIUS_KM = exports.EUROPA_RADIUS_KM = exports.IO_RADIUS_KM = exports.JUPITER_MEAN_RADIUS_KM = exports.JUPITER_POLAR_RADIUS_KM = exports.JUPITER_EQUATORIAL_RADIUS_KM = exports.RAD2HOUR = exports.RAD2DEG = exports.HOUR2RAD = exports.DEG2RAD = exports.AU_PER_LY = exports.KM_PER_AU = exports.C_AUDAY = void 0; +exports.VectorFromHorizon = exports.HorizonFromVector = exports.SphereFromVector = exports.EquatorFromVector = exports.VectorFromSphere = exports.Pivot = exports.IdentityMatrix = exports.CombineRotation = exports.InverseRotation = exports.NextPlanetApsis = exports.SearchPlanetApsis = exports.NextLunarApsis = exports.SearchLunarApsis = exports.Apsis = exports.ApsisKind = exports.SearchPeakMagnitude = exports.SearchMaxElongation = exports.Elongation = exports.ElongationEvent = exports.Seasons = exports.SeasonInfo = exports.HourAngle = exports.SearchHourAngle = exports.HourAngleEvent = exports.SearchAltitude = exports.SearchRiseSet = exports.Atmosphere = exports.AtmosphereInfo = exports.NextMoonQuarter = exports.SearchMoonQuarter = exports.MoonQuarter = exports.SearchMoonPhase = exports.MoonPhase = exports.SearchRelativeLongitude = exports.Illumination = exports.IlluminationInfo = exports.EclipticLongitude = exports.AngleFromSun = exports.PairLongitude = exports.SearchSunLongitude = exports.Search = exports.HelioState = exports.BaryState = exports.GeoVector = exports.BackdatePosition = exports.CorrectLightTravel = exports.HelioDistance = exports.HelioVector = exports.JupiterMoons = exports.JupiterMoonsInfo = void 0; +exports.GravitySimulator = exports.LagrangePointFast = exports.LagrangePoint = exports.RotationAxis = exports.AxisInfo = exports.NextMoonNode = exports.SearchMoonNode = exports.NodeEventInfo = exports.NodeEventKind = exports.NextTransit = exports.SearchTransit = exports.TransitInfo = exports.NextLocalSolarEclipse = exports.SearchLocalSolarEclipse = exports.LocalSolarEclipseInfo = exports.EclipseEvent = exports.NextGlobalSolarEclipse = exports.SearchGlobalSolarEclipse = exports.NextLunarEclipse = exports.GlobalSolarEclipseInfo = exports.SearchLunarEclipse = exports.LunarEclipseInfo = exports.EclipseKind = exports.Constellation = exports.ConstellationInfo = exports.Rotation_EQD_ECT = exports.Rotation_ECT_EQD = exports.Rotation_GAL_EQJ = exports.Rotation_EQJ_GAL = exports.Rotation_HOR_ECL = exports.Rotation_ECL_HOR = exports.Rotation_ECL_EQD = exports.Rotation_EQD_ECL = exports.Rotation_EQJ_HOR = exports.Rotation_HOR_EQJ = exports.Rotation_HOR_EQD = exports.Rotation_EQD_HOR = exports.Rotation_EQD_EQJ = exports.Rotation_ECT_EQJ = exports.Rotation_EQJ_ECT = exports.Rotation_EQJ_EQD = exports.Rotation_ECL_EQJ = exports.Rotation_EQJ_ECL = exports.RotateState = exports.RotateVector = exports.InverseRefraction = exports.Refraction = void 0; +/** + * @brief The speed of light in AU/day. + */ +exports.C_AUDAY = 173.1446326846693; +/** + * @brief The number of kilometers per astronomical unit. + */ +exports.KM_PER_AU = 1.4959787069098932e+8; +/** + * @brief The number of astronomical units per light-year. + */ +exports.AU_PER_LY = 63241.07708807546; +/** + * @brief The factor to convert degrees to radians = pi/180. + */ +exports.DEG2RAD = 0.017453292519943296; +/** + * @brief The factor to convert sidereal hours to radians = pi/12. + */ +exports.HOUR2RAD = 0.2617993877991494365; +/** + * @brief The factor to convert radians to degrees = 180/pi. + */ +exports.RAD2DEG = 57.295779513082321; +/** + * @brief The factor to convert radians to sidereal hours = 12/pi. + */ +exports.RAD2HOUR = 3.819718634205488; +// Jupiter radius data are nominal values obtained from: +// https://www.iau.org/static/resolutions/IAU2015_English.pdf +// https://nssdc.gsfc.nasa.gov/planetary/factsheet/jupiterfact.html +/** + * @brief The equatorial radius of Jupiter, expressed in kilometers. + */ +exports.JUPITER_EQUATORIAL_RADIUS_KM = 71492.0; +/** + * @brief The polar radius of Jupiter, expressed in kilometers. + */ +exports.JUPITER_POLAR_RADIUS_KM = 66854.0; +/** + * @brief The volumetric mean radius of Jupiter, expressed in kilometers. + */ +exports.JUPITER_MEAN_RADIUS_KM = 69911.0; +// The radii of Jupiter's four major moons are obtained from: +// https://ssd.jpl.nasa.gov/?sat_phys_par +/** + * @brief The mean radius of Jupiter's moon Io, expressed in kilometers. + */ +exports.IO_RADIUS_KM = 1821.6; +/** + * @brief The mean radius of Jupiter's moon Europa, expressed in kilometers. + */ +exports.EUROPA_RADIUS_KM = 1560.8; +/** + * @brief The mean radius of Jupiter's moon Ganymede, expressed in kilometers. + */ +exports.GANYMEDE_RADIUS_KM = 2631.2; +/** + * @brief The mean radius of Jupiter's moon Callisto, expressed in kilometers. + */ +exports.CALLISTO_RADIUS_KM = 2410.3; +const DAYS_PER_TROPICAL_YEAR = 365.24217; +const J2000 = new Date('2000-01-01T12:00:00Z'); +const PI2 = 2 * Math.PI; +const ARC = 3600 * (180 / Math.PI); // arcseconds per radian +const ASEC2RAD = 4.848136811095359935899141e-6; +const ASEC180 = 180 * 60 * 60; // arcseconds per 180 degrees (or pi radians) +const ASEC360 = 2 * ASEC180; // arcseconds per 360 degrees (or 2*pi radians) +const ANGVEL = 7.2921150e-5; +const AU_PER_PARSEC = ASEC180 / Math.PI; // exact definition of how many AU = one parsec +const SUN_MAG_1AU = -0.17 - 5 * Math.log10(AU_PER_PARSEC); // formula from JPL Horizons +const MEAN_SYNODIC_MONTH = 29.530588; // average number of days for Moon to return to the same phase +const SECONDS_PER_DAY = 24 * 3600; +const MILLIS_PER_DAY = SECONDS_PER_DAY * 1000; +const SOLAR_DAYS_PER_SIDEREAL_DAY = 0.9972695717592592; +const SUN_RADIUS_KM = 695700.0; +const SUN_RADIUS_AU = SUN_RADIUS_KM / exports.KM_PER_AU; +const EARTH_FLATTENING = 0.996647180302104; +const EARTH_FLATTENING_SQUARED = EARTH_FLATTENING * EARTH_FLATTENING; +const EARTH_EQUATORIAL_RADIUS_KM = 6378.1366; +const EARTH_EQUATORIAL_RADIUS_AU = EARTH_EQUATORIAL_RADIUS_KM / exports.KM_PER_AU; +const EARTH_POLAR_RADIUS_KM = EARTH_EQUATORIAL_RADIUS_KM * EARTH_FLATTENING; +const EARTH_MEAN_RADIUS_KM = 6371.0; /* mean radius of the Earth's geoid, without atmosphere */ +const EARTH_ATMOSPHERE_KM = 88.0; /* effective atmosphere thickness for lunar eclipses */ +const EARTH_ECLIPSE_RADIUS_KM = EARTH_MEAN_RADIUS_KM + EARTH_ATMOSPHERE_KM; +const MOON_EQUATORIAL_RADIUS_KM = 1738.1; +const MOON_EQUATORIAL_RADIUS_AU = (MOON_EQUATORIAL_RADIUS_KM / exports.KM_PER_AU); +const MOON_MEAN_RADIUS_KM = 1737.4; +const MOON_POLAR_RADIUS_KM = 1736.0; +const MOON_POLAR_RADIUS_AU = (MOON_POLAR_RADIUS_KM / exports.KM_PER_AU); +const REFRACTION_NEAR_HORIZON = 34 / 60; // degrees of refractive "lift" seen for objects near horizon +const EARTH_MOON_MASS_RATIO = 81.30056; +/* + Masses of the Sun and outer planets, used for: + (1) Calculating the Solar System Barycenter + (2) Integrating the movement of Pluto + + https://web.archive.org/web/20120220062549/http://iau-comm4.jpl.nasa.gov/de405iom/de405iom.pdf + + Page 10 in the above document describes the constants used in the DE405 ephemeris. + The following are G*M values (gravity constant * mass) in [au^3 / day^2]. + This side-steps issues of not knowing the exact values of G and masses M[i]; + the products GM[i] are known extremely accurately. +*/ +const SUN_GM = 0.2959122082855911e-03; +const MERCURY_GM = 0.4912547451450812e-10; +const VENUS_GM = 0.7243452486162703e-09; +const EARTH_GM = 0.8887692390113509e-09; +const MARS_GM = 0.9549535105779258e-10; +const JUPITER_GM = 0.2825345909524226e-06; +const SATURN_GM = 0.8459715185680659e-07; +const URANUS_GM = 0.1292024916781969e-07; +const NEPTUNE_GM = 0.1524358900784276e-07; +const PLUTO_GM = 0.2188699765425970e-11; +const MOON_GM = EARTH_GM / EARTH_MOON_MASS_RATIO; +/** + * @brief Returns the product of mass and universal gravitational constant of a Solar System body. + * + * For problems involving the gravitational interactions of Solar System bodies, + * it is helpful to know the product GM, where G = the universal gravitational constant + * and M = the mass of the body. In practice, GM is known to a higher precision than + * either G or M alone, and thus using the product results in the most accurate results. + * This function returns the product GM in the units au^3/day^2. + * The values come from page 10 of a + * [JPL memorandum regarding the DE405/LE405 ephemeris](https://web.archive.org/web/20120220062549/http://iau-comm4.jpl.nasa.gov/de405iom/de405iom.pdf). + * + * @param {Body} body + * The body for which to find the GM product. + * Allowed to be the Sun, Moon, EMB (Earth/Moon Barycenter), or any planet. + * Any other value will cause an exception to be thrown. + * + * @returns {number} + * The mass product of the given body in au^3/day^2. + */ +function MassProduct(body) { + switch (body) { + case Body.Sun: return SUN_GM; + case Body.Mercury: return MERCURY_GM; + case Body.Venus: return VENUS_GM; + case Body.Earth: return EARTH_GM; + case Body.Moon: return MOON_GM; + case Body.EMB: return EARTH_GM + MOON_GM; + case Body.Mars: return MARS_GM; + case Body.Jupiter: return JUPITER_GM; + case Body.Saturn: return SATURN_GM; + case Body.Uranus: return URANUS_GM; + case Body.Neptune: return NEPTUNE_GM; + case Body.Pluto: return PLUTO_GM; + default: + throw `Do not know mass product for body: ${body}`; + } +} +exports.MassProduct = MassProduct; +function VerifyBoolean(b) { + if (b !== true && b !== false) { + console.trace(); + throw `Value is not boolean: ${b}`; + } + return b; +} +function VerifyNumber(x) { + if (!Number.isFinite(x)) { + console.trace(); + throw `Value is not a finite number: ${x}`; + } + return x; +} +function Frac(x) { + return x - Math.floor(x); +} +/** + * @brief Calculates the angle in degrees between two vectors. + * + * Given a pair of vectors, this function returns the angle in degrees + * between the two vectors in 3D space. + * The angle is measured in the plane that contains both vectors. + * + * @param {Vector} a + * The first of a pair of vectors between which to measure an angle. + * + * @param {Vector} b + * The second of a pair of vectors between which to measure an angle. + * + * @returns {number} + * The angle between the two vectors expressed in degrees. + * The value is in the range [0, 180]. + */ +function AngleBetween(a, b) { + const aa = (a.x * a.x + a.y * a.y + a.z * a.z); + if (Math.abs(aa) < 1.0e-8) + throw `AngleBetween: first vector is too short.`; + const bb = (b.x * b.x + b.y * b.y + b.z * b.z); + if (Math.abs(bb) < 1.0e-8) + throw `AngleBetween: second vector is too short.`; + const dot = (a.x * b.x + a.y * b.y + a.z * b.z) / Math.sqrt(aa * bb); + if (dot <= -1.0) + return 180; + if (dot >= +1.0) + return 0; + return exports.RAD2DEG * Math.acos(dot); +} +exports.AngleBetween = AngleBetween; +/** + * @brief String constants that represent the solar system bodies supported by Astronomy Engine. + * + * The following strings represent solar system bodies supported by various Astronomy Engine functions. + * Not every body is supported by every function; consult the documentation for each function + * to find which bodies it supports. + * + * "Sun", "Moon", "Mercury", "Venus", "Earth", "Mars", "Jupiter", + * "Saturn", "Uranus", "Neptune", "Pluto", + * "SSB" (Solar System Barycenter), + * "EMB" (Earth/Moon Barycenter) + * + * You can also use enumeration syntax for the bodies, like + * `Astronomy.Body.Moon`, `Astronomy.Body.Jupiter`, etc. + * + * @enum {string} + */ +var Body; +(function (Body) { + Body["Sun"] = "Sun"; + Body["Moon"] = "Moon"; + Body["Mercury"] = "Mercury"; + Body["Venus"] = "Venus"; + Body["Earth"] = "Earth"; + Body["Mars"] = "Mars"; + Body["Jupiter"] = "Jupiter"; + Body["Saturn"] = "Saturn"; + Body["Uranus"] = "Uranus"; + Body["Neptune"] = "Neptune"; + Body["Pluto"] = "Pluto"; + Body["SSB"] = "SSB"; + Body["EMB"] = "EMB"; + // User-defined fixed locations in the sky... + Body["Star1"] = "Star1"; + Body["Star2"] = "Star2"; + Body["Star3"] = "Star3"; + Body["Star4"] = "Star4"; + Body["Star5"] = "Star5"; + Body["Star6"] = "Star6"; + Body["Star7"] = "Star7"; + Body["Star8"] = "Star8"; +})(Body = exports.Body || (exports.Body = {})); +const StarList = [ + Body.Star1, Body.Star2, Body.Star3, Body.Star4, + Body.Star5, Body.Star6, Body.Star7, Body.Star8 +]; +; +const StarTable = [ + { ra: 0, dec: 0, dist: 0 }, + { ra: 0, dec: 0, dist: 0 }, + { ra: 0, dec: 0, dist: 0 }, + { ra: 0, dec: 0, dist: 0 }, + { ra: 0, dec: 0, dist: 0 }, + { ra: 0, dec: 0, dist: 0 }, + { ra: 0, dec: 0, dist: 0 }, + { ra: 0, dec: 0, dist: 0 }, +]; +function GetStar(body) { + const index = StarList.indexOf(body); + return (index >= 0) ? StarTable[index] : null; +} +function UserDefinedStar(body) { + const star = GetStar(body); + return (star && star.dist > 0) ? star : null; +} +/** + * @brief Assign equatorial coordinates to a user-defined star. + * + * Some Astronomy Engine functions allow their `body` parameter to + * be a user-defined fixed point in the sky, loosely called a "star". + * This function assigns a right ascension, declination, and distance + * to one of the eight user-defined stars `Star1`..`Star8`. + * + * Stars are not valid until defined. Once defined, they retain their + * definition until re-defined by another call to `DefineStar`. + * + * @param {Body} body + * One of the eight user-defined star identifiers: + * `Star1`, `Star2`, `Star3`, `Star4`, `Star5`, `Star6`, `Star7`, or `Star8`. + * + * @param {number} ra + * The right ascension to be assigned to the star, expressed in J2000 equatorial coordinates (EQJ). + * The value is in units of sidereal hours, and must be within the half-open range [0, 24). + * + * @param {number} dec + * The declination to be assigned to the star, expressed in J2000 equatorial coordinates (EQJ). + * The value is in units of degrees north (positive) or south (negative) of the J2000 equator, + * and must be within the closed range [-90, +90]. + * + * @param {number} distanceLightYears + * The distance between the star and the Sun, expressed in light-years. + * This value is used to calculate the tiny parallax shift as seen by an observer on Earth. + * If you don't know the distance to the star, using a large value like 1000 will generally work well. + * The minimum allowed distance is 1 light-year, which is required to provide certain internal optimizations. + */ +function DefineStar(body, ra, dec, distanceLightYears) { + const star = GetStar(body); + if (!star) + throw `Invalid star body: ${body}`; + VerifyNumber(ra); + VerifyNumber(dec); + VerifyNumber(distanceLightYears); + if (ra < 0 || ra >= 24) + throw `Invalid right ascension for star: ${ra}`; + if (dec < -90 || dec > +90) + throw `Invalid declination for star: ${dec}`; + if (distanceLightYears < 1) + throw `Invalid star distance: ${distanceLightYears}`; + star.ra = ra; + star.dec = dec; + star.dist = distanceLightYears * exports.AU_PER_LY; +} +exports.DefineStar = DefineStar; +var PrecessDirection; +(function (PrecessDirection) { + PrecessDirection[PrecessDirection["From2000"] = 0] = "From2000"; + PrecessDirection[PrecessDirection["Into2000"] = 1] = "Into2000"; +})(PrecessDirection || (PrecessDirection = {})); +const Planet = { + Mercury: { OrbitalPeriod: 87.969 }, + Venus: { OrbitalPeriod: 224.701 }, + Earth: { OrbitalPeriod: 365.256 }, + Mars: { OrbitalPeriod: 686.980 }, + Jupiter: { OrbitalPeriod: 4332.589 }, + Saturn: { OrbitalPeriod: 10759.22 }, + Uranus: { OrbitalPeriod: 30685.4 }, + Neptune: { OrbitalPeriod: 60189.0 }, + Pluto: { OrbitalPeriod: 90560.0 } +}; +/** + * @brief Returns the mean orbital period of a planet in days. + * + * @param {Body} body + * One of: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, or Pluto. + * + * @returns {number} + * The approximate average time it takes for the planet to travel once around the Sun. + * The value is expressed in days. + */ +function PlanetOrbitalPeriod(body) { + if (body in Planet) + return Planet[body].OrbitalPeriod; + throw `Unknown orbital period for: ${body}`; +} +exports.PlanetOrbitalPeriod = PlanetOrbitalPeriod; +const vsop = { + Mercury: [ + [ + [ + [4.40250710144, 0.00000000000, 0.00000000000], + [0.40989414977, 1.48302034195, 26087.90314157420], + [0.05046294200, 4.47785489551, 52175.80628314840], + [0.00855346844, 1.16520322459, 78263.70942472259], + [0.00165590362, 4.11969163423, 104351.61256629678], + [0.00034561897, 0.77930768443, 130439.51570787099], + [0.00007583476, 3.71348404924, 156527.41884944518] + ], + [ + [26087.90313685529, 0.00000000000, 0.00000000000], + [0.01131199811, 6.21874197797, 26087.90314157420], + [0.00292242298, 3.04449355541, 52175.80628314840], + [0.00075775081, 6.08568821653, 78263.70942472259], + [0.00019676525, 2.80965111777, 104351.61256629678] + ] + ], + [ + [ + [0.11737528961, 1.98357498767, 26087.90314157420], + [0.02388076996, 5.03738959686, 52175.80628314840], + [0.01222839532, 3.14159265359, 0.00000000000], + [0.00543251810, 1.79644363964, 78263.70942472259], + [0.00129778770, 4.83232503958, 104351.61256629678], + [0.00031866927, 1.58088495658, 130439.51570787099], + [0.00007963301, 4.60972126127, 156527.41884944518] + ], + [ + [0.00274646065, 3.95008450011, 26087.90314157420], + [0.00099737713, 3.14159265359, 0.00000000000] + ] + ], + [ + [ + [0.39528271651, 0.00000000000, 0.00000000000], + [0.07834131818, 6.19233722598, 26087.90314157420], + [0.00795525558, 2.95989690104, 52175.80628314840], + [0.00121281764, 6.01064153797, 78263.70942472259], + [0.00021921969, 2.77820093972, 104351.61256629678], + [0.00004354065, 5.82894543774, 130439.51570787099] + ], + [ + [0.00217347740, 4.65617158665, 26087.90314157420], + [0.00044141826, 1.42385544001, 52175.80628314840] + ] + ] + ], + Venus: [ + [ + [ + [3.17614666774, 0.00000000000, 0.00000000000], + [0.01353968419, 5.59313319619, 10213.28554621100], + [0.00089891645, 5.30650047764, 20426.57109242200], + [0.00005477194, 4.41630661466, 7860.41939243920], + [0.00003455741, 2.69964447820, 11790.62908865880], + [0.00002372061, 2.99377542079, 3930.20969621960], + [0.00001317168, 5.18668228402, 26.29831979980], + [0.00001664146, 4.25018630147, 1577.34354244780], + [0.00001438387, 4.15745084182, 9683.59458111640], + [0.00001200521, 6.15357116043, 30639.85663863300] + ], + [ + [10213.28554621638, 0.00000000000, 0.00000000000], + [0.00095617813, 2.46406511110, 10213.28554621100], + [0.00007787201, 0.62478482220, 20426.57109242200] + ] + ], + [ + [ + [0.05923638472, 0.26702775812, 10213.28554621100], + [0.00040107978, 1.14737178112, 20426.57109242200], + [0.00032814918, 3.14159265359, 0.00000000000] + ], + [ + [0.00287821243, 1.88964962838, 10213.28554621100] + ] + ], + [ + [ + [0.72334820891, 0.00000000000, 0.00000000000], + [0.00489824182, 4.02151831717, 10213.28554621100], + [0.00001658058, 4.90206728031, 20426.57109242200], + [0.00001378043, 1.12846591367, 11790.62908865880], + [0.00001632096, 2.84548795207, 7860.41939243920], + [0.00000498395, 2.58682193892, 9683.59458111640], + [0.00000221985, 2.01346696541, 19367.18916223280], + [0.00000237454, 2.55136053886, 15720.83878487840] + ], + [ + [0.00034551041, 0.89198706276, 10213.28554621100] + ] + ] + ], + Earth: [ + [ + [ + [1.75347045673, 0.00000000000, 0.00000000000], + [0.03341656453, 4.66925680415, 6283.07584999140], + [0.00034894275, 4.62610242189, 12566.15169998280], + [0.00003417572, 2.82886579754, 3.52311834900], + [0.00003497056, 2.74411783405, 5753.38488489680], + [0.00003135899, 3.62767041756, 77713.77146812050], + [0.00002676218, 4.41808345438, 7860.41939243920], + [0.00002342691, 6.13516214446, 3930.20969621960], + [0.00001273165, 2.03709657878, 529.69096509460], + [0.00001324294, 0.74246341673, 11506.76976979360], + [0.00000901854, 2.04505446477, 26.29831979980], + [0.00001199167, 1.10962946234, 1577.34354244780], + [0.00000857223, 3.50849152283, 398.14900340820], + [0.00000779786, 1.17882681962, 5223.69391980220], + [0.00000990250, 5.23268072088, 5884.92684658320], + [0.00000753141, 2.53339052847, 5507.55323866740], + [0.00000505267, 4.58292599973, 18849.22754997420], + [0.00000492392, 4.20505711826, 775.52261132400], + [0.00000356672, 2.91954114478, 0.06731030280], + [0.00000284125, 1.89869240932, 796.29800681640], + [0.00000242879, 0.34481445893, 5486.77784317500], + [0.00000317087, 5.84901948512, 11790.62908865880], + [0.00000271112, 0.31486255375, 10977.07880469900], + [0.00000206217, 4.80646631478, 2544.31441988340], + [0.00000205478, 1.86953770281, 5573.14280143310], + [0.00000202318, 2.45767790232, 6069.77675455340], + [0.00000126225, 1.08295459501, 20.77539549240], + [0.00000155516, 0.83306084617, 213.29909543800] + ], + [ + [6283.07584999140, 0.00000000000, 0.00000000000], + [0.00206058863, 2.67823455808, 6283.07584999140], + [0.00004303419, 2.63512233481, 12566.15169998280] + ], + [ + [0.00008721859, 1.07253635559, 6283.07584999140] + ] + ], + [ + [], + [ + [0.00227777722, 3.41376620530, 6283.07584999140], + [0.00003805678, 3.37063423795, 12566.15169998280] + ] + ], + [ + [ + [1.00013988784, 0.00000000000, 0.00000000000], + [0.01670699632, 3.09846350258, 6283.07584999140], + [0.00013956024, 3.05524609456, 12566.15169998280], + [0.00003083720, 5.19846674381, 77713.77146812050], + [0.00001628463, 1.17387558054, 5753.38488489680], + [0.00001575572, 2.84685214877, 7860.41939243920], + [0.00000924799, 5.45292236722, 11506.76976979360], + [0.00000542439, 4.56409151453, 3930.20969621960], + [0.00000472110, 3.66100022149, 5884.92684658320], + [0.00000085831, 1.27079125277, 161000.68573767410], + [0.00000057056, 2.01374292245, 83996.84731811189], + [0.00000055736, 5.24159799170, 71430.69561812909], + [0.00000174844, 3.01193636733, 18849.22754997420], + [0.00000243181, 4.27349530790, 11790.62908865880] + ], + [ + [0.00103018607, 1.10748968172, 6283.07584999140], + [0.00001721238, 1.06442300386, 12566.15169998280] + ], + [ + [0.00004359385, 5.78455133808, 6283.07584999140] + ] + ] + ], + Mars: [ + [ + [ + [6.20347711581, 0.00000000000, 0.00000000000], + [0.18656368093, 5.05037100270, 3340.61242669980], + [0.01108216816, 5.40099836344, 6681.22485339960], + [0.00091798406, 5.75478744667, 10021.83728009940], + [0.00027744987, 5.97049513147, 3.52311834900], + [0.00010610235, 2.93958560338, 2281.23049651060], + [0.00012315897, 0.84956094002, 2810.92146160520], + [0.00008926784, 4.15697846427, 0.01725365220], + [0.00008715691, 6.11005153139, 13362.44970679920], + [0.00006797556, 0.36462229657, 398.14900340820], + [0.00007774872, 3.33968761376, 5621.84292321040], + [0.00003575078, 1.66186505710, 2544.31441988340], + [0.00004161108, 0.22814971327, 2942.46342329160], + [0.00003075252, 0.85696614132, 191.44826611160], + [0.00002628117, 0.64806124465, 3337.08930835080], + [0.00002937546, 6.07893711402, 0.06731030280], + [0.00002389414, 5.03896442664, 796.29800681640], + [0.00002579844, 0.02996736156, 3344.13554504880], + [0.00001528141, 1.14979301996, 6151.53388830500], + [0.00001798806, 0.65634057445, 529.69096509460], + [0.00001264357, 3.62275122593, 5092.15195811580], + [0.00001286228, 3.06796065034, 2146.16541647520], + [0.00001546404, 2.91579701718, 1751.53953141600], + [0.00001024902, 3.69334099279, 8962.45534991020], + [0.00000891566, 0.18293837498, 16703.06213349900], + [0.00000858759, 2.40093811940, 2914.01423582380], + [0.00000832715, 2.46418619474, 3340.59517304760], + [0.00000832720, 4.49495782139, 3340.62968035200], + [0.00000712902, 3.66335473479, 1059.38193018920], + [0.00000748723, 3.82248614017, 155.42039943420], + [0.00000723861, 0.67497311481, 3738.76143010800], + [0.00000635548, 2.92182225127, 8432.76438481560], + [0.00000655162, 0.48864064125, 3127.31333126180], + [0.00000550474, 3.81001042328, 0.98032106820], + [0.00000552750, 4.47479317037, 1748.01641306700], + [0.00000425966, 0.55364317304, 6283.07584999140], + [0.00000415131, 0.49662285038, 213.29909543800], + [0.00000472167, 3.62547124025, 1194.44701022460], + [0.00000306551, 0.38052848348, 6684.74797174860], + [0.00000312141, 0.99853944405, 6677.70173505060], + [0.00000293198, 4.22131299634, 20.77539549240], + [0.00000302375, 4.48618007156, 3532.06069281140], + [0.00000274027, 0.54222167059, 3340.54511639700], + [0.00000281079, 5.88163521788, 1349.86740965880], + [0.00000231183, 1.28242156993, 3870.30339179440], + [0.00000283602, 5.76885434940, 3149.16416058820], + [0.00000236117, 5.75503217933, 3333.49887969900], + [0.00000274033, 0.13372524985, 3340.67973700260], + [0.00000299395, 2.78323740866, 6254.62666252360] + ], + [ + [3340.61242700512, 0.00000000000, 0.00000000000], + [0.01457554523, 3.60433733236, 3340.61242669980], + [0.00168414711, 3.92318567804, 6681.22485339960], + [0.00020622975, 4.26108844583, 10021.83728009940], + [0.00003452392, 4.73210393190, 3.52311834900], + [0.00002586332, 4.60670058555, 13362.44970679920], + [0.00000841535, 4.45864030426, 2281.23049651060] + ], + [ + [0.00058152577, 2.04961712429, 3340.61242669980], + [0.00013459579, 2.45738706163, 6681.22485339960] + ] + ], + [ + [ + [0.03197134986, 3.76832042431, 3340.61242669980], + [0.00298033234, 4.10616996305, 6681.22485339960], + [0.00289104742, 0.00000000000, 0.00000000000], + [0.00031365539, 4.44651053090, 10021.83728009940], + [0.00003484100, 4.78812549260, 13362.44970679920] + ], + [ + [0.00217310991, 6.04472194776, 3340.61242669980], + [0.00020976948, 3.14159265359, 0.00000000000], + [0.00012834709, 1.60810667915, 6681.22485339960] + ] + ], + [ + [ + [1.53033488271, 0.00000000000, 0.00000000000], + [0.14184953160, 3.47971283528, 3340.61242669980], + [0.00660776362, 3.81783443019, 6681.22485339960], + [0.00046179117, 4.15595316782, 10021.83728009940], + [0.00008109733, 5.55958416318, 2810.92146160520], + [0.00007485318, 1.77239078402, 5621.84292321040], + [0.00005523191, 1.36436303770, 2281.23049651060], + [0.00003825160, 4.49407183687, 13362.44970679920], + [0.00002306537, 0.09081579001, 2544.31441988340], + [0.00001999396, 5.36059617709, 3337.08930835080], + [0.00002484394, 4.92545639920, 2942.46342329160], + [0.00001960195, 4.74249437639, 3344.13554504880], + [0.00001167119, 2.11260868341, 5092.15195811580], + [0.00001102816, 5.00908403998, 398.14900340820], + [0.00000899066, 4.40791133207, 529.69096509460], + [0.00000992252, 5.83861961952, 6151.53388830500], + [0.00000807354, 2.10217065501, 1059.38193018920], + [0.00000797915, 3.44839203899, 796.29800681640], + [0.00000740975, 1.49906336885, 2146.16541647520] + ], + [ + [0.01107433345, 2.03250524857, 3340.61242669980], + [0.00103175887, 2.37071847807, 6681.22485339960], + [0.00012877200, 0.00000000000, 0.00000000000], + [0.00010815880, 2.70888095665, 10021.83728009940] + ], + [ + [0.00044242249, 0.47930604954, 3340.61242669980], + [0.00008138042, 0.86998389204, 6681.22485339960] + ] + ] + ], + Jupiter: [ + [ + [ + [0.59954691494, 0.00000000000, 0.00000000000], + [0.09695898719, 5.06191793158, 529.69096509460], + [0.00573610142, 1.44406205629, 7.11354700080], + [0.00306389205, 5.41734730184, 1059.38193018920], + [0.00097178296, 4.14264726552, 632.78373931320], + [0.00072903078, 3.64042916389, 522.57741809380], + [0.00064263975, 3.41145165351, 103.09277421860], + [0.00039806064, 2.29376740788, 419.48464387520], + [0.00038857767, 1.27231755835, 316.39186965660], + [0.00027964629, 1.78454591820, 536.80451209540], + [0.00013589730, 5.77481040790, 1589.07289528380], + [0.00008246349, 3.58227925840, 206.18554843720], + [0.00008768704, 3.63000308199, 949.17560896980], + [0.00007368042, 5.08101194270, 735.87651353180], + [0.00006263150, 0.02497628807, 213.29909543800], + [0.00006114062, 4.51319998626, 1162.47470440780], + [0.00004905396, 1.32084470588, 110.20632121940], + [0.00005305285, 1.30671216791, 14.22709400160], + [0.00005305441, 4.18625634012, 1052.26838318840], + [0.00004647248, 4.69958103684, 3.93215326310], + [0.00003045023, 4.31676431084, 426.59819087600], + [0.00002609999, 1.56667394063, 846.08283475120], + [0.00002028191, 1.06376530715, 3.18139373770], + [0.00001764763, 2.14148655117, 1066.49547719000], + [0.00001722972, 3.88036268267, 1265.56747862640], + [0.00001920945, 0.97168196472, 639.89728631400], + [0.00001633223, 3.58201833555, 515.46387109300], + [0.00001431999, 4.29685556046, 625.67019231240], + [0.00000973272, 4.09764549134, 95.97922721780] + ], + [ + [529.69096508814, 0.00000000000, 0.00000000000], + [0.00489503243, 4.22082939470, 529.69096509460], + [0.00228917222, 6.02646855621, 7.11354700080], + [0.00030099479, 4.54540782858, 1059.38193018920], + [0.00020720920, 5.45943156902, 522.57741809380], + [0.00012103653, 0.16994816098, 536.80451209540], + [0.00006067987, 4.42422292017, 103.09277421860], + [0.00005433968, 3.98480737746, 419.48464387520], + [0.00004237744, 5.89008707199, 14.22709400160] + ], + [ + [0.00047233601, 4.32148536482, 7.11354700080], + [0.00030649436, 2.92977788700, 529.69096509460], + [0.00014837605, 3.14159265359, 0.00000000000] + ] + ], + [ + [ + [0.02268615702, 3.55852606721, 529.69096509460], + [0.00109971634, 3.90809347197, 1059.38193018920], + [0.00110090358, 0.00000000000, 0.00000000000], + [0.00008101428, 3.60509572885, 522.57741809380], + [0.00006043996, 4.25883108339, 1589.07289528380], + [0.00006437782, 0.30627119215, 536.80451209540] + ], + [ + [0.00078203446, 1.52377859742, 529.69096509460] + ] + ], + [ + [ + [5.20887429326, 0.00000000000, 0.00000000000], + [0.25209327119, 3.49108639871, 529.69096509460], + [0.00610599976, 3.84115365948, 1059.38193018920], + [0.00282029458, 2.57419881293, 632.78373931320], + [0.00187647346, 2.07590383214, 522.57741809380], + [0.00086792905, 0.71001145545, 419.48464387520], + [0.00072062974, 0.21465724607, 536.80451209540], + [0.00065517248, 5.97995884790, 316.39186965660], + [0.00029134542, 1.67759379655, 103.09277421860], + [0.00030135335, 2.16132003734, 949.17560896980], + [0.00023453271, 3.54023522184, 735.87651353180], + [0.00022283743, 4.19362594399, 1589.07289528380], + [0.00023947298, 0.27458037480, 7.11354700080], + [0.00013032614, 2.96042965363, 1162.47470440780], + [0.00009703360, 1.90669633585, 206.18554843720], + [0.00012749023, 2.71550286592, 1052.26838318840], + [0.00007057931, 2.18184839926, 1265.56747862640], + [0.00006137703, 6.26418240033, 846.08283475120], + [0.00002616976, 2.00994012876, 1581.95934828300] + ], + [ + [0.01271801520, 2.64937512894, 529.69096509460], + [0.00061661816, 3.00076460387, 1059.38193018920], + [0.00053443713, 3.89717383175, 522.57741809380], + [0.00031185171, 4.88276958012, 536.80451209540], + [0.00041390269, 0.00000000000, 0.00000000000] + ] + ] + ], + Saturn: [ + [ + [ + [0.87401354025, 0.00000000000, 0.00000000000], + [0.11107659762, 3.96205090159, 213.29909543800], + [0.01414150957, 4.58581516874, 7.11354700080], + [0.00398379389, 0.52112032699, 206.18554843720], + [0.00350769243, 3.30329907896, 426.59819087600], + [0.00206816305, 0.24658372002, 103.09277421860], + [0.00079271300, 3.84007056878, 220.41264243880], + [0.00023990355, 4.66976924553, 110.20632121940], + [0.00016573588, 0.43719228296, 419.48464387520], + [0.00014906995, 5.76903183869, 316.39186965660], + [0.00015820290, 0.93809155235, 632.78373931320], + [0.00014609559, 1.56518472000, 3.93215326310], + [0.00013160301, 4.44891291899, 14.22709400160], + [0.00015053543, 2.71669915667, 639.89728631400], + [0.00013005299, 5.98119023644, 11.04570026390], + [0.00010725067, 3.12939523827, 202.25339517410], + [0.00005863206, 0.23656938524, 529.69096509460], + [0.00005227757, 4.20783365759, 3.18139373770], + [0.00006126317, 1.76328667907, 277.03499374140], + [0.00005019687, 3.17787728405, 433.71173787680], + [0.00004592550, 0.61977744975, 199.07200143640], + [0.00004005867, 2.24479718502, 63.73589830340], + [0.00002953796, 0.98280366998, 95.97922721780], + [0.00003873670, 3.22283226966, 138.51749687070], + [0.00002461186, 2.03163875071, 735.87651353180], + [0.00003269484, 0.77492638211, 949.17560896980], + [0.00001758145, 3.26580109940, 522.57741809380], + [0.00001640172, 5.50504453050, 846.08283475120], + [0.00001391327, 4.02333150505, 323.50541665740], + [0.00001580648, 4.37265307169, 309.27832265580], + [0.00001123498, 2.83726798446, 415.55249061210], + [0.00001017275, 3.71700135395, 227.52618943960], + [0.00000848642, 3.19150170830, 209.36694217490] + ], + [ + [213.29909521690, 0.00000000000, 0.00000000000], + [0.01297370862, 1.82834923978, 213.29909543800], + [0.00564345393, 2.88499717272, 7.11354700080], + [0.00093734369, 1.06311793502, 426.59819087600], + [0.00107674962, 2.27769131009, 206.18554843720], + [0.00040244455, 2.04108104671, 220.41264243880], + [0.00019941774, 1.27954390470, 103.09277421860], + [0.00010511678, 2.74880342130, 14.22709400160], + [0.00006416106, 0.38238295041, 639.89728631400], + [0.00004848994, 2.43037610229, 419.48464387520], + [0.00004056892, 2.92133209468, 110.20632121940], + [0.00003768635, 3.64965330780, 3.93215326310] + ], + [ + [0.00116441330, 1.17988132879, 7.11354700080], + [0.00091841837, 0.07325195840, 213.29909543800], + [0.00036661728, 0.00000000000, 0.00000000000], + [0.00015274496, 4.06493179167, 206.18554843720] + ] + ], + [ + [ + [0.04330678039, 3.60284428399, 213.29909543800], + [0.00240348302, 2.85238489373, 426.59819087600], + [0.00084745939, 0.00000000000, 0.00000000000], + [0.00030863357, 3.48441504555, 220.41264243880], + [0.00034116062, 0.57297307557, 206.18554843720], + [0.00014734070, 2.11846596715, 639.89728631400], + [0.00009916667, 5.79003188904, 419.48464387520], + [0.00006993564, 4.73604689720, 7.11354700080], + [0.00004807588, 5.43305312061, 316.39186965660] + ], + [ + [0.00198927992, 4.93901017903, 213.29909543800], + [0.00036947916, 3.14159265359, 0.00000000000], + [0.00017966989, 0.51979431110, 426.59819087600] + ] + ], + [ + [ + [9.55758135486, 0.00000000000, 0.00000000000], + [0.52921382865, 2.39226219573, 213.29909543800], + [0.01873679867, 5.23549604660, 206.18554843720], + [0.01464663929, 1.64763042902, 426.59819087600], + [0.00821891141, 5.93520042303, 316.39186965660], + [0.00547506923, 5.01532618980, 103.09277421860], + [0.00371684650, 2.27114821115, 220.41264243880], + [0.00361778765, 3.13904301847, 7.11354700080], + [0.00140617506, 5.70406606781, 632.78373931320], + [0.00108974848, 3.29313390175, 110.20632121940], + [0.00069006962, 5.94099540992, 419.48464387520], + [0.00061053367, 0.94037691801, 639.89728631400], + [0.00048913294, 1.55733638681, 202.25339517410], + [0.00034143772, 0.19519102597, 277.03499374140], + [0.00032401773, 5.47084567016, 949.17560896980], + [0.00020936596, 0.46349251129, 735.87651353180], + [0.00009796004, 5.20477537945, 1265.56747862640], + [0.00011993338, 5.98050967385, 846.08283475120], + [0.00020839300, 1.52102476129, 433.71173787680], + [0.00015298404, 3.05943814940, 529.69096509460], + [0.00006465823, 0.17732249942, 1052.26838318840], + [0.00011380257, 1.73105427040, 522.57741809380], + [0.00003419618, 4.94550542171, 1581.95934828300] + ], + [ + [0.06182981340, 0.25843511480, 213.29909543800], + [0.00506577242, 0.71114625261, 206.18554843720], + [0.00341394029, 5.79635741658, 426.59819087600], + [0.00188491195, 0.47215589652, 220.41264243880], + [0.00186261486, 3.14159265359, 0.00000000000], + [0.00143891146, 1.40744822888, 7.11354700080] + ], + [ + [0.00436902572, 4.78671677509, 213.29909543800] + ] + ] + ], + Uranus: [ + [ + [ + [5.48129294297, 0.00000000000, 0.00000000000], + [0.09260408234, 0.89106421507, 74.78159856730], + [0.01504247898, 3.62719260920, 1.48447270830], + [0.00365981674, 1.89962179044, 73.29712585900], + [0.00272328168, 3.35823706307, 149.56319713460], + [0.00070328461, 5.39254450063, 63.73589830340], + [0.00068892678, 6.09292483287, 76.26607127560], + [0.00061998615, 2.26952066061, 2.96894541660], + [0.00061950719, 2.85098872691, 11.04570026390], + [0.00026468770, 3.14152083966, 71.81265315070], + [0.00025710476, 6.11379840493, 454.90936652730], + [0.00021078850, 4.36059339067, 148.07872442630], + [0.00017818647, 1.74436930289, 36.64856292950], + [0.00014613507, 4.73732166022, 3.93215326310], + [0.00011162509, 5.82681796350, 224.34479570190], + [0.00010997910, 0.48865004018, 138.51749687070], + [0.00009527478, 2.95516862826, 35.16409022120], + [0.00007545601, 5.23626582400, 109.94568878850], + [0.00004220241, 3.23328220918, 70.84944530420], + [0.00004051900, 2.27755017300, 151.04766984290], + [0.00003354596, 1.06549007380, 4.45341812490], + [0.00002926718, 4.62903718891, 9.56122755560], + [0.00003490340, 5.48306144511, 146.59425171800], + [0.00003144069, 4.75199570434, 77.75054398390], + [0.00002922333, 5.35235361027, 85.82729883120], + [0.00002272788, 4.36600400036, 70.32818044240], + [0.00002051219, 1.51773566586, 0.11187458460], + [0.00002148602, 0.60745949945, 38.13303563780], + [0.00001991643, 4.92437588682, 277.03499374140], + [0.00001376226, 2.04283539351, 65.22037101170], + [0.00001666902, 3.62744066769, 380.12776796000], + [0.00001284107, 3.11347961505, 202.25339517410], + [0.00001150429, 0.93343589092, 3.18139373770], + [0.00001533221, 2.58594681212, 52.69019803950], + [0.00001281604, 0.54271272721, 222.86032299360], + [0.00001372139, 4.19641530878, 111.43016149680], + [0.00001221029, 0.19900650030, 108.46121608020], + [0.00000946181, 1.19253165736, 127.47179660680], + [0.00001150989, 4.17898916639, 33.67961751290] + ], + [ + [74.78159860910, 0.00000000000, 0.00000000000], + [0.00154332863, 5.24158770553, 74.78159856730], + [0.00024456474, 1.71260334156, 1.48447270830], + [0.00009258442, 0.42829732350, 11.04570026390], + [0.00008265977, 1.50218091379, 63.73589830340], + [0.00009150160, 1.41213765216, 149.56319713460] + ] + ], + [ + [ + [0.01346277648, 2.61877810547, 74.78159856730], + [0.00062341400, 5.08111189648, 149.56319713460], + [0.00061601196, 3.14159265359, 0.00000000000], + [0.00009963722, 1.61603805646, 76.26607127560], + [0.00009926160, 0.57630380333, 73.29712585900] + ], + [ + [0.00034101978, 0.01321929936, 74.78159856730] + ] + ], + [ + [ + [19.21264847206, 0.00000000000, 0.00000000000], + [0.88784984413, 5.60377527014, 74.78159856730], + [0.03440836062, 0.32836099706, 73.29712585900], + [0.02055653860, 1.78295159330, 149.56319713460], + [0.00649322410, 4.52247285911, 76.26607127560], + [0.00602247865, 3.86003823674, 63.73589830340], + [0.00496404167, 1.40139935333, 454.90936652730], + [0.00338525369, 1.58002770318, 138.51749687070], + [0.00243509114, 1.57086606044, 71.81265315070], + [0.00190522303, 1.99809394714, 1.48447270830], + [0.00161858838, 2.79137786799, 148.07872442630], + [0.00143706183, 1.38368544947, 11.04570026390], + [0.00093192405, 0.17437220467, 36.64856292950], + [0.00071424548, 4.24509236074, 224.34479570190], + [0.00089806014, 3.66105364565, 109.94568878850], + [0.00039009723, 1.66971401684, 70.84944530420], + [0.00046677296, 1.39976401694, 35.16409022120], + [0.00039025624, 3.36234773834, 277.03499374140], + [0.00036755274, 3.88649278513, 146.59425171800], + [0.00030348723, 0.70100838798, 151.04766984290], + [0.00029156413, 3.18056336700, 77.75054398390], + [0.00022637073, 0.72518687029, 529.69096509460], + [0.00011959076, 1.75043392140, 984.60033162190], + [0.00025620756, 5.25656086672, 380.12776796000] + ], + [ + [0.01479896629, 3.67205697578, 74.78159856730] + ] + ] + ], + Neptune: [ + [ + [ + [5.31188633046, 0.00000000000, 0.00000000000], + [0.01798475530, 2.90101273890, 38.13303563780], + [0.01019727652, 0.48580922867, 1.48447270830], + [0.00124531845, 4.83008090676, 36.64856292950], + [0.00042064466, 5.41054993053, 2.96894541660], + [0.00037714584, 6.09221808686, 35.16409022120], + [0.00033784738, 1.24488874087, 76.26607127560], + [0.00016482741, 0.00007727998, 491.55792945680], + [0.00009198584, 4.93747051954, 39.61750834610], + [0.00008994250, 0.27462171806, 175.16605980020] + ], + [ + [38.13303563957, 0.00000000000, 0.00000000000], + [0.00016604172, 4.86323329249, 1.48447270830], + [0.00015744045, 2.27887427527, 38.13303563780] + ] + ], + [ + [ + [0.03088622933, 1.44104372644, 38.13303563780], + [0.00027780087, 5.91271884599, 76.26607127560], + [0.00027623609, 0.00000000000, 0.00000000000], + [0.00015355489, 2.52123799551, 36.64856292950], + [0.00015448133, 3.50877079215, 39.61750834610] + ] + ], + [ + [ + [30.07013205828, 0.00000000000, 0.00000000000], + [0.27062259632, 1.32999459377, 38.13303563780], + [0.01691764014, 3.25186135653, 36.64856292950], + [0.00807830553, 5.18592878704, 1.48447270830], + [0.00537760510, 4.52113935896, 35.16409022120], + [0.00495725141, 1.57105641650, 491.55792945680], + [0.00274571975, 1.84552258866, 175.16605980020], + [0.00012012320, 1.92059384991, 1021.24889455140], + [0.00121801746, 5.79754470298, 76.26607127560], + [0.00100896068, 0.37702724930, 73.29712585900], + [0.00135134092, 3.37220609835, 39.61750834610], + [0.00007571796, 1.07149207335, 388.46515523820] + ] + ] + ] +}; +function DeltaT_EspenakMeeus(ut) { + var u, u2, u3, u4, u5, u6, u7; + /* + Fred Espenak writes about Delta-T generically here: + https://eclipse.gsfc.nasa.gov/SEhelp/deltaT.html + https://eclipse.gsfc.nasa.gov/SEhelp/deltat2004.html + + He provides polynomial approximations for distant years here: + https://eclipse.gsfc.nasa.gov/SEhelp/deltatpoly2004.html + + They start with a year value 'y' such that y=2000 corresponds + to the UTC Date 15-January-2000. Convert difference in days + to mean tropical years. + */ + const y = 2000 + ((ut - 14) / DAYS_PER_TROPICAL_YEAR); + if (y < -500) { + u = (y - 1820) / 100; + return -20 + (32 * u * u); + } + if (y < 500) { + u = y / 100; + u2 = u * u; + u3 = u * u2; + u4 = u2 * u2; + u5 = u2 * u3; + u6 = u3 * u3; + return 10583.6 - 1014.41 * u + 33.78311 * u2 - 5.952053 * u3 - 0.1798452 * u4 + 0.022174192 * u5 + 0.0090316521 * u6; + } + if (y < 1600) { + u = (y - 1000) / 100; + u2 = u * u; + u3 = u * u2; + u4 = u2 * u2; + u5 = u2 * u3; + u6 = u3 * u3; + return 1574.2 - 556.01 * u + 71.23472 * u2 + 0.319781 * u3 - 0.8503463 * u4 - 0.005050998 * u5 + 0.0083572073 * u6; + } + if (y < 1700) { + u = y - 1600; + u2 = u * u; + u3 = u * u2; + return 120 - 0.9808 * u - 0.01532 * u2 + u3 / 7129.0; + } + if (y < 1800) { + u = y - 1700; + u2 = u * u; + u3 = u * u2; + u4 = u2 * u2; + return 8.83 + 0.1603 * u - 0.0059285 * u2 + 0.00013336 * u3 - u4 / 1174000; + } + if (y < 1860) { + u = y - 1800; + u2 = u * u; + u3 = u * u2; + u4 = u2 * u2; + u5 = u2 * u3; + u6 = u3 * u3; + u7 = u3 * u4; + return 13.72 - 0.332447 * u + 0.0068612 * u2 + 0.0041116 * u3 - 0.00037436 * u4 + 0.0000121272 * u5 - 0.0000001699 * u6 + 0.000000000875 * u7; + } + if (y < 1900) { + u = y - 1860; + u2 = u * u; + u3 = u * u2; + u4 = u2 * u2; + u5 = u2 * u3; + return 7.62 + 0.5737 * u - 0.251754 * u2 + 0.01680668 * u3 - 0.0004473624 * u4 + u5 / 233174; + } + if (y < 1920) { + u = y - 1900; + u2 = u * u; + u3 = u * u2; + u4 = u2 * u2; + return -2.79 + 1.494119 * u - 0.0598939 * u2 + 0.0061966 * u3 - 0.000197 * u4; + } + if (y < 1941) { + u = y - 1920; + u2 = u * u; + u3 = u * u2; + return 21.20 + 0.84493 * u - 0.076100 * u2 + 0.0020936 * u3; + } + if (y < 1961) { + u = y - 1950; + u2 = u * u; + u3 = u * u2; + return 29.07 + 0.407 * u - u2 / 233 + u3 / 2547; + } + if (y < 1986) { + u = y - 1975; + u2 = u * u; + u3 = u * u2; + return 45.45 + 1.067 * u - u2 / 260 - u3 / 718; + } + if (y < 2005) { + u = y - 2000; + u2 = u * u; + u3 = u * u2; + u4 = u2 * u2; + u5 = u2 * u3; + return 63.86 + 0.3345 * u - 0.060374 * u2 + 0.0017275 * u3 + 0.000651814 * u4 + 0.00002373599 * u5; + } + if (y < 2050) { + u = y - 2000; + return 62.92 + 0.32217 * u + 0.005589 * u * u; + } + if (y < 2150) { + u = (y - 1820) / 100; + return -20 + 32 * u * u - 0.5628 * (2150 - y); + } + /* all years after 2150 */ + u = (y - 1820) / 100; + return -20 + (32 * u * u); +} +exports.DeltaT_EspenakMeeus = DeltaT_EspenakMeeus; +function DeltaT_JplHorizons(ut) { + return DeltaT_EspenakMeeus(Math.min(ut, 17.0 * DAYS_PER_TROPICAL_YEAR)); +} +exports.DeltaT_JplHorizons = DeltaT_JplHorizons; +let DeltaT = DeltaT_EspenakMeeus; +function SetDeltaTFunction(func) { + DeltaT = func; +} +exports.SetDeltaTFunction = SetDeltaTFunction; +/** + * @ignore + * + * @brief Calculates Terrestrial Time (TT) from Universal Time (UT). + * + * @param {number} ut + * The Universal Time expressed as a floating point number of days since the 2000.0 epoch. + * + * @returns {number} + * A Terrestrial Time expressed as a floating point number of days since the 2000.0 epoch. + */ +function TerrestrialTime(ut) { + return ut + DeltaT(ut) / 86400; +} +/** + * @brief The date and time of an astronomical observation. + * + * Objects of type `AstroTime` are used throughout the internals + * of the Astronomy library, and are included in certain return objects. + * Use the constructor or the {@link MakeTime} function to create an `AstroTime` object. + * + * @property {Date} date + * The JavaScript Date object for the given date and time. + * This Date corresponds to the numeric day value stored in the `ut` property. + * + * @property {number} ut + * Universal Time (UT1/UTC) in fractional days since the J2000 epoch. + * Universal Time represents time measured with respect to the Earth's rotation, + * tracking mean solar days. + * The Astronomy library approximates UT1 and UTC as being the same thing. + * This gives sufficient accuracy for the precision requirements of this project. + * + * @property {number} tt + * Terrestrial Time in fractional days since the J2000 epoch. + * TT represents a continuously flowing ephemeris timescale independent of + * any variations of the Earth's rotation, and is adjusted from UT + * using a best-fit piecewise polynomial model devised by + * [Espenak and Meeus](https://eclipse.gsfc.nasa.gov/SEhelp/deltatpoly2004.html). + */ +class AstroTime { + /** + * @param {FlexibleDateTime} date + * A JavaScript Date object, a numeric UTC value expressed in J2000 days, or another AstroTime object. + */ + constructor(date) { + if (date instanceof AstroTime) { + // Construct a clone of the AstroTime passed in. + this.date = date.date; + this.ut = date.ut; + this.tt = date.tt; + return; + } + const MillisPerDay = 1000 * 3600 * 24; + if ((date instanceof Date) && Number.isFinite(date.getTime())) { + this.date = date; + this.ut = (date.getTime() - J2000.getTime()) / MillisPerDay; + this.tt = TerrestrialTime(this.ut); + return; + } + if (Number.isFinite(date)) { + this.date = new Date(J2000.getTime() + date * MillisPerDay); + this.ut = date; + this.tt = TerrestrialTime(this.ut); + return; + } + throw 'Argument must be a Date object, an AstroTime object, or a numeric UTC Julian date.'; + } + /** + * @brief Creates an `AstroTime` value from a Terrestrial Time (TT) day value. + * + * This function can be used in rare cases where a time must be based + * on Terrestrial Time (TT) rather than Universal Time (UT). + * Most developers will want to invoke `new AstroTime(ut)` with a universal time + * instead of this function, because usually time is based on civil time adjusted + * by leap seconds to match the Earth's rotation, rather than the uniformly + * flowing TT used to calculate solar system dynamics. In rare cases + * where the caller already knows TT, this function is provided to create + * an `AstroTime` value that can be passed to Astronomy Engine functions. + * + * @param {number} tt + * The number of days since the J2000 epoch as expressed in Terrestrial Time. + * + * @returns {AstroTime} + * An `AstroTime` object for the specified terrestrial time. + */ + static FromTerrestrialTime(tt) { + let time = new AstroTime(tt); + for (;;) { + const err = tt - time.tt; + if (Math.abs(err) < 1.0e-12) + return time; + time = time.AddDays(err); + } + } + /** + * Formats an `AstroTime` object as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) + * date/time string in UTC, to millisecond resolution. + * Example: `2018-08-17T17:22:04.050Z` + * @returns {string} + */ + toString() { + return this.date.toISOString(); + } + /** + * Returns a new `AstroTime` object adjusted by the floating point number of days. + * Does NOT modify the original `AstroTime` object. + * + * @param {number} days + * The floating point number of days by which to adjust the given date and time. + * Positive values adjust the date toward the future, and + * negative values adjust the date toward the past. + * + * @returns {AstroTime} + */ + AddDays(days) { + // This is slightly wrong, but the error is tiny. + // We really should be adding to TT, not to UT. + // But using TT would require creating an inverse function for DeltaT, + // which would be quite a bit of extra calculation. + // I estimate the error is in practice on the order of 10^(-7) + // times the value of 'days'. + // This is based on a typical drift of 1 second per year between UT and TT. + return new AstroTime(this.ut + days); + } +} +exports.AstroTime = AstroTime; +function InterpolateTime(time1, time2, fraction) { + return new AstroTime(time1.ut + fraction * (time2.ut - time1.ut)); +} +/** + * @brief A `Date`, `number`, or `AstroTime` value that specifies the date and time of an astronomical event. + * + * `FlexibleDateTime` is a placeholder type that represents three different types + * that may be passed to many Astronomy Engine functions: a JavaScript `Date` object, + * a number representing the real-valued number of UT days since the J2000 epoch, + * or an {@link AstroTime} object. + * + * This flexibility is for convenience of outside callers. + * Internally, Astronomy Engine always converts a `FlexibleDateTime` parameter + * to an `AstroTime` object by calling {@link MakeTime}. + * + * @typedef {Date | number | AstroTime} FlexibleDateTime + */ +/** + * @brief Converts multiple date/time formats to `AstroTime` format. + * + * Given a Date object or a number days since noon (12:00) on January 1, 2000 (UTC), + * this function creates an {@link AstroTime} object. + * + * Given an {@link AstroTime} object, returns the same object unmodified. + * Use of this function is not required for any of the other exposed functions in this library, + * because they all guarantee converting date/time parameters to `AstroTime` + * as needed. However, it may be convenient for callers who need to understand + * the difference between UTC and TT (Terrestrial Time). In some use cases, + * converting once to `AstroTime` format and passing the result into multiple + * function calls may be more efficient than passing in native JavaScript Date objects. + * + * @param {FlexibleDateTime} date + * A Date object, a number of UTC days since the J2000 epoch (noon on January 1, 2000), + * or an AstroTime object. See remarks above. + * + * @returns {AstroTime} + */ +function MakeTime(date) { + if (date instanceof AstroTime) { + return date; + } + return new AstroTime(date); +} +exports.MakeTime = MakeTime; +function iau2000b(time) { + function mod(x) { + return (x % ASEC360) * ASEC2RAD; + } + const t = time.tt / 36525; + const elp = mod(1287104.79305 + t * 129596581.0481); + const f = mod(335779.526232 + t * 1739527262.8478); + const d = mod(1072260.70369 + t * 1602961601.2090); + const om = mod(450160.398036 - t * 6962890.5431); + let sarg = Math.sin(om); + let carg = Math.cos(om); + let dp = (-172064161.0 - 174666.0 * t) * sarg + 33386.0 * carg; + let de = (92052331.0 + 9086.0 * t) * carg + 15377.0 * sarg; + let arg = 2.0 * (f - d + om); + sarg = Math.sin(arg); + carg = Math.cos(arg); + dp += (-13170906.0 - 1675.0 * t) * sarg - 13696.0 * carg; + de += (5730336.0 - 3015.0 * t) * carg - 4587.0 * sarg; + arg = 2.0 * (f + om); + sarg = Math.sin(arg); + carg = Math.cos(arg); + dp += (-2276413.0 - 234.0 * t) * sarg + 2796.0 * carg; + de += (978459.0 - 485.0 * t) * carg + 1374.0 * sarg; + arg = 2.0 * om; + sarg = Math.sin(arg); + carg = Math.cos(arg); + dp += (2074554.0 + 207.0 * t) * sarg - 698.0 * carg; + de += (-897492.0 + 470.0 * t) * carg - 291.0 * sarg; + sarg = Math.sin(elp); + carg = Math.cos(elp); + dp += (1475877.0 - 3633.0 * t) * sarg + 11817.0 * carg; + de += (73871.0 - 184.0 * t) * carg - 1924.0 * sarg; + return { + dpsi: -0.000135 + (dp * 1.0e-7), + deps: +0.000388 + (de * 1.0e-7) + }; +} +function mean_obliq(time) { + var t = time.tt / 36525; + var asec = (((((-0.0000000434 * t + - 0.000000576) * t + + 0.00200340) * t + - 0.0001831) * t + - 46.836769) * t + 84381.406); + return asec / 3600.0; +} +var cache_e_tilt; +function e_tilt(time) { + if (!cache_e_tilt || Math.abs(cache_e_tilt.tt - time.tt) > 1.0e-6) { + const nut = iau2000b(time); + const mean_ob = mean_obliq(time); + const true_ob = mean_ob + (nut.deps / 3600); + cache_e_tilt = { + tt: time.tt, + dpsi: nut.dpsi, + deps: nut.deps, + ee: nut.dpsi * Math.cos(mean_ob * exports.DEG2RAD) / 15, + mobl: mean_ob, + tobl: true_ob + }; + } + return cache_e_tilt; +} +exports.e_tilt = e_tilt; +function obl_ecl2equ_vec(oblDegrees, pos) { + const obl = oblDegrees * exports.DEG2RAD; + const cos_obl = Math.cos(obl); + const sin_obl = Math.sin(obl); + return [ + pos[0], + pos[1] * cos_obl - pos[2] * sin_obl, + pos[1] * sin_obl + pos[2] * cos_obl + ]; +} +function ecl2equ_vec(time, pos) { + return obl_ecl2equ_vec(mean_obliq(time), pos); +} +exports.CalcMoonCount = 0; +function CalcMoon(time) { + ++exports.CalcMoonCount; + const T = time.tt / 36525; + function DeclareArray1(xmin, xmax) { + const array = []; + let i; + for (i = 0; i <= xmax - xmin; ++i) { + array.push(0); + } + return { min: xmin, array: array }; + } + function DeclareArray2(xmin, xmax, ymin, ymax) { + const array = []; + for (let i = 0; i <= xmax - xmin; ++i) { + array.push(DeclareArray1(ymin, ymax)); + } + return { min: xmin, array: array }; + } + function ArrayGet2(a, x, y) { + const m = a.array[x - a.min]; + return m.array[y - m.min]; + } + function ArraySet2(a, x, y, v) { + const m = a.array[x - a.min]; + m.array[y - m.min] = v; + } + let S, MAX, ARG, FAC, I, J, T2, DGAM, DLAM, N, GAM1C, SINPI, L0, L, LS, F, D, DL0, DL, DLS, DF, DD, DS; + let coArray = DeclareArray2(-6, 6, 1, 4); + let siArray = DeclareArray2(-6, 6, 1, 4); + function CO(x, y) { + return ArrayGet2(coArray, x, y); + } + function SI(x, y) { + return ArrayGet2(siArray, x, y); + } + function SetCO(x, y, v) { + return ArraySet2(coArray, x, y, v); + } + function SetSI(x, y, v) { + return ArraySet2(siArray, x, y, v); + } + function AddThe(c1, s1, c2, s2, func) { + func(c1 * c2 - s1 * s2, s1 * c2 + c1 * s2); + } + function Sine(phi) { + return Math.sin(PI2 * phi); + } + T2 = T * T; + DLAM = 0; + DS = 0; + GAM1C = 0; + SINPI = 3422.7000; + var S1 = Sine(0.19833 + 0.05611 * T); + var S2 = Sine(0.27869 + 0.04508 * T); + var S3 = Sine(0.16827 - 0.36903 * T); + var S4 = Sine(0.34734 - 5.37261 * T); + var S5 = Sine(0.10498 - 5.37899 * T); + var S6 = Sine(0.42681 - 0.41855 * T); + var S7 = Sine(0.14943 - 5.37511 * T); + DL0 = 0.84 * S1 + 0.31 * S2 + 14.27 * S3 + 7.26 * S4 + 0.28 * S5 + 0.24 * S6; + DL = 2.94 * S1 + 0.31 * S2 + 14.27 * S3 + 9.34 * S4 + 1.12 * S5 + 0.83 * S6; + DLS = -6.40 * S1 - 1.89 * S6; + DF = 0.21 * S1 + 0.31 * S2 + 14.27 * S3 - 88.70 * S4 - 15.30 * S5 + 0.24 * S6 - 1.86 * S7; + DD = DL0 - DLS; + DGAM = (-3332E-9 * Sine(0.59734 - 5.37261 * T) + - 539E-9 * Sine(0.35498 - 5.37899 * T) + - 64E-9 * Sine(0.39943 - 5.37511 * T)); + L0 = PI2 * Frac(0.60643382 + 1336.85522467 * T - 0.00000313 * T2) + DL0 / ARC; + L = PI2 * Frac(0.37489701 + 1325.55240982 * T + 0.00002565 * T2) + DL / ARC; + LS = PI2 * Frac(0.99312619 + 99.99735956 * T - 0.00000044 * T2) + DLS / ARC; + F = PI2 * Frac(0.25909118 + 1342.22782980 * T - 0.00000892 * T2) + DF / ARC; + D = PI2 * Frac(0.82736186 + 1236.85308708 * T - 0.00000397 * T2) + DD / ARC; + for (I = 1; I <= 4; ++I) { + switch (I) { + case 1: + ARG = L; + MAX = 4; + FAC = 1.000002208; + break; + case 2: + ARG = LS; + MAX = 3; + FAC = 0.997504612 - 0.002495388 * T; + break; + case 3: + ARG = F; + MAX = 4; + FAC = 1.000002708 + 139.978 * DGAM; + break; + case 4: + ARG = D; + MAX = 6; + FAC = 1.0; + break; + default: throw `Internal error: I = ${I}`; // persuade TypeScript that ARG, ... are all initialized before use. + } + SetCO(0, I, 1); + SetCO(1, I, Math.cos(ARG) * FAC); + SetSI(0, I, 0); + SetSI(1, I, Math.sin(ARG) * FAC); + for (J = 2; J <= MAX; ++J) { + AddThe(CO(J - 1, I), SI(J - 1, I), CO(1, I), SI(1, I), (c, s) => (SetCO(J, I, c), SetSI(J, I, s))); + } + for (J = 1; J <= MAX; ++J) { + SetCO(-J, I, CO(J, I)); + SetSI(-J, I, -SI(J, I)); + } + } + function Term(p, q, r, s) { + var result = { x: 1, y: 0 }; + var I = [0, p, q, r, s]; // I[0] is not used; it is a placeholder + for (var k = 1; k <= 4; ++k) + if (I[k] !== 0) + AddThe(result.x, result.y, CO(I[k], k), SI(I[k], k), (c, s) => (result.x = c, result.y = s)); + return result; + } + function AddSol(coeffl, coeffs, coeffg, coeffp, p, q, r, s) { + var result = Term(p, q, r, s); + DLAM += coeffl * result.y; + DS += coeffs * result.y; + GAM1C += coeffg * result.x; + SINPI += coeffp * result.x; + } + AddSol(13.9020, 14.0600, -0.0010, 0.2607, 0, 0, 0, 4); + AddSol(0.4030, -4.0100, 0.3940, 0.0023, 0, 0, 0, 3); + AddSol(2369.9120, 2373.3600, 0.6010, 28.2333, 0, 0, 0, 2); + AddSol(-125.1540, -112.7900, -0.7250, -0.9781, 0, 0, 0, 1); + AddSol(1.9790, 6.9800, -0.4450, 0.0433, 1, 0, 0, 4); + AddSol(191.9530, 192.7200, 0.0290, 3.0861, 1, 0, 0, 2); + AddSol(-8.4660, -13.5100, 0.4550, -0.1093, 1, 0, 0, 1); + AddSol(22639.5000, 22609.0700, 0.0790, 186.5398, 1, 0, 0, 0); + AddSol(18.6090, 3.5900, -0.0940, 0.0118, 1, 0, 0, -1); + AddSol(-4586.4650, -4578.1300, -0.0770, 34.3117, 1, 0, 0, -2); + AddSol(3.2150, 5.4400, 0.1920, -0.0386, 1, 0, 0, -3); + AddSol(-38.4280, -38.6400, 0.0010, 0.6008, 1, 0, 0, -4); + AddSol(-0.3930, -1.4300, -0.0920, 0.0086, 1, 0, 0, -6); + AddSol(-0.2890, -1.5900, 0.1230, -0.0053, 0, 1, 0, 4); + AddSol(-24.4200, -25.1000, 0.0400, -0.3000, 0, 1, 0, 2); + AddSol(18.0230, 17.9300, 0.0070, 0.1494, 0, 1, 0, 1); + AddSol(-668.1460, -126.9800, -1.3020, -0.3997, 0, 1, 0, 0); + AddSol(0.5600, 0.3200, -0.0010, -0.0037, 0, 1, 0, -1); + AddSol(-165.1450, -165.0600, 0.0540, 1.9178, 0, 1, 0, -2); + AddSol(-1.8770, -6.4600, -0.4160, 0.0339, 0, 1, 0, -4); + AddSol(0.2130, 1.0200, -0.0740, 0.0054, 2, 0, 0, 4); + AddSol(14.3870, 14.7800, -0.0170, 0.2833, 2, 0, 0, 2); + AddSol(-0.5860, -1.2000, 0.0540, -0.0100, 2, 0, 0, 1); + AddSol(769.0160, 767.9600, 0.1070, 10.1657, 2, 0, 0, 0); + AddSol(1.7500, 2.0100, -0.0180, 0.0155, 2, 0, 0, -1); + AddSol(-211.6560, -152.5300, 5.6790, -0.3039, 2, 0, 0, -2); + AddSol(1.2250, 0.9100, -0.0300, -0.0088, 2, 0, 0, -3); + AddSol(-30.7730, -34.0700, -0.3080, 0.3722, 2, 0, 0, -4); + AddSol(-0.5700, -1.4000, -0.0740, 0.0109, 2, 0, 0, -6); + AddSol(-2.9210, -11.7500, 0.7870, -0.0484, 1, 1, 0, 2); + AddSol(1.2670, 1.5200, -0.0220, 0.0164, 1, 1, 0, 1); + AddSol(-109.6730, -115.1800, 0.4610, -0.9490, 1, 1, 0, 0); + AddSol(-205.9620, -182.3600, 2.0560, 1.4437, 1, 1, 0, -2); + AddSol(0.2330, 0.3600, 0.0120, -0.0025, 1, 1, 0, -3); + AddSol(-4.3910, -9.6600, -0.4710, 0.0673, 1, 1, 0, -4); + AddSol(0.2830, 1.5300, -0.1110, 0.0060, 1, -1, 0, 4); + AddSol(14.5770, 31.7000, -1.5400, 0.2302, 1, -1, 0, 2); + AddSol(147.6870, 138.7600, 0.6790, 1.1528, 1, -1, 0, 0); + AddSol(-1.0890, 0.5500, 0.0210, 0.0000, 1, -1, 0, -1); + AddSol(28.4750, 23.5900, -0.4430, -0.2257, 1, -1, 0, -2); + AddSol(-0.2760, -0.3800, -0.0060, -0.0036, 1, -1, 0, -3); + AddSol(0.6360, 2.2700, 0.1460, -0.0102, 1, -1, 0, -4); + AddSol(-0.1890, -1.6800, 0.1310, -0.0028, 0, 2, 0, 2); + AddSol(-7.4860, -0.6600, -0.0370, -0.0086, 0, 2, 0, 0); + AddSol(-8.0960, -16.3500, -0.7400, 0.0918, 0, 2, 0, -2); + AddSol(-5.7410, -0.0400, 0.0000, -0.0009, 0, 0, 2, 2); + AddSol(0.2550, 0.0000, 0.0000, 0.0000, 0, 0, 2, 1); + AddSol(-411.6080, -0.2000, 0.0000, -0.0124, 0, 0, 2, 0); + AddSol(0.5840, 0.8400, 0.0000, 0.0071, 0, 0, 2, -1); + AddSol(-55.1730, -52.1400, 0.0000, -0.1052, 0, 0, 2, -2); + AddSol(0.2540, 0.2500, 0.0000, -0.0017, 0, 0, 2, -3); + AddSol(0.0250, -1.6700, 0.0000, 0.0031, 0, 0, 2, -4); + AddSol(1.0600, 2.9600, -0.1660, 0.0243, 3, 0, 0, 2); + AddSol(36.1240, 50.6400, -1.3000, 0.6215, 3, 0, 0, 0); + AddSol(-13.1930, -16.4000, 0.2580, -0.1187, 3, 0, 0, -2); + AddSol(-1.1870, -0.7400, 0.0420, 0.0074, 3, 0, 0, -4); + AddSol(-0.2930, -0.3100, -0.0020, 0.0046, 3, 0, 0, -6); + AddSol(-0.2900, -1.4500, 0.1160, -0.0051, 2, 1, 0, 2); + AddSol(-7.6490, -10.5600, 0.2590, -0.1038, 2, 1, 0, 0); + AddSol(-8.6270, -7.5900, 0.0780, -0.0192, 2, 1, 0, -2); + AddSol(-2.7400, -2.5400, 0.0220, 0.0324, 2, 1, 0, -4); + AddSol(1.1810, 3.3200, -0.2120, 0.0213, 2, -1, 0, 2); + AddSol(9.7030, 11.6700, -0.1510, 0.1268, 2, -1, 0, 0); + AddSol(-0.3520, -0.3700, 0.0010, -0.0028, 2, -1, 0, -1); + AddSol(-2.4940, -1.1700, -0.0030, -0.0017, 2, -1, 0, -2); + AddSol(0.3600, 0.2000, -0.0120, -0.0043, 2, -1, 0, -4); + AddSol(-1.1670, -1.2500, 0.0080, -0.0106, 1, 2, 0, 0); + AddSol(-7.4120, -6.1200, 0.1170, 0.0484, 1, 2, 0, -2); + AddSol(-0.3110, -0.6500, -0.0320, 0.0044, 1, 2, 0, -4); + AddSol(0.7570, 1.8200, -0.1050, 0.0112, 1, -2, 0, 2); + AddSol(2.5800, 2.3200, 0.0270, 0.0196, 1, -2, 0, 0); + AddSol(2.5330, 2.4000, -0.0140, -0.0212, 1, -2, 0, -2); + AddSol(-0.3440, -0.5700, -0.0250, 0.0036, 0, 3, 0, -2); + AddSol(-0.9920, -0.0200, 0.0000, 0.0000, 1, 0, 2, 2); + AddSol(-45.0990, -0.0200, 0.0000, -0.0010, 1, 0, 2, 0); + AddSol(-0.1790, -9.5200, 0.0000, -0.0833, 1, 0, 2, -2); + AddSol(-0.3010, -0.3300, 0.0000, 0.0014, 1, 0, 2, -4); + AddSol(-6.3820, -3.3700, 0.0000, -0.0481, 1, 0, -2, 2); + AddSol(39.5280, 85.1300, 0.0000, -0.7136, 1, 0, -2, 0); + AddSol(9.3660, 0.7100, 0.0000, -0.0112, 1, 0, -2, -2); + AddSol(0.2020, 0.0200, 0.0000, 0.0000, 1, 0, -2, -4); + AddSol(0.4150, 0.1000, 0.0000, 0.0013, 0, 1, 2, 0); + AddSol(-2.1520, -2.2600, 0.0000, -0.0066, 0, 1, 2, -2); + AddSol(-1.4400, -1.3000, 0.0000, 0.0014, 0, 1, -2, 2); + AddSol(0.3840, -0.0400, 0.0000, 0.0000, 0, 1, -2, -2); + AddSol(1.9380, 3.6000, -0.1450, 0.0401, 4, 0, 0, 0); + AddSol(-0.9520, -1.5800, 0.0520, -0.0130, 4, 0, 0, -2); + AddSol(-0.5510, -0.9400, 0.0320, -0.0097, 3, 1, 0, 0); + AddSol(-0.4820, -0.5700, 0.0050, -0.0045, 3, 1, 0, -2); + AddSol(0.6810, 0.9600, -0.0260, 0.0115, 3, -1, 0, 0); + AddSol(-0.2970, -0.2700, 0.0020, -0.0009, 2, 2, 0, -2); + AddSol(0.2540, 0.2100, -0.0030, 0.0000, 2, -2, 0, -2); + AddSol(-0.2500, -0.2200, 0.0040, 0.0014, 1, 3, 0, -2); + AddSol(-3.9960, 0.0000, 0.0000, 0.0004, 2, 0, 2, 0); + AddSol(0.5570, -0.7500, 0.0000, -0.0090, 2, 0, 2, -2); + AddSol(-0.4590, -0.3800, 0.0000, -0.0053, 2, 0, -2, 2); + AddSol(-1.2980, 0.7400, 0.0000, 0.0004, 2, 0, -2, 0); + AddSol(0.5380, 1.1400, 0.0000, -0.0141, 2, 0, -2, -2); + AddSol(0.2630, 0.0200, 0.0000, 0.0000, 1, 1, 2, 0); + AddSol(0.4260, 0.0700, 0.0000, -0.0006, 1, 1, -2, -2); + AddSol(-0.3040, 0.0300, 0.0000, 0.0003, 1, -1, 2, 0); + AddSol(-0.3720, -0.1900, 0.0000, -0.0027, 1, -1, -2, 2); + AddSol(0.4180, 0.0000, 0.0000, 0.0000, 0, 0, 4, 0); + AddSol(-0.3300, -0.0400, 0.0000, 0.0000, 3, 0, 2, 0); + function ADDN(coeffn, p, q, r, s) { + return coeffn * Term(p, q, r, s).y; + } + N = 0; + N += ADDN(-526.069, 0, 0, 1, -2); + N += ADDN(-3.352, 0, 0, 1, -4); + N += ADDN(+44.297, +1, 0, 1, -2); + N += ADDN(-6.000, +1, 0, 1, -4); + N += ADDN(+20.599, -1, 0, 1, 0); + N += ADDN(-30.598, -1, 0, 1, -2); + N += ADDN(-24.649, -2, 0, 1, 0); + N += ADDN(-2.000, -2, 0, 1, -2); + N += ADDN(-22.571, 0, +1, 1, -2); + N += ADDN(+10.985, 0, -1, 1, -2); + DLAM += (+0.82 * Sine(0.7736 - 62.5512 * T) + 0.31 * Sine(0.0466 - 125.1025 * T) + + 0.35 * Sine(0.5785 - 25.1042 * T) + 0.66 * Sine(0.4591 + 1335.8075 * T) + + 0.64 * Sine(0.3130 - 91.5680 * T) + 1.14 * Sine(0.1480 + 1331.2898 * T) + + 0.21 * Sine(0.5918 + 1056.5859 * T) + 0.44 * Sine(0.5784 + 1322.8595 * T) + + 0.24 * Sine(0.2275 - 5.7374 * T) + 0.28 * Sine(0.2965 + 2.6929 * T) + + 0.33 * Sine(0.3132 + 6.3368 * T)); + S = F + DS / ARC; + let lat_seconds = (1.000002708 + 139.978 * DGAM) * (18518.511 + 1.189 + GAM1C) * Math.sin(S) - 6.24 * Math.sin(3 * S) + N; + return { + geo_eclip_lon: PI2 * Frac((L0 + DLAM / ARC) / PI2), + geo_eclip_lat: (Math.PI / (180 * 3600)) * lat_seconds, + distance_au: (ARC * EARTH_EQUATORIAL_RADIUS_AU) / (0.999953253 * SINPI) + }; +} +/** + * @brief Lunar libration angles, returned by {@link Libration}. + * + * @property {number} elat + * Sub-Earth libration ecliptic latitude angle, in degrees. + * @property {number} elon + * Sub-Earth libration ecliptic longitude angle, in degrees. + * @property {number} mlat + * Moon's geocentric ecliptic latitude, in degrees. + * @property {number} mlon + * Moon's geocentric ecliptic longitude, in degrees. + * @property {number} dist_km + * Distance between the centers of the Earth and Moon in kilometers. + * @property {number} diam_deg + * The apparent angular diameter of the Moon, in degrees, as seen from the center of the Earth. + */ +class LibrationInfo { + constructor(elat, elon, mlat, mlon, dist_km, diam_deg) { + this.elat = elat; + this.elon = elon; + this.mlat = mlat; + this.mlon = mlon; + this.dist_km = dist_km; + this.diam_deg = diam_deg; + } +} +exports.LibrationInfo = LibrationInfo; +/** + * @brief Calculates the Moon's libration angles at a given moment in time. + * + * Libration is an observed back-and-forth wobble of the portion of the + * Moon visible from the Earth. It is caused by the imperfect tidal locking + * of the Moon's fixed rotation rate, compared to its variable angular speed + * of orbit around the Earth. + * + * This function calculates a pair of perpendicular libration angles, + * one representing rotation of the Moon in ecliptic longitude `elon`, the other + * in ecliptic latitude `elat`, both relative to the Moon's mean Earth-facing position. + * + * This function also returns the geocentric position of the Moon + * expressed in ecliptic longitude `mlon`, ecliptic latitude `mlat`, the + * distance `dist_km` between the centers of the Earth and Moon expressed in kilometers, + * and the apparent angular diameter of the Moon `diam_deg`. + * + * @param {FlexibleDateTime} date + * A Date object, a number of UTC days since the J2000 epoch (noon on January 1, 2000), + * or an AstroTime object. + * + * @returns {LibrationInfo} + */ +function Libration(date) { + const time = MakeTime(date); + const t = time.tt / 36525.0; + const t2 = t * t; + const t3 = t2 * t; + const t4 = t2 * t2; + const moon = CalcMoon(time); + const mlon = moon.geo_eclip_lon; + const mlat = moon.geo_eclip_lat; + const dist_km = moon.distance_au * exports.KM_PER_AU; + // Inclination angle + const I = exports.DEG2RAD * 1.543; + // Moon's argument of latitude in radians. + const f = exports.DEG2RAD * NormalizeLongitude(93.2720950 + 483202.0175233 * t - 0.0036539 * t2 - t3 / 3526000 + t4 / 863310000); + // Moon's ascending node's mean longitude in radians. + const omega = exports.DEG2RAD * NormalizeLongitude(125.0445479 - 1934.1362891 * t + 0.0020754 * t2 + t3 / 467441 - t4 / 60616000); + // Sun's mean anomaly. + const m = exports.DEG2RAD * NormalizeLongitude(357.5291092 + 35999.0502909 * t - 0.0001536 * t2 + t3 / 24490000); + // Moon's mean anomaly. + const mdash = exports.DEG2RAD * NormalizeLongitude(134.9633964 + 477198.8675055 * t + 0.0087414 * t2 + t3 / 69699 - t4 / 14712000); + // Moon's mean elongation. + const d = exports.DEG2RAD * NormalizeLongitude(297.8501921 + 445267.1114034 * t - 0.0018819 * t2 + t3 / 545868 - t4 / 113065000); + // Eccentricity of the Earth's orbit. + const e = 1.0 - 0.002516 * t - 0.0000074 * t2; + // Optical librations + const w = mlon - omega; + const a = Math.atan2(Math.sin(w) * Math.cos(mlat) * Math.cos(I) - Math.sin(mlat) * Math.sin(I), Math.cos(w) * Math.cos(mlat)); + const ldash = LongitudeOffset(exports.RAD2DEG * (a - f)); + const bdash = Math.asin(-Math.sin(w) * Math.cos(mlat) * Math.sin(I) - Math.sin(mlat) * Math.cos(I)); + // Physical librations + const k1 = exports.DEG2RAD * (119.75 + 131.849 * t); + const k2 = exports.DEG2RAD * (72.56 + 20.186 * t); + const rho = (-0.02752 * Math.cos(mdash) + + -0.02245 * Math.sin(f) + + +0.00684 * Math.cos(mdash - 2 * f) + + -0.00293 * Math.cos(2 * f) + + -0.00085 * Math.cos(2 * f - 2 * d) + + -0.00054 * Math.cos(mdash - 2 * d) + + -0.00020 * Math.sin(mdash + f) + + -0.00020 * Math.cos(mdash + 2 * f) + + -0.00020 * Math.cos(mdash - f) + + +0.00014 * Math.cos(mdash + 2 * f - 2 * d)); + const sigma = (-0.02816 * Math.sin(mdash) + + +0.02244 * Math.cos(f) + + -0.00682 * Math.sin(mdash - 2 * f) + + -0.00279 * Math.sin(2 * f) + + -0.00083 * Math.sin(2 * f - 2 * d) + + +0.00069 * Math.sin(mdash - 2 * d) + + +0.00040 * Math.cos(mdash + f) + + -0.00025 * Math.sin(2 * mdash) + + -0.00023 * Math.sin(mdash + 2 * f) + + +0.00020 * Math.cos(mdash - f) + + +0.00019 * Math.sin(mdash - f) + + +0.00013 * Math.sin(mdash + 2 * f - 2 * d) + + -0.00010 * Math.cos(mdash - 3 * f)); + const tau = (+0.02520 * e * Math.sin(m) + + +0.00473 * Math.sin(2 * mdash - 2 * f) + + -0.00467 * Math.sin(mdash) + + +0.00396 * Math.sin(k1) + + +0.00276 * Math.sin(2 * mdash - 2 * d) + + +0.00196 * Math.sin(omega) + + -0.00183 * Math.cos(mdash - f) + + +0.00115 * Math.sin(mdash - 2 * d) + + -0.00096 * Math.sin(mdash - d) + + +0.00046 * Math.sin(2 * f - 2 * d) + + -0.00039 * Math.sin(mdash - f) + + -0.00032 * Math.sin(mdash - m - d) + + +0.00027 * Math.sin(2 * mdash - m - 2 * d) + + +0.00023 * Math.sin(k2) + + -0.00014 * Math.sin(2 * d) + + +0.00014 * Math.cos(2 * mdash - 2 * f) + + -0.00012 * Math.sin(mdash - 2 * f) + + -0.00012 * Math.sin(2 * mdash) + + +0.00011 * Math.sin(2 * mdash - 2 * m - 2 * d)); + const ldash2 = -tau + (rho * Math.cos(a) + sigma * Math.sin(a)) * Math.tan(bdash); + const bdash2 = sigma * Math.cos(a) - rho * Math.sin(a); + const diam_deg = 2.0 * exports.RAD2DEG * Math.atan(MOON_MEAN_RADIUS_KM / Math.sqrt(dist_km * dist_km - MOON_MEAN_RADIUS_KM * MOON_MEAN_RADIUS_KM)); + return new LibrationInfo(exports.RAD2DEG * bdash + bdash2, ldash + ldash2, exports.RAD2DEG * mlat, exports.RAD2DEG * mlon, dist_km, diam_deg); +} +exports.Libration = Libration; +function rotate(rot, vec) { + return [ + rot.rot[0][0] * vec[0] + rot.rot[1][0] * vec[1] + rot.rot[2][0] * vec[2], + rot.rot[0][1] * vec[0] + rot.rot[1][1] * vec[1] + rot.rot[2][1] * vec[2], + rot.rot[0][2] * vec[0] + rot.rot[1][2] * vec[1] + rot.rot[2][2] * vec[2] + ]; +} +function precession(pos, time, dir) { + const r = precession_rot(time, dir); + return rotate(r, pos); +} +function precession_posvel(state, time, dir) { + const r = precession_rot(time, dir); + return RotateState(r, state); +} +function precession_rot(time, dir) { + const t = time.tt / 36525; + let eps0 = 84381.406; + let psia = (((((-0.0000000951 * t + + 0.000132851) * t + - 0.00114045) * t + - 1.0790069) * t + + 5038.481507) * t); + let omegaa = (((((+0.0000003337 * t + - 0.000000467) * t + - 0.00772503) * t + + 0.0512623) * t + - 0.025754) * t + eps0); + let chia = (((((-0.0000000560 * t + + 0.000170663) * t + - 0.00121197) * t + - 2.3814292) * t + + 10.556403) * t); + eps0 *= ASEC2RAD; + psia *= ASEC2RAD; + omegaa *= ASEC2RAD; + chia *= ASEC2RAD; + const sa = Math.sin(eps0); + const ca = Math.cos(eps0); + const sb = Math.sin(-psia); + const cb = Math.cos(-psia); + const sc = Math.sin(-omegaa); + const cc = Math.cos(-omegaa); + const sd = Math.sin(chia); + const cd = Math.cos(chia); + const xx = cd * cb - sb * sd * cc; + const yx = cd * sb * ca + sd * cc * cb * ca - sa * sd * sc; + const zx = cd * sb * sa + sd * cc * cb * sa + ca * sd * sc; + const xy = -sd * cb - sb * cd * cc; + const yy = -sd * sb * ca + cd * cc * cb * ca - sa * cd * sc; + const zy = -sd * sb * sa + cd * cc * cb * sa + ca * cd * sc; + const xz = sb * sc; + const yz = -sc * cb * ca - sa * cc; + const zz = -sc * cb * sa + cc * ca; + if (dir === PrecessDirection.Into2000) { + // Perform rotation from epoch to J2000.0. + return new RotationMatrix([ + [xx, yx, zx], + [xy, yy, zy], + [xz, yz, zz] + ]); + } + if (dir === PrecessDirection.From2000) { + // Perform rotation from J2000.0 to epoch. + return new RotationMatrix([ + [xx, xy, xz], + [yx, yy, yz], + [zx, zy, zz] + ]); + } + throw 'Invalid precess direction'; +} +function era(time) { + const thet1 = 0.7790572732640 + 0.00273781191135448 * time.ut; + const thet3 = time.ut % 1; + let theta = 360 * ((thet1 + thet3) % 1); + if (theta < 0) { + theta += 360; + } + return theta; +} +let sidereal_time_cache; +function sidereal_time(time) { + if (!sidereal_time_cache || sidereal_time_cache.tt !== time.tt) { + const t = time.tt / 36525; + let eqeq = 15 * e_tilt(time).ee; // Replace with eqeq=0 to get GMST instead of GAST (if we ever need it) + const theta = era(time); + const st = (eqeq + 0.014506 + + ((((-0.0000000368 * t + - 0.000029956) * t + - 0.00000044) * t + + 1.3915817) * t + + 4612.156534) * t); + let gst = ((st / 3600 + theta) % 360) / 15; + if (gst < 0) { + gst += 24; + } + sidereal_time_cache = { + tt: time.tt, + st: gst + }; + } + return sidereal_time_cache.st; // return sidereal hours in the half-open range [0, 24). +} +/** + * @brief Calculates Greenwich Apparent Sidereal Time (GAST). + * + * Given a date and time, this function calculates the rotation of the + * Earth, represented by the equatorial angle of the Greenwich prime meridian + * with respect to distant stars (not the Sun, which moves relative to background + * stars by almost one degree per day). + * This angle is called Greenwich Apparent Sidereal Time (GAST). + * GAST is measured in sidereal hours in the half-open range [0, 24). + * When GAST = 0, it means the prime meridian is aligned with the of-date equinox, + * corrected at that time for precession and nutation of the Earth's axis. + * In this context, the "equinox" is the direction in space where the Earth's + * orbital plane (the ecliptic) intersects with the plane of the Earth's equator, + * at the location on the Earth's orbit of the (seasonal) March equinox. + * As the Earth rotates, GAST increases from 0 up to 24 sidereal hours, + * then starts over at 0. + * To convert to degrees, multiply the return value by 15. + * + * @param {FlexibleDateTime} date + * The date and time for which to find GAST. + * + * @returns {number} + */ +function SiderealTime(date) { + const time = MakeTime(date); + return sidereal_time(time); +} +exports.SiderealTime = SiderealTime; +function inverse_terra(ovec, st) { + // Convert from AU to kilometers + const x = ovec[0] * exports.KM_PER_AU; + const y = ovec[1] * exports.KM_PER_AU; + const z = ovec[2] * exports.KM_PER_AU; + const p = Math.hypot(x, y); + let lon_deg, lat_deg, height_km; + if (p < 1.0e-6) { + // Special case: within 1 millimeter of a pole! + // Use arbitrary longitude, and latitude determined by polarity of z. + lon_deg = 0; + lat_deg = (z > 0.0) ? +90 : -90; + // Elevation is calculated directly from z. + height_km = Math.abs(z) - EARTH_POLAR_RADIUS_KM; + } + else { + const stlocl = Math.atan2(y, x); + // Calculate exact longitude. + lon_deg = (exports.RAD2DEG * stlocl) - (15.0 * st); + // Normalize longitude to the range (-180, +180]. + while (lon_deg <= -180) + lon_deg += 360; + while (lon_deg > +180) + lon_deg -= 360; + // Numerically solve for exact latitude, using Newton's Method. + // Start with initial latitude estimate, based on a spherical Earth. + let lat = Math.atan2(z, p); + let cos, sin, denom; + let count = 0; + for (;;) { + if (++count > 10) + throw `inverse_terra failed to converge.`; + // Calculate the error function W(lat). + // We try to find the root of W, meaning where the error is 0. + cos = Math.cos(lat); + sin = Math.sin(lat); + const factor = (EARTH_FLATTENING_SQUARED - 1) * EARTH_EQUATORIAL_RADIUS_KM; + const cos2 = cos * cos; + const sin2 = sin * sin; + const radicand = cos2 + EARTH_FLATTENING_SQUARED * sin2; + denom = Math.sqrt(radicand); + const W = (factor * sin * cos) / denom - z * cos + p * sin; + if (Math.abs(W) < 1.0e-8) + break; // The error is now negligible + // Error is still too large. Find the next estimate. + // Calculate D = the derivative of W with respect to lat. + const D = factor * ((cos2 - sin2) / denom - sin2 * cos2 * (EARTH_FLATTENING_SQUARED - 1) / (factor * radicand)) + z * sin + p * cos; + lat -= W / D; + } + // We now have a solution for the latitude in radians. + lat_deg = exports.RAD2DEG * lat; + // Solve for exact height in meters. + // There are two formulas I can use. Use whichever has the less risky denominator. + const adjust = EARTH_EQUATORIAL_RADIUS_KM / denom; + if (Math.abs(sin) > Math.abs(cos)) + height_km = z / sin - EARTH_FLATTENING_SQUARED * adjust; + else + height_km = p / cos - adjust; + } + return new Observer(lat_deg, lon_deg, 1000 * height_km); +} +function terra(observer, st) { + const phi = observer.latitude * exports.DEG2RAD; + const sinphi = Math.sin(phi); + const cosphi = Math.cos(phi); + const c = 1 / Math.hypot(cosphi, EARTH_FLATTENING * sinphi); + const s = EARTH_FLATTENING_SQUARED * c; + const ht_km = observer.height / 1000; + const ach = EARTH_EQUATORIAL_RADIUS_KM * c + ht_km; + const ash = EARTH_EQUATORIAL_RADIUS_KM * s + ht_km; + const stlocl = (15 * st + observer.longitude) * exports.DEG2RAD; + const sinst = Math.sin(stlocl); + const cosst = Math.cos(stlocl); + return { + pos: [ach * cosphi * cosst / exports.KM_PER_AU, ach * cosphi * sinst / exports.KM_PER_AU, ash * sinphi / exports.KM_PER_AU], + vel: [-ANGVEL * ach * cosphi * sinst * 86400 / exports.KM_PER_AU, ANGVEL * ach * cosphi * cosst * 86400 / exports.KM_PER_AU, 0] + }; +} +function nutation(pos, time, dir) { + const r = nutation_rot(time, dir); + return rotate(r, pos); +} +function nutation_posvel(state, time, dir) { + const r = nutation_rot(time, dir); + return RotateState(r, state); +} +function nutation_rot(time, dir) { + const tilt = e_tilt(time); + const oblm = tilt.mobl * exports.DEG2RAD; + const oblt = tilt.tobl * exports.DEG2RAD; + const psi = tilt.dpsi * ASEC2RAD; + const cobm = Math.cos(oblm); + const sobm = Math.sin(oblm); + const cobt = Math.cos(oblt); + const sobt = Math.sin(oblt); + const cpsi = Math.cos(psi); + const spsi = Math.sin(psi); + const xx = cpsi; + const yx = -spsi * cobm; + const zx = -spsi * sobm; + const xy = spsi * cobt; + const yy = cpsi * cobm * cobt + sobm * sobt; + const zy = cpsi * sobm * cobt - cobm * sobt; + const xz = spsi * sobt; + const yz = cpsi * cobm * sobt - sobm * cobt; + const zz = cpsi * sobm * sobt + cobm * cobt; + if (dir === PrecessDirection.From2000) { + // convert J2000 to of-date + return new RotationMatrix([ + [xx, xy, xz], + [yx, yy, yz], + [zx, zy, zz] + ]); + } + if (dir === PrecessDirection.Into2000) { + // convert of-date to J2000 + return new RotationMatrix([ + [xx, yx, zx], + [xy, yy, zy], + [xz, yz, zz] + ]); + } + throw 'Invalid precess direction'; +} +function gyration(pos, time, dir) { + // Combine nutation and precession into a single operation I call "gyration". + // The order they are composed depends on the direction, + // because both directions are mutual inverse functions. + return (dir === PrecessDirection.Into2000) ? + precession(nutation(pos, time, dir), time, dir) : + nutation(precession(pos, time, dir), time, dir); +} +function gyration_posvel(state, time, dir) { + // Combine nutation and precession into a single operation I call "gyration". + // The order they are composed depends on the direction, + // because both directions are mutual inverse functions. + return (dir === PrecessDirection.Into2000) ? + precession_posvel(nutation_posvel(state, time, dir), time, dir) : + nutation_posvel(precession_posvel(state, time, dir), time, dir); +} +function geo_pos(time, observer) { + const gast = sidereal_time(time); + const pos = terra(observer, gast).pos; + return gyration(pos, time, PrecessDirection.Into2000); +} +/** + * @brief A 3D Cartesian vector with a time attached to it. + * + * Holds the Cartesian coordinates of a vector in 3D space, + * along with the time at which the vector is valid. + * + * @property {number} x The x-coordinate expressed in astronomical units (AU). + * @property {number} y The y-coordinate expressed in astronomical units (AU). + * @property {number} z The z-coordinate expressed in astronomical units (AU). + * @property {AstroTime} t The time at which the vector is valid. + */ +class Vector { + constructor(x, y, z, t) { + this.x = x; + this.y = y; + this.z = z; + this.t = t; + } + /** + * Returns the length of the vector in astronomical units (AU). + * @returns {number} + */ + Length() { + return Math.hypot(this.x, this.y, this.z); + } +} +exports.Vector = Vector; +/** + * @brief A combination of a position vector, a velocity vector, and a time. + * + * Holds the state vector of a body at a given time, including its position, + * velocity, and the time they are valid. + * + * @property {number} x The position x-coordinate expressed in astronomical units (AU). + * @property {number} y The position y-coordinate expressed in astronomical units (AU). + * @property {number} z The position z-coordinate expressed in astronomical units (AU). + * @property {number} vx The velocity x-coordinate expressed in AU/day. + * @property {number} vy The velocity y-coordinate expressed in AU/day. + * @property {number} vz The velocity z-coordinate expressed in AU/day. + * @property {AstroTime} t The time at which the vector is valid. + */ +class StateVector { + constructor(x, y, z, vx, vy, vz, t) { + this.x = x; + this.y = y; + this.z = z; + this.vx = vx; + this.vy = vy; + this.vz = vz; + this.t = t; + } +} +exports.StateVector = StateVector; +/** + * @brief Holds spherical coordinates: latitude, longitude, distance. + * + * Spherical coordinates represent the location of + * a point using two angles and a distance. + * + * @property {number} lat The latitude angle: -90..+90 degrees. + * @property {number} lon The longitude angle: 0..360 degrees. + * @property {number} dist Distance in AU. + */ +class Spherical { + constructor(lat, lon, dist) { + this.lat = VerifyNumber(lat); + this.lon = VerifyNumber(lon); + this.dist = VerifyNumber(dist); + } +} +exports.Spherical = Spherical; +/** + * @brief Holds right ascension, declination, and distance of a celestial object. + * + * @property {number} ra + * Right ascension in sidereal hours: [0, 24). + * + * @property {number} dec + * Declination in degrees: [-90, +90]. + * + * @property {number} dist + * Distance to the celestial object expressed in + * astronomical units (AU). + * + * @property {Vector} vec + * The equatorial coordinates in cartesian form, using AU distance units. + * x = direction of the March equinox, + * y = direction of the June solstice, + * z = north. + */ +class EquatorialCoordinates { + constructor(ra, dec, dist, vec) { + this.ra = VerifyNumber(ra); + this.dec = VerifyNumber(dec); + this.dist = VerifyNumber(dist); + this.vec = vec; + } +} +exports.EquatorialCoordinates = EquatorialCoordinates; +function IsValidRotationArray(rot) { + if (!(rot instanceof Array) || (rot.length !== 3)) + return false; + for (let i = 0; i < 3; ++i) { + if (!(rot[i] instanceof Array) || (rot[i].length !== 3)) + return false; + for (let j = 0; j < 3; ++j) + if (!Number.isFinite(rot[i][j])) + return false; + } + return true; +} +/** + * @brief Contains a rotation matrix that can be used to transform one coordinate system to another. + * + * @property {number[][]} rot + * A normalized 3x3 rotation matrix. For example, the identity matrix is represented + * as `[[1, 0, 0], [0, 1, 0], [0, 0, 1]]`. + */ +class RotationMatrix { + constructor(rot) { + this.rot = rot; + } +} +exports.RotationMatrix = RotationMatrix; +/** + * @brief Creates a rotation matrix that can be used to transform one coordinate system to another. + * + * This function verifies that the `rot` parameter is of the correct format: + * a number[3][3] array. It throws an exception if `rot` is not of that shape. + * Otherwise it creates a new {@link RotationMatrix} object based on `rot`. + * + * @param {number[][]} rot + * An array [3][3] of numbers. Defines a rotation matrix used to premultiply + * a 3D vector to reorient it into another coordinate system. + * + * @returns {RotationMatrix} + */ +function MakeRotation(rot) { + if (!IsValidRotationArray(rot)) + throw 'Argument must be a [3][3] array of numbers'; + return new RotationMatrix(rot); +} +exports.MakeRotation = MakeRotation; +/** + * @brief Represents the location of an object seen by an observer on the Earth. + * + * Holds azimuth (compass direction) and altitude (angle above/below the horizon) + * of a celestial object as seen by an observer at a particular location on the Earth's surface. + * Also holds right ascension and declination of the same object. + * All of these coordinates are optionally adjusted for atmospheric refraction; + * therefore the right ascension and declination values may not exactly match + * those found inside a corresponding {@link EquatorialCoordinates} object. + * + * @property {number} azimuth + * A horizontal compass direction angle in degrees measured starting at north + * and increasing positively toward the east. + * The value is in the range [0, 360). + * North = 0, east = 90, south = 180, west = 270. + * + * @property {number} altitude + * A vertical angle in degrees above (positive) or below (negative) the horizon. + * The value is in the range [-90, +90]. + * The altitude angle is optionally adjusted upward due to atmospheric refraction. + * + * @property {number} ra + * The right ascension of the celestial body in sidereal hours. + * The value is in the reange [0, 24). + * If `altitude` was adjusted for atmospheric reaction, `ra` + * is likewise adjusted. + * + * @property {number} dec + * The declination of of the celestial body in degrees. + * The value in the range [-90, +90]. + * If `altitude` was adjusted for atmospheric reaction, `dec` + * is likewise adjusted. + */ +class HorizontalCoordinates { + constructor(azimuth, altitude, ra, dec) { + this.azimuth = VerifyNumber(azimuth); + this.altitude = VerifyNumber(altitude); + this.ra = VerifyNumber(ra); + this.dec = VerifyNumber(dec); + } +} +exports.HorizontalCoordinates = HorizontalCoordinates; +/** + * @brief Ecliptic coordinates of a celestial body. + * + * The origin and date of the coordinate system may vary depending on the caller's usage. + * In general, ecliptic coordinates are measured with respect to the mean plane of the Earth's + * orbit around the Sun. + * Includes Cartesian coordinates `(ex, ey, ez)` measured in + * astronomical units (AU) + * and spherical coordinates `(elon, elat)` measured in degrees. + * + * @property {Vector} vec + * Ecliptic cartesian vector with components measured in astronomical units (AU). + * The x-axis is within the ecliptic plane and is oriented in the direction of the + * equinox. + * The y-axis is within the ecliptic plane and is oriented 90 degrees + * counterclockwise from the equinox, as seen from above the Sun's north pole. + * The z-axis is oriented perpendicular to the ecliptic plane, + * along the direction of the Sun's north pole. + * + * @property {number} elat + * The ecliptic latitude of the body in degrees. + * This is the angle north or south of the ecliptic plane. + * The value is in the range [-90, +90]. + * Positive values are north and negative values are south. + * + * @property {number} elon + * The ecliptic longitude of the body in degrees. + * This is the angle measured counterclockwise around the ecliptic plane, + * as seen from above the Sun's north pole. + * This is the same direction that the Earth orbits around the Sun. + * The angle is measured starting at 0 from the equinox and increases + * up to 360 degrees. + */ +class EclipticCoordinates { + constructor(vec, elat, elon) { + this.vec = vec; + this.elat = VerifyNumber(elat); + this.elon = VerifyNumber(elon); + } +} +exports.EclipticCoordinates = EclipticCoordinates; +function VectorFromArray(av, time) { + return new Vector(av[0], av[1], av[2], time); +} +function vector2radec(pos, time) { + const vec = VectorFromArray(pos, time); + const xyproj = vec.x * vec.x + vec.y * vec.y; + const dist = Math.sqrt(xyproj + vec.z * vec.z); + if (xyproj === 0) { + if (vec.z === 0) + throw 'Indeterminate sky coordinates'; + return new EquatorialCoordinates(0, (vec.z < 0) ? -90 : +90, dist, vec); + } + let ra = exports.RAD2HOUR * Math.atan2(vec.y, vec.x); + if (ra < 0) + ra += 24; + const dec = exports.RAD2DEG * Math.atan2(pos[2], Math.sqrt(xyproj)); + return new EquatorialCoordinates(ra, dec, dist, vec); +} +function spin(angle, pos) { + const angr = angle * exports.DEG2RAD; + const c = Math.cos(angr); + const s = Math.sin(angr); + return [c * pos[0] + s * pos[1], c * pos[1] - s * pos[0], pos[2]]; +} +/** + * @brief Converts equatorial coordinates to horizontal coordinates. + * + * Given a date and time, a geographic location of an observer on the Earth, and + * equatorial coordinates (right ascension and declination) of a celestial body, + * returns horizontal coordinates (azimuth and altitude angles) for that body + * as seen by that observer. Allows optional correction for atmospheric refraction. + * + * @param {FlexibleDateTime} date + * The date and time for which to find horizontal coordinates. + * + * @param {Observer} observer + * The location of the observer for which to find horizontal coordinates. + * + * @param {number} ra + * Right ascension in sidereal hours of the celestial object, + * referred to the mean equinox of date for the J2000 epoch. + * + * @param {number} dec + * Declination in degrees of the celestial object, + * referred to the mean equator of date for the J2000 epoch. + * Positive values are north of the celestial equator and negative values are south. + * + * @param {string} refraction + * If omitted or has a false-like value (false, null, undefined, etc.) + * the calculations are performed without any correction for atmospheric + * refraction. If the value is the string `"normal"`, + * uses the recommended refraction correction based on Meeus "Astronomical Algorithms" + * with a linear taper more than 1 degree below the horizon. The linear + * taper causes the refraction to linearly approach 0 as the altitude of the + * body approaches the nadir (-90 degrees). + * If the value is the string `"jplhor"`, uses a JPL Horizons + * compatible formula. This is the same algorithm as `"normal"`, + * only without linear tapering; this can result in physically impossible + * altitudes of less than -90 degrees, which may cause problems for some applications. + * (The `"jplhor"` option was created for unit testing against data + * generated by JPL Horizons, and is otherwise not recommended for use.) + * + * @returns {HorizontalCoordinates} + */ +function Horizon(date, observer, ra, dec, refraction) { + // based on NOVAS equ2hor() + let time = MakeTime(date); + VerifyObserver(observer); + VerifyNumber(ra); + VerifyNumber(dec); + const sinlat = Math.sin(observer.latitude * exports.DEG2RAD); + const coslat = Math.cos(observer.latitude * exports.DEG2RAD); + const sinlon = Math.sin(observer.longitude * exports.DEG2RAD); + const coslon = Math.cos(observer.longitude * exports.DEG2RAD); + const sindc = Math.sin(dec * exports.DEG2RAD); + const cosdc = Math.cos(dec * exports.DEG2RAD); + const sinra = Math.sin(ra * exports.HOUR2RAD); + const cosra = Math.cos(ra * exports.HOUR2RAD); + // Calculate three mutually perpendicular unit vectors + // in equatorial coordinates: uze, une, uwe. + // + // uze = The direction of the observer's local zenith (straight up). + // une = The direction toward due north on the observer's horizon. + // uwe = The direction toward due west on the observer's horizon. + // + // HOWEVER, these are uncorrected for the Earth's rotation due to the time of day. + // + // The components of these 3 vectors are as follows: + // x = direction from center of Earth toward 0 degrees longitude (the prime meridian) on equator. + // y = direction from center of Earth toward 90 degrees west longitude on equator. + // z = direction from center of Earth toward the north pole. + let uze = [coslat * coslon, coslat * sinlon, sinlat]; + let une = [-sinlat * coslon, -sinlat * sinlon, coslat]; + let uwe = [sinlon, -coslon, 0]; + // Correct the vectors uze, une, uwe for the Earth's rotation by calculating + // sidereal time. Call spin() for each uncorrected vector to rotate about + // the Earth's axis to yield corrected unit vectors uz, un, uw. + // Multiply sidereal hours by -15 to convert to degrees and flip eastward + // rotation of the Earth to westward apparent movement of objects with time. + const spin_angle = -15 * sidereal_time(time); + let uz = spin(spin_angle, uze); + let un = spin(spin_angle, une); + let uw = spin(spin_angle, uwe); + // Convert angular equatorial coordinates (RA, DEC) to + // cartesian equatorial coordinates in 'p', using the + // same orientation system as uze, une, uwe. + let p = [cosdc * cosra, cosdc * sinra, sindc]; + // Use dot products of p with the zenith, north, and west + // vectors to obtain the cartesian coordinates of the body in + // the observer's horizontal orientation system. + // pz = zenith component [-1, +1] + // pn = north component [-1, +1] + // pw = west component [-1, +1] + const pz = p[0] * uz[0] + p[1] * uz[1] + p[2] * uz[2]; + const pn = p[0] * un[0] + p[1] * un[1] + p[2] * un[2]; + const pw = p[0] * uw[0] + p[1] * uw[1] + p[2] * uw[2]; + // proj is the "shadow" of the body vector along the observer's flat ground. + let proj = Math.hypot(pn, pw); + // Calculate az = azimuth (compass direction clockwise from East.) + let az; + if (proj > 0) { + // If the body is not exactly straight up/down, it has an azimuth. + // Invert the angle to produce degrees eastward from north. + az = -exports.RAD2DEG * Math.atan2(pw, pn); + if (az < 0) + az += 360; + } + else { + // The body is straight up/down, so it does not have an azimuth. + // Report an arbitrary but reasonable value. + az = 0; + } + // zd = the angle of the body away from the observer's zenith, in degrees. + let zd = exports.RAD2DEG * Math.atan2(proj, pz); + let out_ra = ra; + let out_dec = dec; + if (refraction) { + let zd0 = zd; + let refr = Refraction(refraction, 90 - zd); + zd -= refr; + if (refr > 0.0 && zd > 3.0e-4) { + const sinzd = Math.sin(zd * exports.DEG2RAD); + const coszd = Math.cos(zd * exports.DEG2RAD); + const sinzd0 = Math.sin(zd0 * exports.DEG2RAD); + const coszd0 = Math.cos(zd0 * exports.DEG2RAD); + const pr = []; + for (let j = 0; j < 3; ++j) { + pr.push(((p[j] - coszd0 * uz[j]) / sinzd0) * sinzd + uz[j] * coszd); + } + proj = Math.hypot(pr[0], pr[1]); + if (proj > 0) { + out_ra = exports.RAD2HOUR * Math.atan2(pr[1], pr[0]); + if (out_ra < 0) { + out_ra += 24; + } + } + else { + out_ra = 0; + } + out_dec = exports.RAD2DEG * Math.atan2(pr[2], proj); + } + } + return new HorizontalCoordinates(az, 90 - zd, out_ra, out_dec); +} +exports.Horizon = Horizon; +function VerifyObserver(observer) { + if (!(observer instanceof Observer)) { + throw `Not an instance of the Observer class: ${observer}`; + } + VerifyNumber(observer.latitude); + VerifyNumber(observer.longitude); + VerifyNumber(observer.height); + if (observer.latitude < -90 || observer.latitude > +90) { + throw `Latitude ${observer.latitude} is out of range. Must be -90..+90.`; + } + return observer; +} +/** + * @brief Represents the geographic location of an observer on the surface of the Earth. + * + * @property {number} latitude + * The observer's geographic latitude in degrees north of the Earth's equator. + * The value is negative for observers south of the equator. + * Must be in the range -90 to +90. + * + * @property {number} longitude + * The observer's geographic longitude in degrees east of the prime meridian + * passing through Greenwich, England. + * The value is negative for observers west of the prime meridian. + * The value should be kept in the range -180 to +180 to minimize floating point errors. + * + * @property {number} height + * The observer's elevation above mean sea level, expressed in meters. + */ +class Observer { + constructor(latitude, longitude, height) { + this.latitude = latitude; + this.longitude = longitude; + this.height = height; + VerifyObserver(this); + } +} +exports.Observer = Observer; +/** + * @brief Returns apparent geocentric true ecliptic coordinates of date for the Sun. + * + * This function is used for calculating the times of equinoxes and solstices. + * + * Geocentric means coordinates as the Sun would appear to a hypothetical observer + * at the center of the Earth. + * Ecliptic coordinates of date are measured along the plane of the Earth's mean + * orbit around the Sun, using the + * equinox + * of the Earth as adjusted for precession and nutation of the Earth's + * axis of rotation on the given date. + * + * @param {FlexibleDateTime} date + * The date and time at which to calculate the Sun's apparent location as seen from + * the center of the Earth. + * + * @returns {EclipticCoordinates} + */ +function SunPosition(date) { + // Correct for light travel time from the Sun. + // This is really the same as correcting for aberration. + // Otherwise season calculations (equinox, solstice) will all be early by about 8 minutes! + const time = MakeTime(date).AddDays(-1 / exports.C_AUDAY); + // Get heliocentric cartesian coordinates of Earth in J2000. + const earth2000 = CalcVsop(vsop.Earth, time); + // Convert to geocentric location of the Sun. + const sun2000 = [-earth2000.x, -earth2000.y, -earth2000.z]; + // Convert to equator-of-date equatorial cartesian coordinates. + const [gx, gy, gz] = gyration(sun2000, time, PrecessDirection.From2000); + // Convert to ecliptic coordinates of date. + const true_obliq = exports.DEG2RAD * e_tilt(time).tobl; + const cos_ob = Math.cos(true_obliq); + const sin_ob = Math.sin(true_obliq); + const vec = new Vector(gx, gy, gz, time); + const sun_ecliptic = RotateEquatorialToEcliptic(vec, cos_ob, sin_ob); + return sun_ecliptic; +} +exports.SunPosition = SunPosition; +/** + * @brief Calculates equatorial coordinates of a Solar System body at a given time. + * + * Returns topocentric equatorial coordinates (right ascension and declination) + * in one of two different systems: J2000 or true-equator-of-date. + * Allows optional correction for aberration. + * Always corrects for light travel time (represents the object as seen by the observer + * with light traveling to the Earth at finite speed, not where the object is right now). + * Topocentric refers to a position as seen by an observer on the surface of the Earth. + * This function corrects for + * parallax + * of the object between a geocentric observer and a topocentric observer. + * This is most significant for the Moon, because it is so close to the Earth. + * However, it can have a small effect on the apparent positions of other bodies. + * + * @param {Body} body + * The body for which to find equatorial coordinates. + * Not allowed to be `Body.Earth`. + * + * @param {FlexibleDateTime} date + * Specifies the date and time at which the body is to be observed. + * + * @param {Observer} observer + * The location on the Earth of the observer. + * + * @param {bool} ofdate + * Pass `true` to return equatorial coordinates of date, + * i.e. corrected for precession and nutation at the given date. + * This is needed to get correct horizontal coordinates when you call + * {@link Horizon}. + * Pass `false` to return equatorial coordinates in the J2000 system. + * + * @param {bool} aberration + * Pass `true` to correct for + * aberration, + * or `false` to leave uncorrected. + * + * @returns {EquatorialCoordinates} + * The topocentric coordinates of the body as adjusted for the given observer. + */ +function Equator(body, date, observer, ofdate, aberration) { + VerifyObserver(observer); + VerifyBoolean(ofdate); + VerifyBoolean(aberration); + const time = MakeTime(date); + const gc_observer = geo_pos(time, observer); + const gc = GeoVector(body, time, aberration); + const j2000 = [ + gc.x - gc_observer[0], + gc.y - gc_observer[1], + gc.z - gc_observer[2] + ]; + if (!ofdate) + return vector2radec(j2000, time); + const datevect = gyration(j2000, time, PrecessDirection.From2000); + return vector2radec(datevect, time); +} +exports.Equator = Equator; +/** + * @brief Calculates geocentric equatorial coordinates of an observer on the surface of the Earth. + * + * This function calculates a vector from the center of the Earth to + * a point on or near the surface of the Earth, expressed in equatorial + * coordinates. It takes into account the rotation of the Earth at the given + * time, along with the given latitude, longitude, and elevation of the observer. + * + * The caller may pass `ofdate` as `true` to return coordinates relative to the Earth's + * equator at the specified time, or `false` to use the J2000 equator. + * + * The returned vector has components expressed in astronomical units (AU). + * To convert to kilometers, multiply the `x`, `y`, and `z` values by + * the constant value {@link KM_PER_AU}. + * + * The inverse of this function is also available: {@link VectorObserver}. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the observer's position vector. + * + * @param {Observer} observer + * The geographic location of a point on or near the surface of the Earth. + * + * @param {boolean} ofdate + * Selects the date of the Earth's equator in which to express the equatorial coordinates. + * The caller may pass `false` to use the orientation of the Earth's equator + * at noon UTC on January 1, 2000, in which case this function corrects for precession + * and nutation of the Earth as it was at the moment specified by the `time` parameter. + * Or the caller may pass `true` to use the Earth's equator at `time` + * as the orientation. + * + * @returns {Vector} + * An equatorial vector from the center of the Earth to the specified location + * on (or near) the Earth's surface. + */ +function ObserverVector(date, observer, ofdate) { + const time = MakeTime(date); + const gast = sidereal_time(time); + let ovec = terra(observer, gast).pos; + if (!ofdate) + ovec = gyration(ovec, time, PrecessDirection.Into2000); + return VectorFromArray(ovec, time); +} +exports.ObserverVector = ObserverVector; +/** + * @brief Calculates geocentric equatorial position and velocity of an observer on the surface of the Earth. + * + * This function calculates position and velocity vectors of an observer + * on or near the surface of the Earth, expressed in equatorial + * coordinates. It takes into account the rotation of the Earth at the given + * time, along with the given latitude, longitude, and elevation of the observer. + * + * The caller may pass `ofdate` as `true` to return coordinates relative to the Earth's + * equator at the specified time, or `false` to use the J2000 equator. + * + * The returned position vector has components expressed in astronomical units (AU). + * To convert to kilometers, multiply the `x`, `y`, and `z` values by + * the constant value {@link KM_PER_AU}. + * The returned velocity vector has components expressed in AU/day. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the observer's position and velocity vectors. + * + * @param {Observer} observer + * The geographic location of a point on or near the surface of the Earth. + * + * @param {boolean} ofdate + * Selects the date of the Earth's equator in which to express the equatorial coordinates. + * The caller may pass `false` to use the orientation of the Earth's equator + * at noon UTC on January 1, 2000, in which case this function corrects for precession + * and nutation of the Earth as it was at the moment specified by the `time` parameter. + * Or the caller may pass `true` to use the Earth's equator at `time` + * as the orientation. + * + * @returns {StateVector} + */ +function ObserverState(date, observer, ofdate) { + const time = MakeTime(date); + const gast = sidereal_time(time); + const svec = terra(observer, gast); + const state = new StateVector(svec.pos[0], svec.pos[1], svec.pos[2], svec.vel[0], svec.vel[1], svec.vel[2], time); + if (!ofdate) + return gyration_posvel(state, time, PrecessDirection.Into2000); + return state; +} +exports.ObserverState = ObserverState; +/** + * @brief Calculates the geographic location corresponding to an equatorial vector. + * + * This is the inverse function of {@link ObserverVector}. + * Given a geocentric equatorial vector, it returns the geographic + * latitude, longitude, and elevation for that vector. + * + * @param {Vector} vector + * The geocentric equatorial position vector for which to find geographic coordinates. + * The components are expressed in Astronomical Units (AU). + * You can calculate AU by dividing kilometers by the constant {@link KM_PER_AU}. + * The time `vector.t` determines the Earth's rotation. + * + * @param {boolean} ofdate + * Selects the date of the Earth's equator in which `vector` is expressed. + * The caller may select `false` to use the orientation of the Earth's equator + * at noon UTC on January 1, 2000, in which case this function corrects for precession + * and nutation of the Earth as it was at the moment specified by `vector.t`. + * Or the caller may select `true` to use the Earth's equator at `vector.t` + * as the orientation. + * + * @returns {Observer} + * The geographic latitude, longitude, and elevation above sea level + * that corresponds to the given equatorial vector. + */ +function VectorObserver(vector, ofdate) { + const gast = sidereal_time(vector.t); + let ovec = [vector.x, vector.y, vector.z]; + if (!ofdate) { + ovec = precession(ovec, vector.t, PrecessDirection.From2000); + ovec = nutation(ovec, vector.t, PrecessDirection.From2000); + } + return inverse_terra(ovec, gast); +} +exports.VectorObserver = VectorObserver; +/** + * @brief Calculates the gravitational acceleration experienced by an observer on the Earth. + * + * This function implements the WGS 84 Ellipsoidal Gravity Formula. + * The result is a combination of inward gravitational acceleration + * with outward centrifugal acceleration, as experienced by an observer + * in the Earth's rotating frame of reference. + * The resulting value increases toward the Earth's poles and decreases + * toward the equator, consistent with changes of the weight measured + * by a spring scale of a fixed mass moved to different latitudes and heights + * on the Earth. + * + * @param {number} latitude + * The latitude of the observer in degrees north or south of the equator. + * By formula symmetry, positive latitudes give the same answer as negative + * latitudes, so the sign does not matter. + * + * @param {number} height + * The height above the sea level geoid in meters. + * No range checking is done; however, accuracy is only valid in the + * range 0 to 100000 meters. + * + * @returns {number} + * The effective gravitational acceleration expressed in meters per second squared [m/s^2]. + */ +function ObserverGravity(latitude, height) { + const s = Math.sin(latitude * exports.DEG2RAD); + const s2 = s * s; + const g0 = 9.7803253359 * (1.0 + 0.00193185265241 * s2) / Math.sqrt(1.0 - 0.00669437999013 * s2); + return g0 * (1.0 - (3.15704e-07 - 2.10269e-09 * s2) * height + 7.37452e-14 * height * height); +} +exports.ObserverGravity = ObserverGravity; +function RotateEquatorialToEcliptic(equ, cos_ob, sin_ob) { + // Rotate equatorial vector to obtain ecliptic vector. + const ex = equ.x; + const ey = equ.y * cos_ob + equ.z * sin_ob; + const ez = -equ.y * sin_ob + equ.z * cos_ob; + const xyproj = Math.hypot(ex, ey); + let elon = 0; + if (xyproj > 0) { + elon = exports.RAD2DEG * Math.atan2(ey, ex); + if (elon < 0) + elon += 360; + } + let elat = exports.RAD2DEG * Math.atan2(ez, xyproj); + let ecl = new Vector(ex, ey, ez, equ.t); + return new EclipticCoordinates(ecl, elat, elon); +} +/** + * @brief Converts a J2000 mean equator (EQJ) vector to a true ecliptic of date (ETC) vector and angles. + * + * Given coordinates relative to the Earth's equator at J2000 (the instant of noon UTC + * on 1 January 2000), this function converts those coordinates to true ecliptic coordinates + * that are relative to the plane of the Earth's orbit around the Sun on that date. + * + * @param {Vector} eqj + * Equatorial coordinates in the EQJ frame of reference. + * You can call {@link GeoVector} to obtain suitable equatorial coordinates. + * + * @returns {EclipticCoordinates} + */ +function Ecliptic(eqj) { + // Calculate nutation and obliquity for this time. + // As an optimization, the nutation angles are cached in `time`, + // and reused below when the `nutation` function is called. + const et = e_tilt(eqj.t); + // Convert mean J2000 equator (EQJ) to true equator of date (EQD). + const eqj_pos = [eqj.x, eqj.y, eqj.z]; + const mean_pos = precession(eqj_pos, eqj.t, PrecessDirection.From2000); + const [x, y, z] = nutation(mean_pos, eqj.t, PrecessDirection.From2000); + const eqd = new Vector(x, y, z, eqj.t); + // Rotate from EQD to true ecliptic of date (ECT). + const tobl = et.tobl * exports.DEG2RAD; + return RotateEquatorialToEcliptic(eqd, Math.cos(tobl), Math.sin(tobl)); +} +exports.Ecliptic = Ecliptic; +/** + * @brief Calculates equatorial geocentric Cartesian coordinates for the Moon. + * + * Given a time of observation, calculates the Moon's position as a vector. + * The vector gives the location of the Moon's center relative to the Earth's center + * with x-, y-, and z-components measured in astronomical units. + * The coordinates are oriented with respect to the Earth's equator at the J2000 epoch. + * In Astronomy Engine, this orientation is called EQJ. + * Based on the Nautical Almanac Office's Improved Lunar Ephemeris of 1954, + * which in turn derives from E. W. Brown's lunar theories. + * Adapted from Turbo Pascal code from the book + * Astronomy on the Personal Computer + * by Montenbruck and Pfleger. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the Moon's geocentric position. + * + * @returns {Vector} + */ +function GeoMoon(date) { + const time = MakeTime(date); + const moon = CalcMoon(time); + // Convert geocentric ecliptic spherical coords to cartesian coords. + const dist_cos_lat = moon.distance_au * Math.cos(moon.geo_eclip_lat); + const gepos = [ + dist_cos_lat * Math.cos(moon.geo_eclip_lon), + dist_cos_lat * Math.sin(moon.geo_eclip_lon), + moon.distance_au * Math.sin(moon.geo_eclip_lat) + ]; + // Convert ecliptic coordinates to equatorial coordinates, both in mean equinox of date. + const mpos1 = ecl2equ_vec(time, gepos); + // Convert from mean equinox of date to J2000... + const mpos2 = precession(mpos1, time, PrecessDirection.Into2000); + return new Vector(mpos2[0], mpos2[1], mpos2[2], time); +} +exports.GeoMoon = GeoMoon; +/** + * @brief Calculates spherical ecliptic geocentric position of the Moon. + * + * Given a time of observation, calculates the Moon's geocentric position + * in ecliptic spherical coordinates. Provides the ecliptic latitude and + * longitude in degrees, and the geocentric distance in astronomical units (AU). + * + * The ecliptic angles are measured in "ECT": relative to the true ecliptic plane and + * equatorial plane at the specified time. This means the Earth's equator + * is corrected for precession and nutation, and the plane of the Earth's + * orbit is corrected for gradual obliquity drift. + * + * This algorithm is based on the Nautical Almanac Office's Improved Lunar Ephemeris of 1954, + * which in turn derives from E. W. Brown's lunar theories from the early twentieth century. + * It is adapted from Turbo Pascal code from the book + * Astronomy on the Personal Computer + * by Montenbruck and Pfleger. + * + * To calculate a J2000 mean equator vector instead, use {@link GeoMoon}. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the Moon's position. + * + * @returns {Spherical} + */ +function EclipticGeoMoon(date) { + const time = MakeTime(date); + const moon = CalcMoon(time); + // Convert spherical coordinates to a vector. + // The MoonResult angles are already expressed in radians. + const dist_cos_lat = moon.distance_au * Math.cos(moon.geo_eclip_lat); + const ecm = [ + dist_cos_lat * Math.cos(moon.geo_eclip_lon), + dist_cos_lat * Math.sin(moon.geo_eclip_lon), + moon.distance_au * Math.sin(moon.geo_eclip_lat) + ]; + // Obtain true and mean obliquity angles for the given time. + // This serves to pre-calculate the nutation also, and cache it in `time`. + const et = e_tilt(time); + // Convert ecliptic coordinates to equatorial coordinates, both in mean equinox of date. + const eqm = obl_ecl2equ_vec(et.mobl, ecm); + // Add nutation to convert ECM to true equatorial coordinates of date (EQD). + const eqd = nutation(eqm, time, PrecessDirection.From2000); + const eqd_vec = VectorFromArray(eqd, time); + // Convert back to ecliptic, this time in true equinox of date (ECT). + const toblRad = et.tobl * exports.DEG2RAD; + const cos_tobl = Math.cos(toblRad); + const sin_tobl = Math.sin(toblRad); + const eclip = RotateEquatorialToEcliptic(eqd_vec, cos_tobl, sin_tobl); + return new Spherical(eclip.elat, eclip.elon, moon.distance_au); +} +exports.EclipticGeoMoon = EclipticGeoMoon; +/** + * @brief Calculates equatorial geocentric position and velocity of the Moon at a given time. + * + * Given a time of observation, calculates the Moon's position and velocity vectors. + * The position and velocity are of the Moon's center relative to the Earth's center. + * The position (x, y, z) components are expressed in AU (astronomical units). + * The velocity (vx, vy, vz) components are expressed in AU/day. + * The coordinates are oriented with respect to the Earth's equator at the J2000 epoch. + * In Astronomy Engine, this orientation is called EQJ. + * If you need the Moon's position only, and not its velocity, + * it is much more efficient to use {@link GeoMoon} instead. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the Moon's geocentric state. + * + * @returns {StateVector} + */ +function GeoMoonState(date) { + const time = MakeTime(date); + // This is a hack, because trying to figure out how to derive a time + // derivative for CalcMoon() would be extremely painful! + // Calculate just before and just after the given time. + // Average to find position, subtract to find velocity. + const dt = 1.0e-5; // 0.864 seconds + const t1 = time.AddDays(-dt); + const t2 = time.AddDays(+dt); + const r1 = GeoMoon(t1); + const r2 = GeoMoon(t2); + return new StateVector((r1.x + r2.x) / 2, (r1.y + r2.y) / 2, (r1.z + r2.z) / 2, (r2.x - r1.x) / (2 * dt), (r2.y - r1.y) / (2 * dt), (r2.z - r1.z) / (2 * dt), time); +} +exports.GeoMoonState = GeoMoonState; +/** + * @brief Calculates the geocentric position and velocity of the Earth/Moon barycenter. + * + * Given a time of observation, calculates the geocentric position and velocity vectors + * of the Earth/Moon barycenter (EMB). + * The position (x, y, z) components are expressed in AU (astronomical units). + * The velocity (vx, vy, vz) components are expressed in AU/day. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the EMB's geocentric state. + * + * @returns {StateVector} + */ +function GeoEmbState(date) { + const time = MakeTime(date); + const s = GeoMoonState(time); + const d = 1.0 + EARTH_MOON_MASS_RATIO; + return new StateVector(s.x / d, s.y / d, s.z / d, s.vx / d, s.vy / d, s.vz / d, time); +} +exports.GeoEmbState = GeoEmbState; +function VsopFormula(formula, t, clamp_angle) { + let tpower = 1; + let coord = 0; + for (let series of formula) { + let sum = 0; + for (let [ampl, phas, freq] of series) + sum += ampl * Math.cos(phas + (t * freq)); + let incr = tpower * sum; + if (clamp_angle) + incr %= PI2; // improve precision for longitudes: they can be hundreds of radians + coord += incr; + tpower *= t; + } + return coord; +} +function VsopDeriv(formula, t) { + let tpower = 1; // t^s + let dpower = 0; // t^(s-1) + let deriv = 0; + let s = 0; + for (let series of formula) { + let sin_sum = 0; + let cos_sum = 0; + for (let [ampl, phas, freq] of series) { + let angle = phas + (t * freq); + sin_sum += ampl * freq * Math.sin(angle); + if (s > 0) + cos_sum += ampl * Math.cos(angle); + } + deriv += (s * dpower * cos_sum) - (tpower * sin_sum); + dpower = tpower; + tpower *= t; + ++s; + } + return deriv; +} +const DAYS_PER_MILLENNIUM = 365250; +const LON_INDEX = 0; +const LAT_INDEX = 1; +const RAD_INDEX = 2; +function VsopRotate(eclip) { + // Convert ecliptic cartesian coordinates to equatorial cartesian coordinates. + return new TerseVector(eclip[0] + 0.000000440360 * eclip[1] - 0.000000190919 * eclip[2], -0.000000479966 * eclip[0] + 0.917482137087 * eclip[1] - 0.397776982902 * eclip[2], 0.397776982902 * eclip[1] + 0.917482137087 * eclip[2]); +} +function VsopSphereToRect(lon, lat, radius) { + // Convert spherical coordinates to ecliptic cartesian coordinates. + const r_coslat = radius * Math.cos(lat); + const coslon = Math.cos(lon); + const sinlon = Math.sin(lon); + return [ + r_coslat * coslon, + r_coslat * sinlon, + radius * Math.sin(lat) + ]; +} +function CalcVsop(model, time) { + const t = time.tt / DAYS_PER_MILLENNIUM; // millennia since 2000 + const lon = VsopFormula(model[LON_INDEX], t, true); + const lat = VsopFormula(model[LAT_INDEX], t, false); + const rad = VsopFormula(model[RAD_INDEX], t, false); + const eclip = VsopSphereToRect(lon, lat, rad); + return VsopRotate(eclip).ToAstroVector(time); +} +function CalcVsopPosVel(model, tt) { + const t = tt / DAYS_PER_MILLENNIUM; + // Calculate the VSOP "B" trigonometric series to obtain ecliptic spherical coordinates. + const lon = VsopFormula(model[LON_INDEX], t, true); + const lat = VsopFormula(model[LAT_INDEX], t, false); + const rad = VsopFormula(model[RAD_INDEX], t, false); + const dlon_dt = VsopDeriv(model[LON_INDEX], t); + const dlat_dt = VsopDeriv(model[LAT_INDEX], t); + const drad_dt = VsopDeriv(model[RAD_INDEX], t); + // Use spherical coords and spherical derivatives to calculate + // the velocity vector in rectangular coordinates. + const coslon = Math.cos(lon); + const sinlon = Math.sin(lon); + const coslat = Math.cos(lat); + const sinlat = Math.sin(lat); + const vx = (+(drad_dt * coslat * coslon) + - (rad * sinlat * coslon * dlat_dt) + - (rad * coslat * sinlon * dlon_dt)); + const vy = (+(drad_dt * coslat * sinlon) + - (rad * sinlat * sinlon * dlat_dt) + + (rad * coslat * coslon * dlon_dt)); + const vz = (+(drad_dt * sinlat) + + (rad * coslat * dlat_dt)); + const eclip_pos = VsopSphereToRect(lon, lat, rad); + // Convert speed units from [AU/millennium] to [AU/day]. + const eclip_vel = [ + vx / DAYS_PER_MILLENNIUM, + vy / DAYS_PER_MILLENNIUM, + vz / DAYS_PER_MILLENNIUM + ]; + // Rotate the vectors from ecliptic to equatorial coordinates. + const equ_pos = VsopRotate(eclip_pos); + const equ_vel = VsopRotate(eclip_vel); + return new body_state_t(tt, equ_pos, equ_vel); +} +function AdjustBarycenter(ssb, time, body, pmass) { + const shift = pmass / (pmass + SUN_GM); + const planet = CalcVsop(vsop[body], time); + ssb.x += shift * planet.x; + ssb.y += shift * planet.y; + ssb.z += shift * planet.z; +} +function CalcSolarSystemBarycenter(time) { + const ssb = new Vector(0.0, 0.0, 0.0, time); + AdjustBarycenter(ssb, time, Body.Jupiter, JUPITER_GM); + AdjustBarycenter(ssb, time, Body.Saturn, SATURN_GM); + AdjustBarycenter(ssb, time, Body.Uranus, URANUS_GM); + AdjustBarycenter(ssb, time, Body.Neptune, NEPTUNE_GM); + return ssb; +} +// Pluto integrator begins ---------------------------------------------------- +const PLUTO_NUM_STATES = 51; +const PLUTO_TIME_STEP = 29200; +const PLUTO_DT = 146; +const PLUTO_NSTEPS = 201; +const PlutoStateTable = [ + [-730000.0, [-26.118207232108, -14.376168177825, 3.384402515299], [1.6339372163656e-03, -2.7861699588508e-03, -1.3585880229445e-03]], + [-700800.0, [41.974905202127, -0.448502952929, -12.770351505989], [7.3458569351457e-04, 2.2785014891658e-03, 4.8619778602049e-04]], + [-671600.0, [14.706930780744, 44.269110540027, 9.353698474772], [-2.1000147999800e-03, 2.2295915939915e-04, 7.0143443551414e-04]], + [-642400.0, [-29.441003929957, -6.430161530570, 6.858481011305], [8.4495803960544e-04, -3.0783914758711e-03, -1.2106305981192e-03]], + [-613200.0, [39.444396946234, -6.557989760571, -13.913760296463], [1.1480029005873e-03, 2.2400006880665e-03, 3.5168075922288e-04]], + [-584000.0, [20.230380950700, 43.266966657189, 7.382966091923], [-1.9754081700585e-03, 5.3457141292226e-04, 7.5929169129793e-04]], + [-554800.0, [-30.658325364620, 2.093818874552, 9.880531138071], [6.1010603013347e-05, -3.1326500935382e-03, -9.9346125151067e-04]], + [-525600.0, [35.737703251673, -12.587706024764, -14.677847247563], [1.5802939375649e-03, 2.1347678412429e-03, 1.9074436384343e-04]], + [-496400.0, [25.466295188546, 41.367478338417, 5.216476873382], [-1.8054401046468e-03, 8.3283083599510e-04, 8.0260156912107e-04]], + [-467200.0, [-29.847174904071, 10.636426313081, 12.297904180106], [-6.3257063052907e-04, -2.9969577578221e-03, -7.4476074151596e-04]], + [-438000.0, [30.774692107687, -18.236637015304, -14.945535879896], [2.0113162005465e-03, 1.9353827024189e-03, -2.0937793168297e-06]], + [-408800.0, [30.243153324028, 38.656267888503, 2.938501750218], [-1.6052508674468e-03, 1.1183495337525e-03, 8.3333973416824e-04]], + [-379600.0, [-27.288984772533, 18.643162147874, 14.023633623329], [-1.1856388898191e-03, -2.7170609282181e-03, -4.9015526126399e-04]], + [-350400.0, [24.519605196774, -23.245756064727, -14.626862367368], [2.4322321483154e-03, 1.6062008146048e-03, -2.3369181613312e-04]], + [-321200.0, [34.505274805875, 35.125338586954, 0.557361475637], [-1.3824391637782e-03, 1.3833397561817e-03, 8.4823598806262e-04]], + [-292000.0, [-23.275363915119, 25.818514298769, 15.055381588598], [-1.6062295460975e-03, -2.3395961498533e-03, -2.4377362639479e-04]], + [-262800.0, [17.050384798092, -27.180376290126, -13.608963321694], [2.8175521080578e-03, 1.1358749093955e-03, -4.9548725258825e-04]], + [-233600.0, [38.093671910285, 30.880588383337, -1.843688067413], [-1.1317697153459e-03, 1.6128814698472e-03, 8.4177586176055e-04]], + [-204400.0, [-18.197852930878, 31.932869934309, 15.438294826279], [-1.9117272501813e-03, -1.9146495909842e-03, -1.9657304369835e-05]], + [-175200.0, [8.528924039997, -29.618422200048, -11.805400994258], [3.1034370787005e-03, 5.1393633292430e-04, -7.7293066202546e-04]], + [-146000.0, [40.946857258640, 25.904973592021, -4.256336240499], [-8.3652705194051e-04, 1.8129497136404e-03, 8.1564228273060e-04]], + [-116800.0, [-12.326958895325, 36.881883446292, 15.217158258711], [-2.1166103705038e-03, -1.4814420035990e-03, 1.7401209844705e-04]], + [-87600.0, [-0.633258375909, -30.018759794709, -9.171932874950], [3.2016994581737e-03, -2.5279858672148e-04, -1.0411088271861e-03]], + [-58400.0, [42.936048423883, 20.344685584452, -6.588027007912], [-5.0525450073192e-04, 1.9910074335507e-03, 7.7440196540269e-04]], + [-29200.0, [-5.975910552974, 40.611809958460, 14.470131723673], [-2.2184202156107e-03, -1.0562361130164e-03, 3.3652250216211e-04]], + [0.0, [-9.875369580774, -27.978926224737, -5.753711824704], [3.0287533248818e-03, -1.1276087003636e-03, -1.2651326732361e-03]], + [29200.0, [43.958831986165, 14.214147973292, -8.808306227163], [-1.4717608981871e-04, 2.1404187242141e-03, 7.1486567806614e-04]], + [58400.0, [0.678136763520, 43.094461639362, 13.243238780721], [-2.2358226110718e-03, -6.3233636090933e-04, 4.7664798895648e-04]], + [87600.0, [-18.282602096834, -23.305039586660, -1.766620508028], [2.5567245263557e-03, -1.9902940754171e-03, -1.3943491701082e-03]], + [116800.0, [43.873338744526, 7.700705617215, -10.814273666425], [2.3174803055677e-04, 2.2402163127924e-03, 6.2988756452032e-04]], + [146000.0, [7.392949027906, 44.382678951534, 11.629500214854], [-2.1932815453830e-03, -2.1751799585364e-04, 5.9556516201114e-04]], + [175200.0, [-24.981690229261, -16.204012851426, 2.466457544298], [1.8193989149580e-03, -2.6765419531201e-03, -1.3848283502247e-03]], + [204400.0, [42.530187039511, 0.845935508021, -12.554907527683], [6.5059779150669e-04, 2.2725657282262e-03, 5.1133743202822e-04]], + [233600.0, [13.999526486822, 44.462363044894, 9.669418486465], [-2.1079296569252e-03, 1.7533423831993e-04, 6.9128485798076e-04]], + [262800.0, [-29.184024803031, -7.371243995762, 6.493275957928], [9.3581363109681e-04, -3.0610357109184e-03, -1.2364201089345e-03]], + [292000.0, [39.831980671753, -6.078405766765, -13.909815358656], [1.1117769689167e-03, 2.2362097830152e-03, 3.6230548231153e-04]], + [321200.0, [20.294955108476, 43.417190420251, 7.450091985932], [-1.9742157451535e-03, 5.3102050468554e-04, 7.5938408813008e-04]], + [350400.0, [-30.669992302160, 2.318743558955, 9.973480913858], [4.5605107450676e-05, -3.1308219926928e-03, -9.9066533301924e-04]], + [379600.0, [35.626122155983, -12.897647509224, -14.777586508444], [1.6015684949743e-03, 2.1171931182284e-03, 1.8002516202204e-04]], + [408800.0, [26.133186148561, 41.232139187599, 5.006401326220], [-1.7857704419579e-03, 8.6046232702817e-04, 8.0614690298954e-04]], + [438000.0, [-29.576740229230, 11.863535943587, 12.631323039872], [-7.2292830060955e-04, -2.9587820140709e-03, -7.0824296450300e-04]], + [467200.0, [29.910805787391, -19.159019294000, -15.013363865194], [2.0871080437997e-03, 1.8848372554514e-03, -3.8528655083926e-05]], + [496400.0, [31.375957451819, 38.050372720763, 2.433138343754], [-1.5546055556611e-03, 1.1699815465629e-03, 8.3565439266001e-04]], + [525600.0, [-26.360071336928, 20.662505904952, 14.414696258958], [-1.3142373118349e-03, -2.6236647854842e-03, -4.2542017598193e-04]], + [554800.0, [22.599441488648, -24.508879898306, -14.484045731468], [2.5454108304806e-03, 1.4917058755191e-03, -3.0243665086079e-04]], + [584000.0, [35.877864013014, 33.894226366071, -0.224524636277], [-1.2941245730845e-03, 1.4560427668319e-03, 8.4762160640137e-04]], + [613200.0, [-21.538149762417, 28.204068269761, 15.321973799534], [-1.7312117409010e-03, -2.1939631314577e-03, -1.6316913275180e-04]], + [642400.0, [13.971521374415, -28.339941764789, -13.083792871886], [2.9334630526035e-03, 9.1860931752944e-04, -5.9939422488627e-04]], + [671600.0, [39.526942044143, 28.939897360110, -2.872799527539], [-1.0068481658095e-03, 1.7021132888090e-03, 8.3578230511981e-04]], + [700800.0, [-15.576200701394, 34.399412961275, 15.466033737854], [-2.0098814612884e-03, -1.7191109825989e-03, 7.0414782780416e-05]], + [730000.0, [4.243252837090, -30.118201690825, -10.707441231349], [3.1725847067411e-03, 1.6098461202270e-04, -9.0672150593868e-04]] +]; +class TerseVector { + constructor(x, y, z) { + this.x = x; + this.y = y; + this.z = z; + } + clone() { + return new TerseVector(this.x, this.y, this.z); + } + ToAstroVector(t) { + return new Vector(this.x, this.y, this.z, t); + } + static zero() { + return new TerseVector(0, 0, 0); + } + quadrature() { + return this.x * this.x + this.y * this.y + this.z * this.z; + } + add(other) { + return new TerseVector(this.x + other.x, this.y + other.y, this.z + other.z); + } + sub(other) { + return new TerseVector(this.x - other.x, this.y - other.y, this.z - other.z); + } + incr(other) { + this.x += other.x; + this.y += other.y; + this.z += other.z; + } + decr(other) { + this.x -= other.x; + this.y -= other.y; + this.z -= other.z; + } + mul(scalar) { + return new TerseVector(scalar * this.x, scalar * this.y, scalar * this.z); + } + div(scalar) { + return new TerseVector(this.x / scalar, this.y / scalar, this.z / scalar); + } + mean(other) { + return new TerseVector((this.x + other.x) / 2, (this.y + other.y) / 2, (this.z + other.z) / 2); + } + neg() { + return new TerseVector(-this.x, -this.y, -this.z); + } +} +class body_state_t { + constructor(tt, r, v) { + this.tt = tt; + this.r = r; + this.v = v; + } + clone() { + return new body_state_t(this.tt, this.r, this.v); + } + sub(other) { + return new body_state_t(this.tt, this.r.sub(other.r), this.v.sub(other.v)); + } +} +function BodyStateFromTable(entry) { + let [tt, [rx, ry, rz], [vx, vy, vz]] = entry; + return new body_state_t(tt, new TerseVector(rx, ry, rz), new TerseVector(vx, vy, vz)); +} +function AdjustBarycenterPosVel(ssb, tt, body, planet_gm) { + const shift = planet_gm / (planet_gm + SUN_GM); + const planet = CalcVsopPosVel(vsop[body], tt); + ssb.r.incr(planet.r.mul(shift)); + ssb.v.incr(planet.v.mul(shift)); + return planet; +} +function AccelerationIncrement(small_pos, gm, major_pos) { + const delta = major_pos.sub(small_pos); + const r2 = delta.quadrature(); + return delta.mul(gm / (r2 * Math.sqrt(r2))); +} +class major_bodies_t { + constructor(tt) { + // Accumulate the Solar System Barycenter position. + let ssb = new body_state_t(tt, new TerseVector(0, 0, 0), new TerseVector(0, 0, 0)); + this.Jupiter = AdjustBarycenterPosVel(ssb, tt, Body.Jupiter, JUPITER_GM); + this.Saturn = AdjustBarycenterPosVel(ssb, tt, Body.Saturn, SATURN_GM); + this.Uranus = AdjustBarycenterPosVel(ssb, tt, Body.Uranus, URANUS_GM); + this.Neptune = AdjustBarycenterPosVel(ssb, tt, Body.Neptune, NEPTUNE_GM); + // Convert planets' [pos, vel] vectors from heliocentric to barycentric. + this.Jupiter.r.decr(ssb.r); + this.Jupiter.v.decr(ssb.v); + this.Saturn.r.decr(ssb.r); + this.Saturn.v.decr(ssb.v); + this.Uranus.r.decr(ssb.r); + this.Uranus.v.decr(ssb.v); + this.Neptune.r.decr(ssb.r); + this.Neptune.v.decr(ssb.v); + // Convert heliocentric SSB to barycentric Sun. + this.Sun = new body_state_t(tt, ssb.r.mul(-1), ssb.v.mul(-1)); + } + Acceleration(pos) { + // Use barycentric coordinates of the Sun and major planets to calculate + // the gravitational acceleration vector experienced at location 'pos'. + let acc = AccelerationIncrement(pos, SUN_GM, this.Sun.r); + acc.incr(AccelerationIncrement(pos, JUPITER_GM, this.Jupiter.r)); + acc.incr(AccelerationIncrement(pos, SATURN_GM, this.Saturn.r)); + acc.incr(AccelerationIncrement(pos, URANUS_GM, this.Uranus.r)); + acc.incr(AccelerationIncrement(pos, NEPTUNE_GM, this.Neptune.r)); + return acc; + } +} +/** + * @ignore + * + * @brief The state of a body at an incremental step in a gravity simulation. + * + * This is an internal data structure used to represent the + * position, velocity, and acceleration vectors of a body + * in a gravity simulation at a given moment in time. + * + * @property tt + * The J2000 terrestrial time of the state [days]. + * + * @property r + * The position vector [au]. + * + * @property v + * The velocity vector [au/day]. + * + * @property a + * The acceleration vector [au/day^2]. + */ +class body_grav_calc_t { + constructor(tt, r, v, a) { + this.tt = tt; + this.r = r; + this.v = v; + this.a = a; + } + clone() { + return new body_grav_calc_t(this.tt, this.r.clone(), this.v.clone(), this.a.clone()); + } +} +class grav_sim_t { + constructor(bary, grav) { + this.bary = bary; + this.grav = grav; + } +} +function UpdatePosition(dt, r, v, a) { + return new TerseVector(r.x + dt * (v.x + dt * a.x / 2), r.y + dt * (v.y + dt * a.y / 2), r.z + dt * (v.z + dt * a.z / 2)); +} +function UpdateVelocity(dt, v, a) { + return new TerseVector(v.x + dt * a.x, v.y + dt * a.y, v.z + dt * a.z); +} +function GravSim(tt2, calc1) { + const dt = tt2 - calc1.tt; + // Calculate where the major bodies (Sun, Jupiter...Neptune) will be at tt2. + const bary2 = new major_bodies_t(tt2); + // Estimate position of small body as if current acceleration applies across the whole time interval. + const approx_pos = UpdatePosition(dt, calc1.r, calc1.v, calc1.a); + // Calculate the average acceleration of the endpoints. + // This becomes our estimate of the mean effective acceleration over the whole interval. + const mean_acc = bary2.Acceleration(approx_pos).mean(calc1.a); + // Refine the estimates of [pos, vel, acc] at tt2 using the mean acceleration. + const pos = UpdatePosition(dt, calc1.r, calc1.v, mean_acc); + const vel = calc1.v.add(mean_acc.mul(dt)); + const acc = bary2.Acceleration(pos); + const grav = new body_grav_calc_t(tt2, pos, vel, acc); + return new grav_sim_t(bary2, grav); +} +const pluto_cache = []; +function ClampIndex(frac, nsteps) { + const index = Math.floor(frac); + if (index < 0) + return 0; + if (index >= nsteps) + return nsteps - 1; + return index; +} +function GravFromState(entry) { + const state = BodyStateFromTable(entry); + const bary = new major_bodies_t(state.tt); + const r = state.r.add(bary.Sun.r); + const v = state.v.add(bary.Sun.v); + const a = bary.Acceleration(r); + const grav = new body_grav_calc_t(state.tt, r, v, a); + return new grav_sim_t(bary, grav); +} +function GetSegment(cache, tt) { + const t0 = PlutoStateTable[0][0]; + if (tt < t0 || tt > PlutoStateTable[PLUTO_NUM_STATES - 1][0]) { + // Don't bother calculating a segment. Let the caller crawl backward/forward to this time. + return null; + } + const seg_index = ClampIndex((tt - t0) / PLUTO_TIME_STEP, PLUTO_NUM_STATES - 1); + if (!cache[seg_index]) { + const seg = cache[seg_index] = []; + // Each endpoint is exact. + seg[0] = GravFromState(PlutoStateTable[seg_index]).grav; + seg[PLUTO_NSTEPS - 1] = GravFromState(PlutoStateTable[seg_index + 1]).grav; + // Simulate forwards from the lower time bound. + let i; + let step_tt = seg[0].tt; + for (i = 1; i < PLUTO_NSTEPS - 1; ++i) + seg[i] = GravSim(step_tt += PLUTO_DT, seg[i - 1]).grav; + // Simulate backwards from the upper time bound. + step_tt = seg[PLUTO_NSTEPS - 1].tt; + var reverse = []; + reverse[PLUTO_NSTEPS - 1] = seg[PLUTO_NSTEPS - 1]; + for (i = PLUTO_NSTEPS - 2; i > 0; --i) + reverse[i] = GravSim(step_tt -= PLUTO_DT, reverse[i + 1]).grav; + // Fade-mix the two series so that there are no discontinuities. + for (i = PLUTO_NSTEPS - 2; i > 0; --i) { + const ramp = i / (PLUTO_NSTEPS - 1); + seg[i].r = seg[i].r.mul(1 - ramp).add(reverse[i].r.mul(ramp)); + seg[i].v = seg[i].v.mul(1 - ramp).add(reverse[i].v.mul(ramp)); + seg[i].a = seg[i].a.mul(1 - ramp).add(reverse[i].a.mul(ramp)); + } + } + return cache[seg_index]; +} +function CalcPlutoOneWay(entry, target_tt, dt) { + let sim = GravFromState(entry); + const n = Math.ceil((target_tt - sim.grav.tt) / dt); + for (let i = 0; i < n; ++i) + sim = GravSim((i + 1 === n) ? target_tt : (sim.grav.tt + dt), sim.grav); + return sim; +} +function CalcPluto(time, helio) { + let r, v, bary; + const seg = GetSegment(pluto_cache, time.tt); + if (!seg) { + // The target time is outside the year range 0000..4000. + // Calculate it by crawling backward from 0000 or forward from 4000. + // FIXFIXFIX - This is super slow. Could optimize this with extra caching if needed. + let sim; + if (time.tt < PlutoStateTable[0][0]) + sim = CalcPlutoOneWay(PlutoStateTable[0], time.tt, -PLUTO_DT); + else + sim = CalcPlutoOneWay(PlutoStateTable[PLUTO_NUM_STATES - 1], time.tt, +PLUTO_DT); + r = sim.grav.r; + v = sim.grav.v; + bary = sim.bary; + } + else { + const left = ClampIndex((time.tt - seg[0].tt) / PLUTO_DT, PLUTO_NSTEPS - 1); + const s1 = seg[left]; + const s2 = seg[left + 1]; + // Find mean acceleration vector over the interval. + const acc = s1.a.mean(s2.a); + // Use Newtonian mechanics to extrapolate away from t1 in the positive time direction. + const ra = UpdatePosition(time.tt - s1.tt, s1.r, s1.v, acc); + const va = UpdateVelocity(time.tt - s1.tt, s1.v, acc); + // Use Newtonian mechanics to extrapolate away from t2 in the negative time direction. + const rb = UpdatePosition(time.tt - s2.tt, s2.r, s2.v, acc); + const vb = UpdateVelocity(time.tt - s2.tt, s2.v, acc); + // Use fade in/out idea to blend the two position estimates. + const ramp = (time.tt - s1.tt) / PLUTO_DT; + r = ra.mul(1 - ramp).add(rb.mul(ramp)); + v = va.mul(1 - ramp).add(vb.mul(ramp)); + } + if (helio) { + // Convert barycentric vectors to heliocentric vectors. + if (!bary) + bary = new major_bodies_t(time.tt); + r = r.sub(bary.Sun.r); + v = v.sub(bary.Sun.v); + } + return new StateVector(r.x, r.y, r.z, v.x, v.y, v.z, time); +} +; +const Rotation_JUP_EQJ = new RotationMatrix([ + [9.99432765338654e-01, -3.36771074697641e-02, 0.00000000000000e+00], + [3.03959428906285e-02, 9.02057912352809e-01, 4.30543388542295e-01], + [-1.44994559663353e-02, -4.30299169409101e-01, 9.02569881273754e-01] +]); +const JupiterMoonModel = [ + // [0] Io + { + mu: 2.8248942843381399e-07, + al: [1.4462132960212239e+00, 3.5515522861824000e+00], + a: [ + [0.0028210960212903, 0.0000000000000000e+00, 0.0000000000000000e+00] + ], + l: [ + [-0.0001925258348666, 4.9369589722644998e+00, 1.3584836583050000e-02], + [-0.0000970803596076, 4.3188796477322002e+00, 1.3034138432430000e-02], + [-0.0000898817416500, 1.9080016428616999e+00, 3.0506486715799999e-03], + [-0.0000553101050262, 1.4936156681568999e+00, 1.2938928911549999e-02] + ], + z: [ + [0.0041510849668155, 4.0899396355450000e+00, -1.2906864146660001e-02], + [0.0006260521444113, 1.4461888986270000e+00, 3.5515522949801999e+00], + [0.0000352747346169, 2.1256287034577999e+00, 1.2727416566999999e-04] + ], + zeta: [ + [0.0003142172466014, 2.7964219722923001e+00, -2.3150960980000000e-03], + [0.0000904169207946, 1.0477061879627001e+00, -5.6920638196000003e-04] + ] + }, + // [1] Europa + { + mu: 2.8248327439289299e-07, + al: [-3.7352634374713622e-01, 1.7693227111234699e+00], + a: [ + [0.0044871037804314, 0.0000000000000000e+00, 0.0000000000000000e+00], + [0.0000004324367498, 1.8196456062910000e+00, 1.7822295777568000e+00] + ], + l: [ + [0.0008576433172936, 4.3188693178264002e+00, 1.3034138308049999e-02], + [0.0004549582875086, 1.4936531751079001e+00, 1.2938928819619999e-02], + [0.0003248939825174, 1.8196494533458001e+00, 1.7822295777568000e+00], + [-0.0003074250079334, 4.9377037005910998e+00, 1.3584832867240000e-02], + [0.0001982386144784, 1.9079869054759999e+00, 3.0510121286900001e-03], + [0.0001834063551804, 2.1402853388529000e+00, 1.4500978933800000e-03], + [-0.0001434383188452, 5.6222140366630002e+00, 8.9111478887838003e-01], + [-0.0000771939140944, 4.3002724372349999e+00, 2.6733443704265998e+00] + ], + z: [ + [-0.0093589104136341, 4.0899396509038999e+00, -1.2906864146660001e-02], + [0.0002988994545555, 5.9097265185595003e+00, 1.7693227079461999e+00], + [0.0002139036390350, 2.1256289300016000e+00, 1.2727418406999999e-04], + [0.0001980963564781, 2.7435168292649998e+00, 6.7797343008999997e-04], + [0.0001210388158965, 5.5839943711203004e+00, 3.2056614899999997e-05], + [0.0000837042048393, 1.6094538368039000e+00, -9.0402165808846002e-01], + [0.0000823525166369, 1.4461887708689001e+00, 3.5515522949801999e+00] + ], + zeta: [ + [0.0040404917832303, 1.0477063169425000e+00, -5.6920640539999997e-04], + [0.0002200421034564, 3.3368857864364001e+00, -1.2491307306999999e-04], + [0.0001662544744719, 2.4134862374710999e+00, 0.0000000000000000e+00], + [0.0000590282470983, 5.9719930968366004e+00, -3.0561602250000000e-05] + ] + }, + // [2] Ganymede + { + mu: 2.8249818418472298e-07, + al: [2.8740893911433479e-01, 8.7820792358932798e-01], + a: [ + [0.0071566594572575, 0.0000000000000000e+00, 0.0000000000000000e+00], + [0.0000013930299110, 1.1586745884981000e+00, 2.6733443704265998e+00] + ], + l: [ + [0.0002310797886226, 2.1402987195941998e+00, 1.4500978438400001e-03], + [-0.0001828635964118, 4.3188672736968003e+00, 1.3034138282630000e-02], + [0.0001512378778204, 4.9373102372298003e+00, 1.3584834812520000e-02], + [-0.0001163720969778, 4.3002659861490002e+00, 2.6733443704265998e+00], + [-0.0000955478069846, 1.4936612842567001e+00, 1.2938928798570001e-02], + [0.0000815246854464, 5.6222137132535002e+00, 8.9111478887838003e-01], + [-0.0000801219679602, 1.2995922951532000e+00, 1.0034433456728999e+00], + [-0.0000607017260182, 6.4978769669238001e-01, 5.0172167043264004e-01] + ], + z: [ + [0.0014289811307319, 2.1256295942738999e+00, 1.2727413029000001e-04], + [0.0007710931226760, 5.5836330003496002e+00, 3.2064341100000001e-05], + [0.0005925911780766, 4.0899396636447998e+00, -1.2906864146660001e-02], + [0.0002045597496146, 5.2713683670371996e+00, -1.2523544076106000e-01], + [0.0001785118648258, 2.8743156721063001e-01, 8.7820792442520001e-01], + [0.0001131999784893, 1.4462127277818000e+00, 3.5515522949801999e+00], + [-0.0000658778169210, 2.2702423990985001e+00, -1.7951364394536999e+00], + [0.0000497058888328, 5.9096792204858000e+00, 1.7693227129285001e+00] + ], + zeta: [ + [0.0015932721570848, 3.3368862796665000e+00, -1.2491307058000000e-04], + [0.0008533093128905, 2.4133881688166001e+00, 0.0000000000000000e+00], + [0.0003513347911037, 5.9720789850126996e+00, -3.0561017709999999e-05], + [-0.0001441929255483, 1.0477061764435001e+00, -5.6920632124000004e-04] + ] + }, + // [3] Callisto + { + mu: 2.8249214488990899e-07, + al: [-3.6203412913757038e-01, 3.7648623343382798e-01], + a: [ + [0.0125879701715314, 0.0000000000000000e+00, 0.0000000000000000e+00], + [0.0000035952049470, 6.4965776007116005e-01, 5.0172168165034003e-01], + [0.0000027580210652, 1.8084235781510001e+00, 3.1750660413359002e+00] + ], + l: [ + [0.0005586040123824, 2.1404207189814999e+00, 1.4500979323100001e-03], + [-0.0003805813868176, 2.7358844897852999e+00, 2.9729650620000000e-05], + [0.0002205152863262, 6.4979652596399995e-01, 5.0172167243580001e-01], + [0.0001877895151158, 1.8084787604004999e+00, 3.1750660413359002e+00], + [0.0000766916975242, 6.2720114319754998e+00, 1.3928364636651001e+00], + [0.0000747056855106, 1.2995916202344000e+00, 1.0034433456728999e+00] + ], + z: [ + [0.0073755808467977, 5.5836071576083999e+00, 3.2065099140000001e-05], + [0.0002065924169942, 5.9209831565786004e+00, 3.7648624194703001e-01], + [0.0001589869764021, 2.8744006242622999e-01, 8.7820792442520001e-01], + [-0.0001561131605348, 2.1257397865089001e+00, 1.2727441285000001e-04], + [0.0001486043380971, 1.4462134301023000e+00, 3.5515522949801999e+00], + [0.0000635073108731, 5.9096803285953996e+00, 1.7693227129285001e+00], + [0.0000599351698525, 4.1125517584797997e+00, -2.7985797954588998e+00], + [0.0000540660842731, 5.5390350845569003e+00, 2.8683408228299999e-03], + [-0.0000489596900866, 4.6218149483337996e+00, -6.2695712529518999e-01] + ], + zeta: [ + [0.0038422977898495, 2.4133922085556998e+00, 0.0000000000000000e+00], + [0.0022453891791894, 5.9721736773277003e+00, -3.0561255249999997e-05], + [-0.0002604479450559, 3.3368746306408998e+00, -1.2491309972000001e-04], + [0.0000332112143230, 5.5604137742336999e+00, 2.9003768850700000e-03] + ] + } +]; +/** + * @brief Holds the positions and velocities of Jupiter's major 4 moons. + * + * The {@link JupiterMoons} function returns an object of this type + * to report position and velocity vectors for Jupiter's largest 4 moons + * Io, Europa, Ganymede, and Callisto. Each position vector is relative + * to the center of Jupiter. Both position and velocity are oriented in + * the EQJ system (that is, using Earth's equator at the J2000 epoch). + * The positions are expressed in astronomical units (AU), + * and the velocities in AU/day. + * + * @property {StateVector} io + * The position and velocity of Jupiter's moon Io. + * + * @property {StateVector} europa + * The position and velocity of Jupiter's moon Europa. + * + * @property {StateVector} ganymede + * The position and velocity of Jupiter's moon Ganymede. + * + * @property {StateVector} callisto + * The position and velocity of Jupiter's moon Callisto. + */ +class JupiterMoonsInfo { + constructor(io, europa, ganymede, callisto) { + this.io = io; + this.europa = europa; + this.ganymede = ganymede; + this.callisto = callisto; + } +} +exports.JupiterMoonsInfo = JupiterMoonsInfo; +function JupiterMoon_elem2pv(time, mu, elem) { + // Translation of FORTRAN subroutine ELEM2PV from: + // https://ftp.imcce.fr/pub/ephem/satel/galilean/L1/L1.2/ + const A = elem[0]; + const AL = elem[1]; + const K = elem[2]; + const H = elem[3]; + const Q = elem[4]; + const P = elem[5]; + const AN = Math.sqrt(mu / (A * A * A)); + let CE, SE, DE; + let EE = AL + K * Math.sin(AL) - H * Math.cos(AL); + do { + CE = Math.cos(EE); + SE = Math.sin(EE); + DE = (AL - EE + K * SE - H * CE) / (1.0 - K * CE - H * SE); + EE += DE; + } while (Math.abs(DE) >= 1.0e-12); + CE = Math.cos(EE); + SE = Math.sin(EE); + const DLE = H * CE - K * SE; + const RSAM1 = -K * CE - H * SE; + const ASR = 1.0 / (1.0 + RSAM1); + const PHI = Math.sqrt(1.0 - K * K - H * H); + const PSI = 1.0 / (1.0 + PHI); + const X1 = A * (CE - K - PSI * H * DLE); + const Y1 = A * (SE - H + PSI * K * DLE); + const VX1 = AN * ASR * A * (-SE - PSI * H * RSAM1); + const VY1 = AN * ASR * A * (+CE + PSI * K * RSAM1); + const F2 = 2.0 * Math.sqrt(1.0 - Q * Q - P * P); + const P2 = 1.0 - 2.0 * P * P; + const Q2 = 1.0 - 2.0 * Q * Q; + const PQ = 2.0 * P * Q; + return new StateVector(X1 * P2 + Y1 * PQ, X1 * PQ + Y1 * Q2, (Q * Y1 - X1 * P) * F2, VX1 * P2 + VY1 * PQ, VX1 * PQ + VY1 * Q2, (Q * VY1 - VX1 * P) * F2, time); +} +function CalcJupiterMoon(time, m) { + // This is a translation of FORTRAN code by Duriez, Lainey, and Vienne: + // https://ftp.imcce.fr/pub/ephem/satel/galilean/L1/L1.2/ + const t = time.tt + 18262.5; // number of days since 1950-01-01T00:00:00Z + // Calculate 6 orbital elements at the given time t + const elem = [0, m.al[0] + (t * m.al[1]), 0, 0, 0, 0]; + for (let [amplitude, phase, frequency] of m.a) + elem[0] += amplitude * Math.cos(phase + (t * frequency)); + for (let [amplitude, phase, frequency] of m.l) + elem[1] += amplitude * Math.sin(phase + (t * frequency)); + elem[1] %= PI2; + if (elem[1] < 0) + elem[1] += PI2; + for (let [amplitude, phase, frequency] of m.z) { + const arg = phase + (t * frequency); + elem[2] += amplitude * Math.cos(arg); + elem[3] += amplitude * Math.sin(arg); + } + for (let [amplitude, phase, frequency] of m.zeta) { + const arg = phase + (t * frequency); + elem[4] += amplitude * Math.cos(arg); + elem[5] += amplitude * Math.sin(arg); + } + // Convert the oribital elements into position vectors in the Jupiter equatorial system (JUP). + const state = JupiterMoon_elem2pv(time, m.mu, elem); + // Re-orient position and velocity vectors from Jupiter-equatorial (JUP) to Earth-equatorial in J2000 (EQJ). + return RotateState(Rotation_JUP_EQJ, state); +} +/** + * @brief Calculates jovicentric positions and velocities of Jupiter's largest 4 moons. + * + * Calculates position and velocity vectors for Jupiter's moons + * Io, Europa, Ganymede, and Callisto, at the given date and time. + * The vectors are jovicentric (relative to the center of Jupiter). + * Their orientation is the Earth's equatorial system at the J2000 epoch (EQJ). + * The position components are expressed in astronomical units (AU), and the + * velocity components are in AU/day. + * + * To convert to heliocentric vectors, call {@link HelioVector} + * with `Astronomy.Body.Jupiter` to get Jupiter's heliocentric position, then + * add the jovicentric vectors. Likewise, you can call {@link GeoVector} + * to convert to geocentric vectors. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate Jupiter's moons. + * + * @return {JupiterMoonsInfo} + * Position and velocity vectors of Jupiter's largest 4 moons. + */ +function JupiterMoons(date) { + const time = new AstroTime(date); + return new JupiterMoonsInfo(CalcJupiterMoon(time, JupiterMoonModel[0]), CalcJupiterMoon(time, JupiterMoonModel[1]), CalcJupiterMoon(time, JupiterMoonModel[2]), CalcJupiterMoon(time, JupiterMoonModel[3])); +} +exports.JupiterMoons = JupiterMoons; +// Jupiter Moons ends -------------------------------------------------------- +/** + * @brief Calculates a vector from the center of the Sun to the given body at the given time. + * + * Calculates heliocentric (i.e., with respect to the center of the Sun) + * Cartesian coordinates in the J2000 equatorial system of a celestial + * body at a specified time. The position is not corrected for light travel time or aberration. + * + * @param {Body} body + * One of the following values: + * `Body.Sun`, `Body.Moon`, `Body.Mercury`, `Body.Venus`, + * `Body.Earth`, `Body.Mars`, `Body.Jupiter`, `Body.Saturn`, + * `Body.Uranus`, `Body.Neptune`, `Body.Pluto`, + * `Body.SSB`, or `Body.EMB`. + * Also allowed to be a user-defined star created by {@link DefineStar}. + * + * @param {FlexibleDateTime} date + * The date and time for which the body's position is to be calculated. + * + * @returns {Vector} + */ +function HelioVector(body, date) { + var time = MakeTime(date); + if (body in vsop) + return CalcVsop(vsop[body], time); + if (body === Body.Pluto) { + const p = CalcPluto(time, true); + return new Vector(p.x, p.y, p.z, time); + } + if (body === Body.Sun) + return new Vector(0, 0, 0, time); + if (body === Body.Moon) { + var e = CalcVsop(vsop.Earth, time); + var m = GeoMoon(time); + return new Vector(e.x + m.x, e.y + m.y, e.z + m.z, time); + } + if (body === Body.EMB) { + const e = CalcVsop(vsop.Earth, time); + const m = GeoMoon(time); + const denom = 1.0 + EARTH_MOON_MASS_RATIO; + return new Vector(e.x + (m.x / denom), e.y + (m.y / denom), e.z + (m.z / denom), time); + } + if (body === Body.SSB) + return CalcSolarSystemBarycenter(time); + const star = UserDefinedStar(body); + if (star) { + const sphere = new Spherical(star.dec, 15 * star.ra, star.dist); + return VectorFromSphere(sphere, time); + } + throw `HelioVector: Unknown body "${body}"`; +} +exports.HelioVector = HelioVector; +; +/** + * @brief Calculates the distance between a body and the Sun at a given time. + * + * Given a date and time, this function calculates the distance between + * the center of `body` and the center of the Sun. + * For the planets Mercury through Neptune, this function is significantly + * more efficient than calling {@link HelioVector} followed by taking the length + * of the resulting vector. + * + * @param {Body} body + * A body for which to calculate a heliocentric distance: + * the Sun, Moon, any of the planets, or a user-defined star. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the heliocentric distance. + * + * @returns {number} + * The heliocentric distance in AU. + */ +function HelioDistance(body, date) { + const star = UserDefinedStar(body); + if (star) + return star.dist; + const time = MakeTime(date); + if (body in vsop) + return VsopFormula(vsop[body][RAD_INDEX], time.tt / DAYS_PER_MILLENNIUM, false); + return HelioVector(body, time).Length(); +} +exports.HelioDistance = HelioDistance; +/** + * Solve for light travel time of a vector function. + * + * When observing a distant object, for example Jupiter as seen from Earth, + * the amount of time it takes for light to travel from the object to the + * observer can significantly affect the object's apparent position. + * This function is a generic solver that figures out how long in the + * past light must have left the observed object to reach the observer + * at the specified observation time. It requires passing in `func` + * to express an arbitrary position vector as a function of time. + * + * `CorrectLightTravel` repeatedly calls `func`, passing a series of time + * estimates in the past. Then `func` must return a relative position vector between + * the observer and the target. `CorrectLightTravel` keeps calling + * `func` with more and more refined estimates of the time light must have + * left the target to arrive at the observer. + * + * For common use cases, it is simpler to use {@link BackdatePosition} + * for calculating the light travel time correction of one body observing another body. + * + * For geocentric calculations, {@link GeoVector} also backdates the returned + * position vector for light travel time, only it returns the observation time in + * the returned vector's `t` field rather than the backdated time. + * + * @param {function(AstroTime): number} func + * An arbitrary position vector as a function of time: + * function({@link AstroTime}) => {@link Vector}. + * + * @param {AstroTime} time + * The observation time for which to solve for light travel delay. + * + * @returns {AstroVector} + * The position vector at the solved backdated time. + * The `t` field holds the time that light left the observed + * body to arrive at the observer at the observation time. + */ +function CorrectLightTravel(func, time) { + let ltime = time; + let dt = 0; + for (let iter = 0; iter < 10; ++iter) { + const pos = func(ltime); + const lt = pos.Length() / exports.C_AUDAY; + // This solver does not support more than one light-day of distance, + // because that would cause convergence problems and inaccurate + // values for stellar aberration angles. + if (lt > 1.0) + throw `Object is too distant for light-travel solver.`; + const ltime2 = time.AddDays(-lt); + dt = Math.abs(ltime2.tt - ltime.tt); + if (dt < 1.0e-9) // 86.4 microseconds + return pos; + ltime = ltime2; + } + throw `Light-travel time solver did not converge: dt = ${dt}`; +} +exports.CorrectLightTravel = CorrectLightTravel; +class BodyPosition { + constructor(observerBody, targetBody, aberration, observerPos) { + this.observerBody = observerBody; + this.targetBody = targetBody; + this.aberration = aberration; + this.observerPos = observerPos; + } + Position(time) { + if (this.aberration) { + // The following discussion is worded with the observer body being the Earth, + // which is often the case. However, the same reasoning applies to any observer body + // without loss of generality. + // + // To include aberration, make a good first-order approximation + // by backdating the Earth's position also. + // This is confusing, but it works for objects within the Solar System + // because the distance the Earth moves in that small amount of light + // travel time (a few minutes to a few hours) is well approximated + // by a line segment that substends the angle seen from the remote + // body viewing Earth. That angle is pretty close to the aberration + // angle of the moving Earth viewing the remote body. + // In other words, both of the following approximate the aberration angle: + // (transverse distance Earth moves) / (distance to body) + // (transverse speed of Earth) / (speed of light). + this.observerPos = HelioVector(this.observerBody, time); + } + else { + // No aberration, so use the pre-calculated initial position of + // the observer body that is already stored in `observerPos`. + } + const targetPos = HelioVector(this.targetBody, time); + return new Vector(targetPos.x - this.observerPos.x, targetPos.y - this.observerPos.y, targetPos.z - this.observerPos.z, time); + } +} +/** + * @brief Solve for light travel time correction of apparent position. + * + * When observing a distant object, for example Jupiter as seen from Earth, + * the amount of time it takes for light to travel from the object to the + * observer can significantly affect the object's apparent position. + * + * This function solves the light travel time correction for the apparent + * relative position vector of a target body as seen by an observer body + * at a given observation time. + * + * For geocentric calculations, {@link GeoVector} also includes light + * travel time correction, but the time `t` embedded in its returned vector + * refers to the observation time, not the backdated time that light left + * the observed body. Thus `BackdatePosition` provides direct + * access to the light departure time for callers that need it. + * + * For a more generalized light travel correction solver, see {@link CorrectLightTravel}. + * + * @param {FlexibleDateTime} date + * The time of observation. + * + * @param {Body} observerBody + * The body to be used as the observation location. + * + * @param {Body} targetBody + * The body to be observed. + * + * @param {boolean} aberration + * `true` to correct for aberration, or `false` to leave uncorrected. + * + * @returns {Vector} + * The position vector at the solved backdated time. + * The `t` field holds the time that light left the observed + * body to arrive at the observer at the observation time. + */ +function BackdatePosition(date, observerBody, targetBody, aberration) { + VerifyBoolean(aberration); + const time = MakeTime(date); + if (UserDefinedStar(targetBody)) { + // This is a user-defined star, which must be treated as a special case. + // First, we assume its heliocentric position does not change with time. + // Second, we assume its heliocentric position has already been corrected + // for light-travel time, its coordinates given as it appears on Earth at the present. + // Therefore, no backdating is applied. + const tvec = HelioVector(targetBody, time); + if (aberration) { + // (Observer velocity) - (light vector) = (Aberration-corrected direction to target body). + // Note that this is an approximation, because technically the light vector should + // be measured in barycentric coordinates, not heliocentric. The error is very small. + const ostate = HelioState(observerBody, time); + const rvec = new Vector(tvec.x - ostate.x, tvec.y - ostate.y, tvec.z - ostate.z, time); + const s = exports.C_AUDAY / rvec.Length(); // conversion factor from relative distance to speed of light + return new Vector(rvec.x + ostate.vx / s, rvec.y + ostate.vy / s, rvec.z + ostate.vz / s, time); + } + // No correction is needed. Simply return the star's current position as seen from the observer. + const ovec = HelioVector(observerBody, time); + return new Vector(tvec.x - ovec.x, tvec.y - ovec.y, tvec.z - ovec.z, time); + } + let observerPos; + if (aberration) { + // With aberration, `BackdatePosition` will calculate `observerPos` at different times. + // Therefore, do not waste time calculating it now. + // Create a placeholder value that will be ignored. + observerPos = new Vector(0, 0, 0, time); + } + else { + observerPos = HelioVector(observerBody, time); + } + const bpos = new BodyPosition(observerBody, targetBody, aberration, observerPos); + return CorrectLightTravel(t => bpos.Position(t), time); +} +exports.BackdatePosition = BackdatePosition; +/** + * @brief Calculates a vector from the center of the Earth to the given body at the given time. + * + * Calculates geocentric (i.e., with respect to the center of the Earth) + * Cartesian coordinates in the J2000 equatorial system of a celestial + * body at a specified time. The position is always corrected for light travel time: + * this means the position of the body is "back-dated" based on how long it + * takes light to travel from the body to an observer on the Earth. + * Also, the position can optionally be corrected for aberration, an effect + * causing the apparent direction of the body to be shifted based on + * transverse movement of the Earth with respect to the rays of light + * coming from that body. + * + * @param {Body} body + * One of the following values: + * `Body.Sun`, `Body.Moon`, `Body.Mercury`, `Body.Venus`, + * `Body.Earth`, `Body.Mars`, `Body.Jupiter`, `Body.Saturn`, + * `Body.Uranus`, `Body.Neptune`, or `Body.Pluto`. + * Also allowed to be a user-defined star created with {@link DefineStar}. + * + * @param {FlexibleDateTime} date + * The date and time for which the body's position is to be calculated. + * + * @param {boolean} aberration + * Pass `true` to correct for + * aberration, + * or `false` to leave uncorrected. + * + * @returns {Vector} + */ +function GeoVector(body, date, aberration) { + VerifyBoolean(aberration); + const time = MakeTime(date); + switch (body) { + case Body.Earth: + return new Vector(0, 0, 0, time); + case Body.Moon: + return GeoMoon(time); + default: + const vec = BackdatePosition(time, Body.Earth, body, aberration); + vec.t = time; // tricky: return the observation time, not the backdated time + return vec; + } +} +exports.GeoVector = GeoVector; +function ExportState(terse, time) { + return new StateVector(terse.r.x, terse.r.y, terse.r.z, terse.v.x, terse.v.y, terse.v.z, time); +} +/** + * @brief Calculates barycentric position and velocity vectors for the given body. + * + * Given a body and a time, calculates the barycentric position and velocity + * vectors for the center of that body at that time. + * The vectors are expressed in J2000 mean equator coordinates (EQJ). + * + * @param {Body} body + * The celestial body whose barycentric state vector is to be calculated. + * Supported values are `Body.Sun`, `Body.Moon`, `Body.EMB`, `Body.SSB`, and all planets: + * `Body.Mercury`, `Body.Venus`, `Body.Earth`, `Body.Mars`, `Body.Jupiter`, + * `Body.Saturn`, `Body.Uranus`, `Body.Neptune`, `Body.Pluto`. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate position and velocity. + * + * @returns {StateVector} + * An object that contains barycentric position and velocity vectors. + */ +function BaryState(body, date) { + const time = MakeTime(date); + if (body === Body.SSB) { + // Trivial case: the solar system barycenter itself. + return new StateVector(0, 0, 0, 0, 0, 0, time); + } + if (body === Body.Pluto) { + return CalcPluto(time, false); + } + // Find the barycentric positions and velocities for the 5 major bodies: + // Sun, Jupiter, Saturn, Uranus, Neptune. + const bary = new major_bodies_t(time.tt); + switch (body) { + case Body.Sun: return ExportState(bary.Sun, time); + case Body.Jupiter: return ExportState(bary.Jupiter, time); + case Body.Saturn: return ExportState(bary.Saturn, time); + case Body.Uranus: return ExportState(bary.Uranus, time); + case Body.Neptune: return ExportState(bary.Neptune, time); + case Body.Moon: + case Body.EMB: + const earth = CalcVsopPosVel(vsop[Body.Earth], time.tt); + const state = (body === Body.Moon) ? GeoMoonState(time) : GeoEmbState(time); + return new StateVector(state.x + bary.Sun.r.x + earth.r.x, state.y + bary.Sun.r.y + earth.r.y, state.z + bary.Sun.r.z + earth.r.z, state.vx + bary.Sun.v.x + earth.v.x, state.vy + bary.Sun.v.y + earth.v.y, state.vz + bary.Sun.v.z + earth.v.z, time); + } + // Handle the remaining VSOP bodies: Mercury, Venus, Earth, Mars. + if (body in vsop) { + const planet = CalcVsopPosVel(vsop[body], time.tt); + return new StateVector(bary.Sun.r.x + planet.r.x, bary.Sun.r.y + planet.r.y, bary.Sun.r.z + planet.r.z, bary.Sun.v.x + planet.v.x, bary.Sun.v.y + planet.v.y, bary.Sun.v.z + planet.v.z, time); + } + throw `BaryState: Unsupported body "${body}"`; +} +exports.BaryState = BaryState; +/** + * @brief Calculates heliocentric position and velocity vectors for the given body. + * + * Given a body and a time, calculates the position and velocity + * vectors for the center of that body at that time, relative to the center of the Sun. + * The vectors are expressed in J2000 mean equator coordinates (EQJ). + * If you need the position vector only, it is more efficient to call {@link HelioVector}. + * The Sun's center is a non-inertial frame of reference. In other words, the Sun + * experiences acceleration due to gravitational forces, mostly from the larger + * planets (Jupiter, Saturn, Uranus, and Neptune). If you want to calculate momentum, + * kinetic energy, or other quantities that require a non-accelerating frame + * of reference, consider using {@link BaryState} instead. + * + * @param {Body} body + * The celestial body whose heliocentric state vector is to be calculated. + * Supported values are `Body.Sun`, `Body.Moon`, `Body.EMB`, `Body.SSB`, and all planets: + * `Body.Mercury`, `Body.Venus`, `Body.Earth`, `Body.Mars`, `Body.Jupiter`, + * `Body.Saturn`, `Body.Uranus`, `Body.Neptune`, `Body.Pluto`. + * Also allowed to be a user-defined star created by {@link DefineStar}. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate position and velocity. + * + * @returns {StateVector} + * An object that contains heliocentric position and velocity vectors. + */ +function HelioState(body, date) { + const time = MakeTime(date); + switch (body) { + case Body.Sun: + // Trivial case: the Sun is the origin of the heliocentric frame. + return new StateVector(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, time); + case Body.SSB: + // Calculate the barycentric Sun. Then the negative of that is the heliocentric SSB. + const bary = new major_bodies_t(time.tt); + return new StateVector(-bary.Sun.r.x, -bary.Sun.r.y, -bary.Sun.r.z, -bary.Sun.v.x, -bary.Sun.v.y, -bary.Sun.v.z, time); + case Body.Mercury: + case Body.Venus: + case Body.Earth: + case Body.Mars: + case Body.Jupiter: + case Body.Saturn: + case Body.Uranus: + case Body.Neptune: + // Planets included in the VSOP87 model. + const planet = CalcVsopPosVel(vsop[body], time.tt); + return ExportState(planet, time); + case Body.Pluto: + return CalcPluto(time, true); + case Body.Moon: + case Body.EMB: + const earth = CalcVsopPosVel(vsop.Earth, time.tt); + const state = (body == Body.Moon) ? GeoMoonState(time) : GeoEmbState(time); + return new StateVector(state.x + earth.r.x, state.y + earth.r.y, state.z + earth.r.z, state.vx + earth.v.x, state.vy + earth.v.y, state.vz + earth.v.z, time); + default: + if (UserDefinedStar(body)) { + const vec = HelioVector(body, time); + return new StateVector(vec.x, vec.y, vec.z, 0, 0, 0, time); + } + throw `HelioState: Unsupported body "${body}"`; + } +} +exports.HelioState = HelioState; +function QuadInterp(tm, dt, fa, fm, fb) { + let Q = (fb + fa) / 2 - fm; + let R = (fb - fa) / 2; + let S = fm; + let x; + if (Q == 0) { + // This is a line, not a parabola. + if (R == 0) { + // This is a HORIZONTAL line... can't make progress! + return null; + } + x = -S / R; + if (x < -1 || x > +1) + return null; // out of bounds + } + else { + // It really is a parabola. Find roots x1, x2. + let u = R * R - 4 * Q * S; + if (u <= 0) + return null; + let ru = Math.sqrt(u); + let x1 = (-R + ru) / (2 * Q); + let x2 = (-R - ru) / (2 * Q); + if (-1 <= x1 && x1 <= +1) { + if (-1 <= x2 && x2 <= +1) + return null; + x = x1; + } + else if (-1 <= x2 && x2 <= +1) { + x = x2; + } + else { + return null; + } + } + let t = tm + x * dt; + let df_dt = (2 * Q * x + R) / dt; + return { t: t, df_dt: df_dt }; +} +/** + * @brief Options for the {@link Search} function. + * + * @typedef {object} SearchOptions + * + * @property {number | undefined} dt_tolerance_seconds + * The number of seconds for a time window smaller than which the search + * is considered successful. Using too large a tolerance can result in + * an inaccurate time estimate. Using too small a tolerance can cause + * excessive computation, or can even cause the search to fail because of + * limited floating-point resolution. Defaults to 1 second. + * + * @property {number | undefined} init_f1 + * As an optimization, if the caller of {@link Search} + * has already calculated the value of the function being searched (the parameter `func`) + * at the time coordinate `t1`, it can pass in that value as `init_f1`. + * For very expensive calculations, this can measurably improve performance. + * + * @property {number | undefined} init_f2 + * The same as `init_f1`, except this is the optional initial value of `func(t2)` + * instead of `func(t1)`. + * + * @property {number | undefined} iter_limit + */ +/** + * @brief Finds the time when a function ascends through zero. + * + * Search for next time t (such that t is between `t1` and `t2`) + * that `func(t)` crosses from a negative value to a non-negative value. + * The given function must have "smooth" behavior over the entire inclusive range [`t1`, `t2`], + * meaning that it behaves like a continuous differentiable function. + * It is not required that `t1` < `t2`; `t1` > `t2` + * allows searching backward in time. + * Note: `t1` and `t2` must be chosen such that there is no possibility + * of more than one zero-crossing (ascending or descending), or it is possible + * that the "wrong" event will be found (i.e. not the first event after t1) + * or even that the function will return `null`, indicating that no event was found. + * + * @param {function(AstroTime): number} func + * The function to find an ascending zero crossing for. + * The function must accept a single parameter of type {@link AstroTime} + * and return a numeric value: + * function({@link AstroTime}) => `number` + * + * @param {AstroTime} t1 + * The lower time bound of a search window. + * + * @param {AstroTime} t2 + * The upper time bound of a search window. + * + * @param {SearchOptions | undefined} options + * Options that can tune the behavior of the search. + * Most callers can omit this argument. + * + * @returns {AstroTime | null} + * If the search is successful, returns the date and time of the solution. + * If the search fails, returns `null`. + */ +function Search(f, t1, t2, options) { + const dt_tolerance_seconds = VerifyNumber((options && options.dt_tolerance_seconds) || 1); + const dt_days = Math.abs(dt_tolerance_seconds / SECONDS_PER_DAY); + let f1 = (options && options.init_f1) || f(t1); + let f2 = (options && options.init_f2) || f(t2); + let fmid = NaN; + let iter = 0; + let iter_limit = (options && options.iter_limit) || 20; + let calc_fmid = true; + while (true) { + if (++iter > iter_limit) + throw `Excessive iteration in Search()`; + let tmid = InterpolateTime(t1, t2, 0.5); + let dt = tmid.ut - t1.ut; + if (Math.abs(dt) < dt_days) { + // We are close enough to the event to stop the search. + return tmid; + } + if (calc_fmid) + fmid = f(tmid); + else + calc_fmid = true; // we already have the correct value of fmid from the previous loop + // Quadratic interpolation: + // Try to find a parabola that passes through the 3 points we have sampled: + // (t1,f1), (tmid,fmid), (t2,f2). + let q = QuadInterp(tmid.ut, t2.ut - tmid.ut, f1, fmid, f2); + // Did we find an approximate root-crossing? + if (q) { + // Evaluate the function at our candidate solution. + let tq = MakeTime(q.t); + let fq = f(tq); + if (q.df_dt !== 0) { + if (Math.abs(fq / q.df_dt) < dt_days) { + // The estimated time error is small enough that we can quit now. + return tq; + } + // Try guessing a tighter boundary with the interpolated root at the center. + let dt_guess = 1.2 * Math.abs(fq / q.df_dt); + if (dt_guess < dt / 10) { + let tleft = tq.AddDays(-dt_guess); + let tright = tq.AddDays(+dt_guess); + if ((tleft.ut - t1.ut) * (tleft.ut - t2.ut) < 0) { + if ((tright.ut - t1.ut) * (tright.ut - t2.ut) < 0) { + let fleft = f(tleft); + let fright = f(tright); + if (fleft < 0 && fright >= 0) { + f1 = fleft; + f2 = fright; + t1 = tleft; + t2 = tright; + fmid = fq; + calc_fmid = false; + continue; + } + } + } + } + } + } + if (f1 < 0 && fmid >= 0) { + t2 = tmid; + f2 = fmid; + continue; + } + if (fmid < 0 && f2 >= 0) { + t1 = tmid; + f1 = fmid; + continue; + } + // Either there is no ascending zero-crossing in this range + // or the search window is too wide. + return null; + } +} +exports.Search = Search; +function LongitudeOffset(diff) { + let offset = diff; + while (offset <= -180) + offset += 360; + while (offset > 180) + offset -= 360; + return offset; +} +function NormalizeLongitude(lon) { + while (lon < 0) + lon += 360; + while (lon >= 360) + lon -= 360; + return lon; +} +/** + * @brief Searches for when the Sun reaches a given ecliptic longitude. + * + * Searches for the moment in time when the center of the Sun reaches a given apparent + * ecliptic longitude, as seen from the center of the Earth, within a given range of dates. + * This function can be used to determine equinoxes and solstices. + * However, it is usually more convenient and efficient to call {@link Seasons} + * to calculate equinoxes and solstices for a given calendar year. + * `SearchSunLongitude` is more general in that it allows searching for arbitrary longitude values. + * + * @param {number} targetLon + * The desired ecliptic longitude of date in degrees. + * This may be any value in the range [0, 360), although certain + * values have conventional meanings: + * + * When `targetLon` is 0, finds the March equinox, + * which is the moment spring begins in the northern hemisphere + * and the beginning of autumn in the southern hemisphere. + * + * When `targetLon` is 180, finds the September equinox, + * which is the moment autumn begins in the northern hemisphere and + * spring begins in the southern hemisphere. + * + * When `targetLon` is 90, finds the northern solstice, which is the + * moment summer begins in the northern hemisphere and winter + * begins in the southern hemisphere. + * + * When `targetLon` is 270, finds the southern solstice, which is the + * moment winter begins in the northern hemisphere and summer + * begins in the southern hemisphere. + * + * @param {FlexibleDateTime} dateStart + * A date and time known to be earlier than the desired longitude event. + * + * @param {number} limitDays + * A floating point number of days, which when added to `dateStart`, + * yields a date and time known to be after the desired longitude event. + * + * @returns {AstroTime | null} + * The date and time when the Sun reaches the apparent ecliptic longitude `targetLon` + * within the range of times specified by `dateStart` and `limitDays`. + * If the Sun does not reach the target longitude within the specified time range, or the + * time range is excessively wide, the return value is `null`. + * To avoid a `null` return value, the caller must pick a time window around + * the event that is within a few days but not so small that the event might fall outside the window. + */ +function SearchSunLongitude(targetLon, dateStart, limitDays) { + function sun_offset(t) { + let pos = SunPosition(t); + return LongitudeOffset(pos.elon - targetLon); + } + VerifyNumber(targetLon); + VerifyNumber(limitDays); + let t1 = MakeTime(dateStart); + let t2 = t1.AddDays(limitDays); + return Search(sun_offset, t1, t2, { dt_tolerance_seconds: 0.01 }); +} +exports.SearchSunLongitude = SearchSunLongitude; +/** + * @brief Returns one body's ecliptic longitude with respect to another, as seen from the Earth. + * + * This function determines where one body appears around the ecliptic plane + * (the plane of the Earth's orbit around the Sun) as seen from the Earth, + * relative to the another body's apparent position. + * The function returns an angle in the half-open range [0, 360) degrees. + * The value is the ecliptic longitude of `body1` relative to the ecliptic + * longitude of `body2`. + * + * The angle is 0 when the two bodies are at the same ecliptic longitude + * as seen from the Earth. The angle increases in the prograde direction + * (the direction that the planets orbit the Sun and the Moon orbits the Earth). + * + * When the angle is 180 degrees, it means the two bodies appear on opposite sides + * of the sky for an Earthly observer. + * + * Neither `body1` nor `body2` is allowed to be `Body.Earth`. + * If this happens, the function throws an exception. + * + * @param {Body} body1 + * The first body, whose longitude is to be found relative to the second body. + * + * @param {Body} body2 + * The second body, relative to which the longitude of the first body is to be found. + * + * @param {FlexibleDateTime} date + * The date and time of the observation. + * + * @returns {number} + * An angle in the range [0, 360), expressed in degrees. + */ +function PairLongitude(body1, body2, date) { + if (body1 === Body.Earth || body2 === Body.Earth) + throw 'The Earth does not have a longitude as seen from itself.'; + const time = MakeTime(date); + const vector1 = GeoVector(body1, time, false); + const eclip1 = Ecliptic(vector1); + const vector2 = GeoVector(body2, time, false); + const eclip2 = Ecliptic(vector2); + return NormalizeLongitude(eclip1.elon - eclip2.elon); +} +exports.PairLongitude = PairLongitude; +/** + * @brief Calculates the angular separation between the Sun and the given body. + * + * Returns the full angle seen from + * the Earth, between the given body and the Sun. + * Unlike {@link PairLongitude}, this function does not + * project the body's "shadow" onto the ecliptic; + * the angle is measured in 3D space around the plane that + * contains the centers of the Earth, the Sun, and `body`. + * + * @param {Body} body + * The name of a supported celestial body other than the Earth. + * + * @param {FlexibleDateTime} date + * The time at which the angle from the Sun is to be found. + * + * @returns {number} + * An angle in degrees in the range [0, 180]. + */ +function AngleFromSun(body, date) { + if (body == Body.Earth) + throw 'The Earth does not have an angle as seen from itself.'; + const time = MakeTime(date); + const sv = GeoVector(Body.Sun, time, true); + const bv = GeoVector(body, time, true); + const angle = AngleBetween(sv, bv); + return angle; +} +exports.AngleFromSun = AngleFromSun; +/** + * @brief Calculates heliocentric ecliptic longitude of a body. + * + * This function calculates the angle around the plane of the Earth's orbit + * of a celestial body, as seen from the center of the Sun. + * The angle is measured prograde (in the direction of the Earth's orbit around the Sun) + * in degrees from the true equinox of date. The ecliptic longitude is always in the range [0, 360). + * + * @param {Body} body + * A body other than the Sun. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the ecliptic longitude. + * + * @returns {number} + */ +function EclipticLongitude(body, date) { + if (body === Body.Sun) + throw 'Cannot calculate heliocentric longitude of the Sun.'; + const hv = HelioVector(body, date); + const eclip = Ecliptic(hv); + return eclip.elon; +} +exports.EclipticLongitude = EclipticLongitude; +function VisualMagnitude(body, phase, helio_dist, geo_dist) { + // For Mercury and Venus, see: https://iopscience.iop.org/article/10.1086/430212 + let c0, c1 = 0, c2 = 0, c3 = 0; + switch (body) { + case Body.Mercury: + c0 = -0.60; + c1 = +4.98; + c2 = -4.88; + c3 = +3.02; + break; + case Body.Venus: + if (phase < 163.6) { + c0 = -4.47; + c1 = +1.03; + c2 = +0.57; + c3 = +0.13; + } + else { + c0 = 0.98; + c1 = -1.02; + } + break; + case Body.Mars: + c0 = -1.52; + c1 = +1.60; + break; + case Body.Jupiter: + c0 = -9.40; + c1 = +0.50; + break; + case Body.Uranus: + c0 = -7.19; + c1 = +0.25; + break; + case Body.Neptune: + c0 = -6.87; + break; + case Body.Pluto: + c0 = -1.00; + c1 = +4.00; + break; + default: throw `VisualMagnitude: unsupported body ${body}`; + } + const x = phase / 100; + let mag = c0 + x * (c1 + x * (c2 + x * c3)); + mag += 5 * Math.log10(helio_dist * geo_dist); + return mag; +} +function SaturnMagnitude(phase, helio_dist, geo_dist, gc, time) { + // Based on formulas by Paul Schlyter found here: + // http://www.stjarnhimlen.se/comp/ppcomp.html#15 + // We must handle Saturn's rings as a major component of its visual magnitude. + // Find geocentric ecliptic coordinates of Saturn. + const eclip = Ecliptic(gc); + const ir = exports.DEG2RAD * 28.06; // tilt of Saturn's rings to the ecliptic, in radians + const Nr = exports.DEG2RAD * (169.51 + (3.82e-5 * time.tt)); // ascending node of Saturn's rings, in radians + // Find tilt of Saturn's rings, as seen from Earth. + const lat = exports.DEG2RAD * eclip.elat; + const lon = exports.DEG2RAD * eclip.elon; + const tilt = Math.asin(Math.sin(lat) * Math.cos(ir) - Math.cos(lat) * Math.sin(ir) * Math.sin(lon - Nr)); + const sin_tilt = Math.sin(Math.abs(tilt)); + let mag = -9.0 + 0.044 * phase; + mag += sin_tilt * (-2.6 + 1.2 * sin_tilt); + mag += 5 * Math.log10(helio_dist * geo_dist); + return { mag: mag, ring_tilt: exports.RAD2DEG * tilt }; +} +function MoonMagnitude(phase, helio_dist, geo_dist) { + // https://astronomy.stackexchange.com/questions/10246/is-there-a-simple-analytical-formula-for-the-lunar-phase-brightness-curve + let rad = phase * exports.DEG2RAD; + let rad2 = rad * rad; + let rad4 = rad2 * rad2; + let mag = -12.717 + 1.49 * Math.abs(rad) + 0.0431 * rad4; + const moon_mean_distance_au = 385000.6 / exports.KM_PER_AU; + let geo_au = geo_dist / moon_mean_distance_au; + mag += 5 * Math.log10(helio_dist * geo_au); + return mag; +} +/** + * @brief Information about the apparent brightness and sunlit phase of a celestial object. + * + * @property {AstroTime} time + * The date and time pertaining to the other calculated values in this object. + * + * @property {number} mag + * The apparent visual magnitude of the celestial body. + * + * @property {number} phase_angle + * The angle in degrees as seen from the center of the celestial body between the Sun and the Earth. + * The value is always in the range 0 to 180. + * The phase angle provides a measure of what fraction of the body's face appears + * illuminated by the Sun as seen from the Earth. + * When the observed body is the Sun, the `phase` property is set to 0, + * although this has no physical meaning because the Sun emits, rather than reflects, light. + * When the phase is near 0 degrees, the body appears "full". + * When it is 90 degrees, the body appears "half full". + * And when it is 180 degrees, the body appears "new" and is very difficult to see + * because it is both dim and lost in the Sun's glare as seen from the Earth. + * + * @property {number} phase_fraction + * The fraction of the body's face that is illuminated by the Sun, as seen from the Earth. + * Calculated from `phase_angle` for convenience. + * This value ranges from 0 to 1. + * + * @property {number} helio_dist + * The distance between the center of the Sun and the center of the body in + * astronomical units (AU). + * + * @property {number} geo_dist + * The distance between the center of the Earth and the center of the body in AU. + * + * @property {Vector} gc + * Geocentric coordinates: the 3D vector from the center of the Earth to the center of the body. + * The components are in expressed in AU and are oriented with respect to the J2000 equatorial plane. + * + * @property {Vector} hc + * Heliocentric coordinates: The 3D vector from the center of the Sun to the center of the body. + * Like `gc`, `hc` is expressed in AU and oriented with respect + * to the J2000 equatorial plane. + * + * @property {number | undefined} ring_tilt + * For Saturn, this is the angular tilt of the planet's rings in degrees away + * from the line of sight from the Earth. When the value is near 0, the rings + * appear edge-on from the Earth and are therefore difficult to see. + * When `ring_tilt` approaches its maximum value (about 27 degrees), + * the rings appear widest and brightest from the Earth. + * Unlike the JPL Horizons online tool, + * this library includes the effect of the ring tilt angle in the calculated value + * for Saturn's visual magnitude. + * For all bodies other than Saturn, the value of `ring_tilt` is `undefined`. + */ +class IlluminationInfo { + constructor(time, mag, phase_angle, helio_dist, geo_dist, gc, hc, ring_tilt) { + this.time = time; + this.mag = mag; + this.phase_angle = phase_angle; + this.helio_dist = helio_dist; + this.geo_dist = geo_dist; + this.gc = gc; + this.hc = hc; + this.ring_tilt = ring_tilt; + this.phase_fraction = (1 + Math.cos(exports.DEG2RAD * phase_angle)) / 2; + } +} +exports.IlluminationInfo = IlluminationInfo; +/** + * @brief Calculates visual magnitude and related information about a body. + * + * Calculates the phase angle, visual magnitude, + * and other values relating to the body's illumination + * at the given date and time, as seen from the Earth. + * + * @param {Body} body + * The name of the celestial body being observed. + * Not allowed to be `Body.Earth`. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the illumination data for the given body. + * + * @returns {IlluminationInfo} + */ +function Illumination(body, date) { + if (body === Body.Earth) + throw `The illumination of the Earth is not defined.`; + const time = MakeTime(date); + const earth = CalcVsop(vsop.Earth, time); + let phase; // phase angle in degrees between Earth and Sun as seen from body + let hc; // vector from Sun to body + let gc; // vector from Earth to body + let mag; // visual magnitude + if (body === Body.Sun) { + gc = new Vector(-earth.x, -earth.y, -earth.z, time); + hc = new Vector(0, 0, 0, time); + phase = 0; // a placeholder value; the Sun does not have an illumination phase because it emits, rather than reflects, light. + } + else { + if (body === Body.Moon) { + // For extra numeric precision, use geocentric moon formula directly. + gc = GeoMoon(time); + hc = new Vector(earth.x + gc.x, earth.y + gc.y, earth.z + gc.z, time); + } + else { + // For planets, heliocentric vector is most direct to calculate. + hc = HelioVector(body, date); + gc = new Vector(hc.x - earth.x, hc.y - earth.y, hc.z - earth.z, time); + } + phase = AngleBetween(gc, hc); + } + let geo_dist = gc.Length(); // distance from body to center of Earth + let helio_dist = hc.Length(); // distance from body to center of Sun + let ring_tilt; // only reported for Saturn + if (body === Body.Sun) { + mag = SUN_MAG_1AU + 5 * Math.log10(geo_dist); + } + else if (body === Body.Moon) { + mag = MoonMagnitude(phase, helio_dist, geo_dist); + } + else if (body === Body.Saturn) { + const saturn = SaturnMagnitude(phase, helio_dist, geo_dist, gc, time); + mag = saturn.mag; + ring_tilt = saturn.ring_tilt; + } + else { + mag = VisualMagnitude(body, phase, helio_dist, geo_dist); + } + return new IlluminationInfo(time, mag, phase, helio_dist, geo_dist, gc, hc, ring_tilt); +} +exports.Illumination = Illumination; +function SynodicPeriod(body) { + if (body === Body.Earth) + throw 'The Earth does not have a synodic period as seen from itself.'; + if (body === Body.Moon) + return MEAN_SYNODIC_MONTH; + // Calculate the synodic period of the planet from its and the Earth's sidereal periods. + // The sidereal period of a planet is how long it takes to go around the Sun in days, on average. + // The synodic period of a planet is how long it takes between consecutive oppositions + // or conjunctions, on average. + let planet = Planet[body]; + if (!planet) + throw `Not a valid planet name: ${body}`; + // See here for explanation of the formula: + // https://en.wikipedia.org/wiki/Elongation_(astronomy)#Elongation_period + const Te = Planet.Earth.OrbitalPeriod; + const Tp = planet.OrbitalPeriod; + const synodicPeriod = Math.abs(Te / (Te / Tp - 1)); + return synodicPeriod; +} +/** + * @brief Searches for when the Earth and a given body reach a relative ecliptic longitude separation. + * + * Searches for the date and time the relative ecliptic longitudes of + * the specified body and the Earth, as seen from the Sun, reach a certain + * difference. This function is useful for finding conjunctions and oppositions + * of the planets. For the opposition of a superior planet (Mars, Jupiter, ..., Pluto), + * or the inferior conjunction of an inferior planet (Mercury, Venus), + * call with `targetRelLon` = 0. The 0 value indicates that both + * planets are on the same ecliptic longitude line, ignoring the other planet's + * distance above or below the plane of the Earth's orbit. + * For superior conjunctions, call with `targetRelLon` = 180. + * This means the Earth and the other planet are on opposite sides of the Sun. + * + * @param {Body} body + * Any planet other than the Earth. + * + * @param {number} targetRelLon + * The desired angular difference in degrees between the ecliptic longitudes + * of `body` and the Earth. Must be in the range (-180, +180]. + * + * @param {FlexibleDateTime} startDate + * The date and time after which to find the next occurrence of the + * body and the Earth reaching the desired relative longitude. + * + * @returns {AstroTime} + * The time when the Earth and the body next reach the specified relative longitudes. + */ +function SearchRelativeLongitude(body, targetRelLon, startDate) { + VerifyNumber(targetRelLon); + const planet = Planet[body]; + if (!planet) + throw `Cannot search relative longitude because body is not a planet: ${body}`; + if (body === Body.Earth) + throw 'Cannot search relative longitude for the Earth (it is always 0)'; + // Determine whether the Earth "gains" (+1) on the planet or "loses" (-1) + // as both race around the Sun. + const direction = (planet.OrbitalPeriod > Planet.Earth.OrbitalPeriod) ? +1 : -1; + function offset(t) { + const plon = EclipticLongitude(body, t); + const elon = EclipticLongitude(Body.Earth, t); + const diff = direction * (elon - plon); + return LongitudeOffset(diff - targetRelLon); + } + let syn = SynodicPeriod(body); + let time = MakeTime(startDate); + // Iterate until we converge on the desired event. + // Calculate the error angle, which will be a negative number of degrees, + // meaning we are "behind" the target relative longitude. + let error_angle = offset(time); + if (error_angle > 0) + error_angle -= 360; // force searching forward in time + for (let iter = 0; iter < 100; ++iter) { + // Estimate how many days in the future (positive) or past (negative) + // we have to go to get closer to the target relative longitude. + let day_adjust = (-error_angle / 360) * syn; + time = time.AddDays(day_adjust); + if (Math.abs(day_adjust) * SECONDS_PER_DAY < 1) + return time; + let prev_angle = error_angle; + error_angle = offset(time); + if (Math.abs(prev_angle) < 30) { + // Improve convergence for Mercury/Mars (eccentric orbits) + // by adjusting the synodic period to more closely match the + // variable speed of both planets in this part of their respective orbits. + if (prev_angle !== error_angle) { + let ratio = prev_angle / (prev_angle - error_angle); + if (ratio > 0.5 && ratio < 2.0) + syn *= ratio; + } + } + } + throw `Relative longitude search failed to converge for ${body} near ${time.toString()} (error_angle = ${error_angle}).`; +} +exports.SearchRelativeLongitude = SearchRelativeLongitude; +/** + * @brief Determines the moon's phase expressed as an ecliptic longitude. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the moon's phase. + * + * @returns {number} + * A value in the range [0, 360) indicating the difference + * in ecliptic longitude between the center of the Sun and the + * center of the Moon, as seen from the center of the Earth. + * Certain longitude values have conventional meanings: + * + * * 0 = new moon + * * 90 = first quarter + * * 180 = full moon + * * 270 = third quarter + */ +function MoonPhase(date) { + return PairLongitude(Body.Moon, Body.Sun, date); +} +exports.MoonPhase = MoonPhase; +/** + * @brief Searches for the date and time that the Moon reaches a specified phase. + * + * Lunar phases are defined in terms of geocentric ecliptic longitudes + * with respect to the Sun. When the Moon and the Sun have the same ecliptic + * longitude, that is defined as a new moon. When the two ecliptic longitudes + * are 180 degrees apart, that is defined as a full moon. + * To enumerate quarter lunar phases, it is simpler to call + * {@link SearchMoonQuarter} once, followed by repeatedly calling + * {@link NextMoonQuarter}. `SearchMoonPhase` is only + * necessary for finding other lunar phases than the usual quarter phases. + * + * @param {number} targetLon + * The difference in geocentric ecliptic longitude between the Sun and Moon + * that specifies the lunar phase being sought. This can be any value + * in the range [0, 360). Here are some helpful examples: + * 0 = new moon, + * 90 = first quarter, + * 180 = full moon, + * 270 = third quarter. + * + * @param {FlexibleDateTime} dateStart + * The beginning of the window of time in which to search. + * + * @param {number} limitDays + * The floating point number of days away from `dateStart` + * that limits the window of time in which to search. + * If the value is negative, the search is performed into the past from `startTime`. + * Otherwise, the search is performed into the future from `startTime`. + * + * @returns {AstroTime | null} + * If successful, returns the date and time the moon reaches the phase specified by `targetlon`. + * This function will return `null` if the phase does not occur within `limitDays` of `startTime`; + * that is, if the search window is too small. + */ +function SearchMoonPhase(targetLon, dateStart, limitDays) { + function moon_offset(t) { + let mlon = MoonPhase(t); + return LongitudeOffset(mlon - targetLon); + } + VerifyNumber(targetLon); + VerifyNumber(limitDays); + // To avoid discontinuities in the moon_offset function causing problems, + // we need to approximate when that function will next return 0. + // We probe it with the start time and take advantage of the fact + // that every lunar phase repeats roughly every 29.5 days. + // There is a surprising uncertainty in the quarter timing, + // due to the eccentricity of the moon's orbit. + // I have seen more than 0.9 days away from the simple prediction. + // To be safe, we take the predicted time of the event and search + // +/-1.5 days around it (a 3.0-day wide window). + // But we must return null if the final result goes beyond limitDays after dateStart. + const uncertainty = 1.5; + const ta = MakeTime(dateStart); + let ya = moon_offset(ta); + let est_dt, dt1, dt2; + if (limitDays < 0) { + // Search backward in time. + if (ya < 0) + ya += 360; + est_dt = -(MEAN_SYNODIC_MONTH * ya) / 360; + dt2 = est_dt + uncertainty; + if (dt2 < limitDays) + return null; // not possible for moon phase to occur within the specified window + dt1 = Math.max(limitDays, est_dt - uncertainty); + } + else { + // Search forward in time. + if (ya > 0) + ya -= 360; + est_dt = -(MEAN_SYNODIC_MONTH * ya) / 360; + dt1 = est_dt - uncertainty; + if (dt1 > limitDays) + return null; // not possible for moon phase to occur within the specified window + dt2 = Math.min(limitDays, est_dt + uncertainty); + } + const t1 = ta.AddDays(dt1); + const t2 = ta.AddDays(dt2); + return Search(moon_offset, t1, t2, { dt_tolerance_seconds: 0.1 }); +} +exports.SearchMoonPhase = SearchMoonPhase; +/** + * @brief A quarter lunar phase, along with when it occurs. + * + * @property {number} quarter + * An integer as follows: + * 0 = new moon, + * 1 = first quarter, + * 2 = full moon, + * 3 = third quarter. + * + * @property {AstroTime} time + * The date and time of the quarter lunar phase. + */ +class MoonQuarter { + constructor(quarter, time) { + this.quarter = quarter; + this.time = time; + } +} +exports.MoonQuarter = MoonQuarter; +/** + * @brief Finds the first quarter lunar phase after the specified date and time. + * + * The quarter lunar phases are: new moon, first quarter, full moon, and third quarter. + * To enumerate quarter lunar phases, call `SearchMoonQuarter` once, + * then pass its return value to {@link NextMoonQuarter} to find the next + * `MoonQuarter`. Keep calling `NextMoonQuarter` in a loop, + * passing the previous return value as the argument to the next call. + * + * @param {FlexibleDateTime} dateStart + * The date and time after which to find the first quarter lunar phase. + * + * @returns {MoonQuarter} + */ +function SearchMoonQuarter(dateStart) { + // Determine what the next quarter phase will be. + let phaseStart = MoonPhase(dateStart); + let quarterStart = Math.floor(phaseStart / 90); + let quarter = (quarterStart + 1) % 4; + let time = SearchMoonPhase(90 * quarter, dateStart, 10); + if (!time) + throw 'Cannot find moon quarter'; + return new MoonQuarter(quarter, time); +} +exports.SearchMoonQuarter = SearchMoonQuarter; +/** + * @brief Finds the next quarter lunar phase in a series. + * + * Given a {@link MoonQuarter} object, finds the next consecutive + * quarter lunar phase. See remarks in {@link SearchMoonQuarter} + * for explanation of usage. + * + * @param {MoonQuarter} mq + * The return value of a prior call to {@link MoonQuarter} or `NextMoonQuarter`. + * + * @returns {MoonQuarter} + */ +function NextMoonQuarter(mq) { + // Skip 6 days past the previous found moon quarter to find the next one. + // This is less than the minimum possible increment. + // So far I have seen the interval well contained by the range (6.5, 8.3) days. + let date = new Date(mq.time.date.getTime() + 6 * MILLIS_PER_DAY); + return SearchMoonQuarter(date); +} +exports.NextMoonQuarter = NextMoonQuarter; +/** + * @brief Information about idealized atmospheric variables at a given elevation. + * + * @property {number} pressure + * Atmospheric pressure in pascals. + * + * @property {number} temperature + * Atmospheric temperature in kelvins. + * + * @property {number} density + * Atmospheric density relative to sea level. + */ +class AtmosphereInfo { + constructor(pressure, temperature, density) { + this.pressure = pressure; + this.temperature = temperature; + this.density = density; + } +} +exports.AtmosphereInfo = AtmosphereInfo; +/** + * @brief Calculates U.S. Standard Atmosphere (1976) variables as a function of elevation. + * + * This function calculates idealized values of pressure, temperature, and density + * using the U.S. Standard Atmosphere (1976) model. + * 1. COESA, U.S. Standard Atmosphere, 1976, U.S. Government Printing Office, Washington, DC, 1976. + * 2. Jursa, A. S., Ed., Handbook of Geophysics and the Space Environment, Air Force Geophysics Laboratory, 1985. + * See: + * https://hbcp.chemnetbase.com/faces/documents/14_12/14_12_0001.xhtml + * https://ntrs.nasa.gov/api/citations/19770009539/downloads/19770009539.pdf + * https://www.ngdc.noaa.gov/stp/space-weather/online-publications/miscellaneous/us-standard-atmosphere-1976/us-standard-atmosphere_st76-1562_noaa.pdf + * + * @param {number} elevationMeters + * The elevation above sea level at which to calculate atmospheric variables. + * Must be in the range -500 to +100000, or an exception will occur. + * + * @returns {AtmosphereInfo} + */ +function Atmosphere(elevationMeters) { + const P0 = 101325.0; // pressure at sea level [pascals] + const T0 = 288.15; // temperature at sea level [kelvins] + const T1 = 216.65; // temperature between 20 km and 32 km [kelvins] + if (!Number.isFinite(elevationMeters) || elevationMeters < -500.0 || elevationMeters > 100000.0) + throw `Invalid elevation: ${elevationMeters}`; + let temperature; + let pressure; + if (elevationMeters <= 11000.0) { + temperature = T0 - 0.0065 * elevationMeters; + pressure = P0 * Math.pow(T0 / temperature, -5.25577); + } + else if (elevationMeters <= 20000.0) { + temperature = T1; + pressure = 22632.0 * Math.exp(-0.00015768832 * (elevationMeters - 11000.0)); + } + else { + temperature = T1 + 0.001 * (elevationMeters - 20000.0); + pressure = 5474.87 * Math.pow(T1 / temperature, 34.16319); + } + // The density is calculated relative to the sea level value. + // Using the ideal gas law PV=nRT, we deduce that density is proportional to P/T. + const density = (pressure / temperature) / (P0 / T0); + return new AtmosphereInfo(pressure, temperature, density); +} +exports.Atmosphere = Atmosphere; +function HorizonDipAngle(observer, metersAboveGround) { + // Calculate the effective radius of the Earth at ground level below the observer. + // Correct for the Earth's oblateness. + const phi = observer.latitude * exports.DEG2RAD; + const sinphi = Math.sin(phi); + const cosphi = Math.cos(phi); + const c = 1.0 / Math.hypot(cosphi, sinphi * EARTH_FLATTENING); + const s = c * (EARTH_FLATTENING * EARTH_FLATTENING); + const ht_km = (observer.height - metersAboveGround) / 1000.0; // height of ground above sea level + const ach = EARTH_EQUATORIAL_RADIUS_KM * c + ht_km; + const ash = EARTH_EQUATORIAL_RADIUS_KM * s + ht_km; + const radius_m = 1000.0 * Math.hypot(ach * cosphi, ash * sinphi); + // Correct refraction of a ray of light traveling tangent to the Earth's surface. + // Based on: https://www.largeformatphotography.info/sunmooncalc/SMCalc.js + // which in turn derives from: + // Sweer, John. 1938. The Path of a Ray of Light Tangent to the Surface of the Earth. + // Journal of the Optical Society of America 28 (September):327-329. + // k = refraction index + const k = 0.175 * Math.pow(1.0 - (6.5e-3 / 283.15) * (observer.height - (2.0 / 3.0) * metersAboveGround), 3.256); + // Calculate how far below the observer's horizontal plane the observed horizon dips. + return exports.RAD2DEG * -(Math.sqrt(2 * (1 - k) * metersAboveGround / radius_m) / (1 - k)); +} +function BodyRadiusAu(body) { + // For the purposes of calculating rise/set times, + // only the Sun and Moon appear large enough to an observer + // on the Earth for their radius to matter. + // All other bodies are treated as points. + switch (body) { + case Body.Sun: return SUN_RADIUS_AU; + case Body.Moon: return MOON_EQUATORIAL_RADIUS_AU; + default: return 0; + } +} +/** + * @brief Searches for the next time a celestial body rises or sets as seen by an observer on the Earth. + * + * This function finds the next rise or set time of the Sun, Moon, or planet other than the Earth. + * Rise time is when the body first starts to be visible above the horizon. + * For example, sunrise is the moment that the top of the Sun first appears to peek above the horizon. + * Set time is the moment when the body appears to vanish below the horizon. + * Therefore, this function adjusts for the apparent angular radius of the observed body + * (significant only for the Sun and Moon). + * + * This function corrects for a typical value of atmospheric refraction, which causes celestial + * bodies to appear higher above the horizon than they would if the Earth had no atmosphere. + * Astronomy Engine uses a correction of 34 arcminutes. Real-world refraction varies based + * on air temperature, pressure, and humidity; such weather-based conditions are outside + * the scope of Astronomy Engine. + * + * Note that rise or set may not occur in every 24 hour period. + * For example, near the Earth's poles, there are long periods of time where + * the Sun stays below the horizon, never rising. + * Also, it is possible for the Moon to rise just before midnight but not set during the subsequent 24-hour day. + * This is because the Moon sets nearly an hour later each day due to orbiting the Earth a + * significant amount during each rotation of the Earth. + * Therefore callers must not assume that the function will always succeed. + * + * @param {Body} body + * The Sun, Moon, any planet other than the Earth, + * or a user-defined star that was created by a call to {@link DefineStar}. + * + * @param {Observer} observer + * Specifies the geographic coordinates and elevation above sea level of the observer. + * + * @param {number} direction + * Either +1 to find rise time or -1 to find set time. + * Any other value will cause an exception to be thrown. + * + * @param {FlexibleDateTime} dateStart + * The date and time after which the specified rise or set time is to be found. + * + * @param {number} limitDays + * Limits how many days to search for a rise or set time, and defines + * the direction in time to search. When `limitDays` is positive, the + * search is performed into the future, after `dateStart`. + * When negative, the search is performed into the past, before `dateStart`. + * To limit a rise or set time to the same day, you can use a value of 1 day. + * In cases where you want to find the next rise or set time no matter how far + * in the future (for example, for an observer near the south pole), you can + * pass in a larger value like 365. + * + * @param {number?} metersAboveGround + * Defaults to 0.0 if omitted. + * Usually the observer is located at ground level. Then this parameter + * should be zero. But if the observer is significantly higher than ground + * level, for example in an airplane, this parameter should be a positive + * number indicating how far above the ground the observer is. + * An exception occurs if `metersAboveGround` is negative. + * + * @returns {AstroTime | null} + * The date and time of the rise or set event, or null if no such event + * occurs within the specified time window. + */ +function SearchRiseSet(body, observer, direction, dateStart, limitDays, metersAboveGround = 0.0) { + if (!Number.isFinite(metersAboveGround) || (metersAboveGround < 0.0)) + throw `Invalid value for metersAboveGround: ${metersAboveGround}`; + // We want to find when the top of the body crosses the horizon, not the body's center. + // Therefore, we need to know the body's radius. + const body_radius_au = BodyRadiusAu(body); + // Calculate atmospheric density at ground level. + const atmos = Atmosphere(observer.height - metersAboveGround); + // Calculate the apparent angular dip of the horizon. + const dip = HorizonDipAngle(observer, metersAboveGround); + // Correct refraction for objects near the horizon, using atmospheric density at the ground. + const altitude = dip - (REFRACTION_NEAR_HORIZON * atmos.density); + // Search for the top of the body crossing the corrected altitude angle. + return InternalSearchAltitude(body, observer, direction, dateStart, limitDays, body_radius_au, altitude); +} +exports.SearchRiseSet = SearchRiseSet; +/** + * @brief Finds the next time the center of a body passes through a given altitude. + * + * Finds when the center of the given body ascends or descends through a given + * altitude angle, as seen by an observer at the specified location on the Earth. + * By using the appropriate combination of `direction` and `altitude` parameters, + * this function can be used to find when civil, nautical, or astronomical twilight + * begins (dawn) or ends (dusk). + * + * Civil dawn begins before sunrise when the Sun ascends through 6 degrees below + * the horizon. To find civil dawn, pass +1 for `direction` and -6 for `altitude`. + * + * Civil dusk ends after sunset when the Sun descends through 6 degrees below the horizon. + * To find civil dusk, pass -1 for `direction` and -6 for `altitude`. + * + * Nautical twilight is similar to civil twilight, only the `altitude` value should be -12 degrees. + * + * Astronomical twilight uses -18 degrees as the `altitude` value. + * + * By convention for twilight time calculations, the altitude is not corrected for + * atmospheric refraction. This is because the target altitudes are below the horizon, + * and refraction is not directly observable. + * + * `SearchAltitude` is not intended to find rise/set times of a body for two reasons: + * (1) Rise/set times of the Sun or Moon are defined by their topmost visible portion, not their centers. + * (2) Rise/set times are affected significantly by atmospheric refraction. + * Therefore, it is better to use {@link SearchRiseSet} to find rise/set times, which + * corrects for both of these considerations. + * + * `SearchAltitude` will not work reliably for altitudes at or near the body's + * maximum or minimum altitudes. To find the time a body reaches minimum or maximum altitude + * angles, use {@link SearchHourAngle}. + * + * @param {Body} body + * The Sun, Moon, any planet other than the Earth, + * or a user-defined star that was created by a call to {@link DefineStar}. + * + * @param {Observer} observer + * Specifies the geographic coordinates and elevation above sea level of the observer. + * + * @param {number} direction + * Either +1 to find when the body ascends through the altitude, + * or -1 for when the body descends through the altitude. + * Any other value will cause an exception to be thrown. + * + * @param {FlexibleDateTime} dateStart + * The date and time after which the specified altitude event is to be found. + * + * @param {number} limitDays + * Limits how many days to search for the body reaching the altitude angle, + * and defines the direction in time to search. When `limitDays` is positive, the + * search is performed into the future, after `dateStart`. + * When negative, the search is performed into the past, before `dateStart`. + * To limit the search to the same day, you can use a value of 1 day. + * In cases where you want to find the altitude event no matter how far + * in the future (for example, for an observer near the south pole), you can + * pass in a larger value like 365. + * + * @param {number} altitude + * The desired altitude angle of the body's center above (positive) + * or below (negative) the observer's local horizon, expressed in degrees. + * Must be in the range [-90, +90]. + * + * @returns {AstroTime | null} + * The date and time of the altitude event, or null if no such event + * occurs within the specified time window. + */ +function SearchAltitude(body, observer, direction, dateStart, limitDays, altitude) { + if (!Number.isFinite(altitude) || altitude < -90 || altitude > +90) + throw `Invalid altitude angle: ${altitude}`; + return InternalSearchAltitude(body, observer, direction, dateStart, limitDays, 0, altitude); +} +exports.SearchAltitude = SearchAltitude; +class AscentInfo { + constructor(tx, ty, ax, ay) { + this.tx = tx; + this.ty = ty; + this.ax = ax; + this.ay = ay; + } +} +function FindAscent(depth, altdiff, max_deriv_alt, t1, t2, a1, a2) { + // See if we can find any time interval where the altitude-diff function + // rises from non-positive to positive. + if (a1 < 0.0 && a2 >= 0.0) { + // Trivial success case: the endpoints already rise through zero. + return new AscentInfo(t1, t2, a1, a2); + } + if (a1 >= 0.0 && a2 < 0.0) { + // Trivial failure case: Assume Nyquist condition prevents an ascent. + return null; + } + if (depth > 17) { + // Safety valve: do not allow unlimited recursion. + // This should never happen if the rest of the logic is working correctly, + // so fail the whole search if it does happen. It's a bug! + throw `Excessive recursion in rise/set ascent search.`; + } + // Both altitudes are on the same side of zero: both are negative, or both are non-negative. + // There could be a convex "hill" or a concave "valley" that passes through zero. + // In polar regions sometimes there is a rise/set or set/rise pair within minutes of each other. + // For example, the Moon can be below the horizon, then the very top of it becomes + // visible (moonrise) for a few minutes, then it moves sideways and down below + // the horizon again (moonset). We want to catch these cases. + // However, for efficiency and practicality concerns, because the rise/set search itself + // has a 0.1 second threshold, we do not worry about rise/set pairs that are less than + // one second apart. These are marginal cases that are rendered highly uncertain + // anyway, due to unpredictable atmospheric refraction conditions (air temperature and pressure). + const dt = t2.ut - t1.ut; + if (dt * SECONDS_PER_DAY < 1.0) + return null; + // Is it possible to reach zero from the altitude that is closer to zero? + const da = Math.min(Math.abs(a1), Math.abs(a2)); + // Without loss of generality, assume |a1| <= |a2|. + // (Reverse the argument in the case |a2| < |a1|.) + // Imagine you have to "drive" from a1 to 0, then back to a2. + // You can't go faster than max_deriv_alt. If you can't reach 0 in half the time, + // you certainly don't have time to reach 0, turn around, and still make your way + // back up to a2 (which is at least as far from 0 than a1 is) in the time interval dt. + // Therefore, the time threshold is half the time interval, or dt/2. + if (da > max_deriv_alt * (dt / 2)) { + // Prune: the altitude cannot change fast enough to reach zero. + return null; + } + // Bisect the time interval and evaluate the altitude at the midpoint. + const tmid = new AstroTime((t1.ut + t2.ut) / 2); + const amid = altdiff(tmid); + // Use recursive bisection to search for a solution bracket. + return (FindAscent(1 + depth, altdiff, max_deriv_alt, t1, tmid, a1, amid) || + FindAscent(1 + depth, altdiff, max_deriv_alt, tmid, t2, amid, a2)); +} +function MaxAltitudeSlope(body, latitude) { + // Calculate the maximum possible rate that this body's altitude + // could change [degrees/day] as seen by this observer. + // First use experimentally determined extreme bounds for this body + // of how much topocentric RA and DEC can ever change per rate of time. + // We need minimum possible d(RA)/dt, and maximum possible magnitude of d(DEC)/dt. + // Conservatively, we round d(RA)/dt down, d(DEC)/dt up. + // Then calculate the resulting maximum possible altitude change rate. + if (latitude < -90 || latitude > +90) + throw `Invalid geographic latitude: ${latitude}`; + let deriv_ra; + let deriv_dec; + switch (body) { + case Body.Moon: + deriv_ra = +4.5; + deriv_dec = +8.2; + break; + case Body.Sun: + deriv_ra = +0.8; + deriv_dec = +0.5; + break; + case Body.Mercury: + deriv_ra = -1.6; + deriv_dec = +1.0; + break; + case Body.Venus: + deriv_ra = -0.8; + deriv_dec = +0.6; + break; + case Body.Mars: + deriv_ra = -0.5; + deriv_dec = +0.4; + break; + case Body.Jupiter: + case Body.Saturn: + case Body.Uranus: + case Body.Neptune: + case Body.Pluto: + deriv_ra = -0.2; + deriv_dec = +0.2; + break; + case Body.Star1: + case Body.Star2: + case Body.Star3: + case Body.Star4: + case Body.Star5: + case Body.Star6: + case Body.Star7: + case Body.Star8: + // The minimum allowed heliocentric distance of a user-defined star + // is one light-year. This can cause a tiny amount of parallax (about 0.001 degrees). + // Also, including stellar aberration (22 arcsec = 0.006 degrees), we provide a + // generous safety buffer of 0.008 degrees. + deriv_ra = -0.008; + deriv_dec = +0.008; + break; + default: + throw `Body not allowed for altitude search: ${body}`; + } + const latrad = exports.DEG2RAD * latitude; + return Math.abs(((360.0 / SOLAR_DAYS_PER_SIDEREAL_DAY) - deriv_ra) * Math.cos(latrad)) + Math.abs(deriv_dec * Math.sin(latrad)); +} +function InternalSearchAltitude(body, observer, direction, dateStart, limitDays, bodyRadiusAu, targetAltitude) { + VerifyObserver(observer); + VerifyNumber(limitDays); + VerifyNumber(bodyRadiusAu); + VerifyNumber(targetAltitude); + if (targetAltitude < -90 || targetAltitude > +90) + throw `Invalid target altitude angle: ${targetAltitude}`; + const RISE_SET_DT = 0.42; // 10.08 hours: Nyquist-safe for 22-hour period. + const max_deriv_alt = MaxAltitudeSlope(body, observer.latitude); + function altdiff(time) { + const ofdate = Equator(body, time, observer, true, true); + const hor = Horizon(time, observer, ofdate.ra, ofdate.dec); + const altitude = hor.altitude + exports.RAD2DEG * Math.asin(bodyRadiusAu / ofdate.dist); + return direction * (altitude - targetAltitude); + } + // We allow searching forward or backward in time. + // But we want to keep t1 < t2, so we need a few if/else statements. + const startTime = MakeTime(dateStart); + let t1 = startTime; + let t2 = startTime; + let a1 = altdiff(t1); + let a2 = a1; + for (;;) { + if (limitDays < 0.0) { + t1 = t2.AddDays(-RISE_SET_DT); + a1 = altdiff(t1); + } + else { + t2 = t1.AddDays(+RISE_SET_DT); + a2 = altdiff(t2); + } + const ascent = FindAscent(0, altdiff, max_deriv_alt, t1, t2, a1, a2); + if (ascent) { + // We found a time interval [t1, t2] that contains an alt-diff + // rising from negative a1 to non-negative a2. + // Search for the time where the root occurs. + const time = Search(altdiff, ascent.tx, ascent.ty, { + dt_tolerance_seconds: 0.1, + init_f1: ascent.ax, + init_f2: ascent.ay + }); + if (time) { + // Now that we have a solution, we have to check whether it goes outside the time bounds. + if (limitDays < 0.0) { + if (time.ut < startTime.ut + limitDays) + return null; + } + else { + if (time.ut > startTime.ut + limitDays) + return null; + } + return time; // success! + } + // The search should have succeeded. Something is wrong with the ascent finder! + throw `Rise/set search failed after finding ascent: t1=${t1}, t2=${t2}, a1=${a1}, a2=${a2}`; + } + // There is no ascent in this interval, so keep searching. + if (limitDays < 0.0) { + if (t1.ut < startTime.ut + limitDays) + return null; + t2 = t1; + a2 = a1; + } + else { + if (t2.ut > startTime.ut + limitDays) + return null; + t1 = t2; + a1 = a2; + } + } +} +/** + * @brief Horizontal position of a body upon reaching an hour angle. + * + * Returns information about an occurrence of a celestial body + * reaching a given hour angle as seen by an observer at a given + * location on the surface of the Earth. + * + * @property {AstroTime} time + * The date and time of the celestial body reaching the hour angle. + * + * @property {HorizontalCoordinates} hor + * Topocentric horizontal coordinates for the body + * at the time indicated by the `time` property. + */ +class HourAngleEvent { + constructor(time, hor) { + this.time = time; + this.hor = hor; + } +} +exports.HourAngleEvent = HourAngleEvent; +/** + * @brief Searches for the time when the center of a body reaches a specified hour angle as seen by an observer on the Earth. + * + * The *hour angle* of a celestial body indicates its position in the sky with respect + * to the Earth's rotation. The hour angle depends on the location of the observer on the Earth. + * The hour angle is 0 when the body's center reaches its highest angle above the horizon in a given day. + * The hour angle increases by 1 unit for every sidereal hour that passes after that point, up + * to 24 sidereal hours when it reaches the highest point again. So the hour angle indicates + * the number of hours that have passed since the most recent time that the body has culminated, + * or reached its highest point. + * + * This function searches for the next or previous time a celestial body reaches the given hour angle + * relative to the date and time specified by `dateStart`. + * To find when a body culminates, pass 0 for `hourAngle`. + * To find when a body reaches its lowest point in the sky, pass 12 for `hourAngle`. + * + * Note that, especially close to the Earth's poles, a body as seen on a given day + * may always be above the horizon or always below the horizon, so the caller cannot + * assume that a culminating object is visible nor that an object is below the horizon + * at its minimum altitude. + * + * The function returns the date and time, along with the horizontal coordinates + * of the body at that time, as seen by the given observer. + * + * @param {Body} body + * The Sun, Moon, any planet other than the Earth, + * or a user-defined star that was created by a call to {@link DefineStar}. + * + * @param {Observer} observer + * Specifies the geographic coordinates and elevation above sea level of the observer. + * + * @param {number} hourAngle + * The hour angle expressed in + * sidereal + * hours for which the caller seeks to find the body attain. + * The value must be in the range [0, 24). + * The hour angle represents the number of sidereal hours that have + * elapsed since the most recent time the body crossed the observer's local + * meridian. + * This specifying `hourAngle` = 0 finds the moment in time + * the body reaches the highest angular altitude in a given sidereal day. + * + * @param {FlexibleDateTime} dateStart + * The date and time after which the desired hour angle crossing event + * is to be found. + * + * @param {number} direction + * The direction in time to perform the search: a positive value + * searches forward in time, a negative value searches backward in time. + * The function throws an exception if `direction` is zero. + * + * @returns {HourAngleEvent} + */ +function SearchHourAngle(body, observer, hourAngle, dateStart, direction = +1) { + VerifyObserver(observer); + let time = MakeTime(dateStart); + let iter = 0; + if (body === Body.Earth) + throw 'Cannot search for hour angle of the Earth.'; + VerifyNumber(hourAngle); + if (hourAngle < 0.0 || hourAngle >= 24.0) + throw `Invalid hour angle ${hourAngle}`; + VerifyNumber(direction); + if (direction === 0) + throw `Direction must be positive or negative.`; + while (true) { + ++iter; + // Calculate Greenwich Apparent Sidereal Time (GAST) at the given time. + let gast = sidereal_time(time); + let ofdate = Equator(body, time, observer, true, true); + // Calculate the adjustment needed in sidereal time to bring + // the hour angle to the desired value. + let delta_sidereal_hours = ((hourAngle + ofdate.ra - observer.longitude / 15) - gast) % 24; + if (iter === 1) { + // On the first iteration, always search in the requested time direction. + if (direction > 0) { + // Search forward in time. + if (delta_sidereal_hours < 0) + delta_sidereal_hours += 24; + } + else { + // Search backward in time. + if (delta_sidereal_hours > 0) + delta_sidereal_hours -= 24; + } + } + else { + // On subsequent iterations, we make the smallest possible adjustment, + // either forward or backward in time. + if (delta_sidereal_hours < -12) + delta_sidereal_hours += 24; + else if (delta_sidereal_hours > +12) + delta_sidereal_hours -= 24; + } + // If the error is tolerable (less than 0.1 seconds), stop searching. + if (Math.abs(delta_sidereal_hours) * 3600 < 0.1) { + const hor = Horizon(time, observer, ofdate.ra, ofdate.dec, 'normal'); + return new HourAngleEvent(time, hor); + } + // We need to loop another time to get more accuracy. + // Update the terrestrial time adjusting by sidereal time. + let delta_days = (delta_sidereal_hours / 24) * SOLAR_DAYS_PER_SIDEREAL_DAY; + time = time.AddDays(delta_days); + } +} +exports.SearchHourAngle = SearchHourAngle; +/** + * @brief Finds the hour angle of a body for a given observer and time. + * + * The *hour angle* of a celestial body indicates its position in the sky with respect + * to the Earth's rotation. The hour angle depends on the location of the observer on the Earth. + * The hour angle is 0 when the body's center reaches its highest angle above the horizon in a given day. + * The hour angle increases by 1 unit for every sidereal hour that passes after that point, up + * to 24 sidereal hours when it reaches the highest point again. So the hour angle indicates + * the number of hours that have passed since the most recent time that the body has culminated, + * or reached its highest point. + * + * This function returns the hour angle of the body as seen at the given time and geogrpahic location. + * The hour angle is a number in the half-open range [0, 24). + * + * @param {Body} body + * The body whose observed hour angle is to be found. + * + * @param {FlexibleDateTime} date + * The date and time of the observation. + * + * @param {Observer} observer + * The geographic location where the observation takes place. + * + * @returns {number} + */ +function HourAngle(body, date, observer) { + const time = MakeTime(date); + const gast = SiderealTime(time); + const ofdate = Equator(body, time, observer, true, true); + let hourAngle = (observer.longitude / 15 + gast - ofdate.ra) % 24; + if (hourAngle < 0.0) + hourAngle += 24.0; + return hourAngle; +} +exports.HourAngle = HourAngle; +/** + * @brief When the seasons change for a given calendar year. + * + * Represents the dates and times of the two solstices + * and the two equinoxes in a given calendar year. + * These four events define the changing of the seasons on the Earth. + * + * @property {AstroTime} mar_equinox + * The date and time of the March equinox in the given calendar year. + * This is the moment in March that the plane of the Earth's equator passes + * through the center of the Sun; thus the Sun's declination + * changes from a negative number to a positive number. + * The March equinox defines + * the beginning of spring in the northern hemisphere and + * the beginning of autumn in the southern hemisphere. + * + * @property {AstroTime} jun_solstice + * The date and time of the June solstice in the given calendar year. + * This is the moment in June that the Sun reaches its most positive + * declination value. + * At this moment the Earth's north pole is most tilted most toward the Sun. + * The June solstice defines + * the beginning of summer in the northern hemisphere and + * the beginning of winter in the southern hemisphere. + * + * @property {AstroTime} sep_equinox + * The date and time of the September equinox in the given calendar year. + * This is the moment in September that the plane of the Earth's equator passes + * through the center of the Sun; thus the Sun's declination + * changes from a positive number to a negative number. + * The September equinox defines + * the beginning of autumn in the northern hemisphere and + * the beginning of spring in the southern hemisphere. + * + * @property {AstroTime} dec_solstice + * The date and time of the December solstice in the given calendar year. + * This is the moment in December that the Sun reaches its most negative + * declination value. + * At this moment the Earth's south pole is tilted most toward the Sun. + * The December solstice defines + * the beginning of winter in the northern hemisphere and + * the beginning of summer in the southern hemisphere. + */ +class SeasonInfo { + constructor(mar_equinox, jun_solstice, sep_equinox, dec_solstice) { + this.mar_equinox = mar_equinox; + this.jun_solstice = jun_solstice; + this.sep_equinox = sep_equinox; + this.dec_solstice = dec_solstice; + } +} +exports.SeasonInfo = SeasonInfo; +/** + * @brief Finds the equinoxes and solstices for a given calendar year. + * + * @param {number | AstroTime} year + * The integer value or `AstroTime` object that specifies + * the UTC calendar year for which to find equinoxes and solstices. + * + * @returns {SeasonInfo} + */ +function Seasons(year) { + function find(targetLon, month, day) { + let startDate = new Date(Date.UTC(year, month - 1, day)); + let time = SearchSunLongitude(targetLon, startDate, 20); + if (!time) + throw `Cannot find season change near ${startDate.toISOString()}`; + return time; + } + if ((year instanceof Date) && Number.isFinite(year.getTime())) + year = year.getUTCFullYear(); + if (!Number.isSafeInteger(year)) + throw `Cannot calculate seasons because year argument ${year} is neither a Date nor a safe integer.`; + let mar_equinox = find(0, 3, 10); + let jun_solstice = find(90, 6, 10); + let sep_equinox = find(180, 9, 10); + let dec_solstice = find(270, 12, 10); + return new SeasonInfo(mar_equinox, jun_solstice, sep_equinox, dec_solstice); +} +exports.Seasons = Seasons; +/** + * @brief The viewing conditions of a body relative to the Sun. + * + * Represents the angular separation of a body from the Sun as seen from the Earth + * and the relative ecliptic longitudes between that body and the Earth as seen from the Sun. + * + * @property {AstroTime} time + * The date and time of the observation. + * + * @property {string} visibility + * Either `"morning"` or `"evening"`, + * indicating when the body is most easily seen. + * + * @property {number} elongation + * The angle in degrees, as seen from the center of the Earth, + * of the apparent separation between the body and the Sun. + * This angle is measured in 3D space and is not projected onto the ecliptic plane. + * When `elongation` is less than a few degrees, the body is very + * difficult to see from the Earth because it is lost in the Sun's glare. + * The elongation is always in the range [0, 180]. + * + * @property {number} ecliptic_separation + * The absolute value of the difference between the body's ecliptic longitude + * and the Sun's ecliptic longitude, both as seen from the center of the Earth. + * This angle measures around the plane of the Earth's orbit (the ecliptic), + * and ignores how far above or below that plane the body is. + * The ecliptic separation is measured in degrees and is always in the range [0, 180]. + * + * @see {@link Elongation} + */ +class ElongationEvent { + constructor(time, visibility, elongation, ecliptic_separation) { + this.time = time; + this.visibility = visibility; + this.elongation = elongation; + this.ecliptic_separation = ecliptic_separation; + } +} +exports.ElongationEvent = ElongationEvent; +/** + * @brief Calculates the viewing conditions of a body relative to the Sun. + * + * Calculates angular separation of a body from the Sun as seen from the Earth + * and the relative ecliptic longitudes between that body and the Earth as seen from the Sun. + * See the return type {@link ElongationEvent} for details. + * + * This function is helpful for determining how easy + * it is to view a planet away from the Sun's glare on a given date. + * It also determines whether the object is visible in the morning or evening; + * this is more important the smaller the elongation is. + * It is also used to determine how far a planet is from opposition, conjunction, or quadrature. + * + * @param {Body} body + * The name of the observed body. Not allowed to be `Body.Earth`. + * + * @param {FlexibleDateTime} date + * The date and time of the observation. + * + * @returns {ElongationEvent} + */ +function Elongation(body, date) { + let time = MakeTime(date); + let lon = PairLongitude(body, Body.Sun, time); + let vis; + if (lon > 180) { + vis = 'morning'; + lon = 360 - lon; + } + else { + vis = 'evening'; + } + let angle = AngleFromSun(body, time); + return new ElongationEvent(time, vis, angle, lon); +} +exports.Elongation = Elongation; +/** + * @brief Finds the next time Mercury or Venus reaches maximum elongation. + * + * Searches for the next maximum elongation event for Mercury or Venus + * that occurs after the given start date. Calling with other values + * of `body` will result in an exception. + * Maximum elongation occurs when the body has the greatest + * angular separation from the Sun, as seen from the Earth. + * Returns an `ElongationEvent` object containing the date and time of the next + * maximum elongation, the elongation in degrees, and whether + * the body is visible in the morning or evening. + * + * @param {Body} body + * Either `Body.Mercury` or `Body.Venus`. + * + * @param {FlexibleDateTime} startDate + * The date and time after which to search for the next maximum elongation event. + * + * @returns {ElongationEvent} + */ +function SearchMaxElongation(body, startDate) { + const dt = 0.01; + function neg_slope(t) { + // The slope de/dt goes from positive to negative at the maximum elongation event. + // But Search() is designed for functions that ascend through zero. + // So this function returns the negative slope. + const t1 = t.AddDays(-dt / 2); + const t2 = t.AddDays(+dt / 2); + let e1 = AngleFromSun(body, t1); + let e2 = AngleFromSun(body, t2); + let m = (e1 - e2) / dt; + return m; + } + let startTime = MakeTime(startDate); + const table = { + Mercury: { s1: 50.0, s2: 85.0 }, + Venus: { s1: 40.0, s2: 50.0 } + }; + const planet = table[body]; + if (!planet) + throw 'SearchMaxElongation works for Mercury and Venus only.'; + let iter = 0; + while (++iter <= 2) { + // Find current heliocentric relative longitude between the + // inferior planet and the Earth. + let plon = EclipticLongitude(body, startTime); + let elon = EclipticLongitude(Body.Earth, startTime); + let rlon = LongitudeOffset(plon - elon); // clamp to (-180, +180] + // The slope function is not well-behaved when rlon is near 0 degrees or 180 degrees + // because there is a cusp there that causes a discontinuity in the derivative. + // So we need to guard against searching near such times. + let rlon_lo, rlon_hi, adjust_days; + if (rlon >= -planet.s1 && rlon < +planet.s1) { + // Seek to the window [+s1, +s2]. + adjust_days = 0; + // Search forward for the time t1 when rel lon = +s1. + rlon_lo = +planet.s1; + // Search forward for the time t2 when rel lon = +s2. + rlon_hi = +planet.s2; + } + else if (rlon >= +planet.s2 || rlon < -planet.s2) { + // Seek to the next search window at [-s2, -s1]. + adjust_days = 0; + // Search forward for the time t1 when rel lon = -s2. + rlon_lo = -planet.s2; + // Search forward for the time t2 when rel lon = -s1. + rlon_hi = -planet.s1; + } + else if (rlon >= 0) { + // rlon must be in the middle of the window [+s1, +s2]. + // Search BACKWARD for the time t1 when rel lon = +s1. + adjust_days = -SynodicPeriod(body) / 4; + rlon_lo = +planet.s1; + rlon_hi = +planet.s2; + // Search forward from t1 to find t2 such that rel lon = +s2. + } + else { + // rlon must be in the middle of the window [-s2, -s1]. + // Search BACKWARD for the time t1 when rel lon = -s2. + adjust_days = -SynodicPeriod(body) / 4; + rlon_lo = -planet.s2; + // Search forward from t1 to find t2 such that rel lon = -s1. + rlon_hi = -planet.s1; + } + let t_start = startTime.AddDays(adjust_days); + let t1 = SearchRelativeLongitude(body, rlon_lo, t_start); + let t2 = SearchRelativeLongitude(body, rlon_hi, t1); + // Now we have a time range [t1,t2] that brackets a maximum elongation event. + // Confirm the bracketing. + let m1 = neg_slope(t1); + if (m1 >= 0) + throw `SearchMaxElongation: internal error: m1 = ${m1}`; + let m2 = neg_slope(t2); + if (m2 <= 0) + throw `SearchMaxElongation: internal error: m2 = ${m2}`; + // Use the generic search algorithm to home in on where the slope crosses from negative to positive. + let tx = Search(neg_slope, t1, t2, { init_f1: m1, init_f2: m2, dt_tolerance_seconds: 10 }); + if (!tx) + throw `SearchMaxElongation: failed search iter ${iter} (t1=${t1.toString()}, t2=${t2.toString()})`; + if (tx.tt >= startTime.tt) + return Elongation(body, tx); + // This event is in the past (earlier than startDate). + // We need to search forward from t2 to find the next possible window. + // We never need to search more than twice. + startTime = t2.AddDays(1); + } + throw `SearchMaxElongation: failed to find event after 2 tries.`; +} +exports.SearchMaxElongation = SearchMaxElongation; +/** + * @brief Searches for the date and time Venus will next appear brightest as seen from the Earth. + * + * @param {Body} body + * Currently only `Body.Venus` is supported. + * Mercury's peak magnitude occurs at superior conjunction, when it is impossible to see from Earth, + * so peak magnitude events have little practical value for that planet. + * The Moon reaches peak magnitude very close to full moon, which can be found using + * {@link SearchMoonQuarter} or {@link SearchMoonPhase}. + * The other planets reach peak magnitude very close to opposition, + * which can be found using {@link SearchRelativeLongitude}. + * + * @param {FlexibleDateTime} startDate + * The date and time after which to find the next peak magnitude event. + * + * @returns {IlluminationInfo} + */ +function SearchPeakMagnitude(body, startDate) { + if (body !== Body.Venus) + throw 'SearchPeakMagnitude currently works for Venus only.'; + const dt = 0.01; + function slope(t) { + // The Search() function finds a transition from negative to positive values. + // The derivative of magnitude y with respect to time t (dy/dt) + // is negative as an object gets brighter, because the magnitude numbers + // get smaller. At peak magnitude dy/dt = 0, then as the object gets dimmer, + // dy/dt > 0. + const t1 = t.AddDays(-dt / 2); + const t2 = t.AddDays(+dt / 2); + const y1 = Illumination(body, t1).mag; + const y2 = Illumination(body, t2).mag; + const m = (y2 - y1) / dt; + return m; + } + let startTime = MakeTime(startDate); + // s1 and s2 are relative longitudes within which peak magnitude of Venus can occur. + const s1 = 10.0; + const s2 = 30.0; + let iter = 0; + while (++iter <= 2) { + // Find current heliocentric relative longitude between the + // inferior planet and the Earth. + let plon = EclipticLongitude(body, startTime); + let elon = EclipticLongitude(Body.Earth, startTime); + let rlon = LongitudeOffset(plon - elon); // clamp to (-180, +180] + // The slope function is not well-behaved when rlon is near 0 degrees or 180 degrees + // because there is a cusp there that causes a discontinuity in the derivative. + // So we need to guard against searching near such times. + let rlon_lo, rlon_hi, adjust_days; + if (rlon >= -s1 && rlon < +s1) { + // Seek to the window [+s1, +s2]. + adjust_days = 0; + // Search forward for the time t1 when rel lon = +s1. + rlon_lo = +s1; + // Search forward for the time t2 when rel lon = +s2. + rlon_hi = +s2; + } + else if (rlon >= +s2 || rlon < -s2) { + // Seek to the next search window at [-s2, -s1]. + adjust_days = 0; + // Search forward for the time t1 when rel lon = -s2. + rlon_lo = -s2; + // Search forward for the time t2 when rel lon = -s1. + rlon_hi = -s1; + } + else if (rlon >= 0) { + // rlon must be in the middle of the window [+s1, +s2]. + // Search BACKWARD for the time t1 when rel lon = +s1. + adjust_days = -SynodicPeriod(body) / 4; + rlon_lo = +s1; + // Search forward from t1 to find t2 such that rel lon = +s2. + rlon_hi = +s2; + } + else { + // rlon must be in the middle of the window [-s2, -s1]. + // Search BACKWARD for the time t1 when rel lon = -s2. + adjust_days = -SynodicPeriod(body) / 4; + rlon_lo = -s2; + // Search forward from t1 to find t2 such that rel lon = -s1. + rlon_hi = -s1; + } + let t_start = startTime.AddDays(adjust_days); + let t1 = SearchRelativeLongitude(body, rlon_lo, t_start); + let t2 = SearchRelativeLongitude(body, rlon_hi, t1); + // Now we have a time range [t1,t2] that brackets a maximum magnitude event. + // Confirm the bracketing. + let m1 = slope(t1); + if (m1 >= 0) + throw `SearchPeakMagnitude: internal error: m1 = ${m1}`; + let m2 = slope(t2); + if (m2 <= 0) + throw `SearchPeakMagnitude: internal error: m2 = ${m2}`; + // Use the generic search algorithm to home in on where the slope crosses from negative to positive. + let tx = Search(slope, t1, t2, { init_f1: m1, init_f2: m2, dt_tolerance_seconds: 10 }); + if (!tx) + throw `SearchPeakMagnitude: failed search iter ${iter} (t1=${t1.toString()}, t2=${t2.toString()})`; + if (tx.tt >= startTime.tt) + return Illumination(body, tx); + // This event is in the past (earlier than startDate). + // We need to search forward from t2 to find the next possible window. + // We never need to search more than twice. + startTime = t2.AddDays(1); + } + throw `SearchPeakMagnitude: failed to find event after 2 tries.`; +} +exports.SearchPeakMagnitude = SearchPeakMagnitude; +/** + * @brief The two kinds of apsis: pericenter (closest) and apocenter (farthest). + * + * `Pericenter`: The body is at its closest distance to the object it orbits. + * `Apocenter`: The body is at its farthest distance from the object it orbits. + * + * @enum {number} + */ +var ApsisKind; +(function (ApsisKind) { + ApsisKind[ApsisKind["Pericenter"] = 0] = "Pericenter"; + ApsisKind[ApsisKind["Apocenter"] = 1] = "Apocenter"; +})(ApsisKind = exports.ApsisKind || (exports.ApsisKind = {})); +/** + * @brief A closest or farthest point in a body's orbit around its primary. + * + * For a planet orbiting the Sun, apsis is a perihelion or aphelion, respectively. + * For the Moon orbiting the Earth, apsis is a perigee or apogee, respectively. + * + * @property {AstroTime} time + * The date and time of the apsis. + * + * @property {ApsisKind} kind + * For a closest approach (perigee or perihelion), `kind` is `ApsisKind.Pericenter`. + * For a farthest distance event (apogee or aphelion), `kind` is `ApsisKind.Apocenter`. + * + * @property {number} dist_au + * The distance between the centers of the two bodies in astronomical units (AU). + * + * @property {number} dist_km + * The distance between the centers of the two bodies in kilometers. + * + * @see {@link SearchLunarApsis} + * @see {@link NextLunarApsis} + * @see {@link SearchPlanetApsis} + * @see {@link NextPlanetApsis} + */ +class Apsis { + constructor(time, kind, dist_au) { + this.time = time; + this.kind = kind; + this.dist_au = dist_au; + this.dist_km = dist_au * exports.KM_PER_AU; + } +} +exports.Apsis = Apsis; +/** + * @brief Finds the next perigee or apogee of the Moon. + * + * Finds the next perigee (closest approach) or apogee (farthest remove) of the Moon + * that occurs after the specified date and time. + * + * @param {FlexibleDateTime} startDate + * The date and time after which to find the next perigee or apogee. + * + * @returns {Apsis} + */ +function SearchLunarApsis(startDate) { + const dt = 0.001; + function distance_slope(t) { + let t1 = t.AddDays(-dt / 2); + let t2 = t.AddDays(+dt / 2); + let r1 = CalcMoon(t1).distance_au; + let r2 = CalcMoon(t2).distance_au; + let m = (r2 - r1) / dt; + return m; + } + function negative_distance_slope(t) { + return -distance_slope(t); + } + // Check the rate of change of the distance dr/dt at the start time. + // If it is positive, the Moon is currently getting farther away, + // so start looking for apogee. + // Conversely, if dr/dt < 0, start looking for perigee. + // Either way, the polarity of the slope will change, so the product will be negative. + // Handle the crazy corner case of exactly touching zero by checking for m1*m2 <= 0. + let t1 = MakeTime(startDate); + let m1 = distance_slope(t1); + const increment = 5; // number of days to skip in each iteration + for (var iter = 0; iter * increment < 2 * MEAN_SYNODIC_MONTH; ++iter) { + let t2 = t1.AddDays(increment); + let m2 = distance_slope(t2); + if (m1 * m2 <= 0) { + // The time range [t1, t2] contains an apsis. + // Figure out whether it is perigee or apogee. + if (m1 < 0 || m2 > 0) { + // We found a minimum distance event: perigee. + // Search the time range [t1, t2] for the time when the slope goes + // from negative to positive. + let tx = Search(distance_slope, t1, t2, { init_f1: m1, init_f2: m2 }); + if (!tx) + throw 'SearchLunarApsis INTERNAL ERROR: perigee search failed!'; + let dist = CalcMoon(tx).distance_au; + return new Apsis(tx, 0, dist); + } + if (m1 > 0 || m2 < 0) { + // We found a maximum distance event: apogee. + // Search the time range [t1, t2] for the time when the slope goes + // from positive to negative. + let tx = Search(negative_distance_slope, t1, t2, { init_f1: -m1, init_f2: -m2 }); + if (!tx) + throw 'SearchLunarApsis INTERNAL ERROR: apogee search failed!'; + let dist = CalcMoon(tx).distance_au; + return new Apsis(tx, 1, dist); + } + // This should never happen; it should not be possible for consecutive + // times t1 and t2 to both have zero slope. + throw 'SearchLunarApsis INTERNAL ERROR: cannot classify apsis event!'; + } + t1 = t2; + m1 = m2; + } + // It should not be possible to fail to find an apsis within 2 synodic months. + throw 'SearchLunarApsis INTERNAL ERROR: could not find apsis within 2 synodic months of start date.'; +} +exports.SearchLunarApsis = SearchLunarApsis; +/** + * @brief Finds the next lunar apsis (perigee or apogee) in a series. + * + * Given a lunar apsis returned by an initial call to {@link SearchLunarApsis}, + * or a previous call to `NextLunarApsis`, finds the next lunar apsis. + * If the given apsis is a perigee, this function finds the next apogee, and vice versa. + * + * @param {Apsis} apsis + * A lunar perigee or apogee event. + * + * @returns {Apsis} + * The successor apogee for the given perigee, or the successor perigee for the given apogee. + */ +function NextLunarApsis(apsis) { + const skip = 11; // number of days to skip to start looking for next apsis event + let next = SearchLunarApsis(apsis.time.AddDays(skip)); + if (next.kind + apsis.kind !== 1) + throw `NextLunarApsis INTERNAL ERROR: did not find alternating apogee/perigee: prev=${apsis.kind} @ ${apsis.time.toString()}, next=${next.kind} @ ${next.time.toString()}`; + return next; +} +exports.NextLunarApsis = NextLunarApsis; +function PlanetExtreme(body, kind, start_time, dayspan) { + const direction = (kind === ApsisKind.Apocenter) ? +1.0 : -1.0; + const npoints = 10; + for (;;) { + const interval = dayspan / (npoints - 1); + // iterate until uncertainty is less than one minute + if (interval < 1.0 / 1440.0) { + const apsis_time = start_time.AddDays(interval / 2.0); + const dist_au = HelioDistance(body, apsis_time); + return new Apsis(apsis_time, kind, dist_au); + } + let best_i = -1; + let best_dist = 0.0; + for (let i = 0; i < npoints; ++i) { + const time = start_time.AddDays(i * interval); + const dist = direction * HelioDistance(body, time); + if (i == 0 || dist > best_dist) { + best_i = i; + best_dist = dist; + } + } + /* Narrow in on the extreme point. */ + start_time = start_time.AddDays((best_i - 1) * interval); + dayspan = 2.0 * interval; + } +} +function BruteSearchPlanetApsis(body, startTime) { + /* + Neptune is a special case for two reasons: + 1. Its orbit is nearly circular (low orbital eccentricity). + 2. It is so distant from the Sun that the orbital period is very long. + Put together, this causes wobbling of the Sun around the Solar System Barycenter (SSB) + to be so significant that there are 3 local minima in the distance-vs-time curve + near each apsis. Therefore, unlike for other planets, we can't use an optimized + algorithm for finding dr/dt = 0. + Instead, we use a dumb, brute-force algorithm of sampling and finding min/max + heliocentric distance. + + There is a similar problem in the TOP2013 model for Pluto: + Its position vector has high-frequency oscillations that confuse the + slope-based determination of apsides. + */ + /* + Rewind approximately 30 degrees in the orbit, + then search forward for 270 degrees. + This is a very cautious way to prevent missing an apsis. + Typically we will find two apsides, and we pick whichever + apsis is ealier, but after startTime. + Sample points around this orbital arc and find when the distance + is greatest and smallest. + */ + const npoints = 100; + const t1 = startTime.AddDays(Planet[body].OrbitalPeriod * (-30 / 360)); + const t2 = startTime.AddDays(Planet[body].OrbitalPeriod * (+270 / 360)); + let t_min = t1; + let t_max = t1; + let min_dist = -1.0; + let max_dist = -1.0; + const interval = (t2.ut - t1.ut) / (npoints - 1); + for (let i = 0; i < npoints; ++i) { + const time = t1.AddDays(i * interval); + const dist = HelioDistance(body, time); + if (i === 0) { + max_dist = min_dist = dist; + } + else { + if (dist > max_dist) { + max_dist = dist; + t_max = time; + } + if (dist < min_dist) { + min_dist = dist; + t_min = time; + } + } + } + const perihelion = PlanetExtreme(body, 0, t_min.AddDays(-2 * interval), 4 * interval); + const aphelion = PlanetExtreme(body, 1, t_max.AddDays(-2 * interval), 4 * interval); + if (perihelion.time.tt >= startTime.tt) { + if (aphelion.time.tt >= startTime.tt && aphelion.time.tt < perihelion.time.tt) + return aphelion; + return perihelion; + } + if (aphelion.time.tt >= startTime.tt) + return aphelion; + throw 'Internal error: failed to find Neptune apsis.'; +} +/** + * @brief Finds the next perihelion or aphelion of a planet. + * + * Finds the date and time of a planet's perihelion (closest approach to the Sun) + * or aphelion (farthest distance from the Sun) after a given time. + * + * Given a date and time to start the search in `startTime`, this function finds the + * next date and time that the center of the specified planet reaches the closest or farthest point + * in its orbit with respect to the center of the Sun, whichever comes first + * after `startTime`. + * + * The closest point is called *perihelion* and the farthest point is called *aphelion*. + * The word *apsis* refers to either event. + * + * To iterate through consecutive alternating perihelion and aphelion events, + * call `SearchPlanetApsis` once, then use the return value to call + * {@link NextPlanetApsis}. After that, keep feeding the previous return value + * from `NextPlanetApsis` into another call of `NextPlanetApsis` + * as many times as desired. + * + * @param {Body} body + * The planet for which to find the next perihelion/aphelion event. + * Not allowed to be `Body.Sun` or `Body.Moon`. + * + * @param {FlexibleDateTime} startTime + * The date and time at which to start searching for the next perihelion or aphelion. + * + * @returns {Apsis} + * The next perihelion or aphelion that occurs after `startTime`. + */ +function SearchPlanetApsis(body, startTime) { + startTime = MakeTime(startTime); + if (body === Body.Neptune || body === Body.Pluto) + return BruteSearchPlanetApsis(body, startTime); + function positive_slope(t) { + const dt = 0.001; + let t1 = t.AddDays(-dt / 2); + let t2 = t.AddDays(+dt / 2); + let r1 = HelioDistance(body, t1); + let r2 = HelioDistance(body, t2); + let m = (r2 - r1) / dt; + return m; + } + function negative_slope(t) { + return -positive_slope(t); + } + const orbit_period_days = Planet[body].OrbitalPeriod; + const increment = orbit_period_days / 6.0; + let t1 = startTime; + let m1 = positive_slope(t1); + for (let iter = 0; iter * increment < 2.0 * orbit_period_days; ++iter) { + const t2 = t1.AddDays(increment); + const m2 = positive_slope(t2); + if (m1 * m2 <= 0.0) { + /* There is a change of slope polarity within the time range [t1, t2]. */ + /* Therefore this time range contains an apsis. */ + /* Figure out whether it is perihelion or aphelion. */ + let slope_func; + let kind; + if (m1 < 0.0 || m2 > 0.0) { + /* We found a minimum-distance event: perihelion. */ + /* Search the time range for the time when the slope goes from negative to positive. */ + slope_func = positive_slope; + kind = ApsisKind.Pericenter; + } + else if (m1 > 0.0 || m2 < 0.0) { + /* We found a maximum-distance event: aphelion. */ + /* Search the time range for the time when the slope goes from positive to negative. */ + slope_func = negative_slope; + kind = ApsisKind.Apocenter; + } + else { + /* This should never happen. It should not be possible for both slopes to be zero. */ + throw "Internal error with slopes in SearchPlanetApsis"; + } + const search = Search(slope_func, t1, t2); + if (!search) + throw "Failed to find slope transition in planetary apsis search."; + const dist = HelioDistance(body, search); + return new Apsis(search, kind, dist); + } + /* We have not yet found a slope polarity change. Keep searching. */ + t1 = t2; + m1 = m2; + } + throw "Internal error: should have found planetary apsis within 2 orbital periods."; +} +exports.SearchPlanetApsis = SearchPlanetApsis; +/** + * @brief Finds the next planetary perihelion or aphelion event in a series. + * + * This function requires an {@link Apsis} value obtained from a call + * to {@link SearchPlanetApsis} or `NextPlanetApsis`. + * Given an aphelion event, this function finds the next perihelion event, and vice versa. + * See {@link SearchPlanetApsis} for more details. + * + * @param {Body} body + * The planet for which to find the next perihelion/aphelion event. + * Not allowed to be `Body.Sun` or `Body.Moon`. + * Must match the body passed into the call that produced the `apsis` parameter. + * + * @param {Apsis} apsis + * An apsis event obtained from a call to {@link SearchPlanetApsis} or `NextPlanetApsis`. + * + * @returns {Apsis} + * Same as the return value for {@link SearchPlanetApsis}. + */ +function NextPlanetApsis(body, apsis) { + if (apsis.kind !== ApsisKind.Pericenter && apsis.kind !== ApsisKind.Apocenter) + throw `Invalid apsis kind: ${apsis.kind}`; + /* skip 1/4 of an orbit before starting search again */ + const skip = 0.25 * Planet[body].OrbitalPeriod; + const time = apsis.time.AddDays(skip); + const next = SearchPlanetApsis(body, time); + /* Verify that we found the opposite apsis from the previous one. */ + if (next.kind + apsis.kind !== 1) + throw `Internal error: previous apsis was ${apsis.kind}, but found ${next.kind} for next apsis.`; + return next; +} +exports.NextPlanetApsis = NextPlanetApsis; +/** + * @brief Calculates the inverse of a rotation matrix. + * + * Given a rotation matrix that performs some coordinate transform, + * this function returns the matrix that reverses that transform. + * + * @param {RotationMatrix} rotation + * The rotation matrix to be inverted. + * + * @returns {RotationMatrix} + * The inverse rotation matrix. + */ +function InverseRotation(rotation) { + return new RotationMatrix([ + [rotation.rot[0][0], rotation.rot[1][0], rotation.rot[2][0]], + [rotation.rot[0][1], rotation.rot[1][1], rotation.rot[2][1]], + [rotation.rot[0][2], rotation.rot[1][2], rotation.rot[2][2]] + ]); +} +exports.InverseRotation = InverseRotation; +/** + * @brief Creates a rotation based on applying one rotation followed by another. + * + * Given two rotation matrices, returns a combined rotation matrix that is + * equivalent to rotating based on the first matrix, followed by the second. + * + * @param {RotationMatrix} a + * The first rotation to apply. + * + * @param {RotationMatrix} b + * The second rotation to apply. + * + * @returns {RotationMatrix} + * The combined rotation matrix. + */ +function CombineRotation(a, b) { + /* + Use matrix multiplication: c = b*a. + We put 'b' on the left and 'a' on the right because, + just like when you use a matrix M to rotate a vector V, + you put the M on the left in the product M*V. + We can think of this as 'b' rotating all the 3 column vectors in 'a'. + */ + return new RotationMatrix([ + [ + b.rot[0][0] * a.rot[0][0] + b.rot[1][0] * a.rot[0][1] + b.rot[2][0] * a.rot[0][2], + b.rot[0][1] * a.rot[0][0] + b.rot[1][1] * a.rot[0][1] + b.rot[2][1] * a.rot[0][2], + b.rot[0][2] * a.rot[0][0] + b.rot[1][2] * a.rot[0][1] + b.rot[2][2] * a.rot[0][2] + ], + [ + b.rot[0][0] * a.rot[1][0] + b.rot[1][0] * a.rot[1][1] + b.rot[2][0] * a.rot[1][2], + b.rot[0][1] * a.rot[1][0] + b.rot[1][1] * a.rot[1][1] + b.rot[2][1] * a.rot[1][2], + b.rot[0][2] * a.rot[1][0] + b.rot[1][2] * a.rot[1][1] + b.rot[2][2] * a.rot[1][2] + ], + [ + b.rot[0][0] * a.rot[2][0] + b.rot[1][0] * a.rot[2][1] + b.rot[2][0] * a.rot[2][2], + b.rot[0][1] * a.rot[2][0] + b.rot[1][1] * a.rot[2][1] + b.rot[2][1] * a.rot[2][2], + b.rot[0][2] * a.rot[2][0] + b.rot[1][2] * a.rot[2][1] + b.rot[2][2] * a.rot[2][2] + ] + ]); +} +exports.CombineRotation = CombineRotation; +/** + * @brief Creates an identity rotation matrix. + * + * Returns a rotation matrix that has no effect on orientation. + * This matrix can be the starting point for other operations, + * such as using a series of calls to {@link Pivot} to + * create a custom rotation matrix. + * + * @returns {RotationMatrix} + * The identity matrix. + */ +function IdentityMatrix() { + return new RotationMatrix([ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1] + ]); +} +exports.IdentityMatrix = IdentityMatrix; +/** +* @brief Re-orients a rotation matrix by pivoting it by an angle around one of its axes. +* +* Given a rotation matrix, a selected coordinate axis, and an angle in degrees, +* this function pivots the rotation matrix by that angle around that coordinate axis. +* +* For example, if you have rotation matrix that converts ecliptic coordinates (ECL) +* to horizontal coordinates (HOR), but you really want to convert ECL to the orientation +* of a telescope camera pointed at a given body, you can use `Astronomy_Pivot` twice: +* (1) pivot around the zenith axis by the body's azimuth, then (2) pivot around the +* western axis by the body's altitude angle. The resulting rotation matrix will then +* reorient ECL coordinates to the orientation of your telescope camera. +* +* @param {RotationMatrix} rotation +* The input rotation matrix. +* +* @param {number} axis +* An integer that selects which coordinate axis to rotate around: +* 0 = x, 1 = y, 2 = z. Any other value will cause an exception. +* +* @param {number} angle +* An angle in degrees indicating the amount of rotation around the specified axis. +* Positive angles indicate rotation counterclockwise as seen from the positive +* direction along that axis, looking towards the origin point of the orientation system. +* Any finite number of degrees is allowed, but best precision will result from +* keeping `angle` in the range [-360, +360]. +* +* @returns {RotationMatrix} +* A pivoted matrix object. +*/ +function Pivot(rotation, axis, angle) { + // Check for an invalid coordinate axis. + if (axis !== 0 && axis !== 1 && axis !== 2) + throw `Invalid axis ${axis}. Must be [0, 1, 2].`; + const radians = VerifyNumber(angle) * exports.DEG2RAD; + const c = Math.cos(radians); + const s = Math.sin(radians); + /* + We need to maintain the "right-hand" rule, no matter which + axis was selected. That means we pick (i, j, k) axis order + such that the following vector cross product is satisfied: + i x j = k + */ + const i = (axis + 1) % 3; + const j = (axis + 2) % 3; + const k = axis; + let rot = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]; + rot[i][i] = c * rotation.rot[i][i] - s * rotation.rot[i][j]; + rot[i][j] = s * rotation.rot[i][i] + c * rotation.rot[i][j]; + rot[i][k] = rotation.rot[i][k]; + rot[j][i] = c * rotation.rot[j][i] - s * rotation.rot[j][j]; + rot[j][j] = s * rotation.rot[j][i] + c * rotation.rot[j][j]; + rot[j][k] = rotation.rot[j][k]; + rot[k][i] = c * rotation.rot[k][i] - s * rotation.rot[k][j]; + rot[k][j] = s * rotation.rot[k][i] + c * rotation.rot[k][j]; + rot[k][k] = rotation.rot[k][k]; + return new RotationMatrix(rot); +} +exports.Pivot = Pivot; +/** + * @brief Converts spherical coordinates to Cartesian coordinates. + * + * Given spherical coordinates and a time at which they are valid, + * returns a vector of Cartesian coordinates. The returned value + * includes the time, as required by `AstroTime`. + * + * @param {Spherical} sphere + * Spherical coordinates to be converted. + * + * @param {FlexibleDateTime} time + * The time that should be included in the returned vector. + * + * @returns {Vector} + * The vector form of the supplied spherical coordinates. + */ +function VectorFromSphere(sphere, time) { + time = MakeTime(time); + const radlat = sphere.lat * exports.DEG2RAD; + const radlon = sphere.lon * exports.DEG2RAD; + const rcoslat = sphere.dist * Math.cos(radlat); + return new Vector(rcoslat * Math.cos(radlon), rcoslat * Math.sin(radlon), sphere.dist * Math.sin(radlat), time); +} +exports.VectorFromSphere = VectorFromSphere; +/** + * @brief Given an equatorial vector, calculates equatorial angular coordinates. + * + * @param {Vector} vec + * A vector in an equatorial coordinate system. + * + * @returns {EquatorialCoordinates} + * Angular coordinates expressed in the same equatorial system as `vec`. + */ +function EquatorFromVector(vec) { + const sphere = SphereFromVector(vec); + return new EquatorialCoordinates(sphere.lon / 15, sphere.lat, sphere.dist, vec); +} +exports.EquatorFromVector = EquatorFromVector; +/** + * @brief Converts Cartesian coordinates to spherical coordinates. + * + * Given a Cartesian vector, returns latitude, longitude, and distance. + * + * @param {Vector} vector + * Cartesian vector to be converted to spherical coordinates. + * + * @returns {Spherical} + * Spherical coordinates that are equivalent to the given vector. + */ +function SphereFromVector(vector) { + const xyproj = vector.x * vector.x + vector.y * vector.y; + const dist = Math.sqrt(xyproj + vector.z * vector.z); + let lat, lon; + if (xyproj === 0.0) { + if (vector.z === 0.0) + throw 'Zero-length vector not allowed.'; + lon = 0.0; + lat = (vector.z < 0.0) ? -90.0 : +90.0; + } + else { + lon = exports.RAD2DEG * Math.atan2(vector.y, vector.x); + if (lon < 0.0) + lon += 360.0; + lat = exports.RAD2DEG * Math.atan2(vector.z, Math.sqrt(xyproj)); + } + return new Spherical(lat, lon, dist); +} +exports.SphereFromVector = SphereFromVector; +function ToggleAzimuthDirection(az) { + az = 360.0 - az; + if (az >= 360.0) + az -= 360.0; + else if (az < 0.0) + az += 360.0; + return az; +} +/** + * @brief Converts Cartesian coordinates to horizontal coordinates. + * + * Given a horizontal Cartesian vector, returns horizontal azimuth and altitude. + * + * *IMPORTANT:* This function differs from {@link SphereFromVector} in two ways: + * - `SphereFromVector` returns a `lon` value that represents azimuth defined counterclockwise + * from north (e.g., west = +90), but this function represents a clockwise rotation + * (e.g., east = +90). The difference is because `SphereFromVector` is intended + * to preserve the vector "right-hand rule", while this function defines azimuth in a more + * traditional way as used in navigation and cartography. + * - This function optionally corrects for atmospheric refraction, while `SphereFromVector` does not. + * + * The returned object contains the azimuth in `lon`. + * It is measured in degrees clockwise from north: east = +90 degrees, west = +270 degrees. + * + * The altitude is stored in `lat`. + * + * The distance to the observed object is stored in `dist`, + * and is expressed in astronomical units (AU). + * + * @param {Vector} vector + * Cartesian vector to be converted to horizontal coordinates. + * + * @param {string} refraction + * `"normal"`: correct altitude for atmospheric refraction (recommended). + * `"jplhor"`: for JPL Horizons compatibility testing only; not recommended for normal use. + * `null`: no atmospheric refraction correction is performed. + * + * @returns {Spherical} + */ +function HorizonFromVector(vector, refraction) { + const sphere = SphereFromVector(vector); + sphere.lon = ToggleAzimuthDirection(sphere.lon); + sphere.lat += Refraction(refraction, sphere.lat); + return sphere; +} +exports.HorizonFromVector = HorizonFromVector; +/** + * @brief Given apparent angular horizontal coordinates in `sphere`, calculate horizontal vector. + * + * @param {Spherical} sphere + * A structure that contains apparent horizontal coordinates: + * `lat` holds the refracted altitude angle, + * `lon` holds the azimuth in degrees clockwise from north, + * and `dist` holds the distance from the observer to the object in AU. + * + * @param {FlexibleDateTime} time + * The date and time of the observation. This is needed because the returned + * vector object requires a valid time value when passed to certain other functions. + * + * @param {string} refraction + * `"normal"`: correct altitude for atmospheric refraction (recommended). + * `"jplhor"`: for JPL Horizons compatibility testing only; not recommended for normal use. + * `null`: no atmospheric refraction correction is performed. + * + * @returns {Vector} + * A vector in the horizontal system: `x` = north, `y` = west, and `z` = zenith (up). + */ +function VectorFromHorizon(sphere, time, refraction) { + time = MakeTime(time); + /* Convert azimuth from clockwise-from-north to counterclockwise-from-north. */ + const lon = ToggleAzimuthDirection(sphere.lon); + /* Reverse any applied refraction. */ + const lat = sphere.lat + InverseRefraction(refraction, sphere.lat); + const xsphere = new Spherical(lat, lon, sphere.dist); + return VectorFromSphere(xsphere, time); +} +exports.VectorFromHorizon = VectorFromHorizon; +/** + * @brief Calculates the amount of "lift" to an altitude angle caused by atmospheric refraction. + * + * Given an altitude angle and a refraction option, calculates + * the amount of "lift" caused by atmospheric refraction. + * This is the number of degrees higher in the sky an object appears + * due to the lensing of the Earth's atmosphere. + * This function works best near sea level. + * To correct for higher elevations, call {@link Atmosphere} for that + * elevation and multiply the refraction angle by the resulting relative density. + * + * @param {string} refraction + * `"normal"`: correct altitude for atmospheric refraction (recommended). + * `"jplhor"`: for JPL Horizons compatibility testing only; not recommended for normal use. + * `null`: no atmospheric refraction correction is performed. + * + * @param {number} altitude + * An altitude angle in a horizontal coordinate system. Must be a value between -90 and +90. + * + * @returns {number} + * The angular adjustment in degrees to be added to the altitude angle to correct for atmospheric lensing. + */ +function Refraction(refraction, altitude) { + let refr; + VerifyNumber(altitude); + if (altitude < -90.0 || altitude > +90.0) + return 0.0; /* no attempt to correct an invalid altitude */ + if (refraction === 'normal' || refraction === 'jplhor') { + // http://extras.springer.com/1999/978-1-4471-0555-8/chap4/horizons/horizons.pdf + // JPL Horizons says it uses refraction algorithm from + // Meeus "Astronomical Algorithms", 1991, p. 101-102. + // I found the following Go implementation: + // https://github.com/soniakeys/meeus/blob/master/v3/refraction/refract.go + // This is a translation from the function "Saemundsson" there. + // I found experimentally that JPL Horizons clamps the angle to 1 degree below the horizon. + // This is important because the 'refr' formula below goes crazy near hd = -5.11. + let hd = altitude; + if (hd < -1.0) + hd = -1.0; + refr = (1.02 / Math.tan((hd + 10.3 / (hd + 5.11)) * exports.DEG2RAD)) / 60.0; + if (refraction === 'normal' && altitude < -1.0) { + // In "normal" mode we gradually reduce refraction toward the nadir + // so that we never get an altitude angle less than -90 degrees. + // When horizon angle is -1 degrees, the factor is exactly 1. + // As altitude approaches -90 (the nadir), the fraction approaches 0 linearly. + refr *= (altitude + 90.0) / 89.0; + } + } + else if (!refraction) { + // The caller does not want refraction correction. + refr = 0.0; + } + else { + throw `Invalid refraction option: ${refraction}`; + } + return refr; +} +exports.Refraction = Refraction; +/** + * @brief Calculates the inverse of an atmospheric refraction angle. + * + * Given an observed altitude angle that includes atmospheric refraction, + * calculates the negative angular correction to obtain the unrefracted + * altitude. This is useful for cases where observed horizontal + * coordinates are to be converted to another orientation system, + * but refraction first must be removed from the observed position. + * + * @param {string} refraction + * `"normal"`: correct altitude for atmospheric refraction (recommended). + * `"jplhor"`: for JPL Horizons compatibility testing only; not recommended for normal use. + * `null`: no atmospheric refraction correction is performed. + * + * @param {number} bent_altitude + * The apparent altitude that includes atmospheric refraction. + * + * @returns {number} + * The angular adjustment in degrees to be added to the + * altitude angle to correct for atmospheric lensing. + * This will be less than or equal to zero. + */ +function InverseRefraction(refraction, bent_altitude) { + if (bent_altitude < -90.0 || bent_altitude > +90.0) + return 0.0; /* no attempt to correct an invalid altitude */ + /* Find the pre-adjusted altitude whose refraction correction leads to 'altitude'. */ + let altitude = bent_altitude - Refraction(refraction, bent_altitude); + for (;;) { + /* See how close we got. */ + let diff = (altitude + Refraction(refraction, altitude)) - bent_altitude; + if (Math.abs(diff) < 1.0e-14) + return altitude - bent_altitude; + altitude -= diff; + } +} +exports.InverseRefraction = InverseRefraction; +/** + * @brief Applies a rotation to a vector, yielding a rotated vector. + * + * This function transforms a vector in one orientation to a vector + * in another orientation. + * + * @param {RotationMatrix} rotation + * A rotation matrix that specifies how the orientation of the vector is to be changed. + * + * @param {Vector} vector + * The vector whose orientation is to be changed. + * + * @returns {Vector} + * A vector in the orientation specified by `rotation`. + */ +function RotateVector(rotation, vector) { + return new Vector(rotation.rot[0][0] * vector.x + rotation.rot[1][0] * vector.y + rotation.rot[2][0] * vector.z, rotation.rot[0][1] * vector.x + rotation.rot[1][1] * vector.y + rotation.rot[2][1] * vector.z, rotation.rot[0][2] * vector.x + rotation.rot[1][2] * vector.y + rotation.rot[2][2] * vector.z, vector.t); +} +exports.RotateVector = RotateVector; +/** + * @brief Applies a rotation to a state vector, yielding a rotated vector. + * + * This function transforms a state vector in one orientation to a vector + * in another orientation. + * + * @param {RotationMatrix} rotation + * A rotation matrix that specifies how the orientation of the state vector is to be changed. + * + * @param {StateVector} state + * The state vector whose orientation is to be changed. + * Both the position and velocity components are transformed. + * + * @return {StateVector} + * A state vector in the orientation specified by `rotation`. + */ +function RotateState(rotation, state) { + return new StateVector(rotation.rot[0][0] * state.x + rotation.rot[1][0] * state.y + rotation.rot[2][0] * state.z, rotation.rot[0][1] * state.x + rotation.rot[1][1] * state.y + rotation.rot[2][1] * state.z, rotation.rot[0][2] * state.x + rotation.rot[1][2] * state.y + rotation.rot[2][2] * state.z, rotation.rot[0][0] * state.vx + rotation.rot[1][0] * state.vy + rotation.rot[2][0] * state.vz, rotation.rot[0][1] * state.vx + rotation.rot[1][1] * state.vy + rotation.rot[2][1] * state.vz, rotation.rot[0][2] * state.vx + rotation.rot[1][2] * state.vy + rotation.rot[2][2] * state.vz, state.t); +} +exports.RotateState = RotateState; +/** + * @brief Calculates a rotation matrix from J2000 mean equator (EQJ) to J2000 mean ecliptic (ECL). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQJ = equatorial system, using equator at J2000 epoch. + * Target: ECL = ecliptic system, using equator at J2000 epoch. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQJ to ECL. + */ +function Rotation_EQJ_ECL() { + /* ob = mean obliquity of the J2000 ecliptic = 0.40909260059599012 radians. */ + const c = 0.9174821430670688; /* cos(ob) */ + const s = 0.3977769691083922; /* sin(ob) */ + return new RotationMatrix([ + [1, 0, 0], + [0, +c, -s], + [0, +s, +c] + ]); +} +exports.Rotation_EQJ_ECL = Rotation_EQJ_ECL; +/** + * @brief Calculates a rotation matrix from J2000 mean ecliptic (ECL) to J2000 mean equator (EQJ). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: ECL = ecliptic system, using equator at J2000 epoch. + * Target: EQJ = equatorial system, using equator at J2000 epoch. + * + * @returns {RotationMatrix} + * A rotation matrix that converts ECL to EQJ. + */ +function Rotation_ECL_EQJ() { + /* ob = mean obliquity of the J2000 ecliptic = 0.40909260059599012 radians. */ + const c = 0.9174821430670688; /* cos(ob) */ + const s = 0.3977769691083922; /* sin(ob) */ + return new RotationMatrix([ + [1, 0, 0], + [0, +c, +s], + [0, -s, +c] + ]); +} +exports.Rotation_ECL_EQJ = Rotation_ECL_EQJ; +/** + * @brief Calculates a rotation matrix from J2000 mean equator (EQJ) to equatorial of-date (EQD). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQJ = equatorial system, using equator at J2000 epoch. + * Target: EQD = equatorial system, using equator of the specified date/time. + * + * @param {FlexibleDateTime} time + * The date and time at which the Earth's equator defines the target orientation. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQJ to EQD at `time`. + */ +function Rotation_EQJ_EQD(time) { + time = MakeTime(time); + const prec = precession_rot(time, PrecessDirection.From2000); + const nut = nutation_rot(time, PrecessDirection.From2000); + return CombineRotation(prec, nut); +} +exports.Rotation_EQJ_EQD = Rotation_EQJ_EQD; +/** + * @brief Calculates a rotation matrix from J2000 mean equator (EQJ) to true ecliptic of date (ECT). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQJ = equatorial system, using equator at J2000 epoch. + * Target: ECT = ecliptic system, using true equinox of the specified date/time. + * + * @param {FlexibleDateTime} time + * The date and time at which the Earth's equator defines the target orientation. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQJ to ECT at `time`. + */ +function Rotation_EQJ_ECT(time) { + const t = MakeTime(time); + const rot = Rotation_EQJ_EQD(t); + const step = Rotation_EQD_ECT(t); + return CombineRotation(rot, step); +} +exports.Rotation_EQJ_ECT = Rotation_EQJ_ECT; +/** + * @brief Calculates a rotation matrix from true ecliptic of date (ECT) to J2000 mean equator (EQJ). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: ECT = ecliptic system, using true equinox of the specified date/time. + * Target: EQJ = equatorial system, using equator at J2000 epoch. + * + * @param {FlexibleDateTime} time + * The date and time at which the Earth's equator defines the target orientation. + * + * @returns {RotationMatrix} + * A rotation matrix that converts ECT to EQJ at `time`. + */ +function Rotation_ECT_EQJ(time) { + const t = MakeTime(time); + const rot = Rotation_ECT_EQD(t); + const step = Rotation_EQD_EQJ(t); + return CombineRotation(rot, step); +} +exports.Rotation_ECT_EQJ = Rotation_ECT_EQJ; +/** + * @brief Calculates a rotation matrix from equatorial of-date (EQD) to J2000 mean equator (EQJ). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQD = equatorial system, using equator of the specified date/time. + * Target: EQJ = equatorial system, using equator at J2000 epoch. + * + * @param {FlexibleDateTime} time + * The date and time at which the Earth's equator defines the source orientation. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQD at `time` to EQJ. + */ +function Rotation_EQD_EQJ(time) { + time = MakeTime(time); + const nut = nutation_rot(time, PrecessDirection.Into2000); + const prec = precession_rot(time, PrecessDirection.Into2000); + return CombineRotation(nut, prec); +} +exports.Rotation_EQD_EQJ = Rotation_EQD_EQJ; +/** + * @brief Calculates a rotation matrix from equatorial of-date (EQD) to horizontal (HOR). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQD = equatorial system, using equator of the specified date/time. + * Target: HOR = horizontal system. + * + * Use `HorizonFromVector` to convert the return value + * to a traditional altitude/azimuth pair. + * + * @param {FlexibleDateTime} time + * The date and time at which the Earth's equator applies. + * + * @param {Observer} observer + * A location near the Earth's mean sea level that defines the observer's horizon. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQD to HOR at `time` and for `observer`. + * The components of the horizontal vector are: + * x = north, y = west, z = zenith (straight up from the observer). + * These components are chosen so that the "right-hand rule" works for the vector + * and so that north represents the direction where azimuth = 0. + */ +function Rotation_EQD_HOR(time, observer) { + time = MakeTime(time); + const sinlat = Math.sin(observer.latitude * exports.DEG2RAD); + const coslat = Math.cos(observer.latitude * exports.DEG2RAD); + const sinlon = Math.sin(observer.longitude * exports.DEG2RAD); + const coslon = Math.cos(observer.longitude * exports.DEG2RAD); + const uze = [coslat * coslon, coslat * sinlon, sinlat]; + const une = [-sinlat * coslon, -sinlat * sinlon, coslat]; + const uwe = [sinlon, -coslon, 0]; + const spin_angle = -15 * sidereal_time(time); + const uz = spin(spin_angle, uze); + const un = spin(spin_angle, une); + const uw = spin(spin_angle, uwe); + return new RotationMatrix([ + [un[0], uw[0], uz[0]], + [un[1], uw[1], uz[1]], + [un[2], uw[2], uz[2]], + ]); +} +exports.Rotation_EQD_HOR = Rotation_EQD_HOR; +/** + * @brief Calculates a rotation matrix from horizontal (HOR) to equatorial of-date (EQD). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: HOR = horizontal system (x=North, y=West, z=Zenith). + * Target: EQD = equatorial system, using equator of the specified date/time. + * + * @param {FlexibleDateTime} time + * The date and time at which the Earth's equator applies. + * + * @param {Observer} observer + * A location near the Earth's mean sea level that defines the observer's horizon. + * + * @returns {RotationMatrix} + * A rotation matrix that converts HOR to EQD at `time` and for `observer`. + */ +function Rotation_HOR_EQD(time, observer) { + const rot = Rotation_EQD_HOR(time, observer); + return InverseRotation(rot); +} +exports.Rotation_HOR_EQD = Rotation_HOR_EQD; +/** + * @brief Calculates a rotation matrix from horizontal (HOR) to J2000 equatorial (EQJ). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: HOR = horizontal system (x=North, y=West, z=Zenith). + * Target: EQJ = equatorial system, using equator at the J2000 epoch. + * + * @param {FlexibleDateTime} time + * The date and time of the observation. + * + * @param {Observer} observer + * A location near the Earth's mean sea level that defines the observer's horizon. + * + * @returns {RotationMatrix} + * A rotation matrix that converts HOR to EQJ at `time` and for `observer`. + */ +function Rotation_HOR_EQJ(time, observer) { + time = MakeTime(time); + const hor_eqd = Rotation_HOR_EQD(time, observer); + const eqd_eqj = Rotation_EQD_EQJ(time); + return CombineRotation(hor_eqd, eqd_eqj); +} +exports.Rotation_HOR_EQJ = Rotation_HOR_EQJ; +/** + * @brief Calculates a rotation matrix from J2000 mean equator (EQJ) to horizontal (HOR). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQJ = equatorial system, using the equator at the J2000 epoch. + * Target: HOR = horizontal system. + * + * Use {@link HorizonFromVector} to convert the return value + * to a traditional altitude/azimuth pair. + * + * @param {FlexibleDateTime} time + * The date and time of the desired horizontal orientation. + * + * @param {Observer} observer + * A location near the Earth's mean sea level that defines the observer's horizon. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQJ to HOR at `time` and for `observer`. + * The components of the horizontal vector are: + * x = north, y = west, z = zenith (straight up from the observer). + * These components are chosen so that the "right-hand rule" works for the vector + * and so that north represents the direction where azimuth = 0. + */ +function Rotation_EQJ_HOR(time, observer) { + const rot = Rotation_HOR_EQJ(time, observer); + return InverseRotation(rot); +} +exports.Rotation_EQJ_HOR = Rotation_EQJ_HOR; +/** + * @brief Calculates a rotation matrix from equatorial of-date (EQD) to J2000 mean ecliptic (ECL). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQD = equatorial system, using equator of date. + * Target: ECL = ecliptic system, using equator at J2000 epoch. + * + * @param {FlexibleDateTime} time + * The date and time of the source equator. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQD to ECL. + */ +function Rotation_EQD_ECL(time) { + const eqd_eqj = Rotation_EQD_EQJ(time); + const eqj_ecl = Rotation_EQJ_ECL(); + return CombineRotation(eqd_eqj, eqj_ecl); +} +exports.Rotation_EQD_ECL = Rotation_EQD_ECL; +/** + * @brief Calculates a rotation matrix from J2000 mean ecliptic (ECL) to equatorial of-date (EQD). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: ECL = ecliptic system, using equator at J2000 epoch. + * Target: EQD = equatorial system, using equator of date. + * + * @param {FlexibleDateTime} time + * The date and time of the desired equator. + * + * @returns {RotationMatrix} + * A rotation matrix that converts ECL to EQD. + */ +function Rotation_ECL_EQD(time) { + const rot = Rotation_EQD_ECL(time); + return InverseRotation(rot); +} +exports.Rotation_ECL_EQD = Rotation_ECL_EQD; +/** + * @brief Calculates a rotation matrix from J2000 mean ecliptic (ECL) to horizontal (HOR). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: ECL = ecliptic system, using equator at J2000 epoch. + * Target: HOR = horizontal system. + * + * Use {@link HorizonFromVector} to convert the return value + * to a traditional altitude/azimuth pair. + * + * @param {FlexibleDateTime} time + * The date and time of the desired horizontal orientation. + * + * @param {Observer} observer + * A location near the Earth's mean sea level that defines the observer's horizon. + * + * @returns {RotationMatrix} + * A rotation matrix that converts ECL to HOR at `time` and for `observer`. + * The components of the horizontal vector are: + * x = north, y = west, z = zenith (straight up from the observer). + * These components are chosen so that the "right-hand rule" works for the vector + * and so that north represents the direction where azimuth = 0. + */ +function Rotation_ECL_HOR(time, observer) { + time = MakeTime(time); + const ecl_eqd = Rotation_ECL_EQD(time); + const eqd_hor = Rotation_EQD_HOR(time, observer); + return CombineRotation(ecl_eqd, eqd_hor); +} +exports.Rotation_ECL_HOR = Rotation_ECL_HOR; +/** + * @brief Calculates a rotation matrix from horizontal (HOR) to J2000 mean ecliptic (ECL). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: HOR = horizontal system. + * Target: ECL = ecliptic system, using equator at J2000 epoch. + * + * @param {FlexibleDateTime} time + * The date and time of the horizontal observation. + * + * @param {Observer} observer + * The location of the horizontal observer. + * + * @returns {RotationMatrix} + * A rotation matrix that converts HOR to ECL. + */ +function Rotation_HOR_ECL(time, observer) { + const rot = Rotation_ECL_HOR(time, observer); + return InverseRotation(rot); +} +exports.Rotation_HOR_ECL = Rotation_HOR_ECL; +/** + * @brief Calculates a rotation matrix from J2000 mean equator (EQJ) to galactic (GAL). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQJ = equatorial system, using the equator at the J2000 epoch. + * Target: GAL = galactic system (IAU 1958 definition). + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQJ to GAL. + */ +function Rotation_EQJ_GAL() { + // This rotation matrix was calculated by the following script + // in this same source code repository: + // demo/python/galeqj_matrix.py + return new RotationMatrix([ + [-0.0548624779711344, +0.4941095946388765, -0.8676668813529025], + [-0.8734572784246782, -0.4447938112296831, -0.1980677870294097], + [-0.4838000529948520, +0.7470034631630423, +0.4559861124470794] + ]); +} +exports.Rotation_EQJ_GAL = Rotation_EQJ_GAL; +/** + * @brief Calculates a rotation matrix from galactic (GAL) to J2000 mean equator (EQJ). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: GAL = galactic system (IAU 1958 definition). + * Target: EQJ = equatorial system, using the equator at the J2000 epoch. + * + * @returns {RotationMatrix} + * A rotation matrix that converts GAL to EQJ. + */ +function Rotation_GAL_EQJ() { + // This rotation matrix was calculated by the following script + // in this same source code repository: + // demo/python/galeqj_matrix.py + return new RotationMatrix([ + [-0.0548624779711344, -0.8734572784246782, -0.4838000529948520], + [+0.4941095946388765, -0.4447938112296831, +0.7470034631630423], + [-0.8676668813529025, -0.1980677870294097, +0.4559861124470794] + ]); +} +exports.Rotation_GAL_EQJ = Rotation_GAL_EQJ; +/** + * @brief Calculates a rotation matrix from true ecliptic of date (ECT) to equator of date (EQD). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: ECT = true ecliptic of date + * Target: EQD = equator of date + * + * @param {FlexibleDateTime} time + * The date and time of the ecliptic/equator conversion. + * + * @returns {RotationMatrix} + * A rotation matrix that converts ECT to EQD. + */ +function Rotation_ECT_EQD(time) { + const et = e_tilt(MakeTime(time)); + const tobl = et.tobl * exports.DEG2RAD; + const c = Math.cos(tobl); + const s = Math.sin(tobl); + return new RotationMatrix([ + [1.0, 0.0, 0.0], + [0.0, +c, +s], + [0.0, -s, +c] + ]); +} +exports.Rotation_ECT_EQD = Rotation_ECT_EQD; +/** + * @brief Calculates a rotation matrix from equator of date (EQD) to true ecliptic of date (ECT). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQD = equator of date + * Target: ECT = true ecliptic of date + * + * @param {FlexibleDateTime} time + * The date and time of the equator/ecliptic conversion. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQD to ECT. + */ +function Rotation_EQD_ECT(time) { + const et = e_tilt(MakeTime(time)); + const tobl = et.tobl * exports.DEG2RAD; + const c = Math.cos(tobl); + const s = Math.sin(tobl); + return new RotationMatrix([ + [1.0, 0.0, 0.0], + [0.0, +c, -s], + [0.0, +s, +c] + ]); +} +exports.Rotation_EQD_ECT = Rotation_EQD_ECT; +const ConstelNames = [ + ['And', 'Andromeda'] // 0 + , + ['Ant', 'Antila'] // 1 + , + ['Aps', 'Apus'] // 2 + , + ['Aql', 'Aquila'] // 3 + , + ['Aqr', 'Aquarius'] // 4 + , + ['Ara', 'Ara'] // 5 + , + ['Ari', 'Aries'] // 6 + , + ['Aur', 'Auriga'] // 7 + , + ['Boo', 'Bootes'] // 8 + , + ['Cae', 'Caelum'] // 9 + , + ['Cam', 'Camelopardis'] // 10 + , + ['Cap', 'Capricornus'] // 11 + , + ['Car', 'Carina'] // 12 + , + ['Cas', 'Cassiopeia'] // 13 + , + ['Cen', 'Centaurus'] // 14 + , + ['Cep', 'Cepheus'] // 15 + , + ['Cet', 'Cetus'] // 16 + , + ['Cha', 'Chamaeleon'] // 17 + , + ['Cir', 'Circinus'] // 18 + , + ['CMa', 'Canis Major'] // 19 + , + ['CMi', 'Canis Minor'] // 20 + , + ['Cnc', 'Cancer'] // 21 + , + ['Col', 'Columba'] // 22 + , + ['Com', 'Coma Berenices'] // 23 + , + ['CrA', 'Corona Australis'] // 24 + , + ['CrB', 'Corona Borealis'] // 25 + , + ['Crt', 'Crater'] // 26 + , + ['Cru', 'Crux'] // 27 + , + ['Crv', 'Corvus'] // 28 + , + ['CVn', 'Canes Venatici'] // 29 + , + ['Cyg', 'Cygnus'] // 30 + , + ['Del', 'Delphinus'] // 31 + , + ['Dor', 'Dorado'] // 32 + , + ['Dra', 'Draco'] // 33 + , + ['Equ', 'Equuleus'] // 34 + , + ['Eri', 'Eridanus'] // 35 + , + ['For', 'Fornax'] // 36 + , + ['Gem', 'Gemini'] // 37 + , + ['Gru', 'Grus'] // 38 + , + ['Her', 'Hercules'] // 39 + , + ['Hor', 'Horologium'] // 40 + , + ['Hya', 'Hydra'] // 41 + , + ['Hyi', 'Hydrus'] // 42 + , + ['Ind', 'Indus'] // 43 + , + ['Lac', 'Lacerta'] // 44 + , + ['Leo', 'Leo'] // 45 + , + ['Lep', 'Lepus'] // 46 + , + ['Lib', 'Libra'] // 47 + , + ['LMi', 'Leo Minor'] // 48 + , + ['Lup', 'Lupus'] // 49 + , + ['Lyn', 'Lynx'] // 50 + , + ['Lyr', 'Lyra'] // 51 + , + ['Men', 'Mensa'] // 52 + , + ['Mic', 'Microscopium'] // 53 + , + ['Mon', 'Monoceros'] // 54 + , + ['Mus', 'Musca'] // 55 + , + ['Nor', 'Norma'] // 56 + , + ['Oct', 'Octans'] // 57 + , + ['Oph', 'Ophiuchus'] // 58 + , + ['Ori', 'Orion'] // 59 + , + ['Pav', 'Pavo'] // 60 + , + ['Peg', 'Pegasus'] // 61 + , + ['Per', 'Perseus'] // 62 + , + ['Phe', 'Phoenix'] // 63 + , + ['Pic', 'Pictor'] // 64 + , + ['PsA', 'Pisces Austrinus'] // 65 + , + ['Psc', 'Pisces'] // 66 + , + ['Pup', 'Puppis'] // 67 + , + ['Pyx', 'Pyxis'] // 68 + , + ['Ret', 'Reticulum'] // 69 + , + ['Scl', 'Sculptor'] // 70 + , + ['Sco', 'Scorpius'] // 71 + , + ['Sct', 'Scutum'] // 72 + , + ['Ser', 'Serpens'] // 73 + , + ['Sex', 'Sextans'] // 74 + , + ['Sge', 'Sagitta'] // 75 + , + ['Sgr', 'Sagittarius'] // 76 + , + ['Tau', 'Taurus'] // 77 + , + ['Tel', 'Telescopium'] // 78 + , + ['TrA', 'Triangulum Australe'] // 79 + , + ['Tri', 'Triangulum'] // 80 + , + ['Tuc', 'Tucana'] // 81 + , + ['UMa', 'Ursa Major'] // 82 + , + ['UMi', 'Ursa Minor'] // 83 + , + ['Vel', 'Vela'] // 84 + , + ['Vir', 'Virgo'] // 85 + , + ['Vol', 'Volans'] // 86 + , + ['Vul', 'Vulpecula'] // 87 +]; +const ConstelBounds = [ + [83, 0, 8640, 2112] // UMi + , + [83, 2880, 5220, 2076] // UMi + , + [83, 7560, 8280, 2068] // UMi + , + [83, 6480, 7560, 2064] // UMi + , + [15, 0, 2880, 2040] // Cep + , + [10, 3300, 3840, 1968] // Cam + , + [15, 0, 1800, 1920] // Cep + , + [10, 3840, 5220, 1920] // Cam + , + [83, 6300, 6480, 1920] // UMi + , + [33, 7260, 7560, 1920] // Dra + , + [15, 0, 1263, 1848] // Cep + , + [10, 4140, 4890, 1848] // Cam + , + [83, 5952, 6300, 1800] // UMi + , + [15, 7260, 7440, 1800] // Cep + , + [10, 2868, 3300, 1764] // Cam + , + [33, 3300, 4080, 1764] // Dra + , + [83, 4680, 5952, 1680] // UMi + , + [13, 1116, 1230, 1632] // Cas + , + [33, 7350, 7440, 1608] // Dra + , + [33, 4080, 4320, 1596] // Dra + , + [15, 0, 120, 1584] // Cep + , + [83, 5040, 5640, 1584] // UMi + , + [15, 8490, 8640, 1584] // Cep + , + [33, 4320, 4860, 1536] // Dra + , + [33, 4860, 5190, 1512] // Dra + , + [15, 8340, 8490, 1512] // Cep + , + [10, 2196, 2520, 1488] // Cam + , + [33, 7200, 7350, 1476] // Dra + , + [15, 7393.2, 7416, 1462] // Cep + , + [10, 2520, 2868, 1440] // Cam + , + [82, 2868, 3030, 1440] // UMa + , + [33, 7116, 7200, 1428] // Dra + , + [15, 7200, 7393.2, 1428] // Cep + , + [15, 8232, 8340, 1418] // Cep + , + [13, 0, 876, 1404] // Cas + , + [33, 6990, 7116, 1392] // Dra + , + [13, 612, 687, 1380] // Cas + , + [13, 876, 1116, 1368] // Cas + , + [10, 1116, 1140, 1368] // Cam + , + [15, 8034, 8232, 1350] // Cep + , + [10, 1800, 2196, 1344] // Cam + , + [82, 5052, 5190, 1332] // UMa + , + [33, 5190, 6990, 1332] // Dra + , + [10, 1140, 1200, 1320] // Cam + , + [15, 7968, 8034, 1320] // Cep + , + [15, 7416, 7908, 1316] // Cep + , + [13, 0, 612, 1296] // Cas + , + [50, 2196, 2340, 1296] // Lyn + , + [82, 4350, 4860, 1272] // UMa + , + [33, 5490, 5670, 1272] // Dra + , + [15, 7908, 7968, 1266] // Cep + , + [10, 1200, 1800, 1260] // Cam + , + [13, 8232, 8400, 1260] // Cas + , + [33, 5670, 6120, 1236] // Dra + , + [62, 735, 906, 1212] // Per + , + [33, 6120, 6564, 1212] // Dra + , + [13, 0, 492, 1200] // Cas + , + [62, 492, 600, 1200] // Per + , + [50, 2340, 2448, 1200] // Lyn + , + [13, 8400, 8640, 1200] // Cas + , + [82, 4860, 5052, 1164] // UMa + , + [13, 0, 402, 1152] // Cas + , + [13, 8490, 8640, 1152] // Cas + , + [39, 6543, 6564, 1140] // Her + , + [33, 6564, 6870, 1140] // Dra + , + [30, 6870, 6900, 1140] // Cyg + , + [62, 600, 735, 1128] // Per + , + [82, 3030, 3300, 1128] // UMa + , + [13, 60, 312, 1104] // Cas + , + [82, 4320, 4350, 1080] // UMa + , + [50, 2448, 2652, 1068] // Lyn + , + [30, 7887, 7908, 1056] // Cyg + , + [30, 7875, 7887, 1050] // Cyg + , + [30, 6900, 6984, 1044] // Cyg + , + [82, 3300, 3660, 1008] // UMa + , + [82, 3660, 3882, 960] // UMa + , + [8, 5556, 5670, 960] // Boo + , + [39, 5670, 5880, 960] // Her + , + [50, 3330, 3450, 954] // Lyn + , + [0, 0, 906, 882] // And + , + [62, 906, 924, 882] // Per + , + [51, 6969, 6984, 876] // Lyr + , + [62, 1620, 1689, 864] // Per + , + [30, 7824, 7875, 864] // Cyg + , + [44, 7875, 7920, 864] // Lac + , + [7, 2352, 2652, 852] // Aur + , + [50, 2652, 2790, 852] // Lyn + , + [0, 0, 720, 840] // And + , + [44, 7920, 8214, 840] // Lac + , + [44, 8214, 8232, 828] // Lac + , + [0, 8232, 8460, 828] // And + , + [62, 924, 978, 816] // Per + , + [82, 3882, 3960, 816] // UMa + , + [29, 4320, 4440, 816] // CVn + , + [50, 2790, 3330, 804] // Lyn + , + [48, 3330, 3558, 804] // LMi + , + [0, 258, 507, 792] // And + , + [8, 5466, 5556, 792] // Boo + , + [0, 8460, 8550, 770] // And + , + [29, 4440, 4770, 768] // CVn + , + [0, 8550, 8640, 752] // And + , + [29, 5025, 5052, 738] // CVn + , + [80, 870, 978, 736] // Tri + , + [62, 978, 1620, 736] // Per + , + [7, 1620, 1710, 720] // Aur + , + [51, 6543, 6969, 720] // Lyr + , + [82, 3960, 4320, 696] // UMa + , + [30, 7080, 7530, 696] // Cyg + , + [7, 1710, 2118, 684] // Aur + , + [48, 3558, 3780, 684] // LMi + , + [29, 4770, 5025, 684] // CVn + , + [0, 0, 24, 672] // And + , + [80, 507, 600, 672] // Tri + , + [7, 2118, 2352, 672] // Aur + , + [37, 2838, 2880, 672] // Gem + , + [30, 7530, 7824, 672] // Cyg + , + [30, 6933, 7080, 660] // Cyg + , + [80, 690, 870, 654] // Tri + , + [25, 5820, 5880, 648] // CrB + , + [8, 5430, 5466, 624] // Boo + , + [25, 5466, 5820, 624] // CrB + , + [51, 6612, 6792, 624] // Lyr + , + [48, 3870, 3960, 612] // LMi + , + [51, 6792, 6933, 612] // Lyr + , + [80, 600, 690, 600] // Tri + , + [66, 258, 306, 570] // Psc + , + [48, 3780, 3870, 564] // LMi + , + [87, 7650, 7710, 564] // Vul + , + [77, 2052, 2118, 548] // Tau + , + [0, 24, 51, 528] // And + , + [73, 5730, 5772, 528] // Ser + , + [37, 2118, 2238, 516] // Gem + , + [87, 7140, 7290, 510] // Vul + , + [87, 6792, 6930, 506] // Vul + , + [0, 51, 306, 504] // And + , + [87, 7290, 7404, 492] // Vul + , + [37, 2811, 2838, 480] // Gem + , + [87, 7404, 7650, 468] // Vul + , + [87, 6930, 7140, 460] // Vul + , + [6, 1182, 1212, 456] // Ari + , + [75, 6792, 6840, 444] // Sge + , + [59, 2052, 2076, 432] // Ori + , + [37, 2238, 2271, 420] // Gem + , + [75, 6840, 7140, 388] // Sge + , + [77, 1788, 1920, 384] // Tau + , + [39, 5730, 5790, 384] // Her + , + [75, 7140, 7290, 378] // Sge + , + [77, 1662, 1788, 372] // Tau + , + [77, 1920, 2016, 372] // Tau + , + [23, 4620, 4860, 360] // Com + , + [39, 6210, 6570, 344] // Her + , + [23, 4272, 4620, 336] // Com + , + [37, 2700, 2811, 324] // Gem + , + [39, 6030, 6210, 308] // Her + , + [61, 0, 51, 300] // Peg + , + [77, 2016, 2076, 300] // Tau + , + [37, 2520, 2700, 300] // Gem + , + [61, 7602, 7680, 300] // Peg + , + [37, 2271, 2496, 288] // Gem + , + [39, 6570, 6792, 288] // Her + , + [31, 7515, 7578, 284] // Del + , + [61, 7578, 7602, 284] // Peg + , + [45, 4146, 4272, 264] // Leo + , + [59, 2247, 2271, 240] // Ori + , + [37, 2496, 2520, 240] // Gem + , + [21, 2811, 2853, 240] // Cnc + , + [61, 8580, 8640, 240] // Peg + , + [6, 600, 1182, 238] // Ari + , + [31, 7251, 7308, 204] // Del + , + [8, 4860, 5430, 192] // Boo + , + [61, 8190, 8580, 180] // Peg + , + [21, 2853, 3330, 168] // Cnc + , + [45, 3330, 3870, 168] // Leo + , + [58, 6570, 6718.4, 150] // Oph + , + [3, 6718.4, 6792, 150] // Aql + , + [31, 7500, 7515, 144] // Del + , + [20, 2520, 2526, 132] // CMi + , + [73, 6570, 6633, 108] // Ser + , + [39, 5790, 6030, 96] // Her + , + [58, 6570, 6633, 72] // Oph + , + [61, 7728, 7800, 66] // Peg + , + [66, 0, 720, 48] // Psc + , + [73, 6690, 6792, 48] // Ser + , + [31, 7308, 7500, 48] // Del + , + [34, 7500, 7680, 48] // Equ + , + [61, 7680, 7728, 48] // Peg + , + [61, 7920, 8190, 48] // Peg + , + [61, 7800, 7920, 42] // Peg + , + [20, 2526, 2592, 36] // CMi + , + [77, 1290, 1662, 0] // Tau + , + [59, 1662, 1680, 0] // Ori + , + [20, 2592, 2910, 0] // CMi + , + [85, 5280, 5430, 0] // Vir + , + [58, 6420, 6570, 0] // Oph + , + [16, 954, 1182, -42] // Cet + , + [77, 1182, 1290, -42] // Tau + , + [73, 5430, 5856, -78] // Ser + , + [59, 1680, 1830, -96] // Ori + , + [59, 2100, 2247, -96] // Ori + , + [73, 6420, 6468, -96] // Ser + , + [73, 6570, 6690, -96] // Ser + , + [3, 6690, 6792, -96] // Aql + , + [66, 8190, 8580, -96] // Psc + , + [45, 3870, 4146, -144] // Leo + , + [85, 4146, 4260, -144] // Vir + , + [66, 0, 120, -168] // Psc + , + [66, 8580, 8640, -168] // Psc + , + [85, 5130, 5280, -192] // Vir + , + [58, 5730, 5856, -192] // Oph + , + [3, 7200, 7392, -216] // Aql + , + [4, 7680, 7872, -216] // Aqr + , + [58, 6180, 6468, -240] // Oph + , + [54, 2100, 2910, -264] // Mon + , + [35, 1770, 1830, -264] // Eri + , + [59, 1830, 2100, -264] // Ori + , + [41, 2910, 3012, -264] // Hya + , + [74, 3450, 3870, -264] // Sex + , + [85, 4260, 4620, -264] // Vir + , + [58, 6330, 6360, -280] // Oph + , + [3, 6792, 7200, -288.8] // Aql + , + [35, 1740, 1770, -348] // Eri + , + [4, 7392, 7680, -360] // Aqr + , + [73, 6180, 6570, -384] // Ser + , + [72, 6570, 6792, -384] // Sct + , + [41, 3012, 3090, -408] // Hya + , + [58, 5856, 5895, -438] // Oph + , + [41, 3090, 3270, -456] // Hya + , + [26, 3870, 3900, -456] // Crt + , + [71, 5856, 5895, -462] // Sco + , + [47, 5640, 5730, -480] // Lib + , + [28, 4530, 4620, -528] // Crv + , + [85, 4620, 5130, -528] // Vir + , + [41, 3270, 3510, -576] // Hya + , + [16, 600, 954, -585.2] // Cet + , + [35, 954, 1350, -585.2] // Eri + , + [26, 3900, 4260, -588] // Crt + , + [28, 4260, 4530, -588] // Crv + , + [47, 5130, 5370, -588] // Lib + , + [58, 5856, 6030, -590] // Oph + , + [16, 0, 600, -612] // Cet + , + [11, 7680, 7872, -612] // Cap + , + [4, 7872, 8580, -612] // Aqr + , + [16, 8580, 8640, -612] // Cet + , + [41, 3510, 3690, -636] // Hya + , + [35, 1692, 1740, -654] // Eri + , + [46, 1740, 2202, -654] // Lep + , + [11, 7200, 7680, -672] // Cap + , + [41, 3690, 3810, -700] // Hya + , + [41, 4530, 5370, -708] // Hya + , + [47, 5370, 5640, -708] // Lib + , + [71, 5640, 5760, -708] // Sco + , + [35, 1650, 1692, -720] // Eri + , + [58, 6030, 6336, -720] // Oph + , + [76, 6336, 6420, -720] // Sgr + , + [41, 3810, 3900, -748] // Hya + , + [19, 2202, 2652, -792] // CMa + , + [41, 4410, 4530, -792] // Hya + , + [41, 3900, 4410, -840] // Hya + , + [36, 1260, 1350, -864] // For + , + [68, 3012, 3372, -882] // Pyx + , + [35, 1536, 1650, -888] // Eri + , + [76, 6420, 6900, -888] // Sgr + , + [65, 7680, 8280, -888] // PsA + , + [70, 8280, 8400, -888] // Scl + , + [36, 1080, 1260, -950] // For + , + [1, 3372, 3960, -954] // Ant + , + [70, 0, 600, -960] // Scl + , + [36, 600, 1080, -960] // For + , + [35, 1392, 1536, -960] // Eri + , + [70, 8400, 8640, -960] // Scl + , + [14, 5100, 5370, -1008] // Cen + , + [49, 5640, 5760, -1008] // Lup + , + [71, 5760, 5911.5, -1008] // Sco + , + [9, 1740, 1800, -1032] // Cae + , + [22, 1800, 2370, -1032] // Col + , + [67, 2880, 3012, -1032] // Pup + , + [35, 1230, 1392, -1056] // Eri + , + [71, 5911.5, 6420, -1092] // Sco + , + [24, 6420, 6900, -1092] // CrA + , + [76, 6900, 7320, -1092] // Sgr + , + [53, 7320, 7680, -1092] // Mic + , + [35, 1080, 1230, -1104] // Eri + , + [9, 1620, 1740, -1116] // Cae + , + [49, 5520, 5640, -1152] // Lup + , + [63, 0, 840, -1156] // Phe + , + [35, 960, 1080, -1176] // Eri + , + [40, 1470, 1536, -1176] // Hor + , + [9, 1536, 1620, -1176] // Cae + , + [38, 7680, 7920, -1200] // Gru + , + [67, 2160, 2880, -1218] // Pup + , + [84, 2880, 2940, -1218] // Vel + , + [35, 870, 960, -1224] // Eri + , + [40, 1380, 1470, -1224] // Hor + , + [63, 0, 660, -1236] // Phe + , + [12, 2160, 2220, -1260] // Car + , + [84, 2940, 3042, -1272] // Vel + , + [40, 1260, 1380, -1276] // Hor + , + [32, 1380, 1440, -1276] // Dor + , + [63, 0, 570, -1284] // Phe + , + [35, 780, 870, -1296] // Eri + , + [64, 1620, 1800, -1296] // Pic + , + [49, 5418, 5520, -1296] // Lup + , + [84, 3042, 3180, -1308] // Vel + , + [12, 2220, 2340, -1320] // Car + , + [14, 4260, 4620, -1320] // Cen + , + [49, 5100, 5418, -1320] // Lup + , + [56, 5418, 5520, -1320] // Nor + , + [32, 1440, 1560, -1356] // Dor + , + [84, 3180, 3960, -1356] // Vel + , + [14, 3960, 4050, -1356] // Cen + , + [5, 6300, 6480, -1368] // Ara + , + [78, 6480, 7320, -1368] // Tel + , + [38, 7920, 8400, -1368] // Gru + , + [40, 1152, 1260, -1380] // Hor + , + [64, 1800, 1980, -1380] // Pic + , + [12, 2340, 2460, -1392] // Car + , + [63, 0, 480, -1404] // Phe + , + [35, 480, 780, -1404] // Eri + , + [63, 8400, 8640, -1404] // Phe + , + [32, 1560, 1650, -1416] // Dor + , + [56, 5520, 5911.5, -1440] // Nor + , + [43, 7320, 7680, -1440] // Ind + , + [64, 1980, 2160, -1464] // Pic + , + [18, 5460, 5520, -1464] // Cir + , + [5, 5911.5, 5970, -1464] // Ara + , + [18, 5370, 5460, -1526] // Cir + , + [5, 5970, 6030, -1526] // Ara + , + [64, 2160, 2460, -1536] // Pic + , + [12, 2460, 3252, -1536] // Car + , + [14, 4050, 4260, -1536] // Cen + , + [27, 4260, 4620, -1536] // Cru + , + [14, 4620, 5232, -1536] // Cen + , + [18, 4860, 4920, -1560] // Cir + , + [5, 6030, 6060, -1560] // Ara + , + [40, 780, 1152, -1620] // Hor + , + [69, 1152, 1650, -1620] // Ret + , + [18, 5310, 5370, -1620] // Cir + , + [5, 6060, 6300, -1620] // Ara + , + [60, 6300, 6480, -1620] // Pav + , + [81, 7920, 8400, -1620] // Tuc + , + [32, 1650, 2370, -1680] // Dor + , + [18, 4920, 5310, -1680] // Cir + , + [79, 5310, 6120, -1680] // TrA + , + [81, 0, 480, -1800] // Tuc + , + [42, 1260, 1650, -1800] // Hyi + , + [86, 2370, 3252, -1800] // Vol + , + [12, 3252, 4050, -1800] // Car + , + [55, 4050, 4920, -1800] // Mus + , + [60, 6480, 7680, -1800] // Pav + , + [43, 7680, 8400, -1800] // Ind + , + [81, 8400, 8640, -1800] // Tuc + , + [81, 270, 480, -1824] // Tuc + , + [42, 0, 1260, -1980] // Hyi + , + [17, 2760, 4920, -1980] // Cha + , + [2, 4920, 6480, -1980] // Aps + , + [52, 1260, 2760, -2040] // Men + , + [57, 0, 8640, -2160] // Oct +]; +let ConstelRot; +let Epoch2000; +/** + * @brief Reports the constellation that a given celestial point lies within. + * + * @property {string} symbol + * 3-character mnemonic symbol for the constellation, e.g. "Ori". + * + * @property {string} name + * Full name of constellation, e.g. "Orion". + * + * @property {number} ra1875 + * Right ascension expressed in B1875 coordinates. + * + * @property {number} dec1875 + * Declination expressed in B1875 coordinates. + */ +class ConstellationInfo { + constructor(symbol, name, ra1875, dec1875) { + this.symbol = symbol; + this.name = name; + this.ra1875 = ra1875; + this.dec1875 = dec1875; + } +} +exports.ConstellationInfo = ConstellationInfo; +/** + * @brief Determines the constellation that contains the given point in the sky. + * + * Given J2000 equatorial (EQJ) coordinates of a point in the sky, + * determines the constellation that contains that point. + * + * @param {number} ra + * The right ascension (RA) of a point in the sky, using the J2000 equatorial system. + * + * @param {number} dec + * The declination (DEC) of a point in the sky, using the J2000 equatorial system. + * + * @returns {ConstellationInfo} + * An object that contains the 3-letter abbreviation and full name + * of the constellation that contains the given (ra,dec), along with + * the converted B1875 (ra,dec) for that point. + */ +function Constellation(ra, dec) { + VerifyNumber(ra); + VerifyNumber(dec); + if (dec < -90 || dec > +90) + throw 'Invalid declination angle. Must be -90..+90.'; + // Clamp right ascension to [0, 24) sidereal hours. + ra %= 24.0; + if (ra < 0.0) + ra += 24.0; + // Lazy-initialize rotation matrix. + if (!ConstelRot) { + // Need to calculate the B1875 epoch. Based on this: + // https://en.wikipedia.org/wiki/Epoch_(astronomy)#Besselian_years + // B = 1900 + (JD - 2415020.31352) / 365.242198781 + // I'm interested in using TT instead of JD, giving: + // B = 1900 + ((TT+2451545) - 2415020.31352) / 365.242198781 + // B = 1900 + (TT + 36524.68648) / 365.242198781 + // TT = 365.242198781*(B - 1900) - 36524.68648 = -45655.741449525 + // But the AstroTime constructor wants UT, not TT. + // Near that date, I get a historical correction of ut-tt = 3.2 seconds. + // That gives UT = -45655.74141261017 for the B1875 epoch, + // or 1874-12-31T18:12:21.950Z. + ConstelRot = Rotation_EQJ_EQD(new AstroTime(-45655.74141261017)); + Epoch2000 = new AstroTime(0); + } + // Convert coordinates from J2000 to B1875. + const sph2000 = new Spherical(dec, 15.0 * ra, 1.0); + const vec2000 = VectorFromSphere(sph2000, Epoch2000); + const vec1875 = RotateVector(ConstelRot, vec2000); + const equ1875 = EquatorFromVector(vec1875); + // Search for the constellation using the B1875 coordinates. + const fd = 10 / (4 * 60); // conversion factor from compact units to DEC degrees + const fr = fd / 15; // conversion factor from compact units to RA sidereal hours + for (let b of ConstelBounds) { + // Convert compact angular units to RA in hours, DEC in degrees. + const dec = b[3] * fd; + const ra_lo = b[1] * fr; + const ra_hi = b[2] * fr; + if (dec <= equ1875.dec && ra_lo <= equ1875.ra && equ1875.ra < ra_hi) { + const c = ConstelNames[b[0]]; + return new ConstellationInfo(c[0], c[1], equ1875.ra, equ1875.dec); + } + } + // This should never happen! + throw 'Unable to find constellation for given coordinates.'; +} +exports.Constellation = Constellation; +/** + * @brief The different kinds of lunar/solar eclipses.. + * + * `Penumbral`: A lunar eclipse in which only the Earth's penumbra falls on the Moon. (Never used for a solar eclipse.) + * `Partial`: A partial lunar/solar eclipse. + * `Annular`: A solar eclipse in which the entire Moon is visible against the Sun, but the Sun appears as a ring around the Moon. (Never used for a lunar eclipse.) + * `Total`: A total lunar/solar eclipse. + * + * @enum {string} + */ +var EclipseKind; +(function (EclipseKind) { + EclipseKind["Penumbral"] = "penumbral"; + EclipseKind["Partial"] = "partial"; + EclipseKind["Annular"] = "annular"; + EclipseKind["Total"] = "total"; +})(EclipseKind = exports.EclipseKind || (exports.EclipseKind = {})); +/** + * @brief Returns information about a lunar eclipse. + * + * Returned by {@link SearchLunarEclipse} or {@link NextLunarEclipse} + * to report information about a lunar eclipse event. + * When a lunar eclipse is found, it is classified as penumbral, partial, or total. + * Penumbral eclipses are difficult to observe, because the Moon is only slightly dimmed + * by the Earth's penumbra; no part of the Moon touches the Earth's umbra. + * Partial eclipses occur when part, but not all, of the Moon touches the Earth's umbra. + * Total eclipses occur when the entire Moon passes into the Earth's umbra. + * + * The `kind` field thus holds one of the enum values `EclipseKind.Penumbral`, `EclipseKind.Partial`, + * or `EclipseKind.Total`, depending on the kind of lunar eclipse found. + * + * The `obscuration` field holds a value in the range [0, 1] that indicates what fraction + * of the Moon's apparent disc area is covered by the Earth's umbra at the eclipse's peak. + * This indicates how dark the peak eclipse appears. For penumbral eclipses, the obscuration + * is 0, because the Moon does not pass through the Earth's umbra. For partial eclipses, + * the obscuration is somewhere between 0 and 1. For total lunar eclipses, the obscuration is 1. + * + * Field `peak` holds the date and time of the peak of the eclipse, when it is at its peak. + * + * Fields `sd_penum`, `sd_partial`, and `sd_total` hold the semi-duration of each phase + * of the eclipse, which is half of the amount of time the eclipse spends in each + * phase (expressed in minutes), or 0 if the eclipse never reaches that phase. + * By converting from minutes to days, and subtracting/adding with `peak`, the caller + * may determine the date and time of the beginning/end of each eclipse phase. + * + * @property {EclipseKind} kind + * The type of lunar eclipse found. + * + * @property {number} obscuration + * The peak fraction of the Moon's apparent disc that is covered by the Earth's umbra. + * + * @property {AstroTime} peak + * The time of the eclipse at its peak. + * + * @property {number} sd_penum + * The semi-duration of the penumbral phase in minutes. + * + * @property {number} sd_partial + * The semi-duration of the penumbral phase in minutes, or 0.0 if none. + * + * @property {number} sd_total + * The semi-duration of the penumbral phase in minutes, or 0.0 if none. + * + */ +class LunarEclipseInfo { + constructor(kind, obscuration, peak, sd_penum, sd_partial, sd_total) { + this.kind = kind; + this.obscuration = obscuration; + this.peak = peak; + this.sd_penum = sd_penum; + this.sd_partial = sd_partial; + this.sd_total = sd_total; + } +} +exports.LunarEclipseInfo = LunarEclipseInfo; +/** + * @ignore + * + * @brief Represents the relative alignment of the Earth and another body, and their respective shadows. + * + * This is an internal data structure used to assist calculation of + * lunar eclipses, solar eclipses, and transits of Mercury and Venus. + * + * Definitions: + * + * casting body = A body that casts a shadow of interest, possibly striking another body. + * + * receiving body = A body on which the shadow of another body might land. + * + * shadow axis = The line passing through the center of the Sun and the center of the casting body. + * + * shadow plane = The plane passing through the center of a receiving body, + * and perpendicular to the shadow axis. + * + * @property {AstroTime} time + * The time associated with the shadow calculation. + * + * @property {number} u + * The distance [au] between the center of the casting body and the shadow plane. + * + * @property {number} r + * The distance [km] between center of receiving body and the shadow axis. + * + * @property {number} k + * The umbra radius [km] at the shadow plane. + * + * @property {number} p + * The penumbra radius [km] at the shadow plane. + * + * @property {Vector} target + * The location in space where we are interested in determining how close a shadow falls. + * For example, when calculating lunar eclipses, `target` would be the center of the Moon + * expressed in geocentric coordinates. Then we can evaluate how far the center of the Earth's + * shadow cone approaches the center of the Moon. + * The vector components are expressed in [au]. + * + * @property {Vector} dir + * The direction in space that the shadow points away from the center of a shadow-casting body. + * This vector lies on the shadow axis and points away from the Sun. + * In other words: the direction light from the Sun would be traveling, + * except that the center of a body (Earth, Moon, Mercury, or Venus) is blocking it. + * The distance units do not matter, because the vector will be normalized. + */ +class ShadowInfo { + constructor(time, u, r, k, p, target, dir) { + this.time = time; + this.u = u; + this.r = r; + this.k = k; + this.p = p; + this.target = target; + this.dir = dir; + } +} +function CalcShadow(body_radius_km, time, target, dir) { + const u = (dir.x * target.x + dir.y * target.y + dir.z * target.z) / (dir.x * dir.x + dir.y * dir.y + dir.z * dir.z); + const dx = (u * dir.x) - target.x; + const dy = (u * dir.y) - target.y; + const dz = (u * dir.z) - target.z; + const r = exports.KM_PER_AU * Math.hypot(dx, dy, dz); + const k = +SUN_RADIUS_KM - (1.0 + u) * (SUN_RADIUS_KM - body_radius_km); + const p = -SUN_RADIUS_KM + (1.0 + u) * (SUN_RADIUS_KM + body_radius_km); + return new ShadowInfo(time, u, r, k, p, target, dir); +} +function EarthShadow(time) { + // Light-travel and aberration corrected vector from the Earth to the Sun. + const s = GeoVector(Body.Sun, time, true); + // The vector e = -s is thus the path of sunlight through the center of the Earth. + const e = new Vector(-s.x, -s.y, -s.z, s.t); + // Geocentric moon. + const m = GeoMoon(time); + return CalcShadow(EARTH_ECLIPSE_RADIUS_KM, time, m, e); +} +function MoonShadow(time) { + const s = GeoVector(Body.Sun, time, true); + const m = GeoMoon(time); // geocentric Moon + // Calculate lunacentric Earth. + const e = new Vector(-m.x, -m.y, -m.z, m.t); + // Convert geocentric moon to heliocentric Moon. + m.x -= s.x; + m.y -= s.y; + m.z -= s.z; + return CalcShadow(MOON_MEAN_RADIUS_KM, time, e, m); +} +function LocalMoonShadow(time, observer) { + // Calculate observer's geocentric position. + const pos = geo_pos(time, observer); + // Calculate light-travel and aberration corrected Sun. + const s = GeoVector(Body.Sun, time, true); + // Calculate geocentric Moon. + const m = GeoMoon(time); // geocentric Moon + // Calculate lunacentric location of an observer on the Earth's surface. + const o = new Vector(pos[0] - m.x, pos[1] - m.y, pos[2] - m.z, time); + // Convert geocentric moon to heliocentric Moon. + m.x -= s.x; + m.y -= s.y; + m.z -= s.z; + return CalcShadow(MOON_MEAN_RADIUS_KM, time, o, m); +} +function PlanetShadow(body, planet_radius_km, time) { + // Calculate light-travel-corrected vector from Earth to planet. + const g = GeoVector(body, time, true); + // Calculate light-travel-corrected vector from Earth to Sun. + const e = GeoVector(Body.Sun, time, true); + // Deduce light-travel-corrected vector from Sun to planet. + const p = new Vector(g.x - e.x, g.y - e.y, g.z - e.z, time); + // Calcluate Earth's position from the planet's point of view. + e.x = -g.x; + e.y = -g.y; + e.z = -g.z; + return CalcShadow(planet_radius_km, time, e, p); +} +function ShadowDistanceSlope(shadowfunc, time) { + const dt = 1.0 / 86400.0; + const t1 = time.AddDays(-dt); + const t2 = time.AddDays(+dt); + const shadow1 = shadowfunc(t1); + const shadow2 = shadowfunc(t2); + return (shadow2.r - shadow1.r) / dt; +} +function PlanetShadowSlope(body, planet_radius_km, time) { + const dt = 1.0 / 86400.0; + const shadow1 = PlanetShadow(body, planet_radius_km, time.AddDays(-dt)); + const shadow2 = PlanetShadow(body, planet_radius_km, time.AddDays(+dt)); + return (shadow2.r - shadow1.r) / dt; +} +function PeakEarthShadow(search_center_time) { + const window = 0.03; /* initial search window, in days, before/after given time */ + const t1 = search_center_time.AddDays(-window); + const t2 = search_center_time.AddDays(+window); + const tx = Search((time) => ShadowDistanceSlope(EarthShadow, time), t1, t2); + if (!tx) + throw 'Failed to find peak Earth shadow time.'; + return EarthShadow(tx); +} +function PeakMoonShadow(search_center_time) { + const window = 0.03; /* initial search window, in days, before/after given time */ + const t1 = search_center_time.AddDays(-window); + const t2 = search_center_time.AddDays(+window); + const tx = Search((time) => ShadowDistanceSlope(MoonShadow, time), t1, t2); + if (!tx) + throw 'Failed to find peak Moon shadow time.'; + return MoonShadow(tx); +} +function PeakPlanetShadow(body, planet_radius_km, search_center_time) { + // Search for when the body's shadow is closest to the center of the Earth. + const window = 1.0; // days before/after inferior conjunction to search for minimum shadow distance. + const t1 = search_center_time.AddDays(-window); + const t2 = search_center_time.AddDays(+window); + const tx = Search((time) => PlanetShadowSlope(body, planet_radius_km, time), t1, t2); + if (!tx) + throw 'Failed to find peak planet shadow time.'; + return PlanetShadow(body, planet_radius_km, tx); +} +function PeakLocalMoonShadow(search_center_time, observer) { + // Search for the time near search_center_time that the Moon's shadow comes + // closest to the given observer. + const window = 0.2; + const t1 = search_center_time.AddDays(-window); + const t2 = search_center_time.AddDays(+window); + function shadowfunc(time) { + return LocalMoonShadow(time, observer); + } + const time = Search((time) => ShadowDistanceSlope(shadowfunc, time), t1, t2); + if (!time) + throw `PeakLocalMoonShadow: search failure for search_center_time = ${search_center_time}`; + return LocalMoonShadow(time, observer); +} +function ShadowSemiDurationMinutes(center_time, radius_limit, window_minutes) { + // Search backwards and forwards from the center time until shadow axis distance crosses radius limit. + const window = window_minutes / (24.0 * 60.0); + const before = center_time.AddDays(-window); + const after = center_time.AddDays(+window); + const t1 = Search((time) => -(EarthShadow(time).r - radius_limit), before, center_time); + const t2 = Search((time) => +(EarthShadow(time).r - radius_limit), center_time, after); + if (!t1 || !t2) + throw 'Failed to find shadow semiduration'; + return (t2.ut - t1.ut) * ((24.0 * 60.0) / 2.0); // convert days to minutes and average the semi-durations. +} +function MoonEclipticLatitudeDegrees(time) { + const moon = CalcMoon(time); + return exports.RAD2DEG * moon.geo_eclip_lat; +} +function Obscuration(a, // radius of first disc +b, // radius of second disc +c // distance between the centers of the discs +) { + if (a <= 0.0) + throw 'Radius of first disc must be positive.'; + if (b <= 0.0) + throw 'Radius of second disc must be positive.'; + if (c < 0.0) + throw 'Distance between discs is not allowed to be negative.'; + if (c >= a + b) { + // The discs are too far apart to have any overlapping area. + return 0.0; + } + if (c == 0.0) { + // The discs have a common center. Therefore, one disc is inside the other. + return (a <= b) ? 1.0 : (b * b) / (a * a); + } + const x = (a * a - b * b + c * c) / (2 * c); + const radicand = a * a - x * x; + if (radicand <= 0.0) { + // The circumferences do not intersect, or are tangent. + // We already ruled out the case of non-overlapping discs. + // Therefore, one disc is inside the other. + return (a <= b) ? 1.0 : (b * b) / (a * a); + } + // The discs overlap fractionally in a pair of lens-shaped areas. + const y = Math.sqrt(radicand); + // Return the overlapping fractional area. + // There are two lens-shaped areas, one to the left of x, the other to the right of x. + // Each part is calculated by subtracting a triangular area from a sector's area. + const lens1 = a * a * Math.acos(x / a) - x * y; + const lens2 = b * b * Math.acos((c - x) / b) - (c - x) * y; + // Find the fractional area with respect to the first disc. + return (lens1 + lens2) / (Math.PI * a * a); +} +function SolarEclipseObscuration(hm, // heliocentric Moon +lo // lunacentric observer +) { + // Find heliocentric observer. + const ho = new Vector(hm.x + lo.x, hm.y + lo.y, hm.z + lo.z, hm.t); + // Calculate the apparent angular radius of the Sun for the observer. + const sun_radius = Math.asin(SUN_RADIUS_AU / ho.Length()); + // Calculate the apparent angular radius of the Moon for the observer. + const moon_radius = Math.asin(MOON_POLAR_RADIUS_AU / lo.Length()); + // Calculate the apparent angular separation between the Sun's center and the Moon's center. + const sun_moon_separation = AngleBetween(lo, ho); + // Find the fraction of the Sun's apparent disc area that is covered by the Moon. + const obscuration = Obscuration(sun_radius, moon_radius, sun_moon_separation * exports.DEG2RAD); + // HACK: In marginal cases, we need to clamp obscuration to less than 1.0. + // This function is never called for total eclipses, so it should never return 1.0. + return Math.min(0.9999, obscuration); +} +/** + * @brief Searches for a lunar eclipse. + * + * This function finds the first lunar eclipse that occurs after `startTime`. + * A lunar eclipse may be penumbral, partial, or total. + * See {@link LunarEclipseInfo} for more information. + * To find a series of lunar eclipses, call this function once, + * then keep calling {@link NextLunarEclipse} as many times as desired, + * passing in the `peak` value returned from the previous call. + * + * @param {FlexibleDateTime} date + * The date and time for starting the search for a lunar eclipse. + * + * @returns {LunarEclipseInfo} + */ +function SearchLunarEclipse(date) { + const PruneLatitude = 1.8; /* full Moon's ecliptic latitude above which eclipse is impossible */ + let fmtime = MakeTime(date); + for (let fmcount = 0; fmcount < 12; ++fmcount) { + /* Search for the next full moon. Any eclipse will be near it. */ + const fullmoon = SearchMoonPhase(180, fmtime, 40); + if (!fullmoon) + throw 'Cannot find full moon.'; + /* + Pruning: if the full Moon's ecliptic latitude is too large, + a lunar eclipse is not possible. Avoid needless work searching for + the minimum moon distance. + */ + const eclip_lat = MoonEclipticLatitudeDegrees(fullmoon); + if (Math.abs(eclip_lat) < PruneLatitude) { + /* Search near the full moon for the time when the center of the Moon */ + /* is closest to the line passing through the centers of the Sun and Earth. */ + const shadow = PeakEarthShadow(fullmoon); + if (shadow.r < shadow.p + MOON_MEAN_RADIUS_KM) { + /* This is at least a penumbral eclipse. We will return a result. */ + let kind = EclipseKind.Penumbral; + let obscuration = 0.0; + let sd_total = 0.0; + let sd_partial = 0.0; + let sd_penum = ShadowSemiDurationMinutes(shadow.time, shadow.p + MOON_MEAN_RADIUS_KM, 200.0); + if (shadow.r < shadow.k + MOON_MEAN_RADIUS_KM) { + /* This is at least a partial eclipse. */ + kind = EclipseKind.Partial; + sd_partial = ShadowSemiDurationMinutes(shadow.time, shadow.k + MOON_MEAN_RADIUS_KM, sd_penum); + if (shadow.r + MOON_MEAN_RADIUS_KM < shadow.k) { + /* This is a total eclipse. */ + kind = EclipseKind.Total; + obscuration = 1.0; + sd_total = ShadowSemiDurationMinutes(shadow.time, shadow.k - MOON_MEAN_RADIUS_KM, sd_partial); + } + else { + obscuration = Obscuration(MOON_MEAN_RADIUS_KM, shadow.k, shadow.r); + } + } + return new LunarEclipseInfo(kind, obscuration, shadow.time, sd_penum, sd_partial, sd_total); + } + } + /* We didn't find an eclipse on this full moon, so search for the next one. */ + fmtime = fullmoon.AddDays(10); + } + /* This should never happen because there are always at least 2 full moons per year. */ + throw 'Failed to find lunar eclipse within 12 full moons.'; +} +exports.SearchLunarEclipse = SearchLunarEclipse; +/** + * @brief Reports the time and geographic location of the peak of a solar eclipse. + * + * Returned by {@link SearchGlobalSolarEclipse} or {@link NextGlobalSolarEclipse} + * to report information about a solar eclipse event. + * + * The eclipse is classified as partial, annular, or total, depending on the + * maximum amount of the Sun's disc obscured, as seen at the peak location + * on the surface of the Earth. + * + * The `kind` field thus holds one of the values `EclipseKind.Partial`, `EclipseKind.Annular`, or `EclipseKind.Total`. + * A total eclipse is when the peak observer sees the Sun completely blocked by the Moon. + * An annular eclipse is like a total eclipse, but the Moon is too far from the Earth's surface + * to completely block the Sun; instead, the Sun takes on a ring-shaped appearance. + * A partial eclipse is when the Moon blocks part of the Sun's disc, but nobody on the Earth + * observes either a total or annular eclipse. + * + * If `kind` is `EclipseKind.Total` or `EclipseKind.Annular`, the `latitude` and `longitude` + * fields give the geographic coordinates of the center of the Moon's shadow projected + * onto the daytime side of the Earth at the instant of the eclipse's peak. + * If `kind` has any other value, `latitude` and `longitude` are undefined and should + * not be used. + * + * For total or annular eclipses, the `obscuration` field holds the fraction (0, 1] + * of the Sun's apparent disc area that is blocked from view by the Moon's silhouette, + * as seen by an observer located at the geographic coordinates `latitude`, `longitude` + * at the darkest time `peak`. The value will always be 1 for total eclipses, and less than + * 1 for annular eclipses. + * For partial eclipses, `obscuration` is undefined and should not be used. + * This is because there is little practical use for an obscuration value of + * a partial eclipse without supplying a particular observation location. + * Developers who wish to find an obscuration value for partial solar eclipses should therefore use + * {@link SearchLocalSolarEclipse} and provide the geographic coordinates of an observer. + * + * @property {EclipseKind} kind + * One of the following enumeration values: `EclipseKind.Partial`, `EclipseKind.Annular`, `EclipseKind.Total`. + * + * @property {number | undefined} obscuration + * The peak fraction of the Sun's apparent disc area obscured by the Moon (total and annular eclipses only) + * + * @property {AstroTime} peak + * The date and time when the solar eclipse is darkest. + * This is the instant when the axis of the Moon's shadow cone passes closest to the Earth's center. + * + * @property {number} distance + * The distance in kilometers between the axis of the Moon's shadow cone + * and the center of the Earth at the time indicated by `peak`. + * + * @property {number | undefined} latitude + * If `kind` holds `EclipseKind.Total`, the geographic latitude in degrees + * where the center of the Moon's shadow falls on the Earth at the + * time indicated by `peak`; otherwise, `latitude` holds `undefined`. + * + * @property {number | undefined} longitude + * If `kind` holds `EclipseKind.Total`, the geographic longitude in degrees + * where the center of the Moon's shadow falls on the Earth at the + * time indicated by `peak`; otherwise, `longitude` holds `undefined`. + */ +class GlobalSolarEclipseInfo { + constructor(kind, obscuration, peak, distance, latitude, longitude) { + this.kind = kind; + this.obscuration = obscuration; + this.peak = peak; + this.distance = distance; + this.latitude = latitude; + this.longitude = longitude; + } +} +exports.GlobalSolarEclipseInfo = GlobalSolarEclipseInfo; +function EclipseKindFromUmbra(k) { + // The umbra radius tells us what kind of eclipse the observer sees. + // If the umbra radius is positive, this is a total eclipse. Otherwise, it's annular. + // HACK: I added a tiny bias (14 meters) to match Espenak test data. + return (k > 0.014) ? EclipseKind.Total : EclipseKind.Annular; +} +function GeoidIntersect(shadow) { + let kind = EclipseKind.Partial; + let peak = shadow.time; + let distance = shadow.r; + let latitude; // left undefined for partial eclipses + let longitude; // left undefined for partial eclipses + // We want to calculate the intersection of the shadow axis with the Earth's geoid. + // First we must convert EQJ (equator of J2000) coordinates to EQD (equator of date) + // coordinates that are perfectly aligned with the Earth's equator at this + // moment in time. + const rot = Rotation_EQJ_EQD(shadow.time); + const v = RotateVector(rot, shadow.dir); // shadow-axis vector in equator-of-date coordinates + const e = RotateVector(rot, shadow.target); // lunacentric Earth in equator-of-date coordinates + // Convert all distances from AU to km. + // But dilate the z-coordinates so that the Earth becomes a perfect sphere. + // Then find the intersection of the vector with the sphere. + // See p 184 in Montenbruck & Pfleger's "Astronomy on the Personal Computer", second edition. + v.x *= exports.KM_PER_AU; + v.y *= exports.KM_PER_AU; + v.z *= exports.KM_PER_AU / EARTH_FLATTENING; + e.x *= exports.KM_PER_AU; + e.y *= exports.KM_PER_AU; + e.z *= exports.KM_PER_AU / EARTH_FLATTENING; + // Solve the quadratic equation that finds whether and where + // the shadow axis intersects with the Earth in the dilated coordinate system. + const R = EARTH_EQUATORIAL_RADIUS_KM; + const A = v.x * v.x + v.y * v.y + v.z * v.z; + const B = -2.0 * (v.x * e.x + v.y * e.y + v.z * e.z); + const C = (e.x * e.x + e.y * e.y + e.z * e.z) - R * R; + const radic = B * B - 4 * A * C; + let obscuration; + if (radic > 0.0) { + // Calculate the closer of the two intersection points. + // This will be on the day side of the Earth. + const u = (-B - Math.sqrt(radic)) / (2 * A); + // Convert lunacentric dilated coordinates to geocentric coordinates. + const px = u * v.x - e.x; + const py = u * v.y - e.y; + const pz = (u * v.z - e.z) * EARTH_FLATTENING; + // Convert cartesian coordinates into geodetic latitude/longitude. + const proj = Math.hypot(px, py) * EARTH_FLATTENING_SQUARED; + if (proj == 0.0) + latitude = (pz > 0.0) ? +90.0 : -90.0; + else + latitude = exports.RAD2DEG * Math.atan(pz / proj); + // Adjust longitude for Earth's rotation at the given UT. + const gast = sidereal_time(peak); + longitude = (exports.RAD2DEG * Math.atan2(py, px) - (15 * gast)) % 360.0; + if (longitude <= -180.0) + longitude += 360.0; + else if (longitude > +180.0) + longitude -= 360.0; + // We want to determine whether the observer sees a total eclipse or an annular eclipse. + // We need to perform a series of vector calculations... + // Calculate the inverse rotation matrix, so we can convert EQD to EQJ. + const inv = InverseRotation(rot); + // Put the EQD geocentric coordinates of the observer into the vector 'o'. + // Also convert back from kilometers to astronomical units. + let o = new Vector(px / exports.KM_PER_AU, py / exports.KM_PER_AU, pz / exports.KM_PER_AU, shadow.time); + // Rotate the observer's geocentric EQD back to the EQJ system. + o = RotateVector(inv, o); + // Convert geocentric vector to lunacentric vector. + o.x += shadow.target.x; + o.y += shadow.target.y; + o.z += shadow.target.z; + // Recalculate the shadow using a vector from the Moon's center toward the observer. + const surface = CalcShadow(MOON_POLAR_RADIUS_KM, shadow.time, o, shadow.dir); + // If we did everything right, the shadow distance should be very close to zero. + // That's because we already determined the observer 'o' is on the shadow axis! + if (surface.r > 1.0e-9 || surface.r < 0.0) + throw `Unexpected shadow distance from geoid intersection = ${surface.r}`; + kind = EclipseKindFromUmbra(surface.k); + obscuration = (kind === EclipseKind.Total) ? 1.0 : SolarEclipseObscuration(shadow.dir, o); + } + else { + // This is a partial solar eclipse. It does not make practical sense to calculate obscuration. + // Anyone who wants obscuration should use Astronomy.SearchLocalSolarEclipse for a specific location on the Earth. + obscuration = undefined; + } + return new GlobalSolarEclipseInfo(kind, obscuration, peak, distance, latitude, longitude); +} +/** + * @brief Searches for the next lunar eclipse in a series. + * + * After using {@link SearchLunarEclipse} to find the first lunar eclipse + * in a series, you can call this function to find the next consecutive lunar eclipse. + * Pass in the `peak` value from the {@link LunarEclipseInfo} returned by the + * previous call to `SearchLunarEclipse` or `NextLunarEclipse` + * to find the next lunar eclipse. + * + * @param {FlexibleDateTime} prevEclipseTime + * A date and time near a full moon. Lunar eclipse search will start at the next full moon. + * + * @returns {LunarEclipseInfo} + */ +function NextLunarEclipse(prevEclipseTime) { + prevEclipseTime = MakeTime(prevEclipseTime); + const startTime = prevEclipseTime.AddDays(10); + return SearchLunarEclipse(startTime); +} +exports.NextLunarEclipse = NextLunarEclipse; +/** + * @brief Searches for a solar eclipse visible anywhere on the Earth's surface. + * + * This function finds the first solar eclipse that occurs after `startTime`. + * A solar eclipse may be partial, annular, or total. + * See {@link GlobalSolarEclipseInfo} for more information. + * To find a series of solar eclipses, call this function once, + * then keep calling {@link NextGlobalSolarEclipse} as many times as desired, + * passing in the `peak` value returned from the previous call. + * + * @param {FlexibleDateTime} startTime + * The date and time for starting the search for a solar eclipse. + * + * @returns {GlobalSolarEclipseInfo} + */ +function SearchGlobalSolarEclipse(startTime) { + startTime = MakeTime(startTime); + const PruneLatitude = 1.8; // Moon's ecliptic latitude beyond which eclipse is impossible + // Iterate through consecutive new moons until we find a solar eclipse visible somewhere on Earth. + let nmtime = startTime; + let nmcount; + for (nmcount = 0; nmcount < 12; ++nmcount) { + // Search for the next new moon. Any eclipse will be near it. + const newmoon = SearchMoonPhase(0.0, nmtime, 40.0); + if (!newmoon) + throw 'Cannot find new moon'; + // Pruning: if the new moon's ecliptic latitude is too large, a solar eclipse is not possible. + const eclip_lat = MoonEclipticLatitudeDegrees(newmoon); + if (Math.abs(eclip_lat) < PruneLatitude) { + // Search near the new moon for the time when the center of the Earth + // is closest to the line passing through the centers of the Sun and Moon. + const shadow = PeakMoonShadow(newmoon); + if (shadow.r < shadow.p + EARTH_MEAN_RADIUS_KM) { + // This is at least a partial solar eclipse visible somewhere on Earth. + // Try to find an intersection between the shadow axis and the Earth's oblate geoid. + return GeoidIntersect(shadow); + } + } + // We didn't find an eclipse on this new moon, so search for the next one. + nmtime = newmoon.AddDays(10.0); + } + // Safety valve to prevent infinite loop. + // This should never happen, because at least 2 solar eclipses happen per year. + throw 'Failed to find solar eclipse within 12 full moons.'; +} +exports.SearchGlobalSolarEclipse = SearchGlobalSolarEclipse; +/** + * @brief Searches for the next global solar eclipse in a series. + * + * After using {@link SearchGlobalSolarEclipse} to find the first solar eclipse + * in a series, you can call this function to find the next consecutive solar eclipse. + * Pass in the `peak` value from the {@link GlobalSolarEclipseInfo} returned by the + * previous call to `SearchGlobalSolarEclipse` or `NextGlobalSolarEclipse` + * to find the next solar eclipse. + * + * @param {FlexibleDateTime} prevEclipseTime + * A date and time near a new moon. Solar eclipse search will start at the next new moon. + * + * @returns {GlobalSolarEclipseInfo} + */ +function NextGlobalSolarEclipse(prevEclipseTime) { + prevEclipseTime = MakeTime(prevEclipseTime); + const startTime = prevEclipseTime.AddDays(10.0); + return SearchGlobalSolarEclipse(startTime); +} +exports.NextGlobalSolarEclipse = NextGlobalSolarEclipse; +/** + * @brief Holds a time and the observed altitude of the Sun at that time. + * + * When reporting a solar eclipse observed at a specific location on the Earth + * (a "local" solar eclipse), a series of events occur. In addition + * to the time of each event, it is important to know the altitude of the Sun, + * because each event may be invisible to the observer if the Sun is below + * the horizon. + * + * If `altitude` is negative, the event is theoretical only; it would be + * visible if the Earth were transparent, but the observer cannot actually see it. + * If `altitude` is positive but less than a few degrees, visibility will be impaired by + * atmospheric interference (sunrise or sunset conditions). + * + * @property {AstroTime} time + * The date and time of the event. + * + * @property {number} altitude + * The angular altitude of the center of the Sun above/below the horizon, at `time`, + * corrected for atmospheric refraction and expressed in degrees. + */ +class EclipseEvent { + constructor(time, altitude) { + this.time = time; + this.altitude = altitude; + } +} +exports.EclipseEvent = EclipseEvent; +/** + * @brief Information about a solar eclipse as seen by an observer at a given time and geographic location. + * + * Returned by {@link SearchLocalSolarEclipse} or {@link NextLocalSolarEclipse} + * to report information about a solar eclipse as seen at a given geographic location. + * + * When a solar eclipse is found, it is classified by setting `kind` + * to `EclipseKind.Partial`, `EclipseKind.Annular`, or `EclipseKind.Total`. + * A partial solar eclipse is when the Moon does not line up directly enough with the Sun + * to completely block the Sun's light from reaching the observer. + * An annular eclipse occurs when the Moon's disc is completely visible against the Sun + * but the Moon is too far away to completely block the Sun's light; this leaves the + * Sun with a ring-like appearance. + * A total eclipse occurs when the Moon is close enough to the Earth and aligned with the + * Sun just right to completely block all sunlight from reaching the observer. + * + * The `obscuration` field reports what fraction of the Sun's disc appears blocked + * by the Moon when viewed by the observer at the peak eclipse time. + * This is a value that ranges from 0 (no blockage) to 1 (total eclipse). + * The obscuration value will be between 0 and 1 for partial eclipses and annular eclipses. + * The value will be exactly 1 for total eclipses. Obscuration gives an indication + * of how dark the eclipse appears. + * + * There are 5 "event" fields, each of which contains a time and a solar altitude. + * Field `peak` holds the date and time of the center of the eclipse, when it is at its peak. + * The fields `partial_begin` and `partial_end` are always set, and indicate when + * the eclipse begins/ends. If the eclipse reaches totality or becomes annular, + * `total_begin` and `total_end` indicate when the total/annular phase begins/ends. + * When an event field is valid, the caller must also check its `altitude` field to + * see whether the Sun is above the horizon at the time indicated by the `time` field. + * See {@link EclipseEvent} for more information. + * + * @property {EclipseKind} kind + * The type of solar eclipse found: `EclipseKind.Partial`, `EclipseKind.Annular`, or `EclipseKind.Total`. + * + * @property {number} obscuration + * The fraction of the Sun's apparent disc area obscured by the Moon at the eclipse peak. + * + * @property {EclipseEvent} partial_begin + * The time and Sun altitude at the beginning of the eclipse. + * + * @property {EclipseEvent | undefined} total_begin + * If this is an annular or a total eclipse, the time and Sun altitude when annular/total phase begins; otherwise undefined. + * + * @property {EclipseEvent} peak + * The time and Sun altitude when the eclipse reaches its peak. + * + * @property {EclipseEvent | undefined} total_end + * If this is an annular or a total eclipse, the time and Sun altitude when annular/total phase ends; otherwise undefined. + * + * @property {EclipseEvent} partial_end + * The time and Sun altitude at the end of the eclipse. + */ +class LocalSolarEclipseInfo { + constructor(kind, obscuration, partial_begin, total_begin, peak, total_end, partial_end) { + this.kind = kind; + this.obscuration = obscuration; + this.partial_begin = partial_begin; + this.total_begin = total_begin; + this.peak = peak; + this.total_end = total_end; + this.partial_end = partial_end; + } +} +exports.LocalSolarEclipseInfo = LocalSolarEclipseInfo; +function local_partial_distance(shadow) { + return shadow.p - shadow.r; +} +function local_total_distance(shadow) { + // Must take the absolute value of the umbra radius 'k' + // because it can be negative for an annular eclipse. + return Math.abs(shadow.k) - shadow.r; +} +function LocalEclipse(shadow, observer) { + const PARTIAL_WINDOW = 0.2; + const TOTAL_WINDOW = 0.01; + const peak = CalcEvent(observer, shadow.time); + let t1 = shadow.time.AddDays(-PARTIAL_WINDOW); + let t2 = shadow.time.AddDays(+PARTIAL_WINDOW); + const partial_begin = LocalEclipseTransition(observer, +1.0, local_partial_distance, t1, shadow.time); + const partial_end = LocalEclipseTransition(observer, -1.0, local_partial_distance, shadow.time, t2); + let total_begin; + let total_end; + let kind; + if (shadow.r < Math.abs(shadow.k)) { // take absolute value of 'k' to handle annular eclipses too. + t1 = shadow.time.AddDays(-TOTAL_WINDOW); + t2 = shadow.time.AddDays(+TOTAL_WINDOW); + total_begin = LocalEclipseTransition(observer, +1.0, local_total_distance, t1, shadow.time); + total_end = LocalEclipseTransition(observer, -1.0, local_total_distance, shadow.time, t2); + kind = EclipseKindFromUmbra(shadow.k); + } + else { + kind = EclipseKind.Partial; + } + const obscuration = (kind === EclipseKind.Total) ? 1.0 : SolarEclipseObscuration(shadow.dir, shadow.target); + return new LocalSolarEclipseInfo(kind, obscuration, partial_begin, total_begin, peak, total_end, partial_end); +} +function LocalEclipseTransition(observer, direction, func, t1, t2) { + function evaluate(time) { + const shadow = LocalMoonShadow(time, observer); + return direction * func(shadow); + } + const search = Search(evaluate, t1, t2); + if (!search) + throw "Local eclipse transition search failed."; + return CalcEvent(observer, search); +} +function CalcEvent(observer, time) { + const altitude = SunAltitude(time, observer); + return new EclipseEvent(time, altitude); +} +function SunAltitude(time, observer) { + const equ = Equator(Body.Sun, time, observer, true, true); + const hor = Horizon(time, observer, equ.ra, equ.dec, 'normal'); + return hor.altitude; +} +/** + * @brief Searches for a solar eclipse visible at a specific location on the Earth's surface. + * + * This function finds the first solar eclipse that occurs after `startTime`. + * A solar eclipse may be partial, annular, or total. + * See {@link LocalSolarEclipseInfo} for more information. + * + * To find a series of solar eclipses, call this function once, + * then keep calling {@link NextLocalSolarEclipse} as many times as desired, + * passing in the `peak` value returned from the previous call. + * + * IMPORTANT: An eclipse reported by this function might be partly or + * completely invisible to the observer due to the time of day. + * See {@link LocalSolarEclipseInfo} for more information about this topic. + * + * @param {FlexibleDateTime} startTime + * The date and time for starting the search for a solar eclipse. + * + * @param {Observer} observer + * The geographic location of the observer. + * + * @returns {LocalSolarEclipseInfo} + */ +function SearchLocalSolarEclipse(startTime, observer) { + startTime = MakeTime(startTime); + VerifyObserver(observer); + const PruneLatitude = 1.8; /* Moon's ecliptic latitude beyond which eclipse is impossible */ + /* Iterate through consecutive new moons until we find a solar eclipse visible somewhere on Earth. */ + let nmtime = startTime; + for (;;) { + /* Search for the next new moon. Any eclipse will be near it. */ + const newmoon = SearchMoonPhase(0.0, nmtime, 40.0); + if (!newmoon) + throw 'Cannot find next new moon'; + /* Pruning: if the new moon's ecliptic latitude is too large, a solar eclipse is not possible. */ + const eclip_lat = MoonEclipticLatitudeDegrees(newmoon); + if (Math.abs(eclip_lat) < PruneLatitude) { + /* Search near the new moon for the time when the observer */ + /* is closest to the line passing through the centers of the Sun and Moon. */ + const shadow = PeakLocalMoonShadow(newmoon, observer); + if (shadow.r < shadow.p) { + /* This is at least a partial solar eclipse for the observer. */ + const eclipse = LocalEclipse(shadow, observer); + /* Ignore any eclipse that happens completely at night. */ + /* More precisely, the center of the Sun must be above the horizon */ + /* at the beginning or the end of the eclipse, or we skip the event. */ + if (eclipse.partial_begin.altitude > 0.0 || eclipse.partial_end.altitude > 0.0) + return eclipse; + } + } + /* We didn't find an eclipse on this new moon, so search for the next one. */ + nmtime = newmoon.AddDays(10.0); + } +} +exports.SearchLocalSolarEclipse = SearchLocalSolarEclipse; +/** + * @brief Searches for the next local solar eclipse in a series. + * + * After using {@link SearchLocalSolarEclipse} to find the first solar eclipse + * in a series, you can call this function to find the next consecutive solar eclipse. + * Pass in the `peak` value from the {@link LocalSolarEclipseInfo} returned by the + * previous call to `SearchLocalSolarEclipse` or `NextLocalSolarEclipse` + * to find the next solar eclipse. + * This function finds the first solar eclipse that occurs after `startTime`. + * A solar eclipse may be partial, annular, or total. + * See {@link LocalSolarEclipseInfo} for more information. + * + * @param {FlexibleDateTime} prevEclipseTime + * The date and time for starting the search for a solar eclipse. + * + * @param {Observer} observer + * The geographic location of the observer. + * + * @returns {LocalSolarEclipseInfo} + */ +function NextLocalSolarEclipse(prevEclipseTime, observer) { + prevEclipseTime = MakeTime(prevEclipseTime); + const startTime = prevEclipseTime.AddDays(10.0); + return SearchLocalSolarEclipse(startTime, observer); +} +exports.NextLocalSolarEclipse = NextLocalSolarEclipse; +/** + * @brief Information about a transit of Mercury or Venus, as seen from the Earth. + * + * Returned by {@link SearchTransit} or {@link NextTransit} to report + * information about a transit of Mercury or Venus. + * A transit is when Mercury or Venus passes between the Sun and Earth so that + * the other planet is seen in silhouette against the Sun. + * + * The calculations are performed from the point of view of a geocentric observer. + * + * @property {AstroTime} start + * The date and time at the beginning of the transit. + * This is the moment the planet first becomes visible against the Sun in its background. + * + * @property {AstroTime} peak + * When the planet is most aligned with the Sun, as seen from the Earth. + * + * @property {AstroTime} finish + * The date and time at the end of the transit. + * This is the moment the planet is last seen against the Sun in its background. + * + * @property {number} separation + * The minimum angular separation, in arcminutes, between the centers of the Sun and the planet. + * This angle pertains to the time stored in `peak`. + */ +class TransitInfo { + constructor(start, peak, finish, separation) { + this.start = start; + this.peak = peak; + this.finish = finish; + this.separation = separation; + } +} +exports.TransitInfo = TransitInfo; +function PlanetShadowBoundary(time, body, planet_radius_km, direction) { + const shadow = PlanetShadow(body, planet_radius_km, time); + return direction * (shadow.r - shadow.p); +} +function PlanetTransitBoundary(body, planet_radius_km, t1, t2, direction) { + // Search for the time the planet's penumbra begins/ends making contact with the center of the Earth. + const tx = Search((time) => PlanetShadowBoundary(time, body, planet_radius_km, direction), t1, t2); + if (!tx) + throw 'Planet transit boundary search failed'; + return tx; +} +/** + * @brief Searches for the first transit of Mercury or Venus after a given date. + * + * Finds the first transit of Mercury or Venus after a specified date. + * A transit is when an inferior planet passes between the Sun and the Earth + * so that the silhouette of the planet is visible against the Sun in the background. + * To continue the search, pass the `finish` time in the returned structure to + * {@link NextTransit}. + * + * @param {Body} body + * The planet whose transit is to be found. Must be `Body.Mercury` or `Body.Venus`. + * + * @param {FlexibleDateTime} startTime + * The date and time for starting the search for a transit. + * + * @returns {TransitInfo} + */ +function SearchTransit(body, startTime) { + startTime = MakeTime(startTime); + const threshold_angle = 0.4; // maximum angular separation to attempt transit calculation + const dt_days = 1.0; + // Validate the planet and find its mean radius. + let planet_radius_km; + switch (body) { + case Body.Mercury: + planet_radius_km = 2439.7; + break; + case Body.Venus: + planet_radius_km = 6051.8; + break; + default: + throw `Invalid body: ${body}`; + } + let search_time = startTime; + for (;;) { + // Search for the next inferior conjunction of the given planet. + // This is the next time the Earth and the other planet have the same + // ecliptic longitude as seen from the Sun. + const conj = SearchRelativeLongitude(body, 0.0, search_time); + // Calculate the angular separation between the body and the Sun at this time. + const conj_separation = AngleFromSun(body, conj); + if (conj_separation < threshold_angle) { + // The planet's angular separation from the Sun is small enough + // to consider it a transit candidate. + // Search for the moment when the line passing through the Sun + // and planet are closest to the Earth's center. + const shadow = PeakPlanetShadow(body, planet_radius_km, conj); + if (shadow.r < shadow.p) { // does the planet's penumbra touch the Earth's center? + // Find the beginning and end of the penumbral contact. + const time_before = shadow.time.AddDays(-dt_days); + const start = PlanetTransitBoundary(body, planet_radius_km, time_before, shadow.time, -1.0); + const time_after = shadow.time.AddDays(+dt_days); + const finish = PlanetTransitBoundary(body, planet_radius_km, shadow.time, time_after, +1.0); + const min_separation = 60.0 * AngleFromSun(body, shadow.time); + return new TransitInfo(start, shadow.time, finish, min_separation); + } + } + // This inferior conjunction was not a transit. Try the next inferior conjunction. + search_time = conj.AddDays(10.0); + } +} +exports.SearchTransit = SearchTransit; +/** + * @brief Searches for the next transit of Mercury or Venus in a series. + * + * After calling {@link SearchTransit} to find a transit of Mercury or Venus, + * this function finds the next transit after that. + * Keep calling this function as many times as you want to keep finding more transits. + * + * @param {Body} body + * The planet whose transit is to be found. Must be `Body.Mercury` or `Body.Venus`. + * + * @param {FlexibleDateTime} prevTransitTime + * A date and time near the previous transit. + * + * @returns {TransitInfo} + */ +function NextTransit(body, prevTransitTime) { + prevTransitTime = MakeTime(prevTransitTime); + const startTime = prevTransitTime.AddDays(100.0); + return SearchTransit(body, startTime); +} +exports.NextTransit = NextTransit; +/** + * @brief Indicates whether a crossing through the ecliptic plane is ascending or descending. + * + * `Invalid` is a placeholder for an unknown or missing node. + * `Ascending` indicates a body passing through the ecliptic plane from south to north. + * `Descending` indicates a body passing through the ecliptic plane from north to south. + * + * @enum {number} + */ +var NodeEventKind; +(function (NodeEventKind) { + NodeEventKind[NodeEventKind["Invalid"] = 0] = "Invalid"; + NodeEventKind[NodeEventKind["Ascending"] = 1] = "Ascending"; + NodeEventKind[NodeEventKind["Descending"] = -1] = "Descending"; +})(NodeEventKind = exports.NodeEventKind || (exports.NodeEventKind = {})); +/** + * @brief Information about an ascending or descending node of a body. + * + * This object is returned by {@link SearchMoonNode} and {@link NextMoonNode} + * to report information about the center of the Moon passing through the ecliptic plane. + * + * @property {NodeEventKind} kind Whether the node is ascending (south to north) or descending (north to south). + * @property {AstroTime} time The time when the body passes through the ecliptic plane. + */ +class NodeEventInfo { + constructor(kind, time) { + this.kind = kind; + this.time = time; + } +} +exports.NodeEventInfo = NodeEventInfo; +const MoonNodeStepDays = +10.0; // a safe number of days to step without missing a Moon node +/** + * @brief Searches for a time when the Moon's center crosses through the ecliptic plane. + * + * Searches for the first ascending or descending node of the Moon after `startTime`. + * An ascending node is when the Moon's center passes through the ecliptic plane + * (the plane of the Earth's orbit around the Sun) from south to north. + * A descending node is when the Moon's center passes through the ecliptic plane + * from north to south. Nodes indicate possible times of solar or lunar eclipses, + * if the Moon also happens to be in the correct phase (new or full, respectively). + * Call `SearchMoonNode` to find the first of a series of nodes. + * Then call {@link NextMoonNode} to find as many more consecutive nodes as desired. + * + * @param {FlexibleDateTime} startTime + * The date and time for starting the search for an ascending or descending node of the Moon. + * + * @returns {NodeEventInfo} + */ +function SearchMoonNode(startTime) { + // Start at the given moment in time and sample the Moon's ecliptic latitude. + // Step 10 days at a time, searching for an interval where that latitude crosses zero. + let time1 = MakeTime(startTime); + let eclip1 = EclipticGeoMoon(time1); + for (;;) { + const time2 = time1.AddDays(MoonNodeStepDays); + const eclip2 = EclipticGeoMoon(time2); + if (eclip1.lat * eclip2.lat <= 0.0) { + // There is a node somewhere inside this closed time interval. + // Figure out whether it is an ascending node or a descending node. + const kind = (eclip2.lat > eclip1.lat) ? NodeEventKind.Ascending : NodeEventKind.Descending; + const result = Search(t => kind * EclipticGeoMoon(t).lat, time1, time2); + if (!result) + throw `Could not find moon node.`; // should never happen + return new NodeEventInfo(kind, result); + } + time1 = time2; + eclip1 = eclip2; + } +} +exports.SearchMoonNode = SearchMoonNode; +/** + * @brief Searches for the next time when the Moon's center crosses through the ecliptic plane. + * + * Call {@link SearchMoonNode} to find the first of a series of nodes. + * Then call `NextMoonNode` to find as many more consecutive nodes as desired. + * + * @param {NodeEventInfo} prevNode + * The previous node found from calling {@link SearchMoonNode} or `NextMoonNode`. + * + * @returns {NodeEventInfo} + */ +function NextMoonNode(prevNode) { + const time = prevNode.time.AddDays(MoonNodeStepDays); + const node = SearchMoonNode(time); + switch (prevNode.kind) { + case NodeEventKind.Ascending: + if (node.kind !== NodeEventKind.Descending) + throw `Internal error: previous node was ascending, but this node was: ${node.kind}`; + break; + case NodeEventKind.Descending: + if (node.kind !== NodeEventKind.Ascending) + throw `Internal error: previous node was descending, but this node was: ${node.kind}`; + break; + default: + throw `Previous node has an invalid node kind: ${prevNode.kind}`; + } + return node; +} +exports.NextMoonNode = NextMoonNode; +/** + * @brief Information about a body's rotation axis at a given time. + * + * This structure is returned by {@link RotationAxis} to report + * the orientation of a body's rotation axis at a given moment in time. + * The axis is specified by the direction in space that the body's north pole + * points, using angular equatorial coordinates in the J2000 system (EQJ). + * + * Thus `ra` is the right ascension, and `dec` is the declination, of the + * body's north pole vector at the given moment in time. The north pole + * of a body is defined as the pole that lies on the north side of the + * [Solar System's invariable plane](https://en.wikipedia.org/wiki/Invariable_plane), + * regardless of the body's direction of rotation. + * + * The `spin` field indicates the angular position of a prime meridian + * arbitrarily recommended for the body by the International Astronomical + * Union (IAU). + * + * The fields `ra`, `dec`, and `spin` correspond to the variables + * α0, δ0, and W, respectively, from + * [Report of the IAU Working Group on Cartographic Coordinates and Rotational Elements: 2015](https://astropedia.astrogeology.usgs.gov/download/Docs/WGCCRE/WGCCRE2015reprint.pdf). + * The field `north` is a unit vector pointing in the direction of the body's north pole. + * It is expressed in the J2000 mean equator system (EQJ). + * + * @property {number} ra + * The J2000 right ascension of the body's north pole direction, in sidereal hours. + * + * @property {number} dec + * The J2000 declination of the body's north pole direction, in degrees. + * + * @property {number} spin + * Rotation angle of the body's prime meridian, in degrees. + * + * @property {Vector} north + * A J2000 dimensionless unit vector pointing in the direction of the body's north pole. + */ +class AxisInfo { + constructor(ra, dec, spin, north) { + this.ra = ra; + this.dec = dec; + this.spin = spin; + this.north = north; + } +} +exports.AxisInfo = AxisInfo; +function EarthRotationAxis(time) { + // Unlike the other planets, we have a model of precession and nutation + // for the Earth's axis that provides a north pole vector. + // So calculate the vector first, then derive the (RA,DEC) angles from the vector. + // Start with a north pole vector in equator-of-date coordinates: (0,0,1). + // Convert the vector into J2000 coordinates. + const pos2 = nutation([0, 0, 1], time, PrecessDirection.Into2000); + const nvec = precession(pos2, time, PrecessDirection.Into2000); + const north = new Vector(nvec[0], nvec[1], nvec[2], time); + // Derive angular values: right ascension and declination. + const equ = EquatorFromVector(north); + // Use a modified version of the era() function that does not trim to 0..360 degrees. + // This expression is also corrected to give the correct angle at the J2000 epoch. + const spin = 190.41375788700253 + (360.9856122880876 * time.ut); + return new AxisInfo(equ.ra, equ.dec, spin, north); +} +/** + * @brief Calculates information about a body's rotation axis at a given time. + * Calculates the orientation of a body's rotation axis, along with + * the rotation angle of its prime meridian, at a given moment in time. + * + * This function uses formulas standardized by the IAU Working Group + * on Cartographics and Rotational Elements 2015 report, as described + * in the following document: + * + * https://astropedia.astrogeology.usgs.gov/download/Docs/WGCCRE/WGCCRE2015reprint.pdf + * + * See {@link AxisInfo} for more detailed information. + * + * @param {Body} body + * One of the following values: + * `Body.Sun`, `Body.Moon`, `Body.Mercury`, `Body.Venus`, `Body.Earth`, `Body.Mars`, + * `Body.Jupiter`, `Body.Saturn`, `Body.Uranus`, `Body.Neptune`, `Body.Pluto`. + * + * @param {FlexibleDateTime} date + * The time at which to calculate the body's rotation axis. + * + * @returns {AxisInfo} + */ +function RotationAxis(body, date) { + const time = MakeTime(date); + const d = time.tt; + const T = d / 36525.0; + let ra, dec, w; + switch (body) { + case Body.Sun: + ra = 286.13; + dec = 63.87; + w = 84.176 + (14.1844 * d); + break; + case Body.Mercury: + ra = 281.0103 - (0.0328 * T); + dec = 61.4155 - (0.0049 * T); + w = (329.5988 + + (6.1385108 * d) + + (0.01067257 * Math.sin(exports.DEG2RAD * (174.7910857 + 4.092335 * d))) + - (0.00112309 * Math.sin(exports.DEG2RAD * (349.5821714 + 8.184670 * d))) + - (0.00011040 * Math.sin(exports.DEG2RAD * (164.3732571 + 12.277005 * d))) + - (0.00002539 * Math.sin(exports.DEG2RAD * (339.1643429 + 16.369340 * d))) + - (0.00000571 * Math.sin(exports.DEG2RAD * (153.9554286 + 20.461675 * d)))); + break; + case Body.Venus: + ra = 272.76; + dec = 67.16; + w = 160.20 - (1.4813688 * d); + break; + case Body.Earth: + return EarthRotationAxis(time); + case Body.Moon: + // See page 8, Table 2 in: + // https://astropedia.astrogeology.usgs.gov/alfresco/d/d/workspace/SpacesStore/28fd9e81-1964-44d6-a58b-fbbf61e64e15/WGCCRE2009reprint.pdf + const E1 = exports.DEG2RAD * (125.045 - 0.0529921 * d); + const E2 = exports.DEG2RAD * (250.089 - 0.1059842 * d); + const E3 = exports.DEG2RAD * (260.008 + 13.0120009 * d); + const E4 = exports.DEG2RAD * (176.625 + 13.3407154 * d); + const E5 = exports.DEG2RAD * (357.529 + 0.9856003 * d); + const E6 = exports.DEG2RAD * (311.589 + 26.4057084 * d); + const E7 = exports.DEG2RAD * (134.963 + 13.0649930 * d); + const E8 = exports.DEG2RAD * (276.617 + 0.3287146 * d); + const E9 = exports.DEG2RAD * (34.226 + 1.7484877 * d); + const E10 = exports.DEG2RAD * (15.134 - 0.1589763 * d); + const E11 = exports.DEG2RAD * (119.743 + 0.0036096 * d); + const E12 = exports.DEG2RAD * (239.961 + 0.1643573 * d); + const E13 = exports.DEG2RAD * (25.053 + 12.9590088 * d); + ra = (269.9949 + 0.0031 * T + - 3.8787 * Math.sin(E1) + - 0.1204 * Math.sin(E2) + + 0.0700 * Math.sin(E3) + - 0.0172 * Math.sin(E4) + + 0.0072 * Math.sin(E6) + - 0.0052 * Math.sin(E10) + + 0.0043 * Math.sin(E13)); + dec = (66.5392 + 0.0130 * T + + 1.5419 * Math.cos(E1) + + 0.0239 * Math.cos(E2) + - 0.0278 * Math.cos(E3) + + 0.0068 * Math.cos(E4) + - 0.0029 * Math.cos(E6) + + 0.0009 * Math.cos(E7) + + 0.0008 * Math.cos(E10) + - 0.0009 * Math.cos(E13)); + w = (38.3213 + (13.17635815 - 1.4e-12 * d) * d + + 3.5610 * Math.sin(E1) + + 0.1208 * Math.sin(E2) + - 0.0642 * Math.sin(E3) + + 0.0158 * Math.sin(E4) + + 0.0252 * Math.sin(E5) + - 0.0066 * Math.sin(E6) + - 0.0047 * Math.sin(E7) + - 0.0046 * Math.sin(E8) + + 0.0028 * Math.sin(E9) + + 0.0052 * Math.sin(E10) + + 0.0040 * Math.sin(E11) + + 0.0019 * Math.sin(E12) + - 0.0044 * Math.sin(E13)); + break; + case Body.Mars: + ra = (317.269202 - 0.10927547 * T + + 0.000068 * Math.sin(exports.DEG2RAD * (198.991226 + 19139.4819985 * T)) + + 0.000238 * Math.sin(exports.DEG2RAD * (226.292679 + 38280.8511281 * T)) + + 0.000052 * Math.sin(exports.DEG2RAD * (249.663391 + 57420.7251593 * T)) + + 0.000009 * Math.sin(exports.DEG2RAD * (266.183510 + 76560.6367950 * T)) + + 0.419057 * Math.sin(exports.DEG2RAD * (79.398797 + 0.5042615 * T))); + dec = (54.432516 - 0.05827105 * T + + 0.000051 * Math.cos(exports.DEG2RAD * (122.433576 + 19139.9407476 * T)) + + 0.000141 * Math.cos(exports.DEG2RAD * (43.058401 + 38280.8753272 * T)) + + 0.000031 * Math.cos(exports.DEG2RAD * (57.663379 + 57420.7517205 * T)) + + 0.000005 * Math.cos(exports.DEG2RAD * (79.476401 + 76560.6495004 * T)) + + 1.591274 * Math.cos(exports.DEG2RAD * (166.325722 + 0.5042615 * T))); + w = (176.049863 + 350.891982443297 * d + + 0.000145 * Math.sin(exports.DEG2RAD * (129.071773 + 19140.0328244 * T)) + + 0.000157 * Math.sin(exports.DEG2RAD * (36.352167 + 38281.0473591 * T)) + + 0.000040 * Math.sin(exports.DEG2RAD * (56.668646 + 57420.9295360 * T)) + + 0.000001 * Math.sin(exports.DEG2RAD * (67.364003 + 76560.2552215 * T)) + + 0.000001 * Math.sin(exports.DEG2RAD * (104.792680 + 95700.4387578 * T)) + + 0.584542 * Math.sin(exports.DEG2RAD * (95.391654 + 0.5042615 * T))); + break; + case Body.Jupiter: + const Ja = exports.DEG2RAD * (99.360714 + 4850.4046 * T); + const Jb = exports.DEG2RAD * (175.895369 + 1191.9605 * T); + const Jc = exports.DEG2RAD * (300.323162 + 262.5475 * T); + const Jd = exports.DEG2RAD * (114.012305 + 6070.2476 * T); + const Je = exports.DEG2RAD * (49.511251 + 64.3000 * T); + ra = (268.056595 - 0.006499 * T + + 0.000117 * Math.sin(Ja) + + 0.000938 * Math.sin(Jb) + + 0.001432 * Math.sin(Jc) + + 0.000030 * Math.sin(Jd) + + 0.002150 * Math.sin(Je)); + dec = (64.495303 + 0.002413 * T + + 0.000050 * Math.cos(Ja) + + 0.000404 * Math.cos(Jb) + + 0.000617 * Math.cos(Jc) + - 0.000013 * Math.cos(Jd) + + 0.000926 * Math.cos(Je)); + w = 284.95 + 870.536 * d; + break; + case Body.Saturn: + ra = 40.589 - 0.036 * T; + dec = 83.537 - 0.004 * T; + w = 38.90 + 810.7939024 * d; + break; + case Body.Uranus: + ra = 257.311; + dec = -15.175; + w = 203.81 - 501.1600928 * d; + break; + case Body.Neptune: + const N = exports.DEG2RAD * (357.85 + 52.316 * T); + ra = 299.36 + 0.70 * Math.sin(N); + dec = 43.46 - 0.51 * Math.cos(N); + w = 249.978 + 541.1397757 * d - 0.48 * Math.sin(N); + break; + case Body.Pluto: + ra = 132.993; + dec = -6.163; + w = 302.695 + 56.3625225 * d; + break; + default: + throw `Invalid body: ${body}`; + } + // Calculate the north pole vector using the given angles. + const radlat = dec * exports.DEG2RAD; + const radlon = ra * exports.DEG2RAD; + const rcoslat = Math.cos(radlat); + const north = new Vector(rcoslat * Math.cos(radlon), rcoslat * Math.sin(radlon), Math.sin(radlat), time); + return new AxisInfo(ra / 15, dec, w, north); +} +exports.RotationAxis = RotationAxis; +/** + * @brief Calculates one of the 5 Lagrange points for a pair of co-orbiting bodies. + * + * Given a more massive "major" body and a much less massive "minor" body, + * calculates one of the five Lagrange points in relation to the minor body's + * orbit around the major body. The parameter `point` is an integer that + * selects the Lagrange point as follows: + * + * 1 = the Lagrange point between the major body and minor body. + * 2 = the Lagrange point on the far side of the minor body. + * 3 = the Lagrange point on the far side of the major body. + * 4 = the Lagrange point 60 degrees ahead of the minor body's orbital position. + * 5 = the Lagrange point 60 degrees behind the minor body's orbital position. + * + * The function returns the state vector for the selected Lagrange point + * in J2000 mean equator coordinates (EQJ), with respect to the center of the + * major body. + * + * To calculate Sun/Earth Lagrange points, pass in `Body.Sun` for `major_body` + * and `Body.EMB` (Earth/Moon barycenter) for `minor_body`. + * For Lagrange points of the Sun and any other planet, pass in that planet + * (e.g. `Body.Jupiter`) for `minor_body`. + * To calculate Earth/Moon Lagrange points, pass in `Body.Earth` and `Body.Moon` + * for the major and minor bodies respectively. + * + * In some cases, it may be more efficient to call {@link LagrangePointFast}, + * especially when the state vectors have already been calculated, or are needed + * for some other purpose. + * + * @param {number} point + * An integer 1..5 that selects which of the Lagrange points to calculate. + * + * @param {FlexibleDateTime} date + * The time at which the Lagrange point is to be calculated. + * + * @param {Body} major_body + * The more massive of the co-orbiting bodies: `Body.Sun` or `Body.Earth`. + * + * @param {Body} minor_body + * The less massive of the co-orbiting bodies. See main remarks. + * + * @returns {StateVector} + * The position and velocity of the selected Lagrange point with respect to the major body's center. + */ +function LagrangePoint(point, date, major_body, minor_body) { + const time = MakeTime(date); + const major_mass = MassProduct(major_body); + const minor_mass = MassProduct(minor_body); + let major_state; + let minor_state; + // Calculate the state vectors for the major and minor bodies. + if (major_body === Body.Earth && minor_body === Body.Moon) { + // Use geocentric calculations for more precision. + // The Earth's geocentric state is trivial. + major_state = new StateVector(0, 0, 0, 0, 0, 0, time); + minor_state = GeoMoonState(time); + } + else { + major_state = HelioState(major_body, time); + minor_state = HelioState(minor_body, time); + } + return LagrangePointFast(point, major_state, major_mass, minor_state, minor_mass); +} +exports.LagrangePoint = LagrangePoint; +/** + * @brief Calculates one of the 5 Lagrange points from body masses and state vectors. + * + * Given a more massive "major" body and a much less massive "minor" body, + * calculates one of the five Lagrange points in relation to the minor body's + * orbit around the major body. The parameter `point` is an integer that + * selects the Lagrange point as follows: + * + * 1 = the Lagrange point between the major body and minor body. + * 2 = the Lagrange point on the far side of the minor body. + * 3 = the Lagrange point on the far side of the major body. + * 4 = the Lagrange point 60 degrees ahead of the minor body's orbital position. + * 5 = the Lagrange point 60 degrees behind the minor body's orbital position. + * + * The caller passes in the state vector and mass for both bodies. + * The state vectors can be in any orientation and frame of reference. + * The body masses are expressed as GM products, where G = the universal + * gravitation constant and M = the body's mass. Thus the units for + * `major_mass` and `minor_mass` must be au^3/day^2. + * Use {@link MassProduct} to obtain GM values for various solar system bodies. + * + * The function returns the state vector for the selected Lagrange point + * using the same orientation as the state vector parameters `major_state` and `minor_state`, + * and the position and velocity components are with respect to the major body's center. + * + * Consider calling {@link LagrangePoint}, instead of this function, for simpler usage in most cases. + * + * @param {number} point + * A value 1..5 that selects which of the Lagrange points to calculate. + * + * @param {StateVector} major_state + * The state vector of the major (more massive) of the pair of bodies. + * + * @param {number} major_mass + * The mass product GM of the major body. + * + * @param {StateVector} minor_state + * The state vector of the minor (less massive) of the pair of bodies. + * + * @param {number} minor_mass + * The mass product GM of the minor body. + * + * @returns {StateVector} + * The position and velocity of the selected Lagrange point with respect to the major body's center. + */ +function LagrangePointFast(point, major_state, major_mass, minor_state, minor_mass) { + const cos_60 = 0.5; + const sin_60 = 0.8660254037844386; /* sqrt(3) / 2 */ + if (point < 1 || point > 5) + throw `Invalid lagrange point ${point}`; + if (!Number.isFinite(major_mass) || major_mass <= 0.0) + throw 'Major mass must be a positive number.'; + if (!Number.isFinite(minor_mass) || minor_mass <= 0.0) + throw 'Minor mass must be a negative number.'; + // Find the relative position vector . + let dx = minor_state.x - major_state.x; + let dy = minor_state.y - major_state.y; + let dz = minor_state.z - major_state.z; + const R2 = (dx * dx + dy * dy + dz * dz); + // R = Total distance between the bodies. + const R = Math.sqrt(R2); + // Find the relative velocity vector . + const vx = minor_state.vx - major_state.vx; + const vy = minor_state.vy - major_state.vy; + const vz = minor_state.vz - major_state.vz; + let p; + if (point === 4 || point === 5) { + // For L4 and L5, we need to find points 60 degrees away from the + // line connecting the two bodies and in the instantaneous orbital plane. + // Define the instantaneous orbital plane as the unique plane that contains + // both the relative position vector and the relative velocity vector. + // Take the cross product of position and velocity to find a normal vector . + const nx = dy * vz - dz * vy; + const ny = dz * vx - dx * vz; + const nz = dx * vy - dy * vx; + // Take the cross product normal*position to get a tangential vector . + let ux = ny * dz - nz * dy; + let uy = nz * dx - nx * dz; + let uz = nx * dy - ny * dx; + // Convert the tangential direction vector to a unit vector. + const U = Math.sqrt(ux * ux + uy * uy + uz * uz); + ux /= U; + uy /= U; + uz /= U; + // Convert the relative position vector into a unit vector. + dx /= R; + dy /= R; + dz /= R; + // Now we have two perpendicular unit vectors in the orbital plane: 'd' and 'u'. + // Create new unit vectors rotated (+/-)60 degrees from the radius/tangent directions. + const vert = (point == 4) ? +sin_60 : -sin_60; + // Rotated radial vector + const Dx = cos_60 * dx + vert * ux; + const Dy = cos_60 * dy + vert * uy; + const Dz = cos_60 * dz + vert * uz; + // Rotated tangent vector + const Ux = cos_60 * ux - vert * dx; + const Uy = cos_60 * uy - vert * dy; + const Uz = cos_60 * uz - vert * dz; + // Calculate L4/L5 positions relative to the major body. + const px = R * Dx; + const py = R * Dy; + const pz = R * Dz; + // Use dot products to find radial and tangential components of the relative velocity. + const vrad = vx * dx + vy * dy + vz * dz; + const vtan = vx * ux + vy * uy + vz * uz; + // Calculate L4/L5 velocities. + const pvx = vrad * Dx + vtan * Ux; + const pvy = vrad * Dy + vtan * Uy; + const pvz = vrad * Dz + vtan * Uz; + p = new StateVector(px, py, pz, pvx, pvy, pvz, major_state.t); + } + else { + // Calculate the distances of each body from their mutual barycenter. + // r1 = negative distance of major mass from barycenter (e.g. Sun to the left of barycenter) + // r2 = positive distance of minor mass from barycenter (e.g. Earth to the right of barycenter) + const r1 = -R * (minor_mass / (major_mass + minor_mass)); + const r2 = +R * (major_mass / (major_mass + minor_mass)); + // Calculate the square of the angular orbital speed in [rad^2 / day^2]. + const omega2 = (major_mass + minor_mass) / (R2 * R); + // Use Newton's Method to numerically solve for the location where + // outward centrifugal acceleration in the rotating frame of reference + // is equal to net inward gravitational acceleration. + // First derive a good initial guess based on approximate analysis. + let scale, numer1, numer2; + if (point === 1 || point === 2) { + scale = (major_mass / (major_mass + minor_mass)) * Math.cbrt(minor_mass / (3.0 * major_mass)); + numer1 = -major_mass; // The major mass is to the left of L1 and L2. + if (point == 1) { + scale = 1.0 - scale; + numer2 = +minor_mass; // The minor mass is to the right of L1. + } + else { + scale = 1.0 + scale; + numer2 = -minor_mass; // The minor mass is to the left of L2. + } + } + else if (point === 3) { + scale = ((7.0 / 12.0) * minor_mass - major_mass) / (minor_mass + major_mass); + numer1 = +major_mass; // major mass is to the right of L3. + numer2 = +minor_mass; // minor mass is to the right of L3. + } + else { + throw `Invalid Langrage point ${point}. Must be an integer 1..5.`; + } + // Iterate Newton's Method until it converges. + let x = R * scale - r1; + let deltax; + do { + const dr1 = x - r1; + const dr2 = x - r2; + const accel = omega2 * x + numer1 / (dr1 * dr1) + numer2 / (dr2 * dr2); + const deriv = omega2 - 2 * numer1 / (dr1 * dr1 * dr1) - 2 * numer2 / (dr2 * dr2 * dr2); + deltax = accel / deriv; + x -= deltax; + } while (Math.abs(deltax / R) > 1.0e-14); + scale = (x - r1) / R; + p = new StateVector(scale * dx, scale * dy, scale * dz, scale * vx, scale * vy, scale * vz, major_state.t); + } + return p; +} +exports.LagrangePointFast = LagrangePointFast; +/** + * @brief A simulation of zero or more small bodies moving through the Solar System. + * + * This class calculates the movement of arbitrary small bodies, + * such as asteroids or comets, that move through the Solar System. + * It does so by calculating the gravitational forces on the small bodies + * from the Sun and planets. The user of this class supplies a + * list of initial positions and velocities for the small bodies. + * Then the class can update the positions and velocities over small + * time steps. + */ +class GravitySimulator { + /** + * @brief Creates a gravity simulation object. + * + * @param {Body} originBody + * Specifies the origin of the reference frame. + * All position vectors and velocity vectors will use `originBody` + * as the origin of the coordinate system. + * This origin applies to all the input vectors provided in the + * `bodyStates` parameter of this function, along with all + * output vectors returned by {@link GravitySimulator#Update}. + * Most callers will want to provide one of the following: + * `Body.Sun` for heliocentric coordinates, + * `Body.SSB` for solar system barycentric coordinates, + * or `Body.Earth` for geocentric coordinates. Note that the + * gravity simulator does not correct for light travel time; + * all state vectors are tied to a Newtonian "instantaneous" time. + * + * @param {FlexibleDateTime} date + * The initial time at which to start the simulation. + * + * @param {StateVector[]} bodyStates + * An array of zero or more initial state vectors (positions and velocities) + * of the small bodies to be simulated. + * The caller must know the positions and velocities of the small bodies at an initial moment in time. + * Their positions and velocities are expressed with respect to `originBody`, using equatorial + * J2000 orientation (EQJ). + * Positions are expressed in astronomical units (AU). + * Velocities are expressed in AU/day. + * All the times embedded within the state vectors must exactly match `date`, + * or this constructor will throw an exception. + */ + constructor(originBody, date, bodyStates) { + const time = MakeTime(date); + this.originBody = originBody; + // Verify that the state vectors have matching times. + for (let b of bodyStates) { + if (b.t.tt !== time.tt) { + throw 'Inconsistent times in bodyStates'; + } + } + // Create a stub list that we append to later. + // We just need the stub to put into `this.curr`. + const smallBodyList = []; + // Calculate the states of the Sun and planets. + const largeBodyDict = GravitySimulator.CalcSolarSystem(time); + this.curr = new GravSimEndpoint(time, largeBodyDict, smallBodyList); + // Convert origin-centric bodyStates vectors into barycentric body_grav_calc_t array. + const o = this.InternalBodyState(originBody); + for (let b of bodyStates) { + const r = new TerseVector(b.x + o.r.x, b.y + o.r.y, b.z + o.r.z); + const v = new TerseVector(b.vx + o.v.x, b.vy + o.v.y, b.vz + o.v.z); + const a = TerseVector.zero(); + smallBodyList.push(new body_grav_calc_t(time.tt, r, v, a)); + } + // Calculate the net acceleration experienced by the small bodies. + this.CalcBodyAccelerations(); + // To prepare for a possible swap operation, duplicate the current state into the previous state. + this.prev = this.Duplicate(); + } + /** + * @brief The body that was selected as the coordinate origin when this simulator was created. + */ + get OriginBody() { + return this.originBody; + } + /** + * @brief The time represented by the current step of the gravity simulation. + */ + get Time() { + return this.curr.time; + } + /** + * Advances the gravity simulation by a small time step. + * + * Updates the simulation of the user-supplied small bodies + * to the time indicated by the `date` parameter. + * Returns an array of state vectors for the simulated bodies. + * The array is in the same order as the original array that + * was used to construct this simulator object. + * The positions and velocities in the returned array are + * referenced to the `originBody` that was used to construct + * this simulator. + * + * @param {FlexibleDateTime} date + * A time that is a small increment away from the current simulation time. + * It is up to the developer to figure out an appropriate time increment. + * Depending on the trajectories, a smaller or larger increment + * may be needed for the desired accuracy. Some experimentation may be needed. + * Generally, bodies that stay in the outer Solar System and move slowly can + * use larger time steps. Bodies that pass into the inner Solar System and + * move faster will need a smaller time step to maintain accuracy. + * The `date` value may be after or before the current simulation time + * to move forward or backward in time. + * + * @return {StateVector[]} + * An array of state vectors, one for each simulated small body. + */ + Update(date) { + const time = MakeTime(date); + const dt = time.tt - this.curr.time.tt; + if (dt === 0.0) { + // Special case: the time has not changed, so skip the usual physics calculations. + // This allows another way for the caller to query the current body states. + // It is also necessary to avoid dividing by `dt` if `dt` is zero. + // To prepare for a possible swap operation, duplicate the current state into the previous state. + this.prev = this.Duplicate(); + } + else { + // Exchange the current state with the previous state. Then calculate the new current state. + this.Swap(); + // Update the current time. + this.curr.time = time; + // Calculate the positions and velocities of the Sun and planets at the given time. + this.curr.gravitators = GravitySimulator.CalcSolarSystem(time); + // Estimate the positions of the small bodies as if their existing + // accelerations apply across the whole time interval. + for (let i = 0; i < this.curr.bodies.length; ++i) { + const p = this.prev.bodies[i]; + this.curr.bodies[i].r = UpdatePosition(dt, p.r, p.v, p.a); + } + // Calculate the acceleration experienced by the small bodies at + // their respective approximate next locations. + this.CalcBodyAccelerations(); + for (let i = 0; i < this.curr.bodies.length; ++i) { + // Calculate the average of the acceleration vectors + // experienced by the previous body positions and + // their estimated next positions. + // These become estimates of the mean effective accelerations + // over the whole interval. + const p = this.prev.bodies[i]; + const c = this.curr.bodies[i]; + const acc = p.a.mean(c.a); + // Refine the estimates of position and velocity at the next time step, + // using the mean acceleration as a better approximation of the + // continuously changing acceleration acting on each body. + c.tt = time.tt; + c.r = UpdatePosition(dt, p.r, p.v, acc); + c.v = UpdateVelocity(dt, p.v, acc); + } + // Re-calculate accelerations experienced by each body. + // These will be needed for the next simulation step (if any). + // Also, they will be potentially useful if some day we add + // a function to query the acceleration vectors for the bodies. + this.CalcBodyAccelerations(); + } + // Translate our internal calculations of body positions and velocities + // into state vectors that the caller can understand. + // We have to convert the internal type body_grav_calc_t to the public type StateVector. + // Also convert from barycentric coordinates to coordinates based on the selected origin body. + const bodyStates = []; + const ostate = this.InternalBodyState(this.originBody); + for (let bcalc of this.curr.bodies) { + bodyStates.push(new StateVector(bcalc.r.x - ostate.r.x, bcalc.r.y - ostate.r.y, bcalc.r.z - ostate.r.z, bcalc.v.x - ostate.v.x, bcalc.v.y - ostate.v.y, bcalc.v.z - ostate.v.z, time)); + } + return bodyStates; + } + /** + * Exchange the current time step with the previous time step. + * + * Sometimes it is helpful to "explore" various times near a given + * simulation time step, while repeatedly returning to the original + * time step. For example, when backdating a position for light travel + * time, the caller may wish to repeatedly try different amounts of + * backdating. When the backdating solver has converged, the caller + * wants to leave the simulation in its original state. + * + * This function allows a single "undo" of a simulation, and does so + * very efficiently. + * + * Usually this function will be called immediately after a matching + * call to {@link GravitySimulator#Update}. It has the effect of rolling + * back the most recent update. If called twice in a row, it reverts + * the swap and thus has no net effect. + * + * The constructor initializes the current state and previous + * state to be identical. Both states represent the `time` parameter that was + * passed into the constructor. Therefore, `Swap` will + * have no effect from the caller's point of view when passed a simulator + * that has not yet been updated by a call to {@link GravitySimulator#Update}. + */ + Swap() { + const swap = this.curr; + this.curr = this.prev; + this.prev = swap; + } + /** + * Get the position and velocity of a Solar System body included in the simulation. + * + * In order to simulate the movement of small bodies through the Solar System, + * the simulator needs to calculate the state vectors for the Sun and planets. + * + * If an application wants to know the positions of one or more of the planets + * in addition to the small bodies, this function provides a way to obtain + * their state vectors. This is provided for the sake of efficiency, to avoid + * redundant calculations. + * + * The state vector is returned relative to the position and velocity + * of the `originBody` parameter that was passed to this object's constructor. + * + * @param {Body} body + * The Sun, Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, or Neptune. + */ + SolarSystemBodyState(body) { + const bstate = this.InternalBodyState(body); + const ostate = this.InternalBodyState(this.originBody); + return ExportState(bstate.sub(ostate), this.curr.time); + } + InternalBodyState(body) { + if (body === Body.SSB) + return new body_state_t(this.curr.time.tt, TerseVector.zero(), TerseVector.zero()); + const bstate = this.curr.gravitators[body]; + if (bstate) + return bstate; + throw `Invalid body: ${body}`; + } + static CalcSolarSystem(time) { + const dict = {}; + // Start with the SSB at zero position and velocity. + const ssb = new body_state_t(time.tt, TerseVector.zero(), TerseVector.zero()); + // Calculate the heliocentric position of each planet, and adjust the SSB + // based each planet's pull on the Sun. + dict[Body.Mercury] = AdjustBarycenterPosVel(ssb, time.tt, Body.Mercury, MERCURY_GM); + dict[Body.Venus] = AdjustBarycenterPosVel(ssb, time.tt, Body.Venus, VENUS_GM); + dict[Body.Earth] = AdjustBarycenterPosVel(ssb, time.tt, Body.Earth, EARTH_GM + MOON_GM); + dict[Body.Mars] = AdjustBarycenterPosVel(ssb, time.tt, Body.Mars, MARS_GM); + dict[Body.Jupiter] = AdjustBarycenterPosVel(ssb, time.tt, Body.Jupiter, JUPITER_GM); + dict[Body.Saturn] = AdjustBarycenterPosVel(ssb, time.tt, Body.Saturn, SATURN_GM); + dict[Body.Uranus] = AdjustBarycenterPosVel(ssb, time.tt, Body.Uranus, URANUS_GM); + dict[Body.Neptune] = AdjustBarycenterPosVel(ssb, time.tt, Body.Neptune, NEPTUNE_GM); + // Convert planet states from heliocentric to barycentric. + for (let body in dict) { + dict[body].r.decr(ssb.r); + dict[body].v.decr(ssb.v); + } + // Convert heliocentric SSB to barycentric Sun. + dict[Body.Sun] = new body_state_t(time.tt, ssb.r.neg(), ssb.v.neg()); + return dict; + } + CalcBodyAccelerations() { + // Calculate the gravitational acceleration experienced by the simulated small bodies. + for (let b of this.curr.bodies) { + b.a = TerseVector.zero(); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Sun].r, SUN_GM); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Mercury].r, MERCURY_GM); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Venus].r, VENUS_GM); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Earth].r, EARTH_GM + MOON_GM); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Mars].r, MARS_GM); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Jupiter].r, JUPITER_GM); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Saturn].r, SATURN_GM); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Uranus].r, URANUS_GM); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Neptune].r, NEPTUNE_GM); + } + } + static AddAcceleration(acc, smallPos, majorPos, gm) { + const dx = majorPos.x - smallPos.x; + const dy = majorPos.y - smallPos.y; + const dz = majorPos.z - smallPos.z; + const r2 = dx * dx + dy * dy + dz * dz; + const pull = gm / (r2 * Math.sqrt(r2)); + acc.x += dx * pull; + acc.y += dy * pull; + acc.z += dz * pull; + } + Duplicate() { + // Copy the current state into the previous state, so that both become the same moment in time. + const gravitators = {}; + for (let body in this.curr.gravitators) { + gravitators[body] = this.curr.gravitators[body].clone(); + } + const bodies = []; + for (let b of this.curr.bodies) { + bodies.push(b.clone()); + } + return new GravSimEndpoint(this.curr.time, gravitators, bodies); + } +} +exports.GravitySimulator = GravitySimulator; +class GravSimEndpoint { + constructor(time, gravitators, bodies) { + this.time = time; + this.gravitators = gravitators; + this.bodies = bodies; + } +} + +},{}]},{},[1])(1) +}); diff --git a/node_modules/astronomy-engine/astronomy.browser.min.js b/node_modules/astronomy-engine/astronomy.browser.min.js new file mode 100644 index 0000000..3aa017a --- /dev/null +++ b/node_modules/astronomy-engine/astronomy.browser.min.js @@ -0,0 +1,258 @@ +/* + MIT + + + Astronomy library for JavaScript (browser and Node.js). + https://github.com/cosinekitty/astronomy + + MIT License + + Copyright (c) 2019-2023 Don Cross + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ +var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.createTemplateTagFirstArg=function(r){return r.raw=r};$jscomp.createTemplateTagFirstArgWithRaw=function(r,u){r.raw=u;return r};$jscomp.arrayIteratorImpl=function(r){var u=0;return function(){return uarguments.length)return arguments.length?Math.abs(arguments[0]):0;var e,C,A;for(e=A=0;eA){if(!A)return A;for(e=C=0;eu?-e:e}},"es6","es3"); +(function(r){"object"===typeof exports&&"undefined"!==typeof module?module.exports=r():"function"===typeof define&&define.amd?define([],r):("undefined"!==typeof window?window:"undefined"!==typeof global?global:"undefined"!==typeof self?self:this).Astronomy=r()})(function(){return function(){function r(u,e,C){function A(N,T){if(!e[N]){if(!u[N]){var ka="function"==typeof require&&require;if(!T&&ka)return ka(N,!0);if(w)return w(N,!0);T=Error("Cannot find module '"+N+"'");throw T.code="MODULE_NOT_FOUND", +T;}T=e[N]={exports:{}};u[N][0].call(T.exports,function(sa){return A(u[N][1][sa]||sa)},T,T.exports,r,u,e,C)}return e[N].exports}for(var w="function"==typeof require&&require,Q=0;QMath.abs(c))throw"AngleBetween: first vector is too short.";var d=b.x*b.x+b.y*b.y+b.z*b.z;if(1E-8>Math.abs(d))throw"AngleBetween: second vector is too short.";a=(a.x*b.x+a.y*b.y+a.z*b.z)/Math.sqrt(c*d);return-1>=a?180:1<=a?0:e.RAD2DEG*Math.acos(a)}function T(a){a=ld.indexOf(a);return 0<=a?md[a]:null}function ka(a){return(a=T(a))&&0b)return a=(b-1820)/100,-20+32*a*a; +if(500>b){a=b/100;b=a*a;var c=a*b;return 10583.6-1014.41*a+33.78311*b-5.952053*c-.1798452*b*b+.022174192*b*c+.0090316521*c*c}if(1600>b)return a=(b-1E3)/100,b=a*a,c=a*b,1574.2-556.01*a+71.23472*b+.319781*c-.8503463*b*b-.005050998*b*c+.0083572073*c*c;if(1700>b)return a=b-1600,b=a*a,120-.9808*a-.01532*b+a*b/7129;if(1800>b)return a=b-1700,b=a*a,8.83+.1603*a-.0059285*b+1.3336E-4*a*b-b*b/1174E3;if(1860>b){a=b-1800;b=a*a;c=a*b;var d=b*b;return 13.72-.332447*a+.0068612*b+.0041116*c-3.7436E-4*d+1.21272E-5* +b*c-1.699E-7*c*c+8.75E-10*c*d}if(1900>b)return a=b-1860,b=a*a,c=a*b,7.62+.5737*a-.251754*b+.01680668*c-4.473624E-4*b*b+b*c/233174;if(1920>b)return a=b-1900,b=a*a,-2.79+1.494119*a-.0598939*b+.0061966*a*b-1.97E-4*b*b;if(1941>b)return a=b-1920,b=a*a,21.2+.84493*a-.0761*b+.0020936*a*b;if(1961>b)return a=b-1950,b=a*a,29.07+.407*a-b/233+a*b/2547;if(1986>b)return a=b-1975,b=a*a,45.45+1.067*a-b/260-a*b/718;if(2005>b)return a=b-2E3,b=a*a,c=a*b,63.86+.3345*a-.060374*b+.0017275*c+6.51814E-4*b*b+2.373599E-5* +b*c;if(2050>b)return a=b-2E3,62.92+.32217*a+.005589*a*a;if(2150>b)return a=(b-1820)/100,-20+32*a*a-.5628*(2150-b);a=(b-1820)/100;return-20+32*a*a}function Vb(a){return a+Wb(a)/86400}function v(a){return a instanceof O?a:new O(a)}function Xb(a){a=a.tt/36525;return(((((-4.34E-8*a-5.76E-7)*a+.0020034)*a-1.831E-4)*a-46.836769)*a+84381.406)/3600}function da(a){if(!$a||1E-6=G;++G)0!==D[G]&&g(L.x,L.y,c(y,D[G],G),c(x,D[G],G),function(ta,ua){return L.x=ta,L.y=ua});return L}function k(D,G,P,fa,L,ta,ua,ub){L=l(L,ta,ua,ub);q+=D*L.y; +t+=G*L.y;ab+=P*L.x;va+=fa*L.x}++e.CalcMoonCount;a=a.tt/36525;var n,p,q,t,y=b(-6,6,1,4),x=b(-6,6,1,4);var z=a*a;var ab=t=q=0;var va=3422.7;var la=h(.19833+.05611*a);var ha=h(.27869+.04508*a);var V=h(.16827-.36903*a);var ba=h(.34734-5.37261*a);var La=h(.10498-5.37899*a);var bb=h(.42681-.41855*a),od=h(.14943-5.37511*a);var cb=.84*la+.31*ha+14.27*V+7.26*ba+.28*La+.24*bb;var wb=2.94*la+.31*ha+14.27*V+9.34*ba+1.12*La+.83*bb;var db=-6.4*la-1.89*bb;ha=.21*la+.31*ha+14.27*V-88.7*ba-15.3*La+.24*bb-1.86*od; +V=cb-db;la=-3.332E-6*h(.59734-5.37261*a)-5.39E-7*h(.35498-5.37899*a)-6.4E-8*h(.39943-5.37511*a);cb=U*Q(.60643382+1336.85522467*a-3.13E-6*z)+cb/ia;wb=U*Q(.37489701+1325.55240982*a+2.565E-5*z)+wb/ia;db=U*Q(.99312619+99.99735956*a-4.4E-7*z)+db/ia;ha=U*Q(.25909118+1342.2278298*a-8.92E-6*z)+ha/ia;La=U*Q(.82736186+1236.85308708*a-3.97E-6*z)+V/ia;for(n=1;4>=n;++n){switch(n){case 1:V=wb;z=4;ba=1.000002208;break;case 2:V=db;z=3;ba=.997504612-.002495388*a;break;case 3:V=ha;z=4;ba=1.000002708+139.978*la;break; +case 4:V=La;z=6;ba=1;break;default:throw"Internal error: I = "+n;}d(0,n,1);d(1,n,Math.cos(V)*ba);f(0,n,0);f(1,n,Math.sin(V)*ba);for(p=2;p<=z;++p)g(c(y,p-1,n),c(x,p-1,n),c(y,1,n),c(x,1,n),function(D,G){return d(p,n,D),f(p,n,G)});for(p=1;p<=z;++p)d(-p,n,c(y,p,n)),f(-p,n,-c(x,p,n))}k(13.902,14.06,-.001,.2607,0,0,0,4);k(.403,-4.01,.394,.0023,0,0,0,3);k(2369.912,2373.36,.601,28.2333,0,0,0,2);k(-125.154,-112.79,-.725,-.9781,0,0,0,1);k(1.979,6.98,-.445,.0433,1,0,0,4);k(191.953,192.72,.029,3.0861,1,0,0,2); +k(-8.466,-13.51,.455,-.1093,1,0,0,1);k(22639.5,22609.07,.079,186.5398,1,0,0,0);k(18.609,3.59,-.094,.0118,1,0,0,-1);k(-4586.465,-4578.13,-.077,34.3117,1,0,0,-2);k(3.215,5.44,.192,-.0386,1,0,0,-3);k(-38.428,-38.64,.001,.6008,1,0,0,-4);k(-.393,-1.43,-.092,.0086,1,0,0,-6);k(-.289,-1.59,.123,-.0053,0,1,0,4);k(-24.42,-25.1,.04,-.3,0,1,0,2);k(18.023,17.93,.007,.1494,0,1,0,1);k(-668.146,-126.98,-1.302,-.3997,0,1,0,0);k(.56,.32,-.001,-.0037,0,1,0,-1);k(-165.145,-165.06,.054,1.9178,0,1,0,-2);k(-1.877,-6.46, +-.416,.0339,0,1,0,-4);k(.213,1.02,-.074,.0054,2,0,0,4);k(14.387,14.78,-.017,.2833,2,0,0,2);k(-.586,-1.2,.054,-.01,2,0,0,1);k(769.016,767.96,.107,10.1657,2,0,0,0);k(1.75,2.01,-.018,.0155,2,0,0,-1);k(-211.656,-152.53,5.679,-.3039,2,0,0,-2);k(1.225,.91,-.03,-.0088,2,0,0,-3);k(-30.773,-34.07,-.308,.3722,2,0,0,-4);k(-.57,-1.4,-.074,.0109,2,0,0,-6);k(-2.921,-11.75,.787,-.0484,1,1,0,2);k(1.267,1.52,-.022,.0164,1,1,0,1);k(-109.673,-115.18,.461,-.949,1,1,0,0);k(-205.962,-182.36,2.056,1.4437,1,1,0,-2);k(.233, +.36,.012,-.0025,1,1,0,-3);k(-4.391,-9.66,-.471,.0673,1,1,0,-4);k(.283,1.53,-.111,.006,1,-1,0,4);k(14.577,31.7,-1.54,.2302,1,-1,0,2);k(147.687,138.76,.679,1.1528,1,-1,0,0);k(-1.089,.55,.021,0,1,-1,0,-1);k(28.475,23.59,-.443,-.2257,1,-1,0,-2);k(-.276,-.38,-.006,-.0036,1,-1,0,-3);k(.636,2.27,.146,-.0102,1,-1,0,-4);k(-.189,-1.68,.131,-.0028,0,2,0,2);k(-7.486,-.66,-.037,-.0086,0,2,0,0);k(-8.096,-16.35,-.74,.0918,0,2,0,-2);k(-5.741,-.04,0,-9E-4,0,0,2,2);k(.255,0,0,0,0,0,2,1);k(-411.608,-.2,0,-.0124,0,0, +2,0);k(.584,.84,0,.0071,0,0,2,-1);k(-55.173,-52.14,0,-.1052,0,0,2,-2);k(.254,.25,0,-.0017,0,0,2,-3);k(.025,-1.67,0,.0031,0,0,2,-4);k(1.06,2.96,-.166,.0243,3,0,0,2);k(36.124,50.64,-1.3,.6215,3,0,0,0);k(-13.193,-16.4,.258,-.1187,3,0,0,-2);k(-1.187,-.74,.042,.0074,3,0,0,-4);k(-.293,-.31,-.002,.0046,3,0,0,-6);k(-.29,-1.45,.116,-.0051,2,1,0,2);k(-7.649,-10.56,.259,-.1038,2,1,0,0);k(-8.627,-7.59,.078,-.0192,2,1,0,-2);k(-2.74,-2.54,.022,.0324,2,1,0,-4);k(1.181,3.32,-.212,.0213,2,-1,0,2);k(9.703,11.67,-.151, +.1268,2,-1,0,0);k(-.352,-.37,.001,-.0028,2,-1,0,-1);k(-2.494,-1.17,-.003,-.0017,2,-1,0,-2);k(.36,.2,-.012,-.0043,2,-1,0,-4);k(-1.167,-1.25,.008,-.0106,1,2,0,0);k(-7.412,-6.12,.117,.0484,1,2,0,-2);k(-.311,-.65,-.032,.0044,1,2,0,-4);k(.757,1.82,-.105,.0112,1,-2,0,2);k(2.58,2.32,.027,.0196,1,-2,0,0);k(2.533,2.4,-.014,-.0212,1,-2,0,-2);k(-.344,-.57,-.025,.0036,0,3,0,-2);k(-.992,-.02,0,0,1,0,2,2);k(-45.099,-.02,0,-.001,1,0,2,0);k(-.179,-9.52,0,-.0833,1,0,2,-2);k(-.301,-.33,0,.0014,1,0,2,-4);k(-6.382,-3.37, +0,-.0481,1,0,-2,2);k(39.528,85.13,0,-.7136,1,0,-2,0);k(9.366,.71,0,-.0112,1,0,-2,-2);k(.202,.02,0,0,1,0,-2,-4);k(.415,.1,0,.0013,0,1,2,0);k(-2.152,-2.26,0,-.0066,0,1,2,-2);k(-1.44,-1.3,0,.0014,0,1,-2,2);k(.384,-.04,0,0,0,1,-2,-2);k(1.938,3.6,-.145,.0401,4,0,0,0);k(-.952,-1.58,.052,-.013,4,0,0,-2);k(-.551,-.94,.032,-.0097,3,1,0,0);k(-.482,-.57,.005,-.0045,3,1,0,-2);k(.681,.96,-.026,.0115,3,-1,0,0);k(-.297,-.27,.002,-9E-4,2,2,0,-2);k(.254,.21,-.003,0,2,-2,0,-2);k(-.25,-.22,.004,.0014,1,3,0,-2);k(-3.996, +0,0,4E-4,2,0,2,0);k(.557,-.75,0,-.009,2,0,2,-2);k(-.459,-.38,0,-.0053,2,0,-2,2);k(-1.298,.74,0,4E-4,2,0,-2,0);k(.538,1.14,0,-.0141,2,0,-2,-2);k(.263,.02,0,0,1,1,2,0);k(.426,.07,0,-6E-4,1,1,-2,-2);k(-.304,.03,0,3E-4,1,-1,2,0);k(-.372,-.19,0,-.0027,1,-1,-2,2);k(.418,0,0,0,0,0,4,0);k(-.33,-.04,0,0,3,0,2,0);z=-526.069*l(0,0,1,-2).y;z+=-3.352*l(0,0,1,-4).y;z+=44.297*l(1,0,1,-2).y;z+=-6*l(1,0,1,-4).y;z+=20.599*l(-1,0,1,0).y;z+=-30.598*l(-1,0,1,-2).y;z+=-24.649*l(-2,0,1,0).y;z+=-2*l(-2,0,1,-2).y;z+=-22.571* +l(0,1,1,-2).y;z+=10.985*l(0,-1,1,-2).y;q+=.82*h(.7736-62.5512*a)+.31*h(.0466-125.1025*a)+.35*h(.5785-25.1042*a)+.66*h(.4591+1335.8075*a)+.64*h(.313-91.568*a)+1.14*h(.148+1331.2898*a)+.21*h(.5918+1056.5859*a)+.44*h(.5784+1322.8595*a)+.24*h(.2275-5.7374*a)+.28*h(.2965+2.6929*a)+.33*h(.3132+6.3368*a);a=ha+t/ia;a=(1.000002708+139.978*la)*(18518.511+1.189+ab)*Math.sin(a)-6.24*Math.sin(3*a)+z;return{geo_eclip_lon:U*Q((cb+q/ia)/U),geo_eclip_lat:Math.PI/648E3*a,distance_au:ia*pd/(.999953253*va)}}function ac(a, +b){return[a.rot[0][0]*b[0]+a.rot[1][0]*b[1]+a.rot[2][0]*b[2],a.rot[0][1]*b[0]+a.rot[1][1]*b[1]+a.rot[2][1]*b[2],a.rot[0][2]*b[0]+a.rot[1][2]*b[1]+a.rot[2][2]*b[2]]}function wa(a,b,c){b=Ma(b,c);return ac(b,a)}function Ma(a,b){a=a.tt/36525;var c=84381.406,d=((((3.337E-7*a-4.67E-7)*a-.00772503)*a+.0512623)*a-.025754)*a+c;c*=4.84813681109536E-6;var f=((((-9.51E-8*a+1.32851E-4)*a-.00114045)*a-1.0790069)*a+5038.481507)*a*4.84813681109536E-6;d*=4.84813681109536E-6;var g=((((-5.6E-8*a+1.70663E-4)*a-.00121197)* +a-2.3814292)*a+10.556403)*a*4.84813681109536E-6;a=Math.sin(c);c=Math.cos(c);var h=Math.sin(-f);f=Math.cos(-f);var l=Math.sin(-d);d=Math.cos(-d);var k=Math.sin(g),n=Math.cos(g);g=n*f-h*k*d;var p=n*h*c+k*d*f*c-a*k*l,q=n*h*a+k*d*f*a+c*k*l,t=-k*f-h*n*d,y=-k*h*c+n*d*f*c-a*n*l;k=-k*h*a+n*d*f*a+c*n*l;h*=l;n=-l*f*c-a*d;a=-l*f*a+d*c;if(b===F.Into2000)return new J([[g,p,q],[t,y,k],[h,n,a]]);if(b===F.From2000)return new J([[g,t,h],[p,y,n],[q,k,a]]);throw"Invalid precess direction";}function ca(a){if(!eb||eb.tt!== +a.tt){var b=a.tt/36525,c=15*da(a).ee,d=(.779057273264+.00273781191135448*a.ut+a.ut%1)%1*360;0>d&&(d+=360);b=((c+.014506+((((-3.68E-8*b-2.9956E-5)*b-4.4E-7)*b+1.3915817)*b+4612.156534)*b)/3600+d)%360/15;0>b&&(b+=24);eb={tt:a.tt,st:b}}return eb.st}function bc(a){a=v(a);return ca(a)}function xb(a,b){var c=a.latitude*e.DEG2RAD,d=Math.sin(c);c=Math.cos(c);var f=1/Math.hypot(c,.996647180302104*d),g=a.height/1E3,h=6378.1366*f+g;b=(15*b+a.longitude)*e.DEG2RAD;a=Math.sin(b);b=Math.cos(b);return{pos:[h*c*b/ +e.KM_PER_AU,h*c*a/e.KM_PER_AU,(6335.438815127603*f+g)*d/e.KM_PER_AU],vel:[-7.292115E-5*h*c*a*86400/e.KM_PER_AU,7.292115E-5*h*c*b*86400/e.KM_PER_AU,0]}}function xa(a,b,c){b=Na(b,c);return ac(b,a)}function Na(a,b){a=da(a);var c=a.mobl*e.DEG2RAD,d=a.tobl*e.DEG2RAD,f=4.84813681109536E-6*a.dpsi;a=Math.cos(c);c=Math.sin(c);var g=Math.cos(d),h=Math.sin(d);d=Math.cos(f);var l=Math.sin(f);f=-l*a;var k=-l*c,n=l*g,p=d*a*g+c*h,q=d*c*g-a*h;l*=h;var t=d*a*h-c*g;a=d*c*h+a*g;if(b===F.From2000)return new J([[d,n, +l],[f,p,t],[k,q,a]]);if(b===F.Into2000)return new J([[d,f,k],[n,p,q],[l,t,a]]);throw"Invalid precess direction";}function fb(a,b,c){return c===F.Into2000?wa(xa(a,b,c),b,c):xa(wa(a,b,c),b,c)}function cc(a,b){var c=ca(a);b=xb(b,c).pos;return fb(b,a,F.Into2000)}function qd(a){if(!(a instanceof Array)||3!==a.length)return!1;for(var b=0;3>b;++b){if(!(a[b]instanceof Array)||3!==a[b].length)return!1;for(var c=0;3>c;++c)if(!Number.isFinite(a[b][c]))return!1}return!0}function yb(a,b){return new E(a[0],a[1], +a[2],b)}function dc(a,b){b=yb(a,b);var c=b.x*b.x+b.y*b.y,d=Math.sqrt(c+b.z*b.z);if(0===c){if(0===b.z)throw"Indeterminate sky coordinates";return new gb(0,0>b.z?-90:90,d,b)}var f=e.RAD2HOUR*Math.atan2(b.y,b.x);0>f&&(f+=24);return new gb(f,e.RAD2DEG*Math.atan2(a[2],Math.sqrt(c)),d,b)}function ya(a,b){var c=a*e.DEG2RAD;a=Math.cos(c);c=Math.sin(c);return[a*b[0]+c*b[1],a*b[1]-c*b[0],b[2]]}function hb(a,b,c,d,f){a=v(a);za(b);w(c);w(d);var g=Math.sin(b.latitude*e.DEG2RAD),h=Math.cos(b.latitude*e.DEG2RAD), +l=Math.sin(b.longitude*e.DEG2RAD),k=Math.cos(b.longitude*e.DEG2RAD);b=Math.sin(d*e.DEG2RAD);var n=Math.cos(d*e.DEG2RAD),p=Math.sin(c*e.HOUR2RAD),q=Math.cos(c*e.HOUR2RAD),t=[h*k,h*l,g];g=[-g*k,-g*l,h];l=[l,-k,0];h=-15*ca(a);a=ya(h,t);t=ya(h,g);l=ya(h,l);b=[n*q,n*p,b];p=b[0]*a[0]+b[1]*a[1]+b[2]*a[2];n=b[0]*t[0]+b[1]*t[1]+b[2]*t[2];t=b[0]*l[0]+b[1]*l[1]+b[2]*l[2];q=Math.hypot(n,t);0n&&(n+=360)):n=0;p=e.RAD2DEG*Math.atan2(q,p);q=d;if(f&&(d=p,f=Oa(f,90-p),p-=f,0l;++l)f.push((b[l]-d*a[l])/t*c+a[l]*q);q=Math.hypot(f[0],f[1]);0c&&(c+=24)):c=0;q=e.RAD2DEG*Math.atan2(f[2],q)}return new ec(n,90-p,c,q)}function za(a){if(!(a instanceof zb))throw"Not an instance of the Observer class: "+a;w(a.latitude);w(a.longitude);w(a.height);if(-90>a.latitude||90b&&(b+=360));g=e.RAD2DEG*Math.atan2(c,g);a=new E(d,f,c,a.t);return new gc(a,g,b)}function Qa(a){var b=da(a.t),c=wa([a.x,a.y,a.z],a.t,F.From2000),d=$jscomp.makeIterator(xa(c,a.t,F.From2000));c=d.next().value;var f=d.next().value;d=d.next().value;a=new E(c,f,d,a.t);b=b.tobl*e.DEG2RAD;return Ab(a,Math.cos(b),Math.sin(b))}function Y(a){a=v(a);var b=ea(a),c=b.distance_au*Math.cos(b.geo_eclip_lat);b=[c*Math.cos(b.geo_eclip_lon),c*Math.sin(b.geo_eclip_lon),b.distance_au* +Math.sin(b.geo_eclip_lat)];b=Yb(Xb(a),b);b=wa(b,a,F.Into2000);return new E(b[0],b[1],b[2],a)}function ib(a){var b=v(a);a=ea(b);var c=a.distance_au*Math.cos(a.geo_eclip_lat),d=[c*Math.cos(a.geo_eclip_lon),c*Math.sin(a.geo_eclip_lon),a.distance_au*Math.sin(a.geo_eclip_lat)];c=da(b);d=Yb(c.mobl,d);d=xa(d,b,F.From2000);b=yb(d,b);c=c.tobl*e.DEG2RAD;b=Ab(b,Math.cos(c),Math.sin(c));return new Ba(b.elat,b.elon,a.distance_au)}function Ra(a){a=v(a);var b=a.AddDays(-1E-5),c=a.AddDays(1E-5);b=Y(b);c=Y(c);return new I((b.x+ +c.x)/2,(b.y+c.y)/2,(b.z+c.z)/2,(c.x-b.x)/2E-5,(c.y-b.y)/2E-5,(c.z-b.z)/2E-5,a)}function Bb(a){a=v(a);var b=Ra(a);return new I(b.x/82.30056,b.y/82.30056,b.z/82.30056,b.vx/82.30056,b.vy/82.30056,b.vz/82.30056,a)}function ma(a,b,c){var d=1,f=0;a=$jscomp.makeIterator(a);for(var g=a.next();!g.done;g=a.next()){var h=0;g=$jscomp.makeIterator(g.value);for(var l=g.next();!l.done;l=g.next()){var k=$jscomp.makeIterator(l.value);l=k.next().value;var n=k.next().value;k=k.next().value;h+=l*Math.cos(n+b*k)}h*=d; +c&&(h%=U);f+=h;d*=b}return f}function Cb(a,b){var c=1,d=0,f=0,g=0;a=$jscomp.makeIterator(a);for(var h=a.next();!h.done;h=a.next()){var l=0,k=0;h=$jscomp.makeIterator(h.value);for(var n=h.next();!n.done;n=h.next()){var p=$jscomp.makeIterator(n.value);n=p.next().value;var q=p.next().value;p=p.next().value;q+=b*p;l+=n*p*Math.sin(q);0a?0:a>=b?b-1:a}function Gb(a){var b=$jscomp.makeIterator(a);a=b.next().value;var c=$jscomp.makeIterator(b.next().value);var d=c.next().value;var f=c.next().value;c=c.next().value;var g=$jscomp.makeIterator(b.next().value);b=g.next().value;var h=g.next().value; +g=g.next().value;d=new X(a,new B(d,f,c),new B(b,h,g));a=new Da(d.tt);f=d.r.add(a.Sun.r);c=d.v.add(a.Sun.v);b=a.Acceleration(f);d=new Ua(d.tt,f,c,b);return new ic(a,d)}function kc(a,b,c){a=Gb(a);for(var d=Math.ceil((b-a.grav.tt)/c),f=0;fna[50][0])c=null;else{c=jc((c-d)/29200,50);if(!Ib[c]){d=Ib[c]=[];d[0]=Gb(na[c]).grav;d[200]=Gb(na[c+1]).grav;var f,g=d[0].tt;for(f=1;200>f;++f)d[f]=Fb(g+=146,d[f- +1]).grav;g=d[200].tt;var h=[];h[200]=d[200];for(f=199;0d[1]&&(d[1]+=U);f=$jscomp.makeIterator(b.z);for(g=f.next();!g.done;g=f.next())h=$jscomp.makeIterator(g.value),g=h.next().value,l=h.next().value,h=h.next().value,l+=c*h,d[2]+=g*Math.cos(l),d[3]+=g*Math.sin(l);f=$jscomp.makeIterator(b.zeta);for(g=f.next();!g.done;g=f.next())h=$jscomp.makeIterator(g.value),g=h.next().value,l=h.next().value,h=h.next().value,l+=c*h,d[4]+=g*Math.cos(l),d[5]+=g*Math.sin(l);f=d[0];h=d[1]; +g=d[2];l=d[3];c=d[4];d=d[5];var k=Math.sqrt(b.mu/(f*f*f));b=h+g*Math.sin(h)-l*Math.cos(h);do{var n=Math.cos(b);var p=Math.sin(b);n=(h-b+g*p-l*n)/(1-g*n-l*p);b+=n}while(1E-12<=Math.abs(n));n=Math.cos(b);p=Math.sin(b);h=l*n-g*p;var q=-g*n-l*p,t=1/(1+q),y=1/(1+Math.sqrt(1-g*g-l*l));b=f*(n-g-y*l*h);h=f*(p-l+y*g*h);l=k*t*f*(-p-y*l*q);f=k*t*f*(+n+y*g*q);g=2*Math.sqrt(1-c*c-d*d);k=1-2*d*d;n=1-2*c*c;p=2*d*c;a=new I(b*k+h*p,b*p+h*n,(c*h-b*d)*g,l*k+f*p,l*p+f*n,(c*f-l*d)*g,a);return Ea(rd,a)}function Z(a,b){b= +v(b);if(a in M)return Aa(M[a],b);if(a===m.Pluto)return a=Hb(b,!0),new E(a.x,a.y,a.z,b);if(a===m.Sun)return new E(0,0,0,b);if(a===m.Moon){a=Aa(M.Earth,b);var c=Y(b);return new E(a.x+c.x,a.y+c.y,a.z+c.z,b)}if(a===m.EMB)return a=Aa(M.Earth,b),c=Y(b),new E(a.x+c.x/82.30056,a.y+c.y/82.30056,a.z+c.z/82.30056,b);if(a===m.SSB)return a=new E(0,0,0,b),jb(a,b,m.Jupiter,2.825345909524226E-7),jb(a,b,m.Saturn,8.459715185680659E-8),jb(a,b,m.Uranus,1.292024916781969E-8),jb(a,b,m.Neptune,1.524358900784276E-8),a;if(c= +ka(a))return a=new Ba(c.dec,15*c.ra,c.dist),lb(a,b);throw'HelioVector: Unknown body "'+a+'"';}function oa(a,b){var c=ka(a);if(c)return c.dist;b=v(b);return a in M?ma(M[a][2],b.tt/365250,!1):Z(a,b).Length()}function lc(a,b){for(var c=b,d=0,f=0;10>f;++f){var g=a(c);d=g.Length()/e.C_AUDAY;if(1d)return g;c=h}throw"Light-travel time solver did not converge: dt = "+d;}function mc(a,b,c,d){A(d);a=v(a); +if(ka(c)){c=Z(c,a);if(d)return b=mb(b,a),d=new E(c.x-b.x,c.y-b.y,c.z-b.z,a),c=e.C_AUDAY/d.Length(),new E(d.x+b.vx/c,d.y+b.vy/c,d.z+b.vz/c,a);b=Z(b,a);return new E(c.x-b.x,c.y-b.y,c.z-b.z,a)}var f=d?new E(0,0,0,a):Z(b,a);var g=new nc(b,c,d,f);return lc(function(h){return g.Position(h)},a)}function W(a,b,c){A(c);b=v(b);switch(a){case m.Earth:return new E(0,0,0,b);case m.Moon:return Y(b);default:return a=mc(b,m.Earth,a,c),a.t=b,a}}function pa(a,b){return new I(a.r.x,a.r.y,a.r.z,a.v.x,a.v.y,a.v.z,b)} +function mb(a,b){b=v(b);switch(a){case m.Sun:return new I(0,0,0,0,0,0,b);case m.SSB:return a=new Da(b.tt),new I(-a.Sun.r.x,-a.Sun.r.y,-a.Sun.r.z,-a.Sun.v.x,-a.Sun.v.y,-a.Sun.v.z,b);case m.Mercury:case m.Venus:case m.Earth:case m.Mars:case m.Jupiter:case m.Saturn:case m.Uranus:case m.Neptune:return a=Sa(M[a],b.tt),pa(a,b);case m.Pluto:return Hb(b,!0);case m.Moon:case m.EMB:var c=Sa(M.Earth,b.tt);a=a==m.Moon?Ra(b):Bb(b);return new I(a.x+c.r.x,a.y+c.r.y,a.z+c.r.z,a.vx+c.v.x,a.vy+c.v.y,a.vz+c.v.z,b); +default:if(ka(a))return a=Z(a,b),new I(a.x,a.y,a.z,0,0,0,b);throw'HelioState: Unsupported body "'+a+'"';}}function sd(a,b,c,d,f){var g=(f+c)/2-d;c=(f-c)/2;if(0==g){if(0==c)return null;d=-d/c;if(-1>d||1=d)return null;f=Math.sqrt(d);d=(-c+f)/(2*g);f=(-c-f)/(2*g);if(-1<=d&&1>=d){if(-1<=f&&1>=f)return null}else if(-1<=f&&1>=f)d=f;else return null}return{t:a+d*b,df_dt:(2*g*d+c)/b}}function K(a,b,c,d){var f=w(d&&d.dt_tolerance_seconds||1);f=Math.abs(f/86400);var g=d&& +d.init_f1||a(b),h=d&&d.init_f2||a(c),l=NaN,k=0;d=d&&d.iter_limit||20;for(var n=!0;;){if(++k>d)throw"Excessive iteration in Search()";var p=new O(b.ut+.5*(c.ut-b.ut)),q=p.ut-b.ut;if(Math.abs(q)(q.ut-b.ut)*(q.ut-c.ut)&&0>(y.ut-b.ut)*(y.ut-c.ut))){t=a(q);var z=a(y);if(0>t&&0<=z){g=t;h=z;b=q;c=y;l=x; +n=!1;continue}}}}if(0>g&&0<=l)c=p,h=l;else if(0>l&&0<=h)b=p,g=l;else return null}}function Fa(a){for(;-180>=a;)a+=360;for(;180a;)a+=360;for(;360<=a;)a-=360;return a}function oc(a,b,c){w(a);w(c);b=v(b);c=b.AddDays(c);return K(function(d){d=fc(d);return Fa(d.elon-a)},b,c,{dt_tolerance_seconds:.01})}function Jb(a,b,c){if(a===m.Earth||b===m.Earth)throw"The Earth does not have a longitude as seen from itself.";c=v(c);a=W(a,c,!1);a=Qa(a);b=W(b,c,!1);b=Qa(b);return Ga(a.elon- +b.elon)}function Ha(a,b){if(a==m.Earth)throw"The Earth does not have an angle as seen from itself.";var c=v(b);b=W(m.Sun,c,!0);a=W(a,c,!0);return N(b,a)}function qa(a,b){if(a===m.Sun)throw"Cannot calculate heliocentric longitude of the Sun.";a=Z(a,b);return Qa(a).elon}function nb(a,b){if(a===m.Earth)throw"The illumination of the Earth is not defined.";var c=v(b),d=Aa(M.Earth,c);if(a===m.Sun){var f=new E(-d.x,-d.y,-d.z,c);b=new E(0,0,0,c);d=0}else a===m.Moon?(f=Y(c),b=new E(d.x+f.x,d.y+f.y,d.z+f.z, +c)):(b=Z(a,b),f=new E(b.x-d.x,b.y-d.y,b.z-d.z,c)),d=N(f,b);var g=f.Length(),h=b.Length();if(a===m.Sun)var l=td+5*Math.log10(g);else if(a===m.Moon)a=d*e.DEG2RAD,l=a*a,a=-12.717+1.49*Math.abs(a)+.0431*l*l,l=a+=5*Math.log10(g/(385000.6/e.KM_PER_AU)*h);else if(a===m.Saturn){var k=d;a=Qa(f);l=28.06*e.DEG2RAD;var n=e.DEG2RAD*a.elat;a=Math.asin(Math.sin(n)*Math.cos(l)-Math.cos(n)*Math.sin(l)*Math.sin(e.DEG2RAD*a.elon-e.DEG2RAD*(169.51+3.82E-5*c.tt)));l=Math.sin(Math.abs(a));k=-9+.044*k+l*(-2.6+1.2*l)+5* +Math.log10(h*g);a*=e.RAD2DEG;l=k;k=a}else{var p=n=l=0;switch(a){case m.Mercury:a=-.6;l=4.98;n=-4.88;p=3.02;break;case m.Venus:163.6>d?(a=-4.47,l=1.03,n=.57,p=.13):(a=.98,l=-1.02);break;case m.Mars:a=-1.52;l=1.6;break;case m.Jupiter:a=-9.4;l=.5;break;case m.Uranus:a=-7.19;l=.25;break;case m.Neptune:a=-6.87;break;case m.Pluto:a=-1;l=4;break;default:throw"VisualMagnitude: unsupported body "+a;}var q=d/100;l=a+q*(l+q*(n+q*p))+5*Math.log10(h*g)}return new pc(c,l,d,h,g,f,b,k)}function Va(a){if(a===m.Earth)throw"The Earth does not have a synodic period as seen from itself."; +if(a===m.Moon)return 29.530588;var b=aa[a];if(!b)throw"Not a valid planet name: "+a;a=aa.Earth.OrbitalPeriod;return Math.abs(a/(a/b.OrbitalPeriod-1))}function Ia(a,b,c){function d(n){var p=qa(a,n);n=qa(m.Earth,n);return Fa(g*(n-p)-b)}w(b);var f=aa[a];if(!f)throw"Cannot search relative longitude because body is not a planet: "+a;if(a===m.Earth)throw"Cannot search relative longitude for the Earth (it is always 0)";var g=f.OrbitalPeriod>aa.Earth.OrbitalPeriod?1:-1;f=Va(a);c=v(c);var h=d(c);0l;++l){var k=-h/360*f;c=c.AddDays(k);if(1>86400*Math.abs(k))return c;k=h;h=d(c);30>Math.abs(k)&&k!==h&&(k/=k-h,.5k&&(f*=k))}throw"Relative longitude search failed to converge for "+a+" near "+c.toString()+" (error_angle = "+h+").";}function Kb(a){return Jb(m.Moon,m.Sun,a)}function Wa(a,b,c){function d(l){l=Kb(l);return Fa(l-a)}w(a);w(c);b=v(b);var f=d(b);if(0>c){0>f&&(f+=360);var g=-(29.530588*f)/360;f=g+1.5;if(fc)return null;f=Math.min(c,g+1.5)}c=b.AddDays(h);b=b.AddDays(f);return K(d,c,b,{dt_tolerance_seconds:.1})}function qc(a){var b=Kb(a);b=(Math.floor(b/90)+1)%4;a=Wa(90*b,a,10);if(!a)throw"Cannot find moon quarter";return new rc(b,a)}function sc(a){if(!Number.isFinite(a)||-500>a||1E5=a){var b=288.15-.0065*a;a=101325*Math.pow(288.15/b,-5.25577)}else 2E4>=a?(b=216.65,a=22632*Math.exp(-1.5768832E-4*(a-11E3))):(b=216.65+.001*(a-2E4), +a=5474.87*Math.pow(216.65/b,34.16319));return new tc(a,b,a/b/(101325/288.15))}function Lb(a,b,c,d,f,g,h){if(0>g&&0<=h)return new ud(d,f,g,h);if(0<=g&&0>h)return null;if(1786400*l||Math.min(Math.abs(g),Math.abs(h))>l/2*c)return null;l=new O((d.ut+f.ut)/2);var k=b(l);return Lb(1+a,b,c,d,l,g,k)||Lb(1+a,b,c,l,f,k,h)}function vd(a,b){if(-90>b||90h||90f?(n=p.AddDays(-.42),q=l(n)):(p=n.AddDays(.42),t=l(p));var y=Lb(0,l,k,n,p,q,t);if(y){if(k=K(l,y.tx,y.ty,{dt_tolerance_seconds:.1,init_f1:y.ax,init_f2:y.ay})){if(0>f){if(k.utd.ut+f)return null;return k}throw"Rise/set search failed after finding ascent: t1="+ +n+", t2="+p+", a1="+q+", a2="+t;}if(0>f){if(n.utd.ut+f)return null;n=p;q=t}}}function vc(a,b){b=v(b);var c=Jb(a,m.Sun,b);if(1805*f;++f){var g=a.AddDays(5),h=b(g);if(0>=d*h){if(0>d||0h){a=K(c,a,g,{init_f1:-d,init_f2:-h});if(!a)throw"SearchLunarApsis INTERNAL ERROR: apogee search failed!";d=ea(a).distance_au;return new Xa(a,1,d)}throw"SearchLunarApsis INTERNAL ERROR: cannot classify apsis event!";}a=g;d=h}throw"SearchLunarApsis INTERNAL ERROR: could not find apsis within 2 synodic months of start date.";}function yc(a,b,c,d){for(var f=b===Ja.Apocenter? +1:-1;;){d/=9;if(d<1/1440)return c=c.AddDays(d/2),a=oa(a,c),new Xa(c,b,a);for(var g=-1,h=0,l=0;10>l;++l){var k=c.AddDays(l*d);k=f*oa(a,k);if(0==l||k>h)g=l,h=k}c=c.AddDays((g-1)*d);d*=2}}function wd(a,b){var c=b.AddDays(-30/360*aa[a].OrbitalPeriod),d=b.AddDays(.75*aa[a].OrbitalPeriod),f=c,g=c,h=-1,l=-1;d=(d.ut-c.ut)/99;for(var k=0;100>k;++k){var n=c.AddDays(k*d),p=oa(a,n);0===k?l=h=p:(p>l&&(l=p,g=n),p=b.tt)return a.time.tt>= +b.tt&&a.time.tt=b.tt)return a;throw"Internal error: failed to find Neptune apsis.";}function zc(a,b){function c(p){var q=p.AddDays(-5E-4);p=p.AddDays(5E-4);q=oa(a,q);return(oa(a,p)-q)/.001}function d(p){return-c(p)}b=v(b);if(a===m.Neptune||a===m.Pluto)return wd(a,b);for(var f=aa[a].OrbitalPeriod,g=f/6,h=c(b),l=0;l*g<2*f;++l){var k=b.AddDays(g),n=c(k);if(0>=h*n){f=g=void 0;if(0>h||0n)g=d,f=Ja.Apocenter;else throw"Internal error with slopes in SearchPlanetApsis"; +b=K(g,b,k);if(!b)throw"Failed to find slope transition in planetary apsis search.";h=oa(a,b);return new Xa(b,f,h)}b=k;h=n}throw"Internal error: should have found planetary apsis within 2 orbital periods.";}function Ka(a){return new J([[a.rot[0][0],a.rot[1][0],a.rot[2][0]],[a.rot[0][1],a.rot[1][1],a.rot[2][1]],[a.rot[0][2],a.rot[1][2],a.rot[2][2]]])}function ja(a,b){return new J([[b.rot[0][0]*a.rot[0][0]+b.rot[1][0]*a.rot[0][1]+b.rot[2][0]*a.rot[0][2],b.rot[0][1]*a.rot[0][0]+b.rot[1][1]*a.rot[0][1]+ +b.rot[2][1]*a.rot[0][2],b.rot[0][2]*a.rot[0][0]+b.rot[1][2]*a.rot[0][1]+b.rot[2][2]*a.rot[0][2]],[b.rot[0][0]*a.rot[1][0]+b.rot[1][0]*a.rot[1][1]+b.rot[2][0]*a.rot[1][2],b.rot[0][1]*a.rot[1][0]+b.rot[1][1]*a.rot[1][1]+b.rot[2][1]*a.rot[1][2],b.rot[0][2]*a.rot[1][0]+b.rot[1][2]*a.rot[1][1]+b.rot[2][2]*a.rot[1][2]],[b.rot[0][0]*a.rot[2][0]+b.rot[1][0]*a.rot[2][1]+b.rot[2][0]*a.rot[2][2],b.rot[0][1]*a.rot[2][0]+b.rot[1][1]*a.rot[2][1]+b.rot[2][1]*a.rot[2][2],b.rot[0][2]*a.rot[2][0]+b.rot[1][2]*a.rot[2][1]+ +b.rot[2][2]*a.rot[2][2]]])}function lb(a,b){b=v(b);var c=a.lat*e.DEG2RAD,d=a.lon*e.DEG2RAD,f=a.dist*Math.cos(c);return new E(f*Math.cos(d),f*Math.sin(d),a.dist*Math.sin(c),b)}function Mb(a){var b=Nb(a);return new gb(b.lon/15,b.lat,b.dist,a)}function Nb(a){var b=a.x*a.x+a.y*a.y,c=Math.sqrt(b+a.z*a.z);if(0===b){if(0===a.z)throw"Zero-length vector not allowed.";var d=0;a=0>a.z?-90:90}else d=e.RAD2DEG*Math.atan2(a.y,a.x),0>d&&(d+=360),a=e.RAD2DEG*Math.atan2(a.z,Math.sqrt(b));return new Ba(a,d,c)}function Ac(a){a= +360-a;360<=a?a-=360:0>a&&(a+=360);return a}function Oa(a,b){w(b);if(-90>b||90c&&(c=-1);c=1.02/Math.tan((c+10.3/(c+5.11))*e.DEG2RAD)/60;"normal"===a&&-1>b&&(c*=(b+90)/89)}else{if(a)throw"Invalid refraction option: "+a;c=0}return c}function Bc(a,b){if(-90>b||90Math.abs(d))return c-b;c-=d}}function Ya(a,b){return new E(a.rot[0][0]*b.x+a.rot[1][0]*b.y+a.rot[2][0]*b.z,a.rot[0][1]*b.x+a.rot[1][1]* +b.y+a.rot[2][1]*b.z,a.rot[0][2]*b.x+a.rot[1][2]*b.y+a.rot[2][2]*b.z,b.t)}function Ea(a,b){return new I(a.rot[0][0]*b.x+a.rot[1][0]*b.y+a.rot[2][0]*b.z,a.rot[0][1]*b.x+a.rot[1][1]*b.y+a.rot[2][1]*b.z,a.rot[0][2]*b.x+a.rot[1][2]*b.y+a.rot[2][2]*b.z,a.rot[0][0]*b.vx+a.rot[1][0]*b.vy+a.rot[2][0]*b.vz,a.rot[0][1]*b.vx+a.rot[1][1]*b.vy+a.rot[2][1]*b.vz,a.rot[0][2]*b.vx+a.rot[1][2]*b.vy+a.rot[2][2]*b.vz,b.t)}function Cc(){return new J([[1,0,0],[0,.9174821430670688,-.3977769691083922],[0,.3977769691083922, +.9174821430670688]])}function ob(a){a=v(a);var b=Ma(a,F.From2000);a=Na(a,F.From2000);return ja(b,a)}function pb(a){a=v(a);var b=Na(a,F.Into2000);a=Ma(a,F.Into2000);return ja(b,a)}function Ob(a,b){a=v(a);var c=Math.sin(b.latitude*e.DEG2RAD),d=Math.cos(b.latitude*e.DEG2RAD),f=Math.sin(b.longitude*e.DEG2RAD),g=Math.cos(b.longitude*e.DEG2RAD);b=[d*g,d*f,c];c=[-c*g,-c*f,d];f=[f,-g,0];a=-15*ca(a);b=ya(a,b);c=ya(a,c);a=ya(a,f);return new J([[c[0],a[0],b[0]],[c[1],a[1],b[1]],[c[2],a[2],b[2]]])}function Dc(a, +b){a=Ob(a,b);return Ka(a)}function Ec(a,b){a=v(a);b=Dc(a,b);a=pb(a);return ja(b,a)}function Fc(a){a=pb(a);var b=Cc();return ja(a,b)}function Gc(a){a=Fc(a);return Ka(a)}function Hc(a,b){a=v(a);var c=Gc(a);a=Ob(a,b);return ja(c,a)}function Ic(a){var b=da(v(a)).tobl*e.DEG2RAD;a=Math.cos(b);b=Math.sin(b);return new J([[1,0,0],[0,+a,+b],[0,-b,+a]])}function Jc(a){var b=da(v(a)).tobl*e.DEG2RAD;a=Math.cos(b);b=Math.sin(b);return new J([[1,0,0],[0,+a,-b],[0,+b,+a]])}function Za(a,b,c,d){var f=(d.x*c.x+d.y* +c.y+d.z*c.z)/(d.x*d.x+d.y*d.y+d.z*d.z);return new xd(b,f,e.KM_PER_AU*Math.hypot(f*d.x-c.x,f*d.y-c.y,f*d.z-c.z),695700-(1+f)*(695700-a),-695700+(1+f)*(695700+a),c,d)}function qb(a){var b=W(m.Sun,a,!0);b=new E(-b.x,-b.y,-b.z,b.t);var c=Y(a);return Za(6459,a,c,b)}function Kc(a){var b=W(m.Sun,a,!0),c=Y(a),d=new E(-c.x,-c.y,-c.z,c.t);c.x-=b.x;c.y-=b.y;c.z-=b.z;return Za(1737.4,a,d,c)}function Pb(a,b){var c=cc(a,b);b=W(m.Sun,a,!0);var d=Y(a);c=new E(c[0]-d.x,c[1]-d.y,c[2]-d.z,a);d.x-=b.x;d.y-=b.y;d.z-= +b.z;return Za(1737.4,a,c,d)}function rb(a,b,c){a=W(a,c,!0);var d=W(m.Sun,c,!0),f=new E(a.x-d.x,a.y-d.y,a.z-d.z,c);d.x=-a.x;d.y=-a.y;d.z=-a.z;return Za(b,c,d,f)}function Qb(a,b){var c=1/86400,d=b.AddDays(-c);b=b.AddDays(+c);d=a(d);return(a(b).r-d.r)/c}function yd(a){var b=a.AddDays(-.03);a=a.AddDays(.03);b=K(function(c){return Qb(qb,c)},b,a);if(!b)throw"Failed to find peak Earth shadow time.";return qb(b)}function zd(a){var b=a.AddDays(-.03);a=a.AddDays(.03);b=K(function(c){return Qb(Kc,c)},b,a);if(!b)throw"Failed to find peak Moon shadow time."; +return Kc(b)}function Ad(a,b,c){var d=c.AddDays(-1);c=c.AddDays(1);d=K(function(f){var g=1/86400,h=rb(a,b,f.AddDays(-g));return(rb(a,b,f.AddDays(+g)).r-h.r)/g},d,c);if(!d)throw"Failed to find peak planet shadow time.";return rb(a,b,d)}function Bd(a,b){function c(g){return Pb(g,b)}var d=a.AddDays(-.2),f=a.AddDays(.2);d=K(function(g){return Qb(c,g)},d,f);if(!d)throw"PeakLocalMoonShadow: search failure for search_center_time = "+a;return Pb(d,b)}function Rb(a,b,c){var d=c/1440;c=a.AddDays(-d);d=a.AddDays(+d); +c=K(function(f){return-(qb(f).r-b)},c,a);a=K(function(f){return+(qb(f).r-b)},a,d);if(!c||!a)throw"Failed to find shadow semiduration";return 720*(a.ut-c.ut)}function Sb(a){a=ea(a);return e.RAD2DEG*a.geo_eclip_lat}function Lc(a,b,c){if(0>=a)throw"Radius of first disc must be positive.";if(0>=b)throw"Radius of second disc must be positive.";if(0>c)throw"Distance between discs is not allowed to be negative.";if(c>=a+b)return 0;if(0==c)return a<=b?1:b*b/(a*a);var d=(a*a-b*b+c*c)/(2*c),f=a*a-d*d;if(0>= +f)return a<=b?1:b*b/(a*a);f=Math.sqrt(f);return(a*a*Math.acos(d/a)-d*f+(b*b*Math.acos((c-d)/b)-(c-d)*f))/(Math.PI*a*a)}function Mc(a,b){var c=new E(a.x+b.x,a.y+b.y,a.z+b.z,a.t);a=Math.asin(Nc/c.Length());var d=Math.asin(Cd/b.Length());b=N(b,c);b=Lc(a,d,b*e.DEG2RAD);return Math.min(.9999,b)}function Oc(a){a=v(a);for(var b=0;12>b;++b){var c=Wa(180,a,40);if(!c)throw"Cannot find full moon.";a=Sb(c);if(1.8>Math.abs(a)&&(a=yd(c),a.rb;++b){var c=Wa(0,a,40);if(!c)throw"Cannot find new moon";a=Sb(c);if(1.8>Math.abs(a)&&(a=zd(c),a.r=d?d+=360:180h.r)throw"Unexpected shadow distance from geoid intersection = "+h.r;g=.014Math.abs(c)){var d=Bd(a,b);if(d.rHa(a,d)&&(b=Ad(a,c,d),b.r=c.lat*f.lat){a.$jscomp$loop$prop$kind$33=f.lat>c.lat?ra.Ascending:ra.Descending;b=K(function(g){return function(h){return g.$jscomp$loop$prop$kind$33* +ib(h).lat}}(a),b,d);if(!b)throw"Could not find moon node.";return new bd(a.$jscomp$loop$prop$kind$33,b)}b=d;c=f}}function cd(a,b,c,d,f){if(1>a||5=c)throw"Major mass must be a positive number.";if(!Number.isFinite(f)||0>=f)throw"Minor mass must be a negative number.";var g=d.x-b.x,h=d.y-b.y,l=d.z-b.z,k=g*g+h*h+l*l,n=Math.sqrt(k),p=d.vx-b.vx,q=d.vy-b.vy;d=d.vz-b.vz;if(4===a||5===a){k=h*d-l*q;c=l*p-g*d;var t=g*q-h*p,y=c*l-t*h;t=t*g-k*l;k= +k*h-c*g;c=Math.sqrt(y*y+t*t+k*k);y/=c;t/=c;k/=c;g/=n;h/=n;l/=n;a=4==a?.8660254037844386:-.8660254037844386;c=.5*g+a*y;f=.5*h+a*t;var x=.5*l+a*k,z=p*g+q*h+d*l;p=p*y+q*t+d*k;b=new I(n*c,n*f,n*x,z*c+p*(.5*y-a*g),z*f+p*(.5*t-a*h),z*x+p*(.5*k-a*l),b.t)}else{y=f/(c+f)*-n;t=c/(c+f)*+n;k=(c+f)/(k*n);if(1===a||2===a)x=c/(c+f)*Math.cbrt(f/(3*c)),c=-c,1==a?(x=1-x,a=+f):(x=1+x,a=-f);else if(3===a)x=(7/12*f-c)/(f+c),c=+c,a=+f;else throw"Invalid Langrage point "+a+". Must be an integer 1..5.";f=n*x-y;do x=f-y, +z=f-t,x=(k*f+c/(x*x)+a/(z*z))/(k-2*c/(x*x*x)-2*a/(z*z*z)),f-=x;while(1E-14b||24<=b)throw"Invalid right ascension for star: "+b;if(-90>c||90d)throw"Invalid star distance: "+d;f.ra=b;f.dec=c;f.dist=d*e.AU_PER_LY};var F;(function(a){a[a.From2000=0]="From2000";a[a.Into2000=1]="Into2000"})(F||(F={}));var aa={Mercury:{OrbitalPeriod:87.969},Venus:{OrbitalPeriod:224.701},Earth:{OrbitalPeriod:365.256},Mars:{OrbitalPeriod:686.98},Jupiter:{OrbitalPeriod:4332.589},Saturn:{OrbitalPeriod:10759.22},Uranus:{OrbitalPeriod:30685.4},Neptune:{OrbitalPeriod:60189}, +Pluto:{OrbitalPeriod:90560}};e.PlanetOrbitalPeriod=function(a){if(a in aa)return aa[a].OrbitalPeriod;throw"Unknown orbital period for: "+a;};var M={Mercury:[[[[4.40250710144,0,0],[.40989414977,1.48302034195,26087.9031415742],[.050462942,4.47785489551,52175.8062831484],[.00855346844,1.16520322459,78263.70942472259],[.00165590362,4.11969163423,104351.61256629678],[3.4561897E-4,.77930768443,130439.51570787099],[7.583476E-5,3.71348404924,156527.41884944518]],[[26087.90313685529,0,0],[.01131199811,6.21874197797, +26087.9031415742],[.00292242298,3.04449355541,52175.8062831484],[7.5775081E-4,6.08568821653,78263.70942472259],[1.9676525E-4,2.80965111777,104351.61256629678]]],[[[.11737528961,1.98357498767,26087.9031415742],[.02388076996,5.03738959686,52175.8062831484],[.01222839532,3.14159265359,0],[.0054325181,1.79644363964,78263.70942472259],[.0012977877,4.83232503958,104351.61256629678],[3.1866927E-4,1.58088495658,130439.51570787099],[7.963301E-5,4.60972126127,156527.41884944518]],[[.00274646065,3.95008450011, +26087.9031415742],[9.9737713E-4,3.14159265359,0]]],[[[.39528271651,0,0],[.07834131818,6.19233722598,26087.9031415742],[.00795525558,2.95989690104,52175.8062831484],[.00121281764,6.01064153797,78263.70942472259],[2.1921969E-4,2.77820093972,104351.61256629678],[4.354065E-5,5.82894543774,130439.51570787099]],[[.0021734774,4.65617158665,26087.9031415742],[4.4141826E-4,1.42385544001,52175.8062831484]]]],Venus:[[[[3.17614666774,0,0],[.01353968419,5.59313319619,10213.285546211],[8.9891645E-4,5.30650047764, +20426.571092422],[5.477194E-5,4.41630661466,7860.4193924392],[3.455741E-5,2.6996444782,11790.6290886588],[2.372061E-5,2.99377542079,3930.2096962196],[1.317168E-5,5.18668228402,26.2983197998],[1.664146E-5,4.25018630147,1577.3435424478],[1.438387E-5,4.15745084182,9683.5945811164],[1.200521E-5,6.15357116043,30639.856638633]],[[10213.28554621638,0,0],[9.5617813E-4,2.4640651111,10213.285546211],[7.787201E-5,.6247848222,20426.571092422]]],[[[.05923638472,.26702775812,10213.285546211],[4.0107978E-4,1.14737178112, +20426.571092422],[3.2814918E-4,3.14159265359,0]],[[.00287821243,1.88964962838,10213.285546211]]],[[[.72334820891,0,0],[.00489824182,4.02151831717,10213.285546211],[1.658058E-5,4.90206728031,20426.571092422],[1.378043E-5,1.12846591367,11790.6290886588],[1.632096E-5,2.84548795207,7860.4193924392],[4.98395E-6,2.58682193892,9683.5945811164],[2.21985E-6,2.01346696541,19367.1891622328],[2.37454E-6,2.55136053886,15720.8387848784]],[[3.4551041E-4,.89198706276,10213.285546211]]]],Earth:[[[[1.75347045673,0, +0],[.03341656453,4.66925680415,6283.0758499914],[3.4894275E-4,4.62610242189,12566.1516999828],[3.417572E-5,2.82886579754,3.523118349],[3.497056E-5,2.74411783405,5753.3848848968],[3.135899E-5,3.62767041756,77713.7714681205],[2.676218E-5,4.41808345438,7860.4193924392],[2.342691E-5,6.13516214446,3930.2096962196],[1.273165E-5,2.03709657878,529.6909650946],[1.324294E-5,.74246341673,11506.7697697936],[9.01854E-6,2.04505446477,26.2983197998],[1.199167E-5,1.10962946234,1577.3435424478],[8.57223E-6,3.50849152283, +398.1490034082],[7.79786E-6,1.17882681962,5223.6939198022],[9.9025E-6,5.23268072088,5884.9268465832],[7.53141E-6,2.53339052847,5507.5532386674],[5.05267E-6,4.58292599973,18849.2275499742],[4.92392E-6,4.20505711826,775.522611324],[3.56672E-6,2.91954114478,.0673103028],[2.84125E-6,1.89869240932,796.2980068164],[2.42879E-6,.34481445893,5486.777843175],[3.17087E-6,5.84901948512,11790.6290886588],[2.71112E-6,.31486255375,10977.078804699],[2.06217E-6,4.80646631478,2544.3144198834],[2.05478E-6,1.86953770281, +5573.1428014331],[2.02318E-6,2.45767790232,6069.7767545534],[1.26225E-6,1.08295459501,20.7753954924],[1.55516E-6,.83306084617,213.299095438]],[[6283.0758499914,0,0],[.00206058863,2.67823455808,6283.0758499914],[4.303419E-5,2.63512233481,12566.1516999828]],[[8.721859E-5,1.07253635559,6283.0758499914]]],[[],[[.00227777722,3.4137662053,6283.0758499914],[3.805678E-5,3.37063423795,12566.1516999828]]],[[[1.00013988784,0,0],[.01670699632,3.09846350258,6283.0758499914],[1.3956024E-4,3.05524609456,12566.1516999828], +[3.08372E-5,5.19846674381,77713.7714681205],[1.628463E-5,1.17387558054,5753.3848848968],[1.575572E-5,2.84685214877,7860.4193924392],[9.24799E-6,5.45292236722,11506.7697697936],[5.42439E-6,4.56409151453,3930.2096962196],[4.7211E-6,3.66100022149,5884.9268465832],[8.5831E-7,1.27079125277,161000.6857376741],[5.7056E-7,2.01374292245,83996.84731811189],[5.5736E-7,5.2415979917,71430.69561812909],[1.74844E-6,3.01193636733,18849.2275499742],[2.43181E-6,4.2734953079,11790.6290886588]],[[.00103018607,1.10748968172, +6283.0758499914],[1.721238E-5,1.06442300386,12566.1516999828]],[[4.359385E-5,5.78455133808,6283.0758499914]]]],Mars:[[[[6.20347711581,0,0],[.18656368093,5.0503710027,3340.6124266998],[.01108216816,5.40099836344,6681.2248533996],[9.1798406E-4,5.75478744667,10021.8372800994],[2.7744987E-4,5.97049513147,3.523118349],[1.0610235E-4,2.93958560338,2281.2304965106],[1.2315897E-4,.84956094002,2810.9214616052],[8.926784E-5,4.15697846427,.0172536522],[8.715691E-5,6.11005153139,13362.4497067992],[6.797556E-5, +.36462229657,398.1490034082],[7.774872E-5,3.33968761376,5621.8429232104],[3.575078E-5,1.6618650571,2544.3144198834],[4.161108E-5,.22814971327,2942.4634232916],[3.075252E-5,.85696614132,191.4482661116],[2.628117E-5,.64806124465,3337.0893083508],[2.937546E-5,6.07893711402,.0673103028],[2.389414E-5,5.03896442664,796.2980068164],[2.579844E-5,.02996736156,3344.1355450488],[1.528141E-5,1.14979301996,6151.533888305],[1.798806E-5,.65634057445,529.6909650946],[1.264357E-5,3.62275122593,5092.1519581158],[1.286228E-5, +3.06796065034,2146.1654164752],[1.546404E-5,2.91579701718,1751.539531416],[1.024902E-5,3.69334099279,8962.4553499102],[8.91566E-6,.18293837498,16703.062133499],[8.58759E-6,2.4009381194,2914.0142358238],[8.32715E-6,2.46418619474,3340.5951730476],[8.3272E-6,4.49495782139,3340.629680352],[7.12902E-6,3.66335473479,1059.3819301892],[7.48723E-6,3.82248614017,155.4203994342],[7.23861E-6,.67497311481,3738.761430108],[6.35548E-6,2.92182225127,8432.7643848156],[6.55162E-6,.48864064125,3127.3133312618],[5.50474E-6, +3.81001042328,.9803210682],[5.5275E-6,4.47479317037,1748.016413067],[4.25966E-6,.55364317304,6283.0758499914],[4.15131E-6,.49662285038,213.299095438],[4.72167E-6,3.62547124025,1194.4470102246],[3.06551E-6,.38052848348,6684.7479717486],[3.12141E-6,.99853944405,6677.7017350506],[2.93198E-6,4.22131299634,20.7753954924],[3.02375E-6,4.48618007156,3532.0606928114],[2.74027E-6,.54222167059,3340.545116397],[2.81079E-6,5.88163521788,1349.8674096588],[2.31183E-6,1.28242156993,3870.3033917944],[2.83602E-6,5.7688543494, +3149.1641605882],[2.36117E-6,5.75503217933,3333.498879699],[2.74033E-6,.13372524985,3340.6797370026],[2.99395E-6,2.78323740866,6254.6266625236]],[[3340.61242700512,0,0],[.01457554523,3.60433733236,3340.6124266998],[.00168414711,3.92318567804,6681.2248533996],[2.0622975E-4,4.26108844583,10021.8372800994],[3.452392E-5,4.7321039319,3.523118349],[2.586332E-5,4.60670058555,13362.4497067992],[8.41535E-6,4.45864030426,2281.2304965106]],[[5.8152577E-4,2.04961712429,3340.6124266998],[1.3459579E-4,2.45738706163, +6681.2248533996]]],[[[.03197134986,3.76832042431,3340.6124266998],[.00298033234,4.10616996305,6681.2248533996],[.00289104742,0,0],[3.1365539E-4,4.4465105309,10021.8372800994],[3.4841E-5,4.7881254926,13362.4497067992]],[[.00217310991,6.04472194776,3340.6124266998],[2.0976948E-4,3.14159265359,0],[1.2834709E-4,1.60810667915,6681.2248533996]]],[[[1.53033488271,0,0],[.1418495316,3.47971283528,3340.6124266998],[.00660776362,3.81783443019,6681.2248533996],[4.6179117E-4,4.15595316782,10021.8372800994],[8.109733E-5, +5.55958416318,2810.9214616052],[7.485318E-5,1.77239078402,5621.8429232104],[5.523191E-5,1.3643630377,2281.2304965106],[3.82516E-5,4.49407183687,13362.4497067992],[2.306537E-5,.09081579001,2544.3144198834],[1.999396E-5,5.36059617709,3337.0893083508],[2.484394E-5,4.9254563992,2942.4634232916],[1.960195E-5,4.74249437639,3344.1355450488],[1.167119E-5,2.11260868341,5092.1519581158],[1.102816E-5,5.00908403998,398.1490034082],[8.99066E-6,4.40791133207,529.6909650946],[9.92252E-6,5.83861961952,6151.533888305], +[8.07354E-6,2.10217065501,1059.3819301892],[7.97915E-6,3.44839203899,796.2980068164],[7.40975E-6,1.49906336885,2146.1654164752]],[[.01107433345,2.03250524857,3340.6124266998],[.00103175887,2.37071847807,6681.2248533996],[1.28772E-4,0,0],[1.081588E-4,2.70888095665,10021.8372800994]],[[4.4242249E-4,.47930604954,3340.6124266998],[8.138042E-5,.86998389204,6681.2248533996]]]],Jupiter:[[[[.59954691494,0,0],[.09695898719,5.06191793158,529.6909650946],[.00573610142,1.44406205629,7.1135470008],[.00306389205, +5.41734730184,1059.3819301892],[9.7178296E-4,4.14264726552,632.7837393132],[7.2903078E-4,3.64042916389,522.5774180938],[6.4263975E-4,3.41145165351,103.0927742186],[3.9806064E-4,2.29376740788,419.4846438752],[3.8857767E-4,1.27231755835,316.3918696566],[2.7964629E-4,1.7845459182,536.8045120954],[1.358973E-4,5.7748104079,1589.0728952838],[8.246349E-5,3.5822792584,206.1855484372],[8.768704E-5,3.63000308199,949.1756089698],[7.368042E-5,5.0810119427,735.8765135318],[6.26315E-5,.02497628807,213.299095438], +[6.114062E-5,4.51319998626,1162.4747044078],[4.905396E-5,1.32084470588,110.2063212194],[5.305285E-5,1.30671216791,14.2270940016],[5.305441E-5,4.18625634012,1052.2683831884],[4.647248E-5,4.69958103684,3.9321532631],[3.045023E-5,4.31676431084,426.598190876],[2.609999E-5,1.56667394063,846.0828347512],[2.028191E-5,1.06376530715,3.1813937377],[1.764763E-5,2.14148655117,1066.49547719],[1.722972E-5,3.88036268267,1265.5674786264],[1.920945E-5,.97168196472,639.897286314],[1.633223E-5,3.58201833555,515.463871093], +[1.431999E-5,4.29685556046,625.6701923124],[9.73272E-6,4.09764549134,95.9792272178]],[[529.69096508814,0,0],[.00489503243,4.2208293947,529.6909650946],[.00228917222,6.02646855621,7.1135470008],[3.0099479E-4,4.54540782858,1059.3819301892],[2.072092E-4,5.45943156902,522.5774180938],[1.2103653E-4,.16994816098,536.8045120954],[6.067987E-5,4.42422292017,103.0927742186],[5.433968E-5,3.98480737746,419.4846438752],[4.237744E-5,5.89008707199,14.2270940016]],[[4.7233601E-4,4.32148536482,7.1135470008],[3.0649436E-4, +2.929777887,529.6909650946],[1.4837605E-4,3.14159265359,0]]],[[[.02268615702,3.55852606721,529.6909650946],[.00109971634,3.90809347197,1059.3819301892],[.00110090358,0,0],[8.101428E-5,3.60509572885,522.5774180938],[6.043996E-5,4.25883108339,1589.0728952838],[6.437782E-5,.30627119215,536.8045120954]],[[7.8203446E-4,1.52377859742,529.6909650946]]],[[[5.20887429326,0,0],[.25209327119,3.49108639871,529.6909650946],[.00610599976,3.84115365948,1059.3819301892],[.00282029458,2.57419881293,632.7837393132], +[.00187647346,2.07590383214,522.5774180938],[8.6792905E-4,.71001145545,419.4846438752],[7.2062974E-4,.21465724607,536.8045120954],[6.5517248E-4,5.9799588479,316.3918696566],[2.9134542E-4,1.67759379655,103.0927742186],[3.0135335E-4,2.16132003734,949.1756089698],[2.3453271E-4,3.54023522184,735.8765135318],[2.2283743E-4,4.19362594399,1589.0728952838],[2.3947298E-4,.2745803748,7.1135470008],[1.3032614E-4,2.96042965363,1162.4747044078],[9.70336E-5,1.90669633585,206.1855484372],[1.2749023E-4,2.71550286592, +1052.2683831884],[7.057931E-5,2.18184839926,1265.5674786264],[6.137703E-5,6.26418240033,846.0828347512],[2.616976E-5,2.00994012876,1581.959348283]],[[.0127180152,2.64937512894,529.6909650946],[6.1661816E-4,3.00076460387,1059.3819301892],[5.3443713E-4,3.89717383175,522.5774180938],[3.1185171E-4,4.88276958012,536.8045120954],[4.1390269E-4,0,0]]]],Saturn:[[[[.87401354025,0,0],[.11107659762,3.96205090159,213.299095438],[.01414150957,4.58581516874,7.1135470008],[.00398379389,.52112032699,206.1855484372], +[.00350769243,3.30329907896,426.598190876],[.00206816305,.24658372002,103.0927742186],[7.92713E-4,3.84007056878,220.4126424388],[2.3990355E-4,4.66976924553,110.2063212194],[1.6573588E-4,.43719228296,419.4846438752],[1.4906995E-4,5.76903183869,316.3918696566],[1.582029E-4,.93809155235,632.7837393132],[1.4609559E-4,1.56518472,3.9321532631],[1.3160301E-4,4.44891291899,14.2270940016],[1.5053543E-4,2.71669915667,639.897286314],[1.3005299E-4,5.98119023644,11.0457002639],[1.0725067E-4,3.12939523827,202.2533951741], +[5.863206E-5,.23656938524,529.6909650946],[5.227757E-5,4.20783365759,3.1813937377],[6.126317E-5,1.76328667907,277.0349937414],[5.019687E-5,3.17787728405,433.7117378768],[4.59255E-5,.61977744975,199.0720014364],[4.005867E-5,2.24479718502,63.7358983034],[2.953796E-5,.98280366998,95.9792272178],[3.87367E-5,3.22283226966,138.5174968707],[2.461186E-5,2.03163875071,735.8765135318],[3.269484E-5,.77492638211,949.1756089698],[1.758145E-5,3.2658010994,522.5774180938],[1.640172E-5,5.5050445305,846.0828347512], +[1.391327E-5,4.02333150505,323.5054166574],[1.580648E-5,4.37265307169,309.2783226558],[1.123498E-5,2.83726798446,415.5524906121],[1.017275E-5,3.71700135395,227.5261894396],[8.48642E-6,3.1915017083,209.3669421749]],[[213.2990952169,0,0],[.01297370862,1.82834923978,213.299095438],[.00564345393,2.88499717272,7.1135470008],[9.3734369E-4,1.06311793502,426.598190876],[.00107674962,2.27769131009,206.1855484372],[4.0244455E-4,2.04108104671,220.4126424388],[1.9941774E-4,1.2795439047,103.0927742186],[1.0511678E-4, +2.7488034213,14.2270940016],[6.416106E-5,.38238295041,639.897286314],[4.848994E-5,2.43037610229,419.4846438752],[4.056892E-5,2.92133209468,110.2063212194],[3.768635E-5,3.6496533078,3.9321532631]],[[.0011644133,1.17988132879,7.1135470008],[9.1841837E-4,.0732519584,213.299095438],[3.6661728E-4,0,0],[1.5274496E-4,4.06493179167,206.1855484372]]],[[[.04330678039,3.60284428399,213.299095438],[.00240348302,2.85238489373,426.598190876],[8.4745939E-4,0,0],[3.0863357E-4,3.48441504555,220.4126424388],[3.4116062E-4, +.57297307557,206.1855484372],[1.473407E-4,2.11846596715,639.897286314],[9.916667E-5,5.79003188904,419.4846438752],[6.993564E-5,4.7360468972,7.1135470008],[4.807588E-5,5.43305312061,316.3918696566]],[[.00198927992,4.93901017903,213.299095438],[3.6947916E-4,3.14159265359,0],[1.7966989E-4,.5197943111,426.598190876]]],[[[9.55758135486,0,0],[.52921382865,2.39226219573,213.299095438],[.01873679867,5.2354960466,206.1855484372],[.01464663929,1.64763042902,426.598190876],[.00821891141,5.93520042303,316.3918696566], +[.00547506923,5.0153261898,103.0927742186],[.0037168465,2.27114821115,220.4126424388],[.00361778765,3.13904301847,7.1135470008],[.00140617506,5.70406606781,632.7837393132],[.00108974848,3.29313390175,110.2063212194],[6.9006962E-4,5.94099540992,419.4846438752],[6.1053367E-4,.94037691801,639.897286314],[4.8913294E-4,1.55733638681,202.2533951741],[3.4143772E-4,.19519102597,277.0349937414],[3.2401773E-4,5.47084567016,949.1756089698],[2.0936596E-4,.46349251129,735.8765135318],[9.796004E-5,5.20477537945, +1265.5674786264],[1.1993338E-4,5.98050967385,846.0828347512],[2.08393E-4,1.52102476129,433.7117378768],[1.5298404E-4,3.0594381494,529.6909650946],[6.465823E-5,.17732249942,1052.2683831884],[1.1380257E-4,1.7310542704,522.5774180938],[3.419618E-5,4.94550542171,1581.959348283]],[[.0618298134,.2584351148,213.299095438],[.00506577242,.71114625261,206.1855484372],[.00341394029,5.79635741658,426.598190876],[.00188491195,.47215589652,220.4126424388],[.00186261486,3.14159265359,0],[.00143891146,1.40744822888, +7.1135470008]],[[.00436902572,4.78671677509,213.299095438]]]],Uranus:[[[[5.48129294297,0,0],[.09260408234,.89106421507,74.7815985673],[.01504247898,3.6271926092,1.4844727083],[.00365981674,1.89962179044,73.297125859],[.00272328168,3.35823706307,149.5631971346],[7.0328461E-4,5.39254450063,63.7358983034],[6.8892678E-4,6.09292483287,76.2660712756],[6.1998615E-4,2.26952066061,2.9689454166],[6.1950719E-4,2.85098872691,11.0457002639],[2.646877E-4,3.14152083966,71.8126531507],[2.5710476E-4,6.11379840493, +454.9093665273],[2.107885E-4,4.36059339067,148.0787244263],[1.7818647E-4,1.74436930289,36.6485629295],[1.4613507E-4,4.73732166022,3.9321532631],[1.1162509E-4,5.8268179635,224.3447957019],[1.099791E-4,.48865004018,138.5174968707],[9.527478E-5,2.95516862826,35.1640902212],[7.545601E-5,5.236265824,109.9456887885],[4.220241E-5,3.23328220918,70.8494453042],[4.0519E-5,2.277550173,151.0476698429],[3.354596E-5,1.0654900738,4.4534181249],[2.926718E-5,4.62903718891,9.5612275556],[3.49034E-5,5.48306144511,146.594251718], +[3.144069E-5,4.75199570434,77.7505439839],[2.922333E-5,5.35235361027,85.8272988312],[2.272788E-5,4.36600400036,70.3281804424],[2.051219E-5,1.51773566586,.1118745846],[2.148602E-5,.60745949945,38.1330356378],[1.991643E-5,4.92437588682,277.0349937414],[1.376226E-5,2.04283539351,65.2203710117],[1.666902E-5,3.62744066769,380.12776796],[1.284107E-5,3.11347961505,202.2533951741],[1.150429E-5,.93343589092,3.1813937377],[1.533221E-5,2.58594681212,52.6901980395],[1.281604E-5,.54271272721,222.8603229936],[1.372139E-5, +4.19641530878,111.4301614968],[1.221029E-5,.1990065003,108.4612160802],[9.46181E-6,1.19253165736,127.4717966068],[1.150989E-5,4.17898916639,33.6796175129]],[[74.7815986091,0,0],[.00154332863,5.24158770553,74.7815985673],[2.4456474E-4,1.71260334156,1.4844727083],[9.258442E-5,.4282973235,11.0457002639],[8.265977E-5,1.50218091379,63.7358983034],[9.15016E-5,1.41213765216,149.5631971346]]],[[[.01346277648,2.61877810547,74.7815985673],[6.23414E-4,5.08111189648,149.5631971346],[6.1601196E-4,3.14159265359, +0],[9.963722E-5,1.61603805646,76.2660712756],[9.92616E-5,.57630380333,73.297125859]],[[3.4101978E-4,.01321929936,74.7815985673]]],[[[19.21264847206,0,0],[.88784984413,5.60377527014,74.7815985673],[.03440836062,.32836099706,73.297125859],[.0205565386,1.7829515933,149.5631971346],[.0064932241,4.52247285911,76.2660712756],[.00602247865,3.86003823674,63.7358983034],[.00496404167,1.40139935333,454.9093665273],[.00338525369,1.58002770318,138.5174968707],[.00243509114,1.57086606044,71.8126531507],[.00190522303, +1.99809394714,1.4844727083],[.00161858838,2.79137786799,148.0787244263],[.00143706183,1.38368544947,11.0457002639],[9.3192405E-4,.17437220467,36.6485629295],[7.1424548E-4,4.24509236074,224.3447957019],[8.9806014E-4,3.66105364565,109.9456887885],[3.9009723E-4,1.66971401684,70.8494453042],[4.6677296E-4,1.39976401694,35.1640902212],[3.9025624E-4,3.36234773834,277.0349937414],[3.6755274E-4,3.88649278513,146.594251718],[3.0348723E-4,.70100838798,151.0476698429],[2.9156413E-4,3.180563367,77.7505439839], +[2.2637073E-4,.72518687029,529.6909650946],[1.1959076E-4,1.7504339214,984.6003316219],[2.5620756E-4,5.25656086672,380.12776796]],[[.01479896629,3.67205697578,74.7815985673]]]],Neptune:[[[[5.31188633046,0,0],[.0179847553,2.9010127389,38.1330356378],[.01019727652,.48580922867,1.4844727083],[.00124531845,4.83008090676,36.6485629295],[4.2064466E-4,5.41054993053,2.9689454166],[3.7714584E-4,6.09221808686,35.1640902212],[3.3784738E-4,1.24488874087,76.2660712756],[1.6482741E-4,7.727998E-5,491.5579294568], +[9.198584E-5,4.93747051954,39.6175083461],[8.99425E-5,.27462171806,175.1660598002]],[[38.13303563957,0,0],[1.6604172E-4,4.86323329249,1.4844727083],[1.5744045E-4,2.27887427527,38.1330356378]]],[[[.03088622933,1.44104372644,38.1330356378],[2.7780087E-4,5.91271884599,76.2660712756],[2.7623609E-4,0,0],[1.5355489E-4,2.52123799551,36.6485629295],[1.5448133E-4,3.50877079215,39.6175083461]]],[[[30.07013205828,0,0],[.27062259632,1.32999459377,38.1330356378],[.01691764014,3.25186135653,36.6485629295],[.00807830553, +5.18592878704,1.4844727083],[.0053776051,4.52113935896,35.1640902212],[.00495725141,1.5710564165,491.5579294568],[.00274571975,1.84552258866,175.1660598002],[1.201232E-4,1.92059384991,1021.2488945514],[.00121801746,5.79754470298,76.2660712756],[.00100896068,.3770272493,73.297125859],[.00135134092,3.37220609835,39.6175083461],[7.571796E-5,1.07149207335,388.4651552382]]]]};e.DeltaT_EspenakMeeus=sa;e.DeltaT_JplHorizons=function(a){return sa(Math.min(a,17*365.24217))};var Wb=sa;e.SetDeltaTFunction=function(a){Wb= +a};var O=function(a){if(a instanceof O)this.date=a.date,this.ut=a.ut,this.tt=a.tt;else if(a instanceof Date&&Number.isFinite(a.getTime()))this.date=a,this.ut=(a.getTime()-dd.getTime())/864E5,this.tt=Vb(this.ut);else if(Number.isFinite(a))this.date=new Date(dd.getTime()+864E5*a),this.ut=a,this.tt=Vb(this.ut);else throw"Argument must be a Date object, an AstroTime object, or a numeric UTC Julian date.";};O.FromTerrestrialTime=function(a){for(var b=new O(a);;){var c=a-b.tt;if(1E-12>Math.abs(c))return b; +b=b.AddDays(c)}};O.prototype.toString=function(){return this.date.toISOString()};O.prototype.AddDays=function(a){return new O(this.ut+a)};e.AstroTime=O;e.MakeTime=v;var $a;e.e_tilt=da;e.CalcMoonCount=0;var ed=function(a,b,c,d,f,g){this.elat=a;this.elon=b;this.mlat=c;this.mlon=d;this.dist_km=f;this.diam_deg=g};e.LibrationInfo=ed;e.Libration=function(a){var b=v(a);a=b.tt/36525;var c=a*a,d=c*a,f=c*c,g=ea(b);b=g.geo_eclip_lon;var h=g.geo_eclip_lat;g=g.distance_au*e.KM_PER_AU;var l=1.543*e.DEG2RAD,k=e.DEG2RAD* +Ga(93.272095+483202.0175233*a-.0036539*c-d/3526E3+f/86331E4),n=e.DEG2RAD*Ga(125.0445479-1934.1362891*a+.0020754*c+d/467441-f/60616E3),p=e.DEG2RAD*Ga(357.5291092+35999.0502909*a-1.536E-4*c+d/2449E4),q=e.DEG2RAD*Ga(134.9633964+477198.8675055*a+.0087414*c+d/69699-f/14712E3);d=e.DEG2RAD*Ga(297.8501921+445267.1114034*a-.0018819*c+d/545868-f/113065E3);c=1-.002516*a-7.4E-6*c;var t=b-n;f=Math.atan2(Math.sin(t)*Math.cos(h)*Math.cos(l)-Math.sin(h)*Math.sin(l),Math.cos(t)*Math.cos(h));var y=Fa(e.RAD2DEG*(f- +k));l=Math.asin(-Math.sin(t)*Math.cos(h)*Math.sin(l)-Math.sin(h)*Math.cos(l));t=-.02752*Math.cos(q)+-.02245*Math.sin(k)+.00684*Math.cos(q-2*k)+-.00293*Math.cos(2*k)+-8.5E-4*Math.cos(2*k-2*d)+-5.4E-4*Math.cos(q-2*d)+-2E-4*Math.sin(q+k)+-2E-4*Math.cos(q+2*k)+-2E-4*Math.cos(q-k)+1.4E-4*Math.cos(q+2*k-2*d);var x=-.02816*Math.sin(q)+.02244*Math.cos(k)+-.00682*Math.sin(q-2*k)+-.00279*Math.sin(2*k)+-8.3E-4*Math.sin(2*k-2*d)+6.9E-4*Math.sin(q-2*d)+4E-4*Math.cos(q+k)+-2.5E-4*Math.sin(2*q)+-2.3E-4*Math.sin(q+ +2*k)+2E-4*Math.cos(q-k)+1.9E-4*Math.sin(q-k)+1.3E-4*Math.sin(q+2*k-2*d)+-1E-4*Math.cos(q-3*k);return new ed(e.RAD2DEG*l+(x*Math.cos(f)-t*Math.sin(f)),y+(-(.0252*c*Math.sin(p)+.00473*Math.sin(2*q-2*k)+-.00467*Math.sin(q)+.00396*Math.sin(e.DEG2RAD*(119.75+131.849*a))+.00276*Math.sin(2*q-2*d)+.00196*Math.sin(n)+-.00183*Math.cos(q-k)+.00115*Math.sin(q-2*d)+-9.6E-4*Math.sin(q-d)+4.6E-4*Math.sin(2*k-2*d)+-3.9E-4*Math.sin(q-k)+-3.2E-4*Math.sin(q-p-d)+2.7E-4*Math.sin(2*q-p-2*d)+2.3E-4*Math.sin(e.DEG2RAD* +(72.56+20.186*a))+-1.4E-4*Math.sin(2*d)+1.4E-4*Math.cos(2*q-2*k)+-1.2E-4*Math.sin(q-2*k)+-1.2E-4*Math.sin(2*q)+1.1E-4*Math.sin(2*q-2*p-2*d))+(t*Math.cos(f)+x*Math.sin(f))*Math.tan(l)),e.RAD2DEG*h,e.RAD2DEG*b,g,2*e.RAD2DEG*Math.atan(1737.4/Math.sqrt(g*g-1737.4*1737.4)))};var eb;e.SiderealTime=bc;var E=function(a,b,c,d){this.x=a;this.y=b;this.z=c;this.t=d};E.prototype.Length=function(){return Math.hypot(this.x,this.y,this.z)};e.Vector=E;var I=function(a,b,c,d,f,g,h){this.x=a;this.y=b;this.z=c;this.vx= +d;this.vy=f;this.vz=g;this.t=h};e.StateVector=I;var Ba=function(a,b,c){this.lat=w(a);this.lon=w(b);this.dist=w(c)};e.Spherical=Ba;var gb=function(a,b,c,d){this.ra=w(a);this.dec=w(b);this.dist=w(c);this.vec=d};e.EquatorialCoordinates=gb;var J=function(a){this.rot=a};e.RotationMatrix=J;e.MakeRotation=function(a){if(!qd(a))throw"Argument must be a [3][3] array of numbers";return new J(a)};var ec=function(a,b,c,d){this.azimuth=w(a);this.altitude=w(b);this.ra=w(c);this.dec=w(d)};e.HorizontalCoordinates= +ec;var gc=function(a,b,c){this.vec=a;this.elat=w(b);this.elon=w(c)};e.EclipticCoordinates=gc;e.Horizon=hb;var zb=function(a,b,c){this.latitude=a;this.longitude=b;this.height=c;za(this)};e.Observer=zb;e.SunPosition=fc;e.Equator=Pa;e.ObserverVector=function(a,b,c){a=v(a);var d=ca(a);b=xb(b,d).pos;c||(b=fb(b,a,F.Into2000));return yb(b,a)};e.ObserverState=function(a,b,c){a=v(a);var d=ca(a);b=xb(b,d);b=new I(b.pos[0],b.pos[1],b.pos[2],b.vel[0],b.vel[1],b.vel[2],a);return c?b:(c=F.Into2000,c===F.Into2000? +(d=Na(a,c),b=Ea(d,b),a=Ma(a,c),a=Ea(a,b)):(d=Ma(a,c),b=Ea(d,b),a=Na(a,c),a=Ea(a,b)),a)};e.VectorObserver=function(a,b){var c=ca(a.t),d=[a.x,a.y,a.z];b||(d=wa(d,a.t,F.From2000),d=xa(d,a.t,F.From2000));b=d[0]*e.KM_PER_AU;var f=d[1]*e.KM_PER_AU;d=d[2]*e.KM_PER_AU;a=Math.hypot(b,f);if(1E-6>a){c=0;var g=0=c;)c+=360;for(;180Math.abs(q))break;g-=q/(-42.69778487239616*((k-n)/h-n*k*-.006694397995865464/(-42.69778487239616*p))+d*f+a*b)}g*=e.RAD2DEG;h=6378.1366/h;d=Math.abs(f)>Math.abs(b)?d/f-.9933056020041345*h:a/b-h}return new zb(g,c,1E3*d)};e.ObserverGravity=function(a,b){a=Math.sin(a*e.DEG2RAD);a*=a;return 9.7803253359*(1+.00193185265241*a)/Math.sqrt(1-.00669437999013*a)*(1-(3.15704E-7-2.10269E-9* +a)*b+7.37452E-14*b*b)};e.Ecliptic=Qa;e.GeoMoon=Y;e.EclipticGeoMoon=ib;e.GeoMoonState=Ra;e.GeoEmbState=Bb;var na=[[-73E4,[-26.118207232108,-14.376168177825,3.384402515299],[.0016339372163656,-.0027861699588508,-.0013585880229445]],[-700800,[41.974905202127,-.448502952929,-12.770351505989],[7.3458569351457E-4,.0022785014891658,4.8619778602049E-4]],[-671600,[14.706930780744,44.269110540027,9.353698474772],[-.00210001479998,2.2295915939915E-4,7.0143443551414E-4]],[-642400,[-29.441003929957,-6.43016153057, +6.858481011305],[8.4495803960544E-4,-.0030783914758711,-.0012106305981192]],[-613200,[39.444396946234,-6.557989760571,-13.913760296463],[.0011480029005873,.0022400006880665,3.5168075922288E-4]],[-584E3,[20.2303809507,43.266966657189,7.382966091923],[-.0019754081700585,5.3457141292226E-4,7.5929169129793E-4]],[-554800,[-30.65832536462,2.093818874552,9.880531138071],[6.1010603013347E-5,-.0031326500935382,-9.9346125151067E-4]],[-525600,[35.737703251673,-12.587706024764,-14.677847247563],[.0015802939375649, +.0021347678412429,1.9074436384343E-4]],[-496400,[25.466295188546,41.367478338417,5.216476873382],[-.0018054401046468,8.328308359951E-4,8.0260156912107E-4]],[-467200,[-29.847174904071,10.636426313081,12.297904180106],[-6.3257063052907E-4,-.0029969577578221,-7.4476074151596E-4]],[-438E3,[30.774692107687,-18.236637015304,-14.945535879896],[.0020113162005465,.0019353827024189,-2.0937793168297E-6]],[-408800,[30.243153324028,38.656267888503,2.938501750218],[-.0016052508674468,.0011183495337525,8.3333973416824E-4]], +[-379600,[-27.288984772533,18.643162147874,14.023633623329],[-.0011856388898191,-.0027170609282181,-4.9015526126399E-4]],[-350400,[24.519605196774,-23.245756064727,-14.626862367368],[.0024322321483154,.0016062008146048,-2.3369181613312E-4]],[-321200,[34.505274805875,35.125338586954,.557361475637],[-.0013824391637782,.0013833397561817,8.4823598806262E-4]],[-292E3,[-23.275363915119,25.818514298769,15.055381588598],[-.0016062295460975,-.0023395961498533,-2.4377362639479E-4]],[-262800,[17.050384798092, +-27.180376290126,-13.608963321694],[.0028175521080578,.0011358749093955,-4.9548725258825E-4]],[-233600,[38.093671910285,30.880588383337,-1.843688067413],[-.0011317697153459,.0016128814698472,8.4177586176055E-4]],[-204400,[-18.197852930878,31.932869934309,15.438294826279],[-.0019117272501813,-.0019146495909842,-1.9657304369835E-5]],[-175200,[8.528924039997,-29.618422200048,-11.805400994258],[.0031034370787005,5.139363329243E-4,-7.7293066202546E-4]],[-146E3,[40.94685725864,25.904973592021,-4.256336240499], +[-8.3652705194051E-4,.0018129497136404,8.156422827306E-4]],[-116800,[-12.326958895325,36.881883446292,15.217158258711],[-.0021166103705038,-.001481442003599,1.7401209844705E-4]],[-87600,[-.633258375909,-30.018759794709,-9.17193287495],[.0032016994581737,-2.5279858672148E-4,-.0010411088271861]],[-58400,[42.936048423883,20.344685584452,-6.588027007912],[-5.0525450073192E-4,.0019910074335507,7.7440196540269E-4]],[-29200,[-5.975910552974,40.61180995846,14.470131723673],[-.0022184202156107,-.0010562361130164, +3.3652250216211E-4]],[0,[-9.875369580774,-27.978926224737,-5.753711824704],[.0030287533248818,-.0011276087003636,-.0012651326732361]],[29200,[43.958831986165,14.214147973292,-8.808306227163],[-1.4717608981871E-4,.0021404187242141,7.1486567806614E-4]],[58400,[.67813676352,43.094461639362,13.243238780721],[-.0022358226110718,-6.3233636090933E-4,4.7664798895648E-4]],[87600,[-18.282602096834,-23.30503958666,-1.766620508028],[.0025567245263557,-.0019902940754171,-.0013943491701082]],[116800,[43.873338744526, +7.700705617215,-10.814273666425],[2.3174803055677E-4,.0022402163127924,6.2988756452032E-4]],[146E3,[7.392949027906,44.382678951534,11.629500214854],[-.002193281545383,-2.1751799585364E-4,5.9556516201114E-4]],[175200,[-24.981690229261,-16.204012851426,2.466457544298],[.001819398914958,-.0026765419531201,-.0013848283502247]],[204400,[42.530187039511,.845935508021,-12.554907527683],[6.5059779150669E-4,.0022725657282262,5.1133743202822E-4]],[233600,[13.999526486822,44.462363044894,9.669418486465],[-.0021079296569252, +1.7533423831993E-4,6.9128485798076E-4]],[262800,[-29.184024803031,-7.371243995762,6.493275957928],[9.3581363109681E-4,-.0030610357109184,-.0012364201089345]],[292E3,[39.831980671753,-6.078405766765,-13.909815358656],[.0011117769689167,.0022362097830152,3.6230548231153E-4]],[321200,[20.294955108476,43.417190420251,7.450091985932],[-.0019742157451535,5.3102050468554E-4,7.5938408813008E-4]],[350400,[-30.66999230216,2.318743558955,9.973480913858],[4.5605107450676E-5,-.0031308219926928,-9.9066533301924E-4]], +[379600,[35.626122155983,-12.897647509224,-14.777586508444],[.0016015684949743,.0021171931182284,1.8002516202204E-4]],[408800,[26.133186148561,41.232139187599,5.00640132622],[-.0017857704419579,8.6046232702817E-4,8.0614690298954E-4]],[438E3,[-29.57674022923,11.863535943587,12.631323039872],[-7.2292830060955E-4,-.0029587820140709,-7.08242964503E-4]],[467200,[29.910805787391,-19.159019294,-15.013363865194],[.0020871080437997,.0018848372554514,-3.8528655083926E-5]],[496400,[31.375957451819,38.050372720763, +2.433138343754],[-.0015546055556611,.0011699815465629,8.3565439266001E-4]],[525600,[-26.360071336928,20.662505904952,14.414696258958],[-.0013142373118349,-.0026236647854842,-4.2542017598193E-4]],[554800,[22.599441488648,-24.508879898306,-14.484045731468],[.0025454108304806,.0014917058755191,-3.0243665086079E-4]],[584E3,[35.877864013014,33.894226366071,-.224524636277],[-.0012941245730845,.0014560427668319,8.4762160640137E-4]],[613200,[-21.538149762417,28.204068269761,15.321973799534],[-.001731211740901, +-.0021939631314577,-1.631691327518E-4]],[642400,[13.971521374415,-28.339941764789,-13.083792871886],[.0029334630526035,9.1860931752944E-4,-5.9939422488627E-4]],[671600,[39.526942044143,28.93989736011,-2.872799527539],[-.0010068481658095,.001702113288809,8.3578230511981E-4]],[700800,[-15.576200701394,34.399412961275,15.466033737854],[-.0020098814612884,-.0017191109825989,7.0414782780416E-5]],[73E4,[4.24325283709,-30.118201690825,-10.707441231349],[.0031725847067411,1.609846120227E-4,-9.0672150593868E-4]]], +B=function(a,b,c){this.x=a;this.y=b;this.z=c};B.prototype.clone=function(){return new B(this.x,this.y,this.z)};B.prototype.ToAstroVector=function(a){return new E(this.x,this.y,this.z,a)};B.zero=function(){return new B(0,0,0)};B.prototype.quadrature=function(){return this.x*this.x+this.y*this.y+this.z*this.z};B.prototype.add=function(a){return new B(this.x+a.x,this.y+a.y,this.z+a.z)};B.prototype.sub=function(a){return new B(this.x-a.x,this.y-a.y,this.z-a.z)};B.prototype.incr=function(a){this.x+=a.x; +this.y+=a.y;this.z+=a.z};B.prototype.decr=function(a){this.x-=a.x;this.y-=a.y;this.z-=a.z};B.prototype.mul=function(a){return new B(a*this.x,a*this.y,a*this.z)};B.prototype.div=function(a){return new B(this.x/a,this.y/a,this.z/a)};B.prototype.mean=function(a){return new B((this.x+a.x)/2,(this.y+a.y)/2,(this.z+a.z)/2)};B.prototype.neg=function(){return new B(-this.x,-this.y,-this.z)};var X=function(a,b,c){this.tt=a;this.r=b;this.v=c};X.prototype.clone=function(){return new X(this.tt,this.r,this.v)}; +X.prototype.sub=function(a){return new X(this.tt,this.r.sub(a.r),this.v.sub(a.v))};var Da=function(a){var b=new X(a,new B(0,0,0),new B(0,0,0));this.Jupiter=R(b,a,m.Jupiter,2.825345909524226E-7);this.Saturn=R(b,a,m.Saturn,8.459715185680659E-8);this.Uranus=R(b,a,m.Uranus,1.292024916781969E-8);this.Neptune=R(b,a,m.Neptune,1.524358900784276E-8);this.Jupiter.r.decr(b.r);this.Jupiter.v.decr(b.v);this.Saturn.r.decr(b.r);this.Saturn.v.decr(b.v);this.Uranus.r.decr(b.r);this.Uranus.v.decr(b.v);this.Neptune.r.decr(b.r); +this.Neptune.v.decr(b.v);this.Sun=new X(a,b.r.mul(-1),b.v.mul(-1))};Da.prototype.Acceleration=function(a){var b=Ta(a,2.959122082855911E-4,this.Sun.r);b.incr(Ta(a,2.825345909524226E-7,this.Jupiter.r));b.incr(Ta(a,8.459715185680659E-8,this.Saturn.r));b.incr(Ta(a,1.292024916781969E-8,this.Uranus.r));b.incr(Ta(a,1.524358900784276E-8,this.Neptune.r));return b};var Ua=function(a,b,c,d){this.tt=a;this.r=b;this.v=c;this.a=d};Ua.prototype.clone=function(){return new Ua(this.tt,this.r.clone(),this.v.clone(), +this.a.clone())};var ic=function(a,b){this.bary=a;this.grav=b},Ib=[],rd=new J([[.999432765338654,-.0336771074697641,0],[.0303959428906285,.902057912352809,.430543388542295],[-.0144994559663353,-.430299169409101,.902569881273754]]),tb=[{mu:2.82489428433814E-7,al:[1.446213296021224,3.5515522861824],a:[[.0028210960212903,0,0]],l:[[-1.925258348666E-4,4.9369589722645,.01358483658305],[-9.70803596076E-5,4.3188796477322,.01303413843243],[-8.988174165E-5,1.9080016428617,.00305064867158],[-5.53101050262E-5, +1.4936156681569,.01293892891155]],z:[[.0041510849668155,4.089939635545,-.01290686414666],[6.260521444113E-4,1.446188898627,3.5515522949802],[3.52747346169E-5,2.1256287034578,1.2727416567E-4]],zeta:[[3.142172466014E-4,2.7964219722923,-.002315096098],[9.04169207946E-5,1.0477061879627,-5.6920638196E-4]]},{mu:2.82483274392893E-7,al:[-.3735263437471362,1.76932271112347],a:[[.0044871037804314,0,0],[4.324367498E-7,1.819645606291,1.7822295777568]],l:[[8.576433172936E-4,4.3188693178264,.01303413830805],[4.549582875086E-4, +1.4936531751079,.01293892881962],[3.248939825174E-4,1.8196494533458,1.7822295777568],[-3.074250079334E-4,4.9377037005911,.01358483286724],[1.982386144784E-4,1.907986905476,.00305101212869],[1.834063551804E-4,2.1402853388529,.00145009789338],[-1.434383188452E-4,5.622214036663,.89111478887838],[-7.71939140944E-5,4.300272437235,2.6733443704266]],z:[[-.0093589104136341,4.0899396509039,-.01290686414666],[2.988994545555E-4,5.9097265185595,1.7693227079462],[2.13903639035E-4,2.1256289300016,1.2727418407E-4], +[1.980963564781E-4,2.743516829265,6.7797343009E-4],[1.210388158965E-4,5.5839943711203,3.20566149E-5],[8.37042048393E-5,1.6094538368039,-.90402165808846],[8.23525166369E-5,1.4461887708689,3.5515522949802]],zeta:[[.0040404917832303,1.0477063169425,-5.692064054E-4],[2.200421034564E-4,3.3368857864364,-1.2491307307E-4],[1.662544744719E-4,2.4134862374711,0],[5.90282470983E-5,5.9719930968366,-3.056160225E-5]]},{mu:2.82498184184723E-7,al:[.2874089391143348,.878207923589328],a:[[.0071566594572575,0,0],[1.393029911E-6, +1.1586745884981,2.6733443704266]],l:[[2.310797886226E-4,2.1402987195942,.00145009784384],[-1.828635964118E-4,4.3188672736968,.01303413828263],[1.512378778204E-4,4.9373102372298,.01358483481252],[-1.163720969778E-4,4.300265986149,2.6733443704266],[-9.55478069846E-5,1.4936612842567,.01293892879857],[8.15246854464E-5,5.6222137132535,.89111478887838],[-8.01219679602E-5,1.2995922951532,1.0034433456729],[-6.07017260182E-5,.64978769669238,.50172167043264]],z:[[.0014289811307319,2.1256295942739,1.2727413029E-4], +[7.71093122676E-4,5.5836330003496,3.20643411E-5],[5.925911780766E-4,4.0899396636448,-.01290686414666],[2.045597496146E-4,5.2713683670372,-.12523544076106],[1.785118648258E-4,.28743156721063,.8782079244252],[1.131999784893E-4,1.4462127277818,3.5515522949802],[-6.5877816921E-5,2.2702423990985,-1.7951364394537],[4.97058888328E-5,5.9096792204858,1.7693227129285]],zeta:[[.0015932721570848,3.3368862796665,-1.2491307058E-4],[8.533093128905E-4,2.4133881688166,0],[3.513347911037E-4,5.9720789850127,-3.056101771E-5], +[-1.441929255483E-4,1.0477061764435,-5.6920632124E-4]]},{mu:2.82492144889909E-7,al:[-.3620341291375704,.376486233433828],a:[[.0125879701715314,0,0],[3.595204947E-6,.64965776007116,.50172168165034],[2.7580210652E-6,1.808423578151,3.1750660413359]],l:[[5.586040123824E-4,2.1404207189815,.00145009793231],[-3.805813868176E-4,2.7358844897853,2.972965062E-5],[2.205152863262E-4,.649796525964,.5017216724358],[1.877895151158E-4,1.8084787604005,3.1750660413359],[7.66916975242E-5,6.2720114319755,1.3928364636651], +[7.47056855106E-5,1.2995916202344,1.0034433456729]],z:[[.0073755808467977,5.5836071576084,3.206509914E-5],[2.065924169942E-4,5.9209831565786,.37648624194703],[1.589869764021E-4,.28744006242623,.8782079244252],[-1.561131605348E-4,2.1257397865089,1.2727441285E-4],[1.486043380971E-4,1.4462134301023,3.5515522949802],[6.35073108731E-5,5.9096803285954,1.7693227129285],[5.99351698525E-5,4.1125517584798,-2.7985797954589],[5.40660842731E-5,5.5390350845569,.00286834082283],[-4.89596900866E-5,4.6218149483338, +-.62695712529519]],zeta:[[.0038422977898495,2.4133922085557,0],[.0022453891791894,5.9721736773277,-3.056125525E-5],[-2.604479450559E-4,3.3368746306409,-1.2491309972E-4],[3.3211214323E-5,5.5604137742337,.00290037688507]]}],fd=function(a,b,c,d){this.io=a;this.europa=b;this.ganymede=c;this.callisto=d};e.JupiterMoonsInfo=fd;e.JupiterMoons=function(a){a=new O(a);return new fd(kb(a,tb[0]),kb(a,tb[1]),kb(a,tb[2]),kb(a,tb[3]))};e.HelioVector=Z;e.HelioDistance=oa;e.CorrectLightTravel=lc;var nc=function(a, +b,c,d){this.observerBody=a;this.targetBody=b;this.aberration=c;this.observerPos=d};nc.prototype.Position=function(a){this.aberration&&(this.observerPos=Z(this.observerBody,a));var b=Z(this.targetBody,a);return new E(b.x-this.observerPos.x,b.y-this.observerPos.y,b.z-this.observerPos.z,a)};e.BackdatePosition=mc;e.GeoVector=W;e.BaryState=function(a,b){b=v(b);if(a===m.SSB)return new I(0,0,0,0,0,0,b);if(a===m.Pluto)return Hb(b,!1);var c=new Da(b.tt);switch(a){case m.Sun:return pa(c.Sun,b);case m.Jupiter:return pa(c.Jupiter, +b);case m.Saturn:return pa(c.Saturn,b);case m.Uranus:return pa(c.Uranus,b);case m.Neptune:return pa(c.Neptune,b);case m.Moon:case m.EMB:var d=Sa(M[m.Earth],b.tt);a=a===m.Moon?Ra(b):Bb(b);return new I(a.x+c.Sun.r.x+d.r.x,a.y+c.Sun.r.y+d.r.y,a.z+c.Sun.r.z+d.r.z,a.vx+c.Sun.v.x+d.v.x,a.vy+c.Sun.v.y+d.v.y,a.vz+c.Sun.v.z+d.v.z,b)}if(a in M)return a=Sa(M[a],b.tt),new I(c.Sun.r.x+a.r.x,c.Sun.r.y+a.r.y,c.Sun.r.z+a.r.z,c.Sun.v.x+a.v.x,c.Sun.v.y+a.v.y,c.Sun.v.z+a.v.z,b);throw'BaryState: Unsupported body "'+ +a+'"';};e.HelioState=mb;e.Search=K;e.SearchSunLongitude=oc;e.PairLongitude=Jb;e.AngleFromSun=Ha;e.EclipticLongitude=qa;var pc=function(a,b,c,d,f,g,h,l){this.time=a;this.mag=b;this.phase_angle=c;this.helio_dist=d;this.geo_dist=f;this.gc=g;this.hc=h;this.ring_tilt=l;this.phase_fraction=(1+Math.cos(e.DEG2RAD*c))/2};e.IlluminationInfo=pc;e.Illumination=nb;e.SearchRelativeLongitude=Ia;e.MoonPhase=Kb;e.SearchMoonPhase=Wa;var rc=function(a,b){this.quarter=a;this.time=b};e.MoonQuarter=rc;e.SearchMoonQuarter= +qc;e.NextMoonQuarter=function(a){a=new Date(a.time.date.getTime()+5184E5);return qc(a)};var tc=function(a,b,c){this.pressure=a;this.temperature=b;this.density=c};e.AtmosphereInfo=tc;e.Atmosphere=sc;e.SearchRiseSet=function(a,b,c,d,f,g){g=void 0===g?0:g;if(!Number.isFinite(g)||0>g)throw"Invalid value for metersAboveGround: "+g;a:switch(a){case m.Sun:var h=Nc;break a;case m.Moon:h=Dd;break a;default:h=0}var l=sc(b.height-g),k=b.latitude*e.DEG2RAD,n=Math.sin(k);k=Math.cos(k);var p=1/Math.hypot(k,.996647180302104* +n),q=(b.height-g)/1E3,t=.175*Math.pow(1-.0065/283.15*(b.height-2/3*g),3.256);return uc(a,b,c,d,f,h,e.RAD2DEG*-(Math.sqrt(2*(1-t)*g/(1E3*Math.hypot((6378.1366*p+q)*k,(6335.438815127603*p+q)*n)))/(1-t))-Ed*l.density)};e.SearchAltitude=function(a,b,c,d,f,g){if(!Number.isFinite(g)||-90>g||90c||24<=c)throw"Invalid hour angle "+c;w(f);if(0===f)throw"Direction must be positive or negative.";for(;;){++g;var h=ca(d),l=Pa(a,d,b,!0,!0);h=(c+l.ra-b.longitude/15-h)%24;1===g?0h&&(h+=24):0h?h+=24:123600*Math.abs(h))return a=hb(d,b,l.ra,l.dec,"normal"),new gd(d,a);d=d.AddDays(h/24*.9972695717592592)}};e.HourAngle=function(a,b,c){var d=v(b); +b=bc(d);a=Pa(a,d,c,!0,!0);c=(c.longitude/15+b-a.ra)%24;0>c&&(c+=24);return c};var hd=function(a,b,c,d){this.mar_equinox=a;this.jun_solstice=b;this.sep_equinox=c;this.dec_solstice=d};e.SeasonInfo=hd;e.Seasons=function(a){function b(h,l,k){l=new Date(Date.UTC(a,l-1,k));h=oc(h,l,20);if(!h)throw"Cannot find season change near "+l.toISOString();return h}a instanceof Date&&Number.isFinite(a.getTime())&&(a=a.getUTCFullYear());if(!Number.isSafeInteger(a))throw"Cannot calculate seasons because year argument "+ +a+" is neither a Date nor a safe integer.";var c=b(0,3,10),d=b(90,6,10),f=b(180,9,10),g=b(270,12,10);return new hd(c,d,f,g)};var wc=function(a,b,c,d){this.time=a;this.visibility=b;this.elongation=c;this.ecliptic_separation=d};e.ElongationEvent=wc;e.Elongation=vc;e.SearchMaxElongation=function(a,b){function c(n){var p=n.AddDays(-.005);n=n.AddDays(.005);p=Ha(a,p);n=Ha(a,n);return(p-n)/.01}b=v(b);var d={Mercury:{s1:50,s2:85},Venus:{s1:40,s2:50}}[a];if(!d)throw"SearchMaxElongation works for Mercury and Venus only."; +for(var f=0;2>=++f;){var g=qa(a,b),h=qa(m.Earth,b),l=Fa(g-h),k=g=h=void 0;l>=-d.s1&&l<+d.s1?(k=0,h=+d.s1,g=+d.s2):l>=+d.s2||l<-d.s2?(k=0,h=-d.s2,g=-d.s1):0<=l?(k=-Va(a)/4,h=+d.s1,g=+d.s2):(k=-Va(a)/4,h=-d.s2,g=-d.s1);l=b.AddDays(k);h=Ia(a,h,l);g=Ia(a,g,h);l=c(h);if(0<=l)throw"SearchMaxElongation: internal error: m1 = "+l;k=c(g);if(0>=k)throw"SearchMaxElongation: internal error: m2 = "+k;l=K(c,h,g,{init_f1:l,init_f2:k,dt_tolerance_seconds:10});if(!l)throw"SearchMaxElongation: failed search iter "+ +f+" (t1="+h.toString()+", t2="+g.toString()+")";if(l.tt>=b.tt)return vc(a,l);b=g.AddDays(1)}throw"SearchMaxElongation: failed to find event after 2 tries.";};e.SearchPeakMagnitude=function(a,b){function c(k){var n=k.AddDays(-.005);k=k.AddDays(.005);n=nb(a,n).mag;return(nb(a,k).mag-n)/.01}if(a!==m.Venus)throw"SearchPeakMagnitude currently works for Venus only.";b=v(b);for(var d=0;2>=++d;){var f=qa(a,b),g=qa(m.Earth,b),h=Fa(f-g),l=f=g=void 0;-10<=h&&10>h?(l=0,g=10,f=30):30<=h||-30>h?(l=0,g=-30,f=-10): +0<=h?(l=-Va(a)/4,g=10,f=30):(l=-Va(a)/4,g=-30,f=-10);h=b.AddDays(l);g=Ia(a,g,h);f=Ia(a,f,g);h=c(g);if(0<=h)throw"SearchPeakMagnitude: internal error: m1 = "+h;l=c(f);if(0>=l)throw"SearchPeakMagnitude: internal error: m2 = "+l;h=K(c,g,f,{init_f1:h,init_f2:l,dt_tolerance_seconds:10});if(!h)throw"SearchPeakMagnitude: failed search iter "+d+" (t1="+g.toString()+", t2="+f.toString()+")";if(h.tt>=b.tt)return nb(a,h);b=f.AddDays(1)}throw"SearchPeakMagnitude: failed to find event after 2 tries.";};var Ja; +(function(a){a[a.Pericenter=0]="Pericenter";a[a.Apocenter=1]="Apocenter"})(Ja=e.ApsisKind||(e.ApsisKind={}));var Xa=function(a,b,c){this.time=a;this.kind=b;this.dist_au=c;this.dist_km=c*e.KM_PER_AU};e.Apsis=Xa;e.SearchLunarApsis=xc;e.NextLunarApsis=function(a){var b=xc(a.time.AddDays(11));if(1!==b.kind+a.kind)throw"NextLunarApsis INTERNAL ERROR: did not find alternating apogee/perigee: prev="+a.kind+" @ "+a.time.toString()+", next="+b.kind+" @ "+b.time.toString();return b};e.SearchPlanetApsis=zc; +e.NextPlanetApsis=function(a,b){if(b.kind!==Ja.Pericenter&&b.kind!==Ja.Apocenter)throw"Invalid apsis kind: "+b.kind;var c=b.time.AddDays(.25*aa[a].OrbitalPeriod);a=zc(a,c);if(1!==a.kind+b.kind)throw"Internal error: previous apsis was "+b.kind+", but found "+a.kind+" for next apsis.";return a};e.InverseRotation=Ka;e.CombineRotation=ja;e.IdentityMatrix=function(){return new J([[1,0,0],[0,1,0],[0,0,1]])};e.Pivot=function(a,b,c){if(0!==b&&1!==b&&2!==b)throw"Invalid axis "+b+". Must be [0, 1, 2].";var d= +w(c)*e.DEG2RAD;c=Math.cos(d);d=Math.sin(d);var f=(b+1)%3,g=(b+2)%3,h=[[0,0,0],[0,0,0],[0,0,0]];h[f][f]=c*a.rot[f][f]-d*a.rot[f][g];h[f][g]=d*a.rot[f][f]+c*a.rot[f][g];h[f][b]=a.rot[f][b];h[g][f]=c*a.rot[g][f]-d*a.rot[g][g];h[g][g]=d*a.rot[g][f]+c*a.rot[g][g];h[g][b]=a.rot[g][b];h[b][f]=c*a.rot[b][f]-d*a.rot[b][g];h[b][g]=d*a.rot[b][f]+c*a.rot[b][g];h[b][b]=a.rot[b][b];return new J(h)};e.VectorFromSphere=lb;e.EquatorFromVector=Mb;e.SphereFromVector=Nb;e.HorizonFromVector=function(a,b){a=Nb(a);a.lon= +Ac(a.lon);a.lat+=Oa(b,a.lat);return a};e.VectorFromHorizon=function(a,b,c){b=v(b);var d=Ac(a.lon);c=a.lat+Bc(c,a.lat);a=new Ba(c,d,a.dist);return lb(a,b)};e.Refraction=Oa;e.InverseRefraction=Bc;e.RotateVector=Ya;e.RotateState=Ea;e.Rotation_EQJ_ECL=Cc;e.Rotation_ECL_EQJ=function(){return new J([[1,0,0],[0,.9174821430670688,.3977769691083922],[0,-.3977769691083922,.9174821430670688]])};e.Rotation_EQJ_EQD=ob;e.Rotation_EQJ_ECT=function(a){var b=v(a);a=ob(b);b=Jc(b);return ja(a,b)};e.Rotation_ECT_EQJ= +function(a){var b=v(a);a=Ic(b);b=pb(b);return ja(a,b)};e.Rotation_EQD_EQJ=pb;e.Rotation_EQD_HOR=Ob;e.Rotation_HOR_EQD=Dc;e.Rotation_HOR_EQJ=Ec;e.Rotation_EQJ_HOR=function(a,b){a=Ec(a,b);return Ka(a)};e.Rotation_EQD_ECL=Fc;e.Rotation_ECL_EQD=Gc;e.Rotation_ECL_HOR=Hc;e.Rotation_HOR_ECL=function(a,b){a=Hc(a,b);return Ka(a)};e.Rotation_EQJ_GAL=function(){return new J([[-.0548624779711344,.4941095946388765,-.8676668813529025],[-.8734572784246782,-.4447938112296831,-.1980677870294097],[-.483800052994852, +.7470034631630423,.4559861124470794]])};e.Rotation_GAL_EQJ=function(){return new J([[-.0548624779711344,-.8734572784246782,-.483800052994852],[.4941095946388765,-.4447938112296831,.7470034631630423],[-.8676668813529025,-.1980677870294097,.4559861124470794]])};e.Rotation_ECT_EQD=Ic;e.Rotation_EQD_ECT=Jc;var Fd=[["And","Andromeda"],["Ant","Antila"],["Aps","Apus"],["Aql","Aquila"],["Aqr","Aquarius"],["Ara","Ara"],["Ari","Aries"],["Aur","Auriga"],["Boo","Bootes"],["Cae","Caelum"],["Cam","Camelopardis"], +["Cap","Capricornus"],["Car","Carina"],["Cas","Cassiopeia"],["Cen","Centaurus"],["Cep","Cepheus"],["Cet","Cetus"],["Cha","Chamaeleon"],["Cir","Circinus"],["CMa","Canis Major"],["CMi","Canis Minor"],["Cnc","Cancer"],["Col","Columba"],["Com","Coma Berenices"],["CrA","Corona Australis"],["CrB","Corona Borealis"],["Crt","Crater"],["Cru","Crux"],["Crv","Corvus"],["CVn","Canes Venatici"],["Cyg","Cygnus"],["Del","Delphinus"],["Dor","Dorado"],["Dra","Draco"],["Equ","Equuleus"],["Eri","Eridanus"],["For","Fornax"], +["Gem","Gemini"],["Gru","Grus"],["Her","Hercules"],["Hor","Horologium"],["Hya","Hydra"],["Hyi","Hydrus"],["Ind","Indus"],["Lac","Lacerta"],["Leo","Leo"],["Lep","Lepus"],["Lib","Libra"],["LMi","Leo Minor"],["Lup","Lupus"],["Lyn","Lynx"],["Lyr","Lyra"],["Men","Mensa"],["Mic","Microscopium"],["Mon","Monoceros"],["Mus","Musca"],["Nor","Norma"],["Oct","Octans"],["Oph","Ophiuchus"],["Ori","Orion"],["Pav","Pavo"],["Peg","Pegasus"],["Per","Perseus"],["Phe","Phoenix"],["Pic","Pictor"],["PsA","Pisces Austrinus"], +["Psc","Pisces"],["Pup","Puppis"],["Pyx","Pyxis"],["Ret","Reticulum"],["Scl","Sculptor"],["Sco","Scorpius"],["Sct","Scutum"],["Ser","Serpens"],["Sex","Sextans"],["Sge","Sagitta"],["Sgr","Sagittarius"],["Tau","Taurus"],["Tel","Telescopium"],["TrA","Triangulum Australe"],["Tri","Triangulum"],["Tuc","Tucana"],["UMa","Ursa Major"],["UMi","Ursa Minor"],["Vel","Vela"],["Vir","Virgo"],["Vol","Volans"],["Vul","Vulpecula"]],Gd=[[83,0,8640,2112],[83,2880,5220,2076],[83,7560,8280,2068],[83,6480,7560,2064],[15, +0,2880,2040],[10,3300,3840,1968],[15,0,1800,1920],[10,3840,5220,1920],[83,6300,6480,1920],[33,7260,7560,1920],[15,0,1263,1848],[10,4140,4890,1848],[83,5952,6300,1800],[15,7260,7440,1800],[10,2868,3300,1764],[33,3300,4080,1764],[83,4680,5952,1680],[13,1116,1230,1632],[33,7350,7440,1608],[33,4080,4320,1596],[15,0,120,1584],[83,5040,5640,1584],[15,8490,8640,1584],[33,4320,4860,1536],[33,4860,5190,1512],[15,8340,8490,1512],[10,2196,2520,1488],[33,7200,7350,1476],[15,7393.2,7416,1462],[10,2520,2868,1440], +[82,2868,3030,1440],[33,7116,7200,1428],[15,7200,7393.2,1428],[15,8232,8340,1418],[13,0,876,1404],[33,6990,7116,1392],[13,612,687,1380],[13,876,1116,1368],[10,1116,1140,1368],[15,8034,8232,1350],[10,1800,2196,1344],[82,5052,5190,1332],[33,5190,6990,1332],[10,1140,1200,1320],[15,7968,8034,1320],[15,7416,7908,1316],[13,0,612,1296],[50,2196,2340,1296],[82,4350,4860,1272],[33,5490,5670,1272],[15,7908,7968,1266],[10,1200,1800,1260],[13,8232,8400,1260],[33,5670,6120,1236],[62,735,906,1212],[33,6120,6564, +1212],[13,0,492,1200],[62,492,600,1200],[50,2340,2448,1200],[13,8400,8640,1200],[82,4860,5052,1164],[13,0,402,1152],[13,8490,8640,1152],[39,6543,6564,1140],[33,6564,6870,1140],[30,6870,6900,1140],[62,600,735,1128],[82,3030,3300,1128],[13,60,312,1104],[82,4320,4350,1080],[50,2448,2652,1068],[30,7887,7908,1056],[30,7875,7887,1050],[30,6900,6984,1044],[82,3300,3660,1008],[82,3660,3882,960],[8,5556,5670,960],[39,5670,5880,960],[50,3330,3450,954],[0,0,906,882],[62,906,924,882],[51,6969,6984,876],[62,1620, +1689,864],[30,7824,7875,864],[44,7875,7920,864],[7,2352,2652,852],[50,2652,2790,852],[0,0,720,840],[44,7920,8214,840],[44,8214,8232,828],[0,8232,8460,828],[62,924,978,816],[82,3882,3960,816],[29,4320,4440,816],[50,2790,3330,804],[48,3330,3558,804],[0,258,507,792],[8,5466,5556,792],[0,8460,8550,770],[29,4440,4770,768],[0,8550,8640,752],[29,5025,5052,738],[80,870,978,736],[62,978,1620,736],[7,1620,1710,720],[51,6543,6969,720],[82,3960,4320,696],[30,7080,7530,696],[7,1710,2118,684],[48,3558,3780,684], +[29,4770,5025,684],[0,0,24,672],[80,507,600,672],[7,2118,2352,672],[37,2838,2880,672],[30,7530,7824,672],[30,6933,7080,660],[80,690,870,654],[25,5820,5880,648],[8,5430,5466,624],[25,5466,5820,624],[51,6612,6792,624],[48,3870,3960,612],[51,6792,6933,612],[80,600,690,600],[66,258,306,570],[48,3780,3870,564],[87,7650,7710,564],[77,2052,2118,548],[0,24,51,528],[73,5730,5772,528],[37,2118,2238,516],[87,7140,7290,510],[87,6792,6930,506],[0,51,306,504],[87,7290,7404,492],[37,2811,2838,480],[87,7404,7650, +468],[87,6930,7140,460],[6,1182,1212,456],[75,6792,6840,444],[59,2052,2076,432],[37,2238,2271,420],[75,6840,7140,388],[77,1788,1920,384],[39,5730,5790,384],[75,7140,7290,378],[77,1662,1788,372],[77,1920,2016,372],[23,4620,4860,360],[39,6210,6570,344],[23,4272,4620,336],[37,2700,2811,324],[39,6030,6210,308],[61,0,51,300],[77,2016,2076,300],[37,2520,2700,300],[61,7602,7680,300],[37,2271,2496,288],[39,6570,6792,288],[31,7515,7578,284],[61,7578,7602,284],[45,4146,4272,264],[59,2247,2271,240],[37,2496, +2520,240],[21,2811,2853,240],[61,8580,8640,240],[6,600,1182,238],[31,7251,7308,204],[8,4860,5430,192],[61,8190,8580,180],[21,2853,3330,168],[45,3330,3870,168],[58,6570,6718.4,150],[3,6718.4,6792,150],[31,7500,7515,144],[20,2520,2526,132],[73,6570,6633,108],[39,5790,6030,96],[58,6570,6633,72],[61,7728,7800,66],[66,0,720,48],[73,6690,6792,48],[31,7308,7500,48],[34,7500,7680,48],[61,7680,7728,48],[61,7920,8190,48],[61,7800,7920,42],[20,2526,2592,36],[77,1290,1662,0],[59,1662,1680,0],[20,2592,2910,0], +[85,5280,5430,0],[58,6420,6570,0],[16,954,1182,-42],[77,1182,1290,-42],[73,5430,5856,-78],[59,1680,1830,-96],[59,2100,2247,-96],[73,6420,6468,-96],[73,6570,6690,-96],[3,6690,6792,-96],[66,8190,8580,-96],[45,3870,4146,-144],[85,4146,4260,-144],[66,0,120,-168],[66,8580,8640,-168],[85,5130,5280,-192],[58,5730,5856,-192],[3,7200,7392,-216],[4,7680,7872,-216],[58,6180,6468,-240],[54,2100,2910,-264],[35,1770,1830,-264],[59,1830,2100,-264],[41,2910,3012,-264],[74,3450,3870,-264],[85,4260,4620,-264],[58, +6330,6360,-280],[3,6792,7200,-288.8],[35,1740,1770,-348],[4,7392,7680,-360],[73,6180,6570,-384],[72,6570,6792,-384],[41,3012,3090,-408],[58,5856,5895,-438],[41,3090,3270,-456],[26,3870,3900,-456],[71,5856,5895,-462],[47,5640,5730,-480],[28,4530,4620,-528],[85,4620,5130,-528],[41,3270,3510,-576],[16,600,954,-585.2],[35,954,1350,-585.2],[26,3900,4260,-588],[28,4260,4530,-588],[47,5130,5370,-588],[58,5856,6030,-590],[16,0,600,-612],[11,7680,7872,-612],[4,7872,8580,-612],[16,8580,8640,-612],[41,3510, +3690,-636],[35,1692,1740,-654],[46,1740,2202,-654],[11,7200,7680,-672],[41,3690,3810,-700],[41,4530,5370,-708],[47,5370,5640,-708],[71,5640,5760,-708],[35,1650,1692,-720],[58,6030,6336,-720],[76,6336,6420,-720],[41,3810,3900,-748],[19,2202,2652,-792],[41,4410,4530,-792],[41,3900,4410,-840],[36,1260,1350,-864],[68,3012,3372,-882],[35,1536,1650,-888],[76,6420,6900,-888],[65,7680,8280,-888],[70,8280,8400,-888],[36,1080,1260,-950],[1,3372,3960,-954],[70,0,600,-960],[36,600,1080,-960],[35,1392,1536,-960], +[70,8400,8640,-960],[14,5100,5370,-1008],[49,5640,5760,-1008],[71,5760,5911.5,-1008],[9,1740,1800,-1032],[22,1800,2370,-1032],[67,2880,3012,-1032],[35,1230,1392,-1056],[71,5911.5,6420,-1092],[24,6420,6900,-1092],[76,6900,7320,-1092],[53,7320,7680,-1092],[35,1080,1230,-1104],[9,1620,1740,-1116],[49,5520,5640,-1152],[63,0,840,-1156],[35,960,1080,-1176],[40,1470,1536,-1176],[9,1536,1620,-1176],[38,7680,7920,-1200],[67,2160,2880,-1218],[84,2880,2940,-1218],[35,870,960,-1224],[40,1380,1470,-1224],[63, +0,660,-1236],[12,2160,2220,-1260],[84,2940,3042,-1272],[40,1260,1380,-1276],[32,1380,1440,-1276],[63,0,570,-1284],[35,780,870,-1296],[64,1620,1800,-1296],[49,5418,5520,-1296],[84,3042,3180,-1308],[12,2220,2340,-1320],[14,4260,4620,-1320],[49,5100,5418,-1320],[56,5418,5520,-1320],[32,1440,1560,-1356],[84,3180,3960,-1356],[14,3960,4050,-1356],[5,6300,6480,-1368],[78,6480,7320,-1368],[38,7920,8400,-1368],[40,1152,1260,-1380],[64,1800,1980,-1380],[12,2340,2460,-1392],[63,0,480,-1404],[35,480,780,-1404], +[63,8400,8640,-1404],[32,1560,1650,-1416],[56,5520,5911.5,-1440],[43,7320,7680,-1440],[64,1980,2160,-1464],[18,5460,5520,-1464],[5,5911.5,5970,-1464],[18,5370,5460,-1526],[5,5970,6030,-1526],[64,2160,2460,-1536],[12,2460,3252,-1536],[14,4050,4260,-1536],[27,4260,4620,-1536],[14,4620,5232,-1536],[18,4860,4920,-1560],[5,6030,6060,-1560],[40,780,1152,-1620],[69,1152,1650,-1620],[18,5310,5370,-1620],[5,6060,6300,-1620],[60,6300,6480,-1620],[81,7920,8400,-1620],[32,1650,2370,-1680],[18,4920,5310,-1680], +[79,5310,6120,-1680],[81,0,480,-1800],[42,1260,1650,-1800],[86,2370,3252,-1800],[12,3252,4050,-1800],[55,4050,4920,-1800],[60,6480,7680,-1800],[43,7680,8400,-1800],[81,8400,8640,-1800],[81,270,480,-1824],[42,0,1260,-1980],[17,2760,4920,-1980],[2,4920,6480,-1980],[52,1260,2760,-2040],[57,0,8640,-2160]],Tb,id,jd=function(a,b,c,d){this.symbol=a;this.name=b;this.ra1875=c;this.dec1875=d};e.ConstellationInfo=jd;e.Constellation=function(a,b){w(a);w(b);if(-90>b||90a&&(a+=24);Tb||(Tb=ob(new O(-45655.74141261017)),id=new O(0));a=new Ba(b,15*a,1);a=lb(a,id);a=Ya(Tb,a);a=Mb(a);b=10/240;for(var c=b/15,d=$jscomp.makeIterator(Gd),f=d.next();!f.done;f=d.next()){f=f.value;var g=f[1]*c,h=f[2]*c;if(f[3]*b<=a.dec&&g<=a.ra&&a.ra + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ +export declare type FlexibleDateTime = Date | number | AstroTime; +/** + * @brief The speed of light in AU/day. + */ +export declare const C_AUDAY = 173.1446326846693; +/** + * @brief The number of kilometers per astronomical unit. + */ +export declare const KM_PER_AU = 149597870.69098932; +/** + * @brief The number of astronomical units per light-year. + */ +export declare const AU_PER_LY = 63241.07708807546; +/** + * @brief The factor to convert degrees to radians = pi/180. + */ +export declare const DEG2RAD = 0.017453292519943295; +/** + * @brief The factor to convert sidereal hours to radians = pi/12. + */ +export declare const HOUR2RAD = 0.26179938779914946; +/** + * @brief The factor to convert radians to degrees = 180/pi. + */ +export declare const RAD2DEG = 57.29577951308232; +/** + * @brief The factor to convert radians to sidereal hours = 12/pi. + */ +export declare const RAD2HOUR = 3.819718634205488; +/** + * @brief The equatorial radius of Jupiter, expressed in kilometers. + */ +export declare const JUPITER_EQUATORIAL_RADIUS_KM = 71492; +/** + * @brief The polar radius of Jupiter, expressed in kilometers. + */ +export declare const JUPITER_POLAR_RADIUS_KM = 66854; +/** + * @brief The volumetric mean radius of Jupiter, expressed in kilometers. + */ +export declare const JUPITER_MEAN_RADIUS_KM = 69911; +/** + * @brief The mean radius of Jupiter's moon Io, expressed in kilometers. + */ +export declare const IO_RADIUS_KM = 1821.6; +/** + * @brief The mean radius of Jupiter's moon Europa, expressed in kilometers. + */ +export declare const EUROPA_RADIUS_KM = 1560.8; +/** + * @brief The mean radius of Jupiter's moon Ganymede, expressed in kilometers. + */ +export declare const GANYMEDE_RADIUS_KM = 2631.2; +/** + * @brief The mean radius of Jupiter's moon Callisto, expressed in kilometers. + */ +export declare const CALLISTO_RADIUS_KM = 2410.3; +/** + * @brief Returns the product of mass and universal gravitational constant of a Solar System body. + * + * For problems involving the gravitational interactions of Solar System bodies, + * it is helpful to know the product GM, where G = the universal gravitational constant + * and M = the mass of the body. In practice, GM is known to a higher precision than + * either G or M alone, and thus using the product results in the most accurate results. + * This function returns the product GM in the units au^3/day^2. + * The values come from page 10 of a + * [JPL memorandum regarding the DE405/LE405 ephemeris](https://web.archive.org/web/20120220062549/http://iau-comm4.jpl.nasa.gov/de405iom/de405iom.pdf). + * + * @param {Body} body + * The body for which to find the GM product. + * Allowed to be the Sun, Moon, EMB (Earth/Moon Barycenter), or any planet. + * Any other value will cause an exception to be thrown. + * + * @returns {number} + * The mass product of the given body in au^3/day^2. + */ +export declare function MassProduct(body: Body): number; +/** + * @brief Calculates the angle in degrees between two vectors. + * + * Given a pair of vectors, this function returns the angle in degrees + * between the two vectors in 3D space. + * The angle is measured in the plane that contains both vectors. + * + * @param {Vector} a + * The first of a pair of vectors between which to measure an angle. + * + * @param {Vector} b + * The second of a pair of vectors between which to measure an angle. + * + * @returns {number} + * The angle between the two vectors expressed in degrees. + * The value is in the range [0, 180]. + */ +export declare function AngleBetween(a: Vector, b: Vector): number; +/** + * @brief String constants that represent the solar system bodies supported by Astronomy Engine. + * + * The following strings represent solar system bodies supported by various Astronomy Engine functions. + * Not every body is supported by every function; consult the documentation for each function + * to find which bodies it supports. + * + * "Sun", "Moon", "Mercury", "Venus", "Earth", "Mars", "Jupiter", + * "Saturn", "Uranus", "Neptune", "Pluto", + * "SSB" (Solar System Barycenter), + * "EMB" (Earth/Moon Barycenter) + * + * You can also use enumeration syntax for the bodies, like + * `Astronomy.Body.Moon`, `Astronomy.Body.Jupiter`, etc. + * + * @enum {string} + */ +export declare enum Body { + Sun = "Sun", + Moon = "Moon", + Mercury = "Mercury", + Venus = "Venus", + Earth = "Earth", + Mars = "Mars", + Jupiter = "Jupiter", + Saturn = "Saturn", + Uranus = "Uranus", + Neptune = "Neptune", + Pluto = "Pluto", + SSB = "SSB", + EMB = "EMB", + Star1 = "Star1", + Star2 = "Star2", + Star3 = "Star3", + Star4 = "Star4", + Star5 = "Star5", + Star6 = "Star6", + Star7 = "Star7", + Star8 = "Star8" +} +/** + * @brief Assign equatorial coordinates to a user-defined star. + * + * Some Astronomy Engine functions allow their `body` parameter to + * be a user-defined fixed point in the sky, loosely called a "star". + * This function assigns a right ascension, declination, and distance + * to one of the eight user-defined stars `Star1`..`Star8`. + * + * Stars are not valid until defined. Once defined, they retain their + * definition until re-defined by another call to `DefineStar`. + * + * @param {Body} body + * One of the eight user-defined star identifiers: + * `Star1`, `Star2`, `Star3`, `Star4`, `Star5`, `Star6`, `Star7`, or `Star8`. + * + * @param {number} ra + * The right ascension to be assigned to the star, expressed in J2000 equatorial coordinates (EQJ). + * The value is in units of sidereal hours, and must be within the half-open range [0, 24). + * + * @param {number} dec + * The declination to be assigned to the star, expressed in J2000 equatorial coordinates (EQJ). + * The value is in units of degrees north (positive) or south (negative) of the J2000 equator, + * and must be within the closed range [-90, +90]. + * + * @param {number} distanceLightYears + * The distance between the star and the Sun, expressed in light-years. + * This value is used to calculate the tiny parallax shift as seen by an observer on Earth. + * If you don't know the distance to the star, using a large value like 1000 will generally work well. + * The minimum allowed distance is 1 light-year, which is required to provide certain internal optimizations. + */ +export declare function DefineStar(body: Body, ra: number, dec: number, distanceLightYears: number): void; +/** + * @brief Returns the mean orbital period of a planet in days. + * + * @param {Body} body + * One of: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, or Pluto. + * + * @returns {number} + * The approximate average time it takes for the planet to travel once around the Sun. + * The value is expressed in days. + */ +export declare function PlanetOrbitalPeriod(body: Body): number; +export declare function DeltaT_EspenakMeeus(ut: number): number; +export declare type DeltaTimeFunction = (ut: number) => number; +export declare function DeltaT_JplHorizons(ut: number): number; +export declare function SetDeltaTFunction(func: DeltaTimeFunction): void; +/** + * @brief The date and time of an astronomical observation. + * + * Objects of type `AstroTime` are used throughout the internals + * of the Astronomy library, and are included in certain return objects. + * Use the constructor or the {@link MakeTime} function to create an `AstroTime` object. + * + * @property {Date} date + * The JavaScript Date object for the given date and time. + * This Date corresponds to the numeric day value stored in the `ut` property. + * + * @property {number} ut + * Universal Time (UT1/UTC) in fractional days since the J2000 epoch. + * Universal Time represents time measured with respect to the Earth's rotation, + * tracking mean solar days. + * The Astronomy library approximates UT1 and UTC as being the same thing. + * This gives sufficient accuracy for the precision requirements of this project. + * + * @property {number} tt + * Terrestrial Time in fractional days since the J2000 epoch. + * TT represents a continuously flowing ephemeris timescale independent of + * any variations of the Earth's rotation, and is adjusted from UT + * using a best-fit piecewise polynomial model devised by + * [Espenak and Meeus](https://eclipse.gsfc.nasa.gov/SEhelp/deltatpoly2004.html). + */ +export declare class AstroTime { + date: Date; + ut: number; + tt: number; + /** + * @param {FlexibleDateTime} date + * A JavaScript Date object, a numeric UTC value expressed in J2000 days, or another AstroTime object. + */ + constructor(date: FlexibleDateTime); + /** + * @brief Creates an `AstroTime` value from a Terrestrial Time (TT) day value. + * + * This function can be used in rare cases where a time must be based + * on Terrestrial Time (TT) rather than Universal Time (UT). + * Most developers will want to invoke `new AstroTime(ut)` with a universal time + * instead of this function, because usually time is based on civil time adjusted + * by leap seconds to match the Earth's rotation, rather than the uniformly + * flowing TT used to calculate solar system dynamics. In rare cases + * where the caller already knows TT, this function is provided to create + * an `AstroTime` value that can be passed to Astronomy Engine functions. + * + * @param {number} tt + * The number of days since the J2000 epoch as expressed in Terrestrial Time. + * + * @returns {AstroTime} + * An `AstroTime` object for the specified terrestrial time. + */ + static FromTerrestrialTime(tt: number): AstroTime; + /** + * Formats an `AstroTime` object as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) + * date/time string in UTC, to millisecond resolution. + * Example: `2018-08-17T17:22:04.050Z` + * @returns {string} + */ + toString(): string; + /** + * Returns a new `AstroTime` object adjusted by the floating point number of days. + * Does NOT modify the original `AstroTime` object. + * + * @param {number} days + * The floating point number of days by which to adjust the given date and time. + * Positive values adjust the date toward the future, and + * negative values adjust the date toward the past. + * + * @returns {AstroTime} + */ + AddDays(days: number): AstroTime; +} +/** + * @brief A `Date`, `number`, or `AstroTime` value that specifies the date and time of an astronomical event. + * + * `FlexibleDateTime` is a placeholder type that represents three different types + * that may be passed to many Astronomy Engine functions: a JavaScript `Date` object, + * a number representing the real-valued number of UT days since the J2000 epoch, + * or an {@link AstroTime} object. + * + * This flexibility is for convenience of outside callers. + * Internally, Astronomy Engine always converts a `FlexibleDateTime` parameter + * to an `AstroTime` object by calling {@link MakeTime}. + * + * @typedef {Date | number | AstroTime} FlexibleDateTime + */ +/** + * @brief Converts multiple date/time formats to `AstroTime` format. + * + * Given a Date object or a number days since noon (12:00) on January 1, 2000 (UTC), + * this function creates an {@link AstroTime} object. + * + * Given an {@link AstroTime} object, returns the same object unmodified. + * Use of this function is not required for any of the other exposed functions in this library, + * because they all guarantee converting date/time parameters to `AstroTime` + * as needed. However, it may be convenient for callers who need to understand + * the difference between UTC and TT (Terrestrial Time). In some use cases, + * converting once to `AstroTime` format and passing the result into multiple + * function calls may be more efficient than passing in native JavaScript Date objects. + * + * @param {FlexibleDateTime} date + * A Date object, a number of UTC days since the J2000 epoch (noon on January 1, 2000), + * or an AstroTime object. See remarks above. + * + * @returns {AstroTime} + */ +export declare function MakeTime(date: FlexibleDateTime): AstroTime; +export interface EarthTiltInfo { + tt: number; + dpsi: number; + deps: number; + ee: number; + mobl: number; + tobl: number; +} +export declare function e_tilt(time: AstroTime): EarthTiltInfo; +export declare let CalcMoonCount: number; +/** + * @brief Lunar libration angles, returned by {@link Libration}. + * + * @property {number} elat + * Sub-Earth libration ecliptic latitude angle, in degrees. + * @property {number} elon + * Sub-Earth libration ecliptic longitude angle, in degrees. + * @property {number} mlat + * Moon's geocentric ecliptic latitude, in degrees. + * @property {number} mlon + * Moon's geocentric ecliptic longitude, in degrees. + * @property {number} dist_km + * Distance between the centers of the Earth and Moon in kilometers. + * @property {number} diam_deg + * The apparent angular diameter of the Moon, in degrees, as seen from the center of the Earth. + */ +export declare class LibrationInfo { + elat: number; + elon: number; + mlat: number; + mlon: number; + dist_km: number; + diam_deg: number; + constructor(elat: number, elon: number, mlat: number, mlon: number, dist_km: number, diam_deg: number); +} +/** + * @brief Calculates the Moon's libration angles at a given moment in time. + * + * Libration is an observed back-and-forth wobble of the portion of the + * Moon visible from the Earth. It is caused by the imperfect tidal locking + * of the Moon's fixed rotation rate, compared to its variable angular speed + * of orbit around the Earth. + * + * This function calculates a pair of perpendicular libration angles, + * one representing rotation of the Moon in ecliptic longitude `elon`, the other + * in ecliptic latitude `elat`, both relative to the Moon's mean Earth-facing position. + * + * This function also returns the geocentric position of the Moon + * expressed in ecliptic longitude `mlon`, ecliptic latitude `mlat`, the + * distance `dist_km` between the centers of the Earth and Moon expressed in kilometers, + * and the apparent angular diameter of the Moon `diam_deg`. + * + * @param {FlexibleDateTime} date + * A Date object, a number of UTC days since the J2000 epoch (noon on January 1, 2000), + * or an AstroTime object. + * + * @returns {LibrationInfo} + */ +export declare function Libration(date: FlexibleDateTime): LibrationInfo; +/** + * @brief Calculates Greenwich Apparent Sidereal Time (GAST). + * + * Given a date and time, this function calculates the rotation of the + * Earth, represented by the equatorial angle of the Greenwich prime meridian + * with respect to distant stars (not the Sun, which moves relative to background + * stars by almost one degree per day). + * This angle is called Greenwich Apparent Sidereal Time (GAST). + * GAST is measured in sidereal hours in the half-open range [0, 24). + * When GAST = 0, it means the prime meridian is aligned with the of-date equinox, + * corrected at that time for precession and nutation of the Earth's axis. + * In this context, the "equinox" is the direction in space where the Earth's + * orbital plane (the ecliptic) intersects with the plane of the Earth's equator, + * at the location on the Earth's orbit of the (seasonal) March equinox. + * As the Earth rotates, GAST increases from 0 up to 24 sidereal hours, + * then starts over at 0. + * To convert to degrees, multiply the return value by 15. + * + * @param {FlexibleDateTime} date + * The date and time for which to find GAST. + * + * @returns {number} + */ +export declare function SiderealTime(date: FlexibleDateTime): number; +/** + * @brief A 3D Cartesian vector with a time attached to it. + * + * Holds the Cartesian coordinates of a vector in 3D space, + * along with the time at which the vector is valid. + * + * @property {number} x The x-coordinate expressed in astronomical units (AU). + * @property {number} y The y-coordinate expressed in astronomical units (AU). + * @property {number} z The z-coordinate expressed in astronomical units (AU). + * @property {AstroTime} t The time at which the vector is valid. + */ +export declare class Vector { + x: number; + y: number; + z: number; + t: AstroTime; + constructor(x: number, y: number, z: number, t: AstroTime); + /** + * Returns the length of the vector in astronomical units (AU). + * @returns {number} + */ + Length(): number; +} +/** + * @brief A combination of a position vector, a velocity vector, and a time. + * + * Holds the state vector of a body at a given time, including its position, + * velocity, and the time they are valid. + * + * @property {number} x The position x-coordinate expressed in astronomical units (AU). + * @property {number} y The position y-coordinate expressed in astronomical units (AU). + * @property {number} z The position z-coordinate expressed in astronomical units (AU). + * @property {number} vx The velocity x-coordinate expressed in AU/day. + * @property {number} vy The velocity y-coordinate expressed in AU/day. + * @property {number} vz The velocity z-coordinate expressed in AU/day. + * @property {AstroTime} t The time at which the vector is valid. + */ +export declare class StateVector { + x: number; + y: number; + z: number; + vx: number; + vy: number; + vz: number; + t: AstroTime; + constructor(x: number, y: number, z: number, vx: number, vy: number, vz: number, t: AstroTime); +} +/** + * @brief Holds spherical coordinates: latitude, longitude, distance. + * + * Spherical coordinates represent the location of + * a point using two angles and a distance. + * + * @property {number} lat The latitude angle: -90..+90 degrees. + * @property {number} lon The longitude angle: 0..360 degrees. + * @property {number} dist Distance in AU. + */ +export declare class Spherical { + lat: number; + lon: number; + dist: number; + constructor(lat: number, lon: number, dist: number); +} +/** + * @brief Holds right ascension, declination, and distance of a celestial object. + * + * @property {number} ra + * Right ascension in sidereal hours: [0, 24). + * + * @property {number} dec + * Declination in degrees: [-90, +90]. + * + * @property {number} dist + * Distance to the celestial object expressed in + * astronomical units (AU). + * + * @property {Vector} vec + * The equatorial coordinates in cartesian form, using AU distance units. + * x = direction of the March equinox, + * y = direction of the June solstice, + * z = north. + */ +export declare class EquatorialCoordinates { + ra: number; + dec: number; + dist: number; + vec: Vector; + constructor(ra: number, dec: number, dist: number, vec: Vector); +} +/** + * @brief Contains a rotation matrix that can be used to transform one coordinate system to another. + * + * @property {number[][]} rot + * A normalized 3x3 rotation matrix. For example, the identity matrix is represented + * as `[[1, 0, 0], [0, 1, 0], [0, 0, 1]]`. + */ +export declare class RotationMatrix { + rot: number[][]; + constructor(rot: number[][]); +} +/** + * @brief Creates a rotation matrix that can be used to transform one coordinate system to another. + * + * This function verifies that the `rot` parameter is of the correct format: + * a number[3][3] array. It throws an exception if `rot` is not of that shape. + * Otherwise it creates a new {@link RotationMatrix} object based on `rot`. + * + * @param {number[][]} rot + * An array [3][3] of numbers. Defines a rotation matrix used to premultiply + * a 3D vector to reorient it into another coordinate system. + * + * @returns {RotationMatrix} + */ +export declare function MakeRotation(rot: number[][]): RotationMatrix; +/** + * @brief Represents the location of an object seen by an observer on the Earth. + * + * Holds azimuth (compass direction) and altitude (angle above/below the horizon) + * of a celestial object as seen by an observer at a particular location on the Earth's surface. + * Also holds right ascension and declination of the same object. + * All of these coordinates are optionally adjusted for atmospheric refraction; + * therefore the right ascension and declination values may not exactly match + * those found inside a corresponding {@link EquatorialCoordinates} object. + * + * @property {number} azimuth + * A horizontal compass direction angle in degrees measured starting at north + * and increasing positively toward the east. + * The value is in the range [0, 360). + * North = 0, east = 90, south = 180, west = 270. + * + * @property {number} altitude + * A vertical angle in degrees above (positive) or below (negative) the horizon. + * The value is in the range [-90, +90]. + * The altitude angle is optionally adjusted upward due to atmospheric refraction. + * + * @property {number} ra + * The right ascension of the celestial body in sidereal hours. + * The value is in the reange [0, 24). + * If `altitude` was adjusted for atmospheric reaction, `ra` + * is likewise adjusted. + * + * @property {number} dec + * The declination of of the celestial body in degrees. + * The value in the range [-90, +90]. + * If `altitude` was adjusted for atmospheric reaction, `dec` + * is likewise adjusted. + */ +export declare class HorizontalCoordinates { + azimuth: number; + altitude: number; + ra: number; + dec: number; + constructor(azimuth: number, altitude: number, ra: number, dec: number); +} +/** + * @brief Ecliptic coordinates of a celestial body. + * + * The origin and date of the coordinate system may vary depending on the caller's usage. + * In general, ecliptic coordinates are measured with respect to the mean plane of the Earth's + * orbit around the Sun. + * Includes Cartesian coordinates `(ex, ey, ez)` measured in + * astronomical units (AU) + * and spherical coordinates `(elon, elat)` measured in degrees. + * + * @property {Vector} vec + * Ecliptic cartesian vector with components measured in astronomical units (AU). + * The x-axis is within the ecliptic plane and is oriented in the direction of the + * equinox. + * The y-axis is within the ecliptic plane and is oriented 90 degrees + * counterclockwise from the equinox, as seen from above the Sun's north pole. + * The z-axis is oriented perpendicular to the ecliptic plane, + * along the direction of the Sun's north pole. + * + * @property {number} elat + * The ecliptic latitude of the body in degrees. + * This is the angle north or south of the ecliptic plane. + * The value is in the range [-90, +90]. + * Positive values are north and negative values are south. + * + * @property {number} elon + * The ecliptic longitude of the body in degrees. + * This is the angle measured counterclockwise around the ecliptic plane, + * as seen from above the Sun's north pole. + * This is the same direction that the Earth orbits around the Sun. + * The angle is measured starting at 0 from the equinox and increases + * up to 360 degrees. + */ +export declare class EclipticCoordinates { + vec: Vector; + elat: number; + elon: number; + constructor(vec: Vector, elat: number, elon: number); +} +/** + * @brief Converts equatorial coordinates to horizontal coordinates. + * + * Given a date and time, a geographic location of an observer on the Earth, and + * equatorial coordinates (right ascension and declination) of a celestial body, + * returns horizontal coordinates (azimuth and altitude angles) for that body + * as seen by that observer. Allows optional correction for atmospheric refraction. + * + * @param {FlexibleDateTime} date + * The date and time for which to find horizontal coordinates. + * + * @param {Observer} observer + * The location of the observer for which to find horizontal coordinates. + * + * @param {number} ra + * Right ascension in sidereal hours of the celestial object, + * referred to the mean equinox of date for the J2000 epoch. + * + * @param {number} dec + * Declination in degrees of the celestial object, + * referred to the mean equator of date for the J2000 epoch. + * Positive values are north of the celestial equator and negative values are south. + * + * @param {string} refraction + * If omitted or has a false-like value (false, null, undefined, etc.) + * the calculations are performed without any correction for atmospheric + * refraction. If the value is the string `"normal"`, + * uses the recommended refraction correction based on Meeus "Astronomical Algorithms" + * with a linear taper more than 1 degree below the horizon. The linear + * taper causes the refraction to linearly approach 0 as the altitude of the + * body approaches the nadir (-90 degrees). + * If the value is the string `"jplhor"`, uses a JPL Horizons + * compatible formula. This is the same algorithm as `"normal"`, + * only without linear tapering; this can result in physically impossible + * altitudes of less than -90 degrees, which may cause problems for some applications. + * (The `"jplhor"` option was created for unit testing against data + * generated by JPL Horizons, and is otherwise not recommended for use.) + * + * @returns {HorizontalCoordinates} + */ +export declare function Horizon(date: FlexibleDateTime, observer: Observer, ra: number, dec: number, refraction?: string): HorizontalCoordinates; +/** + * @brief Represents the geographic location of an observer on the surface of the Earth. + * + * @property {number} latitude + * The observer's geographic latitude in degrees north of the Earth's equator. + * The value is negative for observers south of the equator. + * Must be in the range -90 to +90. + * + * @property {number} longitude + * The observer's geographic longitude in degrees east of the prime meridian + * passing through Greenwich, England. + * The value is negative for observers west of the prime meridian. + * The value should be kept in the range -180 to +180 to minimize floating point errors. + * + * @property {number} height + * The observer's elevation above mean sea level, expressed in meters. + */ +export declare class Observer { + latitude: number; + longitude: number; + height: number; + constructor(latitude: number, longitude: number, height: number); +} +/** + * @brief Returns apparent geocentric true ecliptic coordinates of date for the Sun. + * + * This function is used for calculating the times of equinoxes and solstices. + * + * Geocentric means coordinates as the Sun would appear to a hypothetical observer + * at the center of the Earth. + * Ecliptic coordinates of date are measured along the plane of the Earth's mean + * orbit around the Sun, using the + * equinox + * of the Earth as adjusted for precession and nutation of the Earth's + * axis of rotation on the given date. + * + * @param {FlexibleDateTime} date + * The date and time at which to calculate the Sun's apparent location as seen from + * the center of the Earth. + * + * @returns {EclipticCoordinates} + */ +export declare function SunPosition(date: FlexibleDateTime): EclipticCoordinates; +/** + * @brief Calculates equatorial coordinates of a Solar System body at a given time. + * + * Returns topocentric equatorial coordinates (right ascension and declination) + * in one of two different systems: J2000 or true-equator-of-date. + * Allows optional correction for aberration. + * Always corrects for light travel time (represents the object as seen by the observer + * with light traveling to the Earth at finite speed, not where the object is right now). + * Topocentric refers to a position as seen by an observer on the surface of the Earth. + * This function corrects for + * parallax + * of the object between a geocentric observer and a topocentric observer. + * This is most significant for the Moon, because it is so close to the Earth. + * However, it can have a small effect on the apparent positions of other bodies. + * + * @param {Body} body + * The body for which to find equatorial coordinates. + * Not allowed to be `Body.Earth`. + * + * @param {FlexibleDateTime} date + * Specifies the date and time at which the body is to be observed. + * + * @param {Observer} observer + * The location on the Earth of the observer. + * + * @param {bool} ofdate + * Pass `true` to return equatorial coordinates of date, + * i.e. corrected for precession and nutation at the given date. + * This is needed to get correct horizontal coordinates when you call + * {@link Horizon}. + * Pass `false` to return equatorial coordinates in the J2000 system. + * + * @param {bool} aberration + * Pass `true` to correct for + * aberration, + * or `false` to leave uncorrected. + * + * @returns {EquatorialCoordinates} + * The topocentric coordinates of the body as adjusted for the given observer. + */ +export declare function Equator(body: Body, date: FlexibleDateTime, observer: Observer, ofdate: boolean, aberration: boolean): EquatorialCoordinates; +/** + * @brief Calculates geocentric equatorial coordinates of an observer on the surface of the Earth. + * + * This function calculates a vector from the center of the Earth to + * a point on or near the surface of the Earth, expressed in equatorial + * coordinates. It takes into account the rotation of the Earth at the given + * time, along with the given latitude, longitude, and elevation of the observer. + * + * The caller may pass `ofdate` as `true` to return coordinates relative to the Earth's + * equator at the specified time, or `false` to use the J2000 equator. + * + * The returned vector has components expressed in astronomical units (AU). + * To convert to kilometers, multiply the `x`, `y`, and `z` values by + * the constant value {@link KM_PER_AU}. + * + * The inverse of this function is also available: {@link VectorObserver}. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the observer's position vector. + * + * @param {Observer} observer + * The geographic location of a point on or near the surface of the Earth. + * + * @param {boolean} ofdate + * Selects the date of the Earth's equator in which to express the equatorial coordinates. + * The caller may pass `false` to use the orientation of the Earth's equator + * at noon UTC on January 1, 2000, in which case this function corrects for precession + * and nutation of the Earth as it was at the moment specified by the `time` parameter. + * Or the caller may pass `true` to use the Earth's equator at `time` + * as the orientation. + * + * @returns {Vector} + * An equatorial vector from the center of the Earth to the specified location + * on (or near) the Earth's surface. + */ +export declare function ObserverVector(date: FlexibleDateTime, observer: Observer, ofdate: boolean): Vector; +/** + * @brief Calculates geocentric equatorial position and velocity of an observer on the surface of the Earth. + * + * This function calculates position and velocity vectors of an observer + * on or near the surface of the Earth, expressed in equatorial + * coordinates. It takes into account the rotation of the Earth at the given + * time, along with the given latitude, longitude, and elevation of the observer. + * + * The caller may pass `ofdate` as `true` to return coordinates relative to the Earth's + * equator at the specified time, or `false` to use the J2000 equator. + * + * The returned position vector has components expressed in astronomical units (AU). + * To convert to kilometers, multiply the `x`, `y`, and `z` values by + * the constant value {@link KM_PER_AU}. + * The returned velocity vector has components expressed in AU/day. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the observer's position and velocity vectors. + * + * @param {Observer} observer + * The geographic location of a point on or near the surface of the Earth. + * + * @param {boolean} ofdate + * Selects the date of the Earth's equator in which to express the equatorial coordinates. + * The caller may pass `false` to use the orientation of the Earth's equator + * at noon UTC on January 1, 2000, in which case this function corrects for precession + * and nutation of the Earth as it was at the moment specified by the `time` parameter. + * Or the caller may pass `true` to use the Earth's equator at `time` + * as the orientation. + * + * @returns {StateVector} + */ +export declare function ObserverState(date: FlexibleDateTime, observer: Observer, ofdate: boolean): StateVector; +/** + * @brief Calculates the geographic location corresponding to an equatorial vector. + * + * This is the inverse function of {@link ObserverVector}. + * Given a geocentric equatorial vector, it returns the geographic + * latitude, longitude, and elevation for that vector. + * + * @param {Vector} vector + * The geocentric equatorial position vector for which to find geographic coordinates. + * The components are expressed in Astronomical Units (AU). + * You can calculate AU by dividing kilometers by the constant {@link KM_PER_AU}. + * The time `vector.t` determines the Earth's rotation. + * + * @param {boolean} ofdate + * Selects the date of the Earth's equator in which `vector` is expressed. + * The caller may select `false` to use the orientation of the Earth's equator + * at noon UTC on January 1, 2000, in which case this function corrects for precession + * and nutation of the Earth as it was at the moment specified by `vector.t`. + * Or the caller may select `true` to use the Earth's equator at `vector.t` + * as the orientation. + * + * @returns {Observer} + * The geographic latitude, longitude, and elevation above sea level + * that corresponds to the given equatorial vector. + */ +export declare function VectorObserver(vector: Vector, ofdate: boolean): Observer; +/** + * @brief Calculates the gravitational acceleration experienced by an observer on the Earth. + * + * This function implements the WGS 84 Ellipsoidal Gravity Formula. + * The result is a combination of inward gravitational acceleration + * with outward centrifugal acceleration, as experienced by an observer + * in the Earth's rotating frame of reference. + * The resulting value increases toward the Earth's poles and decreases + * toward the equator, consistent with changes of the weight measured + * by a spring scale of a fixed mass moved to different latitudes and heights + * on the Earth. + * + * @param {number} latitude + * The latitude of the observer in degrees north or south of the equator. + * By formula symmetry, positive latitudes give the same answer as negative + * latitudes, so the sign does not matter. + * + * @param {number} height + * The height above the sea level geoid in meters. + * No range checking is done; however, accuracy is only valid in the + * range 0 to 100000 meters. + * + * @returns {number} + * The effective gravitational acceleration expressed in meters per second squared [m/s^2]. + */ +export declare function ObserverGravity(latitude: number, height: number): number; +/** + * @brief Converts a J2000 mean equator (EQJ) vector to a true ecliptic of date (ETC) vector and angles. + * + * Given coordinates relative to the Earth's equator at J2000 (the instant of noon UTC + * on 1 January 2000), this function converts those coordinates to true ecliptic coordinates + * that are relative to the plane of the Earth's orbit around the Sun on that date. + * + * @param {Vector} eqj + * Equatorial coordinates in the EQJ frame of reference. + * You can call {@link GeoVector} to obtain suitable equatorial coordinates. + * + * @returns {EclipticCoordinates} + */ +export declare function Ecliptic(eqj: Vector): EclipticCoordinates; +/** + * @brief Calculates equatorial geocentric Cartesian coordinates for the Moon. + * + * Given a time of observation, calculates the Moon's position as a vector. + * The vector gives the location of the Moon's center relative to the Earth's center + * with x-, y-, and z-components measured in astronomical units. + * The coordinates are oriented with respect to the Earth's equator at the J2000 epoch. + * In Astronomy Engine, this orientation is called EQJ. + * Based on the Nautical Almanac Office's Improved Lunar Ephemeris of 1954, + * which in turn derives from E. W. Brown's lunar theories. + * Adapted from Turbo Pascal code from the book + * Astronomy on the Personal Computer + * by Montenbruck and Pfleger. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the Moon's geocentric position. + * + * @returns {Vector} + */ +export declare function GeoMoon(date: FlexibleDateTime): Vector; +/** + * @brief Calculates spherical ecliptic geocentric position of the Moon. + * + * Given a time of observation, calculates the Moon's geocentric position + * in ecliptic spherical coordinates. Provides the ecliptic latitude and + * longitude in degrees, and the geocentric distance in astronomical units (AU). + * + * The ecliptic angles are measured in "ECT": relative to the true ecliptic plane and + * equatorial plane at the specified time. This means the Earth's equator + * is corrected for precession and nutation, and the plane of the Earth's + * orbit is corrected for gradual obliquity drift. + * + * This algorithm is based on the Nautical Almanac Office's Improved Lunar Ephemeris of 1954, + * which in turn derives from E. W. Brown's lunar theories from the early twentieth century. + * It is adapted from Turbo Pascal code from the book + * Astronomy on the Personal Computer + * by Montenbruck and Pfleger. + * + * To calculate a J2000 mean equator vector instead, use {@link GeoMoon}. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the Moon's position. + * + * @returns {Spherical} + */ +export declare function EclipticGeoMoon(date: FlexibleDateTime): Spherical; +/** + * @brief Calculates equatorial geocentric position and velocity of the Moon at a given time. + * + * Given a time of observation, calculates the Moon's position and velocity vectors. + * The position and velocity are of the Moon's center relative to the Earth's center. + * The position (x, y, z) components are expressed in AU (astronomical units). + * The velocity (vx, vy, vz) components are expressed in AU/day. + * The coordinates are oriented with respect to the Earth's equator at the J2000 epoch. + * In Astronomy Engine, this orientation is called EQJ. + * If you need the Moon's position only, and not its velocity, + * it is much more efficient to use {@link GeoMoon} instead. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the Moon's geocentric state. + * + * @returns {StateVector} + */ +export declare function GeoMoonState(date: FlexibleDateTime): StateVector; +/** + * @brief Calculates the geocentric position and velocity of the Earth/Moon barycenter. + * + * Given a time of observation, calculates the geocentric position and velocity vectors + * of the Earth/Moon barycenter (EMB). + * The position (x, y, z) components are expressed in AU (astronomical units). + * The velocity (vx, vy, vz) components are expressed in AU/day. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the EMB's geocentric state. + * + * @returns {StateVector} + */ +export declare function GeoEmbState(date: FlexibleDateTime): StateVector; +/** + * @brief Holds the positions and velocities of Jupiter's major 4 moons. + * + * The {@link JupiterMoons} function returns an object of this type + * to report position and velocity vectors for Jupiter's largest 4 moons + * Io, Europa, Ganymede, and Callisto. Each position vector is relative + * to the center of Jupiter. Both position and velocity are oriented in + * the EQJ system (that is, using Earth's equator at the J2000 epoch). + * The positions are expressed in astronomical units (AU), + * and the velocities in AU/day. + * + * @property {StateVector} io + * The position and velocity of Jupiter's moon Io. + * + * @property {StateVector} europa + * The position and velocity of Jupiter's moon Europa. + * + * @property {StateVector} ganymede + * The position and velocity of Jupiter's moon Ganymede. + * + * @property {StateVector} callisto + * The position and velocity of Jupiter's moon Callisto. + */ +export declare class JupiterMoonsInfo { + io: StateVector; + europa: StateVector; + ganymede: StateVector; + callisto: StateVector; + constructor(io: StateVector, europa: StateVector, ganymede: StateVector, callisto: StateVector); +} +/** + * @brief Calculates jovicentric positions and velocities of Jupiter's largest 4 moons. + * + * Calculates position and velocity vectors for Jupiter's moons + * Io, Europa, Ganymede, and Callisto, at the given date and time. + * The vectors are jovicentric (relative to the center of Jupiter). + * Their orientation is the Earth's equatorial system at the J2000 epoch (EQJ). + * The position components are expressed in astronomical units (AU), and the + * velocity components are in AU/day. + * + * To convert to heliocentric vectors, call {@link HelioVector} + * with `Astronomy.Body.Jupiter` to get Jupiter's heliocentric position, then + * add the jovicentric vectors. Likewise, you can call {@link GeoVector} + * to convert to geocentric vectors. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate Jupiter's moons. + * + * @return {JupiterMoonsInfo} + * Position and velocity vectors of Jupiter's largest 4 moons. + */ +export declare function JupiterMoons(date: FlexibleDateTime): JupiterMoonsInfo; +/** + * @brief Calculates a vector from the center of the Sun to the given body at the given time. + * + * Calculates heliocentric (i.e., with respect to the center of the Sun) + * Cartesian coordinates in the J2000 equatorial system of a celestial + * body at a specified time. The position is not corrected for light travel time or aberration. + * + * @param {Body} body + * One of the following values: + * `Body.Sun`, `Body.Moon`, `Body.Mercury`, `Body.Venus`, + * `Body.Earth`, `Body.Mars`, `Body.Jupiter`, `Body.Saturn`, + * `Body.Uranus`, `Body.Neptune`, `Body.Pluto`, + * `Body.SSB`, or `Body.EMB`. + * Also allowed to be a user-defined star created by {@link DefineStar}. + * + * @param {FlexibleDateTime} date + * The date and time for which the body's position is to be calculated. + * + * @returns {Vector} + */ +export declare function HelioVector(body: Body, date: FlexibleDateTime): Vector; +/** + * @brief Calculates the distance between a body and the Sun at a given time. + * + * Given a date and time, this function calculates the distance between + * the center of `body` and the center of the Sun. + * For the planets Mercury through Neptune, this function is significantly + * more efficient than calling {@link HelioVector} followed by taking the length + * of the resulting vector. + * + * @param {Body} body + * A body for which to calculate a heliocentric distance: + * the Sun, Moon, any of the planets, or a user-defined star. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the heliocentric distance. + * + * @returns {number} + * The heliocentric distance in AU. + */ +export declare function HelioDistance(body: Body, date: FlexibleDateTime): number; +/** + * Solve for light travel time of a vector function. + * + * When observing a distant object, for example Jupiter as seen from Earth, + * the amount of time it takes for light to travel from the object to the + * observer can significantly affect the object's apparent position. + * This function is a generic solver that figures out how long in the + * past light must have left the observed object to reach the observer + * at the specified observation time. It requires passing in `func` + * to express an arbitrary position vector as a function of time. + * + * `CorrectLightTravel` repeatedly calls `func`, passing a series of time + * estimates in the past. Then `func` must return a relative position vector between + * the observer and the target. `CorrectLightTravel` keeps calling + * `func` with more and more refined estimates of the time light must have + * left the target to arrive at the observer. + * + * For common use cases, it is simpler to use {@link BackdatePosition} + * for calculating the light travel time correction of one body observing another body. + * + * For geocentric calculations, {@link GeoVector} also backdates the returned + * position vector for light travel time, only it returns the observation time in + * the returned vector's `t` field rather than the backdated time. + * + * @param {function(AstroTime): number} func + * An arbitrary position vector as a function of time: + * function({@link AstroTime}) => {@link Vector}. + * + * @param {AstroTime} time + * The observation time for which to solve for light travel delay. + * + * @returns {AstroVector} + * The position vector at the solved backdated time. + * The `t` field holds the time that light left the observed + * body to arrive at the observer at the observation time. + */ +export declare function CorrectLightTravel(func: (t: AstroTime) => Vector, time: AstroTime): Vector; +/** + * @brief Solve for light travel time correction of apparent position. + * + * When observing a distant object, for example Jupiter as seen from Earth, + * the amount of time it takes for light to travel from the object to the + * observer can significantly affect the object's apparent position. + * + * This function solves the light travel time correction for the apparent + * relative position vector of a target body as seen by an observer body + * at a given observation time. + * + * For geocentric calculations, {@link GeoVector} also includes light + * travel time correction, but the time `t` embedded in its returned vector + * refers to the observation time, not the backdated time that light left + * the observed body. Thus `BackdatePosition` provides direct + * access to the light departure time for callers that need it. + * + * For a more generalized light travel correction solver, see {@link CorrectLightTravel}. + * + * @param {FlexibleDateTime} date + * The time of observation. + * + * @param {Body} observerBody + * The body to be used as the observation location. + * + * @param {Body} targetBody + * The body to be observed. + * + * @param {boolean} aberration + * `true` to correct for aberration, or `false` to leave uncorrected. + * + * @returns {Vector} + * The position vector at the solved backdated time. + * The `t` field holds the time that light left the observed + * body to arrive at the observer at the observation time. + */ +export declare function BackdatePosition(date: FlexibleDateTime, observerBody: Body, targetBody: Body, aberration: boolean): Vector; +/** + * @brief Calculates a vector from the center of the Earth to the given body at the given time. + * + * Calculates geocentric (i.e., with respect to the center of the Earth) + * Cartesian coordinates in the J2000 equatorial system of a celestial + * body at a specified time. The position is always corrected for light travel time: + * this means the position of the body is "back-dated" based on how long it + * takes light to travel from the body to an observer on the Earth. + * Also, the position can optionally be corrected for aberration, an effect + * causing the apparent direction of the body to be shifted based on + * transverse movement of the Earth with respect to the rays of light + * coming from that body. + * + * @param {Body} body + * One of the following values: + * `Body.Sun`, `Body.Moon`, `Body.Mercury`, `Body.Venus`, + * `Body.Earth`, `Body.Mars`, `Body.Jupiter`, `Body.Saturn`, + * `Body.Uranus`, `Body.Neptune`, or `Body.Pluto`. + * Also allowed to be a user-defined star created with {@link DefineStar}. + * + * @param {FlexibleDateTime} date + * The date and time for which the body's position is to be calculated. + * + * @param {boolean} aberration + * Pass `true` to correct for + * aberration, + * or `false` to leave uncorrected. + * + * @returns {Vector} + */ +export declare function GeoVector(body: Body, date: FlexibleDateTime, aberration: boolean): Vector; +/** + * @brief Calculates barycentric position and velocity vectors for the given body. + * + * Given a body and a time, calculates the barycentric position and velocity + * vectors for the center of that body at that time. + * The vectors are expressed in J2000 mean equator coordinates (EQJ). + * + * @param {Body} body + * The celestial body whose barycentric state vector is to be calculated. + * Supported values are `Body.Sun`, `Body.Moon`, `Body.EMB`, `Body.SSB`, and all planets: + * `Body.Mercury`, `Body.Venus`, `Body.Earth`, `Body.Mars`, `Body.Jupiter`, + * `Body.Saturn`, `Body.Uranus`, `Body.Neptune`, `Body.Pluto`. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate position and velocity. + * + * @returns {StateVector} + * An object that contains barycentric position and velocity vectors. + */ +export declare function BaryState(body: Body, date: FlexibleDateTime): StateVector; +/** + * @brief Calculates heliocentric position and velocity vectors for the given body. + * + * Given a body and a time, calculates the position and velocity + * vectors for the center of that body at that time, relative to the center of the Sun. + * The vectors are expressed in J2000 mean equator coordinates (EQJ). + * If you need the position vector only, it is more efficient to call {@link HelioVector}. + * The Sun's center is a non-inertial frame of reference. In other words, the Sun + * experiences acceleration due to gravitational forces, mostly from the larger + * planets (Jupiter, Saturn, Uranus, and Neptune). If you want to calculate momentum, + * kinetic energy, or other quantities that require a non-accelerating frame + * of reference, consider using {@link BaryState} instead. + * + * @param {Body} body + * The celestial body whose heliocentric state vector is to be calculated. + * Supported values are `Body.Sun`, `Body.Moon`, `Body.EMB`, `Body.SSB`, and all planets: + * `Body.Mercury`, `Body.Venus`, `Body.Earth`, `Body.Mars`, `Body.Jupiter`, + * `Body.Saturn`, `Body.Uranus`, `Body.Neptune`, `Body.Pluto`. + * Also allowed to be a user-defined star created by {@link DefineStar}. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate position and velocity. + * + * @returns {StateVector} + * An object that contains heliocentric position and velocity vectors. + */ +export declare function HelioState(body: Body, date: FlexibleDateTime): StateVector; +export interface SearchOptions { + dt_tolerance_seconds?: number; + init_f1?: number; + init_f2?: number; + iter_limit?: number; +} +/** + * @brief Options for the {@link Search} function. + * + * @typedef {object} SearchOptions + * + * @property {number | undefined} dt_tolerance_seconds + * The number of seconds for a time window smaller than which the search + * is considered successful. Using too large a tolerance can result in + * an inaccurate time estimate. Using too small a tolerance can cause + * excessive computation, or can even cause the search to fail because of + * limited floating-point resolution. Defaults to 1 second. + * + * @property {number | undefined} init_f1 + * As an optimization, if the caller of {@link Search} + * has already calculated the value of the function being searched (the parameter `func`) + * at the time coordinate `t1`, it can pass in that value as `init_f1`. + * For very expensive calculations, this can measurably improve performance. + * + * @property {number | undefined} init_f2 + * The same as `init_f1`, except this is the optional initial value of `func(t2)` + * instead of `func(t1)`. + * + * @property {number | undefined} iter_limit + */ +/** + * @brief Finds the time when a function ascends through zero. + * + * Search for next time t (such that t is between `t1` and `t2`) + * that `func(t)` crosses from a negative value to a non-negative value. + * The given function must have "smooth" behavior over the entire inclusive range [`t1`, `t2`], + * meaning that it behaves like a continuous differentiable function. + * It is not required that `t1` < `t2`; `t1` > `t2` + * allows searching backward in time. + * Note: `t1` and `t2` must be chosen such that there is no possibility + * of more than one zero-crossing (ascending or descending), or it is possible + * that the "wrong" event will be found (i.e. not the first event after t1) + * or even that the function will return `null`, indicating that no event was found. + * + * @param {function(AstroTime): number} func + * The function to find an ascending zero crossing for. + * The function must accept a single parameter of type {@link AstroTime} + * and return a numeric value: + * function({@link AstroTime}) => `number` + * + * @param {AstroTime} t1 + * The lower time bound of a search window. + * + * @param {AstroTime} t2 + * The upper time bound of a search window. + * + * @param {SearchOptions | undefined} options + * Options that can tune the behavior of the search. + * Most callers can omit this argument. + * + * @returns {AstroTime | null} + * If the search is successful, returns the date and time of the solution. + * If the search fails, returns `null`. + */ +export declare function Search(f: (t: AstroTime) => number, t1: AstroTime, t2: AstroTime, options?: SearchOptions): AstroTime | null; +/** + * @brief Searches for when the Sun reaches a given ecliptic longitude. + * + * Searches for the moment in time when the center of the Sun reaches a given apparent + * ecliptic longitude, as seen from the center of the Earth, within a given range of dates. + * This function can be used to determine equinoxes and solstices. + * However, it is usually more convenient and efficient to call {@link Seasons} + * to calculate equinoxes and solstices for a given calendar year. + * `SearchSunLongitude` is more general in that it allows searching for arbitrary longitude values. + * + * @param {number} targetLon + * The desired ecliptic longitude of date in degrees. + * This may be any value in the range [0, 360), although certain + * values have conventional meanings: + * + * When `targetLon` is 0, finds the March equinox, + * which is the moment spring begins in the northern hemisphere + * and the beginning of autumn in the southern hemisphere. + * + * When `targetLon` is 180, finds the September equinox, + * which is the moment autumn begins in the northern hemisphere and + * spring begins in the southern hemisphere. + * + * When `targetLon` is 90, finds the northern solstice, which is the + * moment summer begins in the northern hemisphere and winter + * begins in the southern hemisphere. + * + * When `targetLon` is 270, finds the southern solstice, which is the + * moment winter begins in the northern hemisphere and summer + * begins in the southern hemisphere. + * + * @param {FlexibleDateTime} dateStart + * A date and time known to be earlier than the desired longitude event. + * + * @param {number} limitDays + * A floating point number of days, which when added to `dateStart`, + * yields a date and time known to be after the desired longitude event. + * + * @returns {AstroTime | null} + * The date and time when the Sun reaches the apparent ecliptic longitude `targetLon` + * within the range of times specified by `dateStart` and `limitDays`. + * If the Sun does not reach the target longitude within the specified time range, or the + * time range is excessively wide, the return value is `null`. + * To avoid a `null` return value, the caller must pick a time window around + * the event that is within a few days but not so small that the event might fall outside the window. + */ +export declare function SearchSunLongitude(targetLon: number, dateStart: FlexibleDateTime, limitDays: number): AstroTime | null; +/** + * @brief Returns one body's ecliptic longitude with respect to another, as seen from the Earth. + * + * This function determines where one body appears around the ecliptic plane + * (the plane of the Earth's orbit around the Sun) as seen from the Earth, + * relative to the another body's apparent position. + * The function returns an angle in the half-open range [0, 360) degrees. + * The value is the ecliptic longitude of `body1` relative to the ecliptic + * longitude of `body2`. + * + * The angle is 0 when the two bodies are at the same ecliptic longitude + * as seen from the Earth. The angle increases in the prograde direction + * (the direction that the planets orbit the Sun and the Moon orbits the Earth). + * + * When the angle is 180 degrees, it means the two bodies appear on opposite sides + * of the sky for an Earthly observer. + * + * Neither `body1` nor `body2` is allowed to be `Body.Earth`. + * If this happens, the function throws an exception. + * + * @param {Body} body1 + * The first body, whose longitude is to be found relative to the second body. + * + * @param {Body} body2 + * The second body, relative to which the longitude of the first body is to be found. + * + * @param {FlexibleDateTime} date + * The date and time of the observation. + * + * @returns {number} + * An angle in the range [0, 360), expressed in degrees. + */ +export declare function PairLongitude(body1: Body, body2: Body, date: FlexibleDateTime): number; +/** + * @brief Calculates the angular separation between the Sun and the given body. + * + * Returns the full angle seen from + * the Earth, between the given body and the Sun. + * Unlike {@link PairLongitude}, this function does not + * project the body's "shadow" onto the ecliptic; + * the angle is measured in 3D space around the plane that + * contains the centers of the Earth, the Sun, and `body`. + * + * @param {Body} body + * The name of a supported celestial body other than the Earth. + * + * @param {FlexibleDateTime} date + * The time at which the angle from the Sun is to be found. + * + * @returns {number} + * An angle in degrees in the range [0, 180]. + */ +export declare function AngleFromSun(body: Body, date: FlexibleDateTime): number; +/** + * @brief Calculates heliocentric ecliptic longitude of a body. + * + * This function calculates the angle around the plane of the Earth's orbit + * of a celestial body, as seen from the center of the Sun. + * The angle is measured prograde (in the direction of the Earth's orbit around the Sun) + * in degrees from the true equinox of date. The ecliptic longitude is always in the range [0, 360). + * + * @param {Body} body + * A body other than the Sun. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the ecliptic longitude. + * + * @returns {number} + */ +export declare function EclipticLongitude(body: Body, date: FlexibleDateTime): number; +/** + * @brief Information about the apparent brightness and sunlit phase of a celestial object. + * + * @property {AstroTime} time + * The date and time pertaining to the other calculated values in this object. + * + * @property {number} mag + * The apparent visual magnitude of the celestial body. + * + * @property {number} phase_angle + * The angle in degrees as seen from the center of the celestial body between the Sun and the Earth. + * The value is always in the range 0 to 180. + * The phase angle provides a measure of what fraction of the body's face appears + * illuminated by the Sun as seen from the Earth. + * When the observed body is the Sun, the `phase` property is set to 0, + * although this has no physical meaning because the Sun emits, rather than reflects, light. + * When the phase is near 0 degrees, the body appears "full". + * When it is 90 degrees, the body appears "half full". + * And when it is 180 degrees, the body appears "new" and is very difficult to see + * because it is both dim and lost in the Sun's glare as seen from the Earth. + * + * @property {number} phase_fraction + * The fraction of the body's face that is illuminated by the Sun, as seen from the Earth. + * Calculated from `phase_angle` for convenience. + * This value ranges from 0 to 1. + * + * @property {number} helio_dist + * The distance between the center of the Sun and the center of the body in + * astronomical units (AU). + * + * @property {number} geo_dist + * The distance between the center of the Earth and the center of the body in AU. + * + * @property {Vector} gc + * Geocentric coordinates: the 3D vector from the center of the Earth to the center of the body. + * The components are in expressed in AU and are oriented with respect to the J2000 equatorial plane. + * + * @property {Vector} hc + * Heliocentric coordinates: The 3D vector from the center of the Sun to the center of the body. + * Like `gc`, `hc` is expressed in AU and oriented with respect + * to the J2000 equatorial plane. + * + * @property {number | undefined} ring_tilt + * For Saturn, this is the angular tilt of the planet's rings in degrees away + * from the line of sight from the Earth. When the value is near 0, the rings + * appear edge-on from the Earth and are therefore difficult to see. + * When `ring_tilt` approaches its maximum value (about 27 degrees), + * the rings appear widest and brightest from the Earth. + * Unlike the JPL Horizons online tool, + * this library includes the effect of the ring tilt angle in the calculated value + * for Saturn's visual magnitude. + * For all bodies other than Saturn, the value of `ring_tilt` is `undefined`. + */ +export declare class IlluminationInfo { + time: AstroTime; + mag: number; + phase_angle: number; + helio_dist: number; + geo_dist: number; + gc: Vector; + hc: Vector; + ring_tilt?: number | undefined; + phase_fraction: number; + constructor(time: AstroTime, mag: number, phase_angle: number, helio_dist: number, geo_dist: number, gc: Vector, hc: Vector, ring_tilt?: number | undefined); +} +/** + * @brief Calculates visual magnitude and related information about a body. + * + * Calculates the phase angle, visual magnitude, + * and other values relating to the body's illumination + * at the given date and time, as seen from the Earth. + * + * @param {Body} body + * The name of the celestial body being observed. + * Not allowed to be `Body.Earth`. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the illumination data for the given body. + * + * @returns {IlluminationInfo} + */ +export declare function Illumination(body: Body, date: FlexibleDateTime): IlluminationInfo; +/** + * @brief Searches for when the Earth and a given body reach a relative ecliptic longitude separation. + * + * Searches for the date and time the relative ecliptic longitudes of + * the specified body and the Earth, as seen from the Sun, reach a certain + * difference. This function is useful for finding conjunctions and oppositions + * of the planets. For the opposition of a superior planet (Mars, Jupiter, ..., Pluto), + * or the inferior conjunction of an inferior planet (Mercury, Venus), + * call with `targetRelLon` = 0. The 0 value indicates that both + * planets are on the same ecliptic longitude line, ignoring the other planet's + * distance above or below the plane of the Earth's orbit. + * For superior conjunctions, call with `targetRelLon` = 180. + * This means the Earth and the other planet are on opposite sides of the Sun. + * + * @param {Body} body + * Any planet other than the Earth. + * + * @param {number} targetRelLon + * The desired angular difference in degrees between the ecliptic longitudes + * of `body` and the Earth. Must be in the range (-180, +180]. + * + * @param {FlexibleDateTime} startDate + * The date and time after which to find the next occurrence of the + * body and the Earth reaching the desired relative longitude. + * + * @returns {AstroTime} + * The time when the Earth and the body next reach the specified relative longitudes. + */ +export declare function SearchRelativeLongitude(body: Body, targetRelLon: number, startDate: FlexibleDateTime): AstroTime; +/** + * @brief Determines the moon's phase expressed as an ecliptic longitude. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the moon's phase. + * + * @returns {number} + * A value in the range [0, 360) indicating the difference + * in ecliptic longitude between the center of the Sun and the + * center of the Moon, as seen from the center of the Earth. + * Certain longitude values have conventional meanings: + * + * * 0 = new moon + * * 90 = first quarter + * * 180 = full moon + * * 270 = third quarter + */ +export declare function MoonPhase(date: FlexibleDateTime): number; +/** + * @brief Searches for the date and time that the Moon reaches a specified phase. + * + * Lunar phases are defined in terms of geocentric ecliptic longitudes + * with respect to the Sun. When the Moon and the Sun have the same ecliptic + * longitude, that is defined as a new moon. When the two ecliptic longitudes + * are 180 degrees apart, that is defined as a full moon. + * To enumerate quarter lunar phases, it is simpler to call + * {@link SearchMoonQuarter} once, followed by repeatedly calling + * {@link NextMoonQuarter}. `SearchMoonPhase` is only + * necessary for finding other lunar phases than the usual quarter phases. + * + * @param {number} targetLon + * The difference in geocentric ecliptic longitude between the Sun and Moon + * that specifies the lunar phase being sought. This can be any value + * in the range [0, 360). Here are some helpful examples: + * 0 = new moon, + * 90 = first quarter, + * 180 = full moon, + * 270 = third quarter. + * + * @param {FlexibleDateTime} dateStart + * The beginning of the window of time in which to search. + * + * @param {number} limitDays + * The floating point number of days away from `dateStart` + * that limits the window of time in which to search. + * If the value is negative, the search is performed into the past from `startTime`. + * Otherwise, the search is performed into the future from `startTime`. + * + * @returns {AstroTime | null} + * If successful, returns the date and time the moon reaches the phase specified by `targetlon`. + * This function will return `null` if the phase does not occur within `limitDays` of `startTime`; + * that is, if the search window is too small. + */ +export declare function SearchMoonPhase(targetLon: number, dateStart: FlexibleDateTime, limitDays: number): AstroTime | null; +/** + * @brief A quarter lunar phase, along with when it occurs. + * + * @property {number} quarter + * An integer as follows: + * 0 = new moon, + * 1 = first quarter, + * 2 = full moon, + * 3 = third quarter. + * + * @property {AstroTime} time + * The date and time of the quarter lunar phase. + */ +export declare class MoonQuarter { + quarter: number; + time: AstroTime; + constructor(quarter: number, time: AstroTime); +} +/** + * @brief Finds the first quarter lunar phase after the specified date and time. + * + * The quarter lunar phases are: new moon, first quarter, full moon, and third quarter. + * To enumerate quarter lunar phases, call `SearchMoonQuarter` once, + * then pass its return value to {@link NextMoonQuarter} to find the next + * `MoonQuarter`. Keep calling `NextMoonQuarter` in a loop, + * passing the previous return value as the argument to the next call. + * + * @param {FlexibleDateTime} dateStart + * The date and time after which to find the first quarter lunar phase. + * + * @returns {MoonQuarter} + */ +export declare function SearchMoonQuarter(dateStart: FlexibleDateTime): MoonQuarter; +/** + * @brief Finds the next quarter lunar phase in a series. + * + * Given a {@link MoonQuarter} object, finds the next consecutive + * quarter lunar phase. See remarks in {@link SearchMoonQuarter} + * for explanation of usage. + * + * @param {MoonQuarter} mq + * The return value of a prior call to {@link MoonQuarter} or `NextMoonQuarter`. + * + * @returns {MoonQuarter} + */ +export declare function NextMoonQuarter(mq: MoonQuarter): MoonQuarter; +/** + * @brief Information about idealized atmospheric variables at a given elevation. + * + * @property {number} pressure + * Atmospheric pressure in pascals. + * + * @property {number} temperature + * Atmospheric temperature in kelvins. + * + * @property {number} density + * Atmospheric density relative to sea level. + */ +export declare class AtmosphereInfo { + pressure: number; + temperature: number; + density: number; + constructor(pressure: number, temperature: number, density: number); +} +/** + * @brief Calculates U.S. Standard Atmosphere (1976) variables as a function of elevation. + * + * This function calculates idealized values of pressure, temperature, and density + * using the U.S. Standard Atmosphere (1976) model. + * 1. COESA, U.S. Standard Atmosphere, 1976, U.S. Government Printing Office, Washington, DC, 1976. + * 2. Jursa, A. S., Ed., Handbook of Geophysics and the Space Environment, Air Force Geophysics Laboratory, 1985. + * See: + * https://hbcp.chemnetbase.com/faces/documents/14_12/14_12_0001.xhtml + * https://ntrs.nasa.gov/api/citations/19770009539/downloads/19770009539.pdf + * https://www.ngdc.noaa.gov/stp/space-weather/online-publications/miscellaneous/us-standard-atmosphere-1976/us-standard-atmosphere_st76-1562_noaa.pdf + * + * @param {number} elevationMeters + * The elevation above sea level at which to calculate atmospheric variables. + * Must be in the range -500 to +100000, or an exception will occur. + * + * @returns {AtmosphereInfo} + */ +export declare function Atmosphere(elevationMeters: number): AtmosphereInfo; +/** + * @brief Searches for the next time a celestial body rises or sets as seen by an observer on the Earth. + * + * This function finds the next rise or set time of the Sun, Moon, or planet other than the Earth. + * Rise time is when the body first starts to be visible above the horizon. + * For example, sunrise is the moment that the top of the Sun first appears to peek above the horizon. + * Set time is the moment when the body appears to vanish below the horizon. + * Therefore, this function adjusts for the apparent angular radius of the observed body + * (significant only for the Sun and Moon). + * + * This function corrects for a typical value of atmospheric refraction, which causes celestial + * bodies to appear higher above the horizon than they would if the Earth had no atmosphere. + * Astronomy Engine uses a correction of 34 arcminutes. Real-world refraction varies based + * on air temperature, pressure, and humidity; such weather-based conditions are outside + * the scope of Astronomy Engine. + * + * Note that rise or set may not occur in every 24 hour period. + * For example, near the Earth's poles, there are long periods of time where + * the Sun stays below the horizon, never rising. + * Also, it is possible for the Moon to rise just before midnight but not set during the subsequent 24-hour day. + * This is because the Moon sets nearly an hour later each day due to orbiting the Earth a + * significant amount during each rotation of the Earth. + * Therefore callers must not assume that the function will always succeed. + * + * @param {Body} body + * The Sun, Moon, any planet other than the Earth, + * or a user-defined star that was created by a call to {@link DefineStar}. + * + * @param {Observer} observer + * Specifies the geographic coordinates and elevation above sea level of the observer. + * + * @param {number} direction + * Either +1 to find rise time or -1 to find set time. + * Any other value will cause an exception to be thrown. + * + * @param {FlexibleDateTime} dateStart + * The date and time after which the specified rise or set time is to be found. + * + * @param {number} limitDays + * Limits how many days to search for a rise or set time, and defines + * the direction in time to search. When `limitDays` is positive, the + * search is performed into the future, after `dateStart`. + * When negative, the search is performed into the past, before `dateStart`. + * To limit a rise or set time to the same day, you can use a value of 1 day. + * In cases where you want to find the next rise or set time no matter how far + * in the future (for example, for an observer near the south pole), you can + * pass in a larger value like 365. + * + * @param {number?} metersAboveGround + * Defaults to 0.0 if omitted. + * Usually the observer is located at ground level. Then this parameter + * should be zero. But if the observer is significantly higher than ground + * level, for example in an airplane, this parameter should be a positive + * number indicating how far above the ground the observer is. + * An exception occurs if `metersAboveGround` is negative. + * + * @returns {AstroTime | null} + * The date and time of the rise or set event, or null if no such event + * occurs within the specified time window. + */ +export declare function SearchRiseSet(body: Body, observer: Observer, direction: number, dateStart: FlexibleDateTime, limitDays: number, metersAboveGround?: number): AstroTime | null; +/** + * @brief Finds the next time the center of a body passes through a given altitude. + * + * Finds when the center of the given body ascends or descends through a given + * altitude angle, as seen by an observer at the specified location on the Earth. + * By using the appropriate combination of `direction` and `altitude` parameters, + * this function can be used to find when civil, nautical, or astronomical twilight + * begins (dawn) or ends (dusk). + * + * Civil dawn begins before sunrise when the Sun ascends through 6 degrees below + * the horizon. To find civil dawn, pass +1 for `direction` and -6 for `altitude`. + * + * Civil dusk ends after sunset when the Sun descends through 6 degrees below the horizon. + * To find civil dusk, pass -1 for `direction` and -6 for `altitude`. + * + * Nautical twilight is similar to civil twilight, only the `altitude` value should be -12 degrees. + * + * Astronomical twilight uses -18 degrees as the `altitude` value. + * + * By convention for twilight time calculations, the altitude is not corrected for + * atmospheric refraction. This is because the target altitudes are below the horizon, + * and refraction is not directly observable. + * + * `SearchAltitude` is not intended to find rise/set times of a body for two reasons: + * (1) Rise/set times of the Sun or Moon are defined by their topmost visible portion, not their centers. + * (2) Rise/set times are affected significantly by atmospheric refraction. + * Therefore, it is better to use {@link SearchRiseSet} to find rise/set times, which + * corrects for both of these considerations. + * + * `SearchAltitude` will not work reliably for altitudes at or near the body's + * maximum or minimum altitudes. To find the time a body reaches minimum or maximum altitude + * angles, use {@link SearchHourAngle}. + * + * @param {Body} body + * The Sun, Moon, any planet other than the Earth, + * or a user-defined star that was created by a call to {@link DefineStar}. + * + * @param {Observer} observer + * Specifies the geographic coordinates and elevation above sea level of the observer. + * + * @param {number} direction + * Either +1 to find when the body ascends through the altitude, + * or -1 for when the body descends through the altitude. + * Any other value will cause an exception to be thrown. + * + * @param {FlexibleDateTime} dateStart + * The date and time after which the specified altitude event is to be found. + * + * @param {number} limitDays + * Limits how many days to search for the body reaching the altitude angle, + * and defines the direction in time to search. When `limitDays` is positive, the + * search is performed into the future, after `dateStart`. + * When negative, the search is performed into the past, before `dateStart`. + * To limit the search to the same day, you can use a value of 1 day. + * In cases where you want to find the altitude event no matter how far + * in the future (for example, for an observer near the south pole), you can + * pass in a larger value like 365. + * + * @param {number} altitude + * The desired altitude angle of the body's center above (positive) + * or below (negative) the observer's local horizon, expressed in degrees. + * Must be in the range [-90, +90]. + * + * @returns {AstroTime | null} + * The date and time of the altitude event, or null if no such event + * occurs within the specified time window. + */ +export declare function SearchAltitude(body: Body, observer: Observer, direction: number, dateStart: FlexibleDateTime, limitDays: number, altitude: number): AstroTime | null; +/** + * @brief Horizontal position of a body upon reaching an hour angle. + * + * Returns information about an occurrence of a celestial body + * reaching a given hour angle as seen by an observer at a given + * location on the surface of the Earth. + * + * @property {AstroTime} time + * The date and time of the celestial body reaching the hour angle. + * + * @property {HorizontalCoordinates} hor + * Topocentric horizontal coordinates for the body + * at the time indicated by the `time` property. + */ +export declare class HourAngleEvent { + time: AstroTime; + hor: HorizontalCoordinates; + constructor(time: AstroTime, hor: HorizontalCoordinates); +} +/** + * @brief Searches for the time when the center of a body reaches a specified hour angle as seen by an observer on the Earth. + * + * The *hour angle* of a celestial body indicates its position in the sky with respect + * to the Earth's rotation. The hour angle depends on the location of the observer on the Earth. + * The hour angle is 0 when the body's center reaches its highest angle above the horizon in a given day. + * The hour angle increases by 1 unit for every sidereal hour that passes after that point, up + * to 24 sidereal hours when it reaches the highest point again. So the hour angle indicates + * the number of hours that have passed since the most recent time that the body has culminated, + * or reached its highest point. + * + * This function searches for the next or previous time a celestial body reaches the given hour angle + * relative to the date and time specified by `dateStart`. + * To find when a body culminates, pass 0 for `hourAngle`. + * To find when a body reaches its lowest point in the sky, pass 12 for `hourAngle`. + * + * Note that, especially close to the Earth's poles, a body as seen on a given day + * may always be above the horizon or always below the horizon, so the caller cannot + * assume that a culminating object is visible nor that an object is below the horizon + * at its minimum altitude. + * + * The function returns the date and time, along with the horizontal coordinates + * of the body at that time, as seen by the given observer. + * + * @param {Body} body + * The Sun, Moon, any planet other than the Earth, + * or a user-defined star that was created by a call to {@link DefineStar}. + * + * @param {Observer} observer + * Specifies the geographic coordinates and elevation above sea level of the observer. + * + * @param {number} hourAngle + * The hour angle expressed in + * sidereal + * hours for which the caller seeks to find the body attain. + * The value must be in the range [0, 24). + * The hour angle represents the number of sidereal hours that have + * elapsed since the most recent time the body crossed the observer's local + * meridian. + * This specifying `hourAngle` = 0 finds the moment in time + * the body reaches the highest angular altitude in a given sidereal day. + * + * @param {FlexibleDateTime} dateStart + * The date and time after which the desired hour angle crossing event + * is to be found. + * + * @param {number} direction + * The direction in time to perform the search: a positive value + * searches forward in time, a negative value searches backward in time. + * The function throws an exception if `direction` is zero. + * + * @returns {HourAngleEvent} + */ +export declare function SearchHourAngle(body: Body, observer: Observer, hourAngle: number, dateStart: FlexibleDateTime, direction?: number): HourAngleEvent; +/** + * @brief Finds the hour angle of a body for a given observer and time. + * + * The *hour angle* of a celestial body indicates its position in the sky with respect + * to the Earth's rotation. The hour angle depends on the location of the observer on the Earth. + * The hour angle is 0 when the body's center reaches its highest angle above the horizon in a given day. + * The hour angle increases by 1 unit for every sidereal hour that passes after that point, up + * to 24 sidereal hours when it reaches the highest point again. So the hour angle indicates + * the number of hours that have passed since the most recent time that the body has culminated, + * or reached its highest point. + * + * This function returns the hour angle of the body as seen at the given time and geogrpahic location. + * The hour angle is a number in the half-open range [0, 24). + * + * @param {Body} body + * The body whose observed hour angle is to be found. + * + * @param {FlexibleDateTime} date + * The date and time of the observation. + * + * @param {Observer} observer + * The geographic location where the observation takes place. + * + * @returns {number} + */ +export declare function HourAngle(body: Body, date: FlexibleDateTime, observer: Observer): number; +/** + * @brief When the seasons change for a given calendar year. + * + * Represents the dates and times of the two solstices + * and the two equinoxes in a given calendar year. + * These four events define the changing of the seasons on the Earth. + * + * @property {AstroTime} mar_equinox + * The date and time of the March equinox in the given calendar year. + * This is the moment in March that the plane of the Earth's equator passes + * through the center of the Sun; thus the Sun's declination + * changes from a negative number to a positive number. + * The March equinox defines + * the beginning of spring in the northern hemisphere and + * the beginning of autumn in the southern hemisphere. + * + * @property {AstroTime} jun_solstice + * The date and time of the June solstice in the given calendar year. + * This is the moment in June that the Sun reaches its most positive + * declination value. + * At this moment the Earth's north pole is most tilted most toward the Sun. + * The June solstice defines + * the beginning of summer in the northern hemisphere and + * the beginning of winter in the southern hemisphere. + * + * @property {AstroTime} sep_equinox + * The date and time of the September equinox in the given calendar year. + * This is the moment in September that the plane of the Earth's equator passes + * through the center of the Sun; thus the Sun's declination + * changes from a positive number to a negative number. + * The September equinox defines + * the beginning of autumn in the northern hemisphere and + * the beginning of spring in the southern hemisphere. + * + * @property {AstroTime} dec_solstice + * The date and time of the December solstice in the given calendar year. + * This is the moment in December that the Sun reaches its most negative + * declination value. + * At this moment the Earth's south pole is tilted most toward the Sun. + * The December solstice defines + * the beginning of winter in the northern hemisphere and + * the beginning of summer in the southern hemisphere. + */ +export declare class SeasonInfo { + mar_equinox: AstroTime; + jun_solstice: AstroTime; + sep_equinox: AstroTime; + dec_solstice: AstroTime; + constructor(mar_equinox: AstroTime, jun_solstice: AstroTime, sep_equinox: AstroTime, dec_solstice: AstroTime); +} +/** + * @brief Finds the equinoxes and solstices for a given calendar year. + * + * @param {number | AstroTime} year + * The integer value or `AstroTime` object that specifies + * the UTC calendar year for which to find equinoxes and solstices. + * + * @returns {SeasonInfo} + */ +export declare function Seasons(year: (number | AstroTime)): SeasonInfo; +/** + * @brief The viewing conditions of a body relative to the Sun. + * + * Represents the angular separation of a body from the Sun as seen from the Earth + * and the relative ecliptic longitudes between that body and the Earth as seen from the Sun. + * + * @property {AstroTime} time + * The date and time of the observation. + * + * @property {string} visibility + * Either `"morning"` or `"evening"`, + * indicating when the body is most easily seen. + * + * @property {number} elongation + * The angle in degrees, as seen from the center of the Earth, + * of the apparent separation between the body and the Sun. + * This angle is measured in 3D space and is not projected onto the ecliptic plane. + * When `elongation` is less than a few degrees, the body is very + * difficult to see from the Earth because it is lost in the Sun's glare. + * The elongation is always in the range [0, 180]. + * + * @property {number} ecliptic_separation + * The absolute value of the difference between the body's ecliptic longitude + * and the Sun's ecliptic longitude, both as seen from the center of the Earth. + * This angle measures around the plane of the Earth's orbit (the ecliptic), + * and ignores how far above or below that plane the body is. + * The ecliptic separation is measured in degrees and is always in the range [0, 180]. + * + * @see {@link Elongation} + */ +export declare class ElongationEvent { + time: AstroTime; + visibility: string; + elongation: number; + ecliptic_separation: number; + constructor(time: AstroTime, visibility: string, elongation: number, ecliptic_separation: number); +} +/** + * @brief Calculates the viewing conditions of a body relative to the Sun. + * + * Calculates angular separation of a body from the Sun as seen from the Earth + * and the relative ecliptic longitudes between that body and the Earth as seen from the Sun. + * See the return type {@link ElongationEvent} for details. + * + * This function is helpful for determining how easy + * it is to view a planet away from the Sun's glare on a given date. + * It also determines whether the object is visible in the morning or evening; + * this is more important the smaller the elongation is. + * It is also used to determine how far a planet is from opposition, conjunction, or quadrature. + * + * @param {Body} body + * The name of the observed body. Not allowed to be `Body.Earth`. + * + * @param {FlexibleDateTime} date + * The date and time of the observation. + * + * @returns {ElongationEvent} + */ +export declare function Elongation(body: Body, date: FlexibleDateTime): ElongationEvent; +/** + * @brief Finds the next time Mercury or Venus reaches maximum elongation. + * + * Searches for the next maximum elongation event for Mercury or Venus + * that occurs after the given start date. Calling with other values + * of `body` will result in an exception. + * Maximum elongation occurs when the body has the greatest + * angular separation from the Sun, as seen from the Earth. + * Returns an `ElongationEvent` object containing the date and time of the next + * maximum elongation, the elongation in degrees, and whether + * the body is visible in the morning or evening. + * + * @param {Body} body + * Either `Body.Mercury` or `Body.Venus`. + * + * @param {FlexibleDateTime} startDate + * The date and time after which to search for the next maximum elongation event. + * + * @returns {ElongationEvent} + */ +export declare function SearchMaxElongation(body: Body, startDate: FlexibleDateTime): ElongationEvent; +/** + * @brief Searches for the date and time Venus will next appear brightest as seen from the Earth. + * + * @param {Body} body + * Currently only `Body.Venus` is supported. + * Mercury's peak magnitude occurs at superior conjunction, when it is impossible to see from Earth, + * so peak magnitude events have little practical value for that planet. + * The Moon reaches peak magnitude very close to full moon, which can be found using + * {@link SearchMoonQuarter} or {@link SearchMoonPhase}. + * The other planets reach peak magnitude very close to opposition, + * which can be found using {@link SearchRelativeLongitude}. + * + * @param {FlexibleDateTime} startDate + * The date and time after which to find the next peak magnitude event. + * + * @returns {IlluminationInfo} + */ +export declare function SearchPeakMagnitude(body: Body, startDate: FlexibleDateTime): IlluminationInfo; +/** + * @brief The two kinds of apsis: pericenter (closest) and apocenter (farthest). + * + * `Pericenter`: The body is at its closest distance to the object it orbits. + * `Apocenter`: The body is at its farthest distance from the object it orbits. + * + * @enum {number} + */ +export declare enum ApsisKind { + Pericenter = 0, + Apocenter = 1 +} +/** + * @brief A closest or farthest point in a body's orbit around its primary. + * + * For a planet orbiting the Sun, apsis is a perihelion or aphelion, respectively. + * For the Moon orbiting the Earth, apsis is a perigee or apogee, respectively. + * + * @property {AstroTime} time + * The date and time of the apsis. + * + * @property {ApsisKind} kind + * For a closest approach (perigee or perihelion), `kind` is `ApsisKind.Pericenter`. + * For a farthest distance event (apogee or aphelion), `kind` is `ApsisKind.Apocenter`. + * + * @property {number} dist_au + * The distance between the centers of the two bodies in astronomical units (AU). + * + * @property {number} dist_km + * The distance between the centers of the two bodies in kilometers. + * + * @see {@link SearchLunarApsis} + * @see {@link NextLunarApsis} + * @see {@link SearchPlanetApsis} + * @see {@link NextPlanetApsis} + */ +export declare class Apsis { + time: AstroTime; + kind: ApsisKind; + dist_au: number; + dist_km: number; + constructor(time: AstroTime, kind: ApsisKind, dist_au: number); +} +/** + * @brief Finds the next perigee or apogee of the Moon. + * + * Finds the next perigee (closest approach) or apogee (farthest remove) of the Moon + * that occurs after the specified date and time. + * + * @param {FlexibleDateTime} startDate + * The date and time after which to find the next perigee or apogee. + * + * @returns {Apsis} + */ +export declare function SearchLunarApsis(startDate: FlexibleDateTime): Apsis; +/** + * @brief Finds the next lunar apsis (perigee or apogee) in a series. + * + * Given a lunar apsis returned by an initial call to {@link SearchLunarApsis}, + * or a previous call to `NextLunarApsis`, finds the next lunar apsis. + * If the given apsis is a perigee, this function finds the next apogee, and vice versa. + * + * @param {Apsis} apsis + * A lunar perigee or apogee event. + * + * @returns {Apsis} + * The successor apogee for the given perigee, or the successor perigee for the given apogee. + */ +export declare function NextLunarApsis(apsis: Apsis): Apsis; +/** + * @brief Finds the next perihelion or aphelion of a planet. + * + * Finds the date and time of a planet's perihelion (closest approach to the Sun) + * or aphelion (farthest distance from the Sun) after a given time. + * + * Given a date and time to start the search in `startTime`, this function finds the + * next date and time that the center of the specified planet reaches the closest or farthest point + * in its orbit with respect to the center of the Sun, whichever comes first + * after `startTime`. + * + * The closest point is called *perihelion* and the farthest point is called *aphelion*. + * The word *apsis* refers to either event. + * + * To iterate through consecutive alternating perihelion and aphelion events, + * call `SearchPlanetApsis` once, then use the return value to call + * {@link NextPlanetApsis}. After that, keep feeding the previous return value + * from `NextPlanetApsis` into another call of `NextPlanetApsis` + * as many times as desired. + * + * @param {Body} body + * The planet for which to find the next perihelion/aphelion event. + * Not allowed to be `Body.Sun` or `Body.Moon`. + * + * @param {FlexibleDateTime} startTime + * The date and time at which to start searching for the next perihelion or aphelion. + * + * @returns {Apsis} + * The next perihelion or aphelion that occurs after `startTime`. + */ +export declare function SearchPlanetApsis(body: Body, startTime: FlexibleDateTime): Apsis; +/** + * @brief Finds the next planetary perihelion or aphelion event in a series. + * + * This function requires an {@link Apsis} value obtained from a call + * to {@link SearchPlanetApsis} or `NextPlanetApsis`. + * Given an aphelion event, this function finds the next perihelion event, and vice versa. + * See {@link SearchPlanetApsis} for more details. + * + * @param {Body} body + * The planet for which to find the next perihelion/aphelion event. + * Not allowed to be `Body.Sun` or `Body.Moon`. + * Must match the body passed into the call that produced the `apsis` parameter. + * + * @param {Apsis} apsis + * An apsis event obtained from a call to {@link SearchPlanetApsis} or `NextPlanetApsis`. + * + * @returns {Apsis} + * Same as the return value for {@link SearchPlanetApsis}. + */ +export declare function NextPlanetApsis(body: Body, apsis: Apsis): Apsis; +/** + * @brief Calculates the inverse of a rotation matrix. + * + * Given a rotation matrix that performs some coordinate transform, + * this function returns the matrix that reverses that transform. + * + * @param {RotationMatrix} rotation + * The rotation matrix to be inverted. + * + * @returns {RotationMatrix} + * The inverse rotation matrix. + */ +export declare function InverseRotation(rotation: RotationMatrix): RotationMatrix; +/** + * @brief Creates a rotation based on applying one rotation followed by another. + * + * Given two rotation matrices, returns a combined rotation matrix that is + * equivalent to rotating based on the first matrix, followed by the second. + * + * @param {RotationMatrix} a + * The first rotation to apply. + * + * @param {RotationMatrix} b + * The second rotation to apply. + * + * @returns {RotationMatrix} + * The combined rotation matrix. + */ +export declare function CombineRotation(a: RotationMatrix, b: RotationMatrix): RotationMatrix; +/** + * @brief Creates an identity rotation matrix. + * + * Returns a rotation matrix that has no effect on orientation. + * This matrix can be the starting point for other operations, + * such as using a series of calls to {@link Pivot} to + * create a custom rotation matrix. + * + * @returns {RotationMatrix} + * The identity matrix. + */ +export declare function IdentityMatrix(): RotationMatrix; +/** +* @brief Re-orients a rotation matrix by pivoting it by an angle around one of its axes. +* +* Given a rotation matrix, a selected coordinate axis, and an angle in degrees, +* this function pivots the rotation matrix by that angle around that coordinate axis. +* +* For example, if you have rotation matrix that converts ecliptic coordinates (ECL) +* to horizontal coordinates (HOR), but you really want to convert ECL to the orientation +* of a telescope camera pointed at a given body, you can use `Astronomy_Pivot` twice: +* (1) pivot around the zenith axis by the body's azimuth, then (2) pivot around the +* western axis by the body's altitude angle. The resulting rotation matrix will then +* reorient ECL coordinates to the orientation of your telescope camera. +* +* @param {RotationMatrix} rotation +* The input rotation matrix. +* +* @param {number} axis +* An integer that selects which coordinate axis to rotate around: +* 0 = x, 1 = y, 2 = z. Any other value will cause an exception. +* +* @param {number} angle +* An angle in degrees indicating the amount of rotation around the specified axis. +* Positive angles indicate rotation counterclockwise as seen from the positive +* direction along that axis, looking towards the origin point of the orientation system. +* Any finite number of degrees is allowed, but best precision will result from +* keeping `angle` in the range [-360, +360]. +* +* @returns {RotationMatrix} +* A pivoted matrix object. +*/ +export declare function Pivot(rotation: RotationMatrix, axis: 0 | 1 | 2, angle: number): RotationMatrix; +/** + * @brief Converts spherical coordinates to Cartesian coordinates. + * + * Given spherical coordinates and a time at which they are valid, + * returns a vector of Cartesian coordinates. The returned value + * includes the time, as required by `AstroTime`. + * + * @param {Spherical} sphere + * Spherical coordinates to be converted. + * + * @param {FlexibleDateTime} time + * The time that should be included in the returned vector. + * + * @returns {Vector} + * The vector form of the supplied spherical coordinates. + */ +export declare function VectorFromSphere(sphere: Spherical, time: FlexibleDateTime): Vector; +/** + * @brief Given an equatorial vector, calculates equatorial angular coordinates. + * + * @param {Vector} vec + * A vector in an equatorial coordinate system. + * + * @returns {EquatorialCoordinates} + * Angular coordinates expressed in the same equatorial system as `vec`. + */ +export declare function EquatorFromVector(vec: Vector): EquatorialCoordinates; +/** + * @brief Converts Cartesian coordinates to spherical coordinates. + * + * Given a Cartesian vector, returns latitude, longitude, and distance. + * + * @param {Vector} vector + * Cartesian vector to be converted to spherical coordinates. + * + * @returns {Spherical} + * Spherical coordinates that are equivalent to the given vector. + */ +export declare function SphereFromVector(vector: Vector): Spherical; +/** + * @brief Converts Cartesian coordinates to horizontal coordinates. + * + * Given a horizontal Cartesian vector, returns horizontal azimuth and altitude. + * + * *IMPORTANT:* This function differs from {@link SphereFromVector} in two ways: + * - `SphereFromVector` returns a `lon` value that represents azimuth defined counterclockwise + * from north (e.g., west = +90), but this function represents a clockwise rotation + * (e.g., east = +90). The difference is because `SphereFromVector` is intended + * to preserve the vector "right-hand rule", while this function defines azimuth in a more + * traditional way as used in navigation and cartography. + * - This function optionally corrects for atmospheric refraction, while `SphereFromVector` does not. + * + * The returned object contains the azimuth in `lon`. + * It is measured in degrees clockwise from north: east = +90 degrees, west = +270 degrees. + * + * The altitude is stored in `lat`. + * + * The distance to the observed object is stored in `dist`, + * and is expressed in astronomical units (AU). + * + * @param {Vector} vector + * Cartesian vector to be converted to horizontal coordinates. + * + * @param {string} refraction + * `"normal"`: correct altitude for atmospheric refraction (recommended). + * `"jplhor"`: for JPL Horizons compatibility testing only; not recommended for normal use. + * `null`: no atmospheric refraction correction is performed. + * + * @returns {Spherical} + */ +export declare function HorizonFromVector(vector: Vector, refraction: string): Spherical; +/** + * @brief Given apparent angular horizontal coordinates in `sphere`, calculate horizontal vector. + * + * @param {Spherical} sphere + * A structure that contains apparent horizontal coordinates: + * `lat` holds the refracted altitude angle, + * `lon` holds the azimuth in degrees clockwise from north, + * and `dist` holds the distance from the observer to the object in AU. + * + * @param {FlexibleDateTime} time + * The date and time of the observation. This is needed because the returned + * vector object requires a valid time value when passed to certain other functions. + * + * @param {string} refraction + * `"normal"`: correct altitude for atmospheric refraction (recommended). + * `"jplhor"`: for JPL Horizons compatibility testing only; not recommended for normal use. + * `null`: no atmospheric refraction correction is performed. + * + * @returns {Vector} + * A vector in the horizontal system: `x` = north, `y` = west, and `z` = zenith (up). + */ +export declare function VectorFromHorizon(sphere: Spherical, time: FlexibleDateTime, refraction: string): Vector; +/** + * @brief Calculates the amount of "lift" to an altitude angle caused by atmospheric refraction. + * + * Given an altitude angle and a refraction option, calculates + * the amount of "lift" caused by atmospheric refraction. + * This is the number of degrees higher in the sky an object appears + * due to the lensing of the Earth's atmosphere. + * This function works best near sea level. + * To correct for higher elevations, call {@link Atmosphere} for that + * elevation and multiply the refraction angle by the resulting relative density. + * + * @param {string} refraction + * `"normal"`: correct altitude for atmospheric refraction (recommended). + * `"jplhor"`: for JPL Horizons compatibility testing only; not recommended for normal use. + * `null`: no atmospheric refraction correction is performed. + * + * @param {number} altitude + * An altitude angle in a horizontal coordinate system. Must be a value between -90 and +90. + * + * @returns {number} + * The angular adjustment in degrees to be added to the altitude angle to correct for atmospheric lensing. + */ +export declare function Refraction(refraction: string, altitude: number): number; +/** + * @brief Calculates the inverse of an atmospheric refraction angle. + * + * Given an observed altitude angle that includes atmospheric refraction, + * calculates the negative angular correction to obtain the unrefracted + * altitude. This is useful for cases where observed horizontal + * coordinates are to be converted to another orientation system, + * but refraction first must be removed from the observed position. + * + * @param {string} refraction + * `"normal"`: correct altitude for atmospheric refraction (recommended). + * `"jplhor"`: for JPL Horizons compatibility testing only; not recommended for normal use. + * `null`: no atmospheric refraction correction is performed. + * + * @param {number} bent_altitude + * The apparent altitude that includes atmospheric refraction. + * + * @returns {number} + * The angular adjustment in degrees to be added to the + * altitude angle to correct for atmospheric lensing. + * This will be less than or equal to zero. + */ +export declare function InverseRefraction(refraction: string, bent_altitude: number): number; +/** + * @brief Applies a rotation to a vector, yielding a rotated vector. + * + * This function transforms a vector in one orientation to a vector + * in another orientation. + * + * @param {RotationMatrix} rotation + * A rotation matrix that specifies how the orientation of the vector is to be changed. + * + * @param {Vector} vector + * The vector whose orientation is to be changed. + * + * @returns {Vector} + * A vector in the orientation specified by `rotation`. + */ +export declare function RotateVector(rotation: RotationMatrix, vector: Vector): Vector; +/** + * @brief Applies a rotation to a state vector, yielding a rotated vector. + * + * This function transforms a state vector in one orientation to a vector + * in another orientation. + * + * @param {RotationMatrix} rotation + * A rotation matrix that specifies how the orientation of the state vector is to be changed. + * + * @param {StateVector} state + * The state vector whose orientation is to be changed. + * Both the position and velocity components are transformed. + * + * @return {StateVector} + * A state vector in the orientation specified by `rotation`. + */ +export declare function RotateState(rotation: RotationMatrix, state: StateVector): StateVector; +/** + * @brief Calculates a rotation matrix from J2000 mean equator (EQJ) to J2000 mean ecliptic (ECL). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQJ = equatorial system, using equator at J2000 epoch. + * Target: ECL = ecliptic system, using equator at J2000 epoch. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQJ to ECL. + */ +export declare function Rotation_EQJ_ECL(): RotationMatrix; +/** + * @brief Calculates a rotation matrix from J2000 mean ecliptic (ECL) to J2000 mean equator (EQJ). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: ECL = ecliptic system, using equator at J2000 epoch. + * Target: EQJ = equatorial system, using equator at J2000 epoch. + * + * @returns {RotationMatrix} + * A rotation matrix that converts ECL to EQJ. + */ +export declare function Rotation_ECL_EQJ(): RotationMatrix; +/** + * @brief Calculates a rotation matrix from J2000 mean equator (EQJ) to equatorial of-date (EQD). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQJ = equatorial system, using equator at J2000 epoch. + * Target: EQD = equatorial system, using equator of the specified date/time. + * + * @param {FlexibleDateTime} time + * The date and time at which the Earth's equator defines the target orientation. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQJ to EQD at `time`. + */ +export declare function Rotation_EQJ_EQD(time: FlexibleDateTime): RotationMatrix; +/** + * @brief Calculates a rotation matrix from J2000 mean equator (EQJ) to true ecliptic of date (ECT). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQJ = equatorial system, using equator at J2000 epoch. + * Target: ECT = ecliptic system, using true equinox of the specified date/time. + * + * @param {FlexibleDateTime} time + * The date and time at which the Earth's equator defines the target orientation. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQJ to ECT at `time`. + */ +export declare function Rotation_EQJ_ECT(time: FlexibleDateTime): RotationMatrix; +/** + * @brief Calculates a rotation matrix from true ecliptic of date (ECT) to J2000 mean equator (EQJ). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: ECT = ecliptic system, using true equinox of the specified date/time. + * Target: EQJ = equatorial system, using equator at J2000 epoch. + * + * @param {FlexibleDateTime} time + * The date and time at which the Earth's equator defines the target orientation. + * + * @returns {RotationMatrix} + * A rotation matrix that converts ECT to EQJ at `time`. + */ +export declare function Rotation_ECT_EQJ(time: FlexibleDateTime): RotationMatrix; +/** + * @brief Calculates a rotation matrix from equatorial of-date (EQD) to J2000 mean equator (EQJ). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQD = equatorial system, using equator of the specified date/time. + * Target: EQJ = equatorial system, using equator at J2000 epoch. + * + * @param {FlexibleDateTime} time + * The date and time at which the Earth's equator defines the source orientation. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQD at `time` to EQJ. + */ +export declare function Rotation_EQD_EQJ(time: FlexibleDateTime): RotationMatrix; +/** + * @brief Calculates a rotation matrix from equatorial of-date (EQD) to horizontal (HOR). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQD = equatorial system, using equator of the specified date/time. + * Target: HOR = horizontal system. + * + * Use `HorizonFromVector` to convert the return value + * to a traditional altitude/azimuth pair. + * + * @param {FlexibleDateTime} time + * The date and time at which the Earth's equator applies. + * + * @param {Observer} observer + * A location near the Earth's mean sea level that defines the observer's horizon. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQD to HOR at `time` and for `observer`. + * The components of the horizontal vector are: + * x = north, y = west, z = zenith (straight up from the observer). + * These components are chosen so that the "right-hand rule" works for the vector + * and so that north represents the direction where azimuth = 0. + */ +export declare function Rotation_EQD_HOR(time: FlexibleDateTime, observer: Observer): RotationMatrix; +/** + * @brief Calculates a rotation matrix from horizontal (HOR) to equatorial of-date (EQD). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: HOR = horizontal system (x=North, y=West, z=Zenith). + * Target: EQD = equatorial system, using equator of the specified date/time. + * + * @param {FlexibleDateTime} time + * The date and time at which the Earth's equator applies. + * + * @param {Observer} observer + * A location near the Earth's mean sea level that defines the observer's horizon. + * + * @returns {RotationMatrix} + * A rotation matrix that converts HOR to EQD at `time` and for `observer`. + */ +export declare function Rotation_HOR_EQD(time: FlexibleDateTime, observer: Observer): RotationMatrix; +/** + * @brief Calculates a rotation matrix from horizontal (HOR) to J2000 equatorial (EQJ). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: HOR = horizontal system (x=North, y=West, z=Zenith). + * Target: EQJ = equatorial system, using equator at the J2000 epoch. + * + * @param {FlexibleDateTime} time + * The date and time of the observation. + * + * @param {Observer} observer + * A location near the Earth's mean sea level that defines the observer's horizon. + * + * @returns {RotationMatrix} + * A rotation matrix that converts HOR to EQJ at `time` and for `observer`. + */ +export declare function Rotation_HOR_EQJ(time: FlexibleDateTime, observer: Observer): RotationMatrix; +/** + * @brief Calculates a rotation matrix from J2000 mean equator (EQJ) to horizontal (HOR). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQJ = equatorial system, using the equator at the J2000 epoch. + * Target: HOR = horizontal system. + * + * Use {@link HorizonFromVector} to convert the return value + * to a traditional altitude/azimuth pair. + * + * @param {FlexibleDateTime} time + * The date and time of the desired horizontal orientation. + * + * @param {Observer} observer + * A location near the Earth's mean sea level that defines the observer's horizon. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQJ to HOR at `time` and for `observer`. + * The components of the horizontal vector are: + * x = north, y = west, z = zenith (straight up from the observer). + * These components are chosen so that the "right-hand rule" works for the vector + * and so that north represents the direction where azimuth = 0. + */ +export declare function Rotation_EQJ_HOR(time: FlexibleDateTime, observer: Observer): RotationMatrix; +/** + * @brief Calculates a rotation matrix from equatorial of-date (EQD) to J2000 mean ecliptic (ECL). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQD = equatorial system, using equator of date. + * Target: ECL = ecliptic system, using equator at J2000 epoch. + * + * @param {FlexibleDateTime} time + * The date and time of the source equator. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQD to ECL. + */ +export declare function Rotation_EQD_ECL(time: FlexibleDateTime): RotationMatrix; +/** + * @brief Calculates a rotation matrix from J2000 mean ecliptic (ECL) to equatorial of-date (EQD). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: ECL = ecliptic system, using equator at J2000 epoch. + * Target: EQD = equatorial system, using equator of date. + * + * @param {FlexibleDateTime} time + * The date and time of the desired equator. + * + * @returns {RotationMatrix} + * A rotation matrix that converts ECL to EQD. + */ +export declare function Rotation_ECL_EQD(time: FlexibleDateTime): RotationMatrix; +/** + * @brief Calculates a rotation matrix from J2000 mean ecliptic (ECL) to horizontal (HOR). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: ECL = ecliptic system, using equator at J2000 epoch. + * Target: HOR = horizontal system. + * + * Use {@link HorizonFromVector} to convert the return value + * to a traditional altitude/azimuth pair. + * + * @param {FlexibleDateTime} time + * The date and time of the desired horizontal orientation. + * + * @param {Observer} observer + * A location near the Earth's mean sea level that defines the observer's horizon. + * + * @returns {RotationMatrix} + * A rotation matrix that converts ECL to HOR at `time` and for `observer`. + * The components of the horizontal vector are: + * x = north, y = west, z = zenith (straight up from the observer). + * These components are chosen so that the "right-hand rule" works for the vector + * and so that north represents the direction where azimuth = 0. + */ +export declare function Rotation_ECL_HOR(time: FlexibleDateTime, observer: Observer): RotationMatrix; +/** + * @brief Calculates a rotation matrix from horizontal (HOR) to J2000 mean ecliptic (ECL). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: HOR = horizontal system. + * Target: ECL = ecliptic system, using equator at J2000 epoch. + * + * @param {FlexibleDateTime} time + * The date and time of the horizontal observation. + * + * @param {Observer} observer + * The location of the horizontal observer. + * + * @returns {RotationMatrix} + * A rotation matrix that converts HOR to ECL. + */ +export declare function Rotation_HOR_ECL(time: FlexibleDateTime, observer: Observer): RotationMatrix; +/** + * @brief Calculates a rotation matrix from J2000 mean equator (EQJ) to galactic (GAL). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQJ = equatorial system, using the equator at the J2000 epoch. + * Target: GAL = galactic system (IAU 1958 definition). + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQJ to GAL. + */ +export declare function Rotation_EQJ_GAL(): RotationMatrix; +/** + * @brief Calculates a rotation matrix from galactic (GAL) to J2000 mean equator (EQJ). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: GAL = galactic system (IAU 1958 definition). + * Target: EQJ = equatorial system, using the equator at the J2000 epoch. + * + * @returns {RotationMatrix} + * A rotation matrix that converts GAL to EQJ. + */ +export declare function Rotation_GAL_EQJ(): RotationMatrix; +/** + * @brief Calculates a rotation matrix from true ecliptic of date (ECT) to equator of date (EQD). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: ECT = true ecliptic of date + * Target: EQD = equator of date + * + * @param {FlexibleDateTime} time + * The date and time of the ecliptic/equator conversion. + * + * @returns {RotationMatrix} + * A rotation matrix that converts ECT to EQD. + */ +export declare function Rotation_ECT_EQD(time: FlexibleDateTime): RotationMatrix; +/** + * @brief Calculates a rotation matrix from equator of date (EQD) to true ecliptic of date (ECT). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQD = equator of date + * Target: ECT = true ecliptic of date + * + * @param {FlexibleDateTime} time + * The date and time of the equator/ecliptic conversion. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQD to ECT. + */ +export declare function Rotation_EQD_ECT(time: FlexibleDateTime): RotationMatrix; +/** + * @brief Reports the constellation that a given celestial point lies within. + * + * @property {string} symbol + * 3-character mnemonic symbol for the constellation, e.g. "Ori". + * + * @property {string} name + * Full name of constellation, e.g. "Orion". + * + * @property {number} ra1875 + * Right ascension expressed in B1875 coordinates. + * + * @property {number} dec1875 + * Declination expressed in B1875 coordinates. + */ +export declare class ConstellationInfo { + symbol: string; + name: string; + ra1875: number; + dec1875: number; + constructor(symbol: string, name: string, ra1875: number, dec1875: number); +} +/** + * @brief Determines the constellation that contains the given point in the sky. + * + * Given J2000 equatorial (EQJ) coordinates of a point in the sky, + * determines the constellation that contains that point. + * + * @param {number} ra + * The right ascension (RA) of a point in the sky, using the J2000 equatorial system. + * + * @param {number} dec + * The declination (DEC) of a point in the sky, using the J2000 equatorial system. + * + * @returns {ConstellationInfo} + * An object that contains the 3-letter abbreviation and full name + * of the constellation that contains the given (ra,dec), along with + * the converted B1875 (ra,dec) for that point. + */ +export declare function Constellation(ra: number, dec: number): ConstellationInfo; +/** + * @brief The different kinds of lunar/solar eclipses.. + * + * `Penumbral`: A lunar eclipse in which only the Earth's penumbra falls on the Moon. (Never used for a solar eclipse.) + * `Partial`: A partial lunar/solar eclipse. + * `Annular`: A solar eclipse in which the entire Moon is visible against the Sun, but the Sun appears as a ring around the Moon. (Never used for a lunar eclipse.) + * `Total`: A total lunar/solar eclipse. + * + * @enum {string} + */ +export declare enum EclipseKind { + Penumbral = "penumbral", + Partial = "partial", + Annular = "annular", + Total = "total" +} +/** + * @brief Returns information about a lunar eclipse. + * + * Returned by {@link SearchLunarEclipse} or {@link NextLunarEclipse} + * to report information about a lunar eclipse event. + * When a lunar eclipse is found, it is classified as penumbral, partial, or total. + * Penumbral eclipses are difficult to observe, because the Moon is only slightly dimmed + * by the Earth's penumbra; no part of the Moon touches the Earth's umbra. + * Partial eclipses occur when part, but not all, of the Moon touches the Earth's umbra. + * Total eclipses occur when the entire Moon passes into the Earth's umbra. + * + * The `kind` field thus holds one of the enum values `EclipseKind.Penumbral`, `EclipseKind.Partial`, + * or `EclipseKind.Total`, depending on the kind of lunar eclipse found. + * + * The `obscuration` field holds a value in the range [0, 1] that indicates what fraction + * of the Moon's apparent disc area is covered by the Earth's umbra at the eclipse's peak. + * This indicates how dark the peak eclipse appears. For penumbral eclipses, the obscuration + * is 0, because the Moon does not pass through the Earth's umbra. For partial eclipses, + * the obscuration is somewhere between 0 and 1. For total lunar eclipses, the obscuration is 1. + * + * Field `peak` holds the date and time of the peak of the eclipse, when it is at its peak. + * + * Fields `sd_penum`, `sd_partial`, and `sd_total` hold the semi-duration of each phase + * of the eclipse, which is half of the amount of time the eclipse spends in each + * phase (expressed in minutes), or 0 if the eclipse never reaches that phase. + * By converting from minutes to days, and subtracting/adding with `peak`, the caller + * may determine the date and time of the beginning/end of each eclipse phase. + * + * @property {EclipseKind} kind + * The type of lunar eclipse found. + * + * @property {number} obscuration + * The peak fraction of the Moon's apparent disc that is covered by the Earth's umbra. + * + * @property {AstroTime} peak + * The time of the eclipse at its peak. + * + * @property {number} sd_penum + * The semi-duration of the penumbral phase in minutes. + * + * @property {number} sd_partial + * The semi-duration of the penumbral phase in minutes, or 0.0 if none. + * + * @property {number} sd_total + * The semi-duration of the penumbral phase in minutes, or 0.0 if none. + * + */ +export declare class LunarEclipseInfo { + kind: EclipseKind; + obscuration: number; + peak: AstroTime; + sd_penum: number; + sd_partial: number; + sd_total: number; + constructor(kind: EclipseKind, obscuration: number, peak: AstroTime, sd_penum: number, sd_partial: number, sd_total: number); +} +/** + * @brief Searches for a lunar eclipse. + * + * This function finds the first lunar eclipse that occurs after `startTime`. + * A lunar eclipse may be penumbral, partial, or total. + * See {@link LunarEclipseInfo} for more information. + * To find a series of lunar eclipses, call this function once, + * then keep calling {@link NextLunarEclipse} as many times as desired, + * passing in the `peak` value returned from the previous call. + * + * @param {FlexibleDateTime} date + * The date and time for starting the search for a lunar eclipse. + * + * @returns {LunarEclipseInfo} + */ +export declare function SearchLunarEclipse(date: FlexibleDateTime): LunarEclipseInfo; +/** + * @brief Reports the time and geographic location of the peak of a solar eclipse. + * + * Returned by {@link SearchGlobalSolarEclipse} or {@link NextGlobalSolarEclipse} + * to report information about a solar eclipse event. + * + * The eclipse is classified as partial, annular, or total, depending on the + * maximum amount of the Sun's disc obscured, as seen at the peak location + * on the surface of the Earth. + * + * The `kind` field thus holds one of the values `EclipseKind.Partial`, `EclipseKind.Annular`, or `EclipseKind.Total`. + * A total eclipse is when the peak observer sees the Sun completely blocked by the Moon. + * An annular eclipse is like a total eclipse, but the Moon is too far from the Earth's surface + * to completely block the Sun; instead, the Sun takes on a ring-shaped appearance. + * A partial eclipse is when the Moon blocks part of the Sun's disc, but nobody on the Earth + * observes either a total or annular eclipse. + * + * If `kind` is `EclipseKind.Total` or `EclipseKind.Annular`, the `latitude` and `longitude` + * fields give the geographic coordinates of the center of the Moon's shadow projected + * onto the daytime side of the Earth at the instant of the eclipse's peak. + * If `kind` has any other value, `latitude` and `longitude` are undefined and should + * not be used. + * + * For total or annular eclipses, the `obscuration` field holds the fraction (0, 1] + * of the Sun's apparent disc area that is blocked from view by the Moon's silhouette, + * as seen by an observer located at the geographic coordinates `latitude`, `longitude` + * at the darkest time `peak`. The value will always be 1 for total eclipses, and less than + * 1 for annular eclipses. + * For partial eclipses, `obscuration` is undefined and should not be used. + * This is because there is little practical use for an obscuration value of + * a partial eclipse without supplying a particular observation location. + * Developers who wish to find an obscuration value for partial solar eclipses should therefore use + * {@link SearchLocalSolarEclipse} and provide the geographic coordinates of an observer. + * + * @property {EclipseKind} kind + * One of the following enumeration values: `EclipseKind.Partial`, `EclipseKind.Annular`, `EclipseKind.Total`. + * + * @property {number | undefined} obscuration + * The peak fraction of the Sun's apparent disc area obscured by the Moon (total and annular eclipses only) + * + * @property {AstroTime} peak + * The date and time when the solar eclipse is darkest. + * This is the instant when the axis of the Moon's shadow cone passes closest to the Earth's center. + * + * @property {number} distance + * The distance in kilometers between the axis of the Moon's shadow cone + * and the center of the Earth at the time indicated by `peak`. + * + * @property {number | undefined} latitude + * If `kind` holds `EclipseKind.Total`, the geographic latitude in degrees + * where the center of the Moon's shadow falls on the Earth at the + * time indicated by `peak`; otherwise, `latitude` holds `undefined`. + * + * @property {number | undefined} longitude + * If `kind` holds `EclipseKind.Total`, the geographic longitude in degrees + * where the center of the Moon's shadow falls on the Earth at the + * time indicated by `peak`; otherwise, `longitude` holds `undefined`. + */ +export declare class GlobalSolarEclipseInfo { + kind: EclipseKind; + obscuration: number | undefined; + peak: AstroTime; + distance: number; + latitude?: number | undefined; + longitude?: number | undefined; + constructor(kind: EclipseKind, obscuration: number | undefined, peak: AstroTime, distance: number, latitude?: number | undefined, longitude?: number | undefined); +} +/** + * @brief Searches for the next lunar eclipse in a series. + * + * After using {@link SearchLunarEclipse} to find the first lunar eclipse + * in a series, you can call this function to find the next consecutive lunar eclipse. + * Pass in the `peak` value from the {@link LunarEclipseInfo} returned by the + * previous call to `SearchLunarEclipse` or `NextLunarEclipse` + * to find the next lunar eclipse. + * + * @param {FlexibleDateTime} prevEclipseTime + * A date and time near a full moon. Lunar eclipse search will start at the next full moon. + * + * @returns {LunarEclipseInfo} + */ +export declare function NextLunarEclipse(prevEclipseTime: FlexibleDateTime): LunarEclipseInfo; +/** + * @brief Searches for a solar eclipse visible anywhere on the Earth's surface. + * + * This function finds the first solar eclipse that occurs after `startTime`. + * A solar eclipse may be partial, annular, or total. + * See {@link GlobalSolarEclipseInfo} for more information. + * To find a series of solar eclipses, call this function once, + * then keep calling {@link NextGlobalSolarEclipse} as many times as desired, + * passing in the `peak` value returned from the previous call. + * + * @param {FlexibleDateTime} startTime + * The date and time for starting the search for a solar eclipse. + * + * @returns {GlobalSolarEclipseInfo} + */ +export declare function SearchGlobalSolarEclipse(startTime: FlexibleDateTime): GlobalSolarEclipseInfo; +/** + * @brief Searches for the next global solar eclipse in a series. + * + * After using {@link SearchGlobalSolarEclipse} to find the first solar eclipse + * in a series, you can call this function to find the next consecutive solar eclipse. + * Pass in the `peak` value from the {@link GlobalSolarEclipseInfo} returned by the + * previous call to `SearchGlobalSolarEclipse` or `NextGlobalSolarEclipse` + * to find the next solar eclipse. + * + * @param {FlexibleDateTime} prevEclipseTime + * A date and time near a new moon. Solar eclipse search will start at the next new moon. + * + * @returns {GlobalSolarEclipseInfo} + */ +export declare function NextGlobalSolarEclipse(prevEclipseTime: FlexibleDateTime): GlobalSolarEclipseInfo; +/** + * @brief Holds a time and the observed altitude of the Sun at that time. + * + * When reporting a solar eclipse observed at a specific location on the Earth + * (a "local" solar eclipse), a series of events occur. In addition + * to the time of each event, it is important to know the altitude of the Sun, + * because each event may be invisible to the observer if the Sun is below + * the horizon. + * + * If `altitude` is negative, the event is theoretical only; it would be + * visible if the Earth were transparent, but the observer cannot actually see it. + * If `altitude` is positive but less than a few degrees, visibility will be impaired by + * atmospheric interference (sunrise or sunset conditions). + * + * @property {AstroTime} time + * The date and time of the event. + * + * @property {number} altitude + * The angular altitude of the center of the Sun above/below the horizon, at `time`, + * corrected for atmospheric refraction and expressed in degrees. + */ +export declare class EclipseEvent { + time: AstroTime; + altitude: number; + constructor(time: AstroTime, altitude: number); +} +/** + * @brief Information about a solar eclipse as seen by an observer at a given time and geographic location. + * + * Returned by {@link SearchLocalSolarEclipse} or {@link NextLocalSolarEclipse} + * to report information about a solar eclipse as seen at a given geographic location. + * + * When a solar eclipse is found, it is classified by setting `kind` + * to `EclipseKind.Partial`, `EclipseKind.Annular`, or `EclipseKind.Total`. + * A partial solar eclipse is when the Moon does not line up directly enough with the Sun + * to completely block the Sun's light from reaching the observer. + * An annular eclipse occurs when the Moon's disc is completely visible against the Sun + * but the Moon is too far away to completely block the Sun's light; this leaves the + * Sun with a ring-like appearance. + * A total eclipse occurs when the Moon is close enough to the Earth and aligned with the + * Sun just right to completely block all sunlight from reaching the observer. + * + * The `obscuration` field reports what fraction of the Sun's disc appears blocked + * by the Moon when viewed by the observer at the peak eclipse time. + * This is a value that ranges from 0 (no blockage) to 1 (total eclipse). + * The obscuration value will be between 0 and 1 for partial eclipses and annular eclipses. + * The value will be exactly 1 for total eclipses. Obscuration gives an indication + * of how dark the eclipse appears. + * + * There are 5 "event" fields, each of which contains a time and a solar altitude. + * Field `peak` holds the date and time of the center of the eclipse, when it is at its peak. + * The fields `partial_begin` and `partial_end` are always set, and indicate when + * the eclipse begins/ends. If the eclipse reaches totality or becomes annular, + * `total_begin` and `total_end` indicate when the total/annular phase begins/ends. + * When an event field is valid, the caller must also check its `altitude` field to + * see whether the Sun is above the horizon at the time indicated by the `time` field. + * See {@link EclipseEvent} for more information. + * + * @property {EclipseKind} kind + * The type of solar eclipse found: `EclipseKind.Partial`, `EclipseKind.Annular`, or `EclipseKind.Total`. + * + * @property {number} obscuration + * The fraction of the Sun's apparent disc area obscured by the Moon at the eclipse peak. + * + * @property {EclipseEvent} partial_begin + * The time and Sun altitude at the beginning of the eclipse. + * + * @property {EclipseEvent | undefined} total_begin + * If this is an annular or a total eclipse, the time and Sun altitude when annular/total phase begins; otherwise undefined. + * + * @property {EclipseEvent} peak + * The time and Sun altitude when the eclipse reaches its peak. + * + * @property {EclipseEvent | undefined} total_end + * If this is an annular or a total eclipse, the time and Sun altitude when annular/total phase ends; otherwise undefined. + * + * @property {EclipseEvent} partial_end + * The time and Sun altitude at the end of the eclipse. + */ +export declare class LocalSolarEclipseInfo { + kind: EclipseKind; + obscuration: number; + partial_begin: EclipseEvent; + total_begin: EclipseEvent | undefined; + peak: EclipseEvent; + total_end: EclipseEvent | undefined; + partial_end: EclipseEvent; + constructor(kind: EclipseKind, obscuration: number, partial_begin: EclipseEvent, total_begin: EclipseEvent | undefined, peak: EclipseEvent, total_end: EclipseEvent | undefined, partial_end: EclipseEvent); +} +/** + * @brief Searches for a solar eclipse visible at a specific location on the Earth's surface. + * + * This function finds the first solar eclipse that occurs after `startTime`. + * A solar eclipse may be partial, annular, or total. + * See {@link LocalSolarEclipseInfo} for more information. + * + * To find a series of solar eclipses, call this function once, + * then keep calling {@link NextLocalSolarEclipse} as many times as desired, + * passing in the `peak` value returned from the previous call. + * + * IMPORTANT: An eclipse reported by this function might be partly or + * completely invisible to the observer due to the time of day. + * See {@link LocalSolarEclipseInfo} for more information about this topic. + * + * @param {FlexibleDateTime} startTime + * The date and time for starting the search for a solar eclipse. + * + * @param {Observer} observer + * The geographic location of the observer. + * + * @returns {LocalSolarEclipseInfo} + */ +export declare function SearchLocalSolarEclipse(startTime: FlexibleDateTime, observer: Observer): LocalSolarEclipseInfo; +/** + * @brief Searches for the next local solar eclipse in a series. + * + * After using {@link SearchLocalSolarEclipse} to find the first solar eclipse + * in a series, you can call this function to find the next consecutive solar eclipse. + * Pass in the `peak` value from the {@link LocalSolarEclipseInfo} returned by the + * previous call to `SearchLocalSolarEclipse` or `NextLocalSolarEclipse` + * to find the next solar eclipse. + * This function finds the first solar eclipse that occurs after `startTime`. + * A solar eclipse may be partial, annular, or total. + * See {@link LocalSolarEclipseInfo} for more information. + * + * @param {FlexibleDateTime} prevEclipseTime + * The date and time for starting the search for a solar eclipse. + * + * @param {Observer} observer + * The geographic location of the observer. + * + * @returns {LocalSolarEclipseInfo} + */ +export declare function NextLocalSolarEclipse(prevEclipseTime: FlexibleDateTime, observer: Observer): LocalSolarEclipseInfo; +/** + * @brief Information about a transit of Mercury or Venus, as seen from the Earth. + * + * Returned by {@link SearchTransit} or {@link NextTransit} to report + * information about a transit of Mercury or Venus. + * A transit is when Mercury or Venus passes between the Sun and Earth so that + * the other planet is seen in silhouette against the Sun. + * + * The calculations are performed from the point of view of a geocentric observer. + * + * @property {AstroTime} start + * The date and time at the beginning of the transit. + * This is the moment the planet first becomes visible against the Sun in its background. + * + * @property {AstroTime} peak + * When the planet is most aligned with the Sun, as seen from the Earth. + * + * @property {AstroTime} finish + * The date and time at the end of the transit. + * This is the moment the planet is last seen against the Sun in its background. + * + * @property {number} separation + * The minimum angular separation, in arcminutes, between the centers of the Sun and the planet. + * This angle pertains to the time stored in `peak`. + */ +export declare class TransitInfo { + start: AstroTime; + peak: AstroTime; + finish: AstroTime; + separation: number; + constructor(start: AstroTime, peak: AstroTime, finish: AstroTime, separation: number); +} +/** + * @brief Searches for the first transit of Mercury or Venus after a given date. + * + * Finds the first transit of Mercury or Venus after a specified date. + * A transit is when an inferior planet passes between the Sun and the Earth + * so that the silhouette of the planet is visible against the Sun in the background. + * To continue the search, pass the `finish` time in the returned structure to + * {@link NextTransit}. + * + * @param {Body} body + * The planet whose transit is to be found. Must be `Body.Mercury` or `Body.Venus`. + * + * @param {FlexibleDateTime} startTime + * The date and time for starting the search for a transit. + * + * @returns {TransitInfo} + */ +export declare function SearchTransit(body: Body, startTime: FlexibleDateTime): TransitInfo; +/** + * @brief Searches for the next transit of Mercury or Venus in a series. + * + * After calling {@link SearchTransit} to find a transit of Mercury or Venus, + * this function finds the next transit after that. + * Keep calling this function as many times as you want to keep finding more transits. + * + * @param {Body} body + * The planet whose transit is to be found. Must be `Body.Mercury` or `Body.Venus`. + * + * @param {FlexibleDateTime} prevTransitTime + * A date and time near the previous transit. + * + * @returns {TransitInfo} + */ +export declare function NextTransit(body: Body, prevTransitTime: FlexibleDateTime): TransitInfo; +/** + * @brief Indicates whether a crossing through the ecliptic plane is ascending or descending. + * + * `Invalid` is a placeholder for an unknown or missing node. + * `Ascending` indicates a body passing through the ecliptic plane from south to north. + * `Descending` indicates a body passing through the ecliptic plane from north to south. + * + * @enum {number} + */ +export declare enum NodeEventKind { + Invalid = 0, + Ascending = 1, + Descending = -1 +} +/** + * @brief Information about an ascending or descending node of a body. + * + * This object is returned by {@link SearchMoonNode} and {@link NextMoonNode} + * to report information about the center of the Moon passing through the ecliptic plane. + * + * @property {NodeEventKind} kind Whether the node is ascending (south to north) or descending (north to south). + * @property {AstroTime} time The time when the body passes through the ecliptic plane. + */ +export declare class NodeEventInfo { + kind: NodeEventKind; + time: AstroTime; + constructor(kind: NodeEventKind, time: AstroTime); +} +/** + * @brief Searches for a time when the Moon's center crosses through the ecliptic plane. + * + * Searches for the first ascending or descending node of the Moon after `startTime`. + * An ascending node is when the Moon's center passes through the ecliptic plane + * (the plane of the Earth's orbit around the Sun) from south to north. + * A descending node is when the Moon's center passes through the ecliptic plane + * from north to south. Nodes indicate possible times of solar or lunar eclipses, + * if the Moon also happens to be in the correct phase (new or full, respectively). + * Call `SearchMoonNode` to find the first of a series of nodes. + * Then call {@link NextMoonNode} to find as many more consecutive nodes as desired. + * + * @param {FlexibleDateTime} startTime + * The date and time for starting the search for an ascending or descending node of the Moon. + * + * @returns {NodeEventInfo} + */ +export declare function SearchMoonNode(startTime: FlexibleDateTime): NodeEventInfo; +/** + * @brief Searches for the next time when the Moon's center crosses through the ecliptic plane. + * + * Call {@link SearchMoonNode} to find the first of a series of nodes. + * Then call `NextMoonNode` to find as many more consecutive nodes as desired. + * + * @param {NodeEventInfo} prevNode + * The previous node found from calling {@link SearchMoonNode} or `NextMoonNode`. + * + * @returns {NodeEventInfo} + */ +export declare function NextMoonNode(prevNode: NodeEventInfo): NodeEventInfo; +/** + * @brief Information about a body's rotation axis at a given time. + * + * This structure is returned by {@link RotationAxis} to report + * the orientation of a body's rotation axis at a given moment in time. + * The axis is specified by the direction in space that the body's north pole + * points, using angular equatorial coordinates in the J2000 system (EQJ). + * + * Thus `ra` is the right ascension, and `dec` is the declination, of the + * body's north pole vector at the given moment in time. The north pole + * of a body is defined as the pole that lies on the north side of the + * [Solar System's invariable plane](https://en.wikipedia.org/wiki/Invariable_plane), + * regardless of the body's direction of rotation. + * + * The `spin` field indicates the angular position of a prime meridian + * arbitrarily recommended for the body by the International Astronomical + * Union (IAU). + * + * The fields `ra`, `dec`, and `spin` correspond to the variables + * α0, δ0, and W, respectively, from + * [Report of the IAU Working Group on Cartographic Coordinates and Rotational Elements: 2015](https://astropedia.astrogeology.usgs.gov/download/Docs/WGCCRE/WGCCRE2015reprint.pdf). + * The field `north` is a unit vector pointing in the direction of the body's north pole. + * It is expressed in the J2000 mean equator system (EQJ). + * + * @property {number} ra + * The J2000 right ascension of the body's north pole direction, in sidereal hours. + * + * @property {number} dec + * The J2000 declination of the body's north pole direction, in degrees. + * + * @property {number} spin + * Rotation angle of the body's prime meridian, in degrees. + * + * @property {Vector} north + * A J2000 dimensionless unit vector pointing in the direction of the body's north pole. + */ +export declare class AxisInfo { + ra: number; + dec: number; + spin: number; + north: Vector; + constructor(ra: number, dec: number, spin: number, north: Vector); +} +/** + * @brief Calculates information about a body's rotation axis at a given time. + * Calculates the orientation of a body's rotation axis, along with + * the rotation angle of its prime meridian, at a given moment in time. + * + * This function uses formulas standardized by the IAU Working Group + * on Cartographics and Rotational Elements 2015 report, as described + * in the following document: + * + * https://astropedia.astrogeology.usgs.gov/download/Docs/WGCCRE/WGCCRE2015reprint.pdf + * + * See {@link AxisInfo} for more detailed information. + * + * @param {Body} body + * One of the following values: + * `Body.Sun`, `Body.Moon`, `Body.Mercury`, `Body.Venus`, `Body.Earth`, `Body.Mars`, + * `Body.Jupiter`, `Body.Saturn`, `Body.Uranus`, `Body.Neptune`, `Body.Pluto`. + * + * @param {FlexibleDateTime} date + * The time at which to calculate the body's rotation axis. + * + * @returns {AxisInfo} + */ +export declare function RotationAxis(body: Body, date: FlexibleDateTime): AxisInfo; +/** + * @brief Calculates one of the 5 Lagrange points for a pair of co-orbiting bodies. + * + * Given a more massive "major" body and a much less massive "minor" body, + * calculates one of the five Lagrange points in relation to the minor body's + * orbit around the major body. The parameter `point` is an integer that + * selects the Lagrange point as follows: + * + * 1 = the Lagrange point between the major body and minor body. + * 2 = the Lagrange point on the far side of the minor body. + * 3 = the Lagrange point on the far side of the major body. + * 4 = the Lagrange point 60 degrees ahead of the minor body's orbital position. + * 5 = the Lagrange point 60 degrees behind the minor body's orbital position. + * + * The function returns the state vector for the selected Lagrange point + * in J2000 mean equator coordinates (EQJ), with respect to the center of the + * major body. + * + * To calculate Sun/Earth Lagrange points, pass in `Body.Sun` for `major_body` + * and `Body.EMB` (Earth/Moon barycenter) for `minor_body`. + * For Lagrange points of the Sun and any other planet, pass in that planet + * (e.g. `Body.Jupiter`) for `minor_body`. + * To calculate Earth/Moon Lagrange points, pass in `Body.Earth` and `Body.Moon` + * for the major and minor bodies respectively. + * + * In some cases, it may be more efficient to call {@link LagrangePointFast}, + * especially when the state vectors have already been calculated, or are needed + * for some other purpose. + * + * @param {number} point + * An integer 1..5 that selects which of the Lagrange points to calculate. + * + * @param {FlexibleDateTime} date + * The time at which the Lagrange point is to be calculated. + * + * @param {Body} major_body + * The more massive of the co-orbiting bodies: `Body.Sun` or `Body.Earth`. + * + * @param {Body} minor_body + * The less massive of the co-orbiting bodies. See main remarks. + * + * @returns {StateVector} + * The position and velocity of the selected Lagrange point with respect to the major body's center. + */ +export declare function LagrangePoint(point: number, date: FlexibleDateTime, major_body: Body, minor_body: Body): StateVector; +/** + * @brief Calculates one of the 5 Lagrange points from body masses and state vectors. + * + * Given a more massive "major" body and a much less massive "minor" body, + * calculates one of the five Lagrange points in relation to the minor body's + * orbit around the major body. The parameter `point` is an integer that + * selects the Lagrange point as follows: + * + * 1 = the Lagrange point between the major body and minor body. + * 2 = the Lagrange point on the far side of the minor body. + * 3 = the Lagrange point on the far side of the major body. + * 4 = the Lagrange point 60 degrees ahead of the minor body's orbital position. + * 5 = the Lagrange point 60 degrees behind the minor body's orbital position. + * + * The caller passes in the state vector and mass for both bodies. + * The state vectors can be in any orientation and frame of reference. + * The body masses are expressed as GM products, where G = the universal + * gravitation constant and M = the body's mass. Thus the units for + * `major_mass` and `minor_mass` must be au^3/day^2. + * Use {@link MassProduct} to obtain GM values for various solar system bodies. + * + * The function returns the state vector for the selected Lagrange point + * using the same orientation as the state vector parameters `major_state` and `minor_state`, + * and the position and velocity components are with respect to the major body's center. + * + * Consider calling {@link LagrangePoint}, instead of this function, for simpler usage in most cases. + * + * @param {number} point + * A value 1..5 that selects which of the Lagrange points to calculate. + * + * @param {StateVector} major_state + * The state vector of the major (more massive) of the pair of bodies. + * + * @param {number} major_mass + * The mass product GM of the major body. + * + * @param {StateVector} minor_state + * The state vector of the minor (less massive) of the pair of bodies. + * + * @param {number} minor_mass + * The mass product GM of the minor body. + * + * @returns {StateVector} + * The position and velocity of the selected Lagrange point with respect to the major body's center. + */ +export declare function LagrangePointFast(point: number, major_state: StateVector, major_mass: number, minor_state: StateVector, minor_mass: number): StateVector; +/** + * @brief A simulation of zero or more small bodies moving through the Solar System. + * + * This class calculates the movement of arbitrary small bodies, + * such as asteroids or comets, that move through the Solar System. + * It does so by calculating the gravitational forces on the small bodies + * from the Sun and planets. The user of this class supplies a + * list of initial positions and velocities for the small bodies. + * Then the class can update the positions and velocities over small + * time steps. + */ +export declare class GravitySimulator { + private originBody; + private prev; + private curr; + /** + * @brief Creates a gravity simulation object. + * + * @param {Body} originBody + * Specifies the origin of the reference frame. + * All position vectors and velocity vectors will use `originBody` + * as the origin of the coordinate system. + * This origin applies to all the input vectors provided in the + * `bodyStates` parameter of this function, along with all + * output vectors returned by {@link GravitySimulator#Update}. + * Most callers will want to provide one of the following: + * `Body.Sun` for heliocentric coordinates, + * `Body.SSB` for solar system barycentric coordinates, + * or `Body.Earth` for geocentric coordinates. Note that the + * gravity simulator does not correct for light travel time; + * all state vectors are tied to a Newtonian "instantaneous" time. + * + * @param {FlexibleDateTime} date + * The initial time at which to start the simulation. + * + * @param {StateVector[]} bodyStates + * An array of zero or more initial state vectors (positions and velocities) + * of the small bodies to be simulated. + * The caller must know the positions and velocities of the small bodies at an initial moment in time. + * Their positions and velocities are expressed with respect to `originBody`, using equatorial + * J2000 orientation (EQJ). + * Positions are expressed in astronomical units (AU). + * Velocities are expressed in AU/day. + * All the times embedded within the state vectors must exactly match `date`, + * or this constructor will throw an exception. + */ + constructor(originBody: Body, date: FlexibleDateTime, bodyStates: StateVector[]); + /** + * @brief The body that was selected as the coordinate origin when this simulator was created. + */ + get OriginBody(): Body; + /** + * @brief The time represented by the current step of the gravity simulation. + */ + get Time(): AstroTime; + /** + * Advances the gravity simulation by a small time step. + * + * Updates the simulation of the user-supplied small bodies + * to the time indicated by the `date` parameter. + * Returns an array of state vectors for the simulated bodies. + * The array is in the same order as the original array that + * was used to construct this simulator object. + * The positions and velocities in the returned array are + * referenced to the `originBody` that was used to construct + * this simulator. + * + * @param {FlexibleDateTime} date + * A time that is a small increment away from the current simulation time. + * It is up to the developer to figure out an appropriate time increment. + * Depending on the trajectories, a smaller or larger increment + * may be needed for the desired accuracy. Some experimentation may be needed. + * Generally, bodies that stay in the outer Solar System and move slowly can + * use larger time steps. Bodies that pass into the inner Solar System and + * move faster will need a smaller time step to maintain accuracy. + * The `date` value may be after or before the current simulation time + * to move forward or backward in time. + * + * @return {StateVector[]} + * An array of state vectors, one for each simulated small body. + */ + Update(date: FlexibleDateTime): StateVector[]; + /** + * Exchange the current time step with the previous time step. + * + * Sometimes it is helpful to "explore" various times near a given + * simulation time step, while repeatedly returning to the original + * time step. For example, when backdating a position for light travel + * time, the caller may wish to repeatedly try different amounts of + * backdating. When the backdating solver has converged, the caller + * wants to leave the simulation in its original state. + * + * This function allows a single "undo" of a simulation, and does so + * very efficiently. + * + * Usually this function will be called immediately after a matching + * call to {@link GravitySimulator#Update}. It has the effect of rolling + * back the most recent update. If called twice in a row, it reverts + * the swap and thus has no net effect. + * + * The constructor initializes the current state and previous + * state to be identical. Both states represent the `time` parameter that was + * passed into the constructor. Therefore, `Swap` will + * have no effect from the caller's point of view when passed a simulator + * that has not yet been updated by a call to {@link GravitySimulator#Update}. + */ + Swap(): void; + /** + * Get the position and velocity of a Solar System body included in the simulation. + * + * In order to simulate the movement of small bodies through the Solar System, + * the simulator needs to calculate the state vectors for the Sun and planets. + * + * If an application wants to know the positions of one or more of the planets + * in addition to the small bodies, this function provides a way to obtain + * their state vectors. This is provided for the sake of efficiency, to avoid + * redundant calculations. + * + * The state vector is returned relative to the position and velocity + * of the `originBody` parameter that was passed to this object's constructor. + * + * @param {Body} body + * The Sun, Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, or Neptune. + */ + SolarSystemBodyState(body: Body): StateVector; + private InternalBodyState; + private static CalcSolarSystem; + private CalcBodyAccelerations; + private static AddAcceleration; + private Duplicate; +} diff --git a/node_modules/astronomy-engine/astronomy.js b/node_modules/astronomy-engine/astronomy.js new file mode 100644 index 0000000..ab66062 --- /dev/null +++ b/node_modules/astronomy-engine/astronomy.js @@ -0,0 +1,9806 @@ +/** + @preserve + + Astronomy library for JavaScript (browser and Node.js). + https://github.com/cosinekitty/astronomy + + MIT License + + Copyright (c) 2019-2023 Don Cross + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ +/** + * @fileoverview Astronomy calculation library for browser scripting and Node.js. + * @author Don Cross + * @license MIT + */ +'use strict'; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.GeoEmbState = exports.GeoMoonState = exports.EclipticGeoMoon = exports.GeoMoon = exports.Ecliptic = exports.ObserverGravity = exports.VectorObserver = exports.ObserverState = exports.ObserverVector = exports.Equator = exports.SunPosition = exports.Observer = exports.Horizon = exports.EclipticCoordinates = exports.HorizontalCoordinates = exports.MakeRotation = exports.RotationMatrix = exports.EquatorialCoordinates = exports.Spherical = exports.StateVector = exports.Vector = exports.SiderealTime = exports.Libration = exports.LibrationInfo = exports.CalcMoonCount = exports.e_tilt = exports.MakeTime = exports.AstroTime = exports.SetDeltaTFunction = exports.DeltaT_JplHorizons = exports.DeltaT_EspenakMeeus = exports.PlanetOrbitalPeriod = exports.DefineStar = exports.Body = exports.AngleBetween = exports.MassProduct = exports.CALLISTO_RADIUS_KM = exports.GANYMEDE_RADIUS_KM = exports.EUROPA_RADIUS_KM = exports.IO_RADIUS_KM = exports.JUPITER_MEAN_RADIUS_KM = exports.JUPITER_POLAR_RADIUS_KM = exports.JUPITER_EQUATORIAL_RADIUS_KM = exports.RAD2HOUR = exports.RAD2DEG = exports.HOUR2RAD = exports.DEG2RAD = exports.AU_PER_LY = exports.KM_PER_AU = exports.C_AUDAY = void 0; +exports.VectorFromHorizon = exports.HorizonFromVector = exports.SphereFromVector = exports.EquatorFromVector = exports.VectorFromSphere = exports.Pivot = exports.IdentityMatrix = exports.CombineRotation = exports.InverseRotation = exports.NextPlanetApsis = exports.SearchPlanetApsis = exports.NextLunarApsis = exports.SearchLunarApsis = exports.Apsis = exports.ApsisKind = exports.SearchPeakMagnitude = exports.SearchMaxElongation = exports.Elongation = exports.ElongationEvent = exports.Seasons = exports.SeasonInfo = exports.HourAngle = exports.SearchHourAngle = exports.HourAngleEvent = exports.SearchAltitude = exports.SearchRiseSet = exports.Atmosphere = exports.AtmosphereInfo = exports.NextMoonQuarter = exports.SearchMoonQuarter = exports.MoonQuarter = exports.SearchMoonPhase = exports.MoonPhase = exports.SearchRelativeLongitude = exports.Illumination = exports.IlluminationInfo = exports.EclipticLongitude = exports.AngleFromSun = exports.PairLongitude = exports.SearchSunLongitude = exports.Search = exports.HelioState = exports.BaryState = exports.GeoVector = exports.BackdatePosition = exports.CorrectLightTravel = exports.HelioDistance = exports.HelioVector = exports.JupiterMoons = exports.JupiterMoonsInfo = void 0; +exports.GravitySimulator = exports.LagrangePointFast = exports.LagrangePoint = exports.RotationAxis = exports.AxisInfo = exports.NextMoonNode = exports.SearchMoonNode = exports.NodeEventInfo = exports.NodeEventKind = exports.NextTransit = exports.SearchTransit = exports.TransitInfo = exports.NextLocalSolarEclipse = exports.SearchLocalSolarEclipse = exports.LocalSolarEclipseInfo = exports.EclipseEvent = exports.NextGlobalSolarEclipse = exports.SearchGlobalSolarEclipse = exports.NextLunarEclipse = exports.GlobalSolarEclipseInfo = exports.SearchLunarEclipse = exports.LunarEclipseInfo = exports.EclipseKind = exports.Constellation = exports.ConstellationInfo = exports.Rotation_EQD_ECT = exports.Rotation_ECT_EQD = exports.Rotation_GAL_EQJ = exports.Rotation_EQJ_GAL = exports.Rotation_HOR_ECL = exports.Rotation_ECL_HOR = exports.Rotation_ECL_EQD = exports.Rotation_EQD_ECL = exports.Rotation_EQJ_HOR = exports.Rotation_HOR_EQJ = exports.Rotation_HOR_EQD = exports.Rotation_EQD_HOR = exports.Rotation_EQD_EQJ = exports.Rotation_ECT_EQJ = exports.Rotation_EQJ_ECT = exports.Rotation_EQJ_EQD = exports.Rotation_ECL_EQJ = exports.Rotation_EQJ_ECL = exports.RotateState = exports.RotateVector = exports.InverseRefraction = exports.Refraction = void 0; +/** + * @brief The speed of light in AU/day. + */ +exports.C_AUDAY = 173.1446326846693; +/** + * @brief The number of kilometers per astronomical unit. + */ +exports.KM_PER_AU = 1.4959787069098932e+8; +/** + * @brief The number of astronomical units per light-year. + */ +exports.AU_PER_LY = 63241.07708807546; +/** + * @brief The factor to convert degrees to radians = pi/180. + */ +exports.DEG2RAD = 0.017453292519943296; +/** + * @brief The factor to convert sidereal hours to radians = pi/12. + */ +exports.HOUR2RAD = 0.2617993877991494365; +/** + * @brief The factor to convert radians to degrees = 180/pi. + */ +exports.RAD2DEG = 57.295779513082321; +/** + * @brief The factor to convert radians to sidereal hours = 12/pi. + */ +exports.RAD2HOUR = 3.819718634205488; +// Jupiter radius data are nominal values obtained from: +// https://www.iau.org/static/resolutions/IAU2015_English.pdf +// https://nssdc.gsfc.nasa.gov/planetary/factsheet/jupiterfact.html +/** + * @brief The equatorial radius of Jupiter, expressed in kilometers. + */ +exports.JUPITER_EQUATORIAL_RADIUS_KM = 71492.0; +/** + * @brief The polar radius of Jupiter, expressed in kilometers. + */ +exports.JUPITER_POLAR_RADIUS_KM = 66854.0; +/** + * @brief The volumetric mean radius of Jupiter, expressed in kilometers. + */ +exports.JUPITER_MEAN_RADIUS_KM = 69911.0; +// The radii of Jupiter's four major moons are obtained from: +// https://ssd.jpl.nasa.gov/?sat_phys_par +/** + * @brief The mean radius of Jupiter's moon Io, expressed in kilometers. + */ +exports.IO_RADIUS_KM = 1821.6; +/** + * @brief The mean radius of Jupiter's moon Europa, expressed in kilometers. + */ +exports.EUROPA_RADIUS_KM = 1560.8; +/** + * @brief The mean radius of Jupiter's moon Ganymede, expressed in kilometers. + */ +exports.GANYMEDE_RADIUS_KM = 2631.2; +/** + * @brief The mean radius of Jupiter's moon Callisto, expressed in kilometers. + */ +exports.CALLISTO_RADIUS_KM = 2410.3; +const DAYS_PER_TROPICAL_YEAR = 365.24217; +const J2000 = new Date('2000-01-01T12:00:00Z'); +const PI2 = 2 * Math.PI; +const ARC = 3600 * (180 / Math.PI); // arcseconds per radian +const ASEC2RAD = 4.848136811095359935899141e-6; +const ASEC180 = 180 * 60 * 60; // arcseconds per 180 degrees (or pi radians) +const ASEC360 = 2 * ASEC180; // arcseconds per 360 degrees (or 2*pi radians) +const ANGVEL = 7.2921150e-5; +const AU_PER_PARSEC = ASEC180 / Math.PI; // exact definition of how many AU = one parsec +const SUN_MAG_1AU = -0.17 - 5 * Math.log10(AU_PER_PARSEC); // formula from JPL Horizons +const MEAN_SYNODIC_MONTH = 29.530588; // average number of days for Moon to return to the same phase +const SECONDS_PER_DAY = 24 * 3600; +const MILLIS_PER_DAY = SECONDS_PER_DAY * 1000; +const SOLAR_DAYS_PER_SIDEREAL_DAY = 0.9972695717592592; +const SUN_RADIUS_KM = 695700.0; +const SUN_RADIUS_AU = SUN_RADIUS_KM / exports.KM_PER_AU; +const EARTH_FLATTENING = 0.996647180302104; +const EARTH_FLATTENING_SQUARED = EARTH_FLATTENING * EARTH_FLATTENING; +const EARTH_EQUATORIAL_RADIUS_KM = 6378.1366; +const EARTH_EQUATORIAL_RADIUS_AU = EARTH_EQUATORIAL_RADIUS_KM / exports.KM_PER_AU; +const EARTH_POLAR_RADIUS_KM = EARTH_EQUATORIAL_RADIUS_KM * EARTH_FLATTENING; +const EARTH_MEAN_RADIUS_KM = 6371.0; /* mean radius of the Earth's geoid, without atmosphere */ +const EARTH_ATMOSPHERE_KM = 88.0; /* effective atmosphere thickness for lunar eclipses */ +const EARTH_ECLIPSE_RADIUS_KM = EARTH_MEAN_RADIUS_KM + EARTH_ATMOSPHERE_KM; +const MOON_EQUATORIAL_RADIUS_KM = 1738.1; +const MOON_EQUATORIAL_RADIUS_AU = (MOON_EQUATORIAL_RADIUS_KM / exports.KM_PER_AU); +const MOON_MEAN_RADIUS_KM = 1737.4; +const MOON_POLAR_RADIUS_KM = 1736.0; +const MOON_POLAR_RADIUS_AU = (MOON_POLAR_RADIUS_KM / exports.KM_PER_AU); +const REFRACTION_NEAR_HORIZON = 34 / 60; // degrees of refractive "lift" seen for objects near horizon +const EARTH_MOON_MASS_RATIO = 81.30056; +/* + Masses of the Sun and outer planets, used for: + (1) Calculating the Solar System Barycenter + (2) Integrating the movement of Pluto + + https://web.archive.org/web/20120220062549/http://iau-comm4.jpl.nasa.gov/de405iom/de405iom.pdf + + Page 10 in the above document describes the constants used in the DE405 ephemeris. + The following are G*M values (gravity constant * mass) in [au^3 / day^2]. + This side-steps issues of not knowing the exact values of G and masses M[i]; + the products GM[i] are known extremely accurately. +*/ +const SUN_GM = 0.2959122082855911e-03; +const MERCURY_GM = 0.4912547451450812e-10; +const VENUS_GM = 0.7243452486162703e-09; +const EARTH_GM = 0.8887692390113509e-09; +const MARS_GM = 0.9549535105779258e-10; +const JUPITER_GM = 0.2825345909524226e-06; +const SATURN_GM = 0.8459715185680659e-07; +const URANUS_GM = 0.1292024916781969e-07; +const NEPTUNE_GM = 0.1524358900784276e-07; +const PLUTO_GM = 0.2188699765425970e-11; +const MOON_GM = EARTH_GM / EARTH_MOON_MASS_RATIO; +/** + * @brief Returns the product of mass and universal gravitational constant of a Solar System body. + * + * For problems involving the gravitational interactions of Solar System bodies, + * it is helpful to know the product GM, where G = the universal gravitational constant + * and M = the mass of the body. In practice, GM is known to a higher precision than + * either G or M alone, and thus using the product results in the most accurate results. + * This function returns the product GM in the units au^3/day^2. + * The values come from page 10 of a + * [JPL memorandum regarding the DE405/LE405 ephemeris](https://web.archive.org/web/20120220062549/http://iau-comm4.jpl.nasa.gov/de405iom/de405iom.pdf). + * + * @param {Body} body + * The body for which to find the GM product. + * Allowed to be the Sun, Moon, EMB (Earth/Moon Barycenter), or any planet. + * Any other value will cause an exception to be thrown. + * + * @returns {number} + * The mass product of the given body in au^3/day^2. + */ +function MassProduct(body) { + switch (body) { + case Body.Sun: return SUN_GM; + case Body.Mercury: return MERCURY_GM; + case Body.Venus: return VENUS_GM; + case Body.Earth: return EARTH_GM; + case Body.Moon: return MOON_GM; + case Body.EMB: return EARTH_GM + MOON_GM; + case Body.Mars: return MARS_GM; + case Body.Jupiter: return JUPITER_GM; + case Body.Saturn: return SATURN_GM; + case Body.Uranus: return URANUS_GM; + case Body.Neptune: return NEPTUNE_GM; + case Body.Pluto: return PLUTO_GM; + default: + throw `Do not know mass product for body: ${body}`; + } +} +exports.MassProduct = MassProduct; +function VerifyBoolean(b) { + if (b !== true && b !== false) { + console.trace(); + throw `Value is not boolean: ${b}`; + } + return b; +} +function VerifyNumber(x) { + if (!Number.isFinite(x)) { + console.trace(); + throw `Value is not a finite number: ${x}`; + } + return x; +} +function Frac(x) { + return x - Math.floor(x); +} +/** + * @brief Calculates the angle in degrees between two vectors. + * + * Given a pair of vectors, this function returns the angle in degrees + * between the two vectors in 3D space. + * The angle is measured in the plane that contains both vectors. + * + * @param {Vector} a + * The first of a pair of vectors between which to measure an angle. + * + * @param {Vector} b + * The second of a pair of vectors between which to measure an angle. + * + * @returns {number} + * The angle between the two vectors expressed in degrees. + * The value is in the range [0, 180]. + */ +function AngleBetween(a, b) { + const aa = (a.x * a.x + a.y * a.y + a.z * a.z); + if (Math.abs(aa) < 1.0e-8) + throw `AngleBetween: first vector is too short.`; + const bb = (b.x * b.x + b.y * b.y + b.z * b.z); + if (Math.abs(bb) < 1.0e-8) + throw `AngleBetween: second vector is too short.`; + const dot = (a.x * b.x + a.y * b.y + a.z * b.z) / Math.sqrt(aa * bb); + if (dot <= -1.0) + return 180; + if (dot >= +1.0) + return 0; + return exports.RAD2DEG * Math.acos(dot); +} +exports.AngleBetween = AngleBetween; +/** + * @brief String constants that represent the solar system bodies supported by Astronomy Engine. + * + * The following strings represent solar system bodies supported by various Astronomy Engine functions. + * Not every body is supported by every function; consult the documentation for each function + * to find which bodies it supports. + * + * "Sun", "Moon", "Mercury", "Venus", "Earth", "Mars", "Jupiter", + * "Saturn", "Uranus", "Neptune", "Pluto", + * "SSB" (Solar System Barycenter), + * "EMB" (Earth/Moon Barycenter) + * + * You can also use enumeration syntax for the bodies, like + * `Astronomy.Body.Moon`, `Astronomy.Body.Jupiter`, etc. + * + * @enum {string} + */ +var Body; +(function (Body) { + Body["Sun"] = "Sun"; + Body["Moon"] = "Moon"; + Body["Mercury"] = "Mercury"; + Body["Venus"] = "Venus"; + Body["Earth"] = "Earth"; + Body["Mars"] = "Mars"; + Body["Jupiter"] = "Jupiter"; + Body["Saturn"] = "Saturn"; + Body["Uranus"] = "Uranus"; + Body["Neptune"] = "Neptune"; + Body["Pluto"] = "Pluto"; + Body["SSB"] = "SSB"; + Body["EMB"] = "EMB"; + // User-defined fixed locations in the sky... + Body["Star1"] = "Star1"; + Body["Star2"] = "Star2"; + Body["Star3"] = "Star3"; + Body["Star4"] = "Star4"; + Body["Star5"] = "Star5"; + Body["Star6"] = "Star6"; + Body["Star7"] = "Star7"; + Body["Star8"] = "Star8"; +})(Body = exports.Body || (exports.Body = {})); +const StarList = [ + Body.Star1, Body.Star2, Body.Star3, Body.Star4, + Body.Star5, Body.Star6, Body.Star7, Body.Star8 +]; +; +const StarTable = [ + { ra: 0, dec: 0, dist: 0 }, + { ra: 0, dec: 0, dist: 0 }, + { ra: 0, dec: 0, dist: 0 }, + { ra: 0, dec: 0, dist: 0 }, + { ra: 0, dec: 0, dist: 0 }, + { ra: 0, dec: 0, dist: 0 }, + { ra: 0, dec: 0, dist: 0 }, + { ra: 0, dec: 0, dist: 0 }, +]; +function GetStar(body) { + const index = StarList.indexOf(body); + return (index >= 0) ? StarTable[index] : null; +} +function UserDefinedStar(body) { + const star = GetStar(body); + return (star && star.dist > 0) ? star : null; +} +/** + * @brief Assign equatorial coordinates to a user-defined star. + * + * Some Astronomy Engine functions allow their `body` parameter to + * be a user-defined fixed point in the sky, loosely called a "star". + * This function assigns a right ascension, declination, and distance + * to one of the eight user-defined stars `Star1`..`Star8`. + * + * Stars are not valid until defined. Once defined, they retain their + * definition until re-defined by another call to `DefineStar`. + * + * @param {Body} body + * One of the eight user-defined star identifiers: + * `Star1`, `Star2`, `Star3`, `Star4`, `Star5`, `Star6`, `Star7`, or `Star8`. + * + * @param {number} ra + * The right ascension to be assigned to the star, expressed in J2000 equatorial coordinates (EQJ). + * The value is in units of sidereal hours, and must be within the half-open range [0, 24). + * + * @param {number} dec + * The declination to be assigned to the star, expressed in J2000 equatorial coordinates (EQJ). + * The value is in units of degrees north (positive) or south (negative) of the J2000 equator, + * and must be within the closed range [-90, +90]. + * + * @param {number} distanceLightYears + * The distance between the star and the Sun, expressed in light-years. + * This value is used to calculate the tiny parallax shift as seen by an observer on Earth. + * If you don't know the distance to the star, using a large value like 1000 will generally work well. + * The minimum allowed distance is 1 light-year, which is required to provide certain internal optimizations. + */ +function DefineStar(body, ra, dec, distanceLightYears) { + const star = GetStar(body); + if (!star) + throw `Invalid star body: ${body}`; + VerifyNumber(ra); + VerifyNumber(dec); + VerifyNumber(distanceLightYears); + if (ra < 0 || ra >= 24) + throw `Invalid right ascension for star: ${ra}`; + if (dec < -90 || dec > +90) + throw `Invalid declination for star: ${dec}`; + if (distanceLightYears < 1) + throw `Invalid star distance: ${distanceLightYears}`; + star.ra = ra; + star.dec = dec; + star.dist = distanceLightYears * exports.AU_PER_LY; +} +exports.DefineStar = DefineStar; +var PrecessDirection; +(function (PrecessDirection) { + PrecessDirection[PrecessDirection["From2000"] = 0] = "From2000"; + PrecessDirection[PrecessDirection["Into2000"] = 1] = "Into2000"; +})(PrecessDirection || (PrecessDirection = {})); +const Planet = { + Mercury: { OrbitalPeriod: 87.969 }, + Venus: { OrbitalPeriod: 224.701 }, + Earth: { OrbitalPeriod: 365.256 }, + Mars: { OrbitalPeriod: 686.980 }, + Jupiter: { OrbitalPeriod: 4332.589 }, + Saturn: { OrbitalPeriod: 10759.22 }, + Uranus: { OrbitalPeriod: 30685.4 }, + Neptune: { OrbitalPeriod: 60189.0 }, + Pluto: { OrbitalPeriod: 90560.0 } +}; +/** + * @brief Returns the mean orbital period of a planet in days. + * + * @param {Body} body + * One of: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, or Pluto. + * + * @returns {number} + * The approximate average time it takes for the planet to travel once around the Sun. + * The value is expressed in days. + */ +function PlanetOrbitalPeriod(body) { + if (body in Planet) + return Planet[body].OrbitalPeriod; + throw `Unknown orbital period for: ${body}`; +} +exports.PlanetOrbitalPeriod = PlanetOrbitalPeriod; +const vsop = { + Mercury: [ + [ + [ + [4.40250710144, 0.00000000000, 0.00000000000], + [0.40989414977, 1.48302034195, 26087.90314157420], + [0.05046294200, 4.47785489551, 52175.80628314840], + [0.00855346844, 1.16520322459, 78263.70942472259], + [0.00165590362, 4.11969163423, 104351.61256629678], + [0.00034561897, 0.77930768443, 130439.51570787099], + [0.00007583476, 3.71348404924, 156527.41884944518] + ], + [ + [26087.90313685529, 0.00000000000, 0.00000000000], + [0.01131199811, 6.21874197797, 26087.90314157420], + [0.00292242298, 3.04449355541, 52175.80628314840], + [0.00075775081, 6.08568821653, 78263.70942472259], + [0.00019676525, 2.80965111777, 104351.61256629678] + ] + ], + [ + [ + [0.11737528961, 1.98357498767, 26087.90314157420], + [0.02388076996, 5.03738959686, 52175.80628314840], + [0.01222839532, 3.14159265359, 0.00000000000], + [0.00543251810, 1.79644363964, 78263.70942472259], + [0.00129778770, 4.83232503958, 104351.61256629678], + [0.00031866927, 1.58088495658, 130439.51570787099], + [0.00007963301, 4.60972126127, 156527.41884944518] + ], + [ + [0.00274646065, 3.95008450011, 26087.90314157420], + [0.00099737713, 3.14159265359, 0.00000000000] + ] + ], + [ + [ + [0.39528271651, 0.00000000000, 0.00000000000], + [0.07834131818, 6.19233722598, 26087.90314157420], + [0.00795525558, 2.95989690104, 52175.80628314840], + [0.00121281764, 6.01064153797, 78263.70942472259], + [0.00021921969, 2.77820093972, 104351.61256629678], + [0.00004354065, 5.82894543774, 130439.51570787099] + ], + [ + [0.00217347740, 4.65617158665, 26087.90314157420], + [0.00044141826, 1.42385544001, 52175.80628314840] + ] + ] + ], + Venus: [ + [ + [ + [3.17614666774, 0.00000000000, 0.00000000000], + [0.01353968419, 5.59313319619, 10213.28554621100], + [0.00089891645, 5.30650047764, 20426.57109242200], + [0.00005477194, 4.41630661466, 7860.41939243920], + [0.00003455741, 2.69964447820, 11790.62908865880], + [0.00002372061, 2.99377542079, 3930.20969621960], + [0.00001317168, 5.18668228402, 26.29831979980], + [0.00001664146, 4.25018630147, 1577.34354244780], + [0.00001438387, 4.15745084182, 9683.59458111640], + [0.00001200521, 6.15357116043, 30639.85663863300] + ], + [ + [10213.28554621638, 0.00000000000, 0.00000000000], + [0.00095617813, 2.46406511110, 10213.28554621100], + [0.00007787201, 0.62478482220, 20426.57109242200] + ] + ], + [ + [ + [0.05923638472, 0.26702775812, 10213.28554621100], + [0.00040107978, 1.14737178112, 20426.57109242200], + [0.00032814918, 3.14159265359, 0.00000000000] + ], + [ + [0.00287821243, 1.88964962838, 10213.28554621100] + ] + ], + [ + [ + [0.72334820891, 0.00000000000, 0.00000000000], + [0.00489824182, 4.02151831717, 10213.28554621100], + [0.00001658058, 4.90206728031, 20426.57109242200], + [0.00001378043, 1.12846591367, 11790.62908865880], + [0.00001632096, 2.84548795207, 7860.41939243920], + [0.00000498395, 2.58682193892, 9683.59458111640], + [0.00000221985, 2.01346696541, 19367.18916223280], + [0.00000237454, 2.55136053886, 15720.83878487840] + ], + [ + [0.00034551041, 0.89198706276, 10213.28554621100] + ] + ] + ], + Earth: [ + [ + [ + [1.75347045673, 0.00000000000, 0.00000000000], + [0.03341656453, 4.66925680415, 6283.07584999140], + [0.00034894275, 4.62610242189, 12566.15169998280], + [0.00003417572, 2.82886579754, 3.52311834900], + [0.00003497056, 2.74411783405, 5753.38488489680], + [0.00003135899, 3.62767041756, 77713.77146812050], + [0.00002676218, 4.41808345438, 7860.41939243920], + [0.00002342691, 6.13516214446, 3930.20969621960], + [0.00001273165, 2.03709657878, 529.69096509460], + [0.00001324294, 0.74246341673, 11506.76976979360], + [0.00000901854, 2.04505446477, 26.29831979980], + [0.00001199167, 1.10962946234, 1577.34354244780], + [0.00000857223, 3.50849152283, 398.14900340820], + [0.00000779786, 1.17882681962, 5223.69391980220], + [0.00000990250, 5.23268072088, 5884.92684658320], + [0.00000753141, 2.53339052847, 5507.55323866740], + [0.00000505267, 4.58292599973, 18849.22754997420], + [0.00000492392, 4.20505711826, 775.52261132400], + [0.00000356672, 2.91954114478, 0.06731030280], + [0.00000284125, 1.89869240932, 796.29800681640], + [0.00000242879, 0.34481445893, 5486.77784317500], + [0.00000317087, 5.84901948512, 11790.62908865880], + [0.00000271112, 0.31486255375, 10977.07880469900], + [0.00000206217, 4.80646631478, 2544.31441988340], + [0.00000205478, 1.86953770281, 5573.14280143310], + [0.00000202318, 2.45767790232, 6069.77675455340], + [0.00000126225, 1.08295459501, 20.77539549240], + [0.00000155516, 0.83306084617, 213.29909543800] + ], + [ + [6283.07584999140, 0.00000000000, 0.00000000000], + [0.00206058863, 2.67823455808, 6283.07584999140], + [0.00004303419, 2.63512233481, 12566.15169998280] + ], + [ + [0.00008721859, 1.07253635559, 6283.07584999140] + ] + ], + [ + [], + [ + [0.00227777722, 3.41376620530, 6283.07584999140], + [0.00003805678, 3.37063423795, 12566.15169998280] + ] + ], + [ + [ + [1.00013988784, 0.00000000000, 0.00000000000], + [0.01670699632, 3.09846350258, 6283.07584999140], + [0.00013956024, 3.05524609456, 12566.15169998280], + [0.00003083720, 5.19846674381, 77713.77146812050], + [0.00001628463, 1.17387558054, 5753.38488489680], + [0.00001575572, 2.84685214877, 7860.41939243920], + [0.00000924799, 5.45292236722, 11506.76976979360], + [0.00000542439, 4.56409151453, 3930.20969621960], + [0.00000472110, 3.66100022149, 5884.92684658320], + [0.00000085831, 1.27079125277, 161000.68573767410], + [0.00000057056, 2.01374292245, 83996.84731811189], + [0.00000055736, 5.24159799170, 71430.69561812909], + [0.00000174844, 3.01193636733, 18849.22754997420], + [0.00000243181, 4.27349530790, 11790.62908865880] + ], + [ + [0.00103018607, 1.10748968172, 6283.07584999140], + [0.00001721238, 1.06442300386, 12566.15169998280] + ], + [ + [0.00004359385, 5.78455133808, 6283.07584999140] + ] + ] + ], + Mars: [ + [ + [ + [6.20347711581, 0.00000000000, 0.00000000000], + [0.18656368093, 5.05037100270, 3340.61242669980], + [0.01108216816, 5.40099836344, 6681.22485339960], + [0.00091798406, 5.75478744667, 10021.83728009940], + [0.00027744987, 5.97049513147, 3.52311834900], + [0.00010610235, 2.93958560338, 2281.23049651060], + [0.00012315897, 0.84956094002, 2810.92146160520], + [0.00008926784, 4.15697846427, 0.01725365220], + [0.00008715691, 6.11005153139, 13362.44970679920], + [0.00006797556, 0.36462229657, 398.14900340820], + [0.00007774872, 3.33968761376, 5621.84292321040], + [0.00003575078, 1.66186505710, 2544.31441988340], + [0.00004161108, 0.22814971327, 2942.46342329160], + [0.00003075252, 0.85696614132, 191.44826611160], + [0.00002628117, 0.64806124465, 3337.08930835080], + [0.00002937546, 6.07893711402, 0.06731030280], + [0.00002389414, 5.03896442664, 796.29800681640], + [0.00002579844, 0.02996736156, 3344.13554504880], + [0.00001528141, 1.14979301996, 6151.53388830500], + [0.00001798806, 0.65634057445, 529.69096509460], + [0.00001264357, 3.62275122593, 5092.15195811580], + [0.00001286228, 3.06796065034, 2146.16541647520], + [0.00001546404, 2.91579701718, 1751.53953141600], + [0.00001024902, 3.69334099279, 8962.45534991020], + [0.00000891566, 0.18293837498, 16703.06213349900], + [0.00000858759, 2.40093811940, 2914.01423582380], + [0.00000832715, 2.46418619474, 3340.59517304760], + [0.00000832720, 4.49495782139, 3340.62968035200], + [0.00000712902, 3.66335473479, 1059.38193018920], + [0.00000748723, 3.82248614017, 155.42039943420], + [0.00000723861, 0.67497311481, 3738.76143010800], + [0.00000635548, 2.92182225127, 8432.76438481560], + [0.00000655162, 0.48864064125, 3127.31333126180], + [0.00000550474, 3.81001042328, 0.98032106820], + [0.00000552750, 4.47479317037, 1748.01641306700], + [0.00000425966, 0.55364317304, 6283.07584999140], + [0.00000415131, 0.49662285038, 213.29909543800], + [0.00000472167, 3.62547124025, 1194.44701022460], + [0.00000306551, 0.38052848348, 6684.74797174860], + [0.00000312141, 0.99853944405, 6677.70173505060], + [0.00000293198, 4.22131299634, 20.77539549240], + [0.00000302375, 4.48618007156, 3532.06069281140], + [0.00000274027, 0.54222167059, 3340.54511639700], + [0.00000281079, 5.88163521788, 1349.86740965880], + [0.00000231183, 1.28242156993, 3870.30339179440], + [0.00000283602, 5.76885434940, 3149.16416058820], + [0.00000236117, 5.75503217933, 3333.49887969900], + [0.00000274033, 0.13372524985, 3340.67973700260], + [0.00000299395, 2.78323740866, 6254.62666252360] + ], + [ + [3340.61242700512, 0.00000000000, 0.00000000000], + [0.01457554523, 3.60433733236, 3340.61242669980], + [0.00168414711, 3.92318567804, 6681.22485339960], + [0.00020622975, 4.26108844583, 10021.83728009940], + [0.00003452392, 4.73210393190, 3.52311834900], + [0.00002586332, 4.60670058555, 13362.44970679920], + [0.00000841535, 4.45864030426, 2281.23049651060] + ], + [ + [0.00058152577, 2.04961712429, 3340.61242669980], + [0.00013459579, 2.45738706163, 6681.22485339960] + ] + ], + [ + [ + [0.03197134986, 3.76832042431, 3340.61242669980], + [0.00298033234, 4.10616996305, 6681.22485339960], + [0.00289104742, 0.00000000000, 0.00000000000], + [0.00031365539, 4.44651053090, 10021.83728009940], + [0.00003484100, 4.78812549260, 13362.44970679920] + ], + [ + [0.00217310991, 6.04472194776, 3340.61242669980], + [0.00020976948, 3.14159265359, 0.00000000000], + [0.00012834709, 1.60810667915, 6681.22485339960] + ] + ], + [ + [ + [1.53033488271, 0.00000000000, 0.00000000000], + [0.14184953160, 3.47971283528, 3340.61242669980], + [0.00660776362, 3.81783443019, 6681.22485339960], + [0.00046179117, 4.15595316782, 10021.83728009940], + [0.00008109733, 5.55958416318, 2810.92146160520], + [0.00007485318, 1.77239078402, 5621.84292321040], + [0.00005523191, 1.36436303770, 2281.23049651060], + [0.00003825160, 4.49407183687, 13362.44970679920], + [0.00002306537, 0.09081579001, 2544.31441988340], + [0.00001999396, 5.36059617709, 3337.08930835080], + [0.00002484394, 4.92545639920, 2942.46342329160], + [0.00001960195, 4.74249437639, 3344.13554504880], + [0.00001167119, 2.11260868341, 5092.15195811580], + [0.00001102816, 5.00908403998, 398.14900340820], + [0.00000899066, 4.40791133207, 529.69096509460], + [0.00000992252, 5.83861961952, 6151.53388830500], + [0.00000807354, 2.10217065501, 1059.38193018920], + [0.00000797915, 3.44839203899, 796.29800681640], + [0.00000740975, 1.49906336885, 2146.16541647520] + ], + [ + [0.01107433345, 2.03250524857, 3340.61242669980], + [0.00103175887, 2.37071847807, 6681.22485339960], + [0.00012877200, 0.00000000000, 0.00000000000], + [0.00010815880, 2.70888095665, 10021.83728009940] + ], + [ + [0.00044242249, 0.47930604954, 3340.61242669980], + [0.00008138042, 0.86998389204, 6681.22485339960] + ] + ] + ], + Jupiter: [ + [ + [ + [0.59954691494, 0.00000000000, 0.00000000000], + [0.09695898719, 5.06191793158, 529.69096509460], + [0.00573610142, 1.44406205629, 7.11354700080], + [0.00306389205, 5.41734730184, 1059.38193018920], + [0.00097178296, 4.14264726552, 632.78373931320], + [0.00072903078, 3.64042916389, 522.57741809380], + [0.00064263975, 3.41145165351, 103.09277421860], + [0.00039806064, 2.29376740788, 419.48464387520], + [0.00038857767, 1.27231755835, 316.39186965660], + [0.00027964629, 1.78454591820, 536.80451209540], + [0.00013589730, 5.77481040790, 1589.07289528380], + [0.00008246349, 3.58227925840, 206.18554843720], + [0.00008768704, 3.63000308199, 949.17560896980], + [0.00007368042, 5.08101194270, 735.87651353180], + [0.00006263150, 0.02497628807, 213.29909543800], + [0.00006114062, 4.51319998626, 1162.47470440780], + [0.00004905396, 1.32084470588, 110.20632121940], + [0.00005305285, 1.30671216791, 14.22709400160], + [0.00005305441, 4.18625634012, 1052.26838318840], + [0.00004647248, 4.69958103684, 3.93215326310], + [0.00003045023, 4.31676431084, 426.59819087600], + [0.00002609999, 1.56667394063, 846.08283475120], + [0.00002028191, 1.06376530715, 3.18139373770], + [0.00001764763, 2.14148655117, 1066.49547719000], + [0.00001722972, 3.88036268267, 1265.56747862640], + [0.00001920945, 0.97168196472, 639.89728631400], + [0.00001633223, 3.58201833555, 515.46387109300], + [0.00001431999, 4.29685556046, 625.67019231240], + [0.00000973272, 4.09764549134, 95.97922721780] + ], + [ + [529.69096508814, 0.00000000000, 0.00000000000], + [0.00489503243, 4.22082939470, 529.69096509460], + [0.00228917222, 6.02646855621, 7.11354700080], + [0.00030099479, 4.54540782858, 1059.38193018920], + [0.00020720920, 5.45943156902, 522.57741809380], + [0.00012103653, 0.16994816098, 536.80451209540], + [0.00006067987, 4.42422292017, 103.09277421860], + [0.00005433968, 3.98480737746, 419.48464387520], + [0.00004237744, 5.89008707199, 14.22709400160] + ], + [ + [0.00047233601, 4.32148536482, 7.11354700080], + [0.00030649436, 2.92977788700, 529.69096509460], + [0.00014837605, 3.14159265359, 0.00000000000] + ] + ], + [ + [ + [0.02268615702, 3.55852606721, 529.69096509460], + [0.00109971634, 3.90809347197, 1059.38193018920], + [0.00110090358, 0.00000000000, 0.00000000000], + [0.00008101428, 3.60509572885, 522.57741809380], + [0.00006043996, 4.25883108339, 1589.07289528380], + [0.00006437782, 0.30627119215, 536.80451209540] + ], + [ + [0.00078203446, 1.52377859742, 529.69096509460] + ] + ], + [ + [ + [5.20887429326, 0.00000000000, 0.00000000000], + [0.25209327119, 3.49108639871, 529.69096509460], + [0.00610599976, 3.84115365948, 1059.38193018920], + [0.00282029458, 2.57419881293, 632.78373931320], + [0.00187647346, 2.07590383214, 522.57741809380], + [0.00086792905, 0.71001145545, 419.48464387520], + [0.00072062974, 0.21465724607, 536.80451209540], + [0.00065517248, 5.97995884790, 316.39186965660], + [0.00029134542, 1.67759379655, 103.09277421860], + [0.00030135335, 2.16132003734, 949.17560896980], + [0.00023453271, 3.54023522184, 735.87651353180], + [0.00022283743, 4.19362594399, 1589.07289528380], + [0.00023947298, 0.27458037480, 7.11354700080], + [0.00013032614, 2.96042965363, 1162.47470440780], + [0.00009703360, 1.90669633585, 206.18554843720], + [0.00012749023, 2.71550286592, 1052.26838318840], + [0.00007057931, 2.18184839926, 1265.56747862640], + [0.00006137703, 6.26418240033, 846.08283475120], + [0.00002616976, 2.00994012876, 1581.95934828300] + ], + [ + [0.01271801520, 2.64937512894, 529.69096509460], + [0.00061661816, 3.00076460387, 1059.38193018920], + [0.00053443713, 3.89717383175, 522.57741809380], + [0.00031185171, 4.88276958012, 536.80451209540], + [0.00041390269, 0.00000000000, 0.00000000000] + ] + ] + ], + Saturn: [ + [ + [ + [0.87401354025, 0.00000000000, 0.00000000000], + [0.11107659762, 3.96205090159, 213.29909543800], + [0.01414150957, 4.58581516874, 7.11354700080], + [0.00398379389, 0.52112032699, 206.18554843720], + [0.00350769243, 3.30329907896, 426.59819087600], + [0.00206816305, 0.24658372002, 103.09277421860], + [0.00079271300, 3.84007056878, 220.41264243880], + [0.00023990355, 4.66976924553, 110.20632121940], + [0.00016573588, 0.43719228296, 419.48464387520], + [0.00014906995, 5.76903183869, 316.39186965660], + [0.00015820290, 0.93809155235, 632.78373931320], + [0.00014609559, 1.56518472000, 3.93215326310], + [0.00013160301, 4.44891291899, 14.22709400160], + [0.00015053543, 2.71669915667, 639.89728631400], + [0.00013005299, 5.98119023644, 11.04570026390], + [0.00010725067, 3.12939523827, 202.25339517410], + [0.00005863206, 0.23656938524, 529.69096509460], + [0.00005227757, 4.20783365759, 3.18139373770], + [0.00006126317, 1.76328667907, 277.03499374140], + [0.00005019687, 3.17787728405, 433.71173787680], + [0.00004592550, 0.61977744975, 199.07200143640], + [0.00004005867, 2.24479718502, 63.73589830340], + [0.00002953796, 0.98280366998, 95.97922721780], + [0.00003873670, 3.22283226966, 138.51749687070], + [0.00002461186, 2.03163875071, 735.87651353180], + [0.00003269484, 0.77492638211, 949.17560896980], + [0.00001758145, 3.26580109940, 522.57741809380], + [0.00001640172, 5.50504453050, 846.08283475120], + [0.00001391327, 4.02333150505, 323.50541665740], + [0.00001580648, 4.37265307169, 309.27832265580], + [0.00001123498, 2.83726798446, 415.55249061210], + [0.00001017275, 3.71700135395, 227.52618943960], + [0.00000848642, 3.19150170830, 209.36694217490] + ], + [ + [213.29909521690, 0.00000000000, 0.00000000000], + [0.01297370862, 1.82834923978, 213.29909543800], + [0.00564345393, 2.88499717272, 7.11354700080], + [0.00093734369, 1.06311793502, 426.59819087600], + [0.00107674962, 2.27769131009, 206.18554843720], + [0.00040244455, 2.04108104671, 220.41264243880], + [0.00019941774, 1.27954390470, 103.09277421860], + [0.00010511678, 2.74880342130, 14.22709400160], + [0.00006416106, 0.38238295041, 639.89728631400], + [0.00004848994, 2.43037610229, 419.48464387520], + [0.00004056892, 2.92133209468, 110.20632121940], + [0.00003768635, 3.64965330780, 3.93215326310] + ], + [ + [0.00116441330, 1.17988132879, 7.11354700080], + [0.00091841837, 0.07325195840, 213.29909543800], + [0.00036661728, 0.00000000000, 0.00000000000], + [0.00015274496, 4.06493179167, 206.18554843720] + ] + ], + [ + [ + [0.04330678039, 3.60284428399, 213.29909543800], + [0.00240348302, 2.85238489373, 426.59819087600], + [0.00084745939, 0.00000000000, 0.00000000000], + [0.00030863357, 3.48441504555, 220.41264243880], + [0.00034116062, 0.57297307557, 206.18554843720], + [0.00014734070, 2.11846596715, 639.89728631400], + [0.00009916667, 5.79003188904, 419.48464387520], + [0.00006993564, 4.73604689720, 7.11354700080], + [0.00004807588, 5.43305312061, 316.39186965660] + ], + [ + [0.00198927992, 4.93901017903, 213.29909543800], + [0.00036947916, 3.14159265359, 0.00000000000], + [0.00017966989, 0.51979431110, 426.59819087600] + ] + ], + [ + [ + [9.55758135486, 0.00000000000, 0.00000000000], + [0.52921382865, 2.39226219573, 213.29909543800], + [0.01873679867, 5.23549604660, 206.18554843720], + [0.01464663929, 1.64763042902, 426.59819087600], + [0.00821891141, 5.93520042303, 316.39186965660], + [0.00547506923, 5.01532618980, 103.09277421860], + [0.00371684650, 2.27114821115, 220.41264243880], + [0.00361778765, 3.13904301847, 7.11354700080], + [0.00140617506, 5.70406606781, 632.78373931320], + [0.00108974848, 3.29313390175, 110.20632121940], + [0.00069006962, 5.94099540992, 419.48464387520], + [0.00061053367, 0.94037691801, 639.89728631400], + [0.00048913294, 1.55733638681, 202.25339517410], + [0.00034143772, 0.19519102597, 277.03499374140], + [0.00032401773, 5.47084567016, 949.17560896980], + [0.00020936596, 0.46349251129, 735.87651353180], + [0.00009796004, 5.20477537945, 1265.56747862640], + [0.00011993338, 5.98050967385, 846.08283475120], + [0.00020839300, 1.52102476129, 433.71173787680], + [0.00015298404, 3.05943814940, 529.69096509460], + [0.00006465823, 0.17732249942, 1052.26838318840], + [0.00011380257, 1.73105427040, 522.57741809380], + [0.00003419618, 4.94550542171, 1581.95934828300] + ], + [ + [0.06182981340, 0.25843511480, 213.29909543800], + [0.00506577242, 0.71114625261, 206.18554843720], + [0.00341394029, 5.79635741658, 426.59819087600], + [0.00188491195, 0.47215589652, 220.41264243880], + [0.00186261486, 3.14159265359, 0.00000000000], + [0.00143891146, 1.40744822888, 7.11354700080] + ], + [ + [0.00436902572, 4.78671677509, 213.29909543800] + ] + ] + ], + Uranus: [ + [ + [ + [5.48129294297, 0.00000000000, 0.00000000000], + [0.09260408234, 0.89106421507, 74.78159856730], + [0.01504247898, 3.62719260920, 1.48447270830], + [0.00365981674, 1.89962179044, 73.29712585900], + [0.00272328168, 3.35823706307, 149.56319713460], + [0.00070328461, 5.39254450063, 63.73589830340], + [0.00068892678, 6.09292483287, 76.26607127560], + [0.00061998615, 2.26952066061, 2.96894541660], + [0.00061950719, 2.85098872691, 11.04570026390], + [0.00026468770, 3.14152083966, 71.81265315070], + [0.00025710476, 6.11379840493, 454.90936652730], + [0.00021078850, 4.36059339067, 148.07872442630], + [0.00017818647, 1.74436930289, 36.64856292950], + [0.00014613507, 4.73732166022, 3.93215326310], + [0.00011162509, 5.82681796350, 224.34479570190], + [0.00010997910, 0.48865004018, 138.51749687070], + [0.00009527478, 2.95516862826, 35.16409022120], + [0.00007545601, 5.23626582400, 109.94568878850], + [0.00004220241, 3.23328220918, 70.84944530420], + [0.00004051900, 2.27755017300, 151.04766984290], + [0.00003354596, 1.06549007380, 4.45341812490], + [0.00002926718, 4.62903718891, 9.56122755560], + [0.00003490340, 5.48306144511, 146.59425171800], + [0.00003144069, 4.75199570434, 77.75054398390], + [0.00002922333, 5.35235361027, 85.82729883120], + [0.00002272788, 4.36600400036, 70.32818044240], + [0.00002051219, 1.51773566586, 0.11187458460], + [0.00002148602, 0.60745949945, 38.13303563780], + [0.00001991643, 4.92437588682, 277.03499374140], + [0.00001376226, 2.04283539351, 65.22037101170], + [0.00001666902, 3.62744066769, 380.12776796000], + [0.00001284107, 3.11347961505, 202.25339517410], + [0.00001150429, 0.93343589092, 3.18139373770], + [0.00001533221, 2.58594681212, 52.69019803950], + [0.00001281604, 0.54271272721, 222.86032299360], + [0.00001372139, 4.19641530878, 111.43016149680], + [0.00001221029, 0.19900650030, 108.46121608020], + [0.00000946181, 1.19253165736, 127.47179660680], + [0.00001150989, 4.17898916639, 33.67961751290] + ], + [ + [74.78159860910, 0.00000000000, 0.00000000000], + [0.00154332863, 5.24158770553, 74.78159856730], + [0.00024456474, 1.71260334156, 1.48447270830], + [0.00009258442, 0.42829732350, 11.04570026390], + [0.00008265977, 1.50218091379, 63.73589830340], + [0.00009150160, 1.41213765216, 149.56319713460] + ] + ], + [ + [ + [0.01346277648, 2.61877810547, 74.78159856730], + [0.00062341400, 5.08111189648, 149.56319713460], + [0.00061601196, 3.14159265359, 0.00000000000], + [0.00009963722, 1.61603805646, 76.26607127560], + [0.00009926160, 0.57630380333, 73.29712585900] + ], + [ + [0.00034101978, 0.01321929936, 74.78159856730] + ] + ], + [ + [ + [19.21264847206, 0.00000000000, 0.00000000000], + [0.88784984413, 5.60377527014, 74.78159856730], + [0.03440836062, 0.32836099706, 73.29712585900], + [0.02055653860, 1.78295159330, 149.56319713460], + [0.00649322410, 4.52247285911, 76.26607127560], + [0.00602247865, 3.86003823674, 63.73589830340], + [0.00496404167, 1.40139935333, 454.90936652730], + [0.00338525369, 1.58002770318, 138.51749687070], + [0.00243509114, 1.57086606044, 71.81265315070], + [0.00190522303, 1.99809394714, 1.48447270830], + [0.00161858838, 2.79137786799, 148.07872442630], + [0.00143706183, 1.38368544947, 11.04570026390], + [0.00093192405, 0.17437220467, 36.64856292950], + [0.00071424548, 4.24509236074, 224.34479570190], + [0.00089806014, 3.66105364565, 109.94568878850], + [0.00039009723, 1.66971401684, 70.84944530420], + [0.00046677296, 1.39976401694, 35.16409022120], + [0.00039025624, 3.36234773834, 277.03499374140], + [0.00036755274, 3.88649278513, 146.59425171800], + [0.00030348723, 0.70100838798, 151.04766984290], + [0.00029156413, 3.18056336700, 77.75054398390], + [0.00022637073, 0.72518687029, 529.69096509460], + [0.00011959076, 1.75043392140, 984.60033162190], + [0.00025620756, 5.25656086672, 380.12776796000] + ], + [ + [0.01479896629, 3.67205697578, 74.78159856730] + ] + ] + ], + Neptune: [ + [ + [ + [5.31188633046, 0.00000000000, 0.00000000000], + [0.01798475530, 2.90101273890, 38.13303563780], + [0.01019727652, 0.48580922867, 1.48447270830], + [0.00124531845, 4.83008090676, 36.64856292950], + [0.00042064466, 5.41054993053, 2.96894541660], + [0.00037714584, 6.09221808686, 35.16409022120], + [0.00033784738, 1.24488874087, 76.26607127560], + [0.00016482741, 0.00007727998, 491.55792945680], + [0.00009198584, 4.93747051954, 39.61750834610], + [0.00008994250, 0.27462171806, 175.16605980020] + ], + [ + [38.13303563957, 0.00000000000, 0.00000000000], + [0.00016604172, 4.86323329249, 1.48447270830], + [0.00015744045, 2.27887427527, 38.13303563780] + ] + ], + [ + [ + [0.03088622933, 1.44104372644, 38.13303563780], + [0.00027780087, 5.91271884599, 76.26607127560], + [0.00027623609, 0.00000000000, 0.00000000000], + [0.00015355489, 2.52123799551, 36.64856292950], + [0.00015448133, 3.50877079215, 39.61750834610] + ] + ], + [ + [ + [30.07013205828, 0.00000000000, 0.00000000000], + [0.27062259632, 1.32999459377, 38.13303563780], + [0.01691764014, 3.25186135653, 36.64856292950], + [0.00807830553, 5.18592878704, 1.48447270830], + [0.00537760510, 4.52113935896, 35.16409022120], + [0.00495725141, 1.57105641650, 491.55792945680], + [0.00274571975, 1.84552258866, 175.16605980020], + [0.00012012320, 1.92059384991, 1021.24889455140], + [0.00121801746, 5.79754470298, 76.26607127560], + [0.00100896068, 0.37702724930, 73.29712585900], + [0.00135134092, 3.37220609835, 39.61750834610], + [0.00007571796, 1.07149207335, 388.46515523820] + ] + ] + ] +}; +function DeltaT_EspenakMeeus(ut) { + var u, u2, u3, u4, u5, u6, u7; + /* + Fred Espenak writes about Delta-T generically here: + https://eclipse.gsfc.nasa.gov/SEhelp/deltaT.html + https://eclipse.gsfc.nasa.gov/SEhelp/deltat2004.html + + He provides polynomial approximations for distant years here: + https://eclipse.gsfc.nasa.gov/SEhelp/deltatpoly2004.html + + They start with a year value 'y' such that y=2000 corresponds + to the UTC Date 15-January-2000. Convert difference in days + to mean tropical years. + */ + const y = 2000 + ((ut - 14) / DAYS_PER_TROPICAL_YEAR); + if (y < -500) { + u = (y - 1820) / 100; + return -20 + (32 * u * u); + } + if (y < 500) { + u = y / 100; + u2 = u * u; + u3 = u * u2; + u4 = u2 * u2; + u5 = u2 * u3; + u6 = u3 * u3; + return 10583.6 - 1014.41 * u + 33.78311 * u2 - 5.952053 * u3 - 0.1798452 * u4 + 0.022174192 * u5 + 0.0090316521 * u6; + } + if (y < 1600) { + u = (y - 1000) / 100; + u2 = u * u; + u3 = u * u2; + u4 = u2 * u2; + u5 = u2 * u3; + u6 = u3 * u3; + return 1574.2 - 556.01 * u + 71.23472 * u2 + 0.319781 * u3 - 0.8503463 * u4 - 0.005050998 * u5 + 0.0083572073 * u6; + } + if (y < 1700) { + u = y - 1600; + u2 = u * u; + u3 = u * u2; + return 120 - 0.9808 * u - 0.01532 * u2 + u3 / 7129.0; + } + if (y < 1800) { + u = y - 1700; + u2 = u * u; + u3 = u * u2; + u4 = u2 * u2; + return 8.83 + 0.1603 * u - 0.0059285 * u2 + 0.00013336 * u3 - u4 / 1174000; + } + if (y < 1860) { + u = y - 1800; + u2 = u * u; + u3 = u * u2; + u4 = u2 * u2; + u5 = u2 * u3; + u6 = u3 * u3; + u7 = u3 * u4; + return 13.72 - 0.332447 * u + 0.0068612 * u2 + 0.0041116 * u3 - 0.00037436 * u4 + 0.0000121272 * u5 - 0.0000001699 * u6 + 0.000000000875 * u7; + } + if (y < 1900) { + u = y - 1860; + u2 = u * u; + u3 = u * u2; + u4 = u2 * u2; + u5 = u2 * u3; + return 7.62 + 0.5737 * u - 0.251754 * u2 + 0.01680668 * u3 - 0.0004473624 * u4 + u5 / 233174; + } + if (y < 1920) { + u = y - 1900; + u2 = u * u; + u3 = u * u2; + u4 = u2 * u2; + return -2.79 + 1.494119 * u - 0.0598939 * u2 + 0.0061966 * u3 - 0.000197 * u4; + } + if (y < 1941) { + u = y - 1920; + u2 = u * u; + u3 = u * u2; + return 21.20 + 0.84493 * u - 0.076100 * u2 + 0.0020936 * u3; + } + if (y < 1961) { + u = y - 1950; + u2 = u * u; + u3 = u * u2; + return 29.07 + 0.407 * u - u2 / 233 + u3 / 2547; + } + if (y < 1986) { + u = y - 1975; + u2 = u * u; + u3 = u * u2; + return 45.45 + 1.067 * u - u2 / 260 - u3 / 718; + } + if (y < 2005) { + u = y - 2000; + u2 = u * u; + u3 = u * u2; + u4 = u2 * u2; + u5 = u2 * u3; + return 63.86 + 0.3345 * u - 0.060374 * u2 + 0.0017275 * u3 + 0.000651814 * u4 + 0.00002373599 * u5; + } + if (y < 2050) { + u = y - 2000; + return 62.92 + 0.32217 * u + 0.005589 * u * u; + } + if (y < 2150) { + u = (y - 1820) / 100; + return -20 + 32 * u * u - 0.5628 * (2150 - y); + } + /* all years after 2150 */ + u = (y - 1820) / 100; + return -20 + (32 * u * u); +} +exports.DeltaT_EspenakMeeus = DeltaT_EspenakMeeus; +function DeltaT_JplHorizons(ut) { + return DeltaT_EspenakMeeus(Math.min(ut, 17.0 * DAYS_PER_TROPICAL_YEAR)); +} +exports.DeltaT_JplHorizons = DeltaT_JplHorizons; +let DeltaT = DeltaT_EspenakMeeus; +function SetDeltaTFunction(func) { + DeltaT = func; +} +exports.SetDeltaTFunction = SetDeltaTFunction; +/** + * @ignore + * + * @brief Calculates Terrestrial Time (TT) from Universal Time (UT). + * + * @param {number} ut + * The Universal Time expressed as a floating point number of days since the 2000.0 epoch. + * + * @returns {number} + * A Terrestrial Time expressed as a floating point number of days since the 2000.0 epoch. + */ +function TerrestrialTime(ut) { + return ut + DeltaT(ut) / 86400; +} +/** + * @brief The date and time of an astronomical observation. + * + * Objects of type `AstroTime` are used throughout the internals + * of the Astronomy library, and are included in certain return objects. + * Use the constructor or the {@link MakeTime} function to create an `AstroTime` object. + * + * @property {Date} date + * The JavaScript Date object for the given date and time. + * This Date corresponds to the numeric day value stored in the `ut` property. + * + * @property {number} ut + * Universal Time (UT1/UTC) in fractional days since the J2000 epoch. + * Universal Time represents time measured with respect to the Earth's rotation, + * tracking mean solar days. + * The Astronomy library approximates UT1 and UTC as being the same thing. + * This gives sufficient accuracy for the precision requirements of this project. + * + * @property {number} tt + * Terrestrial Time in fractional days since the J2000 epoch. + * TT represents a continuously flowing ephemeris timescale independent of + * any variations of the Earth's rotation, and is adjusted from UT + * using a best-fit piecewise polynomial model devised by + * [Espenak and Meeus](https://eclipse.gsfc.nasa.gov/SEhelp/deltatpoly2004.html). + */ +class AstroTime { + /** + * @param {FlexibleDateTime} date + * A JavaScript Date object, a numeric UTC value expressed in J2000 days, or another AstroTime object. + */ + constructor(date) { + if (date instanceof AstroTime) { + // Construct a clone of the AstroTime passed in. + this.date = date.date; + this.ut = date.ut; + this.tt = date.tt; + return; + } + const MillisPerDay = 1000 * 3600 * 24; + if ((date instanceof Date) && Number.isFinite(date.getTime())) { + this.date = date; + this.ut = (date.getTime() - J2000.getTime()) / MillisPerDay; + this.tt = TerrestrialTime(this.ut); + return; + } + if (Number.isFinite(date)) { + this.date = new Date(J2000.getTime() + date * MillisPerDay); + this.ut = date; + this.tt = TerrestrialTime(this.ut); + return; + } + throw 'Argument must be a Date object, an AstroTime object, or a numeric UTC Julian date.'; + } + /** + * @brief Creates an `AstroTime` value from a Terrestrial Time (TT) day value. + * + * This function can be used in rare cases where a time must be based + * on Terrestrial Time (TT) rather than Universal Time (UT). + * Most developers will want to invoke `new AstroTime(ut)` with a universal time + * instead of this function, because usually time is based on civil time adjusted + * by leap seconds to match the Earth's rotation, rather than the uniformly + * flowing TT used to calculate solar system dynamics. In rare cases + * where the caller already knows TT, this function is provided to create + * an `AstroTime` value that can be passed to Astronomy Engine functions. + * + * @param {number} tt + * The number of days since the J2000 epoch as expressed in Terrestrial Time. + * + * @returns {AstroTime} + * An `AstroTime` object for the specified terrestrial time. + */ + static FromTerrestrialTime(tt) { + let time = new AstroTime(tt); + for (;;) { + const err = tt - time.tt; + if (Math.abs(err) < 1.0e-12) + return time; + time = time.AddDays(err); + } + } + /** + * Formats an `AstroTime` object as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) + * date/time string in UTC, to millisecond resolution. + * Example: `2018-08-17T17:22:04.050Z` + * @returns {string} + */ + toString() { + return this.date.toISOString(); + } + /** + * Returns a new `AstroTime` object adjusted by the floating point number of days. + * Does NOT modify the original `AstroTime` object. + * + * @param {number} days + * The floating point number of days by which to adjust the given date and time. + * Positive values adjust the date toward the future, and + * negative values adjust the date toward the past. + * + * @returns {AstroTime} + */ + AddDays(days) { + // This is slightly wrong, but the error is tiny. + // We really should be adding to TT, not to UT. + // But using TT would require creating an inverse function for DeltaT, + // which would be quite a bit of extra calculation. + // I estimate the error is in practice on the order of 10^(-7) + // times the value of 'days'. + // This is based on a typical drift of 1 second per year between UT and TT. + return new AstroTime(this.ut + days); + } +} +exports.AstroTime = AstroTime; +function InterpolateTime(time1, time2, fraction) { + return new AstroTime(time1.ut + fraction * (time2.ut - time1.ut)); +} +/** + * @brief A `Date`, `number`, or `AstroTime` value that specifies the date and time of an astronomical event. + * + * `FlexibleDateTime` is a placeholder type that represents three different types + * that may be passed to many Astronomy Engine functions: a JavaScript `Date` object, + * a number representing the real-valued number of UT days since the J2000 epoch, + * or an {@link AstroTime} object. + * + * This flexibility is for convenience of outside callers. + * Internally, Astronomy Engine always converts a `FlexibleDateTime` parameter + * to an `AstroTime` object by calling {@link MakeTime}. + * + * @typedef {Date | number | AstroTime} FlexibleDateTime + */ +/** + * @brief Converts multiple date/time formats to `AstroTime` format. + * + * Given a Date object or a number days since noon (12:00) on January 1, 2000 (UTC), + * this function creates an {@link AstroTime} object. + * + * Given an {@link AstroTime} object, returns the same object unmodified. + * Use of this function is not required for any of the other exposed functions in this library, + * because they all guarantee converting date/time parameters to `AstroTime` + * as needed. However, it may be convenient for callers who need to understand + * the difference between UTC and TT (Terrestrial Time). In some use cases, + * converting once to `AstroTime` format and passing the result into multiple + * function calls may be more efficient than passing in native JavaScript Date objects. + * + * @param {FlexibleDateTime} date + * A Date object, a number of UTC days since the J2000 epoch (noon on January 1, 2000), + * or an AstroTime object. See remarks above. + * + * @returns {AstroTime} + */ +function MakeTime(date) { + if (date instanceof AstroTime) { + return date; + } + return new AstroTime(date); +} +exports.MakeTime = MakeTime; +function iau2000b(time) { + function mod(x) { + return (x % ASEC360) * ASEC2RAD; + } + const t = time.tt / 36525; + const elp = mod(1287104.79305 + t * 129596581.0481); + const f = mod(335779.526232 + t * 1739527262.8478); + const d = mod(1072260.70369 + t * 1602961601.2090); + const om = mod(450160.398036 - t * 6962890.5431); + let sarg = Math.sin(om); + let carg = Math.cos(om); + let dp = (-172064161.0 - 174666.0 * t) * sarg + 33386.0 * carg; + let de = (92052331.0 + 9086.0 * t) * carg + 15377.0 * sarg; + let arg = 2.0 * (f - d + om); + sarg = Math.sin(arg); + carg = Math.cos(arg); + dp += (-13170906.0 - 1675.0 * t) * sarg - 13696.0 * carg; + de += (5730336.0 - 3015.0 * t) * carg - 4587.0 * sarg; + arg = 2.0 * (f + om); + sarg = Math.sin(arg); + carg = Math.cos(arg); + dp += (-2276413.0 - 234.0 * t) * sarg + 2796.0 * carg; + de += (978459.0 - 485.0 * t) * carg + 1374.0 * sarg; + arg = 2.0 * om; + sarg = Math.sin(arg); + carg = Math.cos(arg); + dp += (2074554.0 + 207.0 * t) * sarg - 698.0 * carg; + de += (-897492.0 + 470.0 * t) * carg - 291.0 * sarg; + sarg = Math.sin(elp); + carg = Math.cos(elp); + dp += (1475877.0 - 3633.0 * t) * sarg + 11817.0 * carg; + de += (73871.0 - 184.0 * t) * carg - 1924.0 * sarg; + return { + dpsi: -0.000135 + (dp * 1.0e-7), + deps: +0.000388 + (de * 1.0e-7) + }; +} +function mean_obliq(time) { + var t = time.tt / 36525; + var asec = (((((-0.0000000434 * t + - 0.000000576) * t + + 0.00200340) * t + - 0.0001831) * t + - 46.836769) * t + 84381.406); + return asec / 3600.0; +} +var cache_e_tilt; +function e_tilt(time) { + if (!cache_e_tilt || Math.abs(cache_e_tilt.tt - time.tt) > 1.0e-6) { + const nut = iau2000b(time); + const mean_ob = mean_obliq(time); + const true_ob = mean_ob + (nut.deps / 3600); + cache_e_tilt = { + tt: time.tt, + dpsi: nut.dpsi, + deps: nut.deps, + ee: nut.dpsi * Math.cos(mean_ob * exports.DEG2RAD) / 15, + mobl: mean_ob, + tobl: true_ob + }; + } + return cache_e_tilt; +} +exports.e_tilt = e_tilt; +function obl_ecl2equ_vec(oblDegrees, pos) { + const obl = oblDegrees * exports.DEG2RAD; + const cos_obl = Math.cos(obl); + const sin_obl = Math.sin(obl); + return [ + pos[0], + pos[1] * cos_obl - pos[2] * sin_obl, + pos[1] * sin_obl + pos[2] * cos_obl + ]; +} +function ecl2equ_vec(time, pos) { + return obl_ecl2equ_vec(mean_obliq(time), pos); +} +exports.CalcMoonCount = 0; +function CalcMoon(time) { + ++exports.CalcMoonCount; + const T = time.tt / 36525; + function DeclareArray1(xmin, xmax) { + const array = []; + let i; + for (i = 0; i <= xmax - xmin; ++i) { + array.push(0); + } + return { min: xmin, array: array }; + } + function DeclareArray2(xmin, xmax, ymin, ymax) { + const array = []; + for (let i = 0; i <= xmax - xmin; ++i) { + array.push(DeclareArray1(ymin, ymax)); + } + return { min: xmin, array: array }; + } + function ArrayGet2(a, x, y) { + const m = a.array[x - a.min]; + return m.array[y - m.min]; + } + function ArraySet2(a, x, y, v) { + const m = a.array[x - a.min]; + m.array[y - m.min] = v; + } + let S, MAX, ARG, FAC, I, J, T2, DGAM, DLAM, N, GAM1C, SINPI, L0, L, LS, F, D, DL0, DL, DLS, DF, DD, DS; + let coArray = DeclareArray2(-6, 6, 1, 4); + let siArray = DeclareArray2(-6, 6, 1, 4); + function CO(x, y) { + return ArrayGet2(coArray, x, y); + } + function SI(x, y) { + return ArrayGet2(siArray, x, y); + } + function SetCO(x, y, v) { + return ArraySet2(coArray, x, y, v); + } + function SetSI(x, y, v) { + return ArraySet2(siArray, x, y, v); + } + function AddThe(c1, s1, c2, s2, func) { + func(c1 * c2 - s1 * s2, s1 * c2 + c1 * s2); + } + function Sine(phi) { + return Math.sin(PI2 * phi); + } + T2 = T * T; + DLAM = 0; + DS = 0; + GAM1C = 0; + SINPI = 3422.7000; + var S1 = Sine(0.19833 + 0.05611 * T); + var S2 = Sine(0.27869 + 0.04508 * T); + var S3 = Sine(0.16827 - 0.36903 * T); + var S4 = Sine(0.34734 - 5.37261 * T); + var S5 = Sine(0.10498 - 5.37899 * T); + var S6 = Sine(0.42681 - 0.41855 * T); + var S7 = Sine(0.14943 - 5.37511 * T); + DL0 = 0.84 * S1 + 0.31 * S2 + 14.27 * S3 + 7.26 * S4 + 0.28 * S5 + 0.24 * S6; + DL = 2.94 * S1 + 0.31 * S2 + 14.27 * S3 + 9.34 * S4 + 1.12 * S5 + 0.83 * S6; + DLS = -6.40 * S1 - 1.89 * S6; + DF = 0.21 * S1 + 0.31 * S2 + 14.27 * S3 - 88.70 * S4 - 15.30 * S5 + 0.24 * S6 - 1.86 * S7; + DD = DL0 - DLS; + DGAM = (-3332E-9 * Sine(0.59734 - 5.37261 * T) + - 539E-9 * Sine(0.35498 - 5.37899 * T) + - 64E-9 * Sine(0.39943 - 5.37511 * T)); + L0 = PI2 * Frac(0.60643382 + 1336.85522467 * T - 0.00000313 * T2) + DL0 / ARC; + L = PI2 * Frac(0.37489701 + 1325.55240982 * T + 0.00002565 * T2) + DL / ARC; + LS = PI2 * Frac(0.99312619 + 99.99735956 * T - 0.00000044 * T2) + DLS / ARC; + F = PI2 * Frac(0.25909118 + 1342.22782980 * T - 0.00000892 * T2) + DF / ARC; + D = PI2 * Frac(0.82736186 + 1236.85308708 * T - 0.00000397 * T2) + DD / ARC; + for (I = 1; I <= 4; ++I) { + switch (I) { + case 1: + ARG = L; + MAX = 4; + FAC = 1.000002208; + break; + case 2: + ARG = LS; + MAX = 3; + FAC = 0.997504612 - 0.002495388 * T; + break; + case 3: + ARG = F; + MAX = 4; + FAC = 1.000002708 + 139.978 * DGAM; + break; + case 4: + ARG = D; + MAX = 6; + FAC = 1.0; + break; + default: throw `Internal error: I = ${I}`; // persuade TypeScript that ARG, ... are all initialized before use. + } + SetCO(0, I, 1); + SetCO(1, I, Math.cos(ARG) * FAC); + SetSI(0, I, 0); + SetSI(1, I, Math.sin(ARG) * FAC); + for (J = 2; J <= MAX; ++J) { + AddThe(CO(J - 1, I), SI(J - 1, I), CO(1, I), SI(1, I), (c, s) => (SetCO(J, I, c), SetSI(J, I, s))); + } + for (J = 1; J <= MAX; ++J) { + SetCO(-J, I, CO(J, I)); + SetSI(-J, I, -SI(J, I)); + } + } + function Term(p, q, r, s) { + var result = { x: 1, y: 0 }; + var I = [0, p, q, r, s]; // I[0] is not used; it is a placeholder + for (var k = 1; k <= 4; ++k) + if (I[k] !== 0) + AddThe(result.x, result.y, CO(I[k], k), SI(I[k], k), (c, s) => (result.x = c, result.y = s)); + return result; + } + function AddSol(coeffl, coeffs, coeffg, coeffp, p, q, r, s) { + var result = Term(p, q, r, s); + DLAM += coeffl * result.y; + DS += coeffs * result.y; + GAM1C += coeffg * result.x; + SINPI += coeffp * result.x; + } + AddSol(13.9020, 14.0600, -0.0010, 0.2607, 0, 0, 0, 4); + AddSol(0.4030, -4.0100, 0.3940, 0.0023, 0, 0, 0, 3); + AddSol(2369.9120, 2373.3600, 0.6010, 28.2333, 0, 0, 0, 2); + AddSol(-125.1540, -112.7900, -0.7250, -0.9781, 0, 0, 0, 1); + AddSol(1.9790, 6.9800, -0.4450, 0.0433, 1, 0, 0, 4); + AddSol(191.9530, 192.7200, 0.0290, 3.0861, 1, 0, 0, 2); + AddSol(-8.4660, -13.5100, 0.4550, -0.1093, 1, 0, 0, 1); + AddSol(22639.5000, 22609.0700, 0.0790, 186.5398, 1, 0, 0, 0); + AddSol(18.6090, 3.5900, -0.0940, 0.0118, 1, 0, 0, -1); + AddSol(-4586.4650, -4578.1300, -0.0770, 34.3117, 1, 0, 0, -2); + AddSol(3.2150, 5.4400, 0.1920, -0.0386, 1, 0, 0, -3); + AddSol(-38.4280, -38.6400, 0.0010, 0.6008, 1, 0, 0, -4); + AddSol(-0.3930, -1.4300, -0.0920, 0.0086, 1, 0, 0, -6); + AddSol(-0.2890, -1.5900, 0.1230, -0.0053, 0, 1, 0, 4); + AddSol(-24.4200, -25.1000, 0.0400, -0.3000, 0, 1, 0, 2); + AddSol(18.0230, 17.9300, 0.0070, 0.1494, 0, 1, 0, 1); + AddSol(-668.1460, -126.9800, -1.3020, -0.3997, 0, 1, 0, 0); + AddSol(0.5600, 0.3200, -0.0010, -0.0037, 0, 1, 0, -1); + AddSol(-165.1450, -165.0600, 0.0540, 1.9178, 0, 1, 0, -2); + AddSol(-1.8770, -6.4600, -0.4160, 0.0339, 0, 1, 0, -4); + AddSol(0.2130, 1.0200, -0.0740, 0.0054, 2, 0, 0, 4); + AddSol(14.3870, 14.7800, -0.0170, 0.2833, 2, 0, 0, 2); + AddSol(-0.5860, -1.2000, 0.0540, -0.0100, 2, 0, 0, 1); + AddSol(769.0160, 767.9600, 0.1070, 10.1657, 2, 0, 0, 0); + AddSol(1.7500, 2.0100, -0.0180, 0.0155, 2, 0, 0, -1); + AddSol(-211.6560, -152.5300, 5.6790, -0.3039, 2, 0, 0, -2); + AddSol(1.2250, 0.9100, -0.0300, -0.0088, 2, 0, 0, -3); + AddSol(-30.7730, -34.0700, -0.3080, 0.3722, 2, 0, 0, -4); + AddSol(-0.5700, -1.4000, -0.0740, 0.0109, 2, 0, 0, -6); + AddSol(-2.9210, -11.7500, 0.7870, -0.0484, 1, 1, 0, 2); + AddSol(1.2670, 1.5200, -0.0220, 0.0164, 1, 1, 0, 1); + AddSol(-109.6730, -115.1800, 0.4610, -0.9490, 1, 1, 0, 0); + AddSol(-205.9620, -182.3600, 2.0560, 1.4437, 1, 1, 0, -2); + AddSol(0.2330, 0.3600, 0.0120, -0.0025, 1, 1, 0, -3); + AddSol(-4.3910, -9.6600, -0.4710, 0.0673, 1, 1, 0, -4); + AddSol(0.2830, 1.5300, -0.1110, 0.0060, 1, -1, 0, 4); + AddSol(14.5770, 31.7000, -1.5400, 0.2302, 1, -1, 0, 2); + AddSol(147.6870, 138.7600, 0.6790, 1.1528, 1, -1, 0, 0); + AddSol(-1.0890, 0.5500, 0.0210, 0.0000, 1, -1, 0, -1); + AddSol(28.4750, 23.5900, -0.4430, -0.2257, 1, -1, 0, -2); + AddSol(-0.2760, -0.3800, -0.0060, -0.0036, 1, -1, 0, -3); + AddSol(0.6360, 2.2700, 0.1460, -0.0102, 1, -1, 0, -4); + AddSol(-0.1890, -1.6800, 0.1310, -0.0028, 0, 2, 0, 2); + AddSol(-7.4860, -0.6600, -0.0370, -0.0086, 0, 2, 0, 0); + AddSol(-8.0960, -16.3500, -0.7400, 0.0918, 0, 2, 0, -2); + AddSol(-5.7410, -0.0400, 0.0000, -0.0009, 0, 0, 2, 2); + AddSol(0.2550, 0.0000, 0.0000, 0.0000, 0, 0, 2, 1); + AddSol(-411.6080, -0.2000, 0.0000, -0.0124, 0, 0, 2, 0); + AddSol(0.5840, 0.8400, 0.0000, 0.0071, 0, 0, 2, -1); + AddSol(-55.1730, -52.1400, 0.0000, -0.1052, 0, 0, 2, -2); + AddSol(0.2540, 0.2500, 0.0000, -0.0017, 0, 0, 2, -3); + AddSol(0.0250, -1.6700, 0.0000, 0.0031, 0, 0, 2, -4); + AddSol(1.0600, 2.9600, -0.1660, 0.0243, 3, 0, 0, 2); + AddSol(36.1240, 50.6400, -1.3000, 0.6215, 3, 0, 0, 0); + AddSol(-13.1930, -16.4000, 0.2580, -0.1187, 3, 0, 0, -2); + AddSol(-1.1870, -0.7400, 0.0420, 0.0074, 3, 0, 0, -4); + AddSol(-0.2930, -0.3100, -0.0020, 0.0046, 3, 0, 0, -6); + AddSol(-0.2900, -1.4500, 0.1160, -0.0051, 2, 1, 0, 2); + AddSol(-7.6490, -10.5600, 0.2590, -0.1038, 2, 1, 0, 0); + AddSol(-8.6270, -7.5900, 0.0780, -0.0192, 2, 1, 0, -2); + AddSol(-2.7400, -2.5400, 0.0220, 0.0324, 2, 1, 0, -4); + AddSol(1.1810, 3.3200, -0.2120, 0.0213, 2, -1, 0, 2); + AddSol(9.7030, 11.6700, -0.1510, 0.1268, 2, -1, 0, 0); + AddSol(-0.3520, -0.3700, 0.0010, -0.0028, 2, -1, 0, -1); + AddSol(-2.4940, -1.1700, -0.0030, -0.0017, 2, -1, 0, -2); + AddSol(0.3600, 0.2000, -0.0120, -0.0043, 2, -1, 0, -4); + AddSol(-1.1670, -1.2500, 0.0080, -0.0106, 1, 2, 0, 0); + AddSol(-7.4120, -6.1200, 0.1170, 0.0484, 1, 2, 0, -2); + AddSol(-0.3110, -0.6500, -0.0320, 0.0044, 1, 2, 0, -4); + AddSol(0.7570, 1.8200, -0.1050, 0.0112, 1, -2, 0, 2); + AddSol(2.5800, 2.3200, 0.0270, 0.0196, 1, -2, 0, 0); + AddSol(2.5330, 2.4000, -0.0140, -0.0212, 1, -2, 0, -2); + AddSol(-0.3440, -0.5700, -0.0250, 0.0036, 0, 3, 0, -2); + AddSol(-0.9920, -0.0200, 0.0000, 0.0000, 1, 0, 2, 2); + AddSol(-45.0990, -0.0200, 0.0000, -0.0010, 1, 0, 2, 0); + AddSol(-0.1790, -9.5200, 0.0000, -0.0833, 1, 0, 2, -2); + AddSol(-0.3010, -0.3300, 0.0000, 0.0014, 1, 0, 2, -4); + AddSol(-6.3820, -3.3700, 0.0000, -0.0481, 1, 0, -2, 2); + AddSol(39.5280, 85.1300, 0.0000, -0.7136, 1, 0, -2, 0); + AddSol(9.3660, 0.7100, 0.0000, -0.0112, 1, 0, -2, -2); + AddSol(0.2020, 0.0200, 0.0000, 0.0000, 1, 0, -2, -4); + AddSol(0.4150, 0.1000, 0.0000, 0.0013, 0, 1, 2, 0); + AddSol(-2.1520, -2.2600, 0.0000, -0.0066, 0, 1, 2, -2); + AddSol(-1.4400, -1.3000, 0.0000, 0.0014, 0, 1, -2, 2); + AddSol(0.3840, -0.0400, 0.0000, 0.0000, 0, 1, -2, -2); + AddSol(1.9380, 3.6000, -0.1450, 0.0401, 4, 0, 0, 0); + AddSol(-0.9520, -1.5800, 0.0520, -0.0130, 4, 0, 0, -2); + AddSol(-0.5510, -0.9400, 0.0320, -0.0097, 3, 1, 0, 0); + AddSol(-0.4820, -0.5700, 0.0050, -0.0045, 3, 1, 0, -2); + AddSol(0.6810, 0.9600, -0.0260, 0.0115, 3, -1, 0, 0); + AddSol(-0.2970, -0.2700, 0.0020, -0.0009, 2, 2, 0, -2); + AddSol(0.2540, 0.2100, -0.0030, 0.0000, 2, -2, 0, -2); + AddSol(-0.2500, -0.2200, 0.0040, 0.0014, 1, 3, 0, -2); + AddSol(-3.9960, 0.0000, 0.0000, 0.0004, 2, 0, 2, 0); + AddSol(0.5570, -0.7500, 0.0000, -0.0090, 2, 0, 2, -2); + AddSol(-0.4590, -0.3800, 0.0000, -0.0053, 2, 0, -2, 2); + AddSol(-1.2980, 0.7400, 0.0000, 0.0004, 2, 0, -2, 0); + AddSol(0.5380, 1.1400, 0.0000, -0.0141, 2, 0, -2, -2); + AddSol(0.2630, 0.0200, 0.0000, 0.0000, 1, 1, 2, 0); + AddSol(0.4260, 0.0700, 0.0000, -0.0006, 1, 1, -2, -2); + AddSol(-0.3040, 0.0300, 0.0000, 0.0003, 1, -1, 2, 0); + AddSol(-0.3720, -0.1900, 0.0000, -0.0027, 1, -1, -2, 2); + AddSol(0.4180, 0.0000, 0.0000, 0.0000, 0, 0, 4, 0); + AddSol(-0.3300, -0.0400, 0.0000, 0.0000, 3, 0, 2, 0); + function ADDN(coeffn, p, q, r, s) { + return coeffn * Term(p, q, r, s).y; + } + N = 0; + N += ADDN(-526.069, 0, 0, 1, -2); + N += ADDN(-3.352, 0, 0, 1, -4); + N += ADDN(+44.297, +1, 0, 1, -2); + N += ADDN(-6.000, +1, 0, 1, -4); + N += ADDN(+20.599, -1, 0, 1, 0); + N += ADDN(-30.598, -1, 0, 1, -2); + N += ADDN(-24.649, -2, 0, 1, 0); + N += ADDN(-2.000, -2, 0, 1, -2); + N += ADDN(-22.571, 0, +1, 1, -2); + N += ADDN(+10.985, 0, -1, 1, -2); + DLAM += (+0.82 * Sine(0.7736 - 62.5512 * T) + 0.31 * Sine(0.0466 - 125.1025 * T) + + 0.35 * Sine(0.5785 - 25.1042 * T) + 0.66 * Sine(0.4591 + 1335.8075 * T) + + 0.64 * Sine(0.3130 - 91.5680 * T) + 1.14 * Sine(0.1480 + 1331.2898 * T) + + 0.21 * Sine(0.5918 + 1056.5859 * T) + 0.44 * Sine(0.5784 + 1322.8595 * T) + + 0.24 * Sine(0.2275 - 5.7374 * T) + 0.28 * Sine(0.2965 + 2.6929 * T) + + 0.33 * Sine(0.3132 + 6.3368 * T)); + S = F + DS / ARC; + let lat_seconds = (1.000002708 + 139.978 * DGAM) * (18518.511 + 1.189 + GAM1C) * Math.sin(S) - 6.24 * Math.sin(3 * S) + N; + return { + geo_eclip_lon: PI2 * Frac((L0 + DLAM / ARC) / PI2), + geo_eclip_lat: (Math.PI / (180 * 3600)) * lat_seconds, + distance_au: (ARC * EARTH_EQUATORIAL_RADIUS_AU) / (0.999953253 * SINPI) + }; +} +/** + * @brief Lunar libration angles, returned by {@link Libration}. + * + * @property {number} elat + * Sub-Earth libration ecliptic latitude angle, in degrees. + * @property {number} elon + * Sub-Earth libration ecliptic longitude angle, in degrees. + * @property {number} mlat + * Moon's geocentric ecliptic latitude, in degrees. + * @property {number} mlon + * Moon's geocentric ecliptic longitude, in degrees. + * @property {number} dist_km + * Distance between the centers of the Earth and Moon in kilometers. + * @property {number} diam_deg + * The apparent angular diameter of the Moon, in degrees, as seen from the center of the Earth. + */ +class LibrationInfo { + constructor(elat, elon, mlat, mlon, dist_km, diam_deg) { + this.elat = elat; + this.elon = elon; + this.mlat = mlat; + this.mlon = mlon; + this.dist_km = dist_km; + this.diam_deg = diam_deg; + } +} +exports.LibrationInfo = LibrationInfo; +/** + * @brief Calculates the Moon's libration angles at a given moment in time. + * + * Libration is an observed back-and-forth wobble of the portion of the + * Moon visible from the Earth. It is caused by the imperfect tidal locking + * of the Moon's fixed rotation rate, compared to its variable angular speed + * of orbit around the Earth. + * + * This function calculates a pair of perpendicular libration angles, + * one representing rotation of the Moon in ecliptic longitude `elon`, the other + * in ecliptic latitude `elat`, both relative to the Moon's mean Earth-facing position. + * + * This function also returns the geocentric position of the Moon + * expressed in ecliptic longitude `mlon`, ecliptic latitude `mlat`, the + * distance `dist_km` between the centers of the Earth and Moon expressed in kilometers, + * and the apparent angular diameter of the Moon `diam_deg`. + * + * @param {FlexibleDateTime} date + * A Date object, a number of UTC days since the J2000 epoch (noon on January 1, 2000), + * or an AstroTime object. + * + * @returns {LibrationInfo} + */ +function Libration(date) { + const time = MakeTime(date); + const t = time.tt / 36525.0; + const t2 = t * t; + const t3 = t2 * t; + const t4 = t2 * t2; + const moon = CalcMoon(time); + const mlon = moon.geo_eclip_lon; + const mlat = moon.geo_eclip_lat; + const dist_km = moon.distance_au * exports.KM_PER_AU; + // Inclination angle + const I = exports.DEG2RAD * 1.543; + // Moon's argument of latitude in radians. + const f = exports.DEG2RAD * NormalizeLongitude(93.2720950 + 483202.0175233 * t - 0.0036539 * t2 - t3 / 3526000 + t4 / 863310000); + // Moon's ascending node's mean longitude in radians. + const omega = exports.DEG2RAD * NormalizeLongitude(125.0445479 - 1934.1362891 * t + 0.0020754 * t2 + t3 / 467441 - t4 / 60616000); + // Sun's mean anomaly. + const m = exports.DEG2RAD * NormalizeLongitude(357.5291092 + 35999.0502909 * t - 0.0001536 * t2 + t3 / 24490000); + // Moon's mean anomaly. + const mdash = exports.DEG2RAD * NormalizeLongitude(134.9633964 + 477198.8675055 * t + 0.0087414 * t2 + t3 / 69699 - t4 / 14712000); + // Moon's mean elongation. + const d = exports.DEG2RAD * NormalizeLongitude(297.8501921 + 445267.1114034 * t - 0.0018819 * t2 + t3 / 545868 - t4 / 113065000); + // Eccentricity of the Earth's orbit. + const e = 1.0 - 0.002516 * t - 0.0000074 * t2; + // Optical librations + const w = mlon - omega; + const a = Math.atan2(Math.sin(w) * Math.cos(mlat) * Math.cos(I) - Math.sin(mlat) * Math.sin(I), Math.cos(w) * Math.cos(mlat)); + const ldash = LongitudeOffset(exports.RAD2DEG * (a - f)); + const bdash = Math.asin(-Math.sin(w) * Math.cos(mlat) * Math.sin(I) - Math.sin(mlat) * Math.cos(I)); + // Physical librations + const k1 = exports.DEG2RAD * (119.75 + 131.849 * t); + const k2 = exports.DEG2RAD * (72.56 + 20.186 * t); + const rho = (-0.02752 * Math.cos(mdash) + + -0.02245 * Math.sin(f) + + +0.00684 * Math.cos(mdash - 2 * f) + + -0.00293 * Math.cos(2 * f) + + -0.00085 * Math.cos(2 * f - 2 * d) + + -0.00054 * Math.cos(mdash - 2 * d) + + -0.00020 * Math.sin(mdash + f) + + -0.00020 * Math.cos(mdash + 2 * f) + + -0.00020 * Math.cos(mdash - f) + + +0.00014 * Math.cos(mdash + 2 * f - 2 * d)); + const sigma = (-0.02816 * Math.sin(mdash) + + +0.02244 * Math.cos(f) + + -0.00682 * Math.sin(mdash - 2 * f) + + -0.00279 * Math.sin(2 * f) + + -0.00083 * Math.sin(2 * f - 2 * d) + + +0.00069 * Math.sin(mdash - 2 * d) + + +0.00040 * Math.cos(mdash + f) + + -0.00025 * Math.sin(2 * mdash) + + -0.00023 * Math.sin(mdash + 2 * f) + + +0.00020 * Math.cos(mdash - f) + + +0.00019 * Math.sin(mdash - f) + + +0.00013 * Math.sin(mdash + 2 * f - 2 * d) + + -0.00010 * Math.cos(mdash - 3 * f)); + const tau = (+0.02520 * e * Math.sin(m) + + +0.00473 * Math.sin(2 * mdash - 2 * f) + + -0.00467 * Math.sin(mdash) + + +0.00396 * Math.sin(k1) + + +0.00276 * Math.sin(2 * mdash - 2 * d) + + +0.00196 * Math.sin(omega) + + -0.00183 * Math.cos(mdash - f) + + +0.00115 * Math.sin(mdash - 2 * d) + + -0.00096 * Math.sin(mdash - d) + + +0.00046 * Math.sin(2 * f - 2 * d) + + -0.00039 * Math.sin(mdash - f) + + -0.00032 * Math.sin(mdash - m - d) + + +0.00027 * Math.sin(2 * mdash - m - 2 * d) + + +0.00023 * Math.sin(k2) + + -0.00014 * Math.sin(2 * d) + + +0.00014 * Math.cos(2 * mdash - 2 * f) + + -0.00012 * Math.sin(mdash - 2 * f) + + -0.00012 * Math.sin(2 * mdash) + + +0.00011 * Math.sin(2 * mdash - 2 * m - 2 * d)); + const ldash2 = -tau + (rho * Math.cos(a) + sigma * Math.sin(a)) * Math.tan(bdash); + const bdash2 = sigma * Math.cos(a) - rho * Math.sin(a); + const diam_deg = 2.0 * exports.RAD2DEG * Math.atan(MOON_MEAN_RADIUS_KM / Math.sqrt(dist_km * dist_km - MOON_MEAN_RADIUS_KM * MOON_MEAN_RADIUS_KM)); + return new LibrationInfo(exports.RAD2DEG * bdash + bdash2, ldash + ldash2, exports.RAD2DEG * mlat, exports.RAD2DEG * mlon, dist_km, diam_deg); +} +exports.Libration = Libration; +function rotate(rot, vec) { + return [ + rot.rot[0][0] * vec[0] + rot.rot[1][0] * vec[1] + rot.rot[2][0] * vec[2], + rot.rot[0][1] * vec[0] + rot.rot[1][1] * vec[1] + rot.rot[2][1] * vec[2], + rot.rot[0][2] * vec[0] + rot.rot[1][2] * vec[1] + rot.rot[2][2] * vec[2] + ]; +} +function precession(pos, time, dir) { + const r = precession_rot(time, dir); + return rotate(r, pos); +} +function precession_posvel(state, time, dir) { + const r = precession_rot(time, dir); + return RotateState(r, state); +} +function precession_rot(time, dir) { + const t = time.tt / 36525; + let eps0 = 84381.406; + let psia = (((((-0.0000000951 * t + + 0.000132851) * t + - 0.00114045) * t + - 1.0790069) * t + + 5038.481507) * t); + let omegaa = (((((+0.0000003337 * t + - 0.000000467) * t + - 0.00772503) * t + + 0.0512623) * t + - 0.025754) * t + eps0); + let chia = (((((-0.0000000560 * t + + 0.000170663) * t + - 0.00121197) * t + - 2.3814292) * t + + 10.556403) * t); + eps0 *= ASEC2RAD; + psia *= ASEC2RAD; + omegaa *= ASEC2RAD; + chia *= ASEC2RAD; + const sa = Math.sin(eps0); + const ca = Math.cos(eps0); + const sb = Math.sin(-psia); + const cb = Math.cos(-psia); + const sc = Math.sin(-omegaa); + const cc = Math.cos(-omegaa); + const sd = Math.sin(chia); + const cd = Math.cos(chia); + const xx = cd * cb - sb * sd * cc; + const yx = cd * sb * ca + sd * cc * cb * ca - sa * sd * sc; + const zx = cd * sb * sa + sd * cc * cb * sa + ca * sd * sc; + const xy = -sd * cb - sb * cd * cc; + const yy = -sd * sb * ca + cd * cc * cb * ca - sa * cd * sc; + const zy = -sd * sb * sa + cd * cc * cb * sa + ca * cd * sc; + const xz = sb * sc; + const yz = -sc * cb * ca - sa * cc; + const zz = -sc * cb * sa + cc * ca; + if (dir === PrecessDirection.Into2000) { + // Perform rotation from epoch to J2000.0. + return new RotationMatrix([ + [xx, yx, zx], + [xy, yy, zy], + [xz, yz, zz] + ]); + } + if (dir === PrecessDirection.From2000) { + // Perform rotation from J2000.0 to epoch. + return new RotationMatrix([ + [xx, xy, xz], + [yx, yy, yz], + [zx, zy, zz] + ]); + } + throw 'Invalid precess direction'; +} +function era(time) { + const thet1 = 0.7790572732640 + 0.00273781191135448 * time.ut; + const thet3 = time.ut % 1; + let theta = 360 * ((thet1 + thet3) % 1); + if (theta < 0) { + theta += 360; + } + return theta; +} +let sidereal_time_cache; +function sidereal_time(time) { + if (!sidereal_time_cache || sidereal_time_cache.tt !== time.tt) { + const t = time.tt / 36525; + let eqeq = 15 * e_tilt(time).ee; // Replace with eqeq=0 to get GMST instead of GAST (if we ever need it) + const theta = era(time); + const st = (eqeq + 0.014506 + + ((((-0.0000000368 * t + - 0.000029956) * t + - 0.00000044) * t + + 1.3915817) * t + + 4612.156534) * t); + let gst = ((st / 3600 + theta) % 360) / 15; + if (gst < 0) { + gst += 24; + } + sidereal_time_cache = { + tt: time.tt, + st: gst + }; + } + return sidereal_time_cache.st; // return sidereal hours in the half-open range [0, 24). +} +/** + * @brief Calculates Greenwich Apparent Sidereal Time (GAST). + * + * Given a date and time, this function calculates the rotation of the + * Earth, represented by the equatorial angle of the Greenwich prime meridian + * with respect to distant stars (not the Sun, which moves relative to background + * stars by almost one degree per day). + * This angle is called Greenwich Apparent Sidereal Time (GAST). + * GAST is measured in sidereal hours in the half-open range [0, 24). + * When GAST = 0, it means the prime meridian is aligned with the of-date equinox, + * corrected at that time for precession and nutation of the Earth's axis. + * In this context, the "equinox" is the direction in space where the Earth's + * orbital plane (the ecliptic) intersects with the plane of the Earth's equator, + * at the location on the Earth's orbit of the (seasonal) March equinox. + * As the Earth rotates, GAST increases from 0 up to 24 sidereal hours, + * then starts over at 0. + * To convert to degrees, multiply the return value by 15. + * + * @param {FlexibleDateTime} date + * The date and time for which to find GAST. + * + * @returns {number} + */ +function SiderealTime(date) { + const time = MakeTime(date); + return sidereal_time(time); +} +exports.SiderealTime = SiderealTime; +function inverse_terra(ovec, st) { + // Convert from AU to kilometers + const x = ovec[0] * exports.KM_PER_AU; + const y = ovec[1] * exports.KM_PER_AU; + const z = ovec[2] * exports.KM_PER_AU; + const p = Math.hypot(x, y); + let lon_deg, lat_deg, height_km; + if (p < 1.0e-6) { + // Special case: within 1 millimeter of a pole! + // Use arbitrary longitude, and latitude determined by polarity of z. + lon_deg = 0; + lat_deg = (z > 0.0) ? +90 : -90; + // Elevation is calculated directly from z. + height_km = Math.abs(z) - EARTH_POLAR_RADIUS_KM; + } + else { + const stlocl = Math.atan2(y, x); + // Calculate exact longitude. + lon_deg = (exports.RAD2DEG * stlocl) - (15.0 * st); + // Normalize longitude to the range (-180, +180]. + while (lon_deg <= -180) + lon_deg += 360; + while (lon_deg > +180) + lon_deg -= 360; + // Numerically solve for exact latitude, using Newton's Method. + // Start with initial latitude estimate, based on a spherical Earth. + let lat = Math.atan2(z, p); + let cos, sin, denom; + let count = 0; + for (;;) { + if (++count > 10) + throw `inverse_terra failed to converge.`; + // Calculate the error function W(lat). + // We try to find the root of W, meaning where the error is 0. + cos = Math.cos(lat); + sin = Math.sin(lat); + const factor = (EARTH_FLATTENING_SQUARED - 1) * EARTH_EQUATORIAL_RADIUS_KM; + const cos2 = cos * cos; + const sin2 = sin * sin; + const radicand = cos2 + EARTH_FLATTENING_SQUARED * sin2; + denom = Math.sqrt(radicand); + const W = (factor * sin * cos) / denom - z * cos + p * sin; + if (Math.abs(W) < 1.0e-8) + break; // The error is now negligible + // Error is still too large. Find the next estimate. + // Calculate D = the derivative of W with respect to lat. + const D = factor * ((cos2 - sin2) / denom - sin2 * cos2 * (EARTH_FLATTENING_SQUARED - 1) / (factor * radicand)) + z * sin + p * cos; + lat -= W / D; + } + // We now have a solution for the latitude in radians. + lat_deg = exports.RAD2DEG * lat; + // Solve for exact height in meters. + // There are two formulas I can use. Use whichever has the less risky denominator. + const adjust = EARTH_EQUATORIAL_RADIUS_KM / denom; + if (Math.abs(sin) > Math.abs(cos)) + height_km = z / sin - EARTH_FLATTENING_SQUARED * adjust; + else + height_km = p / cos - adjust; + } + return new Observer(lat_deg, lon_deg, 1000 * height_km); +} +function terra(observer, st) { + const phi = observer.latitude * exports.DEG2RAD; + const sinphi = Math.sin(phi); + const cosphi = Math.cos(phi); + const c = 1 / Math.hypot(cosphi, EARTH_FLATTENING * sinphi); + const s = EARTH_FLATTENING_SQUARED * c; + const ht_km = observer.height / 1000; + const ach = EARTH_EQUATORIAL_RADIUS_KM * c + ht_km; + const ash = EARTH_EQUATORIAL_RADIUS_KM * s + ht_km; + const stlocl = (15 * st + observer.longitude) * exports.DEG2RAD; + const sinst = Math.sin(stlocl); + const cosst = Math.cos(stlocl); + return { + pos: [ach * cosphi * cosst / exports.KM_PER_AU, ach * cosphi * sinst / exports.KM_PER_AU, ash * sinphi / exports.KM_PER_AU], + vel: [-ANGVEL * ach * cosphi * sinst * 86400 / exports.KM_PER_AU, ANGVEL * ach * cosphi * cosst * 86400 / exports.KM_PER_AU, 0] + }; +} +function nutation(pos, time, dir) { + const r = nutation_rot(time, dir); + return rotate(r, pos); +} +function nutation_posvel(state, time, dir) { + const r = nutation_rot(time, dir); + return RotateState(r, state); +} +function nutation_rot(time, dir) { + const tilt = e_tilt(time); + const oblm = tilt.mobl * exports.DEG2RAD; + const oblt = tilt.tobl * exports.DEG2RAD; + const psi = tilt.dpsi * ASEC2RAD; + const cobm = Math.cos(oblm); + const sobm = Math.sin(oblm); + const cobt = Math.cos(oblt); + const sobt = Math.sin(oblt); + const cpsi = Math.cos(psi); + const spsi = Math.sin(psi); + const xx = cpsi; + const yx = -spsi * cobm; + const zx = -spsi * sobm; + const xy = spsi * cobt; + const yy = cpsi * cobm * cobt + sobm * sobt; + const zy = cpsi * sobm * cobt - cobm * sobt; + const xz = spsi * sobt; + const yz = cpsi * cobm * sobt - sobm * cobt; + const zz = cpsi * sobm * sobt + cobm * cobt; + if (dir === PrecessDirection.From2000) { + // convert J2000 to of-date + return new RotationMatrix([ + [xx, xy, xz], + [yx, yy, yz], + [zx, zy, zz] + ]); + } + if (dir === PrecessDirection.Into2000) { + // convert of-date to J2000 + return new RotationMatrix([ + [xx, yx, zx], + [xy, yy, zy], + [xz, yz, zz] + ]); + } + throw 'Invalid precess direction'; +} +function gyration(pos, time, dir) { + // Combine nutation and precession into a single operation I call "gyration". + // The order they are composed depends on the direction, + // because both directions are mutual inverse functions. + return (dir === PrecessDirection.Into2000) ? + precession(nutation(pos, time, dir), time, dir) : + nutation(precession(pos, time, dir), time, dir); +} +function gyration_posvel(state, time, dir) { + // Combine nutation and precession into a single operation I call "gyration". + // The order they are composed depends on the direction, + // because both directions are mutual inverse functions. + return (dir === PrecessDirection.Into2000) ? + precession_posvel(nutation_posvel(state, time, dir), time, dir) : + nutation_posvel(precession_posvel(state, time, dir), time, dir); +} +function geo_pos(time, observer) { + const gast = sidereal_time(time); + const pos = terra(observer, gast).pos; + return gyration(pos, time, PrecessDirection.Into2000); +} +/** + * @brief A 3D Cartesian vector with a time attached to it. + * + * Holds the Cartesian coordinates of a vector in 3D space, + * along with the time at which the vector is valid. + * + * @property {number} x The x-coordinate expressed in astronomical units (AU). + * @property {number} y The y-coordinate expressed in astronomical units (AU). + * @property {number} z The z-coordinate expressed in astronomical units (AU). + * @property {AstroTime} t The time at which the vector is valid. + */ +class Vector { + constructor(x, y, z, t) { + this.x = x; + this.y = y; + this.z = z; + this.t = t; + } + /** + * Returns the length of the vector in astronomical units (AU). + * @returns {number} + */ + Length() { + return Math.hypot(this.x, this.y, this.z); + } +} +exports.Vector = Vector; +/** + * @brief A combination of a position vector, a velocity vector, and a time. + * + * Holds the state vector of a body at a given time, including its position, + * velocity, and the time they are valid. + * + * @property {number} x The position x-coordinate expressed in astronomical units (AU). + * @property {number} y The position y-coordinate expressed in astronomical units (AU). + * @property {number} z The position z-coordinate expressed in astronomical units (AU). + * @property {number} vx The velocity x-coordinate expressed in AU/day. + * @property {number} vy The velocity y-coordinate expressed in AU/day. + * @property {number} vz The velocity z-coordinate expressed in AU/day. + * @property {AstroTime} t The time at which the vector is valid. + */ +class StateVector { + constructor(x, y, z, vx, vy, vz, t) { + this.x = x; + this.y = y; + this.z = z; + this.vx = vx; + this.vy = vy; + this.vz = vz; + this.t = t; + } +} +exports.StateVector = StateVector; +/** + * @brief Holds spherical coordinates: latitude, longitude, distance. + * + * Spherical coordinates represent the location of + * a point using two angles and a distance. + * + * @property {number} lat The latitude angle: -90..+90 degrees. + * @property {number} lon The longitude angle: 0..360 degrees. + * @property {number} dist Distance in AU. + */ +class Spherical { + constructor(lat, lon, dist) { + this.lat = VerifyNumber(lat); + this.lon = VerifyNumber(lon); + this.dist = VerifyNumber(dist); + } +} +exports.Spherical = Spherical; +/** + * @brief Holds right ascension, declination, and distance of a celestial object. + * + * @property {number} ra + * Right ascension in sidereal hours: [0, 24). + * + * @property {number} dec + * Declination in degrees: [-90, +90]. + * + * @property {number} dist + * Distance to the celestial object expressed in + * astronomical units (AU). + * + * @property {Vector} vec + * The equatorial coordinates in cartesian form, using AU distance units. + * x = direction of the March equinox, + * y = direction of the June solstice, + * z = north. + */ +class EquatorialCoordinates { + constructor(ra, dec, dist, vec) { + this.ra = VerifyNumber(ra); + this.dec = VerifyNumber(dec); + this.dist = VerifyNumber(dist); + this.vec = vec; + } +} +exports.EquatorialCoordinates = EquatorialCoordinates; +function IsValidRotationArray(rot) { + if (!(rot instanceof Array) || (rot.length !== 3)) + return false; + for (let i = 0; i < 3; ++i) { + if (!(rot[i] instanceof Array) || (rot[i].length !== 3)) + return false; + for (let j = 0; j < 3; ++j) + if (!Number.isFinite(rot[i][j])) + return false; + } + return true; +} +/** + * @brief Contains a rotation matrix that can be used to transform one coordinate system to another. + * + * @property {number[][]} rot + * A normalized 3x3 rotation matrix. For example, the identity matrix is represented + * as `[[1, 0, 0], [0, 1, 0], [0, 0, 1]]`. + */ +class RotationMatrix { + constructor(rot) { + this.rot = rot; + } +} +exports.RotationMatrix = RotationMatrix; +/** + * @brief Creates a rotation matrix that can be used to transform one coordinate system to another. + * + * This function verifies that the `rot` parameter is of the correct format: + * a number[3][3] array. It throws an exception if `rot` is not of that shape. + * Otherwise it creates a new {@link RotationMatrix} object based on `rot`. + * + * @param {number[][]} rot + * An array [3][3] of numbers. Defines a rotation matrix used to premultiply + * a 3D vector to reorient it into another coordinate system. + * + * @returns {RotationMatrix} + */ +function MakeRotation(rot) { + if (!IsValidRotationArray(rot)) + throw 'Argument must be a [3][3] array of numbers'; + return new RotationMatrix(rot); +} +exports.MakeRotation = MakeRotation; +/** + * @brief Represents the location of an object seen by an observer on the Earth. + * + * Holds azimuth (compass direction) and altitude (angle above/below the horizon) + * of a celestial object as seen by an observer at a particular location on the Earth's surface. + * Also holds right ascension and declination of the same object. + * All of these coordinates are optionally adjusted for atmospheric refraction; + * therefore the right ascension and declination values may not exactly match + * those found inside a corresponding {@link EquatorialCoordinates} object. + * + * @property {number} azimuth + * A horizontal compass direction angle in degrees measured starting at north + * and increasing positively toward the east. + * The value is in the range [0, 360). + * North = 0, east = 90, south = 180, west = 270. + * + * @property {number} altitude + * A vertical angle in degrees above (positive) or below (negative) the horizon. + * The value is in the range [-90, +90]. + * The altitude angle is optionally adjusted upward due to atmospheric refraction. + * + * @property {number} ra + * The right ascension of the celestial body in sidereal hours. + * The value is in the reange [0, 24). + * If `altitude` was adjusted for atmospheric reaction, `ra` + * is likewise adjusted. + * + * @property {number} dec + * The declination of of the celestial body in degrees. + * The value in the range [-90, +90]. + * If `altitude` was adjusted for atmospheric reaction, `dec` + * is likewise adjusted. + */ +class HorizontalCoordinates { + constructor(azimuth, altitude, ra, dec) { + this.azimuth = VerifyNumber(azimuth); + this.altitude = VerifyNumber(altitude); + this.ra = VerifyNumber(ra); + this.dec = VerifyNumber(dec); + } +} +exports.HorizontalCoordinates = HorizontalCoordinates; +/** + * @brief Ecliptic coordinates of a celestial body. + * + * The origin and date of the coordinate system may vary depending on the caller's usage. + * In general, ecliptic coordinates are measured with respect to the mean plane of the Earth's + * orbit around the Sun. + * Includes Cartesian coordinates `(ex, ey, ez)` measured in + * astronomical units (AU) + * and spherical coordinates `(elon, elat)` measured in degrees. + * + * @property {Vector} vec + * Ecliptic cartesian vector with components measured in astronomical units (AU). + * The x-axis is within the ecliptic plane and is oriented in the direction of the + * equinox. + * The y-axis is within the ecliptic plane and is oriented 90 degrees + * counterclockwise from the equinox, as seen from above the Sun's north pole. + * The z-axis is oriented perpendicular to the ecliptic plane, + * along the direction of the Sun's north pole. + * + * @property {number} elat + * The ecliptic latitude of the body in degrees. + * This is the angle north or south of the ecliptic plane. + * The value is in the range [-90, +90]. + * Positive values are north and negative values are south. + * + * @property {number} elon + * The ecliptic longitude of the body in degrees. + * This is the angle measured counterclockwise around the ecliptic plane, + * as seen from above the Sun's north pole. + * This is the same direction that the Earth orbits around the Sun. + * The angle is measured starting at 0 from the equinox and increases + * up to 360 degrees. + */ +class EclipticCoordinates { + constructor(vec, elat, elon) { + this.vec = vec; + this.elat = VerifyNumber(elat); + this.elon = VerifyNumber(elon); + } +} +exports.EclipticCoordinates = EclipticCoordinates; +function VectorFromArray(av, time) { + return new Vector(av[0], av[1], av[2], time); +} +function vector2radec(pos, time) { + const vec = VectorFromArray(pos, time); + const xyproj = vec.x * vec.x + vec.y * vec.y; + const dist = Math.sqrt(xyproj + vec.z * vec.z); + if (xyproj === 0) { + if (vec.z === 0) + throw 'Indeterminate sky coordinates'; + return new EquatorialCoordinates(0, (vec.z < 0) ? -90 : +90, dist, vec); + } + let ra = exports.RAD2HOUR * Math.atan2(vec.y, vec.x); + if (ra < 0) + ra += 24; + const dec = exports.RAD2DEG * Math.atan2(pos[2], Math.sqrt(xyproj)); + return new EquatorialCoordinates(ra, dec, dist, vec); +} +function spin(angle, pos) { + const angr = angle * exports.DEG2RAD; + const c = Math.cos(angr); + const s = Math.sin(angr); + return [c * pos[0] + s * pos[1], c * pos[1] - s * pos[0], pos[2]]; +} +/** + * @brief Converts equatorial coordinates to horizontal coordinates. + * + * Given a date and time, a geographic location of an observer on the Earth, and + * equatorial coordinates (right ascension and declination) of a celestial body, + * returns horizontal coordinates (azimuth and altitude angles) for that body + * as seen by that observer. Allows optional correction for atmospheric refraction. + * + * @param {FlexibleDateTime} date + * The date and time for which to find horizontal coordinates. + * + * @param {Observer} observer + * The location of the observer for which to find horizontal coordinates. + * + * @param {number} ra + * Right ascension in sidereal hours of the celestial object, + * referred to the mean equinox of date for the J2000 epoch. + * + * @param {number} dec + * Declination in degrees of the celestial object, + * referred to the mean equator of date for the J2000 epoch. + * Positive values are north of the celestial equator and negative values are south. + * + * @param {string} refraction + * If omitted or has a false-like value (false, null, undefined, etc.) + * the calculations are performed without any correction for atmospheric + * refraction. If the value is the string `"normal"`, + * uses the recommended refraction correction based on Meeus "Astronomical Algorithms" + * with a linear taper more than 1 degree below the horizon. The linear + * taper causes the refraction to linearly approach 0 as the altitude of the + * body approaches the nadir (-90 degrees). + * If the value is the string `"jplhor"`, uses a JPL Horizons + * compatible formula. This is the same algorithm as `"normal"`, + * only without linear tapering; this can result in physically impossible + * altitudes of less than -90 degrees, which may cause problems for some applications. + * (The `"jplhor"` option was created for unit testing against data + * generated by JPL Horizons, and is otherwise not recommended for use.) + * + * @returns {HorizontalCoordinates} + */ +function Horizon(date, observer, ra, dec, refraction) { + // based on NOVAS equ2hor() + let time = MakeTime(date); + VerifyObserver(observer); + VerifyNumber(ra); + VerifyNumber(dec); + const sinlat = Math.sin(observer.latitude * exports.DEG2RAD); + const coslat = Math.cos(observer.latitude * exports.DEG2RAD); + const sinlon = Math.sin(observer.longitude * exports.DEG2RAD); + const coslon = Math.cos(observer.longitude * exports.DEG2RAD); + const sindc = Math.sin(dec * exports.DEG2RAD); + const cosdc = Math.cos(dec * exports.DEG2RAD); + const sinra = Math.sin(ra * exports.HOUR2RAD); + const cosra = Math.cos(ra * exports.HOUR2RAD); + // Calculate three mutually perpendicular unit vectors + // in equatorial coordinates: uze, une, uwe. + // + // uze = The direction of the observer's local zenith (straight up). + // une = The direction toward due north on the observer's horizon. + // uwe = The direction toward due west on the observer's horizon. + // + // HOWEVER, these are uncorrected for the Earth's rotation due to the time of day. + // + // The components of these 3 vectors are as follows: + // x = direction from center of Earth toward 0 degrees longitude (the prime meridian) on equator. + // y = direction from center of Earth toward 90 degrees west longitude on equator. + // z = direction from center of Earth toward the north pole. + let uze = [coslat * coslon, coslat * sinlon, sinlat]; + let une = [-sinlat * coslon, -sinlat * sinlon, coslat]; + let uwe = [sinlon, -coslon, 0]; + // Correct the vectors uze, une, uwe for the Earth's rotation by calculating + // sidereal time. Call spin() for each uncorrected vector to rotate about + // the Earth's axis to yield corrected unit vectors uz, un, uw. + // Multiply sidereal hours by -15 to convert to degrees and flip eastward + // rotation of the Earth to westward apparent movement of objects with time. + const spin_angle = -15 * sidereal_time(time); + let uz = spin(spin_angle, uze); + let un = spin(spin_angle, une); + let uw = spin(spin_angle, uwe); + // Convert angular equatorial coordinates (RA, DEC) to + // cartesian equatorial coordinates in 'p', using the + // same orientation system as uze, une, uwe. + let p = [cosdc * cosra, cosdc * sinra, sindc]; + // Use dot products of p with the zenith, north, and west + // vectors to obtain the cartesian coordinates of the body in + // the observer's horizontal orientation system. + // pz = zenith component [-1, +1] + // pn = north component [-1, +1] + // pw = west component [-1, +1] + const pz = p[0] * uz[0] + p[1] * uz[1] + p[2] * uz[2]; + const pn = p[0] * un[0] + p[1] * un[1] + p[2] * un[2]; + const pw = p[0] * uw[0] + p[1] * uw[1] + p[2] * uw[2]; + // proj is the "shadow" of the body vector along the observer's flat ground. + let proj = Math.hypot(pn, pw); + // Calculate az = azimuth (compass direction clockwise from East.) + let az; + if (proj > 0) { + // If the body is not exactly straight up/down, it has an azimuth. + // Invert the angle to produce degrees eastward from north. + az = -exports.RAD2DEG * Math.atan2(pw, pn); + if (az < 0) + az += 360; + } + else { + // The body is straight up/down, so it does not have an azimuth. + // Report an arbitrary but reasonable value. + az = 0; + } + // zd = the angle of the body away from the observer's zenith, in degrees. + let zd = exports.RAD2DEG * Math.atan2(proj, pz); + let out_ra = ra; + let out_dec = dec; + if (refraction) { + let zd0 = zd; + let refr = Refraction(refraction, 90 - zd); + zd -= refr; + if (refr > 0.0 && zd > 3.0e-4) { + const sinzd = Math.sin(zd * exports.DEG2RAD); + const coszd = Math.cos(zd * exports.DEG2RAD); + const sinzd0 = Math.sin(zd0 * exports.DEG2RAD); + const coszd0 = Math.cos(zd0 * exports.DEG2RAD); + const pr = []; + for (let j = 0; j < 3; ++j) { + pr.push(((p[j] - coszd0 * uz[j]) / sinzd0) * sinzd + uz[j] * coszd); + } + proj = Math.hypot(pr[0], pr[1]); + if (proj > 0) { + out_ra = exports.RAD2HOUR * Math.atan2(pr[1], pr[0]); + if (out_ra < 0) { + out_ra += 24; + } + } + else { + out_ra = 0; + } + out_dec = exports.RAD2DEG * Math.atan2(pr[2], proj); + } + } + return new HorizontalCoordinates(az, 90 - zd, out_ra, out_dec); +} +exports.Horizon = Horizon; +function VerifyObserver(observer) { + if (!(observer instanceof Observer)) { + throw `Not an instance of the Observer class: ${observer}`; + } + VerifyNumber(observer.latitude); + VerifyNumber(observer.longitude); + VerifyNumber(observer.height); + if (observer.latitude < -90 || observer.latitude > +90) { + throw `Latitude ${observer.latitude} is out of range. Must be -90..+90.`; + } + return observer; +} +/** + * @brief Represents the geographic location of an observer on the surface of the Earth. + * + * @property {number} latitude + * The observer's geographic latitude in degrees north of the Earth's equator. + * The value is negative for observers south of the equator. + * Must be in the range -90 to +90. + * + * @property {number} longitude + * The observer's geographic longitude in degrees east of the prime meridian + * passing through Greenwich, England. + * The value is negative for observers west of the prime meridian. + * The value should be kept in the range -180 to +180 to minimize floating point errors. + * + * @property {number} height + * The observer's elevation above mean sea level, expressed in meters. + */ +class Observer { + constructor(latitude, longitude, height) { + this.latitude = latitude; + this.longitude = longitude; + this.height = height; + VerifyObserver(this); + } +} +exports.Observer = Observer; +/** + * @brief Returns apparent geocentric true ecliptic coordinates of date for the Sun. + * + * This function is used for calculating the times of equinoxes and solstices. + * + * Geocentric means coordinates as the Sun would appear to a hypothetical observer + * at the center of the Earth. + * Ecliptic coordinates of date are measured along the plane of the Earth's mean + * orbit around the Sun, using the + * equinox + * of the Earth as adjusted for precession and nutation of the Earth's + * axis of rotation on the given date. + * + * @param {FlexibleDateTime} date + * The date and time at which to calculate the Sun's apparent location as seen from + * the center of the Earth. + * + * @returns {EclipticCoordinates} + */ +function SunPosition(date) { + // Correct for light travel time from the Sun. + // This is really the same as correcting for aberration. + // Otherwise season calculations (equinox, solstice) will all be early by about 8 minutes! + const time = MakeTime(date).AddDays(-1 / exports.C_AUDAY); + // Get heliocentric cartesian coordinates of Earth in J2000. + const earth2000 = CalcVsop(vsop.Earth, time); + // Convert to geocentric location of the Sun. + const sun2000 = [-earth2000.x, -earth2000.y, -earth2000.z]; + // Convert to equator-of-date equatorial cartesian coordinates. + const [gx, gy, gz] = gyration(sun2000, time, PrecessDirection.From2000); + // Convert to ecliptic coordinates of date. + const true_obliq = exports.DEG2RAD * e_tilt(time).tobl; + const cos_ob = Math.cos(true_obliq); + const sin_ob = Math.sin(true_obliq); + const vec = new Vector(gx, gy, gz, time); + const sun_ecliptic = RotateEquatorialToEcliptic(vec, cos_ob, sin_ob); + return sun_ecliptic; +} +exports.SunPosition = SunPosition; +/** + * @brief Calculates equatorial coordinates of a Solar System body at a given time. + * + * Returns topocentric equatorial coordinates (right ascension and declination) + * in one of two different systems: J2000 or true-equator-of-date. + * Allows optional correction for aberration. + * Always corrects for light travel time (represents the object as seen by the observer + * with light traveling to the Earth at finite speed, not where the object is right now). + * Topocentric refers to a position as seen by an observer on the surface of the Earth. + * This function corrects for + * parallax + * of the object between a geocentric observer and a topocentric observer. + * This is most significant for the Moon, because it is so close to the Earth. + * However, it can have a small effect on the apparent positions of other bodies. + * + * @param {Body} body + * The body for which to find equatorial coordinates. + * Not allowed to be `Body.Earth`. + * + * @param {FlexibleDateTime} date + * Specifies the date and time at which the body is to be observed. + * + * @param {Observer} observer + * The location on the Earth of the observer. + * + * @param {bool} ofdate + * Pass `true` to return equatorial coordinates of date, + * i.e. corrected for precession and nutation at the given date. + * This is needed to get correct horizontal coordinates when you call + * {@link Horizon}. + * Pass `false` to return equatorial coordinates in the J2000 system. + * + * @param {bool} aberration + * Pass `true` to correct for + * aberration, + * or `false` to leave uncorrected. + * + * @returns {EquatorialCoordinates} + * The topocentric coordinates of the body as adjusted for the given observer. + */ +function Equator(body, date, observer, ofdate, aberration) { + VerifyObserver(observer); + VerifyBoolean(ofdate); + VerifyBoolean(aberration); + const time = MakeTime(date); + const gc_observer = geo_pos(time, observer); + const gc = GeoVector(body, time, aberration); + const j2000 = [ + gc.x - gc_observer[0], + gc.y - gc_observer[1], + gc.z - gc_observer[2] + ]; + if (!ofdate) + return vector2radec(j2000, time); + const datevect = gyration(j2000, time, PrecessDirection.From2000); + return vector2radec(datevect, time); +} +exports.Equator = Equator; +/** + * @brief Calculates geocentric equatorial coordinates of an observer on the surface of the Earth. + * + * This function calculates a vector from the center of the Earth to + * a point on or near the surface of the Earth, expressed in equatorial + * coordinates. It takes into account the rotation of the Earth at the given + * time, along with the given latitude, longitude, and elevation of the observer. + * + * The caller may pass `ofdate` as `true` to return coordinates relative to the Earth's + * equator at the specified time, or `false` to use the J2000 equator. + * + * The returned vector has components expressed in astronomical units (AU). + * To convert to kilometers, multiply the `x`, `y`, and `z` values by + * the constant value {@link KM_PER_AU}. + * + * The inverse of this function is also available: {@link VectorObserver}. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the observer's position vector. + * + * @param {Observer} observer + * The geographic location of a point on or near the surface of the Earth. + * + * @param {boolean} ofdate + * Selects the date of the Earth's equator in which to express the equatorial coordinates. + * The caller may pass `false` to use the orientation of the Earth's equator + * at noon UTC on January 1, 2000, in which case this function corrects for precession + * and nutation of the Earth as it was at the moment specified by the `time` parameter. + * Or the caller may pass `true` to use the Earth's equator at `time` + * as the orientation. + * + * @returns {Vector} + * An equatorial vector from the center of the Earth to the specified location + * on (or near) the Earth's surface. + */ +function ObserverVector(date, observer, ofdate) { + const time = MakeTime(date); + const gast = sidereal_time(time); + let ovec = terra(observer, gast).pos; + if (!ofdate) + ovec = gyration(ovec, time, PrecessDirection.Into2000); + return VectorFromArray(ovec, time); +} +exports.ObserverVector = ObserverVector; +/** + * @brief Calculates geocentric equatorial position and velocity of an observer on the surface of the Earth. + * + * This function calculates position and velocity vectors of an observer + * on or near the surface of the Earth, expressed in equatorial + * coordinates. It takes into account the rotation of the Earth at the given + * time, along with the given latitude, longitude, and elevation of the observer. + * + * The caller may pass `ofdate` as `true` to return coordinates relative to the Earth's + * equator at the specified time, or `false` to use the J2000 equator. + * + * The returned position vector has components expressed in astronomical units (AU). + * To convert to kilometers, multiply the `x`, `y`, and `z` values by + * the constant value {@link KM_PER_AU}. + * The returned velocity vector has components expressed in AU/day. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the observer's position and velocity vectors. + * + * @param {Observer} observer + * The geographic location of a point on or near the surface of the Earth. + * + * @param {boolean} ofdate + * Selects the date of the Earth's equator in which to express the equatorial coordinates. + * The caller may pass `false` to use the orientation of the Earth's equator + * at noon UTC on January 1, 2000, in which case this function corrects for precession + * and nutation of the Earth as it was at the moment specified by the `time` parameter. + * Or the caller may pass `true` to use the Earth's equator at `time` + * as the orientation. + * + * @returns {StateVector} + */ +function ObserverState(date, observer, ofdate) { + const time = MakeTime(date); + const gast = sidereal_time(time); + const svec = terra(observer, gast); + const state = new StateVector(svec.pos[0], svec.pos[1], svec.pos[2], svec.vel[0], svec.vel[1], svec.vel[2], time); + if (!ofdate) + return gyration_posvel(state, time, PrecessDirection.Into2000); + return state; +} +exports.ObserverState = ObserverState; +/** + * @brief Calculates the geographic location corresponding to an equatorial vector. + * + * This is the inverse function of {@link ObserverVector}. + * Given a geocentric equatorial vector, it returns the geographic + * latitude, longitude, and elevation for that vector. + * + * @param {Vector} vector + * The geocentric equatorial position vector for which to find geographic coordinates. + * The components are expressed in Astronomical Units (AU). + * You can calculate AU by dividing kilometers by the constant {@link KM_PER_AU}. + * The time `vector.t` determines the Earth's rotation. + * + * @param {boolean} ofdate + * Selects the date of the Earth's equator in which `vector` is expressed. + * The caller may select `false` to use the orientation of the Earth's equator + * at noon UTC on January 1, 2000, in which case this function corrects for precession + * and nutation of the Earth as it was at the moment specified by `vector.t`. + * Or the caller may select `true` to use the Earth's equator at `vector.t` + * as the orientation. + * + * @returns {Observer} + * The geographic latitude, longitude, and elevation above sea level + * that corresponds to the given equatorial vector. + */ +function VectorObserver(vector, ofdate) { + const gast = sidereal_time(vector.t); + let ovec = [vector.x, vector.y, vector.z]; + if (!ofdate) { + ovec = precession(ovec, vector.t, PrecessDirection.From2000); + ovec = nutation(ovec, vector.t, PrecessDirection.From2000); + } + return inverse_terra(ovec, gast); +} +exports.VectorObserver = VectorObserver; +/** + * @brief Calculates the gravitational acceleration experienced by an observer on the Earth. + * + * This function implements the WGS 84 Ellipsoidal Gravity Formula. + * The result is a combination of inward gravitational acceleration + * with outward centrifugal acceleration, as experienced by an observer + * in the Earth's rotating frame of reference. + * The resulting value increases toward the Earth's poles and decreases + * toward the equator, consistent with changes of the weight measured + * by a spring scale of a fixed mass moved to different latitudes and heights + * on the Earth. + * + * @param {number} latitude + * The latitude of the observer in degrees north or south of the equator. + * By formula symmetry, positive latitudes give the same answer as negative + * latitudes, so the sign does not matter. + * + * @param {number} height + * The height above the sea level geoid in meters. + * No range checking is done; however, accuracy is only valid in the + * range 0 to 100000 meters. + * + * @returns {number} + * The effective gravitational acceleration expressed in meters per second squared [m/s^2]. + */ +function ObserverGravity(latitude, height) { + const s = Math.sin(latitude * exports.DEG2RAD); + const s2 = s * s; + const g0 = 9.7803253359 * (1.0 + 0.00193185265241 * s2) / Math.sqrt(1.0 - 0.00669437999013 * s2); + return g0 * (1.0 - (3.15704e-07 - 2.10269e-09 * s2) * height + 7.37452e-14 * height * height); +} +exports.ObserverGravity = ObserverGravity; +function RotateEquatorialToEcliptic(equ, cos_ob, sin_ob) { + // Rotate equatorial vector to obtain ecliptic vector. + const ex = equ.x; + const ey = equ.y * cos_ob + equ.z * sin_ob; + const ez = -equ.y * sin_ob + equ.z * cos_ob; + const xyproj = Math.hypot(ex, ey); + let elon = 0; + if (xyproj > 0) { + elon = exports.RAD2DEG * Math.atan2(ey, ex); + if (elon < 0) + elon += 360; + } + let elat = exports.RAD2DEG * Math.atan2(ez, xyproj); + let ecl = new Vector(ex, ey, ez, equ.t); + return new EclipticCoordinates(ecl, elat, elon); +} +/** + * @brief Converts a J2000 mean equator (EQJ) vector to a true ecliptic of date (ETC) vector and angles. + * + * Given coordinates relative to the Earth's equator at J2000 (the instant of noon UTC + * on 1 January 2000), this function converts those coordinates to true ecliptic coordinates + * that are relative to the plane of the Earth's orbit around the Sun on that date. + * + * @param {Vector} eqj + * Equatorial coordinates in the EQJ frame of reference. + * You can call {@link GeoVector} to obtain suitable equatorial coordinates. + * + * @returns {EclipticCoordinates} + */ +function Ecliptic(eqj) { + // Calculate nutation and obliquity for this time. + // As an optimization, the nutation angles are cached in `time`, + // and reused below when the `nutation` function is called. + const et = e_tilt(eqj.t); + // Convert mean J2000 equator (EQJ) to true equator of date (EQD). + const eqj_pos = [eqj.x, eqj.y, eqj.z]; + const mean_pos = precession(eqj_pos, eqj.t, PrecessDirection.From2000); + const [x, y, z] = nutation(mean_pos, eqj.t, PrecessDirection.From2000); + const eqd = new Vector(x, y, z, eqj.t); + // Rotate from EQD to true ecliptic of date (ECT). + const tobl = et.tobl * exports.DEG2RAD; + return RotateEquatorialToEcliptic(eqd, Math.cos(tobl), Math.sin(tobl)); +} +exports.Ecliptic = Ecliptic; +/** + * @brief Calculates equatorial geocentric Cartesian coordinates for the Moon. + * + * Given a time of observation, calculates the Moon's position as a vector. + * The vector gives the location of the Moon's center relative to the Earth's center + * with x-, y-, and z-components measured in astronomical units. + * The coordinates are oriented with respect to the Earth's equator at the J2000 epoch. + * In Astronomy Engine, this orientation is called EQJ. + * Based on the Nautical Almanac Office's Improved Lunar Ephemeris of 1954, + * which in turn derives from E. W. Brown's lunar theories. + * Adapted from Turbo Pascal code from the book + * Astronomy on the Personal Computer + * by Montenbruck and Pfleger. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the Moon's geocentric position. + * + * @returns {Vector} + */ +function GeoMoon(date) { + const time = MakeTime(date); + const moon = CalcMoon(time); + // Convert geocentric ecliptic spherical coords to cartesian coords. + const dist_cos_lat = moon.distance_au * Math.cos(moon.geo_eclip_lat); + const gepos = [ + dist_cos_lat * Math.cos(moon.geo_eclip_lon), + dist_cos_lat * Math.sin(moon.geo_eclip_lon), + moon.distance_au * Math.sin(moon.geo_eclip_lat) + ]; + // Convert ecliptic coordinates to equatorial coordinates, both in mean equinox of date. + const mpos1 = ecl2equ_vec(time, gepos); + // Convert from mean equinox of date to J2000... + const mpos2 = precession(mpos1, time, PrecessDirection.Into2000); + return new Vector(mpos2[0], mpos2[1], mpos2[2], time); +} +exports.GeoMoon = GeoMoon; +/** + * @brief Calculates spherical ecliptic geocentric position of the Moon. + * + * Given a time of observation, calculates the Moon's geocentric position + * in ecliptic spherical coordinates. Provides the ecliptic latitude and + * longitude in degrees, and the geocentric distance in astronomical units (AU). + * + * The ecliptic angles are measured in "ECT": relative to the true ecliptic plane and + * equatorial plane at the specified time. This means the Earth's equator + * is corrected for precession and nutation, and the plane of the Earth's + * orbit is corrected for gradual obliquity drift. + * + * This algorithm is based on the Nautical Almanac Office's Improved Lunar Ephemeris of 1954, + * which in turn derives from E. W. Brown's lunar theories from the early twentieth century. + * It is adapted from Turbo Pascal code from the book + * Astronomy on the Personal Computer + * by Montenbruck and Pfleger. + * + * To calculate a J2000 mean equator vector instead, use {@link GeoMoon}. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the Moon's position. + * + * @returns {Spherical} + */ +function EclipticGeoMoon(date) { + const time = MakeTime(date); + const moon = CalcMoon(time); + // Convert spherical coordinates to a vector. + // The MoonResult angles are already expressed in radians. + const dist_cos_lat = moon.distance_au * Math.cos(moon.geo_eclip_lat); + const ecm = [ + dist_cos_lat * Math.cos(moon.geo_eclip_lon), + dist_cos_lat * Math.sin(moon.geo_eclip_lon), + moon.distance_au * Math.sin(moon.geo_eclip_lat) + ]; + // Obtain true and mean obliquity angles for the given time. + // This serves to pre-calculate the nutation also, and cache it in `time`. + const et = e_tilt(time); + // Convert ecliptic coordinates to equatorial coordinates, both in mean equinox of date. + const eqm = obl_ecl2equ_vec(et.mobl, ecm); + // Add nutation to convert ECM to true equatorial coordinates of date (EQD). + const eqd = nutation(eqm, time, PrecessDirection.From2000); + const eqd_vec = VectorFromArray(eqd, time); + // Convert back to ecliptic, this time in true equinox of date (ECT). + const toblRad = et.tobl * exports.DEG2RAD; + const cos_tobl = Math.cos(toblRad); + const sin_tobl = Math.sin(toblRad); + const eclip = RotateEquatorialToEcliptic(eqd_vec, cos_tobl, sin_tobl); + return new Spherical(eclip.elat, eclip.elon, moon.distance_au); +} +exports.EclipticGeoMoon = EclipticGeoMoon; +/** + * @brief Calculates equatorial geocentric position and velocity of the Moon at a given time. + * + * Given a time of observation, calculates the Moon's position and velocity vectors. + * The position and velocity are of the Moon's center relative to the Earth's center. + * The position (x, y, z) components are expressed in AU (astronomical units). + * The velocity (vx, vy, vz) components are expressed in AU/day. + * The coordinates are oriented with respect to the Earth's equator at the J2000 epoch. + * In Astronomy Engine, this orientation is called EQJ. + * If you need the Moon's position only, and not its velocity, + * it is much more efficient to use {@link GeoMoon} instead. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the Moon's geocentric state. + * + * @returns {StateVector} + */ +function GeoMoonState(date) { + const time = MakeTime(date); + // This is a hack, because trying to figure out how to derive a time + // derivative for CalcMoon() would be extremely painful! + // Calculate just before and just after the given time. + // Average to find position, subtract to find velocity. + const dt = 1.0e-5; // 0.864 seconds + const t1 = time.AddDays(-dt); + const t2 = time.AddDays(+dt); + const r1 = GeoMoon(t1); + const r2 = GeoMoon(t2); + return new StateVector((r1.x + r2.x) / 2, (r1.y + r2.y) / 2, (r1.z + r2.z) / 2, (r2.x - r1.x) / (2 * dt), (r2.y - r1.y) / (2 * dt), (r2.z - r1.z) / (2 * dt), time); +} +exports.GeoMoonState = GeoMoonState; +/** + * @brief Calculates the geocentric position and velocity of the Earth/Moon barycenter. + * + * Given a time of observation, calculates the geocentric position and velocity vectors + * of the Earth/Moon barycenter (EMB). + * The position (x, y, z) components are expressed in AU (astronomical units). + * The velocity (vx, vy, vz) components are expressed in AU/day. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the EMB's geocentric state. + * + * @returns {StateVector} + */ +function GeoEmbState(date) { + const time = MakeTime(date); + const s = GeoMoonState(time); + const d = 1.0 + EARTH_MOON_MASS_RATIO; + return new StateVector(s.x / d, s.y / d, s.z / d, s.vx / d, s.vy / d, s.vz / d, time); +} +exports.GeoEmbState = GeoEmbState; +function VsopFormula(formula, t, clamp_angle) { + let tpower = 1; + let coord = 0; + for (let series of formula) { + let sum = 0; + for (let [ampl, phas, freq] of series) + sum += ampl * Math.cos(phas + (t * freq)); + let incr = tpower * sum; + if (clamp_angle) + incr %= PI2; // improve precision for longitudes: they can be hundreds of radians + coord += incr; + tpower *= t; + } + return coord; +} +function VsopDeriv(formula, t) { + let tpower = 1; // t^s + let dpower = 0; // t^(s-1) + let deriv = 0; + let s = 0; + for (let series of formula) { + let sin_sum = 0; + let cos_sum = 0; + for (let [ampl, phas, freq] of series) { + let angle = phas + (t * freq); + sin_sum += ampl * freq * Math.sin(angle); + if (s > 0) + cos_sum += ampl * Math.cos(angle); + } + deriv += (s * dpower * cos_sum) - (tpower * sin_sum); + dpower = tpower; + tpower *= t; + ++s; + } + return deriv; +} +const DAYS_PER_MILLENNIUM = 365250; +const LON_INDEX = 0; +const LAT_INDEX = 1; +const RAD_INDEX = 2; +function VsopRotate(eclip) { + // Convert ecliptic cartesian coordinates to equatorial cartesian coordinates. + return new TerseVector(eclip[0] + 0.000000440360 * eclip[1] - 0.000000190919 * eclip[2], -0.000000479966 * eclip[0] + 0.917482137087 * eclip[1] - 0.397776982902 * eclip[2], 0.397776982902 * eclip[1] + 0.917482137087 * eclip[2]); +} +function VsopSphereToRect(lon, lat, radius) { + // Convert spherical coordinates to ecliptic cartesian coordinates. + const r_coslat = radius * Math.cos(lat); + const coslon = Math.cos(lon); + const sinlon = Math.sin(lon); + return [ + r_coslat * coslon, + r_coslat * sinlon, + radius * Math.sin(lat) + ]; +} +function CalcVsop(model, time) { + const t = time.tt / DAYS_PER_MILLENNIUM; // millennia since 2000 + const lon = VsopFormula(model[LON_INDEX], t, true); + const lat = VsopFormula(model[LAT_INDEX], t, false); + const rad = VsopFormula(model[RAD_INDEX], t, false); + const eclip = VsopSphereToRect(lon, lat, rad); + return VsopRotate(eclip).ToAstroVector(time); +} +function CalcVsopPosVel(model, tt) { + const t = tt / DAYS_PER_MILLENNIUM; + // Calculate the VSOP "B" trigonometric series to obtain ecliptic spherical coordinates. + const lon = VsopFormula(model[LON_INDEX], t, true); + const lat = VsopFormula(model[LAT_INDEX], t, false); + const rad = VsopFormula(model[RAD_INDEX], t, false); + const dlon_dt = VsopDeriv(model[LON_INDEX], t); + const dlat_dt = VsopDeriv(model[LAT_INDEX], t); + const drad_dt = VsopDeriv(model[RAD_INDEX], t); + // Use spherical coords and spherical derivatives to calculate + // the velocity vector in rectangular coordinates. + const coslon = Math.cos(lon); + const sinlon = Math.sin(lon); + const coslat = Math.cos(lat); + const sinlat = Math.sin(lat); + const vx = (+(drad_dt * coslat * coslon) + - (rad * sinlat * coslon * dlat_dt) + - (rad * coslat * sinlon * dlon_dt)); + const vy = (+(drad_dt * coslat * sinlon) + - (rad * sinlat * sinlon * dlat_dt) + + (rad * coslat * coslon * dlon_dt)); + const vz = (+(drad_dt * sinlat) + + (rad * coslat * dlat_dt)); + const eclip_pos = VsopSphereToRect(lon, lat, rad); + // Convert speed units from [AU/millennium] to [AU/day]. + const eclip_vel = [ + vx / DAYS_PER_MILLENNIUM, + vy / DAYS_PER_MILLENNIUM, + vz / DAYS_PER_MILLENNIUM + ]; + // Rotate the vectors from ecliptic to equatorial coordinates. + const equ_pos = VsopRotate(eclip_pos); + const equ_vel = VsopRotate(eclip_vel); + return new body_state_t(tt, equ_pos, equ_vel); +} +function AdjustBarycenter(ssb, time, body, pmass) { + const shift = pmass / (pmass + SUN_GM); + const planet = CalcVsop(vsop[body], time); + ssb.x += shift * planet.x; + ssb.y += shift * planet.y; + ssb.z += shift * planet.z; +} +function CalcSolarSystemBarycenter(time) { + const ssb = new Vector(0.0, 0.0, 0.0, time); + AdjustBarycenter(ssb, time, Body.Jupiter, JUPITER_GM); + AdjustBarycenter(ssb, time, Body.Saturn, SATURN_GM); + AdjustBarycenter(ssb, time, Body.Uranus, URANUS_GM); + AdjustBarycenter(ssb, time, Body.Neptune, NEPTUNE_GM); + return ssb; +} +// Pluto integrator begins ---------------------------------------------------- +const PLUTO_NUM_STATES = 51; +const PLUTO_TIME_STEP = 29200; +const PLUTO_DT = 146; +const PLUTO_NSTEPS = 201; +const PlutoStateTable = [ + [-730000.0, [-26.118207232108, -14.376168177825, 3.384402515299], [1.6339372163656e-03, -2.7861699588508e-03, -1.3585880229445e-03]], + [-700800.0, [41.974905202127, -0.448502952929, -12.770351505989], [7.3458569351457e-04, 2.2785014891658e-03, 4.8619778602049e-04]], + [-671600.0, [14.706930780744, 44.269110540027, 9.353698474772], [-2.1000147999800e-03, 2.2295915939915e-04, 7.0143443551414e-04]], + [-642400.0, [-29.441003929957, -6.430161530570, 6.858481011305], [8.4495803960544e-04, -3.0783914758711e-03, -1.2106305981192e-03]], + [-613200.0, [39.444396946234, -6.557989760571, -13.913760296463], [1.1480029005873e-03, 2.2400006880665e-03, 3.5168075922288e-04]], + [-584000.0, [20.230380950700, 43.266966657189, 7.382966091923], [-1.9754081700585e-03, 5.3457141292226e-04, 7.5929169129793e-04]], + [-554800.0, [-30.658325364620, 2.093818874552, 9.880531138071], [6.1010603013347e-05, -3.1326500935382e-03, -9.9346125151067e-04]], + [-525600.0, [35.737703251673, -12.587706024764, -14.677847247563], [1.5802939375649e-03, 2.1347678412429e-03, 1.9074436384343e-04]], + [-496400.0, [25.466295188546, 41.367478338417, 5.216476873382], [-1.8054401046468e-03, 8.3283083599510e-04, 8.0260156912107e-04]], + [-467200.0, [-29.847174904071, 10.636426313081, 12.297904180106], [-6.3257063052907e-04, -2.9969577578221e-03, -7.4476074151596e-04]], + [-438000.0, [30.774692107687, -18.236637015304, -14.945535879896], [2.0113162005465e-03, 1.9353827024189e-03, -2.0937793168297e-06]], + [-408800.0, [30.243153324028, 38.656267888503, 2.938501750218], [-1.6052508674468e-03, 1.1183495337525e-03, 8.3333973416824e-04]], + [-379600.0, [-27.288984772533, 18.643162147874, 14.023633623329], [-1.1856388898191e-03, -2.7170609282181e-03, -4.9015526126399e-04]], + [-350400.0, [24.519605196774, -23.245756064727, -14.626862367368], [2.4322321483154e-03, 1.6062008146048e-03, -2.3369181613312e-04]], + [-321200.0, [34.505274805875, 35.125338586954, 0.557361475637], [-1.3824391637782e-03, 1.3833397561817e-03, 8.4823598806262e-04]], + [-292000.0, [-23.275363915119, 25.818514298769, 15.055381588598], [-1.6062295460975e-03, -2.3395961498533e-03, -2.4377362639479e-04]], + [-262800.0, [17.050384798092, -27.180376290126, -13.608963321694], [2.8175521080578e-03, 1.1358749093955e-03, -4.9548725258825e-04]], + [-233600.0, [38.093671910285, 30.880588383337, -1.843688067413], [-1.1317697153459e-03, 1.6128814698472e-03, 8.4177586176055e-04]], + [-204400.0, [-18.197852930878, 31.932869934309, 15.438294826279], [-1.9117272501813e-03, -1.9146495909842e-03, -1.9657304369835e-05]], + [-175200.0, [8.528924039997, -29.618422200048, -11.805400994258], [3.1034370787005e-03, 5.1393633292430e-04, -7.7293066202546e-04]], + [-146000.0, [40.946857258640, 25.904973592021, -4.256336240499], [-8.3652705194051e-04, 1.8129497136404e-03, 8.1564228273060e-04]], + [-116800.0, [-12.326958895325, 36.881883446292, 15.217158258711], [-2.1166103705038e-03, -1.4814420035990e-03, 1.7401209844705e-04]], + [-87600.0, [-0.633258375909, -30.018759794709, -9.171932874950], [3.2016994581737e-03, -2.5279858672148e-04, -1.0411088271861e-03]], + [-58400.0, [42.936048423883, 20.344685584452, -6.588027007912], [-5.0525450073192e-04, 1.9910074335507e-03, 7.7440196540269e-04]], + [-29200.0, [-5.975910552974, 40.611809958460, 14.470131723673], [-2.2184202156107e-03, -1.0562361130164e-03, 3.3652250216211e-04]], + [0.0, [-9.875369580774, -27.978926224737, -5.753711824704], [3.0287533248818e-03, -1.1276087003636e-03, -1.2651326732361e-03]], + [29200.0, [43.958831986165, 14.214147973292, -8.808306227163], [-1.4717608981871e-04, 2.1404187242141e-03, 7.1486567806614e-04]], + [58400.0, [0.678136763520, 43.094461639362, 13.243238780721], [-2.2358226110718e-03, -6.3233636090933e-04, 4.7664798895648e-04]], + [87600.0, [-18.282602096834, -23.305039586660, -1.766620508028], [2.5567245263557e-03, -1.9902940754171e-03, -1.3943491701082e-03]], + [116800.0, [43.873338744526, 7.700705617215, -10.814273666425], [2.3174803055677e-04, 2.2402163127924e-03, 6.2988756452032e-04]], + [146000.0, [7.392949027906, 44.382678951534, 11.629500214854], [-2.1932815453830e-03, -2.1751799585364e-04, 5.9556516201114e-04]], + [175200.0, [-24.981690229261, -16.204012851426, 2.466457544298], [1.8193989149580e-03, -2.6765419531201e-03, -1.3848283502247e-03]], + [204400.0, [42.530187039511, 0.845935508021, -12.554907527683], [6.5059779150669e-04, 2.2725657282262e-03, 5.1133743202822e-04]], + [233600.0, [13.999526486822, 44.462363044894, 9.669418486465], [-2.1079296569252e-03, 1.7533423831993e-04, 6.9128485798076e-04]], + [262800.0, [-29.184024803031, -7.371243995762, 6.493275957928], [9.3581363109681e-04, -3.0610357109184e-03, -1.2364201089345e-03]], + [292000.0, [39.831980671753, -6.078405766765, -13.909815358656], [1.1117769689167e-03, 2.2362097830152e-03, 3.6230548231153e-04]], + [321200.0, [20.294955108476, 43.417190420251, 7.450091985932], [-1.9742157451535e-03, 5.3102050468554e-04, 7.5938408813008e-04]], + [350400.0, [-30.669992302160, 2.318743558955, 9.973480913858], [4.5605107450676e-05, -3.1308219926928e-03, -9.9066533301924e-04]], + [379600.0, [35.626122155983, -12.897647509224, -14.777586508444], [1.6015684949743e-03, 2.1171931182284e-03, 1.8002516202204e-04]], + [408800.0, [26.133186148561, 41.232139187599, 5.006401326220], [-1.7857704419579e-03, 8.6046232702817e-04, 8.0614690298954e-04]], + [438000.0, [-29.576740229230, 11.863535943587, 12.631323039872], [-7.2292830060955e-04, -2.9587820140709e-03, -7.0824296450300e-04]], + [467200.0, [29.910805787391, -19.159019294000, -15.013363865194], [2.0871080437997e-03, 1.8848372554514e-03, -3.8528655083926e-05]], + [496400.0, [31.375957451819, 38.050372720763, 2.433138343754], [-1.5546055556611e-03, 1.1699815465629e-03, 8.3565439266001e-04]], + [525600.0, [-26.360071336928, 20.662505904952, 14.414696258958], [-1.3142373118349e-03, -2.6236647854842e-03, -4.2542017598193e-04]], + [554800.0, [22.599441488648, -24.508879898306, -14.484045731468], [2.5454108304806e-03, 1.4917058755191e-03, -3.0243665086079e-04]], + [584000.0, [35.877864013014, 33.894226366071, -0.224524636277], [-1.2941245730845e-03, 1.4560427668319e-03, 8.4762160640137e-04]], + [613200.0, [-21.538149762417, 28.204068269761, 15.321973799534], [-1.7312117409010e-03, -2.1939631314577e-03, -1.6316913275180e-04]], + [642400.0, [13.971521374415, -28.339941764789, -13.083792871886], [2.9334630526035e-03, 9.1860931752944e-04, -5.9939422488627e-04]], + [671600.0, [39.526942044143, 28.939897360110, -2.872799527539], [-1.0068481658095e-03, 1.7021132888090e-03, 8.3578230511981e-04]], + [700800.0, [-15.576200701394, 34.399412961275, 15.466033737854], [-2.0098814612884e-03, -1.7191109825989e-03, 7.0414782780416e-05]], + [730000.0, [4.243252837090, -30.118201690825, -10.707441231349], [3.1725847067411e-03, 1.6098461202270e-04, -9.0672150593868e-04]] +]; +class TerseVector { + constructor(x, y, z) { + this.x = x; + this.y = y; + this.z = z; + } + clone() { + return new TerseVector(this.x, this.y, this.z); + } + ToAstroVector(t) { + return new Vector(this.x, this.y, this.z, t); + } + static zero() { + return new TerseVector(0, 0, 0); + } + quadrature() { + return this.x * this.x + this.y * this.y + this.z * this.z; + } + add(other) { + return new TerseVector(this.x + other.x, this.y + other.y, this.z + other.z); + } + sub(other) { + return new TerseVector(this.x - other.x, this.y - other.y, this.z - other.z); + } + incr(other) { + this.x += other.x; + this.y += other.y; + this.z += other.z; + } + decr(other) { + this.x -= other.x; + this.y -= other.y; + this.z -= other.z; + } + mul(scalar) { + return new TerseVector(scalar * this.x, scalar * this.y, scalar * this.z); + } + div(scalar) { + return new TerseVector(this.x / scalar, this.y / scalar, this.z / scalar); + } + mean(other) { + return new TerseVector((this.x + other.x) / 2, (this.y + other.y) / 2, (this.z + other.z) / 2); + } + neg() { + return new TerseVector(-this.x, -this.y, -this.z); + } +} +class body_state_t { + constructor(tt, r, v) { + this.tt = tt; + this.r = r; + this.v = v; + } + clone() { + return new body_state_t(this.tt, this.r, this.v); + } + sub(other) { + return new body_state_t(this.tt, this.r.sub(other.r), this.v.sub(other.v)); + } +} +function BodyStateFromTable(entry) { + let [tt, [rx, ry, rz], [vx, vy, vz]] = entry; + return new body_state_t(tt, new TerseVector(rx, ry, rz), new TerseVector(vx, vy, vz)); +} +function AdjustBarycenterPosVel(ssb, tt, body, planet_gm) { + const shift = planet_gm / (planet_gm + SUN_GM); + const planet = CalcVsopPosVel(vsop[body], tt); + ssb.r.incr(planet.r.mul(shift)); + ssb.v.incr(planet.v.mul(shift)); + return planet; +} +function AccelerationIncrement(small_pos, gm, major_pos) { + const delta = major_pos.sub(small_pos); + const r2 = delta.quadrature(); + return delta.mul(gm / (r2 * Math.sqrt(r2))); +} +class major_bodies_t { + constructor(tt) { + // Accumulate the Solar System Barycenter position. + let ssb = new body_state_t(tt, new TerseVector(0, 0, 0), new TerseVector(0, 0, 0)); + this.Jupiter = AdjustBarycenterPosVel(ssb, tt, Body.Jupiter, JUPITER_GM); + this.Saturn = AdjustBarycenterPosVel(ssb, tt, Body.Saturn, SATURN_GM); + this.Uranus = AdjustBarycenterPosVel(ssb, tt, Body.Uranus, URANUS_GM); + this.Neptune = AdjustBarycenterPosVel(ssb, tt, Body.Neptune, NEPTUNE_GM); + // Convert planets' [pos, vel] vectors from heliocentric to barycentric. + this.Jupiter.r.decr(ssb.r); + this.Jupiter.v.decr(ssb.v); + this.Saturn.r.decr(ssb.r); + this.Saturn.v.decr(ssb.v); + this.Uranus.r.decr(ssb.r); + this.Uranus.v.decr(ssb.v); + this.Neptune.r.decr(ssb.r); + this.Neptune.v.decr(ssb.v); + // Convert heliocentric SSB to barycentric Sun. + this.Sun = new body_state_t(tt, ssb.r.mul(-1), ssb.v.mul(-1)); + } + Acceleration(pos) { + // Use barycentric coordinates of the Sun and major planets to calculate + // the gravitational acceleration vector experienced at location 'pos'. + let acc = AccelerationIncrement(pos, SUN_GM, this.Sun.r); + acc.incr(AccelerationIncrement(pos, JUPITER_GM, this.Jupiter.r)); + acc.incr(AccelerationIncrement(pos, SATURN_GM, this.Saturn.r)); + acc.incr(AccelerationIncrement(pos, URANUS_GM, this.Uranus.r)); + acc.incr(AccelerationIncrement(pos, NEPTUNE_GM, this.Neptune.r)); + return acc; + } +} +/** + * @ignore + * + * @brief The state of a body at an incremental step in a gravity simulation. + * + * This is an internal data structure used to represent the + * position, velocity, and acceleration vectors of a body + * in a gravity simulation at a given moment in time. + * + * @property tt + * The J2000 terrestrial time of the state [days]. + * + * @property r + * The position vector [au]. + * + * @property v + * The velocity vector [au/day]. + * + * @property a + * The acceleration vector [au/day^2]. + */ +class body_grav_calc_t { + constructor(tt, r, v, a) { + this.tt = tt; + this.r = r; + this.v = v; + this.a = a; + } + clone() { + return new body_grav_calc_t(this.tt, this.r.clone(), this.v.clone(), this.a.clone()); + } +} +class grav_sim_t { + constructor(bary, grav) { + this.bary = bary; + this.grav = grav; + } +} +function UpdatePosition(dt, r, v, a) { + return new TerseVector(r.x + dt * (v.x + dt * a.x / 2), r.y + dt * (v.y + dt * a.y / 2), r.z + dt * (v.z + dt * a.z / 2)); +} +function UpdateVelocity(dt, v, a) { + return new TerseVector(v.x + dt * a.x, v.y + dt * a.y, v.z + dt * a.z); +} +function GravSim(tt2, calc1) { + const dt = tt2 - calc1.tt; + // Calculate where the major bodies (Sun, Jupiter...Neptune) will be at tt2. + const bary2 = new major_bodies_t(tt2); + // Estimate position of small body as if current acceleration applies across the whole time interval. + const approx_pos = UpdatePosition(dt, calc1.r, calc1.v, calc1.a); + // Calculate the average acceleration of the endpoints. + // This becomes our estimate of the mean effective acceleration over the whole interval. + const mean_acc = bary2.Acceleration(approx_pos).mean(calc1.a); + // Refine the estimates of [pos, vel, acc] at tt2 using the mean acceleration. + const pos = UpdatePosition(dt, calc1.r, calc1.v, mean_acc); + const vel = calc1.v.add(mean_acc.mul(dt)); + const acc = bary2.Acceleration(pos); + const grav = new body_grav_calc_t(tt2, pos, vel, acc); + return new grav_sim_t(bary2, grav); +} +const pluto_cache = []; +function ClampIndex(frac, nsteps) { + const index = Math.floor(frac); + if (index < 0) + return 0; + if (index >= nsteps) + return nsteps - 1; + return index; +} +function GravFromState(entry) { + const state = BodyStateFromTable(entry); + const bary = new major_bodies_t(state.tt); + const r = state.r.add(bary.Sun.r); + const v = state.v.add(bary.Sun.v); + const a = bary.Acceleration(r); + const grav = new body_grav_calc_t(state.tt, r, v, a); + return new grav_sim_t(bary, grav); +} +function GetSegment(cache, tt) { + const t0 = PlutoStateTable[0][0]; + if (tt < t0 || tt > PlutoStateTable[PLUTO_NUM_STATES - 1][0]) { + // Don't bother calculating a segment. Let the caller crawl backward/forward to this time. + return null; + } + const seg_index = ClampIndex((tt - t0) / PLUTO_TIME_STEP, PLUTO_NUM_STATES - 1); + if (!cache[seg_index]) { + const seg = cache[seg_index] = []; + // Each endpoint is exact. + seg[0] = GravFromState(PlutoStateTable[seg_index]).grav; + seg[PLUTO_NSTEPS - 1] = GravFromState(PlutoStateTable[seg_index + 1]).grav; + // Simulate forwards from the lower time bound. + let i; + let step_tt = seg[0].tt; + for (i = 1; i < PLUTO_NSTEPS - 1; ++i) + seg[i] = GravSim(step_tt += PLUTO_DT, seg[i - 1]).grav; + // Simulate backwards from the upper time bound. + step_tt = seg[PLUTO_NSTEPS - 1].tt; + var reverse = []; + reverse[PLUTO_NSTEPS - 1] = seg[PLUTO_NSTEPS - 1]; + for (i = PLUTO_NSTEPS - 2; i > 0; --i) + reverse[i] = GravSim(step_tt -= PLUTO_DT, reverse[i + 1]).grav; + // Fade-mix the two series so that there are no discontinuities. + for (i = PLUTO_NSTEPS - 2; i > 0; --i) { + const ramp = i / (PLUTO_NSTEPS - 1); + seg[i].r = seg[i].r.mul(1 - ramp).add(reverse[i].r.mul(ramp)); + seg[i].v = seg[i].v.mul(1 - ramp).add(reverse[i].v.mul(ramp)); + seg[i].a = seg[i].a.mul(1 - ramp).add(reverse[i].a.mul(ramp)); + } + } + return cache[seg_index]; +} +function CalcPlutoOneWay(entry, target_tt, dt) { + let sim = GravFromState(entry); + const n = Math.ceil((target_tt - sim.grav.tt) / dt); + for (let i = 0; i < n; ++i) + sim = GravSim((i + 1 === n) ? target_tt : (sim.grav.tt + dt), sim.grav); + return sim; +} +function CalcPluto(time, helio) { + let r, v, bary; + const seg = GetSegment(pluto_cache, time.tt); + if (!seg) { + // The target time is outside the year range 0000..4000. + // Calculate it by crawling backward from 0000 or forward from 4000. + // FIXFIXFIX - This is super slow. Could optimize this with extra caching if needed. + let sim; + if (time.tt < PlutoStateTable[0][0]) + sim = CalcPlutoOneWay(PlutoStateTable[0], time.tt, -PLUTO_DT); + else + sim = CalcPlutoOneWay(PlutoStateTable[PLUTO_NUM_STATES - 1], time.tt, +PLUTO_DT); + r = sim.grav.r; + v = sim.grav.v; + bary = sim.bary; + } + else { + const left = ClampIndex((time.tt - seg[0].tt) / PLUTO_DT, PLUTO_NSTEPS - 1); + const s1 = seg[left]; + const s2 = seg[left + 1]; + // Find mean acceleration vector over the interval. + const acc = s1.a.mean(s2.a); + // Use Newtonian mechanics to extrapolate away from t1 in the positive time direction. + const ra = UpdatePosition(time.tt - s1.tt, s1.r, s1.v, acc); + const va = UpdateVelocity(time.tt - s1.tt, s1.v, acc); + // Use Newtonian mechanics to extrapolate away from t2 in the negative time direction. + const rb = UpdatePosition(time.tt - s2.tt, s2.r, s2.v, acc); + const vb = UpdateVelocity(time.tt - s2.tt, s2.v, acc); + // Use fade in/out idea to blend the two position estimates. + const ramp = (time.tt - s1.tt) / PLUTO_DT; + r = ra.mul(1 - ramp).add(rb.mul(ramp)); + v = va.mul(1 - ramp).add(vb.mul(ramp)); + } + if (helio) { + // Convert barycentric vectors to heliocentric vectors. + if (!bary) + bary = new major_bodies_t(time.tt); + r = r.sub(bary.Sun.r); + v = v.sub(bary.Sun.v); + } + return new StateVector(r.x, r.y, r.z, v.x, v.y, v.z, time); +} +; +const Rotation_JUP_EQJ = new RotationMatrix([ + [9.99432765338654e-01, -3.36771074697641e-02, 0.00000000000000e+00], + [3.03959428906285e-02, 9.02057912352809e-01, 4.30543388542295e-01], + [-1.44994559663353e-02, -4.30299169409101e-01, 9.02569881273754e-01] +]); +const JupiterMoonModel = [ + // [0] Io + { + mu: 2.8248942843381399e-07, + al: [1.4462132960212239e+00, 3.5515522861824000e+00], + a: [ + [0.0028210960212903, 0.0000000000000000e+00, 0.0000000000000000e+00] + ], + l: [ + [-0.0001925258348666, 4.9369589722644998e+00, 1.3584836583050000e-02], + [-0.0000970803596076, 4.3188796477322002e+00, 1.3034138432430000e-02], + [-0.0000898817416500, 1.9080016428616999e+00, 3.0506486715799999e-03], + [-0.0000553101050262, 1.4936156681568999e+00, 1.2938928911549999e-02] + ], + z: [ + [0.0041510849668155, 4.0899396355450000e+00, -1.2906864146660001e-02], + [0.0006260521444113, 1.4461888986270000e+00, 3.5515522949801999e+00], + [0.0000352747346169, 2.1256287034577999e+00, 1.2727416566999999e-04] + ], + zeta: [ + [0.0003142172466014, 2.7964219722923001e+00, -2.3150960980000000e-03], + [0.0000904169207946, 1.0477061879627001e+00, -5.6920638196000003e-04] + ] + }, + // [1] Europa + { + mu: 2.8248327439289299e-07, + al: [-3.7352634374713622e-01, 1.7693227111234699e+00], + a: [ + [0.0044871037804314, 0.0000000000000000e+00, 0.0000000000000000e+00], + [0.0000004324367498, 1.8196456062910000e+00, 1.7822295777568000e+00] + ], + l: [ + [0.0008576433172936, 4.3188693178264002e+00, 1.3034138308049999e-02], + [0.0004549582875086, 1.4936531751079001e+00, 1.2938928819619999e-02], + [0.0003248939825174, 1.8196494533458001e+00, 1.7822295777568000e+00], + [-0.0003074250079334, 4.9377037005910998e+00, 1.3584832867240000e-02], + [0.0001982386144784, 1.9079869054759999e+00, 3.0510121286900001e-03], + [0.0001834063551804, 2.1402853388529000e+00, 1.4500978933800000e-03], + [-0.0001434383188452, 5.6222140366630002e+00, 8.9111478887838003e-01], + [-0.0000771939140944, 4.3002724372349999e+00, 2.6733443704265998e+00] + ], + z: [ + [-0.0093589104136341, 4.0899396509038999e+00, -1.2906864146660001e-02], + [0.0002988994545555, 5.9097265185595003e+00, 1.7693227079461999e+00], + [0.0002139036390350, 2.1256289300016000e+00, 1.2727418406999999e-04], + [0.0001980963564781, 2.7435168292649998e+00, 6.7797343008999997e-04], + [0.0001210388158965, 5.5839943711203004e+00, 3.2056614899999997e-05], + [0.0000837042048393, 1.6094538368039000e+00, -9.0402165808846002e-01], + [0.0000823525166369, 1.4461887708689001e+00, 3.5515522949801999e+00] + ], + zeta: [ + [0.0040404917832303, 1.0477063169425000e+00, -5.6920640539999997e-04], + [0.0002200421034564, 3.3368857864364001e+00, -1.2491307306999999e-04], + [0.0001662544744719, 2.4134862374710999e+00, 0.0000000000000000e+00], + [0.0000590282470983, 5.9719930968366004e+00, -3.0561602250000000e-05] + ] + }, + // [2] Ganymede + { + mu: 2.8249818418472298e-07, + al: [2.8740893911433479e-01, 8.7820792358932798e-01], + a: [ + [0.0071566594572575, 0.0000000000000000e+00, 0.0000000000000000e+00], + [0.0000013930299110, 1.1586745884981000e+00, 2.6733443704265998e+00] + ], + l: [ + [0.0002310797886226, 2.1402987195941998e+00, 1.4500978438400001e-03], + [-0.0001828635964118, 4.3188672736968003e+00, 1.3034138282630000e-02], + [0.0001512378778204, 4.9373102372298003e+00, 1.3584834812520000e-02], + [-0.0001163720969778, 4.3002659861490002e+00, 2.6733443704265998e+00], + [-0.0000955478069846, 1.4936612842567001e+00, 1.2938928798570001e-02], + [0.0000815246854464, 5.6222137132535002e+00, 8.9111478887838003e-01], + [-0.0000801219679602, 1.2995922951532000e+00, 1.0034433456728999e+00], + [-0.0000607017260182, 6.4978769669238001e-01, 5.0172167043264004e-01] + ], + z: [ + [0.0014289811307319, 2.1256295942738999e+00, 1.2727413029000001e-04], + [0.0007710931226760, 5.5836330003496002e+00, 3.2064341100000001e-05], + [0.0005925911780766, 4.0899396636447998e+00, -1.2906864146660001e-02], + [0.0002045597496146, 5.2713683670371996e+00, -1.2523544076106000e-01], + [0.0001785118648258, 2.8743156721063001e-01, 8.7820792442520001e-01], + [0.0001131999784893, 1.4462127277818000e+00, 3.5515522949801999e+00], + [-0.0000658778169210, 2.2702423990985001e+00, -1.7951364394536999e+00], + [0.0000497058888328, 5.9096792204858000e+00, 1.7693227129285001e+00] + ], + zeta: [ + [0.0015932721570848, 3.3368862796665000e+00, -1.2491307058000000e-04], + [0.0008533093128905, 2.4133881688166001e+00, 0.0000000000000000e+00], + [0.0003513347911037, 5.9720789850126996e+00, -3.0561017709999999e-05], + [-0.0001441929255483, 1.0477061764435001e+00, -5.6920632124000004e-04] + ] + }, + // [3] Callisto + { + mu: 2.8249214488990899e-07, + al: [-3.6203412913757038e-01, 3.7648623343382798e-01], + a: [ + [0.0125879701715314, 0.0000000000000000e+00, 0.0000000000000000e+00], + [0.0000035952049470, 6.4965776007116005e-01, 5.0172168165034003e-01], + [0.0000027580210652, 1.8084235781510001e+00, 3.1750660413359002e+00] + ], + l: [ + [0.0005586040123824, 2.1404207189814999e+00, 1.4500979323100001e-03], + [-0.0003805813868176, 2.7358844897852999e+00, 2.9729650620000000e-05], + [0.0002205152863262, 6.4979652596399995e-01, 5.0172167243580001e-01], + [0.0001877895151158, 1.8084787604004999e+00, 3.1750660413359002e+00], + [0.0000766916975242, 6.2720114319754998e+00, 1.3928364636651001e+00], + [0.0000747056855106, 1.2995916202344000e+00, 1.0034433456728999e+00] + ], + z: [ + [0.0073755808467977, 5.5836071576083999e+00, 3.2065099140000001e-05], + [0.0002065924169942, 5.9209831565786004e+00, 3.7648624194703001e-01], + [0.0001589869764021, 2.8744006242622999e-01, 8.7820792442520001e-01], + [-0.0001561131605348, 2.1257397865089001e+00, 1.2727441285000001e-04], + [0.0001486043380971, 1.4462134301023000e+00, 3.5515522949801999e+00], + [0.0000635073108731, 5.9096803285953996e+00, 1.7693227129285001e+00], + [0.0000599351698525, 4.1125517584797997e+00, -2.7985797954588998e+00], + [0.0000540660842731, 5.5390350845569003e+00, 2.8683408228299999e-03], + [-0.0000489596900866, 4.6218149483337996e+00, -6.2695712529518999e-01] + ], + zeta: [ + [0.0038422977898495, 2.4133922085556998e+00, 0.0000000000000000e+00], + [0.0022453891791894, 5.9721736773277003e+00, -3.0561255249999997e-05], + [-0.0002604479450559, 3.3368746306408998e+00, -1.2491309972000001e-04], + [0.0000332112143230, 5.5604137742336999e+00, 2.9003768850700000e-03] + ] + } +]; +/** + * @brief Holds the positions and velocities of Jupiter's major 4 moons. + * + * The {@link JupiterMoons} function returns an object of this type + * to report position and velocity vectors for Jupiter's largest 4 moons + * Io, Europa, Ganymede, and Callisto. Each position vector is relative + * to the center of Jupiter. Both position and velocity are oriented in + * the EQJ system (that is, using Earth's equator at the J2000 epoch). + * The positions are expressed in astronomical units (AU), + * and the velocities in AU/day. + * + * @property {StateVector} io + * The position and velocity of Jupiter's moon Io. + * + * @property {StateVector} europa + * The position and velocity of Jupiter's moon Europa. + * + * @property {StateVector} ganymede + * The position and velocity of Jupiter's moon Ganymede. + * + * @property {StateVector} callisto + * The position and velocity of Jupiter's moon Callisto. + */ +class JupiterMoonsInfo { + constructor(io, europa, ganymede, callisto) { + this.io = io; + this.europa = europa; + this.ganymede = ganymede; + this.callisto = callisto; + } +} +exports.JupiterMoonsInfo = JupiterMoonsInfo; +function JupiterMoon_elem2pv(time, mu, elem) { + // Translation of FORTRAN subroutine ELEM2PV from: + // https://ftp.imcce.fr/pub/ephem/satel/galilean/L1/L1.2/ + const A = elem[0]; + const AL = elem[1]; + const K = elem[2]; + const H = elem[3]; + const Q = elem[4]; + const P = elem[5]; + const AN = Math.sqrt(mu / (A * A * A)); + let CE, SE, DE; + let EE = AL + K * Math.sin(AL) - H * Math.cos(AL); + do { + CE = Math.cos(EE); + SE = Math.sin(EE); + DE = (AL - EE + K * SE - H * CE) / (1.0 - K * CE - H * SE); + EE += DE; + } while (Math.abs(DE) >= 1.0e-12); + CE = Math.cos(EE); + SE = Math.sin(EE); + const DLE = H * CE - K * SE; + const RSAM1 = -K * CE - H * SE; + const ASR = 1.0 / (1.0 + RSAM1); + const PHI = Math.sqrt(1.0 - K * K - H * H); + const PSI = 1.0 / (1.0 + PHI); + const X1 = A * (CE - K - PSI * H * DLE); + const Y1 = A * (SE - H + PSI * K * DLE); + const VX1 = AN * ASR * A * (-SE - PSI * H * RSAM1); + const VY1 = AN * ASR * A * (+CE + PSI * K * RSAM1); + const F2 = 2.0 * Math.sqrt(1.0 - Q * Q - P * P); + const P2 = 1.0 - 2.0 * P * P; + const Q2 = 1.0 - 2.0 * Q * Q; + const PQ = 2.0 * P * Q; + return new StateVector(X1 * P2 + Y1 * PQ, X1 * PQ + Y1 * Q2, (Q * Y1 - X1 * P) * F2, VX1 * P2 + VY1 * PQ, VX1 * PQ + VY1 * Q2, (Q * VY1 - VX1 * P) * F2, time); +} +function CalcJupiterMoon(time, m) { + // This is a translation of FORTRAN code by Duriez, Lainey, and Vienne: + // https://ftp.imcce.fr/pub/ephem/satel/galilean/L1/L1.2/ + const t = time.tt + 18262.5; // number of days since 1950-01-01T00:00:00Z + // Calculate 6 orbital elements at the given time t + const elem = [0, m.al[0] + (t * m.al[1]), 0, 0, 0, 0]; + for (let [amplitude, phase, frequency] of m.a) + elem[0] += amplitude * Math.cos(phase + (t * frequency)); + for (let [amplitude, phase, frequency] of m.l) + elem[1] += amplitude * Math.sin(phase + (t * frequency)); + elem[1] %= PI2; + if (elem[1] < 0) + elem[1] += PI2; + for (let [amplitude, phase, frequency] of m.z) { + const arg = phase + (t * frequency); + elem[2] += amplitude * Math.cos(arg); + elem[3] += amplitude * Math.sin(arg); + } + for (let [amplitude, phase, frequency] of m.zeta) { + const arg = phase + (t * frequency); + elem[4] += amplitude * Math.cos(arg); + elem[5] += amplitude * Math.sin(arg); + } + // Convert the oribital elements into position vectors in the Jupiter equatorial system (JUP). + const state = JupiterMoon_elem2pv(time, m.mu, elem); + // Re-orient position and velocity vectors from Jupiter-equatorial (JUP) to Earth-equatorial in J2000 (EQJ). + return RotateState(Rotation_JUP_EQJ, state); +} +/** + * @brief Calculates jovicentric positions and velocities of Jupiter's largest 4 moons. + * + * Calculates position and velocity vectors for Jupiter's moons + * Io, Europa, Ganymede, and Callisto, at the given date and time. + * The vectors are jovicentric (relative to the center of Jupiter). + * Their orientation is the Earth's equatorial system at the J2000 epoch (EQJ). + * The position components are expressed in astronomical units (AU), and the + * velocity components are in AU/day. + * + * To convert to heliocentric vectors, call {@link HelioVector} + * with `Astronomy.Body.Jupiter` to get Jupiter's heliocentric position, then + * add the jovicentric vectors. Likewise, you can call {@link GeoVector} + * to convert to geocentric vectors. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate Jupiter's moons. + * + * @return {JupiterMoonsInfo} + * Position and velocity vectors of Jupiter's largest 4 moons. + */ +function JupiterMoons(date) { + const time = new AstroTime(date); + return new JupiterMoonsInfo(CalcJupiterMoon(time, JupiterMoonModel[0]), CalcJupiterMoon(time, JupiterMoonModel[1]), CalcJupiterMoon(time, JupiterMoonModel[2]), CalcJupiterMoon(time, JupiterMoonModel[3])); +} +exports.JupiterMoons = JupiterMoons; +// Jupiter Moons ends -------------------------------------------------------- +/** + * @brief Calculates a vector from the center of the Sun to the given body at the given time. + * + * Calculates heliocentric (i.e., with respect to the center of the Sun) + * Cartesian coordinates in the J2000 equatorial system of a celestial + * body at a specified time. The position is not corrected for light travel time or aberration. + * + * @param {Body} body + * One of the following values: + * `Body.Sun`, `Body.Moon`, `Body.Mercury`, `Body.Venus`, + * `Body.Earth`, `Body.Mars`, `Body.Jupiter`, `Body.Saturn`, + * `Body.Uranus`, `Body.Neptune`, `Body.Pluto`, + * `Body.SSB`, or `Body.EMB`. + * Also allowed to be a user-defined star created by {@link DefineStar}. + * + * @param {FlexibleDateTime} date + * The date and time for which the body's position is to be calculated. + * + * @returns {Vector} + */ +function HelioVector(body, date) { + var time = MakeTime(date); + if (body in vsop) + return CalcVsop(vsop[body], time); + if (body === Body.Pluto) { + const p = CalcPluto(time, true); + return new Vector(p.x, p.y, p.z, time); + } + if (body === Body.Sun) + return new Vector(0, 0, 0, time); + if (body === Body.Moon) { + var e = CalcVsop(vsop.Earth, time); + var m = GeoMoon(time); + return new Vector(e.x + m.x, e.y + m.y, e.z + m.z, time); + } + if (body === Body.EMB) { + const e = CalcVsop(vsop.Earth, time); + const m = GeoMoon(time); + const denom = 1.0 + EARTH_MOON_MASS_RATIO; + return new Vector(e.x + (m.x / denom), e.y + (m.y / denom), e.z + (m.z / denom), time); + } + if (body === Body.SSB) + return CalcSolarSystemBarycenter(time); + const star = UserDefinedStar(body); + if (star) { + const sphere = new Spherical(star.dec, 15 * star.ra, star.dist); + return VectorFromSphere(sphere, time); + } + throw `HelioVector: Unknown body "${body}"`; +} +exports.HelioVector = HelioVector; +; +/** + * @brief Calculates the distance between a body and the Sun at a given time. + * + * Given a date and time, this function calculates the distance between + * the center of `body` and the center of the Sun. + * For the planets Mercury through Neptune, this function is significantly + * more efficient than calling {@link HelioVector} followed by taking the length + * of the resulting vector. + * + * @param {Body} body + * A body for which to calculate a heliocentric distance: + * the Sun, Moon, any of the planets, or a user-defined star. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the heliocentric distance. + * + * @returns {number} + * The heliocentric distance in AU. + */ +function HelioDistance(body, date) { + const star = UserDefinedStar(body); + if (star) + return star.dist; + const time = MakeTime(date); + if (body in vsop) + return VsopFormula(vsop[body][RAD_INDEX], time.tt / DAYS_PER_MILLENNIUM, false); + return HelioVector(body, time).Length(); +} +exports.HelioDistance = HelioDistance; +/** + * Solve for light travel time of a vector function. + * + * When observing a distant object, for example Jupiter as seen from Earth, + * the amount of time it takes for light to travel from the object to the + * observer can significantly affect the object's apparent position. + * This function is a generic solver that figures out how long in the + * past light must have left the observed object to reach the observer + * at the specified observation time. It requires passing in `func` + * to express an arbitrary position vector as a function of time. + * + * `CorrectLightTravel` repeatedly calls `func`, passing a series of time + * estimates in the past. Then `func` must return a relative position vector between + * the observer and the target. `CorrectLightTravel` keeps calling + * `func` with more and more refined estimates of the time light must have + * left the target to arrive at the observer. + * + * For common use cases, it is simpler to use {@link BackdatePosition} + * for calculating the light travel time correction of one body observing another body. + * + * For geocentric calculations, {@link GeoVector} also backdates the returned + * position vector for light travel time, only it returns the observation time in + * the returned vector's `t` field rather than the backdated time. + * + * @param {function(AstroTime): number} func + * An arbitrary position vector as a function of time: + * function({@link AstroTime}) => {@link Vector}. + * + * @param {AstroTime} time + * The observation time for which to solve for light travel delay. + * + * @returns {AstroVector} + * The position vector at the solved backdated time. + * The `t` field holds the time that light left the observed + * body to arrive at the observer at the observation time. + */ +function CorrectLightTravel(func, time) { + let ltime = time; + let dt = 0; + for (let iter = 0; iter < 10; ++iter) { + const pos = func(ltime); + const lt = pos.Length() / exports.C_AUDAY; + // This solver does not support more than one light-day of distance, + // because that would cause convergence problems and inaccurate + // values for stellar aberration angles. + if (lt > 1.0) + throw `Object is too distant for light-travel solver.`; + const ltime2 = time.AddDays(-lt); + dt = Math.abs(ltime2.tt - ltime.tt); + if (dt < 1.0e-9) // 86.4 microseconds + return pos; + ltime = ltime2; + } + throw `Light-travel time solver did not converge: dt = ${dt}`; +} +exports.CorrectLightTravel = CorrectLightTravel; +class BodyPosition { + constructor(observerBody, targetBody, aberration, observerPos) { + this.observerBody = observerBody; + this.targetBody = targetBody; + this.aberration = aberration; + this.observerPos = observerPos; + } + Position(time) { + if (this.aberration) { + // The following discussion is worded with the observer body being the Earth, + // which is often the case. However, the same reasoning applies to any observer body + // without loss of generality. + // + // To include aberration, make a good first-order approximation + // by backdating the Earth's position also. + // This is confusing, but it works for objects within the Solar System + // because the distance the Earth moves in that small amount of light + // travel time (a few minutes to a few hours) is well approximated + // by a line segment that substends the angle seen from the remote + // body viewing Earth. That angle is pretty close to the aberration + // angle of the moving Earth viewing the remote body. + // In other words, both of the following approximate the aberration angle: + // (transverse distance Earth moves) / (distance to body) + // (transverse speed of Earth) / (speed of light). + this.observerPos = HelioVector(this.observerBody, time); + } + else { + // No aberration, so use the pre-calculated initial position of + // the observer body that is already stored in `observerPos`. + } + const targetPos = HelioVector(this.targetBody, time); + return new Vector(targetPos.x - this.observerPos.x, targetPos.y - this.observerPos.y, targetPos.z - this.observerPos.z, time); + } +} +/** + * @brief Solve for light travel time correction of apparent position. + * + * When observing a distant object, for example Jupiter as seen from Earth, + * the amount of time it takes for light to travel from the object to the + * observer can significantly affect the object's apparent position. + * + * This function solves the light travel time correction for the apparent + * relative position vector of a target body as seen by an observer body + * at a given observation time. + * + * For geocentric calculations, {@link GeoVector} also includes light + * travel time correction, but the time `t` embedded in its returned vector + * refers to the observation time, not the backdated time that light left + * the observed body. Thus `BackdatePosition` provides direct + * access to the light departure time for callers that need it. + * + * For a more generalized light travel correction solver, see {@link CorrectLightTravel}. + * + * @param {FlexibleDateTime} date + * The time of observation. + * + * @param {Body} observerBody + * The body to be used as the observation location. + * + * @param {Body} targetBody + * The body to be observed. + * + * @param {boolean} aberration + * `true` to correct for aberration, or `false` to leave uncorrected. + * + * @returns {Vector} + * The position vector at the solved backdated time. + * The `t` field holds the time that light left the observed + * body to arrive at the observer at the observation time. + */ +function BackdatePosition(date, observerBody, targetBody, aberration) { + VerifyBoolean(aberration); + const time = MakeTime(date); + if (UserDefinedStar(targetBody)) { + // This is a user-defined star, which must be treated as a special case. + // First, we assume its heliocentric position does not change with time. + // Second, we assume its heliocentric position has already been corrected + // for light-travel time, its coordinates given as it appears on Earth at the present. + // Therefore, no backdating is applied. + const tvec = HelioVector(targetBody, time); + if (aberration) { + // (Observer velocity) - (light vector) = (Aberration-corrected direction to target body). + // Note that this is an approximation, because technically the light vector should + // be measured in barycentric coordinates, not heliocentric. The error is very small. + const ostate = HelioState(observerBody, time); + const rvec = new Vector(tvec.x - ostate.x, tvec.y - ostate.y, tvec.z - ostate.z, time); + const s = exports.C_AUDAY / rvec.Length(); // conversion factor from relative distance to speed of light + return new Vector(rvec.x + ostate.vx / s, rvec.y + ostate.vy / s, rvec.z + ostate.vz / s, time); + } + // No correction is needed. Simply return the star's current position as seen from the observer. + const ovec = HelioVector(observerBody, time); + return new Vector(tvec.x - ovec.x, tvec.y - ovec.y, tvec.z - ovec.z, time); + } + let observerPos; + if (aberration) { + // With aberration, `BackdatePosition` will calculate `observerPos` at different times. + // Therefore, do not waste time calculating it now. + // Create a placeholder value that will be ignored. + observerPos = new Vector(0, 0, 0, time); + } + else { + observerPos = HelioVector(observerBody, time); + } + const bpos = new BodyPosition(observerBody, targetBody, aberration, observerPos); + return CorrectLightTravel(t => bpos.Position(t), time); +} +exports.BackdatePosition = BackdatePosition; +/** + * @brief Calculates a vector from the center of the Earth to the given body at the given time. + * + * Calculates geocentric (i.e., with respect to the center of the Earth) + * Cartesian coordinates in the J2000 equatorial system of a celestial + * body at a specified time. The position is always corrected for light travel time: + * this means the position of the body is "back-dated" based on how long it + * takes light to travel from the body to an observer on the Earth. + * Also, the position can optionally be corrected for aberration, an effect + * causing the apparent direction of the body to be shifted based on + * transverse movement of the Earth with respect to the rays of light + * coming from that body. + * + * @param {Body} body + * One of the following values: + * `Body.Sun`, `Body.Moon`, `Body.Mercury`, `Body.Venus`, + * `Body.Earth`, `Body.Mars`, `Body.Jupiter`, `Body.Saturn`, + * `Body.Uranus`, `Body.Neptune`, or `Body.Pluto`. + * Also allowed to be a user-defined star created with {@link DefineStar}. + * + * @param {FlexibleDateTime} date + * The date and time for which the body's position is to be calculated. + * + * @param {boolean} aberration + * Pass `true` to correct for + * aberration, + * or `false` to leave uncorrected. + * + * @returns {Vector} + */ +function GeoVector(body, date, aberration) { + VerifyBoolean(aberration); + const time = MakeTime(date); + switch (body) { + case Body.Earth: + return new Vector(0, 0, 0, time); + case Body.Moon: + return GeoMoon(time); + default: + const vec = BackdatePosition(time, Body.Earth, body, aberration); + vec.t = time; // tricky: return the observation time, not the backdated time + return vec; + } +} +exports.GeoVector = GeoVector; +function ExportState(terse, time) { + return new StateVector(terse.r.x, terse.r.y, terse.r.z, terse.v.x, terse.v.y, terse.v.z, time); +} +/** + * @brief Calculates barycentric position and velocity vectors for the given body. + * + * Given a body and a time, calculates the barycentric position and velocity + * vectors for the center of that body at that time. + * The vectors are expressed in J2000 mean equator coordinates (EQJ). + * + * @param {Body} body + * The celestial body whose barycentric state vector is to be calculated. + * Supported values are `Body.Sun`, `Body.Moon`, `Body.EMB`, `Body.SSB`, and all planets: + * `Body.Mercury`, `Body.Venus`, `Body.Earth`, `Body.Mars`, `Body.Jupiter`, + * `Body.Saturn`, `Body.Uranus`, `Body.Neptune`, `Body.Pluto`. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate position and velocity. + * + * @returns {StateVector} + * An object that contains barycentric position and velocity vectors. + */ +function BaryState(body, date) { + const time = MakeTime(date); + if (body === Body.SSB) { + // Trivial case: the solar system barycenter itself. + return new StateVector(0, 0, 0, 0, 0, 0, time); + } + if (body === Body.Pluto) { + return CalcPluto(time, false); + } + // Find the barycentric positions and velocities for the 5 major bodies: + // Sun, Jupiter, Saturn, Uranus, Neptune. + const bary = new major_bodies_t(time.tt); + switch (body) { + case Body.Sun: return ExportState(bary.Sun, time); + case Body.Jupiter: return ExportState(bary.Jupiter, time); + case Body.Saturn: return ExportState(bary.Saturn, time); + case Body.Uranus: return ExportState(bary.Uranus, time); + case Body.Neptune: return ExportState(bary.Neptune, time); + case Body.Moon: + case Body.EMB: + const earth = CalcVsopPosVel(vsop[Body.Earth], time.tt); + const state = (body === Body.Moon) ? GeoMoonState(time) : GeoEmbState(time); + return new StateVector(state.x + bary.Sun.r.x + earth.r.x, state.y + bary.Sun.r.y + earth.r.y, state.z + bary.Sun.r.z + earth.r.z, state.vx + bary.Sun.v.x + earth.v.x, state.vy + bary.Sun.v.y + earth.v.y, state.vz + bary.Sun.v.z + earth.v.z, time); + } + // Handle the remaining VSOP bodies: Mercury, Venus, Earth, Mars. + if (body in vsop) { + const planet = CalcVsopPosVel(vsop[body], time.tt); + return new StateVector(bary.Sun.r.x + planet.r.x, bary.Sun.r.y + planet.r.y, bary.Sun.r.z + planet.r.z, bary.Sun.v.x + planet.v.x, bary.Sun.v.y + planet.v.y, bary.Sun.v.z + planet.v.z, time); + } + throw `BaryState: Unsupported body "${body}"`; +} +exports.BaryState = BaryState; +/** + * @brief Calculates heliocentric position and velocity vectors for the given body. + * + * Given a body and a time, calculates the position and velocity + * vectors for the center of that body at that time, relative to the center of the Sun. + * The vectors are expressed in J2000 mean equator coordinates (EQJ). + * If you need the position vector only, it is more efficient to call {@link HelioVector}. + * The Sun's center is a non-inertial frame of reference. In other words, the Sun + * experiences acceleration due to gravitational forces, mostly from the larger + * planets (Jupiter, Saturn, Uranus, and Neptune). If you want to calculate momentum, + * kinetic energy, or other quantities that require a non-accelerating frame + * of reference, consider using {@link BaryState} instead. + * + * @param {Body} body + * The celestial body whose heliocentric state vector is to be calculated. + * Supported values are `Body.Sun`, `Body.Moon`, `Body.EMB`, `Body.SSB`, and all planets: + * `Body.Mercury`, `Body.Venus`, `Body.Earth`, `Body.Mars`, `Body.Jupiter`, + * `Body.Saturn`, `Body.Uranus`, `Body.Neptune`, `Body.Pluto`. + * Also allowed to be a user-defined star created by {@link DefineStar}. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate position and velocity. + * + * @returns {StateVector} + * An object that contains heliocentric position and velocity vectors. + */ +function HelioState(body, date) { + const time = MakeTime(date); + switch (body) { + case Body.Sun: + // Trivial case: the Sun is the origin of the heliocentric frame. + return new StateVector(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, time); + case Body.SSB: + // Calculate the barycentric Sun. Then the negative of that is the heliocentric SSB. + const bary = new major_bodies_t(time.tt); + return new StateVector(-bary.Sun.r.x, -bary.Sun.r.y, -bary.Sun.r.z, -bary.Sun.v.x, -bary.Sun.v.y, -bary.Sun.v.z, time); + case Body.Mercury: + case Body.Venus: + case Body.Earth: + case Body.Mars: + case Body.Jupiter: + case Body.Saturn: + case Body.Uranus: + case Body.Neptune: + // Planets included in the VSOP87 model. + const planet = CalcVsopPosVel(vsop[body], time.tt); + return ExportState(planet, time); + case Body.Pluto: + return CalcPluto(time, true); + case Body.Moon: + case Body.EMB: + const earth = CalcVsopPosVel(vsop.Earth, time.tt); + const state = (body == Body.Moon) ? GeoMoonState(time) : GeoEmbState(time); + return new StateVector(state.x + earth.r.x, state.y + earth.r.y, state.z + earth.r.z, state.vx + earth.v.x, state.vy + earth.v.y, state.vz + earth.v.z, time); + default: + if (UserDefinedStar(body)) { + const vec = HelioVector(body, time); + return new StateVector(vec.x, vec.y, vec.z, 0, 0, 0, time); + } + throw `HelioState: Unsupported body "${body}"`; + } +} +exports.HelioState = HelioState; +function QuadInterp(tm, dt, fa, fm, fb) { + let Q = (fb + fa) / 2 - fm; + let R = (fb - fa) / 2; + let S = fm; + let x; + if (Q == 0) { + // This is a line, not a parabola. + if (R == 0) { + // This is a HORIZONTAL line... can't make progress! + return null; + } + x = -S / R; + if (x < -1 || x > +1) + return null; // out of bounds + } + else { + // It really is a parabola. Find roots x1, x2. + let u = R * R - 4 * Q * S; + if (u <= 0) + return null; + let ru = Math.sqrt(u); + let x1 = (-R + ru) / (2 * Q); + let x2 = (-R - ru) / (2 * Q); + if (-1 <= x1 && x1 <= +1) { + if (-1 <= x2 && x2 <= +1) + return null; + x = x1; + } + else if (-1 <= x2 && x2 <= +1) { + x = x2; + } + else { + return null; + } + } + let t = tm + x * dt; + let df_dt = (2 * Q * x + R) / dt; + return { t: t, df_dt: df_dt }; +} +/** + * @brief Options for the {@link Search} function. + * + * @typedef {object} SearchOptions + * + * @property {number | undefined} dt_tolerance_seconds + * The number of seconds for a time window smaller than which the search + * is considered successful. Using too large a tolerance can result in + * an inaccurate time estimate. Using too small a tolerance can cause + * excessive computation, or can even cause the search to fail because of + * limited floating-point resolution. Defaults to 1 second. + * + * @property {number | undefined} init_f1 + * As an optimization, if the caller of {@link Search} + * has already calculated the value of the function being searched (the parameter `func`) + * at the time coordinate `t1`, it can pass in that value as `init_f1`. + * For very expensive calculations, this can measurably improve performance. + * + * @property {number | undefined} init_f2 + * The same as `init_f1`, except this is the optional initial value of `func(t2)` + * instead of `func(t1)`. + * + * @property {number | undefined} iter_limit + */ +/** + * @brief Finds the time when a function ascends through zero. + * + * Search for next time t (such that t is between `t1` and `t2`) + * that `func(t)` crosses from a negative value to a non-negative value. + * The given function must have "smooth" behavior over the entire inclusive range [`t1`, `t2`], + * meaning that it behaves like a continuous differentiable function. + * It is not required that `t1` < `t2`; `t1` > `t2` + * allows searching backward in time. + * Note: `t1` and `t2` must be chosen such that there is no possibility + * of more than one zero-crossing (ascending or descending), or it is possible + * that the "wrong" event will be found (i.e. not the first event after t1) + * or even that the function will return `null`, indicating that no event was found. + * + * @param {function(AstroTime): number} func + * The function to find an ascending zero crossing for. + * The function must accept a single parameter of type {@link AstroTime} + * and return a numeric value: + * function({@link AstroTime}) => `number` + * + * @param {AstroTime} t1 + * The lower time bound of a search window. + * + * @param {AstroTime} t2 + * The upper time bound of a search window. + * + * @param {SearchOptions | undefined} options + * Options that can tune the behavior of the search. + * Most callers can omit this argument. + * + * @returns {AstroTime | null} + * If the search is successful, returns the date and time of the solution. + * If the search fails, returns `null`. + */ +function Search(f, t1, t2, options) { + const dt_tolerance_seconds = VerifyNumber((options && options.dt_tolerance_seconds) || 1); + const dt_days = Math.abs(dt_tolerance_seconds / SECONDS_PER_DAY); + let f1 = (options && options.init_f1) || f(t1); + let f2 = (options && options.init_f2) || f(t2); + let fmid = NaN; + let iter = 0; + let iter_limit = (options && options.iter_limit) || 20; + let calc_fmid = true; + while (true) { + if (++iter > iter_limit) + throw `Excessive iteration in Search()`; + let tmid = InterpolateTime(t1, t2, 0.5); + let dt = tmid.ut - t1.ut; + if (Math.abs(dt) < dt_days) { + // We are close enough to the event to stop the search. + return tmid; + } + if (calc_fmid) + fmid = f(tmid); + else + calc_fmid = true; // we already have the correct value of fmid from the previous loop + // Quadratic interpolation: + // Try to find a parabola that passes through the 3 points we have sampled: + // (t1,f1), (tmid,fmid), (t2,f2). + let q = QuadInterp(tmid.ut, t2.ut - tmid.ut, f1, fmid, f2); + // Did we find an approximate root-crossing? + if (q) { + // Evaluate the function at our candidate solution. + let tq = MakeTime(q.t); + let fq = f(tq); + if (q.df_dt !== 0) { + if (Math.abs(fq / q.df_dt) < dt_days) { + // The estimated time error is small enough that we can quit now. + return tq; + } + // Try guessing a tighter boundary with the interpolated root at the center. + let dt_guess = 1.2 * Math.abs(fq / q.df_dt); + if (dt_guess < dt / 10) { + let tleft = tq.AddDays(-dt_guess); + let tright = tq.AddDays(+dt_guess); + if ((tleft.ut - t1.ut) * (tleft.ut - t2.ut) < 0) { + if ((tright.ut - t1.ut) * (tright.ut - t2.ut) < 0) { + let fleft = f(tleft); + let fright = f(tright); + if (fleft < 0 && fright >= 0) { + f1 = fleft; + f2 = fright; + t1 = tleft; + t2 = tright; + fmid = fq; + calc_fmid = false; + continue; + } + } + } + } + } + } + if (f1 < 0 && fmid >= 0) { + t2 = tmid; + f2 = fmid; + continue; + } + if (fmid < 0 && f2 >= 0) { + t1 = tmid; + f1 = fmid; + continue; + } + // Either there is no ascending zero-crossing in this range + // or the search window is too wide. + return null; + } +} +exports.Search = Search; +function LongitudeOffset(diff) { + let offset = diff; + while (offset <= -180) + offset += 360; + while (offset > 180) + offset -= 360; + return offset; +} +function NormalizeLongitude(lon) { + while (lon < 0) + lon += 360; + while (lon >= 360) + lon -= 360; + return lon; +} +/** + * @brief Searches for when the Sun reaches a given ecliptic longitude. + * + * Searches for the moment in time when the center of the Sun reaches a given apparent + * ecliptic longitude, as seen from the center of the Earth, within a given range of dates. + * This function can be used to determine equinoxes and solstices. + * However, it is usually more convenient and efficient to call {@link Seasons} + * to calculate equinoxes and solstices for a given calendar year. + * `SearchSunLongitude` is more general in that it allows searching for arbitrary longitude values. + * + * @param {number} targetLon + * The desired ecliptic longitude of date in degrees. + * This may be any value in the range [0, 360), although certain + * values have conventional meanings: + * + * When `targetLon` is 0, finds the March equinox, + * which is the moment spring begins in the northern hemisphere + * and the beginning of autumn in the southern hemisphere. + * + * When `targetLon` is 180, finds the September equinox, + * which is the moment autumn begins in the northern hemisphere and + * spring begins in the southern hemisphere. + * + * When `targetLon` is 90, finds the northern solstice, which is the + * moment summer begins in the northern hemisphere and winter + * begins in the southern hemisphere. + * + * When `targetLon` is 270, finds the southern solstice, which is the + * moment winter begins in the northern hemisphere and summer + * begins in the southern hemisphere. + * + * @param {FlexibleDateTime} dateStart + * A date and time known to be earlier than the desired longitude event. + * + * @param {number} limitDays + * A floating point number of days, which when added to `dateStart`, + * yields a date and time known to be after the desired longitude event. + * + * @returns {AstroTime | null} + * The date and time when the Sun reaches the apparent ecliptic longitude `targetLon` + * within the range of times specified by `dateStart` and `limitDays`. + * If the Sun does not reach the target longitude within the specified time range, or the + * time range is excessively wide, the return value is `null`. + * To avoid a `null` return value, the caller must pick a time window around + * the event that is within a few days but not so small that the event might fall outside the window. + */ +function SearchSunLongitude(targetLon, dateStart, limitDays) { + function sun_offset(t) { + let pos = SunPosition(t); + return LongitudeOffset(pos.elon - targetLon); + } + VerifyNumber(targetLon); + VerifyNumber(limitDays); + let t1 = MakeTime(dateStart); + let t2 = t1.AddDays(limitDays); + return Search(sun_offset, t1, t2, { dt_tolerance_seconds: 0.01 }); +} +exports.SearchSunLongitude = SearchSunLongitude; +/** + * @brief Returns one body's ecliptic longitude with respect to another, as seen from the Earth. + * + * This function determines where one body appears around the ecliptic plane + * (the plane of the Earth's orbit around the Sun) as seen from the Earth, + * relative to the another body's apparent position. + * The function returns an angle in the half-open range [0, 360) degrees. + * The value is the ecliptic longitude of `body1` relative to the ecliptic + * longitude of `body2`. + * + * The angle is 0 when the two bodies are at the same ecliptic longitude + * as seen from the Earth. The angle increases in the prograde direction + * (the direction that the planets orbit the Sun and the Moon orbits the Earth). + * + * When the angle is 180 degrees, it means the two bodies appear on opposite sides + * of the sky for an Earthly observer. + * + * Neither `body1` nor `body2` is allowed to be `Body.Earth`. + * If this happens, the function throws an exception. + * + * @param {Body} body1 + * The first body, whose longitude is to be found relative to the second body. + * + * @param {Body} body2 + * The second body, relative to which the longitude of the first body is to be found. + * + * @param {FlexibleDateTime} date + * The date and time of the observation. + * + * @returns {number} + * An angle in the range [0, 360), expressed in degrees. + */ +function PairLongitude(body1, body2, date) { + if (body1 === Body.Earth || body2 === Body.Earth) + throw 'The Earth does not have a longitude as seen from itself.'; + const time = MakeTime(date); + const vector1 = GeoVector(body1, time, false); + const eclip1 = Ecliptic(vector1); + const vector2 = GeoVector(body2, time, false); + const eclip2 = Ecliptic(vector2); + return NormalizeLongitude(eclip1.elon - eclip2.elon); +} +exports.PairLongitude = PairLongitude; +/** + * @brief Calculates the angular separation between the Sun and the given body. + * + * Returns the full angle seen from + * the Earth, between the given body and the Sun. + * Unlike {@link PairLongitude}, this function does not + * project the body's "shadow" onto the ecliptic; + * the angle is measured in 3D space around the plane that + * contains the centers of the Earth, the Sun, and `body`. + * + * @param {Body} body + * The name of a supported celestial body other than the Earth. + * + * @param {FlexibleDateTime} date + * The time at which the angle from the Sun is to be found. + * + * @returns {number} + * An angle in degrees in the range [0, 180]. + */ +function AngleFromSun(body, date) { + if (body == Body.Earth) + throw 'The Earth does not have an angle as seen from itself.'; + const time = MakeTime(date); + const sv = GeoVector(Body.Sun, time, true); + const bv = GeoVector(body, time, true); + const angle = AngleBetween(sv, bv); + return angle; +} +exports.AngleFromSun = AngleFromSun; +/** + * @brief Calculates heliocentric ecliptic longitude of a body. + * + * This function calculates the angle around the plane of the Earth's orbit + * of a celestial body, as seen from the center of the Sun. + * The angle is measured prograde (in the direction of the Earth's orbit around the Sun) + * in degrees from the true equinox of date. The ecliptic longitude is always in the range [0, 360). + * + * @param {Body} body + * A body other than the Sun. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the ecliptic longitude. + * + * @returns {number} + */ +function EclipticLongitude(body, date) { + if (body === Body.Sun) + throw 'Cannot calculate heliocentric longitude of the Sun.'; + const hv = HelioVector(body, date); + const eclip = Ecliptic(hv); + return eclip.elon; +} +exports.EclipticLongitude = EclipticLongitude; +function VisualMagnitude(body, phase, helio_dist, geo_dist) { + // For Mercury and Venus, see: https://iopscience.iop.org/article/10.1086/430212 + let c0, c1 = 0, c2 = 0, c3 = 0; + switch (body) { + case Body.Mercury: + c0 = -0.60; + c1 = +4.98; + c2 = -4.88; + c3 = +3.02; + break; + case Body.Venus: + if (phase < 163.6) { + c0 = -4.47; + c1 = +1.03; + c2 = +0.57; + c3 = +0.13; + } + else { + c0 = 0.98; + c1 = -1.02; + } + break; + case Body.Mars: + c0 = -1.52; + c1 = +1.60; + break; + case Body.Jupiter: + c0 = -9.40; + c1 = +0.50; + break; + case Body.Uranus: + c0 = -7.19; + c1 = +0.25; + break; + case Body.Neptune: + c0 = -6.87; + break; + case Body.Pluto: + c0 = -1.00; + c1 = +4.00; + break; + default: throw `VisualMagnitude: unsupported body ${body}`; + } + const x = phase / 100; + let mag = c0 + x * (c1 + x * (c2 + x * c3)); + mag += 5 * Math.log10(helio_dist * geo_dist); + return mag; +} +function SaturnMagnitude(phase, helio_dist, geo_dist, gc, time) { + // Based on formulas by Paul Schlyter found here: + // http://www.stjarnhimlen.se/comp/ppcomp.html#15 + // We must handle Saturn's rings as a major component of its visual magnitude. + // Find geocentric ecliptic coordinates of Saturn. + const eclip = Ecliptic(gc); + const ir = exports.DEG2RAD * 28.06; // tilt of Saturn's rings to the ecliptic, in radians + const Nr = exports.DEG2RAD * (169.51 + (3.82e-5 * time.tt)); // ascending node of Saturn's rings, in radians + // Find tilt of Saturn's rings, as seen from Earth. + const lat = exports.DEG2RAD * eclip.elat; + const lon = exports.DEG2RAD * eclip.elon; + const tilt = Math.asin(Math.sin(lat) * Math.cos(ir) - Math.cos(lat) * Math.sin(ir) * Math.sin(lon - Nr)); + const sin_tilt = Math.sin(Math.abs(tilt)); + let mag = -9.0 + 0.044 * phase; + mag += sin_tilt * (-2.6 + 1.2 * sin_tilt); + mag += 5 * Math.log10(helio_dist * geo_dist); + return { mag: mag, ring_tilt: exports.RAD2DEG * tilt }; +} +function MoonMagnitude(phase, helio_dist, geo_dist) { + // https://astronomy.stackexchange.com/questions/10246/is-there-a-simple-analytical-formula-for-the-lunar-phase-brightness-curve + let rad = phase * exports.DEG2RAD; + let rad2 = rad * rad; + let rad4 = rad2 * rad2; + let mag = -12.717 + 1.49 * Math.abs(rad) + 0.0431 * rad4; + const moon_mean_distance_au = 385000.6 / exports.KM_PER_AU; + let geo_au = geo_dist / moon_mean_distance_au; + mag += 5 * Math.log10(helio_dist * geo_au); + return mag; +} +/** + * @brief Information about the apparent brightness and sunlit phase of a celestial object. + * + * @property {AstroTime} time + * The date and time pertaining to the other calculated values in this object. + * + * @property {number} mag + * The apparent visual magnitude of the celestial body. + * + * @property {number} phase_angle + * The angle in degrees as seen from the center of the celestial body between the Sun and the Earth. + * The value is always in the range 0 to 180. + * The phase angle provides a measure of what fraction of the body's face appears + * illuminated by the Sun as seen from the Earth. + * When the observed body is the Sun, the `phase` property is set to 0, + * although this has no physical meaning because the Sun emits, rather than reflects, light. + * When the phase is near 0 degrees, the body appears "full". + * When it is 90 degrees, the body appears "half full". + * And when it is 180 degrees, the body appears "new" and is very difficult to see + * because it is both dim and lost in the Sun's glare as seen from the Earth. + * + * @property {number} phase_fraction + * The fraction of the body's face that is illuminated by the Sun, as seen from the Earth. + * Calculated from `phase_angle` for convenience. + * This value ranges from 0 to 1. + * + * @property {number} helio_dist + * The distance between the center of the Sun and the center of the body in + * astronomical units (AU). + * + * @property {number} geo_dist + * The distance between the center of the Earth and the center of the body in AU. + * + * @property {Vector} gc + * Geocentric coordinates: the 3D vector from the center of the Earth to the center of the body. + * The components are in expressed in AU and are oriented with respect to the J2000 equatorial plane. + * + * @property {Vector} hc + * Heliocentric coordinates: The 3D vector from the center of the Sun to the center of the body. + * Like `gc`, `hc` is expressed in AU and oriented with respect + * to the J2000 equatorial plane. + * + * @property {number | undefined} ring_tilt + * For Saturn, this is the angular tilt of the planet's rings in degrees away + * from the line of sight from the Earth. When the value is near 0, the rings + * appear edge-on from the Earth and are therefore difficult to see. + * When `ring_tilt` approaches its maximum value (about 27 degrees), + * the rings appear widest and brightest from the Earth. + * Unlike the JPL Horizons online tool, + * this library includes the effect of the ring tilt angle in the calculated value + * for Saturn's visual magnitude. + * For all bodies other than Saturn, the value of `ring_tilt` is `undefined`. + */ +class IlluminationInfo { + constructor(time, mag, phase_angle, helio_dist, geo_dist, gc, hc, ring_tilt) { + this.time = time; + this.mag = mag; + this.phase_angle = phase_angle; + this.helio_dist = helio_dist; + this.geo_dist = geo_dist; + this.gc = gc; + this.hc = hc; + this.ring_tilt = ring_tilt; + this.phase_fraction = (1 + Math.cos(exports.DEG2RAD * phase_angle)) / 2; + } +} +exports.IlluminationInfo = IlluminationInfo; +/** + * @brief Calculates visual magnitude and related information about a body. + * + * Calculates the phase angle, visual magnitude, + * and other values relating to the body's illumination + * at the given date and time, as seen from the Earth. + * + * @param {Body} body + * The name of the celestial body being observed. + * Not allowed to be `Body.Earth`. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the illumination data for the given body. + * + * @returns {IlluminationInfo} + */ +function Illumination(body, date) { + if (body === Body.Earth) + throw `The illumination of the Earth is not defined.`; + const time = MakeTime(date); + const earth = CalcVsop(vsop.Earth, time); + let phase; // phase angle in degrees between Earth and Sun as seen from body + let hc; // vector from Sun to body + let gc; // vector from Earth to body + let mag; // visual magnitude + if (body === Body.Sun) { + gc = new Vector(-earth.x, -earth.y, -earth.z, time); + hc = new Vector(0, 0, 0, time); + phase = 0; // a placeholder value; the Sun does not have an illumination phase because it emits, rather than reflects, light. + } + else { + if (body === Body.Moon) { + // For extra numeric precision, use geocentric moon formula directly. + gc = GeoMoon(time); + hc = new Vector(earth.x + gc.x, earth.y + gc.y, earth.z + gc.z, time); + } + else { + // For planets, heliocentric vector is most direct to calculate. + hc = HelioVector(body, date); + gc = new Vector(hc.x - earth.x, hc.y - earth.y, hc.z - earth.z, time); + } + phase = AngleBetween(gc, hc); + } + let geo_dist = gc.Length(); // distance from body to center of Earth + let helio_dist = hc.Length(); // distance from body to center of Sun + let ring_tilt; // only reported for Saturn + if (body === Body.Sun) { + mag = SUN_MAG_1AU + 5 * Math.log10(geo_dist); + } + else if (body === Body.Moon) { + mag = MoonMagnitude(phase, helio_dist, geo_dist); + } + else if (body === Body.Saturn) { + const saturn = SaturnMagnitude(phase, helio_dist, geo_dist, gc, time); + mag = saturn.mag; + ring_tilt = saturn.ring_tilt; + } + else { + mag = VisualMagnitude(body, phase, helio_dist, geo_dist); + } + return new IlluminationInfo(time, mag, phase, helio_dist, geo_dist, gc, hc, ring_tilt); +} +exports.Illumination = Illumination; +function SynodicPeriod(body) { + if (body === Body.Earth) + throw 'The Earth does not have a synodic period as seen from itself.'; + if (body === Body.Moon) + return MEAN_SYNODIC_MONTH; + // Calculate the synodic period of the planet from its and the Earth's sidereal periods. + // The sidereal period of a planet is how long it takes to go around the Sun in days, on average. + // The synodic period of a planet is how long it takes between consecutive oppositions + // or conjunctions, on average. + let planet = Planet[body]; + if (!planet) + throw `Not a valid planet name: ${body}`; + // See here for explanation of the formula: + // https://en.wikipedia.org/wiki/Elongation_(astronomy)#Elongation_period + const Te = Planet.Earth.OrbitalPeriod; + const Tp = planet.OrbitalPeriod; + const synodicPeriod = Math.abs(Te / (Te / Tp - 1)); + return synodicPeriod; +} +/** + * @brief Searches for when the Earth and a given body reach a relative ecliptic longitude separation. + * + * Searches for the date and time the relative ecliptic longitudes of + * the specified body and the Earth, as seen from the Sun, reach a certain + * difference. This function is useful for finding conjunctions and oppositions + * of the planets. For the opposition of a superior planet (Mars, Jupiter, ..., Pluto), + * or the inferior conjunction of an inferior planet (Mercury, Venus), + * call with `targetRelLon` = 0. The 0 value indicates that both + * planets are on the same ecliptic longitude line, ignoring the other planet's + * distance above or below the plane of the Earth's orbit. + * For superior conjunctions, call with `targetRelLon` = 180. + * This means the Earth and the other planet are on opposite sides of the Sun. + * + * @param {Body} body + * Any planet other than the Earth. + * + * @param {number} targetRelLon + * The desired angular difference in degrees between the ecliptic longitudes + * of `body` and the Earth. Must be in the range (-180, +180]. + * + * @param {FlexibleDateTime} startDate + * The date and time after which to find the next occurrence of the + * body and the Earth reaching the desired relative longitude. + * + * @returns {AstroTime} + * The time when the Earth and the body next reach the specified relative longitudes. + */ +function SearchRelativeLongitude(body, targetRelLon, startDate) { + VerifyNumber(targetRelLon); + const planet = Planet[body]; + if (!planet) + throw `Cannot search relative longitude because body is not a planet: ${body}`; + if (body === Body.Earth) + throw 'Cannot search relative longitude for the Earth (it is always 0)'; + // Determine whether the Earth "gains" (+1) on the planet or "loses" (-1) + // as both race around the Sun. + const direction = (planet.OrbitalPeriod > Planet.Earth.OrbitalPeriod) ? +1 : -1; + function offset(t) { + const plon = EclipticLongitude(body, t); + const elon = EclipticLongitude(Body.Earth, t); + const diff = direction * (elon - plon); + return LongitudeOffset(diff - targetRelLon); + } + let syn = SynodicPeriod(body); + let time = MakeTime(startDate); + // Iterate until we converge on the desired event. + // Calculate the error angle, which will be a negative number of degrees, + // meaning we are "behind" the target relative longitude. + let error_angle = offset(time); + if (error_angle > 0) + error_angle -= 360; // force searching forward in time + for (let iter = 0; iter < 100; ++iter) { + // Estimate how many days in the future (positive) or past (negative) + // we have to go to get closer to the target relative longitude. + let day_adjust = (-error_angle / 360) * syn; + time = time.AddDays(day_adjust); + if (Math.abs(day_adjust) * SECONDS_PER_DAY < 1) + return time; + let prev_angle = error_angle; + error_angle = offset(time); + if (Math.abs(prev_angle) < 30) { + // Improve convergence for Mercury/Mars (eccentric orbits) + // by adjusting the synodic period to more closely match the + // variable speed of both planets in this part of their respective orbits. + if (prev_angle !== error_angle) { + let ratio = prev_angle / (prev_angle - error_angle); + if (ratio > 0.5 && ratio < 2.0) + syn *= ratio; + } + } + } + throw `Relative longitude search failed to converge for ${body} near ${time.toString()} (error_angle = ${error_angle}).`; +} +exports.SearchRelativeLongitude = SearchRelativeLongitude; +/** + * @brief Determines the moon's phase expressed as an ecliptic longitude. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the moon's phase. + * + * @returns {number} + * A value in the range [0, 360) indicating the difference + * in ecliptic longitude between the center of the Sun and the + * center of the Moon, as seen from the center of the Earth. + * Certain longitude values have conventional meanings: + * + * * 0 = new moon + * * 90 = first quarter + * * 180 = full moon + * * 270 = third quarter + */ +function MoonPhase(date) { + return PairLongitude(Body.Moon, Body.Sun, date); +} +exports.MoonPhase = MoonPhase; +/** + * @brief Searches for the date and time that the Moon reaches a specified phase. + * + * Lunar phases are defined in terms of geocentric ecliptic longitudes + * with respect to the Sun. When the Moon and the Sun have the same ecliptic + * longitude, that is defined as a new moon. When the two ecliptic longitudes + * are 180 degrees apart, that is defined as a full moon. + * To enumerate quarter lunar phases, it is simpler to call + * {@link SearchMoonQuarter} once, followed by repeatedly calling + * {@link NextMoonQuarter}. `SearchMoonPhase` is only + * necessary for finding other lunar phases than the usual quarter phases. + * + * @param {number} targetLon + * The difference in geocentric ecliptic longitude between the Sun and Moon + * that specifies the lunar phase being sought. This can be any value + * in the range [0, 360). Here are some helpful examples: + * 0 = new moon, + * 90 = first quarter, + * 180 = full moon, + * 270 = third quarter. + * + * @param {FlexibleDateTime} dateStart + * The beginning of the window of time in which to search. + * + * @param {number} limitDays + * The floating point number of days away from `dateStart` + * that limits the window of time in which to search. + * If the value is negative, the search is performed into the past from `startTime`. + * Otherwise, the search is performed into the future from `startTime`. + * + * @returns {AstroTime | null} + * If successful, returns the date and time the moon reaches the phase specified by `targetlon`. + * This function will return `null` if the phase does not occur within `limitDays` of `startTime`; + * that is, if the search window is too small. + */ +function SearchMoonPhase(targetLon, dateStart, limitDays) { + function moon_offset(t) { + let mlon = MoonPhase(t); + return LongitudeOffset(mlon - targetLon); + } + VerifyNumber(targetLon); + VerifyNumber(limitDays); + // To avoid discontinuities in the moon_offset function causing problems, + // we need to approximate when that function will next return 0. + // We probe it with the start time and take advantage of the fact + // that every lunar phase repeats roughly every 29.5 days. + // There is a surprising uncertainty in the quarter timing, + // due to the eccentricity of the moon's orbit. + // I have seen more than 0.9 days away from the simple prediction. + // To be safe, we take the predicted time of the event and search + // +/-1.5 days around it (a 3.0-day wide window). + // But we must return null if the final result goes beyond limitDays after dateStart. + const uncertainty = 1.5; + const ta = MakeTime(dateStart); + let ya = moon_offset(ta); + let est_dt, dt1, dt2; + if (limitDays < 0) { + // Search backward in time. + if (ya < 0) + ya += 360; + est_dt = -(MEAN_SYNODIC_MONTH * ya) / 360; + dt2 = est_dt + uncertainty; + if (dt2 < limitDays) + return null; // not possible for moon phase to occur within the specified window + dt1 = Math.max(limitDays, est_dt - uncertainty); + } + else { + // Search forward in time. + if (ya > 0) + ya -= 360; + est_dt = -(MEAN_SYNODIC_MONTH * ya) / 360; + dt1 = est_dt - uncertainty; + if (dt1 > limitDays) + return null; // not possible for moon phase to occur within the specified window + dt2 = Math.min(limitDays, est_dt + uncertainty); + } + const t1 = ta.AddDays(dt1); + const t2 = ta.AddDays(dt2); + return Search(moon_offset, t1, t2, { dt_tolerance_seconds: 0.1 }); +} +exports.SearchMoonPhase = SearchMoonPhase; +/** + * @brief A quarter lunar phase, along with when it occurs. + * + * @property {number} quarter + * An integer as follows: + * 0 = new moon, + * 1 = first quarter, + * 2 = full moon, + * 3 = third quarter. + * + * @property {AstroTime} time + * The date and time of the quarter lunar phase. + */ +class MoonQuarter { + constructor(quarter, time) { + this.quarter = quarter; + this.time = time; + } +} +exports.MoonQuarter = MoonQuarter; +/** + * @brief Finds the first quarter lunar phase after the specified date and time. + * + * The quarter lunar phases are: new moon, first quarter, full moon, and third quarter. + * To enumerate quarter lunar phases, call `SearchMoonQuarter` once, + * then pass its return value to {@link NextMoonQuarter} to find the next + * `MoonQuarter`. Keep calling `NextMoonQuarter` in a loop, + * passing the previous return value as the argument to the next call. + * + * @param {FlexibleDateTime} dateStart + * The date and time after which to find the first quarter lunar phase. + * + * @returns {MoonQuarter} + */ +function SearchMoonQuarter(dateStart) { + // Determine what the next quarter phase will be. + let phaseStart = MoonPhase(dateStart); + let quarterStart = Math.floor(phaseStart / 90); + let quarter = (quarterStart + 1) % 4; + let time = SearchMoonPhase(90 * quarter, dateStart, 10); + if (!time) + throw 'Cannot find moon quarter'; + return new MoonQuarter(quarter, time); +} +exports.SearchMoonQuarter = SearchMoonQuarter; +/** + * @brief Finds the next quarter lunar phase in a series. + * + * Given a {@link MoonQuarter} object, finds the next consecutive + * quarter lunar phase. See remarks in {@link SearchMoonQuarter} + * for explanation of usage. + * + * @param {MoonQuarter} mq + * The return value of a prior call to {@link MoonQuarter} or `NextMoonQuarter`. + * + * @returns {MoonQuarter} + */ +function NextMoonQuarter(mq) { + // Skip 6 days past the previous found moon quarter to find the next one. + // This is less than the minimum possible increment. + // So far I have seen the interval well contained by the range (6.5, 8.3) days. + let date = new Date(mq.time.date.getTime() + 6 * MILLIS_PER_DAY); + return SearchMoonQuarter(date); +} +exports.NextMoonQuarter = NextMoonQuarter; +/** + * @brief Information about idealized atmospheric variables at a given elevation. + * + * @property {number} pressure + * Atmospheric pressure in pascals. + * + * @property {number} temperature + * Atmospheric temperature in kelvins. + * + * @property {number} density + * Atmospheric density relative to sea level. + */ +class AtmosphereInfo { + constructor(pressure, temperature, density) { + this.pressure = pressure; + this.temperature = temperature; + this.density = density; + } +} +exports.AtmosphereInfo = AtmosphereInfo; +/** + * @brief Calculates U.S. Standard Atmosphere (1976) variables as a function of elevation. + * + * This function calculates idealized values of pressure, temperature, and density + * using the U.S. Standard Atmosphere (1976) model. + * 1. COESA, U.S. Standard Atmosphere, 1976, U.S. Government Printing Office, Washington, DC, 1976. + * 2. Jursa, A. S., Ed., Handbook of Geophysics and the Space Environment, Air Force Geophysics Laboratory, 1985. + * See: + * https://hbcp.chemnetbase.com/faces/documents/14_12/14_12_0001.xhtml + * https://ntrs.nasa.gov/api/citations/19770009539/downloads/19770009539.pdf + * https://www.ngdc.noaa.gov/stp/space-weather/online-publications/miscellaneous/us-standard-atmosphere-1976/us-standard-atmosphere_st76-1562_noaa.pdf + * + * @param {number} elevationMeters + * The elevation above sea level at which to calculate atmospheric variables. + * Must be in the range -500 to +100000, or an exception will occur. + * + * @returns {AtmosphereInfo} + */ +function Atmosphere(elevationMeters) { + const P0 = 101325.0; // pressure at sea level [pascals] + const T0 = 288.15; // temperature at sea level [kelvins] + const T1 = 216.65; // temperature between 20 km and 32 km [kelvins] + if (!Number.isFinite(elevationMeters) || elevationMeters < -500.0 || elevationMeters > 100000.0) + throw `Invalid elevation: ${elevationMeters}`; + let temperature; + let pressure; + if (elevationMeters <= 11000.0) { + temperature = T0 - 0.0065 * elevationMeters; + pressure = P0 * Math.pow(T0 / temperature, -5.25577); + } + else if (elevationMeters <= 20000.0) { + temperature = T1; + pressure = 22632.0 * Math.exp(-0.00015768832 * (elevationMeters - 11000.0)); + } + else { + temperature = T1 + 0.001 * (elevationMeters - 20000.0); + pressure = 5474.87 * Math.pow(T1 / temperature, 34.16319); + } + // The density is calculated relative to the sea level value. + // Using the ideal gas law PV=nRT, we deduce that density is proportional to P/T. + const density = (pressure / temperature) / (P0 / T0); + return new AtmosphereInfo(pressure, temperature, density); +} +exports.Atmosphere = Atmosphere; +function HorizonDipAngle(observer, metersAboveGround) { + // Calculate the effective radius of the Earth at ground level below the observer. + // Correct for the Earth's oblateness. + const phi = observer.latitude * exports.DEG2RAD; + const sinphi = Math.sin(phi); + const cosphi = Math.cos(phi); + const c = 1.0 / Math.hypot(cosphi, sinphi * EARTH_FLATTENING); + const s = c * (EARTH_FLATTENING * EARTH_FLATTENING); + const ht_km = (observer.height - metersAboveGround) / 1000.0; // height of ground above sea level + const ach = EARTH_EQUATORIAL_RADIUS_KM * c + ht_km; + const ash = EARTH_EQUATORIAL_RADIUS_KM * s + ht_km; + const radius_m = 1000.0 * Math.hypot(ach * cosphi, ash * sinphi); + // Correct refraction of a ray of light traveling tangent to the Earth's surface. + // Based on: https://www.largeformatphotography.info/sunmooncalc/SMCalc.js + // which in turn derives from: + // Sweer, John. 1938. The Path of a Ray of Light Tangent to the Surface of the Earth. + // Journal of the Optical Society of America 28 (September):327-329. + // k = refraction index + const k = 0.175 * Math.pow(1.0 - (6.5e-3 / 283.15) * (observer.height - (2.0 / 3.0) * metersAboveGround), 3.256); + // Calculate how far below the observer's horizontal plane the observed horizon dips. + return exports.RAD2DEG * -(Math.sqrt(2 * (1 - k) * metersAboveGround / radius_m) / (1 - k)); +} +function BodyRadiusAu(body) { + // For the purposes of calculating rise/set times, + // only the Sun and Moon appear large enough to an observer + // on the Earth for their radius to matter. + // All other bodies are treated as points. + switch (body) { + case Body.Sun: return SUN_RADIUS_AU; + case Body.Moon: return MOON_EQUATORIAL_RADIUS_AU; + default: return 0; + } +} +/** + * @brief Searches for the next time a celestial body rises or sets as seen by an observer on the Earth. + * + * This function finds the next rise or set time of the Sun, Moon, or planet other than the Earth. + * Rise time is when the body first starts to be visible above the horizon. + * For example, sunrise is the moment that the top of the Sun first appears to peek above the horizon. + * Set time is the moment when the body appears to vanish below the horizon. + * Therefore, this function adjusts for the apparent angular radius of the observed body + * (significant only for the Sun and Moon). + * + * This function corrects for a typical value of atmospheric refraction, which causes celestial + * bodies to appear higher above the horizon than they would if the Earth had no atmosphere. + * Astronomy Engine uses a correction of 34 arcminutes. Real-world refraction varies based + * on air temperature, pressure, and humidity; such weather-based conditions are outside + * the scope of Astronomy Engine. + * + * Note that rise or set may not occur in every 24 hour period. + * For example, near the Earth's poles, there are long periods of time where + * the Sun stays below the horizon, never rising. + * Also, it is possible for the Moon to rise just before midnight but not set during the subsequent 24-hour day. + * This is because the Moon sets nearly an hour later each day due to orbiting the Earth a + * significant amount during each rotation of the Earth. + * Therefore callers must not assume that the function will always succeed. + * + * @param {Body} body + * The Sun, Moon, any planet other than the Earth, + * or a user-defined star that was created by a call to {@link DefineStar}. + * + * @param {Observer} observer + * Specifies the geographic coordinates and elevation above sea level of the observer. + * + * @param {number} direction + * Either +1 to find rise time or -1 to find set time. + * Any other value will cause an exception to be thrown. + * + * @param {FlexibleDateTime} dateStart + * The date and time after which the specified rise or set time is to be found. + * + * @param {number} limitDays + * Limits how many days to search for a rise or set time, and defines + * the direction in time to search. When `limitDays` is positive, the + * search is performed into the future, after `dateStart`. + * When negative, the search is performed into the past, before `dateStart`. + * To limit a rise or set time to the same day, you can use a value of 1 day. + * In cases where you want to find the next rise or set time no matter how far + * in the future (for example, for an observer near the south pole), you can + * pass in a larger value like 365. + * + * @param {number?} metersAboveGround + * Defaults to 0.0 if omitted. + * Usually the observer is located at ground level. Then this parameter + * should be zero. But if the observer is significantly higher than ground + * level, for example in an airplane, this parameter should be a positive + * number indicating how far above the ground the observer is. + * An exception occurs if `metersAboveGround` is negative. + * + * @returns {AstroTime | null} + * The date and time of the rise or set event, or null if no such event + * occurs within the specified time window. + */ +function SearchRiseSet(body, observer, direction, dateStart, limitDays, metersAboveGround = 0.0) { + if (!Number.isFinite(metersAboveGround) || (metersAboveGround < 0.0)) + throw `Invalid value for metersAboveGround: ${metersAboveGround}`; + // We want to find when the top of the body crosses the horizon, not the body's center. + // Therefore, we need to know the body's radius. + const body_radius_au = BodyRadiusAu(body); + // Calculate atmospheric density at ground level. + const atmos = Atmosphere(observer.height - metersAboveGround); + // Calculate the apparent angular dip of the horizon. + const dip = HorizonDipAngle(observer, metersAboveGround); + // Correct refraction for objects near the horizon, using atmospheric density at the ground. + const altitude = dip - (REFRACTION_NEAR_HORIZON * atmos.density); + // Search for the top of the body crossing the corrected altitude angle. + return InternalSearchAltitude(body, observer, direction, dateStart, limitDays, body_radius_au, altitude); +} +exports.SearchRiseSet = SearchRiseSet; +/** + * @brief Finds the next time the center of a body passes through a given altitude. + * + * Finds when the center of the given body ascends or descends through a given + * altitude angle, as seen by an observer at the specified location on the Earth. + * By using the appropriate combination of `direction` and `altitude` parameters, + * this function can be used to find when civil, nautical, or astronomical twilight + * begins (dawn) or ends (dusk). + * + * Civil dawn begins before sunrise when the Sun ascends through 6 degrees below + * the horizon. To find civil dawn, pass +1 for `direction` and -6 for `altitude`. + * + * Civil dusk ends after sunset when the Sun descends through 6 degrees below the horizon. + * To find civil dusk, pass -1 for `direction` and -6 for `altitude`. + * + * Nautical twilight is similar to civil twilight, only the `altitude` value should be -12 degrees. + * + * Astronomical twilight uses -18 degrees as the `altitude` value. + * + * By convention for twilight time calculations, the altitude is not corrected for + * atmospheric refraction. This is because the target altitudes are below the horizon, + * and refraction is not directly observable. + * + * `SearchAltitude` is not intended to find rise/set times of a body for two reasons: + * (1) Rise/set times of the Sun or Moon are defined by their topmost visible portion, not their centers. + * (2) Rise/set times are affected significantly by atmospheric refraction. + * Therefore, it is better to use {@link SearchRiseSet} to find rise/set times, which + * corrects for both of these considerations. + * + * `SearchAltitude` will not work reliably for altitudes at or near the body's + * maximum or minimum altitudes. To find the time a body reaches minimum or maximum altitude + * angles, use {@link SearchHourAngle}. + * + * @param {Body} body + * The Sun, Moon, any planet other than the Earth, + * or a user-defined star that was created by a call to {@link DefineStar}. + * + * @param {Observer} observer + * Specifies the geographic coordinates and elevation above sea level of the observer. + * + * @param {number} direction + * Either +1 to find when the body ascends through the altitude, + * or -1 for when the body descends through the altitude. + * Any other value will cause an exception to be thrown. + * + * @param {FlexibleDateTime} dateStart + * The date and time after which the specified altitude event is to be found. + * + * @param {number} limitDays + * Limits how many days to search for the body reaching the altitude angle, + * and defines the direction in time to search. When `limitDays` is positive, the + * search is performed into the future, after `dateStart`. + * When negative, the search is performed into the past, before `dateStart`. + * To limit the search to the same day, you can use a value of 1 day. + * In cases where you want to find the altitude event no matter how far + * in the future (for example, for an observer near the south pole), you can + * pass in a larger value like 365. + * + * @param {number} altitude + * The desired altitude angle of the body's center above (positive) + * or below (negative) the observer's local horizon, expressed in degrees. + * Must be in the range [-90, +90]. + * + * @returns {AstroTime | null} + * The date and time of the altitude event, or null if no such event + * occurs within the specified time window. + */ +function SearchAltitude(body, observer, direction, dateStart, limitDays, altitude) { + if (!Number.isFinite(altitude) || altitude < -90 || altitude > +90) + throw `Invalid altitude angle: ${altitude}`; + return InternalSearchAltitude(body, observer, direction, dateStart, limitDays, 0, altitude); +} +exports.SearchAltitude = SearchAltitude; +class AscentInfo { + constructor(tx, ty, ax, ay) { + this.tx = tx; + this.ty = ty; + this.ax = ax; + this.ay = ay; + } +} +function FindAscent(depth, altdiff, max_deriv_alt, t1, t2, a1, a2) { + // See if we can find any time interval where the altitude-diff function + // rises from non-positive to positive. + if (a1 < 0.0 && a2 >= 0.0) { + // Trivial success case: the endpoints already rise through zero. + return new AscentInfo(t1, t2, a1, a2); + } + if (a1 >= 0.0 && a2 < 0.0) { + // Trivial failure case: Assume Nyquist condition prevents an ascent. + return null; + } + if (depth > 17) { + // Safety valve: do not allow unlimited recursion. + // This should never happen if the rest of the logic is working correctly, + // so fail the whole search if it does happen. It's a bug! + throw `Excessive recursion in rise/set ascent search.`; + } + // Both altitudes are on the same side of zero: both are negative, or both are non-negative. + // There could be a convex "hill" or a concave "valley" that passes through zero. + // In polar regions sometimes there is a rise/set or set/rise pair within minutes of each other. + // For example, the Moon can be below the horizon, then the very top of it becomes + // visible (moonrise) for a few minutes, then it moves sideways and down below + // the horizon again (moonset). We want to catch these cases. + // However, for efficiency and practicality concerns, because the rise/set search itself + // has a 0.1 second threshold, we do not worry about rise/set pairs that are less than + // one second apart. These are marginal cases that are rendered highly uncertain + // anyway, due to unpredictable atmospheric refraction conditions (air temperature and pressure). + const dt = t2.ut - t1.ut; + if (dt * SECONDS_PER_DAY < 1.0) + return null; + // Is it possible to reach zero from the altitude that is closer to zero? + const da = Math.min(Math.abs(a1), Math.abs(a2)); + // Without loss of generality, assume |a1| <= |a2|. + // (Reverse the argument in the case |a2| < |a1|.) + // Imagine you have to "drive" from a1 to 0, then back to a2. + // You can't go faster than max_deriv_alt. If you can't reach 0 in half the time, + // you certainly don't have time to reach 0, turn around, and still make your way + // back up to a2 (which is at least as far from 0 than a1 is) in the time interval dt. + // Therefore, the time threshold is half the time interval, or dt/2. + if (da > max_deriv_alt * (dt / 2)) { + // Prune: the altitude cannot change fast enough to reach zero. + return null; + } + // Bisect the time interval and evaluate the altitude at the midpoint. + const tmid = new AstroTime((t1.ut + t2.ut) / 2); + const amid = altdiff(tmid); + // Use recursive bisection to search for a solution bracket. + return (FindAscent(1 + depth, altdiff, max_deriv_alt, t1, tmid, a1, amid) || + FindAscent(1 + depth, altdiff, max_deriv_alt, tmid, t2, amid, a2)); +} +function MaxAltitudeSlope(body, latitude) { + // Calculate the maximum possible rate that this body's altitude + // could change [degrees/day] as seen by this observer. + // First use experimentally determined extreme bounds for this body + // of how much topocentric RA and DEC can ever change per rate of time. + // We need minimum possible d(RA)/dt, and maximum possible magnitude of d(DEC)/dt. + // Conservatively, we round d(RA)/dt down, d(DEC)/dt up. + // Then calculate the resulting maximum possible altitude change rate. + if (latitude < -90 || latitude > +90) + throw `Invalid geographic latitude: ${latitude}`; + let deriv_ra; + let deriv_dec; + switch (body) { + case Body.Moon: + deriv_ra = +4.5; + deriv_dec = +8.2; + break; + case Body.Sun: + deriv_ra = +0.8; + deriv_dec = +0.5; + break; + case Body.Mercury: + deriv_ra = -1.6; + deriv_dec = +1.0; + break; + case Body.Venus: + deriv_ra = -0.8; + deriv_dec = +0.6; + break; + case Body.Mars: + deriv_ra = -0.5; + deriv_dec = +0.4; + break; + case Body.Jupiter: + case Body.Saturn: + case Body.Uranus: + case Body.Neptune: + case Body.Pluto: + deriv_ra = -0.2; + deriv_dec = +0.2; + break; + case Body.Star1: + case Body.Star2: + case Body.Star3: + case Body.Star4: + case Body.Star5: + case Body.Star6: + case Body.Star7: + case Body.Star8: + // The minimum allowed heliocentric distance of a user-defined star + // is one light-year. This can cause a tiny amount of parallax (about 0.001 degrees). + // Also, including stellar aberration (22 arcsec = 0.006 degrees), we provide a + // generous safety buffer of 0.008 degrees. + deriv_ra = -0.008; + deriv_dec = +0.008; + break; + default: + throw `Body not allowed for altitude search: ${body}`; + } + const latrad = exports.DEG2RAD * latitude; + return Math.abs(((360.0 / SOLAR_DAYS_PER_SIDEREAL_DAY) - deriv_ra) * Math.cos(latrad)) + Math.abs(deriv_dec * Math.sin(latrad)); +} +function InternalSearchAltitude(body, observer, direction, dateStart, limitDays, bodyRadiusAu, targetAltitude) { + VerifyObserver(observer); + VerifyNumber(limitDays); + VerifyNumber(bodyRadiusAu); + VerifyNumber(targetAltitude); + if (targetAltitude < -90 || targetAltitude > +90) + throw `Invalid target altitude angle: ${targetAltitude}`; + const RISE_SET_DT = 0.42; // 10.08 hours: Nyquist-safe for 22-hour period. + const max_deriv_alt = MaxAltitudeSlope(body, observer.latitude); + function altdiff(time) { + const ofdate = Equator(body, time, observer, true, true); + const hor = Horizon(time, observer, ofdate.ra, ofdate.dec); + const altitude = hor.altitude + exports.RAD2DEG * Math.asin(bodyRadiusAu / ofdate.dist); + return direction * (altitude - targetAltitude); + } + // We allow searching forward or backward in time. + // But we want to keep t1 < t2, so we need a few if/else statements. + const startTime = MakeTime(dateStart); + let t1 = startTime; + let t2 = startTime; + let a1 = altdiff(t1); + let a2 = a1; + for (;;) { + if (limitDays < 0.0) { + t1 = t2.AddDays(-RISE_SET_DT); + a1 = altdiff(t1); + } + else { + t2 = t1.AddDays(+RISE_SET_DT); + a2 = altdiff(t2); + } + const ascent = FindAscent(0, altdiff, max_deriv_alt, t1, t2, a1, a2); + if (ascent) { + // We found a time interval [t1, t2] that contains an alt-diff + // rising from negative a1 to non-negative a2. + // Search for the time where the root occurs. + const time = Search(altdiff, ascent.tx, ascent.ty, { + dt_tolerance_seconds: 0.1, + init_f1: ascent.ax, + init_f2: ascent.ay + }); + if (time) { + // Now that we have a solution, we have to check whether it goes outside the time bounds. + if (limitDays < 0.0) { + if (time.ut < startTime.ut + limitDays) + return null; + } + else { + if (time.ut > startTime.ut + limitDays) + return null; + } + return time; // success! + } + // The search should have succeeded. Something is wrong with the ascent finder! + throw `Rise/set search failed after finding ascent: t1=${t1}, t2=${t2}, a1=${a1}, a2=${a2}`; + } + // There is no ascent in this interval, so keep searching. + if (limitDays < 0.0) { + if (t1.ut < startTime.ut + limitDays) + return null; + t2 = t1; + a2 = a1; + } + else { + if (t2.ut > startTime.ut + limitDays) + return null; + t1 = t2; + a1 = a2; + } + } +} +/** + * @brief Horizontal position of a body upon reaching an hour angle. + * + * Returns information about an occurrence of a celestial body + * reaching a given hour angle as seen by an observer at a given + * location on the surface of the Earth. + * + * @property {AstroTime} time + * The date and time of the celestial body reaching the hour angle. + * + * @property {HorizontalCoordinates} hor + * Topocentric horizontal coordinates for the body + * at the time indicated by the `time` property. + */ +class HourAngleEvent { + constructor(time, hor) { + this.time = time; + this.hor = hor; + } +} +exports.HourAngleEvent = HourAngleEvent; +/** + * @brief Searches for the time when the center of a body reaches a specified hour angle as seen by an observer on the Earth. + * + * The *hour angle* of a celestial body indicates its position in the sky with respect + * to the Earth's rotation. The hour angle depends on the location of the observer on the Earth. + * The hour angle is 0 when the body's center reaches its highest angle above the horizon in a given day. + * The hour angle increases by 1 unit for every sidereal hour that passes after that point, up + * to 24 sidereal hours when it reaches the highest point again. So the hour angle indicates + * the number of hours that have passed since the most recent time that the body has culminated, + * or reached its highest point. + * + * This function searches for the next or previous time a celestial body reaches the given hour angle + * relative to the date and time specified by `dateStart`. + * To find when a body culminates, pass 0 for `hourAngle`. + * To find when a body reaches its lowest point in the sky, pass 12 for `hourAngle`. + * + * Note that, especially close to the Earth's poles, a body as seen on a given day + * may always be above the horizon or always below the horizon, so the caller cannot + * assume that a culminating object is visible nor that an object is below the horizon + * at its minimum altitude. + * + * The function returns the date and time, along with the horizontal coordinates + * of the body at that time, as seen by the given observer. + * + * @param {Body} body + * The Sun, Moon, any planet other than the Earth, + * or a user-defined star that was created by a call to {@link DefineStar}. + * + * @param {Observer} observer + * Specifies the geographic coordinates and elevation above sea level of the observer. + * + * @param {number} hourAngle + * The hour angle expressed in + * sidereal + * hours for which the caller seeks to find the body attain. + * The value must be in the range [0, 24). + * The hour angle represents the number of sidereal hours that have + * elapsed since the most recent time the body crossed the observer's local + * meridian. + * This specifying `hourAngle` = 0 finds the moment in time + * the body reaches the highest angular altitude in a given sidereal day. + * + * @param {FlexibleDateTime} dateStart + * The date and time after which the desired hour angle crossing event + * is to be found. + * + * @param {number} direction + * The direction in time to perform the search: a positive value + * searches forward in time, a negative value searches backward in time. + * The function throws an exception if `direction` is zero. + * + * @returns {HourAngleEvent} + */ +function SearchHourAngle(body, observer, hourAngle, dateStart, direction = +1) { + VerifyObserver(observer); + let time = MakeTime(dateStart); + let iter = 0; + if (body === Body.Earth) + throw 'Cannot search for hour angle of the Earth.'; + VerifyNumber(hourAngle); + if (hourAngle < 0.0 || hourAngle >= 24.0) + throw `Invalid hour angle ${hourAngle}`; + VerifyNumber(direction); + if (direction === 0) + throw `Direction must be positive or negative.`; + while (true) { + ++iter; + // Calculate Greenwich Apparent Sidereal Time (GAST) at the given time. + let gast = sidereal_time(time); + let ofdate = Equator(body, time, observer, true, true); + // Calculate the adjustment needed in sidereal time to bring + // the hour angle to the desired value. + let delta_sidereal_hours = ((hourAngle + ofdate.ra - observer.longitude / 15) - gast) % 24; + if (iter === 1) { + // On the first iteration, always search in the requested time direction. + if (direction > 0) { + // Search forward in time. + if (delta_sidereal_hours < 0) + delta_sidereal_hours += 24; + } + else { + // Search backward in time. + if (delta_sidereal_hours > 0) + delta_sidereal_hours -= 24; + } + } + else { + // On subsequent iterations, we make the smallest possible adjustment, + // either forward or backward in time. + if (delta_sidereal_hours < -12) + delta_sidereal_hours += 24; + else if (delta_sidereal_hours > +12) + delta_sidereal_hours -= 24; + } + // If the error is tolerable (less than 0.1 seconds), stop searching. + if (Math.abs(delta_sidereal_hours) * 3600 < 0.1) { + const hor = Horizon(time, observer, ofdate.ra, ofdate.dec, 'normal'); + return new HourAngleEvent(time, hor); + } + // We need to loop another time to get more accuracy. + // Update the terrestrial time adjusting by sidereal time. + let delta_days = (delta_sidereal_hours / 24) * SOLAR_DAYS_PER_SIDEREAL_DAY; + time = time.AddDays(delta_days); + } +} +exports.SearchHourAngle = SearchHourAngle; +/** + * @brief Finds the hour angle of a body for a given observer and time. + * + * The *hour angle* of a celestial body indicates its position in the sky with respect + * to the Earth's rotation. The hour angle depends on the location of the observer on the Earth. + * The hour angle is 0 when the body's center reaches its highest angle above the horizon in a given day. + * The hour angle increases by 1 unit for every sidereal hour that passes after that point, up + * to 24 sidereal hours when it reaches the highest point again. So the hour angle indicates + * the number of hours that have passed since the most recent time that the body has culminated, + * or reached its highest point. + * + * This function returns the hour angle of the body as seen at the given time and geogrpahic location. + * The hour angle is a number in the half-open range [0, 24). + * + * @param {Body} body + * The body whose observed hour angle is to be found. + * + * @param {FlexibleDateTime} date + * The date and time of the observation. + * + * @param {Observer} observer + * The geographic location where the observation takes place. + * + * @returns {number} + */ +function HourAngle(body, date, observer) { + const time = MakeTime(date); + const gast = SiderealTime(time); + const ofdate = Equator(body, time, observer, true, true); + let hourAngle = (observer.longitude / 15 + gast - ofdate.ra) % 24; + if (hourAngle < 0.0) + hourAngle += 24.0; + return hourAngle; +} +exports.HourAngle = HourAngle; +/** + * @brief When the seasons change for a given calendar year. + * + * Represents the dates and times of the two solstices + * and the two equinoxes in a given calendar year. + * These four events define the changing of the seasons on the Earth. + * + * @property {AstroTime} mar_equinox + * The date and time of the March equinox in the given calendar year. + * This is the moment in March that the plane of the Earth's equator passes + * through the center of the Sun; thus the Sun's declination + * changes from a negative number to a positive number. + * The March equinox defines + * the beginning of spring in the northern hemisphere and + * the beginning of autumn in the southern hemisphere. + * + * @property {AstroTime} jun_solstice + * The date and time of the June solstice in the given calendar year. + * This is the moment in June that the Sun reaches its most positive + * declination value. + * At this moment the Earth's north pole is most tilted most toward the Sun. + * The June solstice defines + * the beginning of summer in the northern hemisphere and + * the beginning of winter in the southern hemisphere. + * + * @property {AstroTime} sep_equinox + * The date and time of the September equinox in the given calendar year. + * This is the moment in September that the plane of the Earth's equator passes + * through the center of the Sun; thus the Sun's declination + * changes from a positive number to a negative number. + * The September equinox defines + * the beginning of autumn in the northern hemisphere and + * the beginning of spring in the southern hemisphere. + * + * @property {AstroTime} dec_solstice + * The date and time of the December solstice in the given calendar year. + * This is the moment in December that the Sun reaches its most negative + * declination value. + * At this moment the Earth's south pole is tilted most toward the Sun. + * The December solstice defines + * the beginning of winter in the northern hemisphere and + * the beginning of summer in the southern hemisphere. + */ +class SeasonInfo { + constructor(mar_equinox, jun_solstice, sep_equinox, dec_solstice) { + this.mar_equinox = mar_equinox; + this.jun_solstice = jun_solstice; + this.sep_equinox = sep_equinox; + this.dec_solstice = dec_solstice; + } +} +exports.SeasonInfo = SeasonInfo; +/** + * @brief Finds the equinoxes and solstices for a given calendar year. + * + * @param {number | AstroTime} year + * The integer value or `AstroTime` object that specifies + * the UTC calendar year for which to find equinoxes and solstices. + * + * @returns {SeasonInfo} + */ +function Seasons(year) { + function find(targetLon, month, day) { + let startDate = new Date(Date.UTC(year, month - 1, day)); + let time = SearchSunLongitude(targetLon, startDate, 20); + if (!time) + throw `Cannot find season change near ${startDate.toISOString()}`; + return time; + } + if ((year instanceof Date) && Number.isFinite(year.getTime())) + year = year.getUTCFullYear(); + if (!Number.isSafeInteger(year)) + throw `Cannot calculate seasons because year argument ${year} is neither a Date nor a safe integer.`; + let mar_equinox = find(0, 3, 10); + let jun_solstice = find(90, 6, 10); + let sep_equinox = find(180, 9, 10); + let dec_solstice = find(270, 12, 10); + return new SeasonInfo(mar_equinox, jun_solstice, sep_equinox, dec_solstice); +} +exports.Seasons = Seasons; +/** + * @brief The viewing conditions of a body relative to the Sun. + * + * Represents the angular separation of a body from the Sun as seen from the Earth + * and the relative ecliptic longitudes between that body and the Earth as seen from the Sun. + * + * @property {AstroTime} time + * The date and time of the observation. + * + * @property {string} visibility + * Either `"morning"` or `"evening"`, + * indicating when the body is most easily seen. + * + * @property {number} elongation + * The angle in degrees, as seen from the center of the Earth, + * of the apparent separation between the body and the Sun. + * This angle is measured in 3D space and is not projected onto the ecliptic plane. + * When `elongation` is less than a few degrees, the body is very + * difficult to see from the Earth because it is lost in the Sun's glare. + * The elongation is always in the range [0, 180]. + * + * @property {number} ecliptic_separation + * The absolute value of the difference between the body's ecliptic longitude + * and the Sun's ecliptic longitude, both as seen from the center of the Earth. + * This angle measures around the plane of the Earth's orbit (the ecliptic), + * and ignores how far above or below that plane the body is. + * The ecliptic separation is measured in degrees and is always in the range [0, 180]. + * + * @see {@link Elongation} + */ +class ElongationEvent { + constructor(time, visibility, elongation, ecliptic_separation) { + this.time = time; + this.visibility = visibility; + this.elongation = elongation; + this.ecliptic_separation = ecliptic_separation; + } +} +exports.ElongationEvent = ElongationEvent; +/** + * @brief Calculates the viewing conditions of a body relative to the Sun. + * + * Calculates angular separation of a body from the Sun as seen from the Earth + * and the relative ecliptic longitudes between that body and the Earth as seen from the Sun. + * See the return type {@link ElongationEvent} for details. + * + * This function is helpful for determining how easy + * it is to view a planet away from the Sun's glare on a given date. + * It also determines whether the object is visible in the morning or evening; + * this is more important the smaller the elongation is. + * It is also used to determine how far a planet is from opposition, conjunction, or quadrature. + * + * @param {Body} body + * The name of the observed body. Not allowed to be `Body.Earth`. + * + * @param {FlexibleDateTime} date + * The date and time of the observation. + * + * @returns {ElongationEvent} + */ +function Elongation(body, date) { + let time = MakeTime(date); + let lon = PairLongitude(body, Body.Sun, time); + let vis; + if (lon > 180) { + vis = 'morning'; + lon = 360 - lon; + } + else { + vis = 'evening'; + } + let angle = AngleFromSun(body, time); + return new ElongationEvent(time, vis, angle, lon); +} +exports.Elongation = Elongation; +/** + * @brief Finds the next time Mercury or Venus reaches maximum elongation. + * + * Searches for the next maximum elongation event for Mercury or Venus + * that occurs after the given start date. Calling with other values + * of `body` will result in an exception. + * Maximum elongation occurs when the body has the greatest + * angular separation from the Sun, as seen from the Earth. + * Returns an `ElongationEvent` object containing the date and time of the next + * maximum elongation, the elongation in degrees, and whether + * the body is visible in the morning or evening. + * + * @param {Body} body + * Either `Body.Mercury` or `Body.Venus`. + * + * @param {FlexibleDateTime} startDate + * The date and time after which to search for the next maximum elongation event. + * + * @returns {ElongationEvent} + */ +function SearchMaxElongation(body, startDate) { + const dt = 0.01; + function neg_slope(t) { + // The slope de/dt goes from positive to negative at the maximum elongation event. + // But Search() is designed for functions that ascend through zero. + // So this function returns the negative slope. + const t1 = t.AddDays(-dt / 2); + const t2 = t.AddDays(+dt / 2); + let e1 = AngleFromSun(body, t1); + let e2 = AngleFromSun(body, t2); + let m = (e1 - e2) / dt; + return m; + } + let startTime = MakeTime(startDate); + const table = { + Mercury: { s1: 50.0, s2: 85.0 }, + Venus: { s1: 40.0, s2: 50.0 } + }; + const planet = table[body]; + if (!planet) + throw 'SearchMaxElongation works for Mercury and Venus only.'; + let iter = 0; + while (++iter <= 2) { + // Find current heliocentric relative longitude between the + // inferior planet and the Earth. + let plon = EclipticLongitude(body, startTime); + let elon = EclipticLongitude(Body.Earth, startTime); + let rlon = LongitudeOffset(plon - elon); // clamp to (-180, +180] + // The slope function is not well-behaved when rlon is near 0 degrees or 180 degrees + // because there is a cusp there that causes a discontinuity in the derivative. + // So we need to guard against searching near such times. + let rlon_lo, rlon_hi, adjust_days; + if (rlon >= -planet.s1 && rlon < +planet.s1) { + // Seek to the window [+s1, +s2]. + adjust_days = 0; + // Search forward for the time t1 when rel lon = +s1. + rlon_lo = +planet.s1; + // Search forward for the time t2 when rel lon = +s2. + rlon_hi = +planet.s2; + } + else if (rlon >= +planet.s2 || rlon < -planet.s2) { + // Seek to the next search window at [-s2, -s1]. + adjust_days = 0; + // Search forward for the time t1 when rel lon = -s2. + rlon_lo = -planet.s2; + // Search forward for the time t2 when rel lon = -s1. + rlon_hi = -planet.s1; + } + else if (rlon >= 0) { + // rlon must be in the middle of the window [+s1, +s2]. + // Search BACKWARD for the time t1 when rel lon = +s1. + adjust_days = -SynodicPeriod(body) / 4; + rlon_lo = +planet.s1; + rlon_hi = +planet.s2; + // Search forward from t1 to find t2 such that rel lon = +s2. + } + else { + // rlon must be in the middle of the window [-s2, -s1]. + // Search BACKWARD for the time t1 when rel lon = -s2. + adjust_days = -SynodicPeriod(body) / 4; + rlon_lo = -planet.s2; + // Search forward from t1 to find t2 such that rel lon = -s1. + rlon_hi = -planet.s1; + } + let t_start = startTime.AddDays(adjust_days); + let t1 = SearchRelativeLongitude(body, rlon_lo, t_start); + let t2 = SearchRelativeLongitude(body, rlon_hi, t1); + // Now we have a time range [t1,t2] that brackets a maximum elongation event. + // Confirm the bracketing. + let m1 = neg_slope(t1); + if (m1 >= 0) + throw `SearchMaxElongation: internal error: m1 = ${m1}`; + let m2 = neg_slope(t2); + if (m2 <= 0) + throw `SearchMaxElongation: internal error: m2 = ${m2}`; + // Use the generic search algorithm to home in on where the slope crosses from negative to positive. + let tx = Search(neg_slope, t1, t2, { init_f1: m1, init_f2: m2, dt_tolerance_seconds: 10 }); + if (!tx) + throw `SearchMaxElongation: failed search iter ${iter} (t1=${t1.toString()}, t2=${t2.toString()})`; + if (tx.tt >= startTime.tt) + return Elongation(body, tx); + // This event is in the past (earlier than startDate). + // We need to search forward from t2 to find the next possible window. + // We never need to search more than twice. + startTime = t2.AddDays(1); + } + throw `SearchMaxElongation: failed to find event after 2 tries.`; +} +exports.SearchMaxElongation = SearchMaxElongation; +/** + * @brief Searches for the date and time Venus will next appear brightest as seen from the Earth. + * + * @param {Body} body + * Currently only `Body.Venus` is supported. + * Mercury's peak magnitude occurs at superior conjunction, when it is impossible to see from Earth, + * so peak magnitude events have little practical value for that planet. + * The Moon reaches peak magnitude very close to full moon, which can be found using + * {@link SearchMoonQuarter} or {@link SearchMoonPhase}. + * The other planets reach peak magnitude very close to opposition, + * which can be found using {@link SearchRelativeLongitude}. + * + * @param {FlexibleDateTime} startDate + * The date and time after which to find the next peak magnitude event. + * + * @returns {IlluminationInfo} + */ +function SearchPeakMagnitude(body, startDate) { + if (body !== Body.Venus) + throw 'SearchPeakMagnitude currently works for Venus only.'; + const dt = 0.01; + function slope(t) { + // The Search() function finds a transition from negative to positive values. + // The derivative of magnitude y with respect to time t (dy/dt) + // is negative as an object gets brighter, because the magnitude numbers + // get smaller. At peak magnitude dy/dt = 0, then as the object gets dimmer, + // dy/dt > 0. + const t1 = t.AddDays(-dt / 2); + const t2 = t.AddDays(+dt / 2); + const y1 = Illumination(body, t1).mag; + const y2 = Illumination(body, t2).mag; + const m = (y2 - y1) / dt; + return m; + } + let startTime = MakeTime(startDate); + // s1 and s2 are relative longitudes within which peak magnitude of Venus can occur. + const s1 = 10.0; + const s2 = 30.0; + let iter = 0; + while (++iter <= 2) { + // Find current heliocentric relative longitude between the + // inferior planet and the Earth. + let plon = EclipticLongitude(body, startTime); + let elon = EclipticLongitude(Body.Earth, startTime); + let rlon = LongitudeOffset(plon - elon); // clamp to (-180, +180] + // The slope function is not well-behaved when rlon is near 0 degrees or 180 degrees + // because there is a cusp there that causes a discontinuity in the derivative. + // So we need to guard against searching near such times. + let rlon_lo, rlon_hi, adjust_days; + if (rlon >= -s1 && rlon < +s1) { + // Seek to the window [+s1, +s2]. + adjust_days = 0; + // Search forward for the time t1 when rel lon = +s1. + rlon_lo = +s1; + // Search forward for the time t2 when rel lon = +s2. + rlon_hi = +s2; + } + else if (rlon >= +s2 || rlon < -s2) { + // Seek to the next search window at [-s2, -s1]. + adjust_days = 0; + // Search forward for the time t1 when rel lon = -s2. + rlon_lo = -s2; + // Search forward for the time t2 when rel lon = -s1. + rlon_hi = -s1; + } + else if (rlon >= 0) { + // rlon must be in the middle of the window [+s1, +s2]. + // Search BACKWARD for the time t1 when rel lon = +s1. + adjust_days = -SynodicPeriod(body) / 4; + rlon_lo = +s1; + // Search forward from t1 to find t2 such that rel lon = +s2. + rlon_hi = +s2; + } + else { + // rlon must be in the middle of the window [-s2, -s1]. + // Search BACKWARD for the time t1 when rel lon = -s2. + adjust_days = -SynodicPeriod(body) / 4; + rlon_lo = -s2; + // Search forward from t1 to find t2 such that rel lon = -s1. + rlon_hi = -s1; + } + let t_start = startTime.AddDays(adjust_days); + let t1 = SearchRelativeLongitude(body, rlon_lo, t_start); + let t2 = SearchRelativeLongitude(body, rlon_hi, t1); + // Now we have a time range [t1,t2] that brackets a maximum magnitude event. + // Confirm the bracketing. + let m1 = slope(t1); + if (m1 >= 0) + throw `SearchPeakMagnitude: internal error: m1 = ${m1}`; + let m2 = slope(t2); + if (m2 <= 0) + throw `SearchPeakMagnitude: internal error: m2 = ${m2}`; + // Use the generic search algorithm to home in on where the slope crosses from negative to positive. + let tx = Search(slope, t1, t2, { init_f1: m1, init_f2: m2, dt_tolerance_seconds: 10 }); + if (!tx) + throw `SearchPeakMagnitude: failed search iter ${iter} (t1=${t1.toString()}, t2=${t2.toString()})`; + if (tx.tt >= startTime.tt) + return Illumination(body, tx); + // This event is in the past (earlier than startDate). + // We need to search forward from t2 to find the next possible window. + // We never need to search more than twice. + startTime = t2.AddDays(1); + } + throw `SearchPeakMagnitude: failed to find event after 2 tries.`; +} +exports.SearchPeakMagnitude = SearchPeakMagnitude; +/** + * @brief The two kinds of apsis: pericenter (closest) and apocenter (farthest). + * + * `Pericenter`: The body is at its closest distance to the object it orbits. + * `Apocenter`: The body is at its farthest distance from the object it orbits. + * + * @enum {number} + */ +var ApsisKind; +(function (ApsisKind) { + ApsisKind[ApsisKind["Pericenter"] = 0] = "Pericenter"; + ApsisKind[ApsisKind["Apocenter"] = 1] = "Apocenter"; +})(ApsisKind = exports.ApsisKind || (exports.ApsisKind = {})); +/** + * @brief A closest or farthest point in a body's orbit around its primary. + * + * For a planet orbiting the Sun, apsis is a perihelion or aphelion, respectively. + * For the Moon orbiting the Earth, apsis is a perigee or apogee, respectively. + * + * @property {AstroTime} time + * The date and time of the apsis. + * + * @property {ApsisKind} kind + * For a closest approach (perigee or perihelion), `kind` is `ApsisKind.Pericenter`. + * For a farthest distance event (apogee or aphelion), `kind` is `ApsisKind.Apocenter`. + * + * @property {number} dist_au + * The distance between the centers of the two bodies in astronomical units (AU). + * + * @property {number} dist_km + * The distance between the centers of the two bodies in kilometers. + * + * @see {@link SearchLunarApsis} + * @see {@link NextLunarApsis} + * @see {@link SearchPlanetApsis} + * @see {@link NextPlanetApsis} + */ +class Apsis { + constructor(time, kind, dist_au) { + this.time = time; + this.kind = kind; + this.dist_au = dist_au; + this.dist_km = dist_au * exports.KM_PER_AU; + } +} +exports.Apsis = Apsis; +/** + * @brief Finds the next perigee or apogee of the Moon. + * + * Finds the next perigee (closest approach) or apogee (farthest remove) of the Moon + * that occurs after the specified date and time. + * + * @param {FlexibleDateTime} startDate + * The date and time after which to find the next perigee or apogee. + * + * @returns {Apsis} + */ +function SearchLunarApsis(startDate) { + const dt = 0.001; + function distance_slope(t) { + let t1 = t.AddDays(-dt / 2); + let t2 = t.AddDays(+dt / 2); + let r1 = CalcMoon(t1).distance_au; + let r2 = CalcMoon(t2).distance_au; + let m = (r2 - r1) / dt; + return m; + } + function negative_distance_slope(t) { + return -distance_slope(t); + } + // Check the rate of change of the distance dr/dt at the start time. + // If it is positive, the Moon is currently getting farther away, + // so start looking for apogee. + // Conversely, if dr/dt < 0, start looking for perigee. + // Either way, the polarity of the slope will change, so the product will be negative. + // Handle the crazy corner case of exactly touching zero by checking for m1*m2 <= 0. + let t1 = MakeTime(startDate); + let m1 = distance_slope(t1); + const increment = 5; // number of days to skip in each iteration + for (var iter = 0; iter * increment < 2 * MEAN_SYNODIC_MONTH; ++iter) { + let t2 = t1.AddDays(increment); + let m2 = distance_slope(t2); + if (m1 * m2 <= 0) { + // The time range [t1, t2] contains an apsis. + // Figure out whether it is perigee or apogee. + if (m1 < 0 || m2 > 0) { + // We found a minimum distance event: perigee. + // Search the time range [t1, t2] for the time when the slope goes + // from negative to positive. + let tx = Search(distance_slope, t1, t2, { init_f1: m1, init_f2: m2 }); + if (!tx) + throw 'SearchLunarApsis INTERNAL ERROR: perigee search failed!'; + let dist = CalcMoon(tx).distance_au; + return new Apsis(tx, 0, dist); + } + if (m1 > 0 || m2 < 0) { + // We found a maximum distance event: apogee. + // Search the time range [t1, t2] for the time when the slope goes + // from positive to negative. + let tx = Search(negative_distance_slope, t1, t2, { init_f1: -m1, init_f2: -m2 }); + if (!tx) + throw 'SearchLunarApsis INTERNAL ERROR: apogee search failed!'; + let dist = CalcMoon(tx).distance_au; + return new Apsis(tx, 1, dist); + } + // This should never happen; it should not be possible for consecutive + // times t1 and t2 to both have zero slope. + throw 'SearchLunarApsis INTERNAL ERROR: cannot classify apsis event!'; + } + t1 = t2; + m1 = m2; + } + // It should not be possible to fail to find an apsis within 2 synodic months. + throw 'SearchLunarApsis INTERNAL ERROR: could not find apsis within 2 synodic months of start date.'; +} +exports.SearchLunarApsis = SearchLunarApsis; +/** + * @brief Finds the next lunar apsis (perigee or apogee) in a series. + * + * Given a lunar apsis returned by an initial call to {@link SearchLunarApsis}, + * or a previous call to `NextLunarApsis`, finds the next lunar apsis. + * If the given apsis is a perigee, this function finds the next apogee, and vice versa. + * + * @param {Apsis} apsis + * A lunar perigee or apogee event. + * + * @returns {Apsis} + * The successor apogee for the given perigee, or the successor perigee for the given apogee. + */ +function NextLunarApsis(apsis) { + const skip = 11; // number of days to skip to start looking for next apsis event + let next = SearchLunarApsis(apsis.time.AddDays(skip)); + if (next.kind + apsis.kind !== 1) + throw `NextLunarApsis INTERNAL ERROR: did not find alternating apogee/perigee: prev=${apsis.kind} @ ${apsis.time.toString()}, next=${next.kind} @ ${next.time.toString()}`; + return next; +} +exports.NextLunarApsis = NextLunarApsis; +function PlanetExtreme(body, kind, start_time, dayspan) { + const direction = (kind === ApsisKind.Apocenter) ? +1.0 : -1.0; + const npoints = 10; + for (;;) { + const interval = dayspan / (npoints - 1); + // iterate until uncertainty is less than one minute + if (interval < 1.0 / 1440.0) { + const apsis_time = start_time.AddDays(interval / 2.0); + const dist_au = HelioDistance(body, apsis_time); + return new Apsis(apsis_time, kind, dist_au); + } + let best_i = -1; + let best_dist = 0.0; + for (let i = 0; i < npoints; ++i) { + const time = start_time.AddDays(i * interval); + const dist = direction * HelioDistance(body, time); + if (i == 0 || dist > best_dist) { + best_i = i; + best_dist = dist; + } + } + /* Narrow in on the extreme point. */ + start_time = start_time.AddDays((best_i - 1) * interval); + dayspan = 2.0 * interval; + } +} +function BruteSearchPlanetApsis(body, startTime) { + /* + Neptune is a special case for two reasons: + 1. Its orbit is nearly circular (low orbital eccentricity). + 2. It is so distant from the Sun that the orbital period is very long. + Put together, this causes wobbling of the Sun around the Solar System Barycenter (SSB) + to be so significant that there are 3 local minima in the distance-vs-time curve + near each apsis. Therefore, unlike for other planets, we can't use an optimized + algorithm for finding dr/dt = 0. + Instead, we use a dumb, brute-force algorithm of sampling and finding min/max + heliocentric distance. + + There is a similar problem in the TOP2013 model for Pluto: + Its position vector has high-frequency oscillations that confuse the + slope-based determination of apsides. + */ + /* + Rewind approximately 30 degrees in the orbit, + then search forward for 270 degrees. + This is a very cautious way to prevent missing an apsis. + Typically we will find two apsides, and we pick whichever + apsis is ealier, but after startTime. + Sample points around this orbital arc and find when the distance + is greatest and smallest. + */ + const npoints = 100; + const t1 = startTime.AddDays(Planet[body].OrbitalPeriod * (-30 / 360)); + const t2 = startTime.AddDays(Planet[body].OrbitalPeriod * (+270 / 360)); + let t_min = t1; + let t_max = t1; + let min_dist = -1.0; + let max_dist = -1.0; + const interval = (t2.ut - t1.ut) / (npoints - 1); + for (let i = 0; i < npoints; ++i) { + const time = t1.AddDays(i * interval); + const dist = HelioDistance(body, time); + if (i === 0) { + max_dist = min_dist = dist; + } + else { + if (dist > max_dist) { + max_dist = dist; + t_max = time; + } + if (dist < min_dist) { + min_dist = dist; + t_min = time; + } + } + } + const perihelion = PlanetExtreme(body, 0, t_min.AddDays(-2 * interval), 4 * interval); + const aphelion = PlanetExtreme(body, 1, t_max.AddDays(-2 * interval), 4 * interval); + if (perihelion.time.tt >= startTime.tt) { + if (aphelion.time.tt >= startTime.tt && aphelion.time.tt < perihelion.time.tt) + return aphelion; + return perihelion; + } + if (aphelion.time.tt >= startTime.tt) + return aphelion; + throw 'Internal error: failed to find Neptune apsis.'; +} +/** + * @brief Finds the next perihelion or aphelion of a planet. + * + * Finds the date and time of a planet's perihelion (closest approach to the Sun) + * or aphelion (farthest distance from the Sun) after a given time. + * + * Given a date and time to start the search in `startTime`, this function finds the + * next date and time that the center of the specified planet reaches the closest or farthest point + * in its orbit with respect to the center of the Sun, whichever comes first + * after `startTime`. + * + * The closest point is called *perihelion* and the farthest point is called *aphelion*. + * The word *apsis* refers to either event. + * + * To iterate through consecutive alternating perihelion and aphelion events, + * call `SearchPlanetApsis` once, then use the return value to call + * {@link NextPlanetApsis}. After that, keep feeding the previous return value + * from `NextPlanetApsis` into another call of `NextPlanetApsis` + * as many times as desired. + * + * @param {Body} body + * The planet for which to find the next perihelion/aphelion event. + * Not allowed to be `Body.Sun` or `Body.Moon`. + * + * @param {FlexibleDateTime} startTime + * The date and time at which to start searching for the next perihelion or aphelion. + * + * @returns {Apsis} + * The next perihelion or aphelion that occurs after `startTime`. + */ +function SearchPlanetApsis(body, startTime) { + startTime = MakeTime(startTime); + if (body === Body.Neptune || body === Body.Pluto) + return BruteSearchPlanetApsis(body, startTime); + function positive_slope(t) { + const dt = 0.001; + let t1 = t.AddDays(-dt / 2); + let t2 = t.AddDays(+dt / 2); + let r1 = HelioDistance(body, t1); + let r2 = HelioDistance(body, t2); + let m = (r2 - r1) / dt; + return m; + } + function negative_slope(t) { + return -positive_slope(t); + } + const orbit_period_days = Planet[body].OrbitalPeriod; + const increment = orbit_period_days / 6.0; + let t1 = startTime; + let m1 = positive_slope(t1); + for (let iter = 0; iter * increment < 2.0 * orbit_period_days; ++iter) { + const t2 = t1.AddDays(increment); + const m2 = positive_slope(t2); + if (m1 * m2 <= 0.0) { + /* There is a change of slope polarity within the time range [t1, t2]. */ + /* Therefore this time range contains an apsis. */ + /* Figure out whether it is perihelion or aphelion. */ + let slope_func; + let kind; + if (m1 < 0.0 || m2 > 0.0) { + /* We found a minimum-distance event: perihelion. */ + /* Search the time range for the time when the slope goes from negative to positive. */ + slope_func = positive_slope; + kind = ApsisKind.Pericenter; + } + else if (m1 > 0.0 || m2 < 0.0) { + /* We found a maximum-distance event: aphelion. */ + /* Search the time range for the time when the slope goes from positive to negative. */ + slope_func = negative_slope; + kind = ApsisKind.Apocenter; + } + else { + /* This should never happen. It should not be possible for both slopes to be zero. */ + throw "Internal error with slopes in SearchPlanetApsis"; + } + const search = Search(slope_func, t1, t2); + if (!search) + throw "Failed to find slope transition in planetary apsis search."; + const dist = HelioDistance(body, search); + return new Apsis(search, kind, dist); + } + /* We have not yet found a slope polarity change. Keep searching. */ + t1 = t2; + m1 = m2; + } + throw "Internal error: should have found planetary apsis within 2 orbital periods."; +} +exports.SearchPlanetApsis = SearchPlanetApsis; +/** + * @brief Finds the next planetary perihelion or aphelion event in a series. + * + * This function requires an {@link Apsis} value obtained from a call + * to {@link SearchPlanetApsis} or `NextPlanetApsis`. + * Given an aphelion event, this function finds the next perihelion event, and vice versa. + * See {@link SearchPlanetApsis} for more details. + * + * @param {Body} body + * The planet for which to find the next perihelion/aphelion event. + * Not allowed to be `Body.Sun` or `Body.Moon`. + * Must match the body passed into the call that produced the `apsis` parameter. + * + * @param {Apsis} apsis + * An apsis event obtained from a call to {@link SearchPlanetApsis} or `NextPlanetApsis`. + * + * @returns {Apsis} + * Same as the return value for {@link SearchPlanetApsis}. + */ +function NextPlanetApsis(body, apsis) { + if (apsis.kind !== ApsisKind.Pericenter && apsis.kind !== ApsisKind.Apocenter) + throw `Invalid apsis kind: ${apsis.kind}`; + /* skip 1/4 of an orbit before starting search again */ + const skip = 0.25 * Planet[body].OrbitalPeriod; + const time = apsis.time.AddDays(skip); + const next = SearchPlanetApsis(body, time); + /* Verify that we found the opposite apsis from the previous one. */ + if (next.kind + apsis.kind !== 1) + throw `Internal error: previous apsis was ${apsis.kind}, but found ${next.kind} for next apsis.`; + return next; +} +exports.NextPlanetApsis = NextPlanetApsis; +/** + * @brief Calculates the inverse of a rotation matrix. + * + * Given a rotation matrix that performs some coordinate transform, + * this function returns the matrix that reverses that transform. + * + * @param {RotationMatrix} rotation + * The rotation matrix to be inverted. + * + * @returns {RotationMatrix} + * The inverse rotation matrix. + */ +function InverseRotation(rotation) { + return new RotationMatrix([ + [rotation.rot[0][0], rotation.rot[1][0], rotation.rot[2][0]], + [rotation.rot[0][1], rotation.rot[1][1], rotation.rot[2][1]], + [rotation.rot[0][2], rotation.rot[1][2], rotation.rot[2][2]] + ]); +} +exports.InverseRotation = InverseRotation; +/** + * @brief Creates a rotation based on applying one rotation followed by another. + * + * Given two rotation matrices, returns a combined rotation matrix that is + * equivalent to rotating based on the first matrix, followed by the second. + * + * @param {RotationMatrix} a + * The first rotation to apply. + * + * @param {RotationMatrix} b + * The second rotation to apply. + * + * @returns {RotationMatrix} + * The combined rotation matrix. + */ +function CombineRotation(a, b) { + /* + Use matrix multiplication: c = b*a. + We put 'b' on the left and 'a' on the right because, + just like when you use a matrix M to rotate a vector V, + you put the M on the left in the product M*V. + We can think of this as 'b' rotating all the 3 column vectors in 'a'. + */ + return new RotationMatrix([ + [ + b.rot[0][0] * a.rot[0][0] + b.rot[1][0] * a.rot[0][1] + b.rot[2][0] * a.rot[0][2], + b.rot[0][1] * a.rot[0][0] + b.rot[1][1] * a.rot[0][1] + b.rot[2][1] * a.rot[0][2], + b.rot[0][2] * a.rot[0][0] + b.rot[1][2] * a.rot[0][1] + b.rot[2][2] * a.rot[0][2] + ], + [ + b.rot[0][0] * a.rot[1][0] + b.rot[1][0] * a.rot[1][1] + b.rot[2][0] * a.rot[1][2], + b.rot[0][1] * a.rot[1][0] + b.rot[1][1] * a.rot[1][1] + b.rot[2][1] * a.rot[1][2], + b.rot[0][2] * a.rot[1][0] + b.rot[1][2] * a.rot[1][1] + b.rot[2][2] * a.rot[1][2] + ], + [ + b.rot[0][0] * a.rot[2][0] + b.rot[1][0] * a.rot[2][1] + b.rot[2][0] * a.rot[2][2], + b.rot[0][1] * a.rot[2][0] + b.rot[1][1] * a.rot[2][1] + b.rot[2][1] * a.rot[2][2], + b.rot[0][2] * a.rot[2][0] + b.rot[1][2] * a.rot[2][1] + b.rot[2][2] * a.rot[2][2] + ] + ]); +} +exports.CombineRotation = CombineRotation; +/** + * @brief Creates an identity rotation matrix. + * + * Returns a rotation matrix that has no effect on orientation. + * This matrix can be the starting point for other operations, + * such as using a series of calls to {@link Pivot} to + * create a custom rotation matrix. + * + * @returns {RotationMatrix} + * The identity matrix. + */ +function IdentityMatrix() { + return new RotationMatrix([ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1] + ]); +} +exports.IdentityMatrix = IdentityMatrix; +/** +* @brief Re-orients a rotation matrix by pivoting it by an angle around one of its axes. +* +* Given a rotation matrix, a selected coordinate axis, and an angle in degrees, +* this function pivots the rotation matrix by that angle around that coordinate axis. +* +* For example, if you have rotation matrix that converts ecliptic coordinates (ECL) +* to horizontal coordinates (HOR), but you really want to convert ECL to the orientation +* of a telescope camera pointed at a given body, you can use `Astronomy_Pivot` twice: +* (1) pivot around the zenith axis by the body's azimuth, then (2) pivot around the +* western axis by the body's altitude angle. The resulting rotation matrix will then +* reorient ECL coordinates to the orientation of your telescope camera. +* +* @param {RotationMatrix} rotation +* The input rotation matrix. +* +* @param {number} axis +* An integer that selects which coordinate axis to rotate around: +* 0 = x, 1 = y, 2 = z. Any other value will cause an exception. +* +* @param {number} angle +* An angle in degrees indicating the amount of rotation around the specified axis. +* Positive angles indicate rotation counterclockwise as seen from the positive +* direction along that axis, looking towards the origin point of the orientation system. +* Any finite number of degrees is allowed, but best precision will result from +* keeping `angle` in the range [-360, +360]. +* +* @returns {RotationMatrix} +* A pivoted matrix object. +*/ +function Pivot(rotation, axis, angle) { + // Check for an invalid coordinate axis. + if (axis !== 0 && axis !== 1 && axis !== 2) + throw `Invalid axis ${axis}. Must be [0, 1, 2].`; + const radians = VerifyNumber(angle) * exports.DEG2RAD; + const c = Math.cos(radians); + const s = Math.sin(radians); + /* + We need to maintain the "right-hand" rule, no matter which + axis was selected. That means we pick (i, j, k) axis order + such that the following vector cross product is satisfied: + i x j = k + */ + const i = (axis + 1) % 3; + const j = (axis + 2) % 3; + const k = axis; + let rot = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]; + rot[i][i] = c * rotation.rot[i][i] - s * rotation.rot[i][j]; + rot[i][j] = s * rotation.rot[i][i] + c * rotation.rot[i][j]; + rot[i][k] = rotation.rot[i][k]; + rot[j][i] = c * rotation.rot[j][i] - s * rotation.rot[j][j]; + rot[j][j] = s * rotation.rot[j][i] + c * rotation.rot[j][j]; + rot[j][k] = rotation.rot[j][k]; + rot[k][i] = c * rotation.rot[k][i] - s * rotation.rot[k][j]; + rot[k][j] = s * rotation.rot[k][i] + c * rotation.rot[k][j]; + rot[k][k] = rotation.rot[k][k]; + return new RotationMatrix(rot); +} +exports.Pivot = Pivot; +/** + * @brief Converts spherical coordinates to Cartesian coordinates. + * + * Given spherical coordinates and a time at which they are valid, + * returns a vector of Cartesian coordinates. The returned value + * includes the time, as required by `AstroTime`. + * + * @param {Spherical} sphere + * Spherical coordinates to be converted. + * + * @param {FlexibleDateTime} time + * The time that should be included in the returned vector. + * + * @returns {Vector} + * The vector form of the supplied spherical coordinates. + */ +function VectorFromSphere(sphere, time) { + time = MakeTime(time); + const radlat = sphere.lat * exports.DEG2RAD; + const radlon = sphere.lon * exports.DEG2RAD; + const rcoslat = sphere.dist * Math.cos(radlat); + return new Vector(rcoslat * Math.cos(radlon), rcoslat * Math.sin(radlon), sphere.dist * Math.sin(radlat), time); +} +exports.VectorFromSphere = VectorFromSphere; +/** + * @brief Given an equatorial vector, calculates equatorial angular coordinates. + * + * @param {Vector} vec + * A vector in an equatorial coordinate system. + * + * @returns {EquatorialCoordinates} + * Angular coordinates expressed in the same equatorial system as `vec`. + */ +function EquatorFromVector(vec) { + const sphere = SphereFromVector(vec); + return new EquatorialCoordinates(sphere.lon / 15, sphere.lat, sphere.dist, vec); +} +exports.EquatorFromVector = EquatorFromVector; +/** + * @brief Converts Cartesian coordinates to spherical coordinates. + * + * Given a Cartesian vector, returns latitude, longitude, and distance. + * + * @param {Vector} vector + * Cartesian vector to be converted to spherical coordinates. + * + * @returns {Spherical} + * Spherical coordinates that are equivalent to the given vector. + */ +function SphereFromVector(vector) { + const xyproj = vector.x * vector.x + vector.y * vector.y; + const dist = Math.sqrt(xyproj + vector.z * vector.z); + let lat, lon; + if (xyproj === 0.0) { + if (vector.z === 0.0) + throw 'Zero-length vector not allowed.'; + lon = 0.0; + lat = (vector.z < 0.0) ? -90.0 : +90.0; + } + else { + lon = exports.RAD2DEG * Math.atan2(vector.y, vector.x); + if (lon < 0.0) + lon += 360.0; + lat = exports.RAD2DEG * Math.atan2(vector.z, Math.sqrt(xyproj)); + } + return new Spherical(lat, lon, dist); +} +exports.SphereFromVector = SphereFromVector; +function ToggleAzimuthDirection(az) { + az = 360.0 - az; + if (az >= 360.0) + az -= 360.0; + else if (az < 0.0) + az += 360.0; + return az; +} +/** + * @brief Converts Cartesian coordinates to horizontal coordinates. + * + * Given a horizontal Cartesian vector, returns horizontal azimuth and altitude. + * + * *IMPORTANT:* This function differs from {@link SphereFromVector} in two ways: + * - `SphereFromVector` returns a `lon` value that represents azimuth defined counterclockwise + * from north (e.g., west = +90), but this function represents a clockwise rotation + * (e.g., east = +90). The difference is because `SphereFromVector` is intended + * to preserve the vector "right-hand rule", while this function defines azimuth in a more + * traditional way as used in navigation and cartography. + * - This function optionally corrects for atmospheric refraction, while `SphereFromVector` does not. + * + * The returned object contains the azimuth in `lon`. + * It is measured in degrees clockwise from north: east = +90 degrees, west = +270 degrees. + * + * The altitude is stored in `lat`. + * + * The distance to the observed object is stored in `dist`, + * and is expressed in astronomical units (AU). + * + * @param {Vector} vector + * Cartesian vector to be converted to horizontal coordinates. + * + * @param {string} refraction + * `"normal"`: correct altitude for atmospheric refraction (recommended). + * `"jplhor"`: for JPL Horizons compatibility testing only; not recommended for normal use. + * `null`: no atmospheric refraction correction is performed. + * + * @returns {Spherical} + */ +function HorizonFromVector(vector, refraction) { + const sphere = SphereFromVector(vector); + sphere.lon = ToggleAzimuthDirection(sphere.lon); + sphere.lat += Refraction(refraction, sphere.lat); + return sphere; +} +exports.HorizonFromVector = HorizonFromVector; +/** + * @brief Given apparent angular horizontal coordinates in `sphere`, calculate horizontal vector. + * + * @param {Spherical} sphere + * A structure that contains apparent horizontal coordinates: + * `lat` holds the refracted altitude angle, + * `lon` holds the azimuth in degrees clockwise from north, + * and `dist` holds the distance from the observer to the object in AU. + * + * @param {FlexibleDateTime} time + * The date and time of the observation. This is needed because the returned + * vector object requires a valid time value when passed to certain other functions. + * + * @param {string} refraction + * `"normal"`: correct altitude for atmospheric refraction (recommended). + * `"jplhor"`: for JPL Horizons compatibility testing only; not recommended for normal use. + * `null`: no atmospheric refraction correction is performed. + * + * @returns {Vector} + * A vector in the horizontal system: `x` = north, `y` = west, and `z` = zenith (up). + */ +function VectorFromHorizon(sphere, time, refraction) { + time = MakeTime(time); + /* Convert azimuth from clockwise-from-north to counterclockwise-from-north. */ + const lon = ToggleAzimuthDirection(sphere.lon); + /* Reverse any applied refraction. */ + const lat = sphere.lat + InverseRefraction(refraction, sphere.lat); + const xsphere = new Spherical(lat, lon, sphere.dist); + return VectorFromSphere(xsphere, time); +} +exports.VectorFromHorizon = VectorFromHorizon; +/** + * @brief Calculates the amount of "lift" to an altitude angle caused by atmospheric refraction. + * + * Given an altitude angle and a refraction option, calculates + * the amount of "lift" caused by atmospheric refraction. + * This is the number of degrees higher in the sky an object appears + * due to the lensing of the Earth's atmosphere. + * This function works best near sea level. + * To correct for higher elevations, call {@link Atmosphere} for that + * elevation and multiply the refraction angle by the resulting relative density. + * + * @param {string} refraction + * `"normal"`: correct altitude for atmospheric refraction (recommended). + * `"jplhor"`: for JPL Horizons compatibility testing only; not recommended for normal use. + * `null`: no atmospheric refraction correction is performed. + * + * @param {number} altitude + * An altitude angle in a horizontal coordinate system. Must be a value between -90 and +90. + * + * @returns {number} + * The angular adjustment in degrees to be added to the altitude angle to correct for atmospheric lensing. + */ +function Refraction(refraction, altitude) { + let refr; + VerifyNumber(altitude); + if (altitude < -90.0 || altitude > +90.0) + return 0.0; /* no attempt to correct an invalid altitude */ + if (refraction === 'normal' || refraction === 'jplhor') { + // http://extras.springer.com/1999/978-1-4471-0555-8/chap4/horizons/horizons.pdf + // JPL Horizons says it uses refraction algorithm from + // Meeus "Astronomical Algorithms", 1991, p. 101-102. + // I found the following Go implementation: + // https://github.com/soniakeys/meeus/blob/master/v3/refraction/refract.go + // This is a translation from the function "Saemundsson" there. + // I found experimentally that JPL Horizons clamps the angle to 1 degree below the horizon. + // This is important because the 'refr' formula below goes crazy near hd = -5.11. + let hd = altitude; + if (hd < -1.0) + hd = -1.0; + refr = (1.02 / Math.tan((hd + 10.3 / (hd + 5.11)) * exports.DEG2RAD)) / 60.0; + if (refraction === 'normal' && altitude < -1.0) { + // In "normal" mode we gradually reduce refraction toward the nadir + // so that we never get an altitude angle less than -90 degrees. + // When horizon angle is -1 degrees, the factor is exactly 1. + // As altitude approaches -90 (the nadir), the fraction approaches 0 linearly. + refr *= (altitude + 90.0) / 89.0; + } + } + else if (!refraction) { + // The caller does not want refraction correction. + refr = 0.0; + } + else { + throw `Invalid refraction option: ${refraction}`; + } + return refr; +} +exports.Refraction = Refraction; +/** + * @brief Calculates the inverse of an atmospheric refraction angle. + * + * Given an observed altitude angle that includes atmospheric refraction, + * calculates the negative angular correction to obtain the unrefracted + * altitude. This is useful for cases where observed horizontal + * coordinates are to be converted to another orientation system, + * but refraction first must be removed from the observed position. + * + * @param {string} refraction + * `"normal"`: correct altitude for atmospheric refraction (recommended). + * `"jplhor"`: for JPL Horizons compatibility testing only; not recommended for normal use. + * `null`: no atmospheric refraction correction is performed. + * + * @param {number} bent_altitude + * The apparent altitude that includes atmospheric refraction. + * + * @returns {number} + * The angular adjustment in degrees to be added to the + * altitude angle to correct for atmospheric lensing. + * This will be less than or equal to zero. + */ +function InverseRefraction(refraction, bent_altitude) { + if (bent_altitude < -90.0 || bent_altitude > +90.0) + return 0.0; /* no attempt to correct an invalid altitude */ + /* Find the pre-adjusted altitude whose refraction correction leads to 'altitude'. */ + let altitude = bent_altitude - Refraction(refraction, bent_altitude); + for (;;) { + /* See how close we got. */ + let diff = (altitude + Refraction(refraction, altitude)) - bent_altitude; + if (Math.abs(diff) < 1.0e-14) + return altitude - bent_altitude; + altitude -= diff; + } +} +exports.InverseRefraction = InverseRefraction; +/** + * @brief Applies a rotation to a vector, yielding a rotated vector. + * + * This function transforms a vector in one orientation to a vector + * in another orientation. + * + * @param {RotationMatrix} rotation + * A rotation matrix that specifies how the orientation of the vector is to be changed. + * + * @param {Vector} vector + * The vector whose orientation is to be changed. + * + * @returns {Vector} + * A vector in the orientation specified by `rotation`. + */ +function RotateVector(rotation, vector) { + return new Vector(rotation.rot[0][0] * vector.x + rotation.rot[1][0] * vector.y + rotation.rot[2][0] * vector.z, rotation.rot[0][1] * vector.x + rotation.rot[1][1] * vector.y + rotation.rot[2][1] * vector.z, rotation.rot[0][2] * vector.x + rotation.rot[1][2] * vector.y + rotation.rot[2][2] * vector.z, vector.t); +} +exports.RotateVector = RotateVector; +/** + * @brief Applies a rotation to a state vector, yielding a rotated vector. + * + * This function transforms a state vector in one orientation to a vector + * in another orientation. + * + * @param {RotationMatrix} rotation + * A rotation matrix that specifies how the orientation of the state vector is to be changed. + * + * @param {StateVector} state + * The state vector whose orientation is to be changed. + * Both the position and velocity components are transformed. + * + * @return {StateVector} + * A state vector in the orientation specified by `rotation`. + */ +function RotateState(rotation, state) { + return new StateVector(rotation.rot[0][0] * state.x + rotation.rot[1][0] * state.y + rotation.rot[2][0] * state.z, rotation.rot[0][1] * state.x + rotation.rot[1][1] * state.y + rotation.rot[2][1] * state.z, rotation.rot[0][2] * state.x + rotation.rot[1][2] * state.y + rotation.rot[2][2] * state.z, rotation.rot[0][0] * state.vx + rotation.rot[1][0] * state.vy + rotation.rot[2][0] * state.vz, rotation.rot[0][1] * state.vx + rotation.rot[1][1] * state.vy + rotation.rot[2][1] * state.vz, rotation.rot[0][2] * state.vx + rotation.rot[1][2] * state.vy + rotation.rot[2][2] * state.vz, state.t); +} +exports.RotateState = RotateState; +/** + * @brief Calculates a rotation matrix from J2000 mean equator (EQJ) to J2000 mean ecliptic (ECL). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQJ = equatorial system, using equator at J2000 epoch. + * Target: ECL = ecliptic system, using equator at J2000 epoch. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQJ to ECL. + */ +function Rotation_EQJ_ECL() { + /* ob = mean obliquity of the J2000 ecliptic = 0.40909260059599012 radians. */ + const c = 0.9174821430670688; /* cos(ob) */ + const s = 0.3977769691083922; /* sin(ob) */ + return new RotationMatrix([ + [1, 0, 0], + [0, +c, -s], + [0, +s, +c] + ]); +} +exports.Rotation_EQJ_ECL = Rotation_EQJ_ECL; +/** + * @brief Calculates a rotation matrix from J2000 mean ecliptic (ECL) to J2000 mean equator (EQJ). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: ECL = ecliptic system, using equator at J2000 epoch. + * Target: EQJ = equatorial system, using equator at J2000 epoch. + * + * @returns {RotationMatrix} + * A rotation matrix that converts ECL to EQJ. + */ +function Rotation_ECL_EQJ() { + /* ob = mean obliquity of the J2000 ecliptic = 0.40909260059599012 radians. */ + const c = 0.9174821430670688; /* cos(ob) */ + const s = 0.3977769691083922; /* sin(ob) */ + return new RotationMatrix([ + [1, 0, 0], + [0, +c, +s], + [0, -s, +c] + ]); +} +exports.Rotation_ECL_EQJ = Rotation_ECL_EQJ; +/** + * @brief Calculates a rotation matrix from J2000 mean equator (EQJ) to equatorial of-date (EQD). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQJ = equatorial system, using equator at J2000 epoch. + * Target: EQD = equatorial system, using equator of the specified date/time. + * + * @param {FlexibleDateTime} time + * The date and time at which the Earth's equator defines the target orientation. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQJ to EQD at `time`. + */ +function Rotation_EQJ_EQD(time) { + time = MakeTime(time); + const prec = precession_rot(time, PrecessDirection.From2000); + const nut = nutation_rot(time, PrecessDirection.From2000); + return CombineRotation(prec, nut); +} +exports.Rotation_EQJ_EQD = Rotation_EQJ_EQD; +/** + * @brief Calculates a rotation matrix from J2000 mean equator (EQJ) to true ecliptic of date (ECT). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQJ = equatorial system, using equator at J2000 epoch. + * Target: ECT = ecliptic system, using true equinox of the specified date/time. + * + * @param {FlexibleDateTime} time + * The date and time at which the Earth's equator defines the target orientation. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQJ to ECT at `time`. + */ +function Rotation_EQJ_ECT(time) { + const t = MakeTime(time); + const rot = Rotation_EQJ_EQD(t); + const step = Rotation_EQD_ECT(t); + return CombineRotation(rot, step); +} +exports.Rotation_EQJ_ECT = Rotation_EQJ_ECT; +/** + * @brief Calculates a rotation matrix from true ecliptic of date (ECT) to J2000 mean equator (EQJ). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: ECT = ecliptic system, using true equinox of the specified date/time. + * Target: EQJ = equatorial system, using equator at J2000 epoch. + * + * @param {FlexibleDateTime} time + * The date and time at which the Earth's equator defines the target orientation. + * + * @returns {RotationMatrix} + * A rotation matrix that converts ECT to EQJ at `time`. + */ +function Rotation_ECT_EQJ(time) { + const t = MakeTime(time); + const rot = Rotation_ECT_EQD(t); + const step = Rotation_EQD_EQJ(t); + return CombineRotation(rot, step); +} +exports.Rotation_ECT_EQJ = Rotation_ECT_EQJ; +/** + * @brief Calculates a rotation matrix from equatorial of-date (EQD) to J2000 mean equator (EQJ). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQD = equatorial system, using equator of the specified date/time. + * Target: EQJ = equatorial system, using equator at J2000 epoch. + * + * @param {FlexibleDateTime} time + * The date and time at which the Earth's equator defines the source orientation. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQD at `time` to EQJ. + */ +function Rotation_EQD_EQJ(time) { + time = MakeTime(time); + const nut = nutation_rot(time, PrecessDirection.Into2000); + const prec = precession_rot(time, PrecessDirection.Into2000); + return CombineRotation(nut, prec); +} +exports.Rotation_EQD_EQJ = Rotation_EQD_EQJ; +/** + * @brief Calculates a rotation matrix from equatorial of-date (EQD) to horizontal (HOR). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQD = equatorial system, using equator of the specified date/time. + * Target: HOR = horizontal system. + * + * Use `HorizonFromVector` to convert the return value + * to a traditional altitude/azimuth pair. + * + * @param {FlexibleDateTime} time + * The date and time at which the Earth's equator applies. + * + * @param {Observer} observer + * A location near the Earth's mean sea level that defines the observer's horizon. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQD to HOR at `time` and for `observer`. + * The components of the horizontal vector are: + * x = north, y = west, z = zenith (straight up from the observer). + * These components are chosen so that the "right-hand rule" works for the vector + * and so that north represents the direction where azimuth = 0. + */ +function Rotation_EQD_HOR(time, observer) { + time = MakeTime(time); + const sinlat = Math.sin(observer.latitude * exports.DEG2RAD); + const coslat = Math.cos(observer.latitude * exports.DEG2RAD); + const sinlon = Math.sin(observer.longitude * exports.DEG2RAD); + const coslon = Math.cos(observer.longitude * exports.DEG2RAD); + const uze = [coslat * coslon, coslat * sinlon, sinlat]; + const une = [-sinlat * coslon, -sinlat * sinlon, coslat]; + const uwe = [sinlon, -coslon, 0]; + const spin_angle = -15 * sidereal_time(time); + const uz = spin(spin_angle, uze); + const un = spin(spin_angle, une); + const uw = spin(spin_angle, uwe); + return new RotationMatrix([ + [un[0], uw[0], uz[0]], + [un[1], uw[1], uz[1]], + [un[2], uw[2], uz[2]], + ]); +} +exports.Rotation_EQD_HOR = Rotation_EQD_HOR; +/** + * @brief Calculates a rotation matrix from horizontal (HOR) to equatorial of-date (EQD). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: HOR = horizontal system (x=North, y=West, z=Zenith). + * Target: EQD = equatorial system, using equator of the specified date/time. + * + * @param {FlexibleDateTime} time + * The date and time at which the Earth's equator applies. + * + * @param {Observer} observer + * A location near the Earth's mean sea level that defines the observer's horizon. + * + * @returns {RotationMatrix} + * A rotation matrix that converts HOR to EQD at `time` and for `observer`. + */ +function Rotation_HOR_EQD(time, observer) { + const rot = Rotation_EQD_HOR(time, observer); + return InverseRotation(rot); +} +exports.Rotation_HOR_EQD = Rotation_HOR_EQD; +/** + * @brief Calculates a rotation matrix from horizontal (HOR) to J2000 equatorial (EQJ). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: HOR = horizontal system (x=North, y=West, z=Zenith). + * Target: EQJ = equatorial system, using equator at the J2000 epoch. + * + * @param {FlexibleDateTime} time + * The date and time of the observation. + * + * @param {Observer} observer + * A location near the Earth's mean sea level that defines the observer's horizon. + * + * @returns {RotationMatrix} + * A rotation matrix that converts HOR to EQJ at `time` and for `observer`. + */ +function Rotation_HOR_EQJ(time, observer) { + time = MakeTime(time); + const hor_eqd = Rotation_HOR_EQD(time, observer); + const eqd_eqj = Rotation_EQD_EQJ(time); + return CombineRotation(hor_eqd, eqd_eqj); +} +exports.Rotation_HOR_EQJ = Rotation_HOR_EQJ; +/** + * @brief Calculates a rotation matrix from J2000 mean equator (EQJ) to horizontal (HOR). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQJ = equatorial system, using the equator at the J2000 epoch. + * Target: HOR = horizontal system. + * + * Use {@link HorizonFromVector} to convert the return value + * to a traditional altitude/azimuth pair. + * + * @param {FlexibleDateTime} time + * The date and time of the desired horizontal orientation. + * + * @param {Observer} observer + * A location near the Earth's mean sea level that defines the observer's horizon. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQJ to HOR at `time` and for `observer`. + * The components of the horizontal vector are: + * x = north, y = west, z = zenith (straight up from the observer). + * These components are chosen so that the "right-hand rule" works for the vector + * and so that north represents the direction where azimuth = 0. + */ +function Rotation_EQJ_HOR(time, observer) { + const rot = Rotation_HOR_EQJ(time, observer); + return InverseRotation(rot); +} +exports.Rotation_EQJ_HOR = Rotation_EQJ_HOR; +/** + * @brief Calculates a rotation matrix from equatorial of-date (EQD) to J2000 mean ecliptic (ECL). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQD = equatorial system, using equator of date. + * Target: ECL = ecliptic system, using equator at J2000 epoch. + * + * @param {FlexibleDateTime} time + * The date and time of the source equator. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQD to ECL. + */ +function Rotation_EQD_ECL(time) { + const eqd_eqj = Rotation_EQD_EQJ(time); + const eqj_ecl = Rotation_EQJ_ECL(); + return CombineRotation(eqd_eqj, eqj_ecl); +} +exports.Rotation_EQD_ECL = Rotation_EQD_ECL; +/** + * @brief Calculates a rotation matrix from J2000 mean ecliptic (ECL) to equatorial of-date (EQD). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: ECL = ecliptic system, using equator at J2000 epoch. + * Target: EQD = equatorial system, using equator of date. + * + * @param {FlexibleDateTime} time + * The date and time of the desired equator. + * + * @returns {RotationMatrix} + * A rotation matrix that converts ECL to EQD. + */ +function Rotation_ECL_EQD(time) { + const rot = Rotation_EQD_ECL(time); + return InverseRotation(rot); +} +exports.Rotation_ECL_EQD = Rotation_ECL_EQD; +/** + * @brief Calculates a rotation matrix from J2000 mean ecliptic (ECL) to horizontal (HOR). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: ECL = ecliptic system, using equator at J2000 epoch. + * Target: HOR = horizontal system. + * + * Use {@link HorizonFromVector} to convert the return value + * to a traditional altitude/azimuth pair. + * + * @param {FlexibleDateTime} time + * The date and time of the desired horizontal orientation. + * + * @param {Observer} observer + * A location near the Earth's mean sea level that defines the observer's horizon. + * + * @returns {RotationMatrix} + * A rotation matrix that converts ECL to HOR at `time` and for `observer`. + * The components of the horizontal vector are: + * x = north, y = west, z = zenith (straight up from the observer). + * These components are chosen so that the "right-hand rule" works for the vector + * and so that north represents the direction where azimuth = 0. + */ +function Rotation_ECL_HOR(time, observer) { + time = MakeTime(time); + const ecl_eqd = Rotation_ECL_EQD(time); + const eqd_hor = Rotation_EQD_HOR(time, observer); + return CombineRotation(ecl_eqd, eqd_hor); +} +exports.Rotation_ECL_HOR = Rotation_ECL_HOR; +/** + * @brief Calculates a rotation matrix from horizontal (HOR) to J2000 mean ecliptic (ECL). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: HOR = horizontal system. + * Target: ECL = ecliptic system, using equator at J2000 epoch. + * + * @param {FlexibleDateTime} time + * The date and time of the horizontal observation. + * + * @param {Observer} observer + * The location of the horizontal observer. + * + * @returns {RotationMatrix} + * A rotation matrix that converts HOR to ECL. + */ +function Rotation_HOR_ECL(time, observer) { + const rot = Rotation_ECL_HOR(time, observer); + return InverseRotation(rot); +} +exports.Rotation_HOR_ECL = Rotation_HOR_ECL; +/** + * @brief Calculates a rotation matrix from J2000 mean equator (EQJ) to galactic (GAL). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQJ = equatorial system, using the equator at the J2000 epoch. + * Target: GAL = galactic system (IAU 1958 definition). + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQJ to GAL. + */ +function Rotation_EQJ_GAL() { + // This rotation matrix was calculated by the following script + // in this same source code repository: + // demo/python/galeqj_matrix.py + return new RotationMatrix([ + [-0.0548624779711344, +0.4941095946388765, -0.8676668813529025], + [-0.8734572784246782, -0.4447938112296831, -0.1980677870294097], + [-0.4838000529948520, +0.7470034631630423, +0.4559861124470794] + ]); +} +exports.Rotation_EQJ_GAL = Rotation_EQJ_GAL; +/** + * @brief Calculates a rotation matrix from galactic (GAL) to J2000 mean equator (EQJ). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: GAL = galactic system (IAU 1958 definition). + * Target: EQJ = equatorial system, using the equator at the J2000 epoch. + * + * @returns {RotationMatrix} + * A rotation matrix that converts GAL to EQJ. + */ +function Rotation_GAL_EQJ() { + // This rotation matrix was calculated by the following script + // in this same source code repository: + // demo/python/galeqj_matrix.py + return new RotationMatrix([ + [-0.0548624779711344, -0.8734572784246782, -0.4838000529948520], + [+0.4941095946388765, -0.4447938112296831, +0.7470034631630423], + [-0.8676668813529025, -0.1980677870294097, +0.4559861124470794] + ]); +} +exports.Rotation_GAL_EQJ = Rotation_GAL_EQJ; +/** + * @brief Calculates a rotation matrix from true ecliptic of date (ECT) to equator of date (EQD). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: ECT = true ecliptic of date + * Target: EQD = equator of date + * + * @param {FlexibleDateTime} time + * The date and time of the ecliptic/equator conversion. + * + * @returns {RotationMatrix} + * A rotation matrix that converts ECT to EQD. + */ +function Rotation_ECT_EQD(time) { + const et = e_tilt(MakeTime(time)); + const tobl = et.tobl * exports.DEG2RAD; + const c = Math.cos(tobl); + const s = Math.sin(tobl); + return new RotationMatrix([ + [1.0, 0.0, 0.0], + [0.0, +c, +s], + [0.0, -s, +c] + ]); +} +exports.Rotation_ECT_EQD = Rotation_ECT_EQD; +/** + * @brief Calculates a rotation matrix from equator of date (EQD) to true ecliptic of date (ECT). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQD = equator of date + * Target: ECT = true ecliptic of date + * + * @param {FlexibleDateTime} time + * The date and time of the equator/ecliptic conversion. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQD to ECT. + */ +function Rotation_EQD_ECT(time) { + const et = e_tilt(MakeTime(time)); + const tobl = et.tobl * exports.DEG2RAD; + const c = Math.cos(tobl); + const s = Math.sin(tobl); + return new RotationMatrix([ + [1.0, 0.0, 0.0], + [0.0, +c, -s], + [0.0, +s, +c] + ]); +} +exports.Rotation_EQD_ECT = Rotation_EQD_ECT; +const ConstelNames = [ + ['And', 'Andromeda'] // 0 + , + ['Ant', 'Antila'] // 1 + , + ['Aps', 'Apus'] // 2 + , + ['Aql', 'Aquila'] // 3 + , + ['Aqr', 'Aquarius'] // 4 + , + ['Ara', 'Ara'] // 5 + , + ['Ari', 'Aries'] // 6 + , + ['Aur', 'Auriga'] // 7 + , + ['Boo', 'Bootes'] // 8 + , + ['Cae', 'Caelum'] // 9 + , + ['Cam', 'Camelopardis'] // 10 + , + ['Cap', 'Capricornus'] // 11 + , + ['Car', 'Carina'] // 12 + , + ['Cas', 'Cassiopeia'] // 13 + , + ['Cen', 'Centaurus'] // 14 + , + ['Cep', 'Cepheus'] // 15 + , + ['Cet', 'Cetus'] // 16 + , + ['Cha', 'Chamaeleon'] // 17 + , + ['Cir', 'Circinus'] // 18 + , + ['CMa', 'Canis Major'] // 19 + , + ['CMi', 'Canis Minor'] // 20 + , + ['Cnc', 'Cancer'] // 21 + , + ['Col', 'Columba'] // 22 + , + ['Com', 'Coma Berenices'] // 23 + , + ['CrA', 'Corona Australis'] // 24 + , + ['CrB', 'Corona Borealis'] // 25 + , + ['Crt', 'Crater'] // 26 + , + ['Cru', 'Crux'] // 27 + , + ['Crv', 'Corvus'] // 28 + , + ['CVn', 'Canes Venatici'] // 29 + , + ['Cyg', 'Cygnus'] // 30 + , + ['Del', 'Delphinus'] // 31 + , + ['Dor', 'Dorado'] // 32 + , + ['Dra', 'Draco'] // 33 + , + ['Equ', 'Equuleus'] // 34 + , + ['Eri', 'Eridanus'] // 35 + , + ['For', 'Fornax'] // 36 + , + ['Gem', 'Gemini'] // 37 + , + ['Gru', 'Grus'] // 38 + , + ['Her', 'Hercules'] // 39 + , + ['Hor', 'Horologium'] // 40 + , + ['Hya', 'Hydra'] // 41 + , + ['Hyi', 'Hydrus'] // 42 + , + ['Ind', 'Indus'] // 43 + , + ['Lac', 'Lacerta'] // 44 + , + ['Leo', 'Leo'] // 45 + , + ['Lep', 'Lepus'] // 46 + , + ['Lib', 'Libra'] // 47 + , + ['LMi', 'Leo Minor'] // 48 + , + ['Lup', 'Lupus'] // 49 + , + ['Lyn', 'Lynx'] // 50 + , + ['Lyr', 'Lyra'] // 51 + , + ['Men', 'Mensa'] // 52 + , + ['Mic', 'Microscopium'] // 53 + , + ['Mon', 'Monoceros'] // 54 + , + ['Mus', 'Musca'] // 55 + , + ['Nor', 'Norma'] // 56 + , + ['Oct', 'Octans'] // 57 + , + ['Oph', 'Ophiuchus'] // 58 + , + ['Ori', 'Orion'] // 59 + , + ['Pav', 'Pavo'] // 60 + , + ['Peg', 'Pegasus'] // 61 + , + ['Per', 'Perseus'] // 62 + , + ['Phe', 'Phoenix'] // 63 + , + ['Pic', 'Pictor'] // 64 + , + ['PsA', 'Pisces Austrinus'] // 65 + , + ['Psc', 'Pisces'] // 66 + , + ['Pup', 'Puppis'] // 67 + , + ['Pyx', 'Pyxis'] // 68 + , + ['Ret', 'Reticulum'] // 69 + , + ['Scl', 'Sculptor'] // 70 + , + ['Sco', 'Scorpius'] // 71 + , + ['Sct', 'Scutum'] // 72 + , + ['Ser', 'Serpens'] // 73 + , + ['Sex', 'Sextans'] // 74 + , + ['Sge', 'Sagitta'] // 75 + , + ['Sgr', 'Sagittarius'] // 76 + , + ['Tau', 'Taurus'] // 77 + , + ['Tel', 'Telescopium'] // 78 + , + ['TrA', 'Triangulum Australe'] // 79 + , + ['Tri', 'Triangulum'] // 80 + , + ['Tuc', 'Tucana'] // 81 + , + ['UMa', 'Ursa Major'] // 82 + , + ['UMi', 'Ursa Minor'] // 83 + , + ['Vel', 'Vela'] // 84 + , + ['Vir', 'Virgo'] // 85 + , + ['Vol', 'Volans'] // 86 + , + ['Vul', 'Vulpecula'] // 87 +]; +const ConstelBounds = [ + [83, 0, 8640, 2112] // UMi + , + [83, 2880, 5220, 2076] // UMi + , + [83, 7560, 8280, 2068] // UMi + , + [83, 6480, 7560, 2064] // UMi + , + [15, 0, 2880, 2040] // Cep + , + [10, 3300, 3840, 1968] // Cam + , + [15, 0, 1800, 1920] // Cep + , + [10, 3840, 5220, 1920] // Cam + , + [83, 6300, 6480, 1920] // UMi + , + [33, 7260, 7560, 1920] // Dra + , + [15, 0, 1263, 1848] // Cep + , + [10, 4140, 4890, 1848] // Cam + , + [83, 5952, 6300, 1800] // UMi + , + [15, 7260, 7440, 1800] // Cep + , + [10, 2868, 3300, 1764] // Cam + , + [33, 3300, 4080, 1764] // Dra + , + [83, 4680, 5952, 1680] // UMi + , + [13, 1116, 1230, 1632] // Cas + , + [33, 7350, 7440, 1608] // Dra + , + [33, 4080, 4320, 1596] // Dra + , + [15, 0, 120, 1584] // Cep + , + [83, 5040, 5640, 1584] // UMi + , + [15, 8490, 8640, 1584] // Cep + , + [33, 4320, 4860, 1536] // Dra + , + [33, 4860, 5190, 1512] // Dra + , + [15, 8340, 8490, 1512] // Cep + , + [10, 2196, 2520, 1488] // Cam + , + [33, 7200, 7350, 1476] // Dra + , + [15, 7393.2, 7416, 1462] // Cep + , + [10, 2520, 2868, 1440] // Cam + , + [82, 2868, 3030, 1440] // UMa + , + [33, 7116, 7200, 1428] // Dra + , + [15, 7200, 7393.2, 1428] // Cep + , + [15, 8232, 8340, 1418] // Cep + , + [13, 0, 876, 1404] // Cas + , + [33, 6990, 7116, 1392] // Dra + , + [13, 612, 687, 1380] // Cas + , + [13, 876, 1116, 1368] // Cas + , + [10, 1116, 1140, 1368] // Cam + , + [15, 8034, 8232, 1350] // Cep + , + [10, 1800, 2196, 1344] // Cam + , + [82, 5052, 5190, 1332] // UMa + , + [33, 5190, 6990, 1332] // Dra + , + [10, 1140, 1200, 1320] // Cam + , + [15, 7968, 8034, 1320] // Cep + , + [15, 7416, 7908, 1316] // Cep + , + [13, 0, 612, 1296] // Cas + , + [50, 2196, 2340, 1296] // Lyn + , + [82, 4350, 4860, 1272] // UMa + , + [33, 5490, 5670, 1272] // Dra + , + [15, 7908, 7968, 1266] // Cep + , + [10, 1200, 1800, 1260] // Cam + , + [13, 8232, 8400, 1260] // Cas + , + [33, 5670, 6120, 1236] // Dra + , + [62, 735, 906, 1212] // Per + , + [33, 6120, 6564, 1212] // Dra + , + [13, 0, 492, 1200] // Cas + , + [62, 492, 600, 1200] // Per + , + [50, 2340, 2448, 1200] // Lyn + , + [13, 8400, 8640, 1200] // Cas + , + [82, 4860, 5052, 1164] // UMa + , + [13, 0, 402, 1152] // Cas + , + [13, 8490, 8640, 1152] // Cas + , + [39, 6543, 6564, 1140] // Her + , + [33, 6564, 6870, 1140] // Dra + , + [30, 6870, 6900, 1140] // Cyg + , + [62, 600, 735, 1128] // Per + , + [82, 3030, 3300, 1128] // UMa + , + [13, 60, 312, 1104] // Cas + , + [82, 4320, 4350, 1080] // UMa + , + [50, 2448, 2652, 1068] // Lyn + , + [30, 7887, 7908, 1056] // Cyg + , + [30, 7875, 7887, 1050] // Cyg + , + [30, 6900, 6984, 1044] // Cyg + , + [82, 3300, 3660, 1008] // UMa + , + [82, 3660, 3882, 960] // UMa + , + [8, 5556, 5670, 960] // Boo + , + [39, 5670, 5880, 960] // Her + , + [50, 3330, 3450, 954] // Lyn + , + [0, 0, 906, 882] // And + , + [62, 906, 924, 882] // Per + , + [51, 6969, 6984, 876] // Lyr + , + [62, 1620, 1689, 864] // Per + , + [30, 7824, 7875, 864] // Cyg + , + [44, 7875, 7920, 864] // Lac + , + [7, 2352, 2652, 852] // Aur + , + [50, 2652, 2790, 852] // Lyn + , + [0, 0, 720, 840] // And + , + [44, 7920, 8214, 840] // Lac + , + [44, 8214, 8232, 828] // Lac + , + [0, 8232, 8460, 828] // And + , + [62, 924, 978, 816] // Per + , + [82, 3882, 3960, 816] // UMa + , + [29, 4320, 4440, 816] // CVn + , + [50, 2790, 3330, 804] // Lyn + , + [48, 3330, 3558, 804] // LMi + , + [0, 258, 507, 792] // And + , + [8, 5466, 5556, 792] // Boo + , + [0, 8460, 8550, 770] // And + , + [29, 4440, 4770, 768] // CVn + , + [0, 8550, 8640, 752] // And + , + [29, 5025, 5052, 738] // CVn + , + [80, 870, 978, 736] // Tri + , + [62, 978, 1620, 736] // Per + , + [7, 1620, 1710, 720] // Aur + , + [51, 6543, 6969, 720] // Lyr + , + [82, 3960, 4320, 696] // UMa + , + [30, 7080, 7530, 696] // Cyg + , + [7, 1710, 2118, 684] // Aur + , + [48, 3558, 3780, 684] // LMi + , + [29, 4770, 5025, 684] // CVn + , + [0, 0, 24, 672] // And + , + [80, 507, 600, 672] // Tri + , + [7, 2118, 2352, 672] // Aur + , + [37, 2838, 2880, 672] // Gem + , + [30, 7530, 7824, 672] // Cyg + , + [30, 6933, 7080, 660] // Cyg + , + [80, 690, 870, 654] // Tri + , + [25, 5820, 5880, 648] // CrB + , + [8, 5430, 5466, 624] // Boo + , + [25, 5466, 5820, 624] // CrB + , + [51, 6612, 6792, 624] // Lyr + , + [48, 3870, 3960, 612] // LMi + , + [51, 6792, 6933, 612] // Lyr + , + [80, 600, 690, 600] // Tri + , + [66, 258, 306, 570] // Psc + , + [48, 3780, 3870, 564] // LMi + , + [87, 7650, 7710, 564] // Vul + , + [77, 2052, 2118, 548] // Tau + , + [0, 24, 51, 528] // And + , + [73, 5730, 5772, 528] // Ser + , + [37, 2118, 2238, 516] // Gem + , + [87, 7140, 7290, 510] // Vul + , + [87, 6792, 6930, 506] // Vul + , + [0, 51, 306, 504] // And + , + [87, 7290, 7404, 492] // Vul + , + [37, 2811, 2838, 480] // Gem + , + [87, 7404, 7650, 468] // Vul + , + [87, 6930, 7140, 460] // Vul + , + [6, 1182, 1212, 456] // Ari + , + [75, 6792, 6840, 444] // Sge + , + [59, 2052, 2076, 432] // Ori + , + [37, 2238, 2271, 420] // Gem + , + [75, 6840, 7140, 388] // Sge + , + [77, 1788, 1920, 384] // Tau + , + [39, 5730, 5790, 384] // Her + , + [75, 7140, 7290, 378] // Sge + , + [77, 1662, 1788, 372] // Tau + , + [77, 1920, 2016, 372] // Tau + , + [23, 4620, 4860, 360] // Com + , + [39, 6210, 6570, 344] // Her + , + [23, 4272, 4620, 336] // Com + , + [37, 2700, 2811, 324] // Gem + , + [39, 6030, 6210, 308] // Her + , + [61, 0, 51, 300] // Peg + , + [77, 2016, 2076, 300] // Tau + , + [37, 2520, 2700, 300] // Gem + , + [61, 7602, 7680, 300] // Peg + , + [37, 2271, 2496, 288] // Gem + , + [39, 6570, 6792, 288] // Her + , + [31, 7515, 7578, 284] // Del + , + [61, 7578, 7602, 284] // Peg + , + [45, 4146, 4272, 264] // Leo + , + [59, 2247, 2271, 240] // Ori + , + [37, 2496, 2520, 240] // Gem + , + [21, 2811, 2853, 240] // Cnc + , + [61, 8580, 8640, 240] // Peg + , + [6, 600, 1182, 238] // Ari + , + [31, 7251, 7308, 204] // Del + , + [8, 4860, 5430, 192] // Boo + , + [61, 8190, 8580, 180] // Peg + , + [21, 2853, 3330, 168] // Cnc + , + [45, 3330, 3870, 168] // Leo + , + [58, 6570, 6718.4, 150] // Oph + , + [3, 6718.4, 6792, 150] // Aql + , + [31, 7500, 7515, 144] // Del + , + [20, 2520, 2526, 132] // CMi + , + [73, 6570, 6633, 108] // Ser + , + [39, 5790, 6030, 96] // Her + , + [58, 6570, 6633, 72] // Oph + , + [61, 7728, 7800, 66] // Peg + , + [66, 0, 720, 48] // Psc + , + [73, 6690, 6792, 48] // Ser + , + [31, 7308, 7500, 48] // Del + , + [34, 7500, 7680, 48] // Equ + , + [61, 7680, 7728, 48] // Peg + , + [61, 7920, 8190, 48] // Peg + , + [61, 7800, 7920, 42] // Peg + , + [20, 2526, 2592, 36] // CMi + , + [77, 1290, 1662, 0] // Tau + , + [59, 1662, 1680, 0] // Ori + , + [20, 2592, 2910, 0] // CMi + , + [85, 5280, 5430, 0] // Vir + , + [58, 6420, 6570, 0] // Oph + , + [16, 954, 1182, -42] // Cet + , + [77, 1182, 1290, -42] // Tau + , + [73, 5430, 5856, -78] // Ser + , + [59, 1680, 1830, -96] // Ori + , + [59, 2100, 2247, -96] // Ori + , + [73, 6420, 6468, -96] // Ser + , + [73, 6570, 6690, -96] // Ser + , + [3, 6690, 6792, -96] // Aql + , + [66, 8190, 8580, -96] // Psc + , + [45, 3870, 4146, -144] // Leo + , + [85, 4146, 4260, -144] // Vir + , + [66, 0, 120, -168] // Psc + , + [66, 8580, 8640, -168] // Psc + , + [85, 5130, 5280, -192] // Vir + , + [58, 5730, 5856, -192] // Oph + , + [3, 7200, 7392, -216] // Aql + , + [4, 7680, 7872, -216] // Aqr + , + [58, 6180, 6468, -240] // Oph + , + [54, 2100, 2910, -264] // Mon + , + [35, 1770, 1830, -264] // Eri + , + [59, 1830, 2100, -264] // Ori + , + [41, 2910, 3012, -264] // Hya + , + [74, 3450, 3870, -264] // Sex + , + [85, 4260, 4620, -264] // Vir + , + [58, 6330, 6360, -280] // Oph + , + [3, 6792, 7200, -288.8] // Aql + , + [35, 1740, 1770, -348] // Eri + , + [4, 7392, 7680, -360] // Aqr + , + [73, 6180, 6570, -384] // Ser + , + [72, 6570, 6792, -384] // Sct + , + [41, 3012, 3090, -408] // Hya + , + [58, 5856, 5895, -438] // Oph + , + [41, 3090, 3270, -456] // Hya + , + [26, 3870, 3900, -456] // Crt + , + [71, 5856, 5895, -462] // Sco + , + [47, 5640, 5730, -480] // Lib + , + [28, 4530, 4620, -528] // Crv + , + [85, 4620, 5130, -528] // Vir + , + [41, 3270, 3510, -576] // Hya + , + [16, 600, 954, -585.2] // Cet + , + [35, 954, 1350, -585.2] // Eri + , + [26, 3900, 4260, -588] // Crt + , + [28, 4260, 4530, -588] // Crv + , + [47, 5130, 5370, -588] // Lib + , + [58, 5856, 6030, -590] // Oph + , + [16, 0, 600, -612] // Cet + , + [11, 7680, 7872, -612] // Cap + , + [4, 7872, 8580, -612] // Aqr + , + [16, 8580, 8640, -612] // Cet + , + [41, 3510, 3690, -636] // Hya + , + [35, 1692, 1740, -654] // Eri + , + [46, 1740, 2202, -654] // Lep + , + [11, 7200, 7680, -672] // Cap + , + [41, 3690, 3810, -700] // Hya + , + [41, 4530, 5370, -708] // Hya + , + [47, 5370, 5640, -708] // Lib + , + [71, 5640, 5760, -708] // Sco + , + [35, 1650, 1692, -720] // Eri + , + [58, 6030, 6336, -720] // Oph + , + [76, 6336, 6420, -720] // Sgr + , + [41, 3810, 3900, -748] // Hya + , + [19, 2202, 2652, -792] // CMa + , + [41, 4410, 4530, -792] // Hya + , + [41, 3900, 4410, -840] // Hya + , + [36, 1260, 1350, -864] // For + , + [68, 3012, 3372, -882] // Pyx + , + [35, 1536, 1650, -888] // Eri + , + [76, 6420, 6900, -888] // Sgr + , + [65, 7680, 8280, -888] // PsA + , + [70, 8280, 8400, -888] // Scl + , + [36, 1080, 1260, -950] // For + , + [1, 3372, 3960, -954] // Ant + , + [70, 0, 600, -960] // Scl + , + [36, 600, 1080, -960] // For + , + [35, 1392, 1536, -960] // Eri + , + [70, 8400, 8640, -960] // Scl + , + [14, 5100, 5370, -1008] // Cen + , + [49, 5640, 5760, -1008] // Lup + , + [71, 5760, 5911.5, -1008] // Sco + , + [9, 1740, 1800, -1032] // Cae + , + [22, 1800, 2370, -1032] // Col + , + [67, 2880, 3012, -1032] // Pup + , + [35, 1230, 1392, -1056] // Eri + , + [71, 5911.5, 6420, -1092] // Sco + , + [24, 6420, 6900, -1092] // CrA + , + [76, 6900, 7320, -1092] // Sgr + , + [53, 7320, 7680, -1092] // Mic + , + [35, 1080, 1230, -1104] // Eri + , + [9, 1620, 1740, -1116] // Cae + , + [49, 5520, 5640, -1152] // Lup + , + [63, 0, 840, -1156] // Phe + , + [35, 960, 1080, -1176] // Eri + , + [40, 1470, 1536, -1176] // Hor + , + [9, 1536, 1620, -1176] // Cae + , + [38, 7680, 7920, -1200] // Gru + , + [67, 2160, 2880, -1218] // Pup + , + [84, 2880, 2940, -1218] // Vel + , + [35, 870, 960, -1224] // Eri + , + [40, 1380, 1470, -1224] // Hor + , + [63, 0, 660, -1236] // Phe + , + [12, 2160, 2220, -1260] // Car + , + [84, 2940, 3042, -1272] // Vel + , + [40, 1260, 1380, -1276] // Hor + , + [32, 1380, 1440, -1276] // Dor + , + [63, 0, 570, -1284] // Phe + , + [35, 780, 870, -1296] // Eri + , + [64, 1620, 1800, -1296] // Pic + , + [49, 5418, 5520, -1296] // Lup + , + [84, 3042, 3180, -1308] // Vel + , + [12, 2220, 2340, -1320] // Car + , + [14, 4260, 4620, -1320] // Cen + , + [49, 5100, 5418, -1320] // Lup + , + [56, 5418, 5520, -1320] // Nor + , + [32, 1440, 1560, -1356] // Dor + , + [84, 3180, 3960, -1356] // Vel + , + [14, 3960, 4050, -1356] // Cen + , + [5, 6300, 6480, -1368] // Ara + , + [78, 6480, 7320, -1368] // Tel + , + [38, 7920, 8400, -1368] // Gru + , + [40, 1152, 1260, -1380] // Hor + , + [64, 1800, 1980, -1380] // Pic + , + [12, 2340, 2460, -1392] // Car + , + [63, 0, 480, -1404] // Phe + , + [35, 480, 780, -1404] // Eri + , + [63, 8400, 8640, -1404] // Phe + , + [32, 1560, 1650, -1416] // Dor + , + [56, 5520, 5911.5, -1440] // Nor + , + [43, 7320, 7680, -1440] // Ind + , + [64, 1980, 2160, -1464] // Pic + , + [18, 5460, 5520, -1464] // Cir + , + [5, 5911.5, 5970, -1464] // Ara + , + [18, 5370, 5460, -1526] // Cir + , + [5, 5970, 6030, -1526] // Ara + , + [64, 2160, 2460, -1536] // Pic + , + [12, 2460, 3252, -1536] // Car + , + [14, 4050, 4260, -1536] // Cen + , + [27, 4260, 4620, -1536] // Cru + , + [14, 4620, 5232, -1536] // Cen + , + [18, 4860, 4920, -1560] // Cir + , + [5, 6030, 6060, -1560] // Ara + , + [40, 780, 1152, -1620] // Hor + , + [69, 1152, 1650, -1620] // Ret + , + [18, 5310, 5370, -1620] // Cir + , + [5, 6060, 6300, -1620] // Ara + , + [60, 6300, 6480, -1620] // Pav + , + [81, 7920, 8400, -1620] // Tuc + , + [32, 1650, 2370, -1680] // Dor + , + [18, 4920, 5310, -1680] // Cir + , + [79, 5310, 6120, -1680] // TrA + , + [81, 0, 480, -1800] // Tuc + , + [42, 1260, 1650, -1800] // Hyi + , + [86, 2370, 3252, -1800] // Vol + , + [12, 3252, 4050, -1800] // Car + , + [55, 4050, 4920, -1800] // Mus + , + [60, 6480, 7680, -1800] // Pav + , + [43, 7680, 8400, -1800] // Ind + , + [81, 8400, 8640, -1800] // Tuc + , + [81, 270, 480, -1824] // Tuc + , + [42, 0, 1260, -1980] // Hyi + , + [17, 2760, 4920, -1980] // Cha + , + [2, 4920, 6480, -1980] // Aps + , + [52, 1260, 2760, -2040] // Men + , + [57, 0, 8640, -2160] // Oct +]; +let ConstelRot; +let Epoch2000; +/** + * @brief Reports the constellation that a given celestial point lies within. + * + * @property {string} symbol + * 3-character mnemonic symbol for the constellation, e.g. "Ori". + * + * @property {string} name + * Full name of constellation, e.g. "Orion". + * + * @property {number} ra1875 + * Right ascension expressed in B1875 coordinates. + * + * @property {number} dec1875 + * Declination expressed in B1875 coordinates. + */ +class ConstellationInfo { + constructor(symbol, name, ra1875, dec1875) { + this.symbol = symbol; + this.name = name; + this.ra1875 = ra1875; + this.dec1875 = dec1875; + } +} +exports.ConstellationInfo = ConstellationInfo; +/** + * @brief Determines the constellation that contains the given point in the sky. + * + * Given J2000 equatorial (EQJ) coordinates of a point in the sky, + * determines the constellation that contains that point. + * + * @param {number} ra + * The right ascension (RA) of a point in the sky, using the J2000 equatorial system. + * + * @param {number} dec + * The declination (DEC) of a point in the sky, using the J2000 equatorial system. + * + * @returns {ConstellationInfo} + * An object that contains the 3-letter abbreviation and full name + * of the constellation that contains the given (ra,dec), along with + * the converted B1875 (ra,dec) for that point. + */ +function Constellation(ra, dec) { + VerifyNumber(ra); + VerifyNumber(dec); + if (dec < -90 || dec > +90) + throw 'Invalid declination angle. Must be -90..+90.'; + // Clamp right ascension to [0, 24) sidereal hours. + ra %= 24.0; + if (ra < 0.0) + ra += 24.0; + // Lazy-initialize rotation matrix. + if (!ConstelRot) { + // Need to calculate the B1875 epoch. Based on this: + // https://en.wikipedia.org/wiki/Epoch_(astronomy)#Besselian_years + // B = 1900 + (JD - 2415020.31352) / 365.242198781 + // I'm interested in using TT instead of JD, giving: + // B = 1900 + ((TT+2451545) - 2415020.31352) / 365.242198781 + // B = 1900 + (TT + 36524.68648) / 365.242198781 + // TT = 365.242198781*(B - 1900) - 36524.68648 = -45655.741449525 + // But the AstroTime constructor wants UT, not TT. + // Near that date, I get a historical correction of ut-tt = 3.2 seconds. + // That gives UT = -45655.74141261017 for the B1875 epoch, + // or 1874-12-31T18:12:21.950Z. + ConstelRot = Rotation_EQJ_EQD(new AstroTime(-45655.74141261017)); + Epoch2000 = new AstroTime(0); + } + // Convert coordinates from J2000 to B1875. + const sph2000 = new Spherical(dec, 15.0 * ra, 1.0); + const vec2000 = VectorFromSphere(sph2000, Epoch2000); + const vec1875 = RotateVector(ConstelRot, vec2000); + const equ1875 = EquatorFromVector(vec1875); + // Search for the constellation using the B1875 coordinates. + const fd = 10 / (4 * 60); // conversion factor from compact units to DEC degrees + const fr = fd / 15; // conversion factor from compact units to RA sidereal hours + for (let b of ConstelBounds) { + // Convert compact angular units to RA in hours, DEC in degrees. + const dec = b[3] * fd; + const ra_lo = b[1] * fr; + const ra_hi = b[2] * fr; + if (dec <= equ1875.dec && ra_lo <= equ1875.ra && equ1875.ra < ra_hi) { + const c = ConstelNames[b[0]]; + return new ConstellationInfo(c[0], c[1], equ1875.ra, equ1875.dec); + } + } + // This should never happen! + throw 'Unable to find constellation for given coordinates.'; +} +exports.Constellation = Constellation; +/** + * @brief The different kinds of lunar/solar eclipses.. + * + * `Penumbral`: A lunar eclipse in which only the Earth's penumbra falls on the Moon. (Never used for a solar eclipse.) + * `Partial`: A partial lunar/solar eclipse. + * `Annular`: A solar eclipse in which the entire Moon is visible against the Sun, but the Sun appears as a ring around the Moon. (Never used for a lunar eclipse.) + * `Total`: A total lunar/solar eclipse. + * + * @enum {string} + */ +var EclipseKind; +(function (EclipseKind) { + EclipseKind["Penumbral"] = "penumbral"; + EclipseKind["Partial"] = "partial"; + EclipseKind["Annular"] = "annular"; + EclipseKind["Total"] = "total"; +})(EclipseKind = exports.EclipseKind || (exports.EclipseKind = {})); +/** + * @brief Returns information about a lunar eclipse. + * + * Returned by {@link SearchLunarEclipse} or {@link NextLunarEclipse} + * to report information about a lunar eclipse event. + * When a lunar eclipse is found, it is classified as penumbral, partial, or total. + * Penumbral eclipses are difficult to observe, because the Moon is only slightly dimmed + * by the Earth's penumbra; no part of the Moon touches the Earth's umbra. + * Partial eclipses occur when part, but not all, of the Moon touches the Earth's umbra. + * Total eclipses occur when the entire Moon passes into the Earth's umbra. + * + * The `kind` field thus holds one of the enum values `EclipseKind.Penumbral`, `EclipseKind.Partial`, + * or `EclipseKind.Total`, depending on the kind of lunar eclipse found. + * + * The `obscuration` field holds a value in the range [0, 1] that indicates what fraction + * of the Moon's apparent disc area is covered by the Earth's umbra at the eclipse's peak. + * This indicates how dark the peak eclipse appears. For penumbral eclipses, the obscuration + * is 0, because the Moon does not pass through the Earth's umbra. For partial eclipses, + * the obscuration is somewhere between 0 and 1. For total lunar eclipses, the obscuration is 1. + * + * Field `peak` holds the date and time of the peak of the eclipse, when it is at its peak. + * + * Fields `sd_penum`, `sd_partial`, and `sd_total` hold the semi-duration of each phase + * of the eclipse, which is half of the amount of time the eclipse spends in each + * phase (expressed in minutes), or 0 if the eclipse never reaches that phase. + * By converting from minutes to days, and subtracting/adding with `peak`, the caller + * may determine the date and time of the beginning/end of each eclipse phase. + * + * @property {EclipseKind} kind + * The type of lunar eclipse found. + * + * @property {number} obscuration + * The peak fraction of the Moon's apparent disc that is covered by the Earth's umbra. + * + * @property {AstroTime} peak + * The time of the eclipse at its peak. + * + * @property {number} sd_penum + * The semi-duration of the penumbral phase in minutes. + * + * @property {number} sd_partial + * The semi-duration of the penumbral phase in minutes, or 0.0 if none. + * + * @property {number} sd_total + * The semi-duration of the penumbral phase in minutes, or 0.0 if none. + * + */ +class LunarEclipseInfo { + constructor(kind, obscuration, peak, sd_penum, sd_partial, sd_total) { + this.kind = kind; + this.obscuration = obscuration; + this.peak = peak; + this.sd_penum = sd_penum; + this.sd_partial = sd_partial; + this.sd_total = sd_total; + } +} +exports.LunarEclipseInfo = LunarEclipseInfo; +/** + * @ignore + * + * @brief Represents the relative alignment of the Earth and another body, and their respective shadows. + * + * This is an internal data structure used to assist calculation of + * lunar eclipses, solar eclipses, and transits of Mercury and Venus. + * + * Definitions: + * + * casting body = A body that casts a shadow of interest, possibly striking another body. + * + * receiving body = A body on which the shadow of another body might land. + * + * shadow axis = The line passing through the center of the Sun and the center of the casting body. + * + * shadow plane = The plane passing through the center of a receiving body, + * and perpendicular to the shadow axis. + * + * @property {AstroTime} time + * The time associated with the shadow calculation. + * + * @property {number} u + * The distance [au] between the center of the casting body and the shadow plane. + * + * @property {number} r + * The distance [km] between center of receiving body and the shadow axis. + * + * @property {number} k + * The umbra radius [km] at the shadow plane. + * + * @property {number} p + * The penumbra radius [km] at the shadow plane. + * + * @property {Vector} target + * The location in space where we are interested in determining how close a shadow falls. + * For example, when calculating lunar eclipses, `target` would be the center of the Moon + * expressed in geocentric coordinates. Then we can evaluate how far the center of the Earth's + * shadow cone approaches the center of the Moon. + * The vector components are expressed in [au]. + * + * @property {Vector} dir + * The direction in space that the shadow points away from the center of a shadow-casting body. + * This vector lies on the shadow axis and points away from the Sun. + * In other words: the direction light from the Sun would be traveling, + * except that the center of a body (Earth, Moon, Mercury, or Venus) is blocking it. + * The distance units do not matter, because the vector will be normalized. + */ +class ShadowInfo { + constructor(time, u, r, k, p, target, dir) { + this.time = time; + this.u = u; + this.r = r; + this.k = k; + this.p = p; + this.target = target; + this.dir = dir; + } +} +function CalcShadow(body_radius_km, time, target, dir) { + const u = (dir.x * target.x + dir.y * target.y + dir.z * target.z) / (dir.x * dir.x + dir.y * dir.y + dir.z * dir.z); + const dx = (u * dir.x) - target.x; + const dy = (u * dir.y) - target.y; + const dz = (u * dir.z) - target.z; + const r = exports.KM_PER_AU * Math.hypot(dx, dy, dz); + const k = +SUN_RADIUS_KM - (1.0 + u) * (SUN_RADIUS_KM - body_radius_km); + const p = -SUN_RADIUS_KM + (1.0 + u) * (SUN_RADIUS_KM + body_radius_km); + return new ShadowInfo(time, u, r, k, p, target, dir); +} +function EarthShadow(time) { + // Light-travel and aberration corrected vector from the Earth to the Sun. + const s = GeoVector(Body.Sun, time, true); + // The vector e = -s is thus the path of sunlight through the center of the Earth. + const e = new Vector(-s.x, -s.y, -s.z, s.t); + // Geocentric moon. + const m = GeoMoon(time); + return CalcShadow(EARTH_ECLIPSE_RADIUS_KM, time, m, e); +} +function MoonShadow(time) { + const s = GeoVector(Body.Sun, time, true); + const m = GeoMoon(time); // geocentric Moon + // Calculate lunacentric Earth. + const e = new Vector(-m.x, -m.y, -m.z, m.t); + // Convert geocentric moon to heliocentric Moon. + m.x -= s.x; + m.y -= s.y; + m.z -= s.z; + return CalcShadow(MOON_MEAN_RADIUS_KM, time, e, m); +} +function LocalMoonShadow(time, observer) { + // Calculate observer's geocentric position. + const pos = geo_pos(time, observer); + // Calculate light-travel and aberration corrected Sun. + const s = GeoVector(Body.Sun, time, true); + // Calculate geocentric Moon. + const m = GeoMoon(time); // geocentric Moon + // Calculate lunacentric location of an observer on the Earth's surface. + const o = new Vector(pos[0] - m.x, pos[1] - m.y, pos[2] - m.z, time); + // Convert geocentric moon to heliocentric Moon. + m.x -= s.x; + m.y -= s.y; + m.z -= s.z; + return CalcShadow(MOON_MEAN_RADIUS_KM, time, o, m); +} +function PlanetShadow(body, planet_radius_km, time) { + // Calculate light-travel-corrected vector from Earth to planet. + const g = GeoVector(body, time, true); + // Calculate light-travel-corrected vector from Earth to Sun. + const e = GeoVector(Body.Sun, time, true); + // Deduce light-travel-corrected vector from Sun to planet. + const p = new Vector(g.x - e.x, g.y - e.y, g.z - e.z, time); + // Calcluate Earth's position from the planet's point of view. + e.x = -g.x; + e.y = -g.y; + e.z = -g.z; + return CalcShadow(planet_radius_km, time, e, p); +} +function ShadowDistanceSlope(shadowfunc, time) { + const dt = 1.0 / 86400.0; + const t1 = time.AddDays(-dt); + const t2 = time.AddDays(+dt); + const shadow1 = shadowfunc(t1); + const shadow2 = shadowfunc(t2); + return (shadow2.r - shadow1.r) / dt; +} +function PlanetShadowSlope(body, planet_radius_km, time) { + const dt = 1.0 / 86400.0; + const shadow1 = PlanetShadow(body, planet_radius_km, time.AddDays(-dt)); + const shadow2 = PlanetShadow(body, planet_radius_km, time.AddDays(+dt)); + return (shadow2.r - shadow1.r) / dt; +} +function PeakEarthShadow(search_center_time) { + const window = 0.03; /* initial search window, in days, before/after given time */ + const t1 = search_center_time.AddDays(-window); + const t2 = search_center_time.AddDays(+window); + const tx = Search((time) => ShadowDistanceSlope(EarthShadow, time), t1, t2); + if (!tx) + throw 'Failed to find peak Earth shadow time.'; + return EarthShadow(tx); +} +function PeakMoonShadow(search_center_time) { + const window = 0.03; /* initial search window, in days, before/after given time */ + const t1 = search_center_time.AddDays(-window); + const t2 = search_center_time.AddDays(+window); + const tx = Search((time) => ShadowDistanceSlope(MoonShadow, time), t1, t2); + if (!tx) + throw 'Failed to find peak Moon shadow time.'; + return MoonShadow(tx); +} +function PeakPlanetShadow(body, planet_radius_km, search_center_time) { + // Search for when the body's shadow is closest to the center of the Earth. + const window = 1.0; // days before/after inferior conjunction to search for minimum shadow distance. + const t1 = search_center_time.AddDays(-window); + const t2 = search_center_time.AddDays(+window); + const tx = Search((time) => PlanetShadowSlope(body, planet_radius_km, time), t1, t2); + if (!tx) + throw 'Failed to find peak planet shadow time.'; + return PlanetShadow(body, planet_radius_km, tx); +} +function PeakLocalMoonShadow(search_center_time, observer) { + // Search for the time near search_center_time that the Moon's shadow comes + // closest to the given observer. + const window = 0.2; + const t1 = search_center_time.AddDays(-window); + const t2 = search_center_time.AddDays(+window); + function shadowfunc(time) { + return LocalMoonShadow(time, observer); + } + const time = Search((time) => ShadowDistanceSlope(shadowfunc, time), t1, t2); + if (!time) + throw `PeakLocalMoonShadow: search failure for search_center_time = ${search_center_time}`; + return LocalMoonShadow(time, observer); +} +function ShadowSemiDurationMinutes(center_time, radius_limit, window_minutes) { + // Search backwards and forwards from the center time until shadow axis distance crosses radius limit. + const window = window_minutes / (24.0 * 60.0); + const before = center_time.AddDays(-window); + const after = center_time.AddDays(+window); + const t1 = Search((time) => -(EarthShadow(time).r - radius_limit), before, center_time); + const t2 = Search((time) => +(EarthShadow(time).r - radius_limit), center_time, after); + if (!t1 || !t2) + throw 'Failed to find shadow semiduration'; + return (t2.ut - t1.ut) * ((24.0 * 60.0) / 2.0); // convert days to minutes and average the semi-durations. +} +function MoonEclipticLatitudeDegrees(time) { + const moon = CalcMoon(time); + return exports.RAD2DEG * moon.geo_eclip_lat; +} +function Obscuration(a, // radius of first disc +b, // radius of second disc +c // distance between the centers of the discs +) { + if (a <= 0.0) + throw 'Radius of first disc must be positive.'; + if (b <= 0.0) + throw 'Radius of second disc must be positive.'; + if (c < 0.0) + throw 'Distance between discs is not allowed to be negative.'; + if (c >= a + b) { + // The discs are too far apart to have any overlapping area. + return 0.0; + } + if (c == 0.0) { + // The discs have a common center. Therefore, one disc is inside the other. + return (a <= b) ? 1.0 : (b * b) / (a * a); + } + const x = (a * a - b * b + c * c) / (2 * c); + const radicand = a * a - x * x; + if (radicand <= 0.0) { + // The circumferences do not intersect, or are tangent. + // We already ruled out the case of non-overlapping discs. + // Therefore, one disc is inside the other. + return (a <= b) ? 1.0 : (b * b) / (a * a); + } + // The discs overlap fractionally in a pair of lens-shaped areas. + const y = Math.sqrt(radicand); + // Return the overlapping fractional area. + // There are two lens-shaped areas, one to the left of x, the other to the right of x. + // Each part is calculated by subtracting a triangular area from a sector's area. + const lens1 = a * a * Math.acos(x / a) - x * y; + const lens2 = b * b * Math.acos((c - x) / b) - (c - x) * y; + // Find the fractional area with respect to the first disc. + return (lens1 + lens2) / (Math.PI * a * a); +} +function SolarEclipseObscuration(hm, // heliocentric Moon +lo // lunacentric observer +) { + // Find heliocentric observer. + const ho = new Vector(hm.x + lo.x, hm.y + lo.y, hm.z + lo.z, hm.t); + // Calculate the apparent angular radius of the Sun for the observer. + const sun_radius = Math.asin(SUN_RADIUS_AU / ho.Length()); + // Calculate the apparent angular radius of the Moon for the observer. + const moon_radius = Math.asin(MOON_POLAR_RADIUS_AU / lo.Length()); + // Calculate the apparent angular separation between the Sun's center and the Moon's center. + const sun_moon_separation = AngleBetween(lo, ho); + // Find the fraction of the Sun's apparent disc area that is covered by the Moon. + const obscuration = Obscuration(sun_radius, moon_radius, sun_moon_separation * exports.DEG2RAD); + // HACK: In marginal cases, we need to clamp obscuration to less than 1.0. + // This function is never called for total eclipses, so it should never return 1.0. + return Math.min(0.9999, obscuration); +} +/** + * @brief Searches for a lunar eclipse. + * + * This function finds the first lunar eclipse that occurs after `startTime`. + * A lunar eclipse may be penumbral, partial, or total. + * See {@link LunarEclipseInfo} for more information. + * To find a series of lunar eclipses, call this function once, + * then keep calling {@link NextLunarEclipse} as many times as desired, + * passing in the `peak` value returned from the previous call. + * + * @param {FlexibleDateTime} date + * The date and time for starting the search for a lunar eclipse. + * + * @returns {LunarEclipseInfo} + */ +function SearchLunarEclipse(date) { + const PruneLatitude = 1.8; /* full Moon's ecliptic latitude above which eclipse is impossible */ + let fmtime = MakeTime(date); + for (let fmcount = 0; fmcount < 12; ++fmcount) { + /* Search for the next full moon. Any eclipse will be near it. */ + const fullmoon = SearchMoonPhase(180, fmtime, 40); + if (!fullmoon) + throw 'Cannot find full moon.'; + /* + Pruning: if the full Moon's ecliptic latitude is too large, + a lunar eclipse is not possible. Avoid needless work searching for + the minimum moon distance. + */ + const eclip_lat = MoonEclipticLatitudeDegrees(fullmoon); + if (Math.abs(eclip_lat) < PruneLatitude) { + /* Search near the full moon for the time when the center of the Moon */ + /* is closest to the line passing through the centers of the Sun and Earth. */ + const shadow = PeakEarthShadow(fullmoon); + if (shadow.r < shadow.p + MOON_MEAN_RADIUS_KM) { + /* This is at least a penumbral eclipse. We will return a result. */ + let kind = EclipseKind.Penumbral; + let obscuration = 0.0; + let sd_total = 0.0; + let sd_partial = 0.0; + let sd_penum = ShadowSemiDurationMinutes(shadow.time, shadow.p + MOON_MEAN_RADIUS_KM, 200.0); + if (shadow.r < shadow.k + MOON_MEAN_RADIUS_KM) { + /* This is at least a partial eclipse. */ + kind = EclipseKind.Partial; + sd_partial = ShadowSemiDurationMinutes(shadow.time, shadow.k + MOON_MEAN_RADIUS_KM, sd_penum); + if (shadow.r + MOON_MEAN_RADIUS_KM < shadow.k) { + /* This is a total eclipse. */ + kind = EclipseKind.Total; + obscuration = 1.0; + sd_total = ShadowSemiDurationMinutes(shadow.time, shadow.k - MOON_MEAN_RADIUS_KM, sd_partial); + } + else { + obscuration = Obscuration(MOON_MEAN_RADIUS_KM, shadow.k, shadow.r); + } + } + return new LunarEclipseInfo(kind, obscuration, shadow.time, sd_penum, sd_partial, sd_total); + } + } + /* We didn't find an eclipse on this full moon, so search for the next one. */ + fmtime = fullmoon.AddDays(10); + } + /* This should never happen because there are always at least 2 full moons per year. */ + throw 'Failed to find lunar eclipse within 12 full moons.'; +} +exports.SearchLunarEclipse = SearchLunarEclipse; +/** + * @brief Reports the time and geographic location of the peak of a solar eclipse. + * + * Returned by {@link SearchGlobalSolarEclipse} or {@link NextGlobalSolarEclipse} + * to report information about a solar eclipse event. + * + * The eclipse is classified as partial, annular, or total, depending on the + * maximum amount of the Sun's disc obscured, as seen at the peak location + * on the surface of the Earth. + * + * The `kind` field thus holds one of the values `EclipseKind.Partial`, `EclipseKind.Annular`, or `EclipseKind.Total`. + * A total eclipse is when the peak observer sees the Sun completely blocked by the Moon. + * An annular eclipse is like a total eclipse, but the Moon is too far from the Earth's surface + * to completely block the Sun; instead, the Sun takes on a ring-shaped appearance. + * A partial eclipse is when the Moon blocks part of the Sun's disc, but nobody on the Earth + * observes either a total or annular eclipse. + * + * If `kind` is `EclipseKind.Total` or `EclipseKind.Annular`, the `latitude` and `longitude` + * fields give the geographic coordinates of the center of the Moon's shadow projected + * onto the daytime side of the Earth at the instant of the eclipse's peak. + * If `kind` has any other value, `latitude` and `longitude` are undefined and should + * not be used. + * + * For total or annular eclipses, the `obscuration` field holds the fraction (0, 1] + * of the Sun's apparent disc area that is blocked from view by the Moon's silhouette, + * as seen by an observer located at the geographic coordinates `latitude`, `longitude` + * at the darkest time `peak`. The value will always be 1 for total eclipses, and less than + * 1 for annular eclipses. + * For partial eclipses, `obscuration` is undefined and should not be used. + * This is because there is little practical use for an obscuration value of + * a partial eclipse without supplying a particular observation location. + * Developers who wish to find an obscuration value for partial solar eclipses should therefore use + * {@link SearchLocalSolarEclipse} and provide the geographic coordinates of an observer. + * + * @property {EclipseKind} kind + * One of the following enumeration values: `EclipseKind.Partial`, `EclipseKind.Annular`, `EclipseKind.Total`. + * + * @property {number | undefined} obscuration + * The peak fraction of the Sun's apparent disc area obscured by the Moon (total and annular eclipses only) + * + * @property {AstroTime} peak + * The date and time when the solar eclipse is darkest. + * This is the instant when the axis of the Moon's shadow cone passes closest to the Earth's center. + * + * @property {number} distance + * The distance in kilometers between the axis of the Moon's shadow cone + * and the center of the Earth at the time indicated by `peak`. + * + * @property {number | undefined} latitude + * If `kind` holds `EclipseKind.Total`, the geographic latitude in degrees + * where the center of the Moon's shadow falls on the Earth at the + * time indicated by `peak`; otherwise, `latitude` holds `undefined`. + * + * @property {number | undefined} longitude + * If `kind` holds `EclipseKind.Total`, the geographic longitude in degrees + * where the center of the Moon's shadow falls on the Earth at the + * time indicated by `peak`; otherwise, `longitude` holds `undefined`. + */ +class GlobalSolarEclipseInfo { + constructor(kind, obscuration, peak, distance, latitude, longitude) { + this.kind = kind; + this.obscuration = obscuration; + this.peak = peak; + this.distance = distance; + this.latitude = latitude; + this.longitude = longitude; + } +} +exports.GlobalSolarEclipseInfo = GlobalSolarEclipseInfo; +function EclipseKindFromUmbra(k) { + // The umbra radius tells us what kind of eclipse the observer sees. + // If the umbra radius is positive, this is a total eclipse. Otherwise, it's annular. + // HACK: I added a tiny bias (14 meters) to match Espenak test data. + return (k > 0.014) ? EclipseKind.Total : EclipseKind.Annular; +} +function GeoidIntersect(shadow) { + let kind = EclipseKind.Partial; + let peak = shadow.time; + let distance = shadow.r; + let latitude; // left undefined for partial eclipses + let longitude; // left undefined for partial eclipses + // We want to calculate the intersection of the shadow axis with the Earth's geoid. + // First we must convert EQJ (equator of J2000) coordinates to EQD (equator of date) + // coordinates that are perfectly aligned with the Earth's equator at this + // moment in time. + const rot = Rotation_EQJ_EQD(shadow.time); + const v = RotateVector(rot, shadow.dir); // shadow-axis vector in equator-of-date coordinates + const e = RotateVector(rot, shadow.target); // lunacentric Earth in equator-of-date coordinates + // Convert all distances from AU to km. + // But dilate the z-coordinates so that the Earth becomes a perfect sphere. + // Then find the intersection of the vector with the sphere. + // See p 184 in Montenbruck & Pfleger's "Astronomy on the Personal Computer", second edition. + v.x *= exports.KM_PER_AU; + v.y *= exports.KM_PER_AU; + v.z *= exports.KM_PER_AU / EARTH_FLATTENING; + e.x *= exports.KM_PER_AU; + e.y *= exports.KM_PER_AU; + e.z *= exports.KM_PER_AU / EARTH_FLATTENING; + // Solve the quadratic equation that finds whether and where + // the shadow axis intersects with the Earth in the dilated coordinate system. + const R = EARTH_EQUATORIAL_RADIUS_KM; + const A = v.x * v.x + v.y * v.y + v.z * v.z; + const B = -2.0 * (v.x * e.x + v.y * e.y + v.z * e.z); + const C = (e.x * e.x + e.y * e.y + e.z * e.z) - R * R; + const radic = B * B - 4 * A * C; + let obscuration; + if (radic > 0.0) { + // Calculate the closer of the two intersection points. + // This will be on the day side of the Earth. + const u = (-B - Math.sqrt(radic)) / (2 * A); + // Convert lunacentric dilated coordinates to geocentric coordinates. + const px = u * v.x - e.x; + const py = u * v.y - e.y; + const pz = (u * v.z - e.z) * EARTH_FLATTENING; + // Convert cartesian coordinates into geodetic latitude/longitude. + const proj = Math.hypot(px, py) * EARTH_FLATTENING_SQUARED; + if (proj == 0.0) + latitude = (pz > 0.0) ? +90.0 : -90.0; + else + latitude = exports.RAD2DEG * Math.atan(pz / proj); + // Adjust longitude for Earth's rotation at the given UT. + const gast = sidereal_time(peak); + longitude = (exports.RAD2DEG * Math.atan2(py, px) - (15 * gast)) % 360.0; + if (longitude <= -180.0) + longitude += 360.0; + else if (longitude > +180.0) + longitude -= 360.0; + // We want to determine whether the observer sees a total eclipse or an annular eclipse. + // We need to perform a series of vector calculations... + // Calculate the inverse rotation matrix, so we can convert EQD to EQJ. + const inv = InverseRotation(rot); + // Put the EQD geocentric coordinates of the observer into the vector 'o'. + // Also convert back from kilometers to astronomical units. + let o = new Vector(px / exports.KM_PER_AU, py / exports.KM_PER_AU, pz / exports.KM_PER_AU, shadow.time); + // Rotate the observer's geocentric EQD back to the EQJ system. + o = RotateVector(inv, o); + // Convert geocentric vector to lunacentric vector. + o.x += shadow.target.x; + o.y += shadow.target.y; + o.z += shadow.target.z; + // Recalculate the shadow using a vector from the Moon's center toward the observer. + const surface = CalcShadow(MOON_POLAR_RADIUS_KM, shadow.time, o, shadow.dir); + // If we did everything right, the shadow distance should be very close to zero. + // That's because we already determined the observer 'o' is on the shadow axis! + if (surface.r > 1.0e-9 || surface.r < 0.0) + throw `Unexpected shadow distance from geoid intersection = ${surface.r}`; + kind = EclipseKindFromUmbra(surface.k); + obscuration = (kind === EclipseKind.Total) ? 1.0 : SolarEclipseObscuration(shadow.dir, o); + } + else { + // This is a partial solar eclipse. It does not make practical sense to calculate obscuration. + // Anyone who wants obscuration should use Astronomy.SearchLocalSolarEclipse for a specific location on the Earth. + obscuration = undefined; + } + return new GlobalSolarEclipseInfo(kind, obscuration, peak, distance, latitude, longitude); +} +/** + * @brief Searches for the next lunar eclipse in a series. + * + * After using {@link SearchLunarEclipse} to find the first lunar eclipse + * in a series, you can call this function to find the next consecutive lunar eclipse. + * Pass in the `peak` value from the {@link LunarEclipseInfo} returned by the + * previous call to `SearchLunarEclipse` or `NextLunarEclipse` + * to find the next lunar eclipse. + * + * @param {FlexibleDateTime} prevEclipseTime + * A date and time near a full moon. Lunar eclipse search will start at the next full moon. + * + * @returns {LunarEclipseInfo} + */ +function NextLunarEclipse(prevEclipseTime) { + prevEclipseTime = MakeTime(prevEclipseTime); + const startTime = prevEclipseTime.AddDays(10); + return SearchLunarEclipse(startTime); +} +exports.NextLunarEclipse = NextLunarEclipse; +/** + * @brief Searches for a solar eclipse visible anywhere on the Earth's surface. + * + * This function finds the first solar eclipse that occurs after `startTime`. + * A solar eclipse may be partial, annular, or total. + * See {@link GlobalSolarEclipseInfo} for more information. + * To find a series of solar eclipses, call this function once, + * then keep calling {@link NextGlobalSolarEclipse} as many times as desired, + * passing in the `peak` value returned from the previous call. + * + * @param {FlexibleDateTime} startTime + * The date and time for starting the search for a solar eclipse. + * + * @returns {GlobalSolarEclipseInfo} + */ +function SearchGlobalSolarEclipse(startTime) { + startTime = MakeTime(startTime); + const PruneLatitude = 1.8; // Moon's ecliptic latitude beyond which eclipse is impossible + // Iterate through consecutive new moons until we find a solar eclipse visible somewhere on Earth. + let nmtime = startTime; + let nmcount; + for (nmcount = 0; nmcount < 12; ++nmcount) { + // Search for the next new moon. Any eclipse will be near it. + const newmoon = SearchMoonPhase(0.0, nmtime, 40.0); + if (!newmoon) + throw 'Cannot find new moon'; + // Pruning: if the new moon's ecliptic latitude is too large, a solar eclipse is not possible. + const eclip_lat = MoonEclipticLatitudeDegrees(newmoon); + if (Math.abs(eclip_lat) < PruneLatitude) { + // Search near the new moon for the time when the center of the Earth + // is closest to the line passing through the centers of the Sun and Moon. + const shadow = PeakMoonShadow(newmoon); + if (shadow.r < shadow.p + EARTH_MEAN_RADIUS_KM) { + // This is at least a partial solar eclipse visible somewhere on Earth. + // Try to find an intersection between the shadow axis and the Earth's oblate geoid. + return GeoidIntersect(shadow); + } + } + // We didn't find an eclipse on this new moon, so search for the next one. + nmtime = newmoon.AddDays(10.0); + } + // Safety valve to prevent infinite loop. + // This should never happen, because at least 2 solar eclipses happen per year. + throw 'Failed to find solar eclipse within 12 full moons.'; +} +exports.SearchGlobalSolarEclipse = SearchGlobalSolarEclipse; +/** + * @brief Searches for the next global solar eclipse in a series. + * + * After using {@link SearchGlobalSolarEclipse} to find the first solar eclipse + * in a series, you can call this function to find the next consecutive solar eclipse. + * Pass in the `peak` value from the {@link GlobalSolarEclipseInfo} returned by the + * previous call to `SearchGlobalSolarEclipse` or `NextGlobalSolarEclipse` + * to find the next solar eclipse. + * + * @param {FlexibleDateTime} prevEclipseTime + * A date and time near a new moon. Solar eclipse search will start at the next new moon. + * + * @returns {GlobalSolarEclipseInfo} + */ +function NextGlobalSolarEclipse(prevEclipseTime) { + prevEclipseTime = MakeTime(prevEclipseTime); + const startTime = prevEclipseTime.AddDays(10.0); + return SearchGlobalSolarEclipse(startTime); +} +exports.NextGlobalSolarEclipse = NextGlobalSolarEclipse; +/** + * @brief Holds a time and the observed altitude of the Sun at that time. + * + * When reporting a solar eclipse observed at a specific location on the Earth + * (a "local" solar eclipse), a series of events occur. In addition + * to the time of each event, it is important to know the altitude of the Sun, + * because each event may be invisible to the observer if the Sun is below + * the horizon. + * + * If `altitude` is negative, the event is theoretical only; it would be + * visible if the Earth were transparent, but the observer cannot actually see it. + * If `altitude` is positive but less than a few degrees, visibility will be impaired by + * atmospheric interference (sunrise or sunset conditions). + * + * @property {AstroTime} time + * The date and time of the event. + * + * @property {number} altitude + * The angular altitude of the center of the Sun above/below the horizon, at `time`, + * corrected for atmospheric refraction and expressed in degrees. + */ +class EclipseEvent { + constructor(time, altitude) { + this.time = time; + this.altitude = altitude; + } +} +exports.EclipseEvent = EclipseEvent; +/** + * @brief Information about a solar eclipse as seen by an observer at a given time and geographic location. + * + * Returned by {@link SearchLocalSolarEclipse} or {@link NextLocalSolarEclipse} + * to report information about a solar eclipse as seen at a given geographic location. + * + * When a solar eclipse is found, it is classified by setting `kind` + * to `EclipseKind.Partial`, `EclipseKind.Annular`, or `EclipseKind.Total`. + * A partial solar eclipse is when the Moon does not line up directly enough with the Sun + * to completely block the Sun's light from reaching the observer. + * An annular eclipse occurs when the Moon's disc is completely visible against the Sun + * but the Moon is too far away to completely block the Sun's light; this leaves the + * Sun with a ring-like appearance. + * A total eclipse occurs when the Moon is close enough to the Earth and aligned with the + * Sun just right to completely block all sunlight from reaching the observer. + * + * The `obscuration` field reports what fraction of the Sun's disc appears blocked + * by the Moon when viewed by the observer at the peak eclipse time. + * This is a value that ranges from 0 (no blockage) to 1 (total eclipse). + * The obscuration value will be between 0 and 1 for partial eclipses and annular eclipses. + * The value will be exactly 1 for total eclipses. Obscuration gives an indication + * of how dark the eclipse appears. + * + * There are 5 "event" fields, each of which contains a time and a solar altitude. + * Field `peak` holds the date and time of the center of the eclipse, when it is at its peak. + * The fields `partial_begin` and `partial_end` are always set, and indicate when + * the eclipse begins/ends. If the eclipse reaches totality or becomes annular, + * `total_begin` and `total_end` indicate when the total/annular phase begins/ends. + * When an event field is valid, the caller must also check its `altitude` field to + * see whether the Sun is above the horizon at the time indicated by the `time` field. + * See {@link EclipseEvent} for more information. + * + * @property {EclipseKind} kind + * The type of solar eclipse found: `EclipseKind.Partial`, `EclipseKind.Annular`, or `EclipseKind.Total`. + * + * @property {number} obscuration + * The fraction of the Sun's apparent disc area obscured by the Moon at the eclipse peak. + * + * @property {EclipseEvent} partial_begin + * The time and Sun altitude at the beginning of the eclipse. + * + * @property {EclipseEvent | undefined} total_begin + * If this is an annular or a total eclipse, the time and Sun altitude when annular/total phase begins; otherwise undefined. + * + * @property {EclipseEvent} peak + * The time and Sun altitude when the eclipse reaches its peak. + * + * @property {EclipseEvent | undefined} total_end + * If this is an annular or a total eclipse, the time and Sun altitude when annular/total phase ends; otherwise undefined. + * + * @property {EclipseEvent} partial_end + * The time and Sun altitude at the end of the eclipse. + */ +class LocalSolarEclipseInfo { + constructor(kind, obscuration, partial_begin, total_begin, peak, total_end, partial_end) { + this.kind = kind; + this.obscuration = obscuration; + this.partial_begin = partial_begin; + this.total_begin = total_begin; + this.peak = peak; + this.total_end = total_end; + this.partial_end = partial_end; + } +} +exports.LocalSolarEclipseInfo = LocalSolarEclipseInfo; +function local_partial_distance(shadow) { + return shadow.p - shadow.r; +} +function local_total_distance(shadow) { + // Must take the absolute value of the umbra radius 'k' + // because it can be negative for an annular eclipse. + return Math.abs(shadow.k) - shadow.r; +} +function LocalEclipse(shadow, observer) { + const PARTIAL_WINDOW = 0.2; + const TOTAL_WINDOW = 0.01; + const peak = CalcEvent(observer, shadow.time); + let t1 = shadow.time.AddDays(-PARTIAL_WINDOW); + let t2 = shadow.time.AddDays(+PARTIAL_WINDOW); + const partial_begin = LocalEclipseTransition(observer, +1.0, local_partial_distance, t1, shadow.time); + const partial_end = LocalEclipseTransition(observer, -1.0, local_partial_distance, shadow.time, t2); + let total_begin; + let total_end; + let kind; + if (shadow.r < Math.abs(shadow.k)) { // take absolute value of 'k' to handle annular eclipses too. + t1 = shadow.time.AddDays(-TOTAL_WINDOW); + t2 = shadow.time.AddDays(+TOTAL_WINDOW); + total_begin = LocalEclipseTransition(observer, +1.0, local_total_distance, t1, shadow.time); + total_end = LocalEclipseTransition(observer, -1.0, local_total_distance, shadow.time, t2); + kind = EclipseKindFromUmbra(shadow.k); + } + else { + kind = EclipseKind.Partial; + } + const obscuration = (kind === EclipseKind.Total) ? 1.0 : SolarEclipseObscuration(shadow.dir, shadow.target); + return new LocalSolarEclipseInfo(kind, obscuration, partial_begin, total_begin, peak, total_end, partial_end); +} +function LocalEclipseTransition(observer, direction, func, t1, t2) { + function evaluate(time) { + const shadow = LocalMoonShadow(time, observer); + return direction * func(shadow); + } + const search = Search(evaluate, t1, t2); + if (!search) + throw "Local eclipse transition search failed."; + return CalcEvent(observer, search); +} +function CalcEvent(observer, time) { + const altitude = SunAltitude(time, observer); + return new EclipseEvent(time, altitude); +} +function SunAltitude(time, observer) { + const equ = Equator(Body.Sun, time, observer, true, true); + const hor = Horizon(time, observer, equ.ra, equ.dec, 'normal'); + return hor.altitude; +} +/** + * @brief Searches for a solar eclipse visible at a specific location on the Earth's surface. + * + * This function finds the first solar eclipse that occurs after `startTime`. + * A solar eclipse may be partial, annular, or total. + * See {@link LocalSolarEclipseInfo} for more information. + * + * To find a series of solar eclipses, call this function once, + * then keep calling {@link NextLocalSolarEclipse} as many times as desired, + * passing in the `peak` value returned from the previous call. + * + * IMPORTANT: An eclipse reported by this function might be partly or + * completely invisible to the observer due to the time of day. + * See {@link LocalSolarEclipseInfo} for more information about this topic. + * + * @param {FlexibleDateTime} startTime + * The date and time for starting the search for a solar eclipse. + * + * @param {Observer} observer + * The geographic location of the observer. + * + * @returns {LocalSolarEclipseInfo} + */ +function SearchLocalSolarEclipse(startTime, observer) { + startTime = MakeTime(startTime); + VerifyObserver(observer); + const PruneLatitude = 1.8; /* Moon's ecliptic latitude beyond which eclipse is impossible */ + /* Iterate through consecutive new moons until we find a solar eclipse visible somewhere on Earth. */ + let nmtime = startTime; + for (;;) { + /* Search for the next new moon. Any eclipse will be near it. */ + const newmoon = SearchMoonPhase(0.0, nmtime, 40.0); + if (!newmoon) + throw 'Cannot find next new moon'; + /* Pruning: if the new moon's ecliptic latitude is too large, a solar eclipse is not possible. */ + const eclip_lat = MoonEclipticLatitudeDegrees(newmoon); + if (Math.abs(eclip_lat) < PruneLatitude) { + /* Search near the new moon for the time when the observer */ + /* is closest to the line passing through the centers of the Sun and Moon. */ + const shadow = PeakLocalMoonShadow(newmoon, observer); + if (shadow.r < shadow.p) { + /* This is at least a partial solar eclipse for the observer. */ + const eclipse = LocalEclipse(shadow, observer); + /* Ignore any eclipse that happens completely at night. */ + /* More precisely, the center of the Sun must be above the horizon */ + /* at the beginning or the end of the eclipse, or we skip the event. */ + if (eclipse.partial_begin.altitude > 0.0 || eclipse.partial_end.altitude > 0.0) + return eclipse; + } + } + /* We didn't find an eclipse on this new moon, so search for the next one. */ + nmtime = newmoon.AddDays(10.0); + } +} +exports.SearchLocalSolarEclipse = SearchLocalSolarEclipse; +/** + * @brief Searches for the next local solar eclipse in a series. + * + * After using {@link SearchLocalSolarEclipse} to find the first solar eclipse + * in a series, you can call this function to find the next consecutive solar eclipse. + * Pass in the `peak` value from the {@link LocalSolarEclipseInfo} returned by the + * previous call to `SearchLocalSolarEclipse` or `NextLocalSolarEclipse` + * to find the next solar eclipse. + * This function finds the first solar eclipse that occurs after `startTime`. + * A solar eclipse may be partial, annular, or total. + * See {@link LocalSolarEclipseInfo} for more information. + * + * @param {FlexibleDateTime} prevEclipseTime + * The date and time for starting the search for a solar eclipse. + * + * @param {Observer} observer + * The geographic location of the observer. + * + * @returns {LocalSolarEclipseInfo} + */ +function NextLocalSolarEclipse(prevEclipseTime, observer) { + prevEclipseTime = MakeTime(prevEclipseTime); + const startTime = prevEclipseTime.AddDays(10.0); + return SearchLocalSolarEclipse(startTime, observer); +} +exports.NextLocalSolarEclipse = NextLocalSolarEclipse; +/** + * @brief Information about a transit of Mercury or Venus, as seen from the Earth. + * + * Returned by {@link SearchTransit} or {@link NextTransit} to report + * information about a transit of Mercury or Venus. + * A transit is when Mercury or Venus passes between the Sun and Earth so that + * the other planet is seen in silhouette against the Sun. + * + * The calculations are performed from the point of view of a geocentric observer. + * + * @property {AstroTime} start + * The date and time at the beginning of the transit. + * This is the moment the planet first becomes visible against the Sun in its background. + * + * @property {AstroTime} peak + * When the planet is most aligned with the Sun, as seen from the Earth. + * + * @property {AstroTime} finish + * The date and time at the end of the transit. + * This is the moment the planet is last seen against the Sun in its background. + * + * @property {number} separation + * The minimum angular separation, in arcminutes, between the centers of the Sun and the planet. + * This angle pertains to the time stored in `peak`. + */ +class TransitInfo { + constructor(start, peak, finish, separation) { + this.start = start; + this.peak = peak; + this.finish = finish; + this.separation = separation; + } +} +exports.TransitInfo = TransitInfo; +function PlanetShadowBoundary(time, body, planet_radius_km, direction) { + const shadow = PlanetShadow(body, planet_radius_km, time); + return direction * (shadow.r - shadow.p); +} +function PlanetTransitBoundary(body, planet_radius_km, t1, t2, direction) { + // Search for the time the planet's penumbra begins/ends making contact with the center of the Earth. + const tx = Search((time) => PlanetShadowBoundary(time, body, planet_radius_km, direction), t1, t2); + if (!tx) + throw 'Planet transit boundary search failed'; + return tx; +} +/** + * @brief Searches for the first transit of Mercury or Venus after a given date. + * + * Finds the first transit of Mercury or Venus after a specified date. + * A transit is when an inferior planet passes between the Sun and the Earth + * so that the silhouette of the planet is visible against the Sun in the background. + * To continue the search, pass the `finish` time in the returned structure to + * {@link NextTransit}. + * + * @param {Body} body + * The planet whose transit is to be found. Must be `Body.Mercury` or `Body.Venus`. + * + * @param {FlexibleDateTime} startTime + * The date and time for starting the search for a transit. + * + * @returns {TransitInfo} + */ +function SearchTransit(body, startTime) { + startTime = MakeTime(startTime); + const threshold_angle = 0.4; // maximum angular separation to attempt transit calculation + const dt_days = 1.0; + // Validate the planet and find its mean radius. + let planet_radius_km; + switch (body) { + case Body.Mercury: + planet_radius_km = 2439.7; + break; + case Body.Venus: + planet_radius_km = 6051.8; + break; + default: + throw `Invalid body: ${body}`; + } + let search_time = startTime; + for (;;) { + // Search for the next inferior conjunction of the given planet. + // This is the next time the Earth and the other planet have the same + // ecliptic longitude as seen from the Sun. + const conj = SearchRelativeLongitude(body, 0.0, search_time); + // Calculate the angular separation between the body and the Sun at this time. + const conj_separation = AngleFromSun(body, conj); + if (conj_separation < threshold_angle) { + // The planet's angular separation from the Sun is small enough + // to consider it a transit candidate. + // Search for the moment when the line passing through the Sun + // and planet are closest to the Earth's center. + const shadow = PeakPlanetShadow(body, planet_radius_km, conj); + if (shadow.r < shadow.p) { // does the planet's penumbra touch the Earth's center? + // Find the beginning and end of the penumbral contact. + const time_before = shadow.time.AddDays(-dt_days); + const start = PlanetTransitBoundary(body, planet_radius_km, time_before, shadow.time, -1.0); + const time_after = shadow.time.AddDays(+dt_days); + const finish = PlanetTransitBoundary(body, planet_radius_km, shadow.time, time_after, +1.0); + const min_separation = 60.0 * AngleFromSun(body, shadow.time); + return new TransitInfo(start, shadow.time, finish, min_separation); + } + } + // This inferior conjunction was not a transit. Try the next inferior conjunction. + search_time = conj.AddDays(10.0); + } +} +exports.SearchTransit = SearchTransit; +/** + * @brief Searches for the next transit of Mercury or Venus in a series. + * + * After calling {@link SearchTransit} to find a transit of Mercury or Venus, + * this function finds the next transit after that. + * Keep calling this function as many times as you want to keep finding more transits. + * + * @param {Body} body + * The planet whose transit is to be found. Must be `Body.Mercury` or `Body.Venus`. + * + * @param {FlexibleDateTime} prevTransitTime + * A date and time near the previous transit. + * + * @returns {TransitInfo} + */ +function NextTransit(body, prevTransitTime) { + prevTransitTime = MakeTime(prevTransitTime); + const startTime = prevTransitTime.AddDays(100.0); + return SearchTransit(body, startTime); +} +exports.NextTransit = NextTransit; +/** + * @brief Indicates whether a crossing through the ecliptic plane is ascending or descending. + * + * `Invalid` is a placeholder for an unknown or missing node. + * `Ascending` indicates a body passing through the ecliptic plane from south to north. + * `Descending` indicates a body passing through the ecliptic plane from north to south. + * + * @enum {number} + */ +var NodeEventKind; +(function (NodeEventKind) { + NodeEventKind[NodeEventKind["Invalid"] = 0] = "Invalid"; + NodeEventKind[NodeEventKind["Ascending"] = 1] = "Ascending"; + NodeEventKind[NodeEventKind["Descending"] = -1] = "Descending"; +})(NodeEventKind = exports.NodeEventKind || (exports.NodeEventKind = {})); +/** + * @brief Information about an ascending or descending node of a body. + * + * This object is returned by {@link SearchMoonNode} and {@link NextMoonNode} + * to report information about the center of the Moon passing through the ecliptic plane. + * + * @property {NodeEventKind} kind Whether the node is ascending (south to north) or descending (north to south). + * @property {AstroTime} time The time when the body passes through the ecliptic plane. + */ +class NodeEventInfo { + constructor(kind, time) { + this.kind = kind; + this.time = time; + } +} +exports.NodeEventInfo = NodeEventInfo; +const MoonNodeStepDays = +10.0; // a safe number of days to step without missing a Moon node +/** + * @brief Searches for a time when the Moon's center crosses through the ecliptic plane. + * + * Searches for the first ascending or descending node of the Moon after `startTime`. + * An ascending node is when the Moon's center passes through the ecliptic plane + * (the plane of the Earth's orbit around the Sun) from south to north. + * A descending node is when the Moon's center passes through the ecliptic plane + * from north to south. Nodes indicate possible times of solar or lunar eclipses, + * if the Moon also happens to be in the correct phase (new or full, respectively). + * Call `SearchMoonNode` to find the first of a series of nodes. + * Then call {@link NextMoonNode} to find as many more consecutive nodes as desired. + * + * @param {FlexibleDateTime} startTime + * The date and time for starting the search for an ascending or descending node of the Moon. + * + * @returns {NodeEventInfo} + */ +function SearchMoonNode(startTime) { + // Start at the given moment in time and sample the Moon's ecliptic latitude. + // Step 10 days at a time, searching for an interval where that latitude crosses zero. + let time1 = MakeTime(startTime); + let eclip1 = EclipticGeoMoon(time1); + for (;;) { + const time2 = time1.AddDays(MoonNodeStepDays); + const eclip2 = EclipticGeoMoon(time2); + if (eclip1.lat * eclip2.lat <= 0.0) { + // There is a node somewhere inside this closed time interval. + // Figure out whether it is an ascending node or a descending node. + const kind = (eclip2.lat > eclip1.lat) ? NodeEventKind.Ascending : NodeEventKind.Descending; + const result = Search(t => kind * EclipticGeoMoon(t).lat, time1, time2); + if (!result) + throw `Could not find moon node.`; // should never happen + return new NodeEventInfo(kind, result); + } + time1 = time2; + eclip1 = eclip2; + } +} +exports.SearchMoonNode = SearchMoonNode; +/** + * @brief Searches for the next time when the Moon's center crosses through the ecliptic plane. + * + * Call {@link SearchMoonNode} to find the first of a series of nodes. + * Then call `NextMoonNode` to find as many more consecutive nodes as desired. + * + * @param {NodeEventInfo} prevNode + * The previous node found from calling {@link SearchMoonNode} or `NextMoonNode`. + * + * @returns {NodeEventInfo} + */ +function NextMoonNode(prevNode) { + const time = prevNode.time.AddDays(MoonNodeStepDays); + const node = SearchMoonNode(time); + switch (prevNode.kind) { + case NodeEventKind.Ascending: + if (node.kind !== NodeEventKind.Descending) + throw `Internal error: previous node was ascending, but this node was: ${node.kind}`; + break; + case NodeEventKind.Descending: + if (node.kind !== NodeEventKind.Ascending) + throw `Internal error: previous node was descending, but this node was: ${node.kind}`; + break; + default: + throw `Previous node has an invalid node kind: ${prevNode.kind}`; + } + return node; +} +exports.NextMoonNode = NextMoonNode; +/** + * @brief Information about a body's rotation axis at a given time. + * + * This structure is returned by {@link RotationAxis} to report + * the orientation of a body's rotation axis at a given moment in time. + * The axis is specified by the direction in space that the body's north pole + * points, using angular equatorial coordinates in the J2000 system (EQJ). + * + * Thus `ra` is the right ascension, and `dec` is the declination, of the + * body's north pole vector at the given moment in time. The north pole + * of a body is defined as the pole that lies on the north side of the + * [Solar System's invariable plane](https://en.wikipedia.org/wiki/Invariable_plane), + * regardless of the body's direction of rotation. + * + * The `spin` field indicates the angular position of a prime meridian + * arbitrarily recommended for the body by the International Astronomical + * Union (IAU). + * + * The fields `ra`, `dec`, and `spin` correspond to the variables + * α0, δ0, and W, respectively, from + * [Report of the IAU Working Group on Cartographic Coordinates and Rotational Elements: 2015](https://astropedia.astrogeology.usgs.gov/download/Docs/WGCCRE/WGCCRE2015reprint.pdf). + * The field `north` is a unit vector pointing in the direction of the body's north pole. + * It is expressed in the J2000 mean equator system (EQJ). + * + * @property {number} ra + * The J2000 right ascension of the body's north pole direction, in sidereal hours. + * + * @property {number} dec + * The J2000 declination of the body's north pole direction, in degrees. + * + * @property {number} spin + * Rotation angle of the body's prime meridian, in degrees. + * + * @property {Vector} north + * A J2000 dimensionless unit vector pointing in the direction of the body's north pole. + */ +class AxisInfo { + constructor(ra, dec, spin, north) { + this.ra = ra; + this.dec = dec; + this.spin = spin; + this.north = north; + } +} +exports.AxisInfo = AxisInfo; +function EarthRotationAxis(time) { + // Unlike the other planets, we have a model of precession and nutation + // for the Earth's axis that provides a north pole vector. + // So calculate the vector first, then derive the (RA,DEC) angles from the vector. + // Start with a north pole vector in equator-of-date coordinates: (0,0,1). + // Convert the vector into J2000 coordinates. + const pos2 = nutation([0, 0, 1], time, PrecessDirection.Into2000); + const nvec = precession(pos2, time, PrecessDirection.Into2000); + const north = new Vector(nvec[0], nvec[1], nvec[2], time); + // Derive angular values: right ascension and declination. + const equ = EquatorFromVector(north); + // Use a modified version of the era() function that does not trim to 0..360 degrees. + // This expression is also corrected to give the correct angle at the J2000 epoch. + const spin = 190.41375788700253 + (360.9856122880876 * time.ut); + return new AxisInfo(equ.ra, equ.dec, spin, north); +} +/** + * @brief Calculates information about a body's rotation axis at a given time. + * Calculates the orientation of a body's rotation axis, along with + * the rotation angle of its prime meridian, at a given moment in time. + * + * This function uses formulas standardized by the IAU Working Group + * on Cartographics and Rotational Elements 2015 report, as described + * in the following document: + * + * https://astropedia.astrogeology.usgs.gov/download/Docs/WGCCRE/WGCCRE2015reprint.pdf + * + * See {@link AxisInfo} for more detailed information. + * + * @param {Body} body + * One of the following values: + * `Body.Sun`, `Body.Moon`, `Body.Mercury`, `Body.Venus`, `Body.Earth`, `Body.Mars`, + * `Body.Jupiter`, `Body.Saturn`, `Body.Uranus`, `Body.Neptune`, `Body.Pluto`. + * + * @param {FlexibleDateTime} date + * The time at which to calculate the body's rotation axis. + * + * @returns {AxisInfo} + */ +function RotationAxis(body, date) { + const time = MakeTime(date); + const d = time.tt; + const T = d / 36525.0; + let ra, dec, w; + switch (body) { + case Body.Sun: + ra = 286.13; + dec = 63.87; + w = 84.176 + (14.1844 * d); + break; + case Body.Mercury: + ra = 281.0103 - (0.0328 * T); + dec = 61.4155 - (0.0049 * T); + w = (329.5988 + + (6.1385108 * d) + + (0.01067257 * Math.sin(exports.DEG2RAD * (174.7910857 + 4.092335 * d))) + - (0.00112309 * Math.sin(exports.DEG2RAD * (349.5821714 + 8.184670 * d))) + - (0.00011040 * Math.sin(exports.DEG2RAD * (164.3732571 + 12.277005 * d))) + - (0.00002539 * Math.sin(exports.DEG2RAD * (339.1643429 + 16.369340 * d))) + - (0.00000571 * Math.sin(exports.DEG2RAD * (153.9554286 + 20.461675 * d)))); + break; + case Body.Venus: + ra = 272.76; + dec = 67.16; + w = 160.20 - (1.4813688 * d); + break; + case Body.Earth: + return EarthRotationAxis(time); + case Body.Moon: + // See page 8, Table 2 in: + // https://astropedia.astrogeology.usgs.gov/alfresco/d/d/workspace/SpacesStore/28fd9e81-1964-44d6-a58b-fbbf61e64e15/WGCCRE2009reprint.pdf + const E1 = exports.DEG2RAD * (125.045 - 0.0529921 * d); + const E2 = exports.DEG2RAD * (250.089 - 0.1059842 * d); + const E3 = exports.DEG2RAD * (260.008 + 13.0120009 * d); + const E4 = exports.DEG2RAD * (176.625 + 13.3407154 * d); + const E5 = exports.DEG2RAD * (357.529 + 0.9856003 * d); + const E6 = exports.DEG2RAD * (311.589 + 26.4057084 * d); + const E7 = exports.DEG2RAD * (134.963 + 13.0649930 * d); + const E8 = exports.DEG2RAD * (276.617 + 0.3287146 * d); + const E9 = exports.DEG2RAD * (34.226 + 1.7484877 * d); + const E10 = exports.DEG2RAD * (15.134 - 0.1589763 * d); + const E11 = exports.DEG2RAD * (119.743 + 0.0036096 * d); + const E12 = exports.DEG2RAD * (239.961 + 0.1643573 * d); + const E13 = exports.DEG2RAD * (25.053 + 12.9590088 * d); + ra = (269.9949 + 0.0031 * T + - 3.8787 * Math.sin(E1) + - 0.1204 * Math.sin(E2) + + 0.0700 * Math.sin(E3) + - 0.0172 * Math.sin(E4) + + 0.0072 * Math.sin(E6) + - 0.0052 * Math.sin(E10) + + 0.0043 * Math.sin(E13)); + dec = (66.5392 + 0.0130 * T + + 1.5419 * Math.cos(E1) + + 0.0239 * Math.cos(E2) + - 0.0278 * Math.cos(E3) + + 0.0068 * Math.cos(E4) + - 0.0029 * Math.cos(E6) + + 0.0009 * Math.cos(E7) + + 0.0008 * Math.cos(E10) + - 0.0009 * Math.cos(E13)); + w = (38.3213 + (13.17635815 - 1.4e-12 * d) * d + + 3.5610 * Math.sin(E1) + + 0.1208 * Math.sin(E2) + - 0.0642 * Math.sin(E3) + + 0.0158 * Math.sin(E4) + + 0.0252 * Math.sin(E5) + - 0.0066 * Math.sin(E6) + - 0.0047 * Math.sin(E7) + - 0.0046 * Math.sin(E8) + + 0.0028 * Math.sin(E9) + + 0.0052 * Math.sin(E10) + + 0.0040 * Math.sin(E11) + + 0.0019 * Math.sin(E12) + - 0.0044 * Math.sin(E13)); + break; + case Body.Mars: + ra = (317.269202 - 0.10927547 * T + + 0.000068 * Math.sin(exports.DEG2RAD * (198.991226 + 19139.4819985 * T)) + + 0.000238 * Math.sin(exports.DEG2RAD * (226.292679 + 38280.8511281 * T)) + + 0.000052 * Math.sin(exports.DEG2RAD * (249.663391 + 57420.7251593 * T)) + + 0.000009 * Math.sin(exports.DEG2RAD * (266.183510 + 76560.6367950 * T)) + + 0.419057 * Math.sin(exports.DEG2RAD * (79.398797 + 0.5042615 * T))); + dec = (54.432516 - 0.05827105 * T + + 0.000051 * Math.cos(exports.DEG2RAD * (122.433576 + 19139.9407476 * T)) + + 0.000141 * Math.cos(exports.DEG2RAD * (43.058401 + 38280.8753272 * T)) + + 0.000031 * Math.cos(exports.DEG2RAD * (57.663379 + 57420.7517205 * T)) + + 0.000005 * Math.cos(exports.DEG2RAD * (79.476401 + 76560.6495004 * T)) + + 1.591274 * Math.cos(exports.DEG2RAD * (166.325722 + 0.5042615 * T))); + w = (176.049863 + 350.891982443297 * d + + 0.000145 * Math.sin(exports.DEG2RAD * (129.071773 + 19140.0328244 * T)) + + 0.000157 * Math.sin(exports.DEG2RAD * (36.352167 + 38281.0473591 * T)) + + 0.000040 * Math.sin(exports.DEG2RAD * (56.668646 + 57420.9295360 * T)) + + 0.000001 * Math.sin(exports.DEG2RAD * (67.364003 + 76560.2552215 * T)) + + 0.000001 * Math.sin(exports.DEG2RAD * (104.792680 + 95700.4387578 * T)) + + 0.584542 * Math.sin(exports.DEG2RAD * (95.391654 + 0.5042615 * T))); + break; + case Body.Jupiter: + const Ja = exports.DEG2RAD * (99.360714 + 4850.4046 * T); + const Jb = exports.DEG2RAD * (175.895369 + 1191.9605 * T); + const Jc = exports.DEG2RAD * (300.323162 + 262.5475 * T); + const Jd = exports.DEG2RAD * (114.012305 + 6070.2476 * T); + const Je = exports.DEG2RAD * (49.511251 + 64.3000 * T); + ra = (268.056595 - 0.006499 * T + + 0.000117 * Math.sin(Ja) + + 0.000938 * Math.sin(Jb) + + 0.001432 * Math.sin(Jc) + + 0.000030 * Math.sin(Jd) + + 0.002150 * Math.sin(Je)); + dec = (64.495303 + 0.002413 * T + + 0.000050 * Math.cos(Ja) + + 0.000404 * Math.cos(Jb) + + 0.000617 * Math.cos(Jc) + - 0.000013 * Math.cos(Jd) + + 0.000926 * Math.cos(Je)); + w = 284.95 + 870.536 * d; + break; + case Body.Saturn: + ra = 40.589 - 0.036 * T; + dec = 83.537 - 0.004 * T; + w = 38.90 + 810.7939024 * d; + break; + case Body.Uranus: + ra = 257.311; + dec = -15.175; + w = 203.81 - 501.1600928 * d; + break; + case Body.Neptune: + const N = exports.DEG2RAD * (357.85 + 52.316 * T); + ra = 299.36 + 0.70 * Math.sin(N); + dec = 43.46 - 0.51 * Math.cos(N); + w = 249.978 + 541.1397757 * d - 0.48 * Math.sin(N); + break; + case Body.Pluto: + ra = 132.993; + dec = -6.163; + w = 302.695 + 56.3625225 * d; + break; + default: + throw `Invalid body: ${body}`; + } + // Calculate the north pole vector using the given angles. + const radlat = dec * exports.DEG2RAD; + const radlon = ra * exports.DEG2RAD; + const rcoslat = Math.cos(radlat); + const north = new Vector(rcoslat * Math.cos(radlon), rcoslat * Math.sin(radlon), Math.sin(radlat), time); + return new AxisInfo(ra / 15, dec, w, north); +} +exports.RotationAxis = RotationAxis; +/** + * @brief Calculates one of the 5 Lagrange points for a pair of co-orbiting bodies. + * + * Given a more massive "major" body and a much less massive "minor" body, + * calculates one of the five Lagrange points in relation to the minor body's + * orbit around the major body. The parameter `point` is an integer that + * selects the Lagrange point as follows: + * + * 1 = the Lagrange point between the major body and minor body. + * 2 = the Lagrange point on the far side of the minor body. + * 3 = the Lagrange point on the far side of the major body. + * 4 = the Lagrange point 60 degrees ahead of the minor body's orbital position. + * 5 = the Lagrange point 60 degrees behind the minor body's orbital position. + * + * The function returns the state vector for the selected Lagrange point + * in J2000 mean equator coordinates (EQJ), with respect to the center of the + * major body. + * + * To calculate Sun/Earth Lagrange points, pass in `Body.Sun` for `major_body` + * and `Body.EMB` (Earth/Moon barycenter) for `minor_body`. + * For Lagrange points of the Sun and any other planet, pass in that planet + * (e.g. `Body.Jupiter`) for `minor_body`. + * To calculate Earth/Moon Lagrange points, pass in `Body.Earth` and `Body.Moon` + * for the major and minor bodies respectively. + * + * In some cases, it may be more efficient to call {@link LagrangePointFast}, + * especially when the state vectors have already been calculated, or are needed + * for some other purpose. + * + * @param {number} point + * An integer 1..5 that selects which of the Lagrange points to calculate. + * + * @param {FlexibleDateTime} date + * The time at which the Lagrange point is to be calculated. + * + * @param {Body} major_body + * The more massive of the co-orbiting bodies: `Body.Sun` or `Body.Earth`. + * + * @param {Body} minor_body + * The less massive of the co-orbiting bodies. See main remarks. + * + * @returns {StateVector} + * The position and velocity of the selected Lagrange point with respect to the major body's center. + */ +function LagrangePoint(point, date, major_body, minor_body) { + const time = MakeTime(date); + const major_mass = MassProduct(major_body); + const minor_mass = MassProduct(minor_body); + let major_state; + let minor_state; + // Calculate the state vectors for the major and minor bodies. + if (major_body === Body.Earth && minor_body === Body.Moon) { + // Use geocentric calculations for more precision. + // The Earth's geocentric state is trivial. + major_state = new StateVector(0, 0, 0, 0, 0, 0, time); + minor_state = GeoMoonState(time); + } + else { + major_state = HelioState(major_body, time); + minor_state = HelioState(minor_body, time); + } + return LagrangePointFast(point, major_state, major_mass, minor_state, minor_mass); +} +exports.LagrangePoint = LagrangePoint; +/** + * @brief Calculates one of the 5 Lagrange points from body masses and state vectors. + * + * Given a more massive "major" body and a much less massive "minor" body, + * calculates one of the five Lagrange points in relation to the minor body's + * orbit around the major body. The parameter `point` is an integer that + * selects the Lagrange point as follows: + * + * 1 = the Lagrange point between the major body and minor body. + * 2 = the Lagrange point on the far side of the minor body. + * 3 = the Lagrange point on the far side of the major body. + * 4 = the Lagrange point 60 degrees ahead of the minor body's orbital position. + * 5 = the Lagrange point 60 degrees behind the minor body's orbital position. + * + * The caller passes in the state vector and mass for both bodies. + * The state vectors can be in any orientation and frame of reference. + * The body masses are expressed as GM products, where G = the universal + * gravitation constant and M = the body's mass. Thus the units for + * `major_mass` and `minor_mass` must be au^3/day^2. + * Use {@link MassProduct} to obtain GM values for various solar system bodies. + * + * The function returns the state vector for the selected Lagrange point + * using the same orientation as the state vector parameters `major_state` and `minor_state`, + * and the position and velocity components are with respect to the major body's center. + * + * Consider calling {@link LagrangePoint}, instead of this function, for simpler usage in most cases. + * + * @param {number} point + * A value 1..5 that selects which of the Lagrange points to calculate. + * + * @param {StateVector} major_state + * The state vector of the major (more massive) of the pair of bodies. + * + * @param {number} major_mass + * The mass product GM of the major body. + * + * @param {StateVector} minor_state + * The state vector of the minor (less massive) of the pair of bodies. + * + * @param {number} minor_mass + * The mass product GM of the minor body. + * + * @returns {StateVector} + * The position and velocity of the selected Lagrange point with respect to the major body's center. + */ +function LagrangePointFast(point, major_state, major_mass, minor_state, minor_mass) { + const cos_60 = 0.5; + const sin_60 = 0.8660254037844386; /* sqrt(3) / 2 */ + if (point < 1 || point > 5) + throw `Invalid lagrange point ${point}`; + if (!Number.isFinite(major_mass) || major_mass <= 0.0) + throw 'Major mass must be a positive number.'; + if (!Number.isFinite(minor_mass) || minor_mass <= 0.0) + throw 'Minor mass must be a negative number.'; + // Find the relative position vector . + let dx = minor_state.x - major_state.x; + let dy = minor_state.y - major_state.y; + let dz = minor_state.z - major_state.z; + const R2 = (dx * dx + dy * dy + dz * dz); + // R = Total distance between the bodies. + const R = Math.sqrt(R2); + // Find the relative velocity vector . + const vx = minor_state.vx - major_state.vx; + const vy = minor_state.vy - major_state.vy; + const vz = minor_state.vz - major_state.vz; + let p; + if (point === 4 || point === 5) { + // For L4 and L5, we need to find points 60 degrees away from the + // line connecting the two bodies and in the instantaneous orbital plane. + // Define the instantaneous orbital plane as the unique plane that contains + // both the relative position vector and the relative velocity vector. + // Take the cross product of position and velocity to find a normal vector . + const nx = dy * vz - dz * vy; + const ny = dz * vx - dx * vz; + const nz = dx * vy - dy * vx; + // Take the cross product normal*position to get a tangential vector . + let ux = ny * dz - nz * dy; + let uy = nz * dx - nx * dz; + let uz = nx * dy - ny * dx; + // Convert the tangential direction vector to a unit vector. + const U = Math.sqrt(ux * ux + uy * uy + uz * uz); + ux /= U; + uy /= U; + uz /= U; + // Convert the relative position vector into a unit vector. + dx /= R; + dy /= R; + dz /= R; + // Now we have two perpendicular unit vectors in the orbital plane: 'd' and 'u'. + // Create new unit vectors rotated (+/-)60 degrees from the radius/tangent directions. + const vert = (point == 4) ? +sin_60 : -sin_60; + // Rotated radial vector + const Dx = cos_60 * dx + vert * ux; + const Dy = cos_60 * dy + vert * uy; + const Dz = cos_60 * dz + vert * uz; + // Rotated tangent vector + const Ux = cos_60 * ux - vert * dx; + const Uy = cos_60 * uy - vert * dy; + const Uz = cos_60 * uz - vert * dz; + // Calculate L4/L5 positions relative to the major body. + const px = R * Dx; + const py = R * Dy; + const pz = R * Dz; + // Use dot products to find radial and tangential components of the relative velocity. + const vrad = vx * dx + vy * dy + vz * dz; + const vtan = vx * ux + vy * uy + vz * uz; + // Calculate L4/L5 velocities. + const pvx = vrad * Dx + vtan * Ux; + const pvy = vrad * Dy + vtan * Uy; + const pvz = vrad * Dz + vtan * Uz; + p = new StateVector(px, py, pz, pvx, pvy, pvz, major_state.t); + } + else { + // Calculate the distances of each body from their mutual barycenter. + // r1 = negative distance of major mass from barycenter (e.g. Sun to the left of barycenter) + // r2 = positive distance of minor mass from barycenter (e.g. Earth to the right of barycenter) + const r1 = -R * (minor_mass / (major_mass + minor_mass)); + const r2 = +R * (major_mass / (major_mass + minor_mass)); + // Calculate the square of the angular orbital speed in [rad^2 / day^2]. + const omega2 = (major_mass + minor_mass) / (R2 * R); + // Use Newton's Method to numerically solve for the location where + // outward centrifugal acceleration in the rotating frame of reference + // is equal to net inward gravitational acceleration. + // First derive a good initial guess based on approximate analysis. + let scale, numer1, numer2; + if (point === 1 || point === 2) { + scale = (major_mass / (major_mass + minor_mass)) * Math.cbrt(minor_mass / (3.0 * major_mass)); + numer1 = -major_mass; // The major mass is to the left of L1 and L2. + if (point == 1) { + scale = 1.0 - scale; + numer2 = +minor_mass; // The minor mass is to the right of L1. + } + else { + scale = 1.0 + scale; + numer2 = -minor_mass; // The minor mass is to the left of L2. + } + } + else if (point === 3) { + scale = ((7.0 / 12.0) * minor_mass - major_mass) / (minor_mass + major_mass); + numer1 = +major_mass; // major mass is to the right of L3. + numer2 = +minor_mass; // minor mass is to the right of L3. + } + else { + throw `Invalid Langrage point ${point}. Must be an integer 1..5.`; + } + // Iterate Newton's Method until it converges. + let x = R * scale - r1; + let deltax; + do { + const dr1 = x - r1; + const dr2 = x - r2; + const accel = omega2 * x + numer1 / (dr1 * dr1) + numer2 / (dr2 * dr2); + const deriv = omega2 - 2 * numer1 / (dr1 * dr1 * dr1) - 2 * numer2 / (dr2 * dr2 * dr2); + deltax = accel / deriv; + x -= deltax; + } while (Math.abs(deltax / R) > 1.0e-14); + scale = (x - r1) / R; + p = new StateVector(scale * dx, scale * dy, scale * dz, scale * vx, scale * vy, scale * vz, major_state.t); + } + return p; +} +exports.LagrangePointFast = LagrangePointFast; +/** + * @brief A simulation of zero or more small bodies moving through the Solar System. + * + * This class calculates the movement of arbitrary small bodies, + * such as asteroids or comets, that move through the Solar System. + * It does so by calculating the gravitational forces on the small bodies + * from the Sun and planets. The user of this class supplies a + * list of initial positions and velocities for the small bodies. + * Then the class can update the positions and velocities over small + * time steps. + */ +class GravitySimulator { + /** + * @brief Creates a gravity simulation object. + * + * @param {Body} originBody + * Specifies the origin of the reference frame. + * All position vectors and velocity vectors will use `originBody` + * as the origin of the coordinate system. + * This origin applies to all the input vectors provided in the + * `bodyStates` parameter of this function, along with all + * output vectors returned by {@link GravitySimulator#Update}. + * Most callers will want to provide one of the following: + * `Body.Sun` for heliocentric coordinates, + * `Body.SSB` for solar system barycentric coordinates, + * or `Body.Earth` for geocentric coordinates. Note that the + * gravity simulator does not correct for light travel time; + * all state vectors are tied to a Newtonian "instantaneous" time. + * + * @param {FlexibleDateTime} date + * The initial time at which to start the simulation. + * + * @param {StateVector[]} bodyStates + * An array of zero or more initial state vectors (positions and velocities) + * of the small bodies to be simulated. + * The caller must know the positions and velocities of the small bodies at an initial moment in time. + * Their positions and velocities are expressed with respect to `originBody`, using equatorial + * J2000 orientation (EQJ). + * Positions are expressed in astronomical units (AU). + * Velocities are expressed in AU/day. + * All the times embedded within the state vectors must exactly match `date`, + * or this constructor will throw an exception. + */ + constructor(originBody, date, bodyStates) { + const time = MakeTime(date); + this.originBody = originBody; + // Verify that the state vectors have matching times. + for (let b of bodyStates) { + if (b.t.tt !== time.tt) { + throw 'Inconsistent times in bodyStates'; + } + } + // Create a stub list that we append to later. + // We just need the stub to put into `this.curr`. + const smallBodyList = []; + // Calculate the states of the Sun and planets. + const largeBodyDict = GravitySimulator.CalcSolarSystem(time); + this.curr = new GravSimEndpoint(time, largeBodyDict, smallBodyList); + // Convert origin-centric bodyStates vectors into barycentric body_grav_calc_t array. + const o = this.InternalBodyState(originBody); + for (let b of bodyStates) { + const r = new TerseVector(b.x + o.r.x, b.y + o.r.y, b.z + o.r.z); + const v = new TerseVector(b.vx + o.v.x, b.vy + o.v.y, b.vz + o.v.z); + const a = TerseVector.zero(); + smallBodyList.push(new body_grav_calc_t(time.tt, r, v, a)); + } + // Calculate the net acceleration experienced by the small bodies. + this.CalcBodyAccelerations(); + // To prepare for a possible swap operation, duplicate the current state into the previous state. + this.prev = this.Duplicate(); + } + /** + * @brief The body that was selected as the coordinate origin when this simulator was created. + */ + get OriginBody() { + return this.originBody; + } + /** + * @brief The time represented by the current step of the gravity simulation. + */ + get Time() { + return this.curr.time; + } + /** + * Advances the gravity simulation by a small time step. + * + * Updates the simulation of the user-supplied small bodies + * to the time indicated by the `date` parameter. + * Returns an array of state vectors for the simulated bodies. + * The array is in the same order as the original array that + * was used to construct this simulator object. + * The positions and velocities in the returned array are + * referenced to the `originBody` that was used to construct + * this simulator. + * + * @param {FlexibleDateTime} date + * A time that is a small increment away from the current simulation time. + * It is up to the developer to figure out an appropriate time increment. + * Depending on the trajectories, a smaller or larger increment + * may be needed for the desired accuracy. Some experimentation may be needed. + * Generally, bodies that stay in the outer Solar System and move slowly can + * use larger time steps. Bodies that pass into the inner Solar System and + * move faster will need a smaller time step to maintain accuracy. + * The `date` value may be after or before the current simulation time + * to move forward or backward in time. + * + * @return {StateVector[]} + * An array of state vectors, one for each simulated small body. + */ + Update(date) { + const time = MakeTime(date); + const dt = time.tt - this.curr.time.tt; + if (dt === 0.0) { + // Special case: the time has not changed, so skip the usual physics calculations. + // This allows another way for the caller to query the current body states. + // It is also necessary to avoid dividing by `dt` if `dt` is zero. + // To prepare for a possible swap operation, duplicate the current state into the previous state. + this.prev = this.Duplicate(); + } + else { + // Exchange the current state with the previous state. Then calculate the new current state. + this.Swap(); + // Update the current time. + this.curr.time = time; + // Calculate the positions and velocities of the Sun and planets at the given time. + this.curr.gravitators = GravitySimulator.CalcSolarSystem(time); + // Estimate the positions of the small bodies as if their existing + // accelerations apply across the whole time interval. + for (let i = 0; i < this.curr.bodies.length; ++i) { + const p = this.prev.bodies[i]; + this.curr.bodies[i].r = UpdatePosition(dt, p.r, p.v, p.a); + } + // Calculate the acceleration experienced by the small bodies at + // their respective approximate next locations. + this.CalcBodyAccelerations(); + for (let i = 0; i < this.curr.bodies.length; ++i) { + // Calculate the average of the acceleration vectors + // experienced by the previous body positions and + // their estimated next positions. + // These become estimates of the mean effective accelerations + // over the whole interval. + const p = this.prev.bodies[i]; + const c = this.curr.bodies[i]; + const acc = p.a.mean(c.a); + // Refine the estimates of position and velocity at the next time step, + // using the mean acceleration as a better approximation of the + // continuously changing acceleration acting on each body. + c.tt = time.tt; + c.r = UpdatePosition(dt, p.r, p.v, acc); + c.v = UpdateVelocity(dt, p.v, acc); + } + // Re-calculate accelerations experienced by each body. + // These will be needed for the next simulation step (if any). + // Also, they will be potentially useful if some day we add + // a function to query the acceleration vectors for the bodies. + this.CalcBodyAccelerations(); + } + // Translate our internal calculations of body positions and velocities + // into state vectors that the caller can understand. + // We have to convert the internal type body_grav_calc_t to the public type StateVector. + // Also convert from barycentric coordinates to coordinates based on the selected origin body. + const bodyStates = []; + const ostate = this.InternalBodyState(this.originBody); + for (let bcalc of this.curr.bodies) { + bodyStates.push(new StateVector(bcalc.r.x - ostate.r.x, bcalc.r.y - ostate.r.y, bcalc.r.z - ostate.r.z, bcalc.v.x - ostate.v.x, bcalc.v.y - ostate.v.y, bcalc.v.z - ostate.v.z, time)); + } + return bodyStates; + } + /** + * Exchange the current time step with the previous time step. + * + * Sometimes it is helpful to "explore" various times near a given + * simulation time step, while repeatedly returning to the original + * time step. For example, when backdating a position for light travel + * time, the caller may wish to repeatedly try different amounts of + * backdating. When the backdating solver has converged, the caller + * wants to leave the simulation in its original state. + * + * This function allows a single "undo" of a simulation, and does so + * very efficiently. + * + * Usually this function will be called immediately after a matching + * call to {@link GravitySimulator#Update}. It has the effect of rolling + * back the most recent update. If called twice in a row, it reverts + * the swap and thus has no net effect. + * + * The constructor initializes the current state and previous + * state to be identical. Both states represent the `time` parameter that was + * passed into the constructor. Therefore, `Swap` will + * have no effect from the caller's point of view when passed a simulator + * that has not yet been updated by a call to {@link GravitySimulator#Update}. + */ + Swap() { + const swap = this.curr; + this.curr = this.prev; + this.prev = swap; + } + /** + * Get the position and velocity of a Solar System body included in the simulation. + * + * In order to simulate the movement of small bodies through the Solar System, + * the simulator needs to calculate the state vectors for the Sun and planets. + * + * If an application wants to know the positions of one or more of the planets + * in addition to the small bodies, this function provides a way to obtain + * their state vectors. This is provided for the sake of efficiency, to avoid + * redundant calculations. + * + * The state vector is returned relative to the position and velocity + * of the `originBody` parameter that was passed to this object's constructor. + * + * @param {Body} body + * The Sun, Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, or Neptune. + */ + SolarSystemBodyState(body) { + const bstate = this.InternalBodyState(body); + const ostate = this.InternalBodyState(this.originBody); + return ExportState(bstate.sub(ostate), this.curr.time); + } + InternalBodyState(body) { + if (body === Body.SSB) + return new body_state_t(this.curr.time.tt, TerseVector.zero(), TerseVector.zero()); + const bstate = this.curr.gravitators[body]; + if (bstate) + return bstate; + throw `Invalid body: ${body}`; + } + static CalcSolarSystem(time) { + const dict = {}; + // Start with the SSB at zero position and velocity. + const ssb = new body_state_t(time.tt, TerseVector.zero(), TerseVector.zero()); + // Calculate the heliocentric position of each planet, and adjust the SSB + // based each planet's pull on the Sun. + dict[Body.Mercury] = AdjustBarycenterPosVel(ssb, time.tt, Body.Mercury, MERCURY_GM); + dict[Body.Venus] = AdjustBarycenterPosVel(ssb, time.tt, Body.Venus, VENUS_GM); + dict[Body.Earth] = AdjustBarycenterPosVel(ssb, time.tt, Body.Earth, EARTH_GM + MOON_GM); + dict[Body.Mars] = AdjustBarycenterPosVel(ssb, time.tt, Body.Mars, MARS_GM); + dict[Body.Jupiter] = AdjustBarycenterPosVel(ssb, time.tt, Body.Jupiter, JUPITER_GM); + dict[Body.Saturn] = AdjustBarycenterPosVel(ssb, time.tt, Body.Saturn, SATURN_GM); + dict[Body.Uranus] = AdjustBarycenterPosVel(ssb, time.tt, Body.Uranus, URANUS_GM); + dict[Body.Neptune] = AdjustBarycenterPosVel(ssb, time.tt, Body.Neptune, NEPTUNE_GM); + // Convert planet states from heliocentric to barycentric. + for (let body in dict) { + dict[body].r.decr(ssb.r); + dict[body].v.decr(ssb.v); + } + // Convert heliocentric SSB to barycentric Sun. + dict[Body.Sun] = new body_state_t(time.tt, ssb.r.neg(), ssb.v.neg()); + return dict; + } + CalcBodyAccelerations() { + // Calculate the gravitational acceleration experienced by the simulated small bodies. + for (let b of this.curr.bodies) { + b.a = TerseVector.zero(); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Sun].r, SUN_GM); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Mercury].r, MERCURY_GM); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Venus].r, VENUS_GM); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Earth].r, EARTH_GM + MOON_GM); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Mars].r, MARS_GM); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Jupiter].r, JUPITER_GM); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Saturn].r, SATURN_GM); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Uranus].r, URANUS_GM); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Neptune].r, NEPTUNE_GM); + } + } + static AddAcceleration(acc, smallPos, majorPos, gm) { + const dx = majorPos.x - smallPos.x; + const dy = majorPos.y - smallPos.y; + const dz = majorPos.z - smallPos.z; + const r2 = dx * dx + dy * dy + dz * dz; + const pull = gm / (r2 * Math.sqrt(r2)); + acc.x += dx * pull; + acc.y += dy * pull; + acc.z += dz * pull; + } + Duplicate() { + // Copy the current state into the previous state, so that both become the same moment in time. + const gravitators = {}; + for (let body in this.curr.gravitators) { + gravitators[body] = this.curr.gravitators[body].clone(); + } + const bodies = []; + for (let b of this.curr.bodies) { + bodies.push(b.clone()); + } + return new GravSimEndpoint(this.curr.time, gravitators, bodies); + } +} +exports.GravitySimulator = GravitySimulator; +class GravSimEndpoint { + constructor(time, gravitators, bodies) { + this.time = time; + this.gravitators = gravitators; + this.bodies = bodies; + } +} diff --git a/node_modules/astronomy-engine/astronomy.min.js b/node_modules/astronomy-engine/astronomy.min.js new file mode 100644 index 0000000..b16e546 --- /dev/null +++ b/node_modules/astronomy-engine/astronomy.min.js @@ -0,0 +1,338 @@ +/* + MIT + + + Astronomy library for JavaScript (browser and Node.js). + https://github.com/cosinekitty/astronomy + + MIT License + + Copyright (c) 2019-2023 Don Cross + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ +var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.createTemplateTagFirstArg=function(a){return a.raw=a};$jscomp.createTemplateTagFirstArgWithRaw=function(a,b){a.raw=b;return a};$jscomp.arrayIteratorImpl=function(a){var b=0;return function(){return barguments.length)return arguments.length?Math.abs(arguments[0]):0;var c,d,e;for(c=e=0;ce){if(!e)return e;for(c=d=0;cb?-c:c}},"es6","es3");Object.defineProperty(exports,"__esModule",{value:!0}); +exports.GeoEmbState=exports.GeoMoonState=exports.EclipticGeoMoon=exports.GeoMoon=exports.Ecliptic=exports.ObserverGravity=exports.VectorObserver=exports.ObserverState=exports.ObserverVector=exports.Equator=exports.SunPosition=exports.Observer=exports.Horizon=exports.EclipticCoordinates=exports.HorizontalCoordinates=exports.MakeRotation=exports.RotationMatrix=exports.EquatorialCoordinates=exports.Spherical=exports.StateVector=exports.Vector=exports.SiderealTime=exports.Libration=exports.LibrationInfo= +exports.CalcMoonCount=exports.e_tilt=exports.MakeTime=exports.AstroTime=exports.SetDeltaTFunction=exports.DeltaT_JplHorizons=exports.DeltaT_EspenakMeeus=exports.PlanetOrbitalPeriod=exports.DefineStar=exports.Body=exports.AngleBetween=exports.MassProduct=exports.CALLISTO_RADIUS_KM=exports.GANYMEDE_RADIUS_KM=exports.EUROPA_RADIUS_KM=exports.IO_RADIUS_KM=exports.JUPITER_MEAN_RADIUS_KM=exports.JUPITER_POLAR_RADIUS_KM=exports.JUPITER_EQUATORIAL_RADIUS_KM=exports.RAD2HOUR=exports.RAD2DEG=exports.HOUR2RAD= +exports.DEG2RAD=exports.AU_PER_LY=exports.KM_PER_AU=exports.C_AUDAY=void 0; +exports.VectorFromHorizon=exports.HorizonFromVector=exports.SphereFromVector=exports.EquatorFromVector=exports.VectorFromSphere=exports.Pivot=exports.IdentityMatrix=exports.CombineRotation=exports.InverseRotation=exports.NextPlanetApsis=exports.SearchPlanetApsis=exports.NextLunarApsis=exports.SearchLunarApsis=exports.Apsis=exports.ApsisKind=exports.SearchPeakMagnitude=exports.SearchMaxElongation=exports.Elongation=exports.ElongationEvent=exports.Seasons=exports.SeasonInfo=exports.HourAngle=exports.SearchHourAngle= +exports.HourAngleEvent=exports.SearchAltitude=exports.SearchRiseSet=exports.Atmosphere=exports.AtmosphereInfo=exports.NextMoonQuarter=exports.SearchMoonQuarter=exports.MoonQuarter=exports.SearchMoonPhase=exports.MoonPhase=exports.SearchRelativeLongitude=exports.Illumination=exports.IlluminationInfo=exports.EclipticLongitude=exports.AngleFromSun=exports.PairLongitude=exports.SearchSunLongitude=exports.Search=exports.HelioState=exports.BaryState=exports.GeoVector=exports.BackdatePosition=exports.CorrectLightTravel= +exports.HelioDistance=exports.HelioVector=exports.JupiterMoons=exports.JupiterMoonsInfo=void 0; +exports.GravitySimulator=exports.LagrangePointFast=exports.LagrangePoint=exports.RotationAxis=exports.AxisInfo=exports.NextMoonNode=exports.SearchMoonNode=exports.NodeEventInfo=exports.NodeEventKind=exports.NextTransit=exports.SearchTransit=exports.TransitInfo=exports.NextLocalSolarEclipse=exports.SearchLocalSolarEclipse=exports.LocalSolarEclipseInfo=exports.EclipseEvent=exports.NextGlobalSolarEclipse=exports.SearchGlobalSolarEclipse=exports.NextLunarEclipse=exports.GlobalSolarEclipseInfo=exports.SearchLunarEclipse= +exports.LunarEclipseInfo=exports.EclipseKind=exports.Constellation=exports.ConstellationInfo=exports.Rotation_EQD_ECT=exports.Rotation_ECT_EQD=exports.Rotation_GAL_EQJ=exports.Rotation_EQJ_GAL=exports.Rotation_HOR_ECL=exports.Rotation_ECL_HOR=exports.Rotation_ECL_EQD=exports.Rotation_EQD_ECL=exports.Rotation_EQJ_HOR=exports.Rotation_HOR_EQJ=exports.Rotation_HOR_EQD=exports.Rotation_EQD_HOR=exports.Rotation_EQD_EQJ=exports.Rotation_ECT_EQJ=exports.Rotation_EQJ_ECT=exports.Rotation_EQJ_EQD=exports.Rotation_ECL_EQJ= +exports.Rotation_EQJ_ECL=exports.RotateState=exports.RotateVector=exports.InverseRefraction=exports.Refraction=void 0;exports.C_AUDAY=173.1446326846693;exports.KM_PER_AU=1.4959787069098932E8;exports.AU_PER_LY=63241.07708807546;exports.DEG2RAD=.017453292519943295;exports.HOUR2RAD=.26179938779914946;exports.RAD2DEG=57.29577951308232;exports.RAD2HOUR=3.819718634205488;exports.JUPITER_EQUATORIAL_RADIUS_KM=71492;exports.JUPITER_POLAR_RADIUS_KM=66854;exports.JUPITER_MEAN_RADIUS_KM=69911; +exports.IO_RADIUS_KM=1821.6;exports.EUROPA_RADIUS_KM=1560.8;exports.GANYMEDE_RADIUS_KM=2631.2;exports.CALLISTO_RADIUS_KM=2410.3; +var DAYS_PER_TROPICAL_YEAR=365.24217,J2000=new Date("2000-01-01T12:00:00Z"),PI2=2*Math.PI,ARC=180/Math.PI*3600,ASEC2RAD=4.84813681109536E-6,ASEC180=648E3,ASEC360=2*ASEC180,ANGVEL=7.292115E-5,AU_PER_PARSEC=ASEC180/Math.PI,SUN_MAG_1AU=-.17-5*Math.log10(AU_PER_PARSEC),MEAN_SYNODIC_MONTH=29.530588,SECONDS_PER_DAY=86400,MILLIS_PER_DAY=1E3*SECONDS_PER_DAY,SOLAR_DAYS_PER_SIDEREAL_DAY=.9972695717592592,SUN_RADIUS_KM=695700,SUN_RADIUS_AU=SUN_RADIUS_KM/exports.KM_PER_AU,EARTH_FLATTENING=.996647180302104,EARTH_FLATTENING_SQUARED= +EARTH_FLATTENING*EARTH_FLATTENING,EARTH_EQUATORIAL_RADIUS_KM=6378.1366,EARTH_EQUATORIAL_RADIUS_AU=EARTH_EQUATORIAL_RADIUS_KM/exports.KM_PER_AU,EARTH_POLAR_RADIUS_KM=EARTH_EQUATORIAL_RADIUS_KM*EARTH_FLATTENING,EARTH_MEAN_RADIUS_KM=6371,EARTH_ATMOSPHERE_KM=88,EARTH_ECLIPSE_RADIUS_KM=EARTH_MEAN_RADIUS_KM+EARTH_ATMOSPHERE_KM,MOON_EQUATORIAL_RADIUS_KM=1738.1,MOON_EQUATORIAL_RADIUS_AU=MOON_EQUATORIAL_RADIUS_KM/exports.KM_PER_AU,MOON_MEAN_RADIUS_KM=1737.4,MOON_POLAR_RADIUS_KM=1736,MOON_POLAR_RADIUS_AU=MOON_POLAR_RADIUS_KM/ +exports.KM_PER_AU,REFRACTION_NEAR_HORIZON=34/60,EARTH_MOON_MASS_RATIO=81.30056,SUN_GM=2.959122082855911E-4,MERCURY_GM=4.912547451450812E-11,VENUS_GM=7.243452486162703E-10,EARTH_GM=8.887692390113509E-10,MARS_GM=9.549535105779258E-11,JUPITER_GM=2.825345909524226E-7,SATURN_GM=8.459715185680659E-8,URANUS_GM=1.292024916781969E-8,NEPTUNE_GM=1.524358900784276E-8,PLUTO_GM=2.18869976542597E-12,MOON_GM=EARTH_GM/EARTH_MOON_MASS_RATIO; +function MassProduct(a){switch(a){case Body.Sun:return SUN_GM;case Body.Mercury:return MERCURY_GM;case Body.Venus:return VENUS_GM;case Body.Earth:return EARTH_GM;case Body.Moon:return MOON_GM;case Body.EMB:return EARTH_GM+MOON_GM;case Body.Mars:return MARS_GM;case Body.Jupiter:return JUPITER_GM;case Body.Saturn:return SATURN_GM;case Body.Uranus:return URANUS_GM;case Body.Neptune:return NEPTUNE_GM;case Body.Pluto:return PLUTO_GM;default:throw"Do not know mass product for body: "+a;}} +exports.MassProduct=MassProduct;function VerifyBoolean(a){if(!0!==a&&!1!==a)throw console.trace(),"Value is not boolean: "+a;return a}function VerifyNumber(a){if(!Number.isFinite(a))throw console.trace(),"Value is not a finite number: "+a;return a}function Frac(a){return a-Math.floor(a)} +function AngleBetween(a,b){var c=a.x*a.x+a.y*a.y+a.z*a.z;if(1E-8>Math.abs(c))throw"AngleBetween: first vector is too short.";var d=b.x*b.x+b.y*b.y+b.z*b.z;if(1E-8>Math.abs(d))throw"AngleBetween: second vector is too short.";a=(a.x*b.x+a.y*b.y+a.z*b.z)/Math.sqrt(c*d);return-1>=a?180:1<=a?0:exports.RAD2DEG*Math.acos(a)}exports.AngleBetween=AngleBetween;var Body; +(function(a){a.Sun="Sun";a.Moon="Moon";a.Mercury="Mercury";a.Venus="Venus";a.Earth="Earth";a.Mars="Mars";a.Jupiter="Jupiter";a.Saturn="Saturn";a.Uranus="Uranus";a.Neptune="Neptune";a.Pluto="Pluto";a.SSB="SSB";a.EMB="EMB";a.Star1="Star1";a.Star2="Star2";a.Star3="Star3";a.Star4="Star4";a.Star5="Star5";a.Star6="Star6";a.Star7="Star7";a.Star8="Star8"})(Body=exports.Body||(exports.Body={})); +var StarList=[Body.Star1,Body.Star2,Body.Star3,Body.Star4,Body.Star5,Body.Star6,Body.Star7,Body.Star8],StarTable=[{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0},{ra:0,dec:0,dist:0}];function GetStar(a){a=StarList.indexOf(a);return 0<=a?StarTable[a]:null}function UserDefinedStar(a){return(a=GetStar(a))&&0b||24<=b)throw"Invalid right ascension for star: "+b;if(-90>c||90d)throw"Invalid star distance: "+d;e.ra=b;e.dec=c;e.dist=d*exports.AU_PER_LY}exports.DefineStar=DefineStar;var PrecessDirection;(function(a){a[a.From2000=0]="From2000";a[a.Into2000=1]="Into2000"})(PrecessDirection||(PrecessDirection={})); +var Planet={Mercury:{OrbitalPeriod:87.969},Venus:{OrbitalPeriod:224.701},Earth:{OrbitalPeriod:365.256},Mars:{OrbitalPeriod:686.98},Jupiter:{OrbitalPeriod:4332.589},Saturn:{OrbitalPeriod:10759.22},Uranus:{OrbitalPeriod:30685.4},Neptune:{OrbitalPeriod:60189},Pluto:{OrbitalPeriod:90560}};function PlanetOrbitalPeriod(a){if(a in Planet)return Planet[a].OrbitalPeriod;throw"Unknown orbital period for: "+a;}exports.PlanetOrbitalPeriod=PlanetOrbitalPeriod; +var vsop={Mercury:[[[[4.40250710144,0,0],[.40989414977,1.48302034195,26087.9031415742],[.050462942,4.47785489551,52175.8062831484],[.00855346844,1.16520322459,78263.70942472259],[.00165590362,4.11969163423,104351.61256629678],[3.4561897E-4,.77930768443,130439.51570787099],[7.583476E-5,3.71348404924,156527.41884944518]],[[26087.90313685529,0,0],[.01131199811,6.21874197797,26087.9031415742],[.00292242298,3.04449355541,52175.8062831484],[7.5775081E-4,6.08568821653,78263.70942472259],[1.9676525E-4,2.80965111777, +104351.61256629678]]],[[[.11737528961,1.98357498767,26087.9031415742],[.02388076996,5.03738959686,52175.8062831484],[.01222839532,3.14159265359,0],[.0054325181,1.79644363964,78263.70942472259],[.0012977877,4.83232503958,104351.61256629678],[3.1866927E-4,1.58088495658,130439.51570787099],[7.963301E-5,4.60972126127,156527.41884944518]],[[.00274646065,3.95008450011,26087.9031415742],[9.9737713E-4,3.14159265359,0]]],[[[.39528271651,0,0],[.07834131818,6.19233722598,26087.9031415742],[.00795525558,2.95989690104, +52175.8062831484],[.00121281764,6.01064153797,78263.70942472259],[2.1921969E-4,2.77820093972,104351.61256629678],[4.354065E-5,5.82894543774,130439.51570787099]],[[.0021734774,4.65617158665,26087.9031415742],[4.4141826E-4,1.42385544001,52175.8062831484]]]],Venus:[[[[3.17614666774,0,0],[.01353968419,5.59313319619,10213.285546211],[8.9891645E-4,5.30650047764,20426.571092422],[5.477194E-5,4.41630661466,7860.4193924392],[3.455741E-5,2.6996444782,11790.6290886588],[2.372061E-5,2.99377542079,3930.2096962196], +[1.317168E-5,5.18668228402,26.2983197998],[1.664146E-5,4.25018630147,1577.3435424478],[1.438387E-5,4.15745084182,9683.5945811164],[1.200521E-5,6.15357116043,30639.856638633]],[[10213.28554621638,0,0],[9.5617813E-4,2.4640651111,10213.285546211],[7.787201E-5,.6247848222,20426.571092422]]],[[[.05923638472,.26702775812,10213.285546211],[4.0107978E-4,1.14737178112,20426.571092422],[3.2814918E-4,3.14159265359,0]],[[.00287821243,1.88964962838,10213.285546211]]],[[[.72334820891,0,0],[.00489824182,4.02151831717, +10213.285546211],[1.658058E-5,4.90206728031,20426.571092422],[1.378043E-5,1.12846591367,11790.6290886588],[1.632096E-5,2.84548795207,7860.4193924392],[4.98395E-6,2.58682193892,9683.5945811164],[2.21985E-6,2.01346696541,19367.1891622328],[2.37454E-6,2.55136053886,15720.8387848784]],[[3.4551041E-4,.89198706276,10213.285546211]]]],Earth:[[[[1.75347045673,0,0],[.03341656453,4.66925680415,6283.0758499914],[3.4894275E-4,4.62610242189,12566.1516999828],[3.417572E-5,2.82886579754,3.523118349],[3.497056E-5, +2.74411783405,5753.3848848968],[3.135899E-5,3.62767041756,77713.7714681205],[2.676218E-5,4.41808345438,7860.4193924392],[2.342691E-5,6.13516214446,3930.2096962196],[1.273165E-5,2.03709657878,529.6909650946],[1.324294E-5,.74246341673,11506.7697697936],[9.01854E-6,2.04505446477,26.2983197998],[1.199167E-5,1.10962946234,1577.3435424478],[8.57223E-6,3.50849152283,398.1490034082],[7.79786E-6,1.17882681962,5223.6939198022],[9.9025E-6,5.23268072088,5884.9268465832],[7.53141E-6,2.53339052847,5507.5532386674], +[5.05267E-6,4.58292599973,18849.2275499742],[4.92392E-6,4.20505711826,775.522611324],[3.56672E-6,2.91954114478,.0673103028],[2.84125E-6,1.89869240932,796.2980068164],[2.42879E-6,.34481445893,5486.777843175],[3.17087E-6,5.84901948512,11790.6290886588],[2.71112E-6,.31486255375,10977.078804699],[2.06217E-6,4.80646631478,2544.3144198834],[2.05478E-6,1.86953770281,5573.1428014331],[2.02318E-6,2.45767790232,6069.7767545534],[1.26225E-6,1.08295459501,20.7753954924],[1.55516E-6,.83306084617,213.299095438]], +[[6283.0758499914,0,0],[.00206058863,2.67823455808,6283.0758499914],[4.303419E-5,2.63512233481,12566.1516999828]],[[8.721859E-5,1.07253635559,6283.0758499914]]],[[],[[.00227777722,3.4137662053,6283.0758499914],[3.805678E-5,3.37063423795,12566.1516999828]]],[[[1.00013988784,0,0],[.01670699632,3.09846350258,6283.0758499914],[1.3956024E-4,3.05524609456,12566.1516999828],[3.08372E-5,5.19846674381,77713.7714681205],[1.628463E-5,1.17387558054,5753.3848848968],[1.575572E-5,2.84685214877,7860.4193924392], +[9.24799E-6,5.45292236722,11506.7697697936],[5.42439E-6,4.56409151453,3930.2096962196],[4.7211E-6,3.66100022149,5884.9268465832],[8.5831E-7,1.27079125277,161000.6857376741],[5.7056E-7,2.01374292245,83996.84731811189],[5.5736E-7,5.2415979917,71430.69561812909],[1.74844E-6,3.01193636733,18849.2275499742],[2.43181E-6,4.2734953079,11790.6290886588]],[[.00103018607,1.10748968172,6283.0758499914],[1.721238E-5,1.06442300386,12566.1516999828]],[[4.359385E-5,5.78455133808,6283.0758499914]]]],Mars:[[[[6.20347711581, +0,0],[.18656368093,5.0503710027,3340.6124266998],[.01108216816,5.40099836344,6681.2248533996],[9.1798406E-4,5.75478744667,10021.8372800994],[2.7744987E-4,5.97049513147,3.523118349],[1.0610235E-4,2.93958560338,2281.2304965106],[1.2315897E-4,.84956094002,2810.9214616052],[8.926784E-5,4.15697846427,.0172536522],[8.715691E-5,6.11005153139,13362.4497067992],[6.797556E-5,.36462229657,398.1490034082],[7.774872E-5,3.33968761376,5621.8429232104],[3.575078E-5,1.6618650571,2544.3144198834],[4.161108E-5,.22814971327, +2942.4634232916],[3.075252E-5,.85696614132,191.4482661116],[2.628117E-5,.64806124465,3337.0893083508],[2.937546E-5,6.07893711402,.0673103028],[2.389414E-5,5.03896442664,796.2980068164],[2.579844E-5,.02996736156,3344.1355450488],[1.528141E-5,1.14979301996,6151.533888305],[1.798806E-5,.65634057445,529.6909650946],[1.264357E-5,3.62275122593,5092.1519581158],[1.286228E-5,3.06796065034,2146.1654164752],[1.546404E-5,2.91579701718,1751.539531416],[1.024902E-5,3.69334099279,8962.4553499102],[8.91566E-6,.18293837498, +16703.062133499],[8.58759E-6,2.4009381194,2914.0142358238],[8.32715E-6,2.46418619474,3340.5951730476],[8.3272E-6,4.49495782139,3340.629680352],[7.12902E-6,3.66335473479,1059.3819301892],[7.48723E-6,3.82248614017,155.4203994342],[7.23861E-6,.67497311481,3738.761430108],[6.35548E-6,2.92182225127,8432.7643848156],[6.55162E-6,.48864064125,3127.3133312618],[5.50474E-6,3.81001042328,.9803210682],[5.5275E-6,4.47479317037,1748.016413067],[4.25966E-6,.55364317304,6283.0758499914],[4.15131E-6,.49662285038, +213.299095438],[4.72167E-6,3.62547124025,1194.4470102246],[3.06551E-6,.38052848348,6684.7479717486],[3.12141E-6,.99853944405,6677.7017350506],[2.93198E-6,4.22131299634,20.7753954924],[3.02375E-6,4.48618007156,3532.0606928114],[2.74027E-6,.54222167059,3340.545116397],[2.81079E-6,5.88163521788,1349.8674096588],[2.31183E-6,1.28242156993,3870.3033917944],[2.83602E-6,5.7688543494,3149.1641605882],[2.36117E-6,5.75503217933,3333.498879699],[2.74033E-6,.13372524985,3340.6797370026],[2.99395E-6,2.78323740866, +6254.6266625236]],[[3340.61242700512,0,0],[.01457554523,3.60433733236,3340.6124266998],[.00168414711,3.92318567804,6681.2248533996],[2.0622975E-4,4.26108844583,10021.8372800994],[3.452392E-5,4.7321039319,3.523118349],[2.586332E-5,4.60670058555,13362.4497067992],[8.41535E-6,4.45864030426,2281.2304965106]],[[5.8152577E-4,2.04961712429,3340.6124266998],[1.3459579E-4,2.45738706163,6681.2248533996]]],[[[.03197134986,3.76832042431,3340.6124266998],[.00298033234,4.10616996305,6681.2248533996],[.00289104742, +0,0],[3.1365539E-4,4.4465105309,10021.8372800994],[3.4841E-5,4.7881254926,13362.4497067992]],[[.00217310991,6.04472194776,3340.6124266998],[2.0976948E-4,3.14159265359,0],[1.2834709E-4,1.60810667915,6681.2248533996]]],[[[1.53033488271,0,0],[.1418495316,3.47971283528,3340.6124266998],[.00660776362,3.81783443019,6681.2248533996],[4.6179117E-4,4.15595316782,10021.8372800994],[8.109733E-5,5.55958416318,2810.9214616052],[7.485318E-5,1.77239078402,5621.8429232104],[5.523191E-5,1.3643630377,2281.2304965106], +[3.82516E-5,4.49407183687,13362.4497067992],[2.306537E-5,.09081579001,2544.3144198834],[1.999396E-5,5.36059617709,3337.0893083508],[2.484394E-5,4.9254563992,2942.4634232916],[1.960195E-5,4.74249437639,3344.1355450488],[1.167119E-5,2.11260868341,5092.1519581158],[1.102816E-5,5.00908403998,398.1490034082],[8.99066E-6,4.40791133207,529.6909650946],[9.92252E-6,5.83861961952,6151.533888305],[8.07354E-6,2.10217065501,1059.3819301892],[7.97915E-6,3.44839203899,796.2980068164],[7.40975E-6,1.49906336885,2146.1654164752]], +[[.01107433345,2.03250524857,3340.6124266998],[.00103175887,2.37071847807,6681.2248533996],[1.28772E-4,0,0],[1.081588E-4,2.70888095665,10021.8372800994]],[[4.4242249E-4,.47930604954,3340.6124266998],[8.138042E-5,.86998389204,6681.2248533996]]]],Jupiter:[[[[.59954691494,0,0],[.09695898719,5.06191793158,529.6909650946],[.00573610142,1.44406205629,7.1135470008],[.00306389205,5.41734730184,1059.3819301892],[9.7178296E-4,4.14264726552,632.7837393132],[7.2903078E-4,3.64042916389,522.5774180938],[6.4263975E-4, +3.41145165351,103.0927742186],[3.9806064E-4,2.29376740788,419.4846438752],[3.8857767E-4,1.27231755835,316.3918696566],[2.7964629E-4,1.7845459182,536.8045120954],[1.358973E-4,5.7748104079,1589.0728952838],[8.246349E-5,3.5822792584,206.1855484372],[8.768704E-5,3.63000308199,949.1756089698],[7.368042E-5,5.0810119427,735.8765135318],[6.26315E-5,.02497628807,213.299095438],[6.114062E-5,4.51319998626,1162.4747044078],[4.905396E-5,1.32084470588,110.2063212194],[5.305285E-5,1.30671216791,14.2270940016],[5.305441E-5, +4.18625634012,1052.2683831884],[4.647248E-5,4.69958103684,3.9321532631],[3.045023E-5,4.31676431084,426.598190876],[2.609999E-5,1.56667394063,846.0828347512],[2.028191E-5,1.06376530715,3.1813937377],[1.764763E-5,2.14148655117,1066.49547719],[1.722972E-5,3.88036268267,1265.5674786264],[1.920945E-5,.97168196472,639.897286314],[1.633223E-5,3.58201833555,515.463871093],[1.431999E-5,4.29685556046,625.6701923124],[9.73272E-6,4.09764549134,95.9792272178]],[[529.69096508814,0,0],[.00489503243,4.2208293947, +529.6909650946],[.00228917222,6.02646855621,7.1135470008],[3.0099479E-4,4.54540782858,1059.3819301892],[2.072092E-4,5.45943156902,522.5774180938],[1.2103653E-4,.16994816098,536.8045120954],[6.067987E-5,4.42422292017,103.0927742186],[5.433968E-5,3.98480737746,419.4846438752],[4.237744E-5,5.89008707199,14.2270940016]],[[4.7233601E-4,4.32148536482,7.1135470008],[3.0649436E-4,2.929777887,529.6909650946],[1.4837605E-4,3.14159265359,0]]],[[[.02268615702,3.55852606721,529.6909650946],[.00109971634,3.90809347197, +1059.3819301892],[.00110090358,0,0],[8.101428E-5,3.60509572885,522.5774180938],[6.043996E-5,4.25883108339,1589.0728952838],[6.437782E-5,.30627119215,536.8045120954]],[[7.8203446E-4,1.52377859742,529.6909650946]]],[[[5.20887429326,0,0],[.25209327119,3.49108639871,529.6909650946],[.00610599976,3.84115365948,1059.3819301892],[.00282029458,2.57419881293,632.7837393132],[.00187647346,2.07590383214,522.5774180938],[8.6792905E-4,.71001145545,419.4846438752],[7.2062974E-4,.21465724607,536.8045120954],[6.5517248E-4, +5.9799588479,316.3918696566],[2.9134542E-4,1.67759379655,103.0927742186],[3.0135335E-4,2.16132003734,949.1756089698],[2.3453271E-4,3.54023522184,735.8765135318],[2.2283743E-4,4.19362594399,1589.0728952838],[2.3947298E-4,.2745803748,7.1135470008],[1.3032614E-4,2.96042965363,1162.4747044078],[9.70336E-5,1.90669633585,206.1855484372],[1.2749023E-4,2.71550286592,1052.2683831884],[7.057931E-5,2.18184839926,1265.5674786264],[6.137703E-5,6.26418240033,846.0828347512],[2.616976E-5,2.00994012876,1581.959348283]], +[[.0127180152,2.64937512894,529.6909650946],[6.1661816E-4,3.00076460387,1059.3819301892],[5.3443713E-4,3.89717383175,522.5774180938],[3.1185171E-4,4.88276958012,536.8045120954],[4.1390269E-4,0,0]]]],Saturn:[[[[.87401354025,0,0],[.11107659762,3.96205090159,213.299095438],[.01414150957,4.58581516874,7.1135470008],[.00398379389,.52112032699,206.1855484372],[.00350769243,3.30329907896,426.598190876],[.00206816305,.24658372002,103.0927742186],[7.92713E-4,3.84007056878,220.4126424388],[2.3990355E-4,4.66976924553, +110.2063212194],[1.6573588E-4,.43719228296,419.4846438752],[1.4906995E-4,5.76903183869,316.3918696566],[1.582029E-4,.93809155235,632.7837393132],[1.4609559E-4,1.56518472,3.9321532631],[1.3160301E-4,4.44891291899,14.2270940016],[1.5053543E-4,2.71669915667,639.897286314],[1.3005299E-4,5.98119023644,11.0457002639],[1.0725067E-4,3.12939523827,202.2533951741],[5.863206E-5,.23656938524,529.6909650946],[5.227757E-5,4.20783365759,3.1813937377],[6.126317E-5,1.76328667907,277.0349937414],[5.019687E-5,3.17787728405, +433.7117378768],[4.59255E-5,.61977744975,199.0720014364],[4.005867E-5,2.24479718502,63.7358983034],[2.953796E-5,.98280366998,95.9792272178],[3.87367E-5,3.22283226966,138.5174968707],[2.461186E-5,2.03163875071,735.8765135318],[3.269484E-5,.77492638211,949.1756089698],[1.758145E-5,3.2658010994,522.5774180938],[1.640172E-5,5.5050445305,846.0828347512],[1.391327E-5,4.02333150505,323.5054166574],[1.580648E-5,4.37265307169,309.2783226558],[1.123498E-5,2.83726798446,415.5524906121],[1.017275E-5,3.71700135395, +227.5261894396],[8.48642E-6,3.1915017083,209.3669421749]],[[213.2990952169,0,0],[.01297370862,1.82834923978,213.299095438],[.00564345393,2.88499717272,7.1135470008],[9.3734369E-4,1.06311793502,426.598190876],[.00107674962,2.27769131009,206.1855484372],[4.0244455E-4,2.04108104671,220.4126424388],[1.9941774E-4,1.2795439047,103.0927742186],[1.0511678E-4,2.7488034213,14.2270940016],[6.416106E-5,.38238295041,639.897286314],[4.848994E-5,2.43037610229,419.4846438752],[4.056892E-5,2.92133209468,110.2063212194], +[3.768635E-5,3.6496533078,3.9321532631]],[[.0011644133,1.17988132879,7.1135470008],[9.1841837E-4,.0732519584,213.299095438],[3.6661728E-4,0,0],[1.5274496E-4,4.06493179167,206.1855484372]]],[[[.04330678039,3.60284428399,213.299095438],[.00240348302,2.85238489373,426.598190876],[8.4745939E-4,0,0],[3.0863357E-4,3.48441504555,220.4126424388],[3.4116062E-4,.57297307557,206.1855484372],[1.473407E-4,2.11846596715,639.897286314],[9.916667E-5,5.79003188904,419.4846438752],[6.993564E-5,4.7360468972,7.1135470008], +[4.807588E-5,5.43305312061,316.3918696566]],[[.00198927992,4.93901017903,213.299095438],[3.6947916E-4,3.14159265359,0],[1.7966989E-4,.5197943111,426.598190876]]],[[[9.55758135486,0,0],[.52921382865,2.39226219573,213.299095438],[.01873679867,5.2354960466,206.1855484372],[.01464663929,1.64763042902,426.598190876],[.00821891141,5.93520042303,316.3918696566],[.00547506923,5.0153261898,103.0927742186],[.0037168465,2.27114821115,220.4126424388],[.00361778765,3.13904301847,7.1135470008],[.00140617506,5.70406606781, +632.7837393132],[.00108974848,3.29313390175,110.2063212194],[6.9006962E-4,5.94099540992,419.4846438752],[6.1053367E-4,.94037691801,639.897286314],[4.8913294E-4,1.55733638681,202.2533951741],[3.4143772E-4,.19519102597,277.0349937414],[3.2401773E-4,5.47084567016,949.1756089698],[2.0936596E-4,.46349251129,735.8765135318],[9.796004E-5,5.20477537945,1265.5674786264],[1.1993338E-4,5.98050967385,846.0828347512],[2.08393E-4,1.52102476129,433.7117378768],[1.5298404E-4,3.0594381494,529.6909650946],[6.465823E-5, +.17732249942,1052.2683831884],[1.1380257E-4,1.7310542704,522.5774180938],[3.419618E-5,4.94550542171,1581.959348283]],[[.0618298134,.2584351148,213.299095438],[.00506577242,.71114625261,206.1855484372],[.00341394029,5.79635741658,426.598190876],[.00188491195,.47215589652,220.4126424388],[.00186261486,3.14159265359,0],[.00143891146,1.40744822888,7.1135470008]],[[.00436902572,4.78671677509,213.299095438]]]],Uranus:[[[[5.48129294297,0,0],[.09260408234,.89106421507,74.7815985673],[.01504247898,3.6271926092, +1.4844727083],[.00365981674,1.89962179044,73.297125859],[.00272328168,3.35823706307,149.5631971346],[7.0328461E-4,5.39254450063,63.7358983034],[6.8892678E-4,6.09292483287,76.2660712756],[6.1998615E-4,2.26952066061,2.9689454166],[6.1950719E-4,2.85098872691,11.0457002639],[2.646877E-4,3.14152083966,71.8126531507],[2.5710476E-4,6.11379840493,454.9093665273],[2.107885E-4,4.36059339067,148.0787244263],[1.7818647E-4,1.74436930289,36.6485629295],[1.4613507E-4,4.73732166022,3.9321532631],[1.1162509E-4,5.8268179635, +224.3447957019],[1.099791E-4,.48865004018,138.5174968707],[9.527478E-5,2.95516862826,35.1640902212],[7.545601E-5,5.236265824,109.9456887885],[4.220241E-5,3.23328220918,70.8494453042],[4.0519E-5,2.277550173,151.0476698429],[3.354596E-5,1.0654900738,4.4534181249],[2.926718E-5,4.62903718891,9.5612275556],[3.49034E-5,5.48306144511,146.594251718],[3.144069E-5,4.75199570434,77.7505439839],[2.922333E-5,5.35235361027,85.8272988312],[2.272788E-5,4.36600400036,70.3281804424],[2.051219E-5,1.51773566586,.1118745846], +[2.148602E-5,.60745949945,38.1330356378],[1.991643E-5,4.92437588682,277.0349937414],[1.376226E-5,2.04283539351,65.2203710117],[1.666902E-5,3.62744066769,380.12776796],[1.284107E-5,3.11347961505,202.2533951741],[1.150429E-5,.93343589092,3.1813937377],[1.533221E-5,2.58594681212,52.6901980395],[1.281604E-5,.54271272721,222.8603229936],[1.372139E-5,4.19641530878,111.4301614968],[1.221029E-5,.1990065003,108.4612160802],[9.46181E-6,1.19253165736,127.4717966068],[1.150989E-5,4.17898916639,33.6796175129]], +[[74.7815986091,0,0],[.00154332863,5.24158770553,74.7815985673],[2.4456474E-4,1.71260334156,1.4844727083],[9.258442E-5,.4282973235,11.0457002639],[8.265977E-5,1.50218091379,63.7358983034],[9.15016E-5,1.41213765216,149.5631971346]]],[[[.01346277648,2.61877810547,74.7815985673],[6.23414E-4,5.08111189648,149.5631971346],[6.1601196E-4,3.14159265359,0],[9.963722E-5,1.61603805646,76.2660712756],[9.92616E-5,.57630380333,73.297125859]],[[3.4101978E-4,.01321929936,74.7815985673]]],[[[19.21264847206,0,0],[.88784984413, +5.60377527014,74.7815985673],[.03440836062,.32836099706,73.297125859],[.0205565386,1.7829515933,149.5631971346],[.0064932241,4.52247285911,76.2660712756],[.00602247865,3.86003823674,63.7358983034],[.00496404167,1.40139935333,454.9093665273],[.00338525369,1.58002770318,138.5174968707],[.00243509114,1.57086606044,71.8126531507],[.00190522303,1.99809394714,1.4844727083],[.00161858838,2.79137786799,148.0787244263],[.00143706183,1.38368544947,11.0457002639],[9.3192405E-4,.17437220467,36.6485629295],[7.1424548E-4, +4.24509236074,224.3447957019],[8.9806014E-4,3.66105364565,109.9456887885],[3.9009723E-4,1.66971401684,70.8494453042],[4.6677296E-4,1.39976401694,35.1640902212],[3.9025624E-4,3.36234773834,277.0349937414],[3.6755274E-4,3.88649278513,146.594251718],[3.0348723E-4,.70100838798,151.0476698429],[2.9156413E-4,3.180563367,77.7505439839],[2.2637073E-4,.72518687029,529.6909650946],[1.1959076E-4,1.7504339214,984.6003316219],[2.5620756E-4,5.25656086672,380.12776796]],[[.01479896629,3.67205697578,74.7815985673]]]], +Neptune:[[[[5.31188633046,0,0],[.0179847553,2.9010127389,38.1330356378],[.01019727652,.48580922867,1.4844727083],[.00124531845,4.83008090676,36.6485629295],[4.2064466E-4,5.41054993053,2.9689454166],[3.7714584E-4,6.09221808686,35.1640902212],[3.3784738E-4,1.24488874087,76.2660712756],[1.6482741E-4,7.727998E-5,491.5579294568],[9.198584E-5,4.93747051954,39.6175083461],[8.99425E-5,.27462171806,175.1660598002]],[[38.13303563957,0,0],[1.6604172E-4,4.86323329249,1.4844727083],[1.5744045E-4,2.27887427527, +38.1330356378]]],[[[.03088622933,1.44104372644,38.1330356378],[2.7780087E-4,5.91271884599,76.2660712756],[2.7623609E-4,0,0],[1.5355489E-4,2.52123799551,36.6485629295],[1.5448133E-4,3.50877079215,39.6175083461]]],[[[30.07013205828,0,0],[.27062259632,1.32999459377,38.1330356378],[.01691764014,3.25186135653,36.6485629295],[.00807830553,5.18592878704,1.4844727083],[.0053776051,4.52113935896,35.1640902212],[.00495725141,1.5710564165,491.5579294568],[.00274571975,1.84552258866,175.1660598002],[1.201232E-4, +1.92059384991,1021.2488945514],[.00121801746,5.79754470298,76.2660712756],[.00100896068,.3770272493,73.297125859],[.00135134092,3.37220609835,39.6175083461],[7.571796E-5,1.07149207335,388.4651552382]]]]}; +function DeltaT_EspenakMeeus(a){var b=2E3+(a-14)/DAYS_PER_TROPICAL_YEAR;if(-500>b)return a=(b-1820)/100,-20+32*a*a;if(500>b){a=b/100;b=a*a;var c=a*b;return 10583.6-1014.41*a+33.78311*b-5.952053*c-.1798452*b*b+.022174192*b*c+.0090316521*c*c}if(1600>b)return a=(b-1E3)/100,b=a*a,c=a*b,1574.2-556.01*a+71.23472*b+.319781*c-.8503463*b*b-.005050998*b*c+.0083572073*c*c;if(1700>b)return a=b-1600,b=a*a,120-.9808*a-.01532*b+a*b/7129;if(1800>b)return a=b-1700,b=a*a,8.83+.1603*a-.0059285*b+1.3336E-4*a*b-b*b/1174E3; +if(1860>b){a=b-1800;b=a*a;c=a*b;var d=b*b;return 13.72-.332447*a+.0068612*b+.0041116*c-3.7436E-4*d+1.21272E-5*b*c-1.699E-7*c*c+8.75E-10*c*d}if(1900>b)return a=b-1860,b=a*a,c=a*b,7.62+.5737*a-.251754*b+.01680668*c-4.473624E-4*b*b+b*c/233174;if(1920>b)return a=b-1900,b=a*a,-2.79+1.494119*a-.0598939*b+.0061966*a*b-1.97E-4*b*b;if(1941>b)return a=b-1920,b=a*a,21.2+.84493*a-.0761*b+.0020936*a*b;if(1961>b)return a=b-1950,b=a*a,29.07+.407*a-b/233+a*b/2547;if(1986>b)return a=b-1975,b=a*a,45.45+1.067*a-b/260- +a*b/718;if(2005>b)return a=b-2E3,b=a*a,c=a*b,63.86+.3345*a-.060374*b+.0017275*c+6.51814E-4*b*b+2.373599E-5*b*c;if(2050>b)return a=b-2E3,62.92+.32217*a+.005589*a*a;if(2150>b)return a=(b-1820)/100,-20+32*a*a-.5628*(2150-b);a=(b-1820)/100;return-20+32*a*a}exports.DeltaT_EspenakMeeus=DeltaT_EspenakMeeus;function DeltaT_JplHorizons(a){return DeltaT_EspenakMeeus(Math.min(a,17*DAYS_PER_TROPICAL_YEAR))}exports.DeltaT_JplHorizons=DeltaT_JplHorizons;var DeltaT=DeltaT_EspenakMeeus; +function SetDeltaTFunction(a){DeltaT=a}exports.SetDeltaTFunction=SetDeltaTFunction;function TerrestrialTime(a){return a+DeltaT(a)/86400} +var AstroTime=function(a){if(a instanceof AstroTime)this.date=a.date,this.ut=a.ut,this.tt=a.tt;else if(a instanceof Date&&Number.isFinite(a.getTime()))this.date=a,this.ut=(a.getTime()-J2000.getTime())/864E5,this.tt=TerrestrialTime(this.ut);else if(Number.isFinite(a))this.date=new Date(J2000.getTime()+864E5*a),this.ut=a,this.tt=TerrestrialTime(this.ut);else throw"Argument must be a Date object, an AstroTime object, or a numeric UTC Julian date.";}; +AstroTime.FromTerrestrialTime=function(a){for(var b=new AstroTime(a);;){var c=a-b.tt;if(1E-12>Math.abs(c))return b;b=b.AddDays(c)}};AstroTime.prototype.toString=function(){return this.date.toISOString()};AstroTime.prototype.AddDays=function(a){return new AstroTime(this.ut+a)};exports.AstroTime=AstroTime;function InterpolateTime(a,b,c){return new AstroTime(a.ut+c*(b.ut-a.ut))}function MakeTime(a){return a instanceof AstroTime?a:new AstroTime(a)}exports.MakeTime=MakeTime; +function iau2000b(a){a=a.tt/36525;var b=(1287104.79305+1.295965810481E8*a)%ASEC360*ASEC2RAD,c=(335779.526232+1.7395272628478E9*a)%ASEC360*ASEC2RAD,d=(450160.398036-6962890.5431*a)%ASEC360*ASEC2RAD,e=Math.sin(d),f=Math.cos(d),g=(-172064161-174666*a)*e+33386*f,k=(92052331+9086*a)*f+15377*e;f=2*(c-(1072260.70369+1.602961601209E9*a)%ASEC360*ASEC2RAD+d);e=Math.sin(f);f=Math.cos(f);g+=(-13170906-1675*a)*e-13696*f;k+=(5730336-3015*a)*f-4587*e;f=2*(c+d);e=Math.sin(f);f=Math.cos(f);g+=(-2276413-234*a)*e+2796* +f;k+=(978459-485*a)*f+1374*e;f=2*d;e=Math.sin(f);f=Math.cos(f);g+=(2074554+207*a)*e-698*f;k+=(-897492+470*a)*f-291*e;e=Math.sin(b);f=Math.cos(b);return{dpsi:-1.35E-4+1E-7*(g+((1475877-3633*a)*e+11817*f)),deps:3.88E-4+1E-7*(k+((73871-184*a)*f-1924*e))}}function mean_obliq(a){a=a.tt/36525;return(((((-4.34E-8*a-5.76E-7)*a+.0020034)*a-1.831E-4)*a-46.836769)*a+84381.406)/3600}var cache_e_tilt; +function e_tilt(a){if(!cache_e_tilt||1E-6=v;++v)0!== +u[v]&&f(w.x,w.y,c(r,u[v],v),c(q,u[v],v),function(D,E){return w.x=D,w.y=E});return w}function h(u,v,x,A,w,D,E,L){w=k(w,D,E,L);n+=u*w.y;p+=v*w.y;H+=x*w.x;F+=A*w.x}++exports.CalcMoonCount;a=a.tt/36525;var l,m,n,p,r=b(-6,6,1,4),q=b(-6,6,1,4);var t=a*a;var H=p=n=0;var F=3422.7;var C=g(.19833+.05611*a);var B=g(.27869+.04508*a);var y=g(.16827-.36903*a);var z=g(.34734-5.37261*a);var G=g(.10498-5.37899*a);var I=g(.42681-.41855*a),R=g(.14943-5.37511*a);var J=.84*C+.31*B+14.27*y+7.26*z+.28*G+.24*I;var N=2.94* +C+.31*B+14.27*y+9.34*z+1.12*G+.83*I;var K=-6.4*C-1.89*I;B=.21*C+.31*B+14.27*y-88.7*z-15.3*G+.24*I-1.86*R;y=J-K;C=-3.332E-6*g(.59734-5.37261*a)-5.39E-7*g(.35498-5.37899*a)-6.4E-8*g(.39943-5.37511*a);J=PI2*Frac(.60643382+1336.85522467*a-3.13E-6*t)+J/ARC;N=PI2*Frac(.37489701+1325.55240982*a+2.565E-5*t)+N/ARC;K=PI2*Frac(.99312619+99.99735956*a-4.4E-7*t)+K/ARC;B=PI2*Frac(.25909118+1342.2278298*a-8.92E-6*t)+B/ARC;G=PI2*Frac(.82736186+1236.85308708*a-3.97E-6*t)+y/ARC;for(l=1;4>=l;++l){switch(l){case 1:y= +N;t=4;z=1.000002208;break;case 2:y=K;t=3;z=.997504612-.002495388*a;break;case 3:y=B;t=4;z=1.000002708+139.978*C;break;case 4:y=G;t=6;z=1;break;default:throw"Internal error: I = "+l;}d(0,l,1);d(1,l,Math.cos(y)*z);e(0,l,0);e(1,l,Math.sin(y)*z);for(m=2;m<=t;++m)f(c(r,m-1,l),c(q,m-1,l),c(r,1,l),c(q,1,l),function(u,v){return d(m,l,u),e(m,l,v)});for(m=1;m<=t;++m)d(-m,l,c(r,m,l)),e(-m,l,-c(q,m,l))}h(13.902,14.06,-.001,.2607,0,0,0,4);h(.403,-4.01,.394,.0023,0,0,0,3);h(2369.912,2373.36,.601,28.2333,0,0,0, +2);h(-125.154,-112.79,-.725,-.9781,0,0,0,1);h(1.979,6.98,-.445,.0433,1,0,0,4);h(191.953,192.72,.029,3.0861,1,0,0,2);h(-8.466,-13.51,.455,-.1093,1,0,0,1);h(22639.5,22609.07,.079,186.5398,1,0,0,0);h(18.609,3.59,-.094,.0118,1,0,0,-1);h(-4586.465,-4578.13,-.077,34.3117,1,0,0,-2);h(3.215,5.44,.192,-.0386,1,0,0,-3);h(-38.428,-38.64,.001,.6008,1,0,0,-4);h(-.393,-1.43,-.092,.0086,1,0,0,-6);h(-.289,-1.59,.123,-.0053,0,1,0,4);h(-24.42,-25.1,.04,-.3,0,1,0,2);h(18.023,17.93,.007,.1494,0,1,0,1);h(-668.146,-126.98, +-1.302,-.3997,0,1,0,0);h(.56,.32,-.001,-.0037,0,1,0,-1);h(-165.145,-165.06,.054,1.9178,0,1,0,-2);h(-1.877,-6.46,-.416,.0339,0,1,0,-4);h(.213,1.02,-.074,.0054,2,0,0,4);h(14.387,14.78,-.017,.2833,2,0,0,2);h(-.586,-1.2,.054,-.01,2,0,0,1);h(769.016,767.96,.107,10.1657,2,0,0,0);h(1.75,2.01,-.018,.0155,2,0,0,-1);h(-211.656,-152.53,5.679,-.3039,2,0,0,-2);h(1.225,.91,-.03,-.0088,2,0,0,-3);h(-30.773,-34.07,-.308,.3722,2,0,0,-4);h(-.57,-1.4,-.074,.0109,2,0,0,-6);h(-2.921,-11.75,.787,-.0484,1,1,0,2);h(1.267, +1.52,-.022,.0164,1,1,0,1);h(-109.673,-115.18,.461,-.949,1,1,0,0);h(-205.962,-182.36,2.056,1.4437,1,1,0,-2);h(.233,.36,.012,-.0025,1,1,0,-3);h(-4.391,-9.66,-.471,.0673,1,1,0,-4);h(.283,1.53,-.111,.006,1,-1,0,4);h(14.577,31.7,-1.54,.2302,1,-1,0,2);h(147.687,138.76,.679,1.1528,1,-1,0,0);h(-1.089,.55,.021,0,1,-1,0,-1);h(28.475,23.59,-.443,-.2257,1,-1,0,-2);h(-.276,-.38,-.006,-.0036,1,-1,0,-3);h(.636,2.27,.146,-.0102,1,-1,0,-4);h(-.189,-1.68,.131,-.0028,0,2,0,2);h(-7.486,-.66,-.037,-.0086,0,2,0,0);h(-8.096, +-16.35,-.74,.0918,0,2,0,-2);h(-5.741,-.04,0,-9E-4,0,0,2,2);h(.255,0,0,0,0,0,2,1);h(-411.608,-.2,0,-.0124,0,0,2,0);h(.584,.84,0,.0071,0,0,2,-1);h(-55.173,-52.14,0,-.1052,0,0,2,-2);h(.254,.25,0,-.0017,0,0,2,-3);h(.025,-1.67,0,.0031,0,0,2,-4);h(1.06,2.96,-.166,.0243,3,0,0,2);h(36.124,50.64,-1.3,.6215,3,0,0,0);h(-13.193,-16.4,.258,-.1187,3,0,0,-2);h(-1.187,-.74,.042,.0074,3,0,0,-4);h(-.293,-.31,-.002,.0046,3,0,0,-6);h(-.29,-1.45,.116,-.0051,2,1,0,2);h(-7.649,-10.56,.259,-.1038,2,1,0,0);h(-8.627,-7.59, +.078,-.0192,2,1,0,-2);h(-2.74,-2.54,.022,.0324,2,1,0,-4);h(1.181,3.32,-.212,.0213,2,-1,0,2);h(9.703,11.67,-.151,.1268,2,-1,0,0);h(-.352,-.37,.001,-.0028,2,-1,0,-1);h(-2.494,-1.17,-.003,-.0017,2,-1,0,-2);h(.36,.2,-.012,-.0043,2,-1,0,-4);h(-1.167,-1.25,.008,-.0106,1,2,0,0);h(-7.412,-6.12,.117,.0484,1,2,0,-2);h(-.311,-.65,-.032,.0044,1,2,0,-4);h(.757,1.82,-.105,.0112,1,-2,0,2);h(2.58,2.32,.027,.0196,1,-2,0,0);h(2.533,2.4,-.014,-.0212,1,-2,0,-2);h(-.344,-.57,-.025,.0036,0,3,0,-2);h(-.992,-.02,0,0,1,0, +2,2);h(-45.099,-.02,0,-.001,1,0,2,0);h(-.179,-9.52,0,-.0833,1,0,2,-2);h(-.301,-.33,0,.0014,1,0,2,-4);h(-6.382,-3.37,0,-.0481,1,0,-2,2);h(39.528,85.13,0,-.7136,1,0,-2,0);h(9.366,.71,0,-.0112,1,0,-2,-2);h(.202,.02,0,0,1,0,-2,-4);h(.415,.1,0,.0013,0,1,2,0);h(-2.152,-2.26,0,-.0066,0,1,2,-2);h(-1.44,-1.3,0,.0014,0,1,-2,2);h(.384,-.04,0,0,0,1,-2,-2);h(1.938,3.6,-.145,.0401,4,0,0,0);h(-.952,-1.58,.052,-.013,4,0,0,-2);h(-.551,-.94,.032,-.0097,3,1,0,0);h(-.482,-.57,.005,-.0045,3,1,0,-2);h(.681,.96,-.026,.0115, +3,-1,0,0);h(-.297,-.27,.002,-9E-4,2,2,0,-2);h(.254,.21,-.003,0,2,-2,0,-2);h(-.25,-.22,.004,.0014,1,3,0,-2);h(-3.996,0,0,4E-4,2,0,2,0);h(.557,-.75,0,-.009,2,0,2,-2);h(-.459,-.38,0,-.0053,2,0,-2,2);h(-1.298,.74,0,4E-4,2,0,-2,0);h(.538,1.14,0,-.0141,2,0,-2,-2);h(.263,.02,0,0,1,1,2,0);h(.426,.07,0,-6E-4,1,1,-2,-2);h(-.304,.03,0,3E-4,1,-1,2,0);h(-.372,-.19,0,-.0027,1,-1,-2,2);h(.418,0,0,0,0,0,4,0);h(-.33,-.04,0,0,3,0,2,0);t=-526.069*k(0,0,1,-2).y;t+=-3.352*k(0,0,1,-4).y;t+=44.297*k(1,0,1,-2).y;t+=-6*k(1, +0,1,-4).y;t+=20.599*k(-1,0,1,0).y;t+=-30.598*k(-1,0,1,-2).y;t+=-24.649*k(-2,0,1,0).y;t+=-2*k(-2,0,1,-2).y;t+=-22.571*k(0,1,1,-2).y;t+=10.985*k(0,-1,1,-2).y;n+=.82*g(.7736-62.5512*a)+.31*g(.0466-125.1025*a)+.35*g(.5785-25.1042*a)+.66*g(.4591+1335.8075*a)+.64*g(.313-91.568*a)+1.14*g(.148+1331.2898*a)+.21*g(.5918+1056.5859*a)+.44*g(.5784+1322.8595*a)+.24*g(.2275-5.7374*a)+.28*g(.2965+2.6929*a)+.33*g(.3132+6.3368*a);a=B+p/ARC;a=(1.000002708+139.978*C)*(18518.511+1.189+H)*Math.sin(a)-6.24*Math.sin(3*a)+ +t;return{geo_eclip_lon:PI2*Frac((J+n/ARC)/PI2),geo_eclip_lat:Math.PI/648E3*a,distance_au:ARC*EARTH_EQUATORIAL_RADIUS_AU/(.999953253*F)}}var LibrationInfo=function(a,b,c,d,e,f){this.elat=a;this.elon=b;this.mlat=c;this.mlon=d;this.dist_km=e;this.diam_deg=f};exports.LibrationInfo=LibrationInfo; +function Libration(a){var b=MakeTime(a);a=b.tt/36525;var c=a*a,d=c*a,e=c*c,f=CalcMoon(b);b=f.geo_eclip_lon;var g=f.geo_eclip_lat;f=f.distance_au*exports.KM_PER_AU;var k=1.543*exports.DEG2RAD,h=exports.DEG2RAD*NormalizeLongitude(93.272095+483202.0175233*a-.0036539*c-d/3526E3+e/86331E4),l=exports.DEG2RAD*NormalizeLongitude(125.0445479-1934.1362891*a+.0020754*c+d/467441-e/60616E3),m=exports.DEG2RAD*NormalizeLongitude(357.5291092+35999.0502909*a-1.536E-4*c+d/2449E4),n=exports.DEG2RAD*NormalizeLongitude(134.9633964+ +477198.8675055*a+.0087414*c+d/69699-e/14712E3);d=exports.DEG2RAD*NormalizeLongitude(297.8501921+445267.1114034*a-.0018819*c+d/545868-e/113065E3);c=1-.002516*a-7.4E-6*c;var p=b-l;e=Math.atan2(Math.sin(p)*Math.cos(g)*Math.cos(k)-Math.sin(g)*Math.sin(k),Math.cos(p)*Math.cos(g));var r=LongitudeOffset(exports.RAD2DEG*(e-h));k=Math.asin(-Math.sin(p)*Math.cos(g)*Math.sin(k)-Math.sin(g)*Math.cos(k));p=-.02752*Math.cos(n)+-.02245*Math.sin(h)+.00684*Math.cos(n-2*h)+-.00293*Math.cos(2*h)+-8.5E-4*Math.cos(2* +h-2*d)+-5.4E-4*Math.cos(n-2*d)+-2E-4*Math.sin(n+h)+-2E-4*Math.cos(n+2*h)+-2E-4*Math.cos(n-h)+1.4E-4*Math.cos(n+2*h-2*d);var q=-.02816*Math.sin(n)+.02244*Math.cos(h)+-.00682*Math.sin(n-2*h)+-.00279*Math.sin(2*h)+-8.3E-4*Math.sin(2*h-2*d)+6.9E-4*Math.sin(n-2*d)+4E-4*Math.cos(n+h)+-2.5E-4*Math.sin(2*n)+-2.3E-4*Math.sin(n+2*h)+2E-4*Math.cos(n-h)+1.9E-4*Math.sin(n-h)+1.3E-4*Math.sin(n+2*h-2*d)+-1E-4*Math.cos(n-3*h);return new LibrationInfo(exports.RAD2DEG*k+(q*Math.cos(e)-p*Math.sin(e)),r+(-(.0252*c*Math.sin(m)+ +.00473*Math.sin(2*n-2*h)+-.00467*Math.sin(n)+.00396*Math.sin(exports.DEG2RAD*(119.75+131.849*a))+.00276*Math.sin(2*n-2*d)+.00196*Math.sin(l)+-.00183*Math.cos(n-h)+.00115*Math.sin(n-2*d)+-9.6E-4*Math.sin(n-d)+4.6E-4*Math.sin(2*h-2*d)+-3.9E-4*Math.sin(n-h)+-3.2E-4*Math.sin(n-m-d)+2.7E-4*Math.sin(2*n-m-2*d)+2.3E-4*Math.sin(exports.DEG2RAD*(72.56+20.186*a))+-1.4E-4*Math.sin(2*d)+1.4E-4*Math.cos(2*n-2*h)+-1.2E-4*Math.sin(n-2*h)+-1.2E-4*Math.sin(2*n)+1.1E-4*Math.sin(2*n-2*m-2*d))+(p*Math.cos(e)+q*Math.sin(e))* +Math.tan(k)),exports.RAD2DEG*g,exports.RAD2DEG*b,f,2*exports.RAD2DEG*Math.atan(MOON_MEAN_RADIUS_KM/Math.sqrt(f*f-MOON_MEAN_RADIUS_KM*MOON_MEAN_RADIUS_KM)))}exports.Libration=Libration;function rotate(a,b){return[a.rot[0][0]*b[0]+a.rot[1][0]*b[1]+a.rot[2][0]*b[2],a.rot[0][1]*b[0]+a.rot[1][1]*b[1]+a.rot[2][1]*b[2],a.rot[0][2]*b[0]+a.rot[1][2]*b[1]+a.rot[2][2]*b[2]]}function precession(a,b,c){b=precession_rot(b,c);return rotate(b,a)} +function precession_posvel(a,b,c){b=precession_rot(b,c);return RotateState(b,a)} +function precession_rot(a,b){a=a.tt/36525;var c=84381.406,d=((((3.337E-7*a-4.67E-7)*a-.00772503)*a+.0512623)*a-.025754)*a+c;c*=ASEC2RAD;var e=((((-9.51E-8*a+1.32851E-4)*a-.00114045)*a-1.0790069)*a+5038.481507)*a*ASEC2RAD;d*=ASEC2RAD;var f=((((-5.6E-8*a+1.70663E-4)*a-.00121197)*a-2.3814292)*a+10.556403)*a*ASEC2RAD;a=Math.sin(c);c=Math.cos(c);var g=Math.sin(-e);e=Math.cos(-e);var k=Math.sin(-d);d=Math.cos(-d);var h=Math.sin(f),l=Math.cos(f);f=l*e-g*h*d;var m=l*g*c+h*d*e*c-a*h*k,n=l*g*a+h*d*e*a+c*h* +k,p=-h*e-g*l*d,r=-h*g*c+l*d*e*c-a*l*k;h=-h*g*a+l*d*e*a+c*l*k;g*=k;l=-k*e*c-a*d;a=-k*e*a+d*c;if(b===PrecessDirection.Into2000)return new RotationMatrix([[f,m,n],[p,r,h],[g,l,a]]);if(b===PrecessDirection.From2000)return new RotationMatrix([[f,p,g],[m,r,l],[n,h,a]]);throw"Invalid precess direction";}function era(a){a=(.779057273264+.00273781191135448*a.ut+a.ut%1)%1*360;0>a&&(a+=360);return a}var sidereal_time_cache; +function sidereal_time(a){if(!sidereal_time_cache||sidereal_time_cache.tt!==a.tt){var b=a.tt/36525,c=15*e_tilt(a).ee,d=era(a);b=((c+.014506+((((-3.68E-8*b-2.9956E-5)*b-4.4E-7)*b+1.3915817)*b+4612.156534)*b)/3600+d)%360/15;0>b&&(b+=24);sidereal_time_cache={tt:a.tt,st:b}}return sidereal_time_cache.st}function SiderealTime(a){a=MakeTime(a);return sidereal_time(a)}exports.SiderealTime=SiderealTime; +function inverse_terra(a,b){var c=a[0]*exports.KM_PER_AU,d=a[1]*exports.KM_PER_AU;a=a[2]*exports.KM_PER_AU;var e=Math.hypot(c,d);if(1E-6>e){b=0;var f=0=b;)b+=360;for(;180Math.abs(p))break;f-=p/(h*((l-m)/g-m*l*(EARTH_FLATTENING_SQUARED-1)/(h*n))+a*d+e*c)}f*=exports.RAD2DEG;g=EARTH_EQUATORIAL_RADIUS_KM/g;a=Math.abs(d)>Math.abs(c)?a/d-EARTH_FLATTENING_SQUARED*g:e/c-g}return new Observer(f,b,1E3*a)} +function terra(a,b){var c=a.latitude*exports.DEG2RAD,d=Math.sin(c);c=Math.cos(c);var e=1/Math.hypot(c,EARTH_FLATTENING*d),f=a.height/1E3,g=EARTH_EQUATORIAL_RADIUS_KM*e+f;b=(15*b+a.longitude)*exports.DEG2RAD;a=Math.sin(b);b=Math.cos(b);return{pos:[g*c*b/exports.KM_PER_AU,g*c*a/exports.KM_PER_AU,(EARTH_EQUATORIAL_RADIUS_KM*EARTH_FLATTENING_SQUARED*e+f)*d/exports.KM_PER_AU],vel:[-ANGVEL*g*c*a*86400/exports.KM_PER_AU,ANGVEL*g*c*b*86400/exports.KM_PER_AU,0]}} +function nutation(a,b,c){b=nutation_rot(b,c);return rotate(b,a)}function nutation_posvel(a,b,c){b=nutation_rot(b,c);return RotateState(b,a)} +function nutation_rot(a,b){a=e_tilt(a);var c=a.mobl*exports.DEG2RAD,d=a.tobl*exports.DEG2RAD,e=a.dpsi*ASEC2RAD;a=Math.cos(c);c=Math.sin(c);var f=Math.cos(d),g=Math.sin(d);d=Math.cos(e);var k=Math.sin(e);e=-k*a;var h=-k*c,l=k*f,m=d*a*f+c*g,n=d*c*f-a*g;k*=g;var p=d*a*g-c*f;a=d*c*g+a*f;if(b===PrecessDirection.From2000)return new RotationMatrix([[d,l,k],[e,m,p],[h,n,a]]);if(b===PrecessDirection.Into2000)return new RotationMatrix([[d,e,h],[l,m,n],[k,p,a]]);throw"Invalid precess direction";} +function gyration(a,b,c){return c===PrecessDirection.Into2000?precession(nutation(a,b,c),b,c):nutation(precession(a,b,c),b,c)}function gyration_posvel(a,b,c){return c===PrecessDirection.Into2000?precession_posvel(nutation_posvel(a,b,c),b,c):nutation_posvel(precession_posvel(a,b,c),b,c)}function geo_pos(a,b){var c=sidereal_time(a);b=terra(b,c).pos;return gyration(b,a,PrecessDirection.Into2000)}var Vector=function(a,b,c,d){this.x=a;this.y=b;this.z=c;this.t=d}; +Vector.prototype.Length=function(){return Math.hypot(this.x,this.y,this.z)};exports.Vector=Vector;var StateVector=function(a,b,c,d,e,f,g){this.x=a;this.y=b;this.z=c;this.vx=d;this.vy=e;this.vz=f;this.t=g};exports.StateVector=StateVector;var Spherical=function(a,b,c){this.lat=VerifyNumber(a);this.lon=VerifyNumber(b);this.dist=VerifyNumber(c)};exports.Spherical=Spherical;var EquatorialCoordinates=function(a,b,c,d){this.ra=VerifyNumber(a);this.dec=VerifyNumber(b);this.dist=VerifyNumber(c);this.vec=d}; +exports.EquatorialCoordinates=EquatorialCoordinates;function IsValidRotationArray(a){if(!(a instanceof Array)||3!==a.length)return!1;for(var b=0;3>b;++b){if(!(a[b]instanceof Array)||3!==a[b].length)return!1;for(var c=0;3>c;++c)if(!Number.isFinite(a[b][c]))return!1}return!0}var RotationMatrix=function(a){this.rot=a};exports.RotationMatrix=RotationMatrix;function MakeRotation(a){if(!IsValidRotationArray(a))throw"Argument must be a [3][3] array of numbers";return new RotationMatrix(a)} +exports.MakeRotation=MakeRotation;var HorizontalCoordinates=function(a,b,c,d){this.azimuth=VerifyNumber(a);this.altitude=VerifyNumber(b);this.ra=VerifyNumber(c);this.dec=VerifyNumber(d)};exports.HorizontalCoordinates=HorizontalCoordinates;var EclipticCoordinates=function(a,b,c){this.vec=a;this.elat=VerifyNumber(b);this.elon=VerifyNumber(c)};exports.EclipticCoordinates=EclipticCoordinates;function VectorFromArray(a,b){return new Vector(a[0],a[1],a[2],b)} +function vector2radec(a,b){b=VectorFromArray(a,b);var c=b.x*b.x+b.y*b.y,d=Math.sqrt(c+b.z*b.z);if(0===c){if(0===b.z)throw"Indeterminate sky coordinates";return new EquatorialCoordinates(0,0>b.z?-90:90,d,b)}var e=exports.RAD2HOUR*Math.atan2(b.y,b.x);0>e&&(e+=24);return new EquatorialCoordinates(e,exports.RAD2DEG*Math.atan2(a[2],Math.sqrt(c)),d,b)}function spin(a,b){var c=a*exports.DEG2RAD;a=Math.cos(c);c=Math.sin(c);return[a*b[0]+c*b[1],a*b[1]-c*b[0],b[2]]} +function Horizon(a,b,c,d,e){a=MakeTime(a);VerifyObserver(b);VerifyNumber(c);VerifyNumber(d);var f=Math.sin(b.latitude*exports.DEG2RAD),g=Math.cos(b.latitude*exports.DEG2RAD),k=Math.sin(b.longitude*exports.DEG2RAD),h=Math.cos(b.longitude*exports.DEG2RAD);b=Math.sin(d*exports.DEG2RAD);var l=Math.cos(d*exports.DEG2RAD),m=Math.sin(c*exports.HOUR2RAD),n=Math.cos(c*exports.HOUR2RAD),p=[g*h,g*k,f];f=[-f*h,-f*k,g];k=[k,-h,0];g=-15*sidereal_time(a);a=spin(g,p);p=spin(g,f);k=spin(g,k);b=[l*n,l*m,b];m=b[0]* +a[0]+b[1]*a[1]+b[2]*a[2];l=b[0]*p[0]+b[1]*p[1]+b[2]*p[2];p=b[0]*k[0]+b[1]*k[1]+b[2]*k[2];n=Math.hypot(l,p);0l&&(l+=360)):l=0;m=exports.RAD2DEG*Math.atan2(n,m);n=d;if(e&&(d=m,e=Refraction(e,90-m),m-=e,0k;++k)e.push((b[k]-d*a[k])/p*c+a[k]*n);n=Math.hypot(e[0],e[1]);0 +c&&(c+=24)):c=0;n=exports.RAD2DEG*Math.atan2(e[2],n)}return new HorizontalCoordinates(l,90-m,c,n)}exports.Horizon=Horizon;function VerifyObserver(a){if(!(a instanceof Observer))throw"Not an instance of the Observer class: "+a;VerifyNumber(a.latitude);VerifyNumber(a.longitude);VerifyNumber(a.height);if(-90>a.latitude||90b&&(b+=360));f=exports.RAD2DEG*Math.atan2(c,f);a=new Vector(d,e,c,a.t);return new EclipticCoordinates(a,f,b)} +function Ecliptic(a){var b=e_tilt(a.t),c=precession([a.x,a.y,a.z],a.t,PrecessDirection.From2000),d=$jscomp.makeIterator(nutation(c,a.t,PrecessDirection.From2000));c=d.next().value;var e=d.next().value;d=d.next().value;a=new Vector(c,e,d,a.t);b=b.tobl*exports.DEG2RAD;return RotateEquatorialToEcliptic(a,Math.cos(b),Math.sin(b))}exports.Ecliptic=Ecliptic; +function GeoMoon(a){a=MakeTime(a);var b=CalcMoon(a),c=b.distance_au*Math.cos(b.geo_eclip_lat);b=ecl2equ_vec(a,[c*Math.cos(b.geo_eclip_lon),c*Math.sin(b.geo_eclip_lon),b.distance_au*Math.sin(b.geo_eclip_lat)]);b=precession(b,a,PrecessDirection.Into2000);return new Vector(b[0],b[1],b[2],a)}exports.GeoMoon=GeoMoon; +function EclipticGeoMoon(a){var b=MakeTime(a);a=CalcMoon(b);var c=a.distance_au*Math.cos(a.geo_eclip_lat),d=[c*Math.cos(a.geo_eclip_lon),c*Math.sin(a.geo_eclip_lon),a.distance_au*Math.sin(a.geo_eclip_lat)];c=e_tilt(b);d=obl_ecl2equ_vec(c.mobl,d);d=nutation(d,b,PrecessDirection.From2000);b=VectorFromArray(d,b);c=c.tobl*exports.DEG2RAD;b=RotateEquatorialToEcliptic(b,Math.cos(c),Math.sin(c));return new Spherical(b.elat,b.elon,a.distance_au)}exports.EclipticGeoMoon=EclipticGeoMoon; +function GeoMoonState(a){a=MakeTime(a);var b=a.AddDays(-1E-5),c=a.AddDays(1E-5);b=GeoMoon(b);c=GeoMoon(c);return new StateVector((b.x+c.x)/2,(b.y+c.y)/2,(b.z+c.z)/2,(c.x-b.x)/2E-5,(c.y-b.y)/2E-5,(c.z-b.z)/2E-5,a)}exports.GeoMoonState=GeoMoonState;function GeoEmbState(a){a=MakeTime(a);var b=GeoMoonState(a),c=1+EARTH_MOON_MASS_RATIO;return new StateVector(b.x/c,b.y/c,b.z/c,b.vx/c,b.vy/c,b.vz/c,a)}exports.GeoEmbState=GeoEmbState; +function VsopFormula(a,b,c){var d=1,e=0;a=$jscomp.makeIterator(a);for(var f=a.next();!f.done;f=a.next()){var g=0;f=$jscomp.makeIterator(f.value);for(var k=f.next();!k.done;k=f.next()){var h=$jscomp.makeIterator(k.value);k=h.next().value;var l=h.next().value;h=h.next().value;g+=k*Math.cos(l+b*h)}g*=d;c&&(g%=PI2);e+=g;d*=b}return e} +function VsopDeriv(a,b){var c=1,d=0,e=0,f=0;a=$jscomp.makeIterator(a);for(var g=a.next();!g.done;g=a.next()){var k=0,h=0;g=$jscomp.makeIterator(g.value);for(var l=g.next();!l.done;l=g.next()){var m=$jscomp.makeIterator(l.value);l=m.next().value;var n=m.next().value;m=m.next().value;n+=b*m;k+=l*m*Math.sin(n);0a?0:a>=b?b-1:a} +function GravFromState(a){var b=BodyStateFromTable(a);a=new major_bodies_t(b.tt);var c=b.r.add(a.Sun.r),d=b.v.add(a.Sun.v),e=a.Acceleration(c);b=new body_grav_calc_t(b.tt,c,d,e);return new grav_sim_t(a,b)} +function GetSegment(a,b){var c=PlutoStateTable[0][0];if(bPlutoStateTable[PLUTO_NUM_STATES-1][0])return null;b=ClampIndex((b-c)/PLUTO_TIME_STEP,PLUTO_NUM_STATES-1);if(!a[b]){c=a[b]=[];c[0]=GravFromState(PlutoStateTable[b]).grav;c[PLUTO_NSTEPS-1]=GravFromState(PlutoStateTable[b+1]).grav;var d,e=c[0].tt;for(d=1;dd[1]&&(d[1]+=PI2);e=$jscomp.makeIterator(b.z);for(f=e.next();!f.done;f= +e.next())g=$jscomp.makeIterator(f.value),f=g.next().value,k=g.next().value,g=g.next().value,k+=c*g,d[2]+=f*Math.cos(k),d[3]+=f*Math.sin(k);e=$jscomp.makeIterator(b.zeta);for(f=e.next();!f.done;f=e.next())g=$jscomp.makeIterator(f.value),f=g.next().value,k=g.next().value,g=g.next().value,k+=c*g,d[4]+=f*Math.cos(k),d[5]+=f*Math.sin(k);a=JupiterMoon_elem2pv(a,b.mu,d);return RotateState(Rotation_JUP_EQJ,a)} +function JupiterMoons(a){a=new AstroTime(a);return new JupiterMoonsInfo(CalcJupiterMoon(a,JupiterMoonModel[0]),CalcJupiterMoon(a,JupiterMoonModel[1]),CalcJupiterMoon(a,JupiterMoonModel[2]),CalcJupiterMoon(a,JupiterMoonModel[3]))}exports.JupiterMoons=JupiterMoons; +function HelioVector(a,b){b=MakeTime(b);if(a in vsop)return CalcVsop(vsop[a],b);if(a===Body.Pluto)return a=CalcPluto(b,!0),new Vector(a.x,a.y,a.z,b);if(a===Body.Sun)return new Vector(0,0,0,b);if(a===Body.Moon){a=CalcVsop(vsop.Earth,b);var c=GeoMoon(b);return new Vector(a.x+c.x,a.y+c.y,a.z+c.z,b)}if(a===Body.EMB){a=CalcVsop(vsop.Earth,b);c=GeoMoon(b);var d=1+EARTH_MOON_MASS_RATIO;return new Vector(a.x+c.x/d,a.y+c.y/d,a.z+c.z/d,b)}if(a===Body.SSB)return CalcSolarSystemBarycenter(b);if(c=UserDefinedStar(a))return a= +new Spherical(c.dec,15*c.ra,c.dist),VectorFromSphere(a,b);throw'HelioVector: Unknown body "'+a+'"';}exports.HelioVector=HelioVector;function HelioDistance(a,b){var c=UserDefinedStar(a);if(c)return c.dist;b=MakeTime(b);return a in vsop?VsopFormula(vsop[a][RAD_INDEX],b.tt/DAYS_PER_MILLENNIUM,!1):HelioVector(a,b).Length()}exports.HelioDistance=HelioDistance; +function CorrectLightTravel(a,b){for(var c=b,d=0,e=0;10>e;++e){var f=a(c);d=f.Length()/exports.C_AUDAY;if(1d)return f;c=g}throw"Light-travel time solver did not converge: dt = "+d;}exports.CorrectLightTravel=CorrectLightTravel;var BodyPosition=function(a,b,c,d){this.observerBody=a;this.targetBody=b;this.aberration=c;this.observerPos=d}; +BodyPosition.prototype.Position=function(a){this.aberration&&(this.observerPos=HelioVector(this.observerBody,a));var b=HelioVector(this.targetBody,a);return new Vector(b.x-this.observerPos.x,b.y-this.observerPos.y,b.z-this.observerPos.z,a)}; +function BackdatePosition(a,b,c,d){VerifyBoolean(d);a=MakeTime(a);if(UserDefinedStar(c)){c=HelioVector(c,a);if(d)return b=HelioState(b,a),d=new Vector(c.x-b.x,c.y-b.y,c.z-b.z,a),c=exports.C_AUDAY/d.Length(),new Vector(d.x+b.vx/c,d.y+b.vy/c,d.z+b.vz/c,a);b=HelioVector(b,a);return new Vector(c.x-b.x,c.y-b.y,c.z-b.z,a)}var e=d?new Vector(0,0,0,a):HelioVector(b,a);var f=new BodyPosition(b,c,d,e);return CorrectLightTravel(function(g){return f.Position(g)},a)}exports.BackdatePosition=BackdatePosition; +function GeoVector(a,b,c){VerifyBoolean(c);b=MakeTime(b);switch(a){case Body.Earth:return new Vector(0,0,0,b);case Body.Moon:return GeoMoon(b);default:return a=BackdatePosition(b,Body.Earth,a,c),a.t=b,a}}exports.GeoVector=GeoVector;function ExportState(a,b){return new StateVector(a.r.x,a.r.y,a.r.z,a.v.x,a.v.y,a.v.z,b)} +function BaryState(a,b){b=MakeTime(b);if(a===Body.SSB)return new StateVector(0,0,0,0,0,0,b);if(a===Body.Pluto)return CalcPluto(b,!1);var c=new major_bodies_t(b.tt);switch(a){case Body.Sun:return ExportState(c.Sun,b);case Body.Jupiter:return ExportState(c.Jupiter,b);case Body.Saturn:return ExportState(c.Saturn,b);case Body.Uranus:return ExportState(c.Uranus,b);case Body.Neptune:return ExportState(c.Neptune,b);case Body.Moon:case Body.EMB:var d=CalcVsopPosVel(vsop[Body.Earth],b.tt);a=a===Body.Moon? +GeoMoonState(b):GeoEmbState(b);return new StateVector(a.x+c.Sun.r.x+d.r.x,a.y+c.Sun.r.y+d.r.y,a.z+c.Sun.r.z+d.r.z,a.vx+c.Sun.v.x+d.v.x,a.vy+c.Sun.v.y+d.v.y,a.vz+c.Sun.v.z+d.v.z,b)}if(a in vsop)return a=CalcVsopPosVel(vsop[a],b.tt),new StateVector(c.Sun.r.x+a.r.x,c.Sun.r.y+a.r.y,c.Sun.r.z+a.r.z,c.Sun.v.x+a.v.x,c.Sun.v.y+a.v.y,c.Sun.v.z+a.v.z,b);throw'BaryState: Unsupported body "'+a+'"';}exports.BaryState=BaryState; +function HelioState(a,b){b=MakeTime(b);switch(a){case Body.Sun:return new StateVector(0,0,0,0,0,0,b);case Body.SSB:return a=new major_bodies_t(b.tt),new StateVector(-a.Sun.r.x,-a.Sun.r.y,-a.Sun.r.z,-a.Sun.v.x,-a.Sun.v.y,-a.Sun.v.z,b);case Body.Mercury:case Body.Venus:case Body.Earth:case Body.Mars:case Body.Jupiter:case Body.Saturn:case Body.Uranus:case Body.Neptune:return a=CalcVsopPosVel(vsop[a],b.tt),ExportState(a,b);case Body.Pluto:return CalcPluto(b,!0);case Body.Moon:case Body.EMB:var c=CalcVsopPosVel(vsop.Earth, +b.tt);a=a==Body.Moon?GeoMoonState(b):GeoEmbState(b);return new StateVector(a.x+c.r.x,a.y+c.r.y,a.z+c.r.z,a.vx+c.v.x,a.vy+c.v.y,a.vz+c.v.z,b);default:if(UserDefinedStar(a))return a=HelioVector(a,b),new StateVector(a.x,a.y,a.z,0,0,0,b);throw'HelioState: Unsupported body "'+a+'"';}}exports.HelioState=HelioState; +function QuadInterp(a,b,c,d,e){var f=(e+c)/2-d;c=(e-c)/2;if(0==f){if(0==c)return null;d=-d/c;if(-1>d||1=d)return null;e=Math.sqrt(d);d=(-c+e)/(2*f);e=(-c-e)/(2*f);if(-1<=d&&1>=d){if(-1<=e&&1>=e)return null}else if(-1<=e&&1>=e)d=e;else return null}return{t:a+d*b,df_dt:(2*f*d+c)/b}} +function Search(a,b,c,d){var e=VerifyNumber(d&&d.dt_tolerance_seconds||1);e=Math.abs(e/SECONDS_PER_DAY);var f=d&&d.init_f1||a(b),g=d&&d.init_f2||a(c),k=NaN,h=0;d=d&&d.iter_limit||20;for(var l=!0;;){if(++h>d)throw"Excessive iteration in Search()";var m=InterpolateTime(b,c,.5),n=m.ut-b.ut;if(Math.abs(n)(n.ut-b.ut)*(n.ut-c.ut)&&0>(r.ut-b.ut)*(r.ut-c.ut))){p=a(n);var t=a(r);if(0>p&&0<=t){f=p;g=t;b=n;c=r;k=q;l=!1;continue}}}}if(0>f&&0<=k)c=m,g=k;else if(0>k&&0<=g)b=m,f=k;else return null}}exports.Search=Search;function LongitudeOffset(a){for(;-180>=a;)a+=360;for(;180a;)a+=360;for(;360<=a;)a-=360;return a} +function SearchSunLongitude(a,b,c){VerifyNumber(a);VerifyNumber(c);b=MakeTime(b);c=b.AddDays(c);return Search(function(d){d=SunPosition(d);return LongitudeOffset(d.elon-a)},b,c,{dt_tolerance_seconds:.01})}exports.SearchSunLongitude=SearchSunLongitude; +function PairLongitude(a,b,c){if(a===Body.Earth||b===Body.Earth)throw"The Earth does not have a longitude as seen from itself.";c=MakeTime(c);a=GeoVector(a,c,!1);a=Ecliptic(a);b=GeoVector(b,c,!1);b=Ecliptic(b);return NormalizeLongitude(a.elon-b.elon)}exports.PairLongitude=PairLongitude;function AngleFromSun(a,b){if(a==Body.Earth)throw"The Earth does not have an angle as seen from itself.";var c=MakeTime(b);b=GeoVector(Body.Sun,c,!0);a=GeoVector(a,c,!0);return AngleBetween(b,a)} +exports.AngleFromSun=AngleFromSun;function EclipticLongitude(a,b){if(a===Body.Sun)throw"Cannot calculate heliocentric longitude of the Sun.";a=HelioVector(a,b);return Ecliptic(a).elon}exports.EclipticLongitude=EclipticLongitude; +function VisualMagnitude(a,b,c,d){var e=0,f=0,g=0;switch(a){case Body.Mercury:a=-.6;e=4.98;f=-4.88;g=3.02;break;case Body.Venus:163.6>b?(a=-4.47,e=1.03,f=.57,g=.13):(a=.98,e=-1.02);break;case Body.Mars:a=-1.52;e=1.6;break;case Body.Jupiter:a=-9.4;e=.5;break;case Body.Uranus:a=-7.19;e=.25;break;case Body.Neptune:a=-6.87;break;case Body.Pluto:a=-1;e=4;break;default:throw"VisualMagnitude: unsupported body "+a;}b/=100;return a+b*(e+b*(f+b*g))+5*Math.log10(c*d)} +function SaturnMagnitude(a,b,c,d,e){d=Ecliptic(d);var f=28.06*exports.DEG2RAD,g=exports.DEG2RAD*d.elat;e=Math.asin(Math.sin(g)*Math.cos(f)-Math.cos(g)*Math.sin(f)*Math.sin(exports.DEG2RAD*d.elon-exports.DEG2RAD*(169.51+3.82E-5*e.tt)));d=Math.sin(Math.abs(e));a=-9+.044*a+d*(-2.6+1.2*d)+5*Math.log10(b*c);return{mag:a,ring_tilt:exports.RAD2DEG*e}}function MoonMagnitude(a,b,c){a*=exports.DEG2RAD;var d=a*a;a=-12.717+1.49*Math.abs(a)+.0431*d*d;return a+=5*Math.log10(c/(385000.6/exports.KM_PER_AU)*b)} +var IlluminationInfo=function(a,b,c,d,e,f,g,k){this.time=a;this.mag=b;this.phase_angle=c;this.helio_dist=d;this.geo_dist=e;this.gc=f;this.hc=g;this.ring_tilt=k;this.phase_fraction=(1+Math.cos(exports.DEG2RAD*c))/2};exports.IlluminationInfo=IlluminationInfo; +function Illumination(a,b){if(a===Body.Earth)throw"The illumination of the Earth is not defined.";var c=MakeTime(b),d=CalcVsop(vsop.Earth,c);if(a===Body.Sun){var e=new Vector(-d.x,-d.y,-d.z,c);b=new Vector(0,0,0,c);d=0}else a===Body.Moon?(e=GeoMoon(c),b=new Vector(d.x+e.x,d.y+e.y,d.z+e.z,c)):(b=HelioVector(a,b),e=new Vector(b.x-d.x,b.y-d.y,b.z-d.z,c)),d=AngleBetween(e,b);var f=e.Length(),g=b.Length();if(a===Body.Sun)a=SUN_MAG_1AU+5*Math.log10(f);else if(a===Body.Moon)a=MoonMagnitude(d,g,f);else if(a=== +Body.Saturn){var k=SaturnMagnitude(d,g,f,e,c);a=k.mag;k=k.ring_tilt}else a=VisualMagnitude(a,d,g,f);return new IlluminationInfo(c,a,d,g,f,e,b,k)}exports.Illumination=Illumination;function SynodicPeriod(a){if(a===Body.Earth)throw"The Earth does not have a synodic period as seen from itself.";if(a===Body.Moon)return MEAN_SYNODIC_MONTH;var b=Planet[a];if(!b)throw"Not a valid planet name: "+a;a=Planet.Earth.OrbitalPeriod;return Math.abs(a/(a/b.OrbitalPeriod-1))} +function SearchRelativeLongitude(a,b,c){function d(l){var m=EclipticLongitude(a,l);l=EclipticLongitude(Body.Earth,l);return LongitudeOffset(f*(l-m)-b)}VerifyNumber(b);var e=Planet[a];if(!e)throw"Cannot search relative longitude because body is not a planet: "+a;if(a===Body.Earth)throw"Cannot search relative longitude for the Earth (it is always 0)";var f=e.OrbitalPeriod>Planet.Earth.OrbitalPeriod?1:-1;e=SynodicPeriod(a);c=MakeTime(c);var g=d(c);0k;++k){var h=-g/360*e; +c=c.AddDays(h);if(1>Math.abs(h)*SECONDS_PER_DAY)return c;h=g;g=d(c);30>Math.abs(h)&&h!==g&&(h/=h-g,.5h&&(e*=h))}throw"Relative longitude search failed to converge for "+a+" near "+c.toString()+" (error_angle = "+g+").";}exports.SearchRelativeLongitude=SearchRelativeLongitude;function MoonPhase(a){return PairLongitude(Body.Moon,Body.Sun,a)}exports.MoonPhase=MoonPhase; +function SearchMoonPhase(a,b,c){function d(k){k=MoonPhase(k);return LongitudeOffset(k-a)}VerifyNumber(a);VerifyNumber(c);b=MakeTime(b);var e=d(b);if(0>c){0>e&&(e+=360);var f=-(MEAN_SYNODIC_MONTH*e)/360;e=f+1.5;if(ec)return null;e=Math.min(c,f+1.5)}c=b.AddDays(g);b=b.AddDays(e);return Search(d,c,b,{dt_tolerance_seconds:.1})}exports.SearchMoonPhase=SearchMoonPhase; +var MoonQuarter=function(a,b){this.quarter=a;this.time=b};exports.MoonQuarter=MoonQuarter;function SearchMoonQuarter(a){var b=MoonPhase(a);b=(Math.floor(b/90)+1)%4;a=SearchMoonPhase(90*b,a,10);if(!a)throw"Cannot find moon quarter";return new MoonQuarter(b,a)}exports.SearchMoonQuarter=SearchMoonQuarter;function NextMoonQuarter(a){a=new Date(a.time.date.getTime()+6*MILLIS_PER_DAY);return SearchMoonQuarter(a)}exports.NextMoonQuarter=NextMoonQuarter; +var AtmosphereInfo=function(a,b,c){this.pressure=a;this.temperature=b;this.density=c};exports.AtmosphereInfo=AtmosphereInfo;function Atmosphere(a){if(!Number.isFinite(a)||-500>a||1E5=a){var b=288.15-.0065*a;a=101325*Math.pow(288.15/b,-5.25577)}else 2E4>=a?(b=216.65,a=22632*Math.exp(-1.5768832E-4*(a-11E3))):(b=216.65+.001*(a-2E4),a=5474.87*Math.pow(216.65/b,34.16319));return new AtmosphereInfo(a,b,a/b/(101325/288.15))}exports.Atmosphere=Atmosphere; +function HorizonDipAngle(a,b){var c=a.latitude*exports.DEG2RAD,d=Math.sin(c);c=Math.cos(c);var e=1/Math.hypot(c,d*EARTH_FLATTENING),f=(a.height-b)/1E3;a=.175*Math.pow(1-.0065/283.15*(a.height-2/3*b),3.256);return exports.RAD2DEG*-(Math.sqrt(2*(1-a)*b/(1E3*Math.hypot((EARTH_EQUATORIAL_RADIUS_KM*e+f)*c,(EARTH_EQUATORIAL_RADIUS_KM*e*EARTH_FLATTENING*EARTH_FLATTENING+f)*d)))/(1-a))} +function BodyRadiusAu(a){switch(a){case Body.Sun:return SUN_RADIUS_AU;case Body.Moon:return MOON_EQUATORIAL_RADIUS_AU;default:return 0}}function SearchRiseSet(a,b,c,d,e,f){f=void 0===f?0:f;if(!Number.isFinite(f)||0>f)throw"Invalid value for metersAboveGround: "+f;var g=BodyRadiusAu(a),k=Atmosphere(b.height-f);f=HorizonDipAngle(b,f)-REFRACTION_NEAR_HORIZON*k.density;return InternalSearchAltitude(a,b,c,d,e,g,f)}exports.SearchRiseSet=SearchRiseSet; +function SearchAltitude(a,b,c,d,e,f){if(!Number.isFinite(f)||-90>f||90f&&0<=g)return new AscentInfo(d,e,f,g);if(0<=f&&0>g)return null;if(17k*SECONDS_PER_DAY||Math.min(Math.abs(f),Math.abs(g))>k/2*c)return null;k=new AstroTime((d.ut+e.ut)/2);var h=b(k);return FindAscent(1+a,b,c,d,k,f,h)||FindAscent(1+a,b,c,k,e,h,g)} +function MaxAltitudeSlope(a,b){if(-90>b||90g||90e?(l=m.AddDays(-.42),n=k(l)):(m=l.AddDays(.42),p=k(m));var r=FindAscent(0,k,h,l,m,n,p);if(r){if(h=Search(k,r.tx,r.ty,{dt_tolerance_seconds:.1, +init_f1:r.ax,init_f2:r.ay})){if(0>e){if(h.utd.ut+e)return null;return h}throw"Rise/set search failed after finding ascent: t1="+l+", t2="+m+", a1="+n+", a2="+p;}if(0>e){if(l.utd.ut+e)return null;l=m;n=p}}}var HourAngleEvent=function(a,b){this.time=a;this.hor=b};exports.HourAngleEvent=HourAngleEvent; +function SearchHourAngle(a,b,c,d,e){e=void 0===e?1:e;VerifyObserver(b);d=MakeTime(d);var f=0;if(a===Body.Earth)throw"Cannot search for hour angle of the Earth.";VerifyNumber(c);if(0>c||24<=c)throw"Invalid hour angle "+c;VerifyNumber(e);if(0===e)throw"Direction must be positive or negative.";for(;;){++f;var g=sidereal_time(d),k=Equator(a,d,b,!0,!0);g=(c+k.ra-b.longitude/15-g)%24;1===f?0g&&(g+=24):0g?g+=24:123600*Math.abs(g))return a=Horizon(d,b,k.ra,k.dec,"normal"), +new HourAngleEvent(d,a);d=d.AddDays(g/24*SOLAR_DAYS_PER_SIDEREAL_DAY)}}exports.SearchHourAngle=SearchHourAngle;function HourAngle(a,b,c){var d=MakeTime(b);b=SiderealTime(d);a=Equator(a,d,c,!0,!0);c=(c.longitude/15+b-a.ra)%24;0>c&&(c+=24);return c}exports.HourAngle=HourAngle;var SeasonInfo=function(a,b,c,d){this.mar_equinox=a;this.jun_solstice=b;this.sep_equinox=c;this.dec_solstice=d};exports.SeasonInfo=SeasonInfo; +function Seasons(a){function b(g,k,h){k=new Date(Date.UTC(a,k-1,h));g=SearchSunLongitude(g,k,20);if(!g)throw"Cannot find season change near "+k.toISOString();return g}a instanceof Date&&Number.isFinite(a.getTime())&&(a=a.getUTCFullYear());if(!Number.isSafeInteger(a))throw"Cannot calculate seasons because year argument "+a+" is neither a Date nor a safe integer.";var c=b(0,3,10),d=b(90,6,10),e=b(180,9,10),f=b(270,12,10);return new SeasonInfo(c,d,e,f)}exports.Seasons=Seasons; +var ElongationEvent=function(a,b,c,d){this.time=a;this.visibility=b;this.elongation=c;this.ecliptic_separation=d};exports.ElongationEvent=ElongationEvent;function Elongation(a,b){b=MakeTime(b);var c=PairLongitude(a,Body.Sun,b);if(180=++e;){var f=EclipticLongitude(a,b),g=EclipticLongitude(Body.Earth,b),k=LongitudeOffset(f-g),h=f=g=void 0;k>=-d.s1&&k<+d.s1?(h=0,g=+d.s1,f=+d.s2):k>=+d.s2||k<-d.s2?(h=0,g=-d.s2,f=-d.s1):0<=k?(h=-SynodicPeriod(a)/ +4,g=+d.s1,f=+d.s2):(h=-SynodicPeriod(a)/4,g=-d.s2,f=-d.s1);k=b.AddDays(h);g=SearchRelativeLongitude(a,g,k);f=SearchRelativeLongitude(a,f,g);k=c(g);if(0<=k)throw"SearchMaxElongation: internal error: m1 = "+k;h=c(f);if(0>=h)throw"SearchMaxElongation: internal error: m2 = "+h;k=Search(c,g,f,{init_f1:k,init_f2:h,dt_tolerance_seconds:10});if(!k)throw"SearchMaxElongation: failed search iter "+e+" (t1="+g.toString()+", t2="+f.toString()+")";if(k.tt>=b.tt)return Elongation(a,k);b=f.AddDays(1)}throw"SearchMaxElongation: failed to find event after 2 tries."; +}exports.SearchMaxElongation=SearchMaxElongation; +function SearchPeakMagnitude(a,b){function c(h){var l=h.AddDays(-.005);h=h.AddDays(.005);l=Illumination(a,l).mag;return(Illumination(a,h).mag-l)/.01}if(a!==Body.Venus)throw"SearchPeakMagnitude currently works for Venus only.";b=MakeTime(b);for(var d=0;2>=++d;){var e=EclipticLongitude(a,b),f=EclipticLongitude(Body.Earth,b),g=LongitudeOffset(e-f),k=e=f=void 0;-10<=g&&10>g?(k=0,f=10,e=30):30<=g||-30>g?(k=0,f=-30,e=-10):0<=g?(k=-SynodicPeriod(a)/4,f=10,e=30):(k=-SynodicPeriod(a)/4,f=-30,e=-10);g=b.AddDays(k); +f=SearchRelativeLongitude(a,f,g);e=SearchRelativeLongitude(a,e,f);g=c(f);if(0<=g)throw"SearchPeakMagnitude: internal error: m1 = "+g;k=c(e);if(0>=k)throw"SearchPeakMagnitude: internal error: m2 = "+k;g=Search(c,f,e,{init_f1:g,init_f2:k,dt_tolerance_seconds:10});if(!g)throw"SearchPeakMagnitude: failed search iter "+d+" (t1="+f.toString()+", t2="+e.toString()+")";if(g.tt>=b.tt)return Illumination(a,g);b=e.AddDays(1)}throw"SearchPeakMagnitude: failed to find event after 2 tries.";} +exports.SearchPeakMagnitude=SearchPeakMagnitude;var ApsisKind;(function(a){a[a.Pericenter=0]="Pericenter";a[a.Apocenter=1]="Apocenter"})(ApsisKind=exports.ApsisKind||(exports.ApsisKind={}));var Apsis=function(a,b,c){this.time=a;this.kind=b;this.dist_au=c;this.dist_km=c*exports.KM_PER_AU};exports.Apsis=Apsis; +function SearchLunarApsis(a){function b(k){var h=k.AddDays(-5E-4);k=k.AddDays(5E-4);h=CalcMoon(h).distance_au;return(CalcMoon(k).distance_au-h)/.001}function c(k){return-b(k)}a=MakeTime(a);for(var d=b(a),e=0;5*e<2*MEAN_SYNODIC_MONTH;++e){var f=a.AddDays(5),g=b(f);if(0>=d*g){if(0>d||0g){a=Search(c,a,f,{init_f1:-d,init_f2:-g});if(!a)throw"SearchLunarApsis INTERNAL ERROR: apogee search failed!"; +d=CalcMoon(a).distance_au;return new Apsis(a,1,d)}throw"SearchLunarApsis INTERNAL ERROR: cannot classify apsis event!";}a=f;d=g}throw"SearchLunarApsis INTERNAL ERROR: could not find apsis within 2 synodic months of start date.";}exports.SearchLunarApsis=SearchLunarApsis; +function NextLunarApsis(a){var b=SearchLunarApsis(a.time.AddDays(11));if(1!==b.kind+a.kind)throw"NextLunarApsis INTERNAL ERROR: did not find alternating apogee/perigee: prev="+a.kind+" @ "+a.time.toString()+", next="+b.kind+" @ "+b.time.toString();return b}exports.NextLunarApsis=NextLunarApsis; +function PlanetExtreme(a,b,c,d){for(var e=b===ApsisKind.Apocenter?1:-1;;){d/=9;if(d<1/1440)return c=c.AddDays(d/2),a=HelioDistance(a,c),new Apsis(c,b,a);for(var f=-1,g=0,k=0;10>k;++k){var h=c.AddDays(k*d);h=e*HelioDistance(a,h);if(0==k||h>g)f=k,g=h}c=c.AddDays((f-1)*d);d*=2}} +function BruteSearchPlanetApsis(a,b){var c=b.AddDays(-30/360*Planet[a].OrbitalPeriod),d=b.AddDays(.75*Planet[a].OrbitalPeriod),e=c,f=c,g=-1,k=-1;d=(d.ut-c.ut)/99;for(var h=0;100>h;++h){var l=c.AddDays(h*d),m=HelioDistance(a,l);0===h?k=g=m:(m>k&&(k=m,f=l),m=b.tt)return a.time.tt>=b.tt&&a.time.tt=b.tt)return a;throw"Internal error: failed to find Neptune apsis."; +} +function SearchPlanetApsis(a,b){function c(m){var n=m.AddDays(-5E-4);m=m.AddDays(5E-4);n=HelioDistance(a,n);return(HelioDistance(a,m)-n)/.001}function d(m){return-c(m)}b=MakeTime(b);if(a===Body.Neptune||a===Body.Pluto)return BruteSearchPlanetApsis(a,b);for(var e=Planet[a].OrbitalPeriod,f=e/6,g=c(b),k=0;k*f<2*e;++k){var h=b.AddDays(f),l=c(h);if(0>=g*l){e=f=void 0;if(0>g||0l)f=d,e=ApsisKind.Apocenter;else throw"Internal error with slopes in SearchPlanetApsis";b= +Search(f,b,h);if(!b)throw"Failed to find slope transition in planetary apsis search.";g=HelioDistance(a,b);return new Apsis(b,e,g)}b=h;g=l}throw"Internal error: should have found planetary apsis within 2 orbital periods.";}exports.SearchPlanetApsis=SearchPlanetApsis; +function NextPlanetApsis(a,b){if(b.kind!==ApsisKind.Pericenter&&b.kind!==ApsisKind.Apocenter)throw"Invalid apsis kind: "+b.kind;var c=b.time.AddDays(.25*Planet[a].OrbitalPeriod);a=SearchPlanetApsis(a,c);if(1!==a.kind+b.kind)throw"Internal error: previous apsis was "+b.kind+", but found "+a.kind+" for next apsis.";return a}exports.NextPlanetApsis=NextPlanetApsis; +function InverseRotation(a){return new RotationMatrix([[a.rot[0][0],a.rot[1][0],a.rot[2][0]],[a.rot[0][1],a.rot[1][1],a.rot[2][1]],[a.rot[0][2],a.rot[1][2],a.rot[2][2]]])}exports.InverseRotation=InverseRotation; +function CombineRotation(a,b){return new RotationMatrix([[b.rot[0][0]*a.rot[0][0]+b.rot[1][0]*a.rot[0][1]+b.rot[2][0]*a.rot[0][2],b.rot[0][1]*a.rot[0][0]+b.rot[1][1]*a.rot[0][1]+b.rot[2][1]*a.rot[0][2],b.rot[0][2]*a.rot[0][0]+b.rot[1][2]*a.rot[0][1]+b.rot[2][2]*a.rot[0][2]],[b.rot[0][0]*a.rot[1][0]+b.rot[1][0]*a.rot[1][1]+b.rot[2][0]*a.rot[1][2],b.rot[0][1]*a.rot[1][0]+b.rot[1][1]*a.rot[1][1]+b.rot[2][1]*a.rot[1][2],b.rot[0][2]*a.rot[1][0]+b.rot[1][2]*a.rot[1][1]+b.rot[2][2]*a.rot[1][2]],[b.rot[0][0]* +a.rot[2][0]+b.rot[1][0]*a.rot[2][1]+b.rot[2][0]*a.rot[2][2],b.rot[0][1]*a.rot[2][0]+b.rot[1][1]*a.rot[2][1]+b.rot[2][1]*a.rot[2][2],b.rot[0][2]*a.rot[2][0]+b.rot[1][2]*a.rot[2][1]+b.rot[2][2]*a.rot[2][2]]])}exports.CombineRotation=CombineRotation;function IdentityMatrix(){return new RotationMatrix([[1,0,0],[0,1,0],[0,0,1]])}exports.IdentityMatrix=IdentityMatrix; +function Pivot(a,b,c){if(0!==b&&1!==b&&2!==b)throw"Invalid axis "+b+". Must be [0, 1, 2].";var d=VerifyNumber(c)*exports.DEG2RAD;c=Math.cos(d);d=Math.sin(d);var e=(b+1)%3,f=(b+2)%3,g=[[0,0,0],[0,0,0],[0,0,0]];g[e][e]=c*a.rot[e][e]-d*a.rot[e][f];g[e][f]=d*a.rot[e][e]+c*a.rot[e][f];g[e][b]=a.rot[e][b];g[f][e]=c*a.rot[f][e]-d*a.rot[f][f];g[f][f]=d*a.rot[f][e]+c*a.rot[f][f];g[f][b]=a.rot[f][b];g[b][e]=c*a.rot[b][e]-d*a.rot[b][f];g[b][f]=d*a.rot[b][e]+c*a.rot[b][f];g[b][b]=a.rot[b][b];return new RotationMatrix(g)} +exports.Pivot=Pivot;function VectorFromSphere(a,b){b=MakeTime(b);var c=a.lat*exports.DEG2RAD,d=a.lon*exports.DEG2RAD,e=a.dist*Math.cos(c);return new Vector(e*Math.cos(d),e*Math.sin(d),a.dist*Math.sin(c),b)}exports.VectorFromSphere=VectorFromSphere;function EquatorFromVector(a){var b=SphereFromVector(a);return new EquatorialCoordinates(b.lon/15,b.lat,b.dist,a)}exports.EquatorFromVector=EquatorFromVector; +function SphereFromVector(a){var b=a.x*a.x+a.y*a.y,c=Math.sqrt(b+a.z*a.z);if(0===b){if(0===a.z)throw"Zero-length vector not allowed.";var d=0;a=0>a.z?-90:90}else d=exports.RAD2DEG*Math.atan2(a.y,a.x),0>d&&(d+=360),a=exports.RAD2DEG*Math.atan2(a.z,Math.sqrt(b));return new Spherical(a,d,c)}exports.SphereFromVector=SphereFromVector;function ToggleAzimuthDirection(a){a=360-a;360<=a?a-=360:0>a&&(a+=360);return a} +function HorizonFromVector(a,b){a=SphereFromVector(a);a.lon=ToggleAzimuthDirection(a.lon);a.lat+=Refraction(b,a.lat);return a}exports.HorizonFromVector=HorizonFromVector;function VectorFromHorizon(a,b,c){b=MakeTime(b);var d=ToggleAzimuthDirection(a.lon);c=a.lat+InverseRefraction(c,a.lat);a=new Spherical(c,d,a.dist);return VectorFromSphere(a,b)}exports.VectorFromHorizon=VectorFromHorizon; +function Refraction(a,b){VerifyNumber(b);if(-90>b||90c&&(c=-1);c=1.02/Math.tan((c+10.3/(c+5.11))*exports.DEG2RAD)/60;"normal"===a&&-1>b&&(c*=(b+90)/89)}else{if(a)throw"Invalid refraction option: "+a;c=0}return c}exports.Refraction=Refraction;function InverseRefraction(a,b){if(-90>b||90Math.abs(d))return c-b;c-=d}}exports.InverseRefraction=InverseRefraction; +function RotateVector(a,b){return new Vector(a.rot[0][0]*b.x+a.rot[1][0]*b.y+a.rot[2][0]*b.z,a.rot[0][1]*b.x+a.rot[1][1]*b.y+a.rot[2][1]*b.z,a.rot[0][2]*b.x+a.rot[1][2]*b.y+a.rot[2][2]*b.z,b.t)}exports.RotateVector=RotateVector; +function RotateState(a,b){return new StateVector(a.rot[0][0]*b.x+a.rot[1][0]*b.y+a.rot[2][0]*b.z,a.rot[0][1]*b.x+a.rot[1][1]*b.y+a.rot[2][1]*b.z,a.rot[0][2]*b.x+a.rot[1][2]*b.y+a.rot[2][2]*b.z,a.rot[0][0]*b.vx+a.rot[1][0]*b.vy+a.rot[2][0]*b.vz,a.rot[0][1]*b.vx+a.rot[1][1]*b.vy+a.rot[2][1]*b.vz,a.rot[0][2]*b.vx+a.rot[1][2]*b.vy+a.rot[2][2]*b.vz,b.t)}exports.RotateState=RotateState; +function Rotation_EQJ_ECL(){return new RotationMatrix([[1,0,0],[0,.9174821430670688,-.3977769691083922],[0,.3977769691083922,.9174821430670688]])}exports.Rotation_EQJ_ECL=Rotation_EQJ_ECL;function Rotation_ECL_EQJ(){return new RotationMatrix([[1,0,0],[0,.9174821430670688,.3977769691083922],[0,-.3977769691083922,.9174821430670688]])}exports.Rotation_ECL_EQJ=Rotation_ECL_EQJ; +function Rotation_EQJ_EQD(a){a=MakeTime(a);var b=precession_rot(a,PrecessDirection.From2000);a=nutation_rot(a,PrecessDirection.From2000);return CombineRotation(b,a)}exports.Rotation_EQJ_EQD=Rotation_EQJ_EQD;function Rotation_EQJ_ECT(a){var b=MakeTime(a);a=Rotation_EQJ_EQD(b);b=Rotation_EQD_ECT(b);return CombineRotation(a,b)}exports.Rotation_EQJ_ECT=Rotation_EQJ_ECT;function Rotation_ECT_EQJ(a){var b=MakeTime(a);a=Rotation_ECT_EQD(b);b=Rotation_EQD_EQJ(b);return CombineRotation(a,b)} +exports.Rotation_ECT_EQJ=Rotation_ECT_EQJ;function Rotation_EQD_EQJ(a){a=MakeTime(a);var b=nutation_rot(a,PrecessDirection.Into2000);a=precession_rot(a,PrecessDirection.Into2000);return CombineRotation(b,a)}exports.Rotation_EQD_EQJ=Rotation_EQD_EQJ; +function Rotation_EQD_HOR(a,b){a=MakeTime(a);var c=Math.sin(b.latitude*exports.DEG2RAD),d=Math.cos(b.latitude*exports.DEG2RAD),e=Math.sin(b.longitude*exports.DEG2RAD),f=Math.cos(b.longitude*exports.DEG2RAD);b=[d*f,d*e,c];c=[-c*f,-c*e,d];e=[e,-f,0];a=-15*sidereal_time(a);b=spin(a,b);c=spin(a,c);a=spin(a,e);return new RotationMatrix([[c[0],a[0],b[0]],[c[1],a[1],b[1]],[c[2],a[2],b[2]]])}exports.Rotation_EQD_HOR=Rotation_EQD_HOR; +function Rotation_HOR_EQD(a,b){a=Rotation_EQD_HOR(a,b);return InverseRotation(a)}exports.Rotation_HOR_EQD=Rotation_HOR_EQD;function Rotation_HOR_EQJ(a,b){a=MakeTime(a);b=Rotation_HOR_EQD(a,b);a=Rotation_EQD_EQJ(a);return CombineRotation(b,a)}exports.Rotation_HOR_EQJ=Rotation_HOR_EQJ;function Rotation_EQJ_HOR(a,b){a=Rotation_HOR_EQJ(a,b);return InverseRotation(a)}exports.Rotation_EQJ_HOR=Rotation_EQJ_HOR; +function Rotation_EQD_ECL(a){a=Rotation_EQD_EQJ(a);var b=Rotation_EQJ_ECL();return CombineRotation(a,b)}exports.Rotation_EQD_ECL=Rotation_EQD_ECL;function Rotation_ECL_EQD(a){a=Rotation_EQD_ECL(a);return InverseRotation(a)}exports.Rotation_ECL_EQD=Rotation_ECL_EQD;function Rotation_ECL_HOR(a,b){a=MakeTime(a);var c=Rotation_ECL_EQD(a);a=Rotation_EQD_HOR(a,b);return CombineRotation(c,a)}exports.Rotation_ECL_HOR=Rotation_ECL_HOR; +function Rotation_HOR_ECL(a,b){a=Rotation_ECL_HOR(a,b);return InverseRotation(a)}exports.Rotation_HOR_ECL=Rotation_HOR_ECL;function Rotation_EQJ_GAL(){return new RotationMatrix([[-.0548624779711344,.4941095946388765,-.8676668813529025],[-.8734572784246782,-.4447938112296831,-.1980677870294097],[-.483800052994852,.7470034631630423,.4559861124470794]])}exports.Rotation_EQJ_GAL=Rotation_EQJ_GAL; +function Rotation_GAL_EQJ(){return new RotationMatrix([[-.0548624779711344,-.8734572784246782,-.483800052994852],[.4941095946388765,-.4447938112296831,.7470034631630423],[-.8676668813529025,-.1980677870294097,.4559861124470794]])}exports.Rotation_GAL_EQJ=Rotation_GAL_EQJ;function Rotation_ECT_EQD(a){var b=e_tilt(MakeTime(a)).tobl*exports.DEG2RAD;a=Math.cos(b);b=Math.sin(b);return new RotationMatrix([[1,0,0],[0,+a,+b],[0,-b,+a]])}exports.Rotation_ECT_EQD=Rotation_ECT_EQD; +function Rotation_EQD_ECT(a){var b=e_tilt(MakeTime(a)).tobl*exports.DEG2RAD;a=Math.cos(b);b=Math.sin(b);return new RotationMatrix([[1,0,0],[0,+a,-b],[0,+b,+a]])}exports.Rotation_EQD_ECT=Rotation_EQD_ECT; +var ConstelNames=[["And","Andromeda"],["Ant","Antila"],["Aps","Apus"],["Aql","Aquila"],["Aqr","Aquarius"],["Ara","Ara"],["Ari","Aries"],["Aur","Auriga"],["Boo","Bootes"],["Cae","Caelum"],["Cam","Camelopardis"],["Cap","Capricornus"],["Car","Carina"],["Cas","Cassiopeia"],["Cen","Centaurus"],["Cep","Cepheus"],["Cet","Cetus"],["Cha","Chamaeleon"],["Cir","Circinus"],["CMa","Canis Major"],["CMi","Canis Minor"],["Cnc","Cancer"],["Col","Columba"],["Com","Coma Berenices"],["CrA","Corona Australis"],["CrB", +"Corona Borealis"],["Crt","Crater"],["Cru","Crux"],["Crv","Corvus"],["CVn","Canes Venatici"],["Cyg","Cygnus"],["Del","Delphinus"],["Dor","Dorado"],["Dra","Draco"],["Equ","Equuleus"],["Eri","Eridanus"],["For","Fornax"],["Gem","Gemini"],["Gru","Grus"],["Her","Hercules"],["Hor","Horologium"],["Hya","Hydra"],["Hyi","Hydrus"],["Ind","Indus"],["Lac","Lacerta"],["Leo","Leo"],["Lep","Lepus"],["Lib","Libra"],["LMi","Leo Minor"],["Lup","Lupus"],["Lyn","Lynx"],["Lyr","Lyra"],["Men","Mensa"],["Mic","Microscopium"], +["Mon","Monoceros"],["Mus","Musca"],["Nor","Norma"],["Oct","Octans"],["Oph","Ophiuchus"],["Ori","Orion"],["Pav","Pavo"],["Peg","Pegasus"],["Per","Perseus"],["Phe","Phoenix"],["Pic","Pictor"],["PsA","Pisces Austrinus"],["Psc","Pisces"],["Pup","Puppis"],["Pyx","Pyxis"],["Ret","Reticulum"],["Scl","Sculptor"],["Sco","Scorpius"],["Sct","Scutum"],["Ser","Serpens"],["Sex","Sextans"],["Sge","Sagitta"],["Sgr","Sagittarius"],["Tau","Taurus"],["Tel","Telescopium"],["TrA","Triangulum Australe"],["Tri","Triangulum"], +["Tuc","Tucana"],["UMa","Ursa Major"],["UMi","Ursa Minor"],["Vel","Vela"],["Vir","Virgo"],["Vol","Volans"],["Vul","Vulpecula"]],ConstelBounds=[[83,0,8640,2112],[83,2880,5220,2076],[83,7560,8280,2068],[83,6480,7560,2064],[15,0,2880,2040],[10,3300,3840,1968],[15,0,1800,1920],[10,3840,5220,1920],[83,6300,6480,1920],[33,7260,7560,1920],[15,0,1263,1848],[10,4140,4890,1848],[83,5952,6300,1800],[15,7260,7440,1800],[10,2868,3300,1764],[33,3300,4080,1764],[83,4680,5952,1680],[13,1116,1230,1632],[33,7350,7440, +1608],[33,4080,4320,1596],[15,0,120,1584],[83,5040,5640,1584],[15,8490,8640,1584],[33,4320,4860,1536],[33,4860,5190,1512],[15,8340,8490,1512],[10,2196,2520,1488],[33,7200,7350,1476],[15,7393.2,7416,1462],[10,2520,2868,1440],[82,2868,3030,1440],[33,7116,7200,1428],[15,7200,7393.2,1428],[15,8232,8340,1418],[13,0,876,1404],[33,6990,7116,1392],[13,612,687,1380],[13,876,1116,1368],[10,1116,1140,1368],[15,8034,8232,1350],[10,1800,2196,1344],[82,5052,5190,1332],[33,5190,6990,1332],[10,1140,1200,1320],[15, +7968,8034,1320],[15,7416,7908,1316],[13,0,612,1296],[50,2196,2340,1296],[82,4350,4860,1272],[33,5490,5670,1272],[15,7908,7968,1266],[10,1200,1800,1260],[13,8232,8400,1260],[33,5670,6120,1236],[62,735,906,1212],[33,6120,6564,1212],[13,0,492,1200],[62,492,600,1200],[50,2340,2448,1200],[13,8400,8640,1200],[82,4860,5052,1164],[13,0,402,1152],[13,8490,8640,1152],[39,6543,6564,1140],[33,6564,6870,1140],[30,6870,6900,1140],[62,600,735,1128],[82,3030,3300,1128],[13,60,312,1104],[82,4320,4350,1080],[50,2448, +2652,1068],[30,7887,7908,1056],[30,7875,7887,1050],[30,6900,6984,1044],[82,3300,3660,1008],[82,3660,3882,960],[8,5556,5670,960],[39,5670,5880,960],[50,3330,3450,954],[0,0,906,882],[62,906,924,882],[51,6969,6984,876],[62,1620,1689,864],[30,7824,7875,864],[44,7875,7920,864],[7,2352,2652,852],[50,2652,2790,852],[0,0,720,840],[44,7920,8214,840],[44,8214,8232,828],[0,8232,8460,828],[62,924,978,816],[82,3882,3960,816],[29,4320,4440,816],[50,2790,3330,804],[48,3330,3558,804],[0,258,507,792],[8,5466,5556, +792],[0,8460,8550,770],[29,4440,4770,768],[0,8550,8640,752],[29,5025,5052,738],[80,870,978,736],[62,978,1620,736],[7,1620,1710,720],[51,6543,6969,720],[82,3960,4320,696],[30,7080,7530,696],[7,1710,2118,684],[48,3558,3780,684],[29,4770,5025,684],[0,0,24,672],[80,507,600,672],[7,2118,2352,672],[37,2838,2880,672],[30,7530,7824,672],[30,6933,7080,660],[80,690,870,654],[25,5820,5880,648],[8,5430,5466,624],[25,5466,5820,624],[51,6612,6792,624],[48,3870,3960,612],[51,6792,6933,612],[80,600,690,600],[66, +258,306,570],[48,3780,3870,564],[87,7650,7710,564],[77,2052,2118,548],[0,24,51,528],[73,5730,5772,528],[37,2118,2238,516],[87,7140,7290,510],[87,6792,6930,506],[0,51,306,504],[87,7290,7404,492],[37,2811,2838,480],[87,7404,7650,468],[87,6930,7140,460],[6,1182,1212,456],[75,6792,6840,444],[59,2052,2076,432],[37,2238,2271,420],[75,6840,7140,388],[77,1788,1920,384],[39,5730,5790,384],[75,7140,7290,378],[77,1662,1788,372],[77,1920,2016,372],[23,4620,4860,360],[39,6210,6570,344],[23,4272,4620,336],[37, +2700,2811,324],[39,6030,6210,308],[61,0,51,300],[77,2016,2076,300],[37,2520,2700,300],[61,7602,7680,300],[37,2271,2496,288],[39,6570,6792,288],[31,7515,7578,284],[61,7578,7602,284],[45,4146,4272,264],[59,2247,2271,240],[37,2496,2520,240],[21,2811,2853,240],[61,8580,8640,240],[6,600,1182,238],[31,7251,7308,204],[8,4860,5430,192],[61,8190,8580,180],[21,2853,3330,168],[45,3330,3870,168],[58,6570,6718.4,150],[3,6718.4,6792,150],[31,7500,7515,144],[20,2520,2526,132],[73,6570,6633,108],[39,5790,6030,96], +[58,6570,6633,72],[61,7728,7800,66],[66,0,720,48],[73,6690,6792,48],[31,7308,7500,48],[34,7500,7680,48],[61,7680,7728,48],[61,7920,8190,48],[61,7800,7920,42],[20,2526,2592,36],[77,1290,1662,0],[59,1662,1680,0],[20,2592,2910,0],[85,5280,5430,0],[58,6420,6570,0],[16,954,1182,-42],[77,1182,1290,-42],[73,5430,5856,-78],[59,1680,1830,-96],[59,2100,2247,-96],[73,6420,6468,-96],[73,6570,6690,-96],[3,6690,6792,-96],[66,8190,8580,-96],[45,3870,4146,-144],[85,4146,4260,-144],[66,0,120,-168],[66,8580,8640,-168], +[85,5130,5280,-192],[58,5730,5856,-192],[3,7200,7392,-216],[4,7680,7872,-216],[58,6180,6468,-240],[54,2100,2910,-264],[35,1770,1830,-264],[59,1830,2100,-264],[41,2910,3012,-264],[74,3450,3870,-264],[85,4260,4620,-264],[58,6330,6360,-280],[3,6792,7200,-288.8],[35,1740,1770,-348],[4,7392,7680,-360],[73,6180,6570,-384],[72,6570,6792,-384],[41,3012,3090,-408],[58,5856,5895,-438],[41,3090,3270,-456],[26,3870,3900,-456],[71,5856,5895,-462],[47,5640,5730,-480],[28,4530,4620,-528],[85,4620,5130,-528],[41, +3270,3510,-576],[16,600,954,-585.2],[35,954,1350,-585.2],[26,3900,4260,-588],[28,4260,4530,-588],[47,5130,5370,-588],[58,5856,6030,-590],[16,0,600,-612],[11,7680,7872,-612],[4,7872,8580,-612],[16,8580,8640,-612],[41,3510,3690,-636],[35,1692,1740,-654],[46,1740,2202,-654],[11,7200,7680,-672],[41,3690,3810,-700],[41,4530,5370,-708],[47,5370,5640,-708],[71,5640,5760,-708],[35,1650,1692,-720],[58,6030,6336,-720],[76,6336,6420,-720],[41,3810,3900,-748],[19,2202,2652,-792],[41,4410,4530,-792],[41,3900, +4410,-840],[36,1260,1350,-864],[68,3012,3372,-882],[35,1536,1650,-888],[76,6420,6900,-888],[65,7680,8280,-888],[70,8280,8400,-888],[36,1080,1260,-950],[1,3372,3960,-954],[70,0,600,-960],[36,600,1080,-960],[35,1392,1536,-960],[70,8400,8640,-960],[14,5100,5370,-1008],[49,5640,5760,-1008],[71,5760,5911.5,-1008],[9,1740,1800,-1032],[22,1800,2370,-1032],[67,2880,3012,-1032],[35,1230,1392,-1056],[71,5911.5,6420,-1092],[24,6420,6900,-1092],[76,6900,7320,-1092],[53,7320,7680,-1092],[35,1080,1230,-1104],[9, +1620,1740,-1116],[49,5520,5640,-1152],[63,0,840,-1156],[35,960,1080,-1176],[40,1470,1536,-1176],[9,1536,1620,-1176],[38,7680,7920,-1200],[67,2160,2880,-1218],[84,2880,2940,-1218],[35,870,960,-1224],[40,1380,1470,-1224],[63,0,660,-1236],[12,2160,2220,-1260],[84,2940,3042,-1272],[40,1260,1380,-1276],[32,1380,1440,-1276],[63,0,570,-1284],[35,780,870,-1296],[64,1620,1800,-1296],[49,5418,5520,-1296],[84,3042,3180,-1308],[12,2220,2340,-1320],[14,4260,4620,-1320],[49,5100,5418,-1320],[56,5418,5520,-1320], +[32,1440,1560,-1356],[84,3180,3960,-1356],[14,3960,4050,-1356],[5,6300,6480,-1368],[78,6480,7320,-1368],[38,7920,8400,-1368],[40,1152,1260,-1380],[64,1800,1980,-1380],[12,2340,2460,-1392],[63,0,480,-1404],[35,480,780,-1404],[63,8400,8640,-1404],[32,1560,1650,-1416],[56,5520,5911.5,-1440],[43,7320,7680,-1440],[64,1980,2160,-1464],[18,5460,5520,-1464],[5,5911.5,5970,-1464],[18,5370,5460,-1526],[5,5970,6030,-1526],[64,2160,2460,-1536],[12,2460,3252,-1536],[14,4050,4260,-1536],[27,4260,4620,-1536],[14, +4620,5232,-1536],[18,4860,4920,-1560],[5,6030,6060,-1560],[40,780,1152,-1620],[69,1152,1650,-1620],[18,5310,5370,-1620],[5,6060,6300,-1620],[60,6300,6480,-1620],[81,7920,8400,-1620],[32,1650,2370,-1680],[18,4920,5310,-1680],[79,5310,6120,-1680],[81,0,480,-1800],[42,1260,1650,-1800],[86,2370,3252,-1800],[12,3252,4050,-1800],[55,4050,4920,-1800],[60,6480,7680,-1800],[43,7680,8400,-1800],[81,8400,8640,-1800],[81,270,480,-1824],[42,0,1260,-1980],[17,2760,4920,-1980],[2,4920,6480,-1980],[52,1260,2760, +-2040],[57,0,8640,-2160]],ConstelRot,Epoch2000,ConstellationInfo=function(a,b,c,d){this.symbol=a;this.name=b;this.ra1875=c;this.dec1875=d};exports.ConstellationInfo=ConstellationInfo; +function Constellation(a,b){VerifyNumber(a);VerifyNumber(b);if(-90>b||90a&&(a+=24);ConstelRot||(ConstelRot=Rotation_EQJ_EQD(new AstroTime(-45655.74141261017)),Epoch2000=new AstroTime(0));a=new Spherical(b,15*a,1);a=VectorFromSphere(a,Epoch2000);a=RotateVector(ConstelRot,a);a=EquatorFromVector(a);b=10/240;for(var c=b/15,d=$jscomp.makeIterator(ConstelBounds),e=d.next();!e.done;e=d.next()){e=e.value;var f=e[1]*c,g=e[2]*c;if(e[3]*b<=a.dec&& +f<=a.ra&&a.ra=a)throw"Radius of first disc must be positive.";if(0>=b)throw"Radius of second disc must be positive.";if(0>c)throw"Distance between discs is not allowed to be negative.";if(c>=a+b)return 0;if(0==c)return a<=b?1:b*b/(a*a);var d=(a*a-b*b+c*c)/(2*c),e=a*a-d*d;if(0>=e)return a<=b?1:b*b/(a*a);e=Math.sqrt(e);return(a*a*Math.acos(d/a)-d*e+(b*b*Math.acos((c-d)/b)-(c-d)*e))/(Math.PI*a*a)} +function SolarEclipseObscuration(a,b){var c=new Vector(a.x+b.x,a.y+b.y,a.z+b.z,a.t);a=Math.asin(SUN_RADIUS_AU/c.Length());var d=Math.asin(MOON_POLAR_RADIUS_AU/b.Length());b=AngleBetween(b,c);b=Obscuration(a,d,b*exports.DEG2RAD);return Math.min(.9999,b)} +function SearchLunarEclipse(a){a=MakeTime(a);for(var b=0;12>b;++b){var c=SearchMoonPhase(180,a,40);if(!c)throw"Cannot find full moon.";a=MoonEclipticLatitudeDegrees(c);if(1.8>Math.abs(a)&&(a=PeakEarthShadow(c),a.r=n?n+=360:180e.r)throw"Unexpected shadow distance from geoid intersection = "+ +e.r;b=EclipseKindFromUmbra(e.k);a=b===EclipseKind.Total?1:SolarEclipseObscuration(a.dir,f)}else a=void 0;return new GlobalSolarEclipseInfo(b,a,c,d,m,n)}function NextLunarEclipse(a){a=MakeTime(a);a=a.AddDays(10);return SearchLunarEclipse(a)}exports.NextLunarEclipse=NextLunarEclipse; +function SearchGlobalSolarEclipse(a){var b=a=MakeTime(a);for(a=0;12>a;++a){b=SearchMoonPhase(0,b,40);if(!b)throw"Cannot find new moon";var c=MoonEclipticLatitudeDegrees(b);if(1.8>Math.abs(c)&&(c=PeakMoonShadow(b),c.rMath.abs(c)&&(c=PeakLocalMoonShadow(a,b),c.rAngleFromSun(a,d)&&(b=PeakPlanetShadow(a,c,d),b.r=c.lat*e.lat){a.$jscomp$loop$prop$kind$33=e.lat>c.lat?NodeEventKind.Ascending:NodeEventKind.Descending;b=Search(function(f){return function(g){return f.$jscomp$loop$prop$kind$33*EclipticGeoMoon(g).lat}}(a),b,d);if(!b)throw"Could not find moon node.";return new NodeEventInfo(a.$jscomp$loop$prop$kind$33,b)}b= +d;c=e}}exports.SearchMoonNode=SearchMoonNode; +function NextMoonNode(a){var b=a.time.AddDays(MoonNodeStepDays);b=SearchMoonNode(b);switch(a.kind){case NodeEventKind.Ascending:if(b.kind!==NodeEventKind.Descending)throw"Internal error: previous node was ascending, but this node was: "+b.kind;break;case NodeEventKind.Descending:if(b.kind!==NodeEventKind.Ascending)throw"Internal error: previous node was descending, but this node was: "+b.kind;break;default:throw"Previous node has an invalid node kind: "+a.kind;}return b}exports.NextMoonNode=NextMoonNode; +var AxisInfo=function(a,b,c,d){this.ra=a;this.dec=b;this.spin=c;this.north=d};exports.AxisInfo=AxisInfo;function EarthRotationAxis(a){var b=nutation([0,0,1],a,PrecessDirection.Into2000);b=precession(b,a,PrecessDirection.Into2000);b=new Vector(b[0],b[1],b[2],a);var c=EquatorFromVector(b);return new AxisInfo(c.ra,c.dec,190.41375788700253+360.9856122880876*a.ut,b)} +function RotationAxis(a,b){b=MakeTime(b);var c=b.tt,d=c/36525;switch(a){case Body.Sun:a=286.13;var e=63.87;c=84.176+14.1844*c;break;case Body.Mercury:a=281.0103-.0328*d;e=61.4155-.0049*d;c=329.5988+6.1385108*c+.01067257*Math.sin(exports.DEG2RAD*(174.7910857+4.092335*c))-.00112309*Math.sin(exports.DEG2RAD*(349.5821714+8.18467*c))-1.104E-4*Math.sin(exports.DEG2RAD*(164.3732571+12.277005*c))-2.539E-5*Math.sin(exports.DEG2RAD*(339.1643429+16.36934*c))-5.71E-6*Math.sin(exports.DEG2RAD*(153.9554286+20.461675* +c));break;case Body.Venus:a=272.76;e=67.16;c=160.2-1.4813688*c;break;case Body.Earth:return EarthRotationAxis(b);case Body.Moon:var f=exports.DEG2RAD*(125.045-.0529921*c),g=exports.DEG2RAD*(250.089-.1059842*c),k=exports.DEG2RAD*(260.008+13.0120009*c),h=exports.DEG2RAD*(176.625+13.3407154*c),l=exports.DEG2RAD*(357.529+.9856003*c),m=exports.DEG2RAD*(311.589+26.4057084*c),n=exports.DEG2RAD*(134.963+13.064993*c),p=exports.DEG2RAD*(276.617+.3287146*c),r=exports.DEG2RAD*(34.226+1.7484877*c),q=exports.DEG2RAD* +(15.134-.1589763*c),t=exports.DEG2RAD*(119.743+.0036096*c),H=exports.DEG2RAD*(239.961+.1643573*c),F=exports.DEG2RAD*(25.053+12.9590088*c);a=269.9949+.0031*d-3.8787*Math.sin(f)-.1204*Math.sin(g)+.07*Math.sin(k)-.0172*Math.sin(h)+.0072*Math.sin(m)-.0052*Math.sin(q)+.0043*Math.sin(F);e=66.5392+.013*d+1.5419*Math.cos(f)+.0239*Math.cos(g)-.0278*Math.cos(k)+.0068*Math.cos(h)-.0029*Math.cos(m)+9E-4*Math.cos(n)+8E-4*Math.cos(q)-9E-4*Math.cos(F);c=38.3213+(13.17635815-1.4E-12*c)*c+3.561*Math.sin(f)+.1208* +Math.sin(g)-.0642*Math.sin(k)+.0158*Math.sin(h)+.0252*Math.sin(l)-.0066*Math.sin(m)-.0047*Math.sin(n)-.0046*Math.sin(p)+.0028*Math.sin(r)+.0052*Math.sin(q)+.004*Math.sin(t)+.0019*Math.sin(H)-.0044*Math.sin(F);break;case Body.Mars:a=317.269202-.10927547*d+6.8E-5*Math.sin(exports.DEG2RAD*(198.991226+19139.4819985*d))+2.38E-4*Math.sin(exports.DEG2RAD*(226.292679+38280.8511281*d))+5.2E-5*Math.sin(exports.DEG2RAD*(249.663391+57420.7251593*d))+9E-6*Math.sin(exports.DEG2RAD*(266.18351+76560.636795*d))+.419057* +Math.sin(exports.DEG2RAD*(79.398797+.5042615*d));e=54.432516-.05827105*d+5.1E-5*Math.cos(exports.DEG2RAD*(122.433576+19139.9407476*d))+1.41E-4*Math.cos(exports.DEG2RAD*(43.058401+38280.8753272*d))+3.1E-5*Math.cos(exports.DEG2RAD*(57.663379+57420.7517205*d))+5E-6*Math.cos(exports.DEG2RAD*(79.476401+76560.6495004*d))+1.591274*Math.cos(exports.DEG2RAD*(166.325722+.5042615*d));c=176.049863+350.891982443297*c+1.45E-4*Math.sin(exports.DEG2RAD*(129.071773+19140.0328244*d))+1.57E-4*Math.sin(exports.DEG2RAD* +(36.352167+38281.0473591*d))+4E-5*Math.sin(exports.DEG2RAD*(56.668646+57420.929536*d))+1E-6*Math.sin(exports.DEG2RAD*(67.364003+76560.2552215*d))+1E-6*Math.sin(exports.DEG2RAD*(104.79268+95700.4387578*d))+.584542*Math.sin(exports.DEG2RAD*(95.391654+.5042615*d));break;case Body.Jupiter:e=exports.DEG2RAD*(99.360714+4850.4046*d);f=exports.DEG2RAD*(175.895369+1191.9605*d);g=exports.DEG2RAD*(300.323162+262.5475*d);k=exports.DEG2RAD*(114.012305+6070.2476*d);h=exports.DEG2RAD*(49.511251+64.3*d);a=268.056595- +.006499*d+1.17E-4*Math.sin(e)+9.38E-4*Math.sin(f)+.001432*Math.sin(g)+3E-5*Math.sin(k)+.00215*Math.sin(h);e=64.495303+.002413*d+5E-5*Math.cos(e)+4.04E-4*Math.cos(f)+6.17E-4*Math.cos(g)-1.3E-5*Math.cos(k)+9.26E-4*Math.cos(h);c=284.95+870.536*c;break;case Body.Saturn:a=40.589-.036*d;e=83.537-.004*d;c=38.9+810.7939024*c;break;case Body.Uranus:a=257.311;e=-15.175;c=203.81-501.1600928*c;break;case Body.Neptune:d=exports.DEG2RAD*(357.85+52.316*d);a=299.36+.7*Math.sin(d);e=43.46-.51*Math.cos(d);c=249.978+ +541.1397757*c-.48*Math.sin(d);break;case Body.Pluto:a=132.993;e=-6.163;c=302.695+56.3625225*c;break;default:throw"Invalid body: "+a;}d=e*exports.DEG2RAD;f=a*exports.DEG2RAD;g=Math.cos(d);b=new Vector(g*Math.cos(f),g*Math.sin(f),Math.sin(d),b);return new AxisInfo(a/15,e,c,b)}exports.RotationAxis=RotationAxis; +function LagrangePoint(a,b,c,d){var e=MakeTime(b);b=MassProduct(c);var f=MassProduct(d);c===Body.Earth&&d===Body.Moon?(c=new StateVector(0,0,0,0,0,0,e),d=GeoMoonState(e)):(c=HelioState(c,e),d=HelioState(d,e));return LagrangePointFast(a,c,b,d,f)}exports.LagrangePoint=LagrangePoint; +function LagrangePointFast(a,b,c,d,e){if(1>a||5=c)throw"Major mass must be a positive number.";if(!Number.isFinite(e)||0>=e)throw"Minor mass must be a negative number.";var f=d.x-b.x,g=d.y-b.y,k=d.z-b.z,h=f*f+g*g+k*k,l=Math.sqrt(h),m=d.vx-b.vx,n=d.vy-b.vy;d=d.vz-b.vz;if(4===a||5===a){h=g*d-k*n;c=k*m-f*d;var p=f*n-g*m,r=c*k-p*g;p=p*f-h*k;h=h*g-c*f;c=Math.sqrt(r*r+p*p+h*h);r/=c;p/=c;h/=c;f/=l;g/=l;k/=l;a=4==a?.8660254037844386:-.8660254037844386; +c=.5*f+a*r;e=.5*g+a*p;var q=.5*k+a*h,t=m*f+n*g+d*k;m=m*r+n*p+d*h;b=new StateVector(l*c,l*e,l*q,t*c+m*(.5*r-a*f),t*e+m*(.5*p-a*g),t*q+m*(.5*h-a*k),b.t)}else{r=e/(c+e)*-l;p=c/(c+e)*+l;h=(c+e)/(h*l);if(1===a||2===a)q=c/(c+e)*Math.cbrt(e/(3*c)),c=-c,1==a?(q=1-q,a=+e):(q=1+q,a=-e);else if(3===a)q=(7/12*e-c)/(e+c),c=+c,a=+e;else throw"Invalid Langrage point "+a+". Must be an integer 1..5.";e=l*q-r;do q=e-r,t=e-p,q=(h*e+c/(q*q)+a/(t*t))/(h-2*c/(q*q*q)-2*a/(t*t*t)),e-=q;while(1E-14 + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. +*/ +/** + * @fileoverview Astronomy calculation library for browser scripting and Node.js. + * @author Don Cross + * @license MIT + */ +'use strict'; +/** + * @brief The speed of light in AU/day. + */ +export const C_AUDAY = 173.1446326846693; +/** + * @brief The number of kilometers per astronomical unit. + */ +export const KM_PER_AU = 1.4959787069098932e+8; +/** + * @brief The number of astronomical units per light-year. + */ +export const AU_PER_LY = 63241.07708807546; +/** + * @brief The factor to convert degrees to radians = pi/180. + */ +export const DEG2RAD = 0.017453292519943296; +/** + * @brief The factor to convert sidereal hours to radians = pi/12. + */ +export const HOUR2RAD = 0.2617993877991494365; +/** + * @brief The factor to convert radians to degrees = 180/pi. + */ +export const RAD2DEG = 57.295779513082321; +/** + * @brief The factor to convert radians to sidereal hours = 12/pi. + */ +export const RAD2HOUR = 3.819718634205488; +// Jupiter radius data are nominal values obtained from: +// https://www.iau.org/static/resolutions/IAU2015_English.pdf +// https://nssdc.gsfc.nasa.gov/planetary/factsheet/jupiterfact.html +/** + * @brief The equatorial radius of Jupiter, expressed in kilometers. + */ +export const JUPITER_EQUATORIAL_RADIUS_KM = 71492.0; +/** + * @brief The polar radius of Jupiter, expressed in kilometers. + */ +export const JUPITER_POLAR_RADIUS_KM = 66854.0; +/** + * @brief The volumetric mean radius of Jupiter, expressed in kilometers. + */ +export const JUPITER_MEAN_RADIUS_KM = 69911.0; +// The radii of Jupiter's four major moons are obtained from: +// https://ssd.jpl.nasa.gov/?sat_phys_par +/** + * @brief The mean radius of Jupiter's moon Io, expressed in kilometers. + */ +export const IO_RADIUS_KM = 1821.6; +/** + * @brief The mean radius of Jupiter's moon Europa, expressed in kilometers. + */ +export const EUROPA_RADIUS_KM = 1560.8; +/** + * @brief The mean radius of Jupiter's moon Ganymede, expressed in kilometers. + */ +export const GANYMEDE_RADIUS_KM = 2631.2; +/** + * @brief The mean radius of Jupiter's moon Callisto, expressed in kilometers. + */ +export const CALLISTO_RADIUS_KM = 2410.3; +const DAYS_PER_TROPICAL_YEAR = 365.24217; +const J2000 = new Date('2000-01-01T12:00:00Z'); +const PI2 = 2 * Math.PI; +const ARC = 3600 * (180 / Math.PI); // arcseconds per radian +const ASEC2RAD = 4.848136811095359935899141e-6; +const ASEC180 = 180 * 60 * 60; // arcseconds per 180 degrees (or pi radians) +const ASEC360 = 2 * ASEC180; // arcseconds per 360 degrees (or 2*pi radians) +const ANGVEL = 7.2921150e-5; +const AU_PER_PARSEC = ASEC180 / Math.PI; // exact definition of how many AU = one parsec +const SUN_MAG_1AU = -0.17 - 5 * Math.log10(AU_PER_PARSEC); // formula from JPL Horizons +const MEAN_SYNODIC_MONTH = 29.530588; // average number of days for Moon to return to the same phase +const SECONDS_PER_DAY = 24 * 3600; +const MILLIS_PER_DAY = SECONDS_PER_DAY * 1000; +const SOLAR_DAYS_PER_SIDEREAL_DAY = 0.9972695717592592; +const SUN_RADIUS_KM = 695700.0; +const SUN_RADIUS_AU = SUN_RADIUS_KM / KM_PER_AU; +const EARTH_FLATTENING = 0.996647180302104; +const EARTH_FLATTENING_SQUARED = EARTH_FLATTENING * EARTH_FLATTENING; +const EARTH_EQUATORIAL_RADIUS_KM = 6378.1366; +const EARTH_EQUATORIAL_RADIUS_AU = EARTH_EQUATORIAL_RADIUS_KM / KM_PER_AU; +const EARTH_POLAR_RADIUS_KM = EARTH_EQUATORIAL_RADIUS_KM * EARTH_FLATTENING; +const EARTH_MEAN_RADIUS_KM = 6371.0; /* mean radius of the Earth's geoid, without atmosphere */ +const EARTH_ATMOSPHERE_KM = 88.0; /* effective atmosphere thickness for lunar eclipses */ +const EARTH_ECLIPSE_RADIUS_KM = EARTH_MEAN_RADIUS_KM + EARTH_ATMOSPHERE_KM; +const MOON_EQUATORIAL_RADIUS_KM = 1738.1; +const MOON_EQUATORIAL_RADIUS_AU = (MOON_EQUATORIAL_RADIUS_KM / KM_PER_AU); +const MOON_MEAN_RADIUS_KM = 1737.4; +const MOON_POLAR_RADIUS_KM = 1736.0; +const MOON_POLAR_RADIUS_AU = (MOON_POLAR_RADIUS_KM / KM_PER_AU); +const REFRACTION_NEAR_HORIZON = 34 / 60; // degrees of refractive "lift" seen for objects near horizon +const EARTH_MOON_MASS_RATIO = 81.30056; +/* + Masses of the Sun and outer planets, used for: + (1) Calculating the Solar System Barycenter + (2) Integrating the movement of Pluto + + https://web.archive.org/web/20120220062549/http://iau-comm4.jpl.nasa.gov/de405iom/de405iom.pdf + + Page 10 in the above document describes the constants used in the DE405 ephemeris. + The following are G*M values (gravity constant * mass) in [au^3 / day^2]. + This side-steps issues of not knowing the exact values of G and masses M[i]; + the products GM[i] are known extremely accurately. +*/ +const SUN_GM = 0.2959122082855911e-03; +const MERCURY_GM = 0.4912547451450812e-10; +const VENUS_GM = 0.7243452486162703e-09; +const EARTH_GM = 0.8887692390113509e-09; +const MARS_GM = 0.9549535105779258e-10; +const JUPITER_GM = 0.2825345909524226e-06; +const SATURN_GM = 0.8459715185680659e-07; +const URANUS_GM = 0.1292024916781969e-07; +const NEPTUNE_GM = 0.1524358900784276e-07; +const PLUTO_GM = 0.2188699765425970e-11; +const MOON_GM = EARTH_GM / EARTH_MOON_MASS_RATIO; +/** + * @brief Returns the product of mass and universal gravitational constant of a Solar System body. + * + * For problems involving the gravitational interactions of Solar System bodies, + * it is helpful to know the product GM, where G = the universal gravitational constant + * and M = the mass of the body. In practice, GM is known to a higher precision than + * either G or M alone, and thus using the product results in the most accurate results. + * This function returns the product GM in the units au^3/day^2. + * The values come from page 10 of a + * [JPL memorandum regarding the DE405/LE405 ephemeris](https://web.archive.org/web/20120220062549/http://iau-comm4.jpl.nasa.gov/de405iom/de405iom.pdf). + * + * @param {Body} body + * The body for which to find the GM product. + * Allowed to be the Sun, Moon, EMB (Earth/Moon Barycenter), or any planet. + * Any other value will cause an exception to be thrown. + * + * @returns {number} + * The mass product of the given body in au^3/day^2. + */ +export function MassProduct(body) { + switch (body) { + case Body.Sun: return SUN_GM; + case Body.Mercury: return MERCURY_GM; + case Body.Venus: return VENUS_GM; + case Body.Earth: return EARTH_GM; + case Body.Moon: return MOON_GM; + case Body.EMB: return EARTH_GM + MOON_GM; + case Body.Mars: return MARS_GM; + case Body.Jupiter: return JUPITER_GM; + case Body.Saturn: return SATURN_GM; + case Body.Uranus: return URANUS_GM; + case Body.Neptune: return NEPTUNE_GM; + case Body.Pluto: return PLUTO_GM; + default: + throw `Do not know mass product for body: ${body}`; + } +} +function VerifyBoolean(b) { + if (b !== true && b !== false) { + console.trace(); + throw `Value is not boolean: ${b}`; + } + return b; +} +function VerifyNumber(x) { + if (!Number.isFinite(x)) { + console.trace(); + throw `Value is not a finite number: ${x}`; + } + return x; +} +function Frac(x) { + return x - Math.floor(x); +} +/** + * @brief Calculates the angle in degrees between two vectors. + * + * Given a pair of vectors, this function returns the angle in degrees + * between the two vectors in 3D space. + * The angle is measured in the plane that contains both vectors. + * + * @param {Vector} a + * The first of a pair of vectors between which to measure an angle. + * + * @param {Vector} b + * The second of a pair of vectors between which to measure an angle. + * + * @returns {number} + * The angle between the two vectors expressed in degrees. + * The value is in the range [0, 180]. + */ +export function AngleBetween(a, b) { + const aa = (a.x * a.x + a.y * a.y + a.z * a.z); + if (Math.abs(aa) < 1.0e-8) + throw `AngleBetween: first vector is too short.`; + const bb = (b.x * b.x + b.y * b.y + b.z * b.z); + if (Math.abs(bb) < 1.0e-8) + throw `AngleBetween: second vector is too short.`; + const dot = (a.x * b.x + a.y * b.y + a.z * b.z) / Math.sqrt(aa * bb); + if (dot <= -1.0) + return 180; + if (dot >= +1.0) + return 0; + return RAD2DEG * Math.acos(dot); +} +/** + * @brief String constants that represent the solar system bodies supported by Astronomy Engine. + * + * The following strings represent solar system bodies supported by various Astronomy Engine functions. + * Not every body is supported by every function; consult the documentation for each function + * to find which bodies it supports. + * + * "Sun", "Moon", "Mercury", "Venus", "Earth", "Mars", "Jupiter", + * "Saturn", "Uranus", "Neptune", "Pluto", + * "SSB" (Solar System Barycenter), + * "EMB" (Earth/Moon Barycenter) + * + * You can also use enumeration syntax for the bodies, like + * `Astronomy.Body.Moon`, `Astronomy.Body.Jupiter`, etc. + * + * @enum {string} + */ +export var Body; +(function (Body) { + Body["Sun"] = "Sun"; + Body["Moon"] = "Moon"; + Body["Mercury"] = "Mercury"; + Body["Venus"] = "Venus"; + Body["Earth"] = "Earth"; + Body["Mars"] = "Mars"; + Body["Jupiter"] = "Jupiter"; + Body["Saturn"] = "Saturn"; + Body["Uranus"] = "Uranus"; + Body["Neptune"] = "Neptune"; + Body["Pluto"] = "Pluto"; + Body["SSB"] = "SSB"; + Body["EMB"] = "EMB"; + // User-defined fixed locations in the sky... + Body["Star1"] = "Star1"; + Body["Star2"] = "Star2"; + Body["Star3"] = "Star3"; + Body["Star4"] = "Star4"; + Body["Star5"] = "Star5"; + Body["Star6"] = "Star6"; + Body["Star7"] = "Star7"; + Body["Star8"] = "Star8"; +})(Body || (Body = {})); +const StarList = [ + Body.Star1, Body.Star2, Body.Star3, Body.Star4, + Body.Star5, Body.Star6, Body.Star7, Body.Star8 +]; +; +const StarTable = [ + { ra: 0, dec: 0, dist: 0 }, + { ra: 0, dec: 0, dist: 0 }, + { ra: 0, dec: 0, dist: 0 }, + { ra: 0, dec: 0, dist: 0 }, + { ra: 0, dec: 0, dist: 0 }, + { ra: 0, dec: 0, dist: 0 }, + { ra: 0, dec: 0, dist: 0 }, + { ra: 0, dec: 0, dist: 0 }, +]; +function GetStar(body) { + const index = StarList.indexOf(body); + return (index >= 0) ? StarTable[index] : null; +} +function UserDefinedStar(body) { + const star = GetStar(body); + return (star && star.dist > 0) ? star : null; +} +/** + * @brief Assign equatorial coordinates to a user-defined star. + * + * Some Astronomy Engine functions allow their `body` parameter to + * be a user-defined fixed point in the sky, loosely called a "star". + * This function assigns a right ascension, declination, and distance + * to one of the eight user-defined stars `Star1`..`Star8`. + * + * Stars are not valid until defined. Once defined, they retain their + * definition until re-defined by another call to `DefineStar`. + * + * @param {Body} body + * One of the eight user-defined star identifiers: + * `Star1`, `Star2`, `Star3`, `Star4`, `Star5`, `Star6`, `Star7`, or `Star8`. + * + * @param {number} ra + * The right ascension to be assigned to the star, expressed in J2000 equatorial coordinates (EQJ). + * The value is in units of sidereal hours, and must be within the half-open range [0, 24). + * + * @param {number} dec + * The declination to be assigned to the star, expressed in J2000 equatorial coordinates (EQJ). + * The value is in units of degrees north (positive) or south (negative) of the J2000 equator, + * and must be within the closed range [-90, +90]. + * + * @param {number} distanceLightYears + * The distance between the star and the Sun, expressed in light-years. + * This value is used to calculate the tiny parallax shift as seen by an observer on Earth. + * If you don't know the distance to the star, using a large value like 1000 will generally work well. + * The minimum allowed distance is 1 light-year, which is required to provide certain internal optimizations. + */ +export function DefineStar(body, ra, dec, distanceLightYears) { + const star = GetStar(body); + if (!star) + throw `Invalid star body: ${body}`; + VerifyNumber(ra); + VerifyNumber(dec); + VerifyNumber(distanceLightYears); + if (ra < 0 || ra >= 24) + throw `Invalid right ascension for star: ${ra}`; + if (dec < -90 || dec > +90) + throw `Invalid declination for star: ${dec}`; + if (distanceLightYears < 1) + throw `Invalid star distance: ${distanceLightYears}`; + star.ra = ra; + star.dec = dec; + star.dist = distanceLightYears * AU_PER_LY; +} +var PrecessDirection; +(function (PrecessDirection) { + PrecessDirection[PrecessDirection["From2000"] = 0] = "From2000"; + PrecessDirection[PrecessDirection["Into2000"] = 1] = "Into2000"; +})(PrecessDirection || (PrecessDirection = {})); +const Planet = { + Mercury: { OrbitalPeriod: 87.969 }, + Venus: { OrbitalPeriod: 224.701 }, + Earth: { OrbitalPeriod: 365.256 }, + Mars: { OrbitalPeriod: 686.980 }, + Jupiter: { OrbitalPeriod: 4332.589 }, + Saturn: { OrbitalPeriod: 10759.22 }, + Uranus: { OrbitalPeriod: 30685.4 }, + Neptune: { OrbitalPeriod: 60189.0 }, + Pluto: { OrbitalPeriod: 90560.0 } +}; +/** + * @brief Returns the mean orbital period of a planet in days. + * + * @param {Body} body + * One of: Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, or Pluto. + * + * @returns {number} + * The approximate average time it takes for the planet to travel once around the Sun. + * The value is expressed in days. + */ +export function PlanetOrbitalPeriod(body) { + if (body in Planet) + return Planet[body].OrbitalPeriod; + throw `Unknown orbital period for: ${body}`; +} +const vsop = { + Mercury: [ + [ + [ + [4.40250710144, 0.00000000000, 0.00000000000], + [0.40989414977, 1.48302034195, 26087.90314157420], + [0.05046294200, 4.47785489551, 52175.80628314840], + [0.00855346844, 1.16520322459, 78263.70942472259], + [0.00165590362, 4.11969163423, 104351.61256629678], + [0.00034561897, 0.77930768443, 130439.51570787099], + [0.00007583476, 3.71348404924, 156527.41884944518] + ], + [ + [26087.90313685529, 0.00000000000, 0.00000000000], + [0.01131199811, 6.21874197797, 26087.90314157420], + [0.00292242298, 3.04449355541, 52175.80628314840], + [0.00075775081, 6.08568821653, 78263.70942472259], + [0.00019676525, 2.80965111777, 104351.61256629678] + ] + ], + [ + [ + [0.11737528961, 1.98357498767, 26087.90314157420], + [0.02388076996, 5.03738959686, 52175.80628314840], + [0.01222839532, 3.14159265359, 0.00000000000], + [0.00543251810, 1.79644363964, 78263.70942472259], + [0.00129778770, 4.83232503958, 104351.61256629678], + [0.00031866927, 1.58088495658, 130439.51570787099], + [0.00007963301, 4.60972126127, 156527.41884944518] + ], + [ + [0.00274646065, 3.95008450011, 26087.90314157420], + [0.00099737713, 3.14159265359, 0.00000000000] + ] + ], + [ + [ + [0.39528271651, 0.00000000000, 0.00000000000], + [0.07834131818, 6.19233722598, 26087.90314157420], + [0.00795525558, 2.95989690104, 52175.80628314840], + [0.00121281764, 6.01064153797, 78263.70942472259], + [0.00021921969, 2.77820093972, 104351.61256629678], + [0.00004354065, 5.82894543774, 130439.51570787099] + ], + [ + [0.00217347740, 4.65617158665, 26087.90314157420], + [0.00044141826, 1.42385544001, 52175.80628314840] + ] + ] + ], + Venus: [ + [ + [ + [3.17614666774, 0.00000000000, 0.00000000000], + [0.01353968419, 5.59313319619, 10213.28554621100], + [0.00089891645, 5.30650047764, 20426.57109242200], + [0.00005477194, 4.41630661466, 7860.41939243920], + [0.00003455741, 2.69964447820, 11790.62908865880], + [0.00002372061, 2.99377542079, 3930.20969621960], + [0.00001317168, 5.18668228402, 26.29831979980], + [0.00001664146, 4.25018630147, 1577.34354244780], + [0.00001438387, 4.15745084182, 9683.59458111640], + [0.00001200521, 6.15357116043, 30639.85663863300] + ], + [ + [10213.28554621638, 0.00000000000, 0.00000000000], + [0.00095617813, 2.46406511110, 10213.28554621100], + [0.00007787201, 0.62478482220, 20426.57109242200] + ] + ], + [ + [ + [0.05923638472, 0.26702775812, 10213.28554621100], + [0.00040107978, 1.14737178112, 20426.57109242200], + [0.00032814918, 3.14159265359, 0.00000000000] + ], + [ + [0.00287821243, 1.88964962838, 10213.28554621100] + ] + ], + [ + [ + [0.72334820891, 0.00000000000, 0.00000000000], + [0.00489824182, 4.02151831717, 10213.28554621100], + [0.00001658058, 4.90206728031, 20426.57109242200], + [0.00001378043, 1.12846591367, 11790.62908865880], + [0.00001632096, 2.84548795207, 7860.41939243920], + [0.00000498395, 2.58682193892, 9683.59458111640], + [0.00000221985, 2.01346696541, 19367.18916223280], + [0.00000237454, 2.55136053886, 15720.83878487840] + ], + [ + [0.00034551041, 0.89198706276, 10213.28554621100] + ] + ] + ], + Earth: [ + [ + [ + [1.75347045673, 0.00000000000, 0.00000000000], + [0.03341656453, 4.66925680415, 6283.07584999140], + [0.00034894275, 4.62610242189, 12566.15169998280], + [0.00003417572, 2.82886579754, 3.52311834900], + [0.00003497056, 2.74411783405, 5753.38488489680], + [0.00003135899, 3.62767041756, 77713.77146812050], + [0.00002676218, 4.41808345438, 7860.41939243920], + [0.00002342691, 6.13516214446, 3930.20969621960], + [0.00001273165, 2.03709657878, 529.69096509460], + [0.00001324294, 0.74246341673, 11506.76976979360], + [0.00000901854, 2.04505446477, 26.29831979980], + [0.00001199167, 1.10962946234, 1577.34354244780], + [0.00000857223, 3.50849152283, 398.14900340820], + [0.00000779786, 1.17882681962, 5223.69391980220], + [0.00000990250, 5.23268072088, 5884.92684658320], + [0.00000753141, 2.53339052847, 5507.55323866740], + [0.00000505267, 4.58292599973, 18849.22754997420], + [0.00000492392, 4.20505711826, 775.52261132400], + [0.00000356672, 2.91954114478, 0.06731030280], + [0.00000284125, 1.89869240932, 796.29800681640], + [0.00000242879, 0.34481445893, 5486.77784317500], + [0.00000317087, 5.84901948512, 11790.62908865880], + [0.00000271112, 0.31486255375, 10977.07880469900], + [0.00000206217, 4.80646631478, 2544.31441988340], + [0.00000205478, 1.86953770281, 5573.14280143310], + [0.00000202318, 2.45767790232, 6069.77675455340], + [0.00000126225, 1.08295459501, 20.77539549240], + [0.00000155516, 0.83306084617, 213.29909543800] + ], + [ + [6283.07584999140, 0.00000000000, 0.00000000000], + [0.00206058863, 2.67823455808, 6283.07584999140], + [0.00004303419, 2.63512233481, 12566.15169998280] + ], + [ + [0.00008721859, 1.07253635559, 6283.07584999140] + ] + ], + [ + [], + [ + [0.00227777722, 3.41376620530, 6283.07584999140], + [0.00003805678, 3.37063423795, 12566.15169998280] + ] + ], + [ + [ + [1.00013988784, 0.00000000000, 0.00000000000], + [0.01670699632, 3.09846350258, 6283.07584999140], + [0.00013956024, 3.05524609456, 12566.15169998280], + [0.00003083720, 5.19846674381, 77713.77146812050], + [0.00001628463, 1.17387558054, 5753.38488489680], + [0.00001575572, 2.84685214877, 7860.41939243920], + [0.00000924799, 5.45292236722, 11506.76976979360], + [0.00000542439, 4.56409151453, 3930.20969621960], + [0.00000472110, 3.66100022149, 5884.92684658320], + [0.00000085831, 1.27079125277, 161000.68573767410], + [0.00000057056, 2.01374292245, 83996.84731811189], + [0.00000055736, 5.24159799170, 71430.69561812909], + [0.00000174844, 3.01193636733, 18849.22754997420], + [0.00000243181, 4.27349530790, 11790.62908865880] + ], + [ + [0.00103018607, 1.10748968172, 6283.07584999140], + [0.00001721238, 1.06442300386, 12566.15169998280] + ], + [ + [0.00004359385, 5.78455133808, 6283.07584999140] + ] + ] + ], + Mars: [ + [ + [ + [6.20347711581, 0.00000000000, 0.00000000000], + [0.18656368093, 5.05037100270, 3340.61242669980], + [0.01108216816, 5.40099836344, 6681.22485339960], + [0.00091798406, 5.75478744667, 10021.83728009940], + [0.00027744987, 5.97049513147, 3.52311834900], + [0.00010610235, 2.93958560338, 2281.23049651060], + [0.00012315897, 0.84956094002, 2810.92146160520], + [0.00008926784, 4.15697846427, 0.01725365220], + [0.00008715691, 6.11005153139, 13362.44970679920], + [0.00006797556, 0.36462229657, 398.14900340820], + [0.00007774872, 3.33968761376, 5621.84292321040], + [0.00003575078, 1.66186505710, 2544.31441988340], + [0.00004161108, 0.22814971327, 2942.46342329160], + [0.00003075252, 0.85696614132, 191.44826611160], + [0.00002628117, 0.64806124465, 3337.08930835080], + [0.00002937546, 6.07893711402, 0.06731030280], + [0.00002389414, 5.03896442664, 796.29800681640], + [0.00002579844, 0.02996736156, 3344.13554504880], + [0.00001528141, 1.14979301996, 6151.53388830500], + [0.00001798806, 0.65634057445, 529.69096509460], + [0.00001264357, 3.62275122593, 5092.15195811580], + [0.00001286228, 3.06796065034, 2146.16541647520], + [0.00001546404, 2.91579701718, 1751.53953141600], + [0.00001024902, 3.69334099279, 8962.45534991020], + [0.00000891566, 0.18293837498, 16703.06213349900], + [0.00000858759, 2.40093811940, 2914.01423582380], + [0.00000832715, 2.46418619474, 3340.59517304760], + [0.00000832720, 4.49495782139, 3340.62968035200], + [0.00000712902, 3.66335473479, 1059.38193018920], + [0.00000748723, 3.82248614017, 155.42039943420], + [0.00000723861, 0.67497311481, 3738.76143010800], + [0.00000635548, 2.92182225127, 8432.76438481560], + [0.00000655162, 0.48864064125, 3127.31333126180], + [0.00000550474, 3.81001042328, 0.98032106820], + [0.00000552750, 4.47479317037, 1748.01641306700], + [0.00000425966, 0.55364317304, 6283.07584999140], + [0.00000415131, 0.49662285038, 213.29909543800], + [0.00000472167, 3.62547124025, 1194.44701022460], + [0.00000306551, 0.38052848348, 6684.74797174860], + [0.00000312141, 0.99853944405, 6677.70173505060], + [0.00000293198, 4.22131299634, 20.77539549240], + [0.00000302375, 4.48618007156, 3532.06069281140], + [0.00000274027, 0.54222167059, 3340.54511639700], + [0.00000281079, 5.88163521788, 1349.86740965880], + [0.00000231183, 1.28242156993, 3870.30339179440], + [0.00000283602, 5.76885434940, 3149.16416058820], + [0.00000236117, 5.75503217933, 3333.49887969900], + [0.00000274033, 0.13372524985, 3340.67973700260], + [0.00000299395, 2.78323740866, 6254.62666252360] + ], + [ + [3340.61242700512, 0.00000000000, 0.00000000000], + [0.01457554523, 3.60433733236, 3340.61242669980], + [0.00168414711, 3.92318567804, 6681.22485339960], + [0.00020622975, 4.26108844583, 10021.83728009940], + [0.00003452392, 4.73210393190, 3.52311834900], + [0.00002586332, 4.60670058555, 13362.44970679920], + [0.00000841535, 4.45864030426, 2281.23049651060] + ], + [ + [0.00058152577, 2.04961712429, 3340.61242669980], + [0.00013459579, 2.45738706163, 6681.22485339960] + ] + ], + [ + [ + [0.03197134986, 3.76832042431, 3340.61242669980], + [0.00298033234, 4.10616996305, 6681.22485339960], + [0.00289104742, 0.00000000000, 0.00000000000], + [0.00031365539, 4.44651053090, 10021.83728009940], + [0.00003484100, 4.78812549260, 13362.44970679920] + ], + [ + [0.00217310991, 6.04472194776, 3340.61242669980], + [0.00020976948, 3.14159265359, 0.00000000000], + [0.00012834709, 1.60810667915, 6681.22485339960] + ] + ], + [ + [ + [1.53033488271, 0.00000000000, 0.00000000000], + [0.14184953160, 3.47971283528, 3340.61242669980], + [0.00660776362, 3.81783443019, 6681.22485339960], + [0.00046179117, 4.15595316782, 10021.83728009940], + [0.00008109733, 5.55958416318, 2810.92146160520], + [0.00007485318, 1.77239078402, 5621.84292321040], + [0.00005523191, 1.36436303770, 2281.23049651060], + [0.00003825160, 4.49407183687, 13362.44970679920], + [0.00002306537, 0.09081579001, 2544.31441988340], + [0.00001999396, 5.36059617709, 3337.08930835080], + [0.00002484394, 4.92545639920, 2942.46342329160], + [0.00001960195, 4.74249437639, 3344.13554504880], + [0.00001167119, 2.11260868341, 5092.15195811580], + [0.00001102816, 5.00908403998, 398.14900340820], + [0.00000899066, 4.40791133207, 529.69096509460], + [0.00000992252, 5.83861961952, 6151.53388830500], + [0.00000807354, 2.10217065501, 1059.38193018920], + [0.00000797915, 3.44839203899, 796.29800681640], + [0.00000740975, 1.49906336885, 2146.16541647520] + ], + [ + [0.01107433345, 2.03250524857, 3340.61242669980], + [0.00103175887, 2.37071847807, 6681.22485339960], + [0.00012877200, 0.00000000000, 0.00000000000], + [0.00010815880, 2.70888095665, 10021.83728009940] + ], + [ + [0.00044242249, 0.47930604954, 3340.61242669980], + [0.00008138042, 0.86998389204, 6681.22485339960] + ] + ] + ], + Jupiter: [ + [ + [ + [0.59954691494, 0.00000000000, 0.00000000000], + [0.09695898719, 5.06191793158, 529.69096509460], + [0.00573610142, 1.44406205629, 7.11354700080], + [0.00306389205, 5.41734730184, 1059.38193018920], + [0.00097178296, 4.14264726552, 632.78373931320], + [0.00072903078, 3.64042916389, 522.57741809380], + [0.00064263975, 3.41145165351, 103.09277421860], + [0.00039806064, 2.29376740788, 419.48464387520], + [0.00038857767, 1.27231755835, 316.39186965660], + [0.00027964629, 1.78454591820, 536.80451209540], + [0.00013589730, 5.77481040790, 1589.07289528380], + [0.00008246349, 3.58227925840, 206.18554843720], + [0.00008768704, 3.63000308199, 949.17560896980], + [0.00007368042, 5.08101194270, 735.87651353180], + [0.00006263150, 0.02497628807, 213.29909543800], + [0.00006114062, 4.51319998626, 1162.47470440780], + [0.00004905396, 1.32084470588, 110.20632121940], + [0.00005305285, 1.30671216791, 14.22709400160], + [0.00005305441, 4.18625634012, 1052.26838318840], + [0.00004647248, 4.69958103684, 3.93215326310], + [0.00003045023, 4.31676431084, 426.59819087600], + [0.00002609999, 1.56667394063, 846.08283475120], + [0.00002028191, 1.06376530715, 3.18139373770], + [0.00001764763, 2.14148655117, 1066.49547719000], + [0.00001722972, 3.88036268267, 1265.56747862640], + [0.00001920945, 0.97168196472, 639.89728631400], + [0.00001633223, 3.58201833555, 515.46387109300], + [0.00001431999, 4.29685556046, 625.67019231240], + [0.00000973272, 4.09764549134, 95.97922721780] + ], + [ + [529.69096508814, 0.00000000000, 0.00000000000], + [0.00489503243, 4.22082939470, 529.69096509460], + [0.00228917222, 6.02646855621, 7.11354700080], + [0.00030099479, 4.54540782858, 1059.38193018920], + [0.00020720920, 5.45943156902, 522.57741809380], + [0.00012103653, 0.16994816098, 536.80451209540], + [0.00006067987, 4.42422292017, 103.09277421860], + [0.00005433968, 3.98480737746, 419.48464387520], + [0.00004237744, 5.89008707199, 14.22709400160] + ], + [ + [0.00047233601, 4.32148536482, 7.11354700080], + [0.00030649436, 2.92977788700, 529.69096509460], + [0.00014837605, 3.14159265359, 0.00000000000] + ] + ], + [ + [ + [0.02268615702, 3.55852606721, 529.69096509460], + [0.00109971634, 3.90809347197, 1059.38193018920], + [0.00110090358, 0.00000000000, 0.00000000000], + [0.00008101428, 3.60509572885, 522.57741809380], + [0.00006043996, 4.25883108339, 1589.07289528380], + [0.00006437782, 0.30627119215, 536.80451209540] + ], + [ + [0.00078203446, 1.52377859742, 529.69096509460] + ] + ], + [ + [ + [5.20887429326, 0.00000000000, 0.00000000000], + [0.25209327119, 3.49108639871, 529.69096509460], + [0.00610599976, 3.84115365948, 1059.38193018920], + [0.00282029458, 2.57419881293, 632.78373931320], + [0.00187647346, 2.07590383214, 522.57741809380], + [0.00086792905, 0.71001145545, 419.48464387520], + [0.00072062974, 0.21465724607, 536.80451209540], + [0.00065517248, 5.97995884790, 316.39186965660], + [0.00029134542, 1.67759379655, 103.09277421860], + [0.00030135335, 2.16132003734, 949.17560896980], + [0.00023453271, 3.54023522184, 735.87651353180], + [0.00022283743, 4.19362594399, 1589.07289528380], + [0.00023947298, 0.27458037480, 7.11354700080], + [0.00013032614, 2.96042965363, 1162.47470440780], + [0.00009703360, 1.90669633585, 206.18554843720], + [0.00012749023, 2.71550286592, 1052.26838318840], + [0.00007057931, 2.18184839926, 1265.56747862640], + [0.00006137703, 6.26418240033, 846.08283475120], + [0.00002616976, 2.00994012876, 1581.95934828300] + ], + [ + [0.01271801520, 2.64937512894, 529.69096509460], + [0.00061661816, 3.00076460387, 1059.38193018920], + [0.00053443713, 3.89717383175, 522.57741809380], + [0.00031185171, 4.88276958012, 536.80451209540], + [0.00041390269, 0.00000000000, 0.00000000000] + ] + ] + ], + Saturn: [ + [ + [ + [0.87401354025, 0.00000000000, 0.00000000000], + [0.11107659762, 3.96205090159, 213.29909543800], + [0.01414150957, 4.58581516874, 7.11354700080], + [0.00398379389, 0.52112032699, 206.18554843720], + [0.00350769243, 3.30329907896, 426.59819087600], + [0.00206816305, 0.24658372002, 103.09277421860], + [0.00079271300, 3.84007056878, 220.41264243880], + [0.00023990355, 4.66976924553, 110.20632121940], + [0.00016573588, 0.43719228296, 419.48464387520], + [0.00014906995, 5.76903183869, 316.39186965660], + [0.00015820290, 0.93809155235, 632.78373931320], + [0.00014609559, 1.56518472000, 3.93215326310], + [0.00013160301, 4.44891291899, 14.22709400160], + [0.00015053543, 2.71669915667, 639.89728631400], + [0.00013005299, 5.98119023644, 11.04570026390], + [0.00010725067, 3.12939523827, 202.25339517410], + [0.00005863206, 0.23656938524, 529.69096509460], + [0.00005227757, 4.20783365759, 3.18139373770], + [0.00006126317, 1.76328667907, 277.03499374140], + [0.00005019687, 3.17787728405, 433.71173787680], + [0.00004592550, 0.61977744975, 199.07200143640], + [0.00004005867, 2.24479718502, 63.73589830340], + [0.00002953796, 0.98280366998, 95.97922721780], + [0.00003873670, 3.22283226966, 138.51749687070], + [0.00002461186, 2.03163875071, 735.87651353180], + [0.00003269484, 0.77492638211, 949.17560896980], + [0.00001758145, 3.26580109940, 522.57741809380], + [0.00001640172, 5.50504453050, 846.08283475120], + [0.00001391327, 4.02333150505, 323.50541665740], + [0.00001580648, 4.37265307169, 309.27832265580], + [0.00001123498, 2.83726798446, 415.55249061210], + [0.00001017275, 3.71700135395, 227.52618943960], + [0.00000848642, 3.19150170830, 209.36694217490] + ], + [ + [213.29909521690, 0.00000000000, 0.00000000000], + [0.01297370862, 1.82834923978, 213.29909543800], + [0.00564345393, 2.88499717272, 7.11354700080], + [0.00093734369, 1.06311793502, 426.59819087600], + [0.00107674962, 2.27769131009, 206.18554843720], + [0.00040244455, 2.04108104671, 220.41264243880], + [0.00019941774, 1.27954390470, 103.09277421860], + [0.00010511678, 2.74880342130, 14.22709400160], + [0.00006416106, 0.38238295041, 639.89728631400], + [0.00004848994, 2.43037610229, 419.48464387520], + [0.00004056892, 2.92133209468, 110.20632121940], + [0.00003768635, 3.64965330780, 3.93215326310] + ], + [ + [0.00116441330, 1.17988132879, 7.11354700080], + [0.00091841837, 0.07325195840, 213.29909543800], + [0.00036661728, 0.00000000000, 0.00000000000], + [0.00015274496, 4.06493179167, 206.18554843720] + ] + ], + [ + [ + [0.04330678039, 3.60284428399, 213.29909543800], + [0.00240348302, 2.85238489373, 426.59819087600], + [0.00084745939, 0.00000000000, 0.00000000000], + [0.00030863357, 3.48441504555, 220.41264243880], + [0.00034116062, 0.57297307557, 206.18554843720], + [0.00014734070, 2.11846596715, 639.89728631400], + [0.00009916667, 5.79003188904, 419.48464387520], + [0.00006993564, 4.73604689720, 7.11354700080], + [0.00004807588, 5.43305312061, 316.39186965660] + ], + [ + [0.00198927992, 4.93901017903, 213.29909543800], + [0.00036947916, 3.14159265359, 0.00000000000], + [0.00017966989, 0.51979431110, 426.59819087600] + ] + ], + [ + [ + [9.55758135486, 0.00000000000, 0.00000000000], + [0.52921382865, 2.39226219573, 213.29909543800], + [0.01873679867, 5.23549604660, 206.18554843720], + [0.01464663929, 1.64763042902, 426.59819087600], + [0.00821891141, 5.93520042303, 316.39186965660], + [0.00547506923, 5.01532618980, 103.09277421860], + [0.00371684650, 2.27114821115, 220.41264243880], + [0.00361778765, 3.13904301847, 7.11354700080], + [0.00140617506, 5.70406606781, 632.78373931320], + [0.00108974848, 3.29313390175, 110.20632121940], + [0.00069006962, 5.94099540992, 419.48464387520], + [0.00061053367, 0.94037691801, 639.89728631400], + [0.00048913294, 1.55733638681, 202.25339517410], + [0.00034143772, 0.19519102597, 277.03499374140], + [0.00032401773, 5.47084567016, 949.17560896980], + [0.00020936596, 0.46349251129, 735.87651353180], + [0.00009796004, 5.20477537945, 1265.56747862640], + [0.00011993338, 5.98050967385, 846.08283475120], + [0.00020839300, 1.52102476129, 433.71173787680], + [0.00015298404, 3.05943814940, 529.69096509460], + [0.00006465823, 0.17732249942, 1052.26838318840], + [0.00011380257, 1.73105427040, 522.57741809380], + [0.00003419618, 4.94550542171, 1581.95934828300] + ], + [ + [0.06182981340, 0.25843511480, 213.29909543800], + [0.00506577242, 0.71114625261, 206.18554843720], + [0.00341394029, 5.79635741658, 426.59819087600], + [0.00188491195, 0.47215589652, 220.41264243880], + [0.00186261486, 3.14159265359, 0.00000000000], + [0.00143891146, 1.40744822888, 7.11354700080] + ], + [ + [0.00436902572, 4.78671677509, 213.29909543800] + ] + ] + ], + Uranus: [ + [ + [ + [5.48129294297, 0.00000000000, 0.00000000000], + [0.09260408234, 0.89106421507, 74.78159856730], + [0.01504247898, 3.62719260920, 1.48447270830], + [0.00365981674, 1.89962179044, 73.29712585900], + [0.00272328168, 3.35823706307, 149.56319713460], + [0.00070328461, 5.39254450063, 63.73589830340], + [0.00068892678, 6.09292483287, 76.26607127560], + [0.00061998615, 2.26952066061, 2.96894541660], + [0.00061950719, 2.85098872691, 11.04570026390], + [0.00026468770, 3.14152083966, 71.81265315070], + [0.00025710476, 6.11379840493, 454.90936652730], + [0.00021078850, 4.36059339067, 148.07872442630], + [0.00017818647, 1.74436930289, 36.64856292950], + [0.00014613507, 4.73732166022, 3.93215326310], + [0.00011162509, 5.82681796350, 224.34479570190], + [0.00010997910, 0.48865004018, 138.51749687070], + [0.00009527478, 2.95516862826, 35.16409022120], + [0.00007545601, 5.23626582400, 109.94568878850], + [0.00004220241, 3.23328220918, 70.84944530420], + [0.00004051900, 2.27755017300, 151.04766984290], + [0.00003354596, 1.06549007380, 4.45341812490], + [0.00002926718, 4.62903718891, 9.56122755560], + [0.00003490340, 5.48306144511, 146.59425171800], + [0.00003144069, 4.75199570434, 77.75054398390], + [0.00002922333, 5.35235361027, 85.82729883120], + [0.00002272788, 4.36600400036, 70.32818044240], + [0.00002051219, 1.51773566586, 0.11187458460], + [0.00002148602, 0.60745949945, 38.13303563780], + [0.00001991643, 4.92437588682, 277.03499374140], + [0.00001376226, 2.04283539351, 65.22037101170], + [0.00001666902, 3.62744066769, 380.12776796000], + [0.00001284107, 3.11347961505, 202.25339517410], + [0.00001150429, 0.93343589092, 3.18139373770], + [0.00001533221, 2.58594681212, 52.69019803950], + [0.00001281604, 0.54271272721, 222.86032299360], + [0.00001372139, 4.19641530878, 111.43016149680], + [0.00001221029, 0.19900650030, 108.46121608020], + [0.00000946181, 1.19253165736, 127.47179660680], + [0.00001150989, 4.17898916639, 33.67961751290] + ], + [ + [74.78159860910, 0.00000000000, 0.00000000000], + [0.00154332863, 5.24158770553, 74.78159856730], + [0.00024456474, 1.71260334156, 1.48447270830], + [0.00009258442, 0.42829732350, 11.04570026390], + [0.00008265977, 1.50218091379, 63.73589830340], + [0.00009150160, 1.41213765216, 149.56319713460] + ] + ], + [ + [ + [0.01346277648, 2.61877810547, 74.78159856730], + [0.00062341400, 5.08111189648, 149.56319713460], + [0.00061601196, 3.14159265359, 0.00000000000], + [0.00009963722, 1.61603805646, 76.26607127560], + [0.00009926160, 0.57630380333, 73.29712585900] + ], + [ + [0.00034101978, 0.01321929936, 74.78159856730] + ] + ], + [ + [ + [19.21264847206, 0.00000000000, 0.00000000000], + [0.88784984413, 5.60377527014, 74.78159856730], + [0.03440836062, 0.32836099706, 73.29712585900], + [0.02055653860, 1.78295159330, 149.56319713460], + [0.00649322410, 4.52247285911, 76.26607127560], + [0.00602247865, 3.86003823674, 63.73589830340], + [0.00496404167, 1.40139935333, 454.90936652730], + [0.00338525369, 1.58002770318, 138.51749687070], + [0.00243509114, 1.57086606044, 71.81265315070], + [0.00190522303, 1.99809394714, 1.48447270830], + [0.00161858838, 2.79137786799, 148.07872442630], + [0.00143706183, 1.38368544947, 11.04570026390], + [0.00093192405, 0.17437220467, 36.64856292950], + [0.00071424548, 4.24509236074, 224.34479570190], + [0.00089806014, 3.66105364565, 109.94568878850], + [0.00039009723, 1.66971401684, 70.84944530420], + [0.00046677296, 1.39976401694, 35.16409022120], + [0.00039025624, 3.36234773834, 277.03499374140], + [0.00036755274, 3.88649278513, 146.59425171800], + [0.00030348723, 0.70100838798, 151.04766984290], + [0.00029156413, 3.18056336700, 77.75054398390], + [0.00022637073, 0.72518687029, 529.69096509460], + [0.00011959076, 1.75043392140, 984.60033162190], + [0.00025620756, 5.25656086672, 380.12776796000] + ], + [ + [0.01479896629, 3.67205697578, 74.78159856730] + ] + ] + ], + Neptune: [ + [ + [ + [5.31188633046, 0.00000000000, 0.00000000000], + [0.01798475530, 2.90101273890, 38.13303563780], + [0.01019727652, 0.48580922867, 1.48447270830], + [0.00124531845, 4.83008090676, 36.64856292950], + [0.00042064466, 5.41054993053, 2.96894541660], + [0.00037714584, 6.09221808686, 35.16409022120], + [0.00033784738, 1.24488874087, 76.26607127560], + [0.00016482741, 0.00007727998, 491.55792945680], + [0.00009198584, 4.93747051954, 39.61750834610], + [0.00008994250, 0.27462171806, 175.16605980020] + ], + [ + [38.13303563957, 0.00000000000, 0.00000000000], + [0.00016604172, 4.86323329249, 1.48447270830], + [0.00015744045, 2.27887427527, 38.13303563780] + ] + ], + [ + [ + [0.03088622933, 1.44104372644, 38.13303563780], + [0.00027780087, 5.91271884599, 76.26607127560], + [0.00027623609, 0.00000000000, 0.00000000000], + [0.00015355489, 2.52123799551, 36.64856292950], + [0.00015448133, 3.50877079215, 39.61750834610] + ] + ], + [ + [ + [30.07013205828, 0.00000000000, 0.00000000000], + [0.27062259632, 1.32999459377, 38.13303563780], + [0.01691764014, 3.25186135653, 36.64856292950], + [0.00807830553, 5.18592878704, 1.48447270830], + [0.00537760510, 4.52113935896, 35.16409022120], + [0.00495725141, 1.57105641650, 491.55792945680], + [0.00274571975, 1.84552258866, 175.16605980020], + [0.00012012320, 1.92059384991, 1021.24889455140], + [0.00121801746, 5.79754470298, 76.26607127560], + [0.00100896068, 0.37702724930, 73.29712585900], + [0.00135134092, 3.37220609835, 39.61750834610], + [0.00007571796, 1.07149207335, 388.46515523820] + ] + ] + ] +}; +export function DeltaT_EspenakMeeus(ut) { + var u, u2, u3, u4, u5, u6, u7; + /* + Fred Espenak writes about Delta-T generically here: + https://eclipse.gsfc.nasa.gov/SEhelp/deltaT.html + https://eclipse.gsfc.nasa.gov/SEhelp/deltat2004.html + + He provides polynomial approximations for distant years here: + https://eclipse.gsfc.nasa.gov/SEhelp/deltatpoly2004.html + + They start with a year value 'y' such that y=2000 corresponds + to the UTC Date 15-January-2000. Convert difference in days + to mean tropical years. + */ + const y = 2000 + ((ut - 14) / DAYS_PER_TROPICAL_YEAR); + if (y < -500) { + u = (y - 1820) / 100; + return -20 + (32 * u * u); + } + if (y < 500) { + u = y / 100; + u2 = u * u; + u3 = u * u2; + u4 = u2 * u2; + u5 = u2 * u3; + u6 = u3 * u3; + return 10583.6 - 1014.41 * u + 33.78311 * u2 - 5.952053 * u3 - 0.1798452 * u4 + 0.022174192 * u5 + 0.0090316521 * u6; + } + if (y < 1600) { + u = (y - 1000) / 100; + u2 = u * u; + u3 = u * u2; + u4 = u2 * u2; + u5 = u2 * u3; + u6 = u3 * u3; + return 1574.2 - 556.01 * u + 71.23472 * u2 + 0.319781 * u3 - 0.8503463 * u4 - 0.005050998 * u5 + 0.0083572073 * u6; + } + if (y < 1700) { + u = y - 1600; + u2 = u * u; + u3 = u * u2; + return 120 - 0.9808 * u - 0.01532 * u2 + u3 / 7129.0; + } + if (y < 1800) { + u = y - 1700; + u2 = u * u; + u3 = u * u2; + u4 = u2 * u2; + return 8.83 + 0.1603 * u - 0.0059285 * u2 + 0.00013336 * u3 - u4 / 1174000; + } + if (y < 1860) { + u = y - 1800; + u2 = u * u; + u3 = u * u2; + u4 = u2 * u2; + u5 = u2 * u3; + u6 = u3 * u3; + u7 = u3 * u4; + return 13.72 - 0.332447 * u + 0.0068612 * u2 + 0.0041116 * u3 - 0.00037436 * u4 + 0.0000121272 * u5 - 0.0000001699 * u6 + 0.000000000875 * u7; + } + if (y < 1900) { + u = y - 1860; + u2 = u * u; + u3 = u * u2; + u4 = u2 * u2; + u5 = u2 * u3; + return 7.62 + 0.5737 * u - 0.251754 * u2 + 0.01680668 * u3 - 0.0004473624 * u4 + u5 / 233174; + } + if (y < 1920) { + u = y - 1900; + u2 = u * u; + u3 = u * u2; + u4 = u2 * u2; + return -2.79 + 1.494119 * u - 0.0598939 * u2 + 0.0061966 * u3 - 0.000197 * u4; + } + if (y < 1941) { + u = y - 1920; + u2 = u * u; + u3 = u * u2; + return 21.20 + 0.84493 * u - 0.076100 * u2 + 0.0020936 * u3; + } + if (y < 1961) { + u = y - 1950; + u2 = u * u; + u3 = u * u2; + return 29.07 + 0.407 * u - u2 / 233 + u3 / 2547; + } + if (y < 1986) { + u = y - 1975; + u2 = u * u; + u3 = u * u2; + return 45.45 + 1.067 * u - u2 / 260 - u3 / 718; + } + if (y < 2005) { + u = y - 2000; + u2 = u * u; + u3 = u * u2; + u4 = u2 * u2; + u5 = u2 * u3; + return 63.86 + 0.3345 * u - 0.060374 * u2 + 0.0017275 * u3 + 0.000651814 * u4 + 0.00002373599 * u5; + } + if (y < 2050) { + u = y - 2000; + return 62.92 + 0.32217 * u + 0.005589 * u * u; + } + if (y < 2150) { + u = (y - 1820) / 100; + return -20 + 32 * u * u - 0.5628 * (2150 - y); + } + /* all years after 2150 */ + u = (y - 1820) / 100; + return -20 + (32 * u * u); +} +export function DeltaT_JplHorizons(ut) { + return DeltaT_EspenakMeeus(Math.min(ut, 17.0 * DAYS_PER_TROPICAL_YEAR)); +} +let DeltaT = DeltaT_EspenakMeeus; +export function SetDeltaTFunction(func) { + DeltaT = func; +} +/** + * @ignore + * + * @brief Calculates Terrestrial Time (TT) from Universal Time (UT). + * + * @param {number} ut + * The Universal Time expressed as a floating point number of days since the 2000.0 epoch. + * + * @returns {number} + * A Terrestrial Time expressed as a floating point number of days since the 2000.0 epoch. + */ +function TerrestrialTime(ut) { + return ut + DeltaT(ut) / 86400; +} +/** + * @brief The date and time of an astronomical observation. + * + * Objects of type `AstroTime` are used throughout the internals + * of the Astronomy library, and are included in certain return objects. + * Use the constructor or the {@link MakeTime} function to create an `AstroTime` object. + * + * @property {Date} date + * The JavaScript Date object for the given date and time. + * This Date corresponds to the numeric day value stored in the `ut` property. + * + * @property {number} ut + * Universal Time (UT1/UTC) in fractional days since the J2000 epoch. + * Universal Time represents time measured with respect to the Earth's rotation, + * tracking mean solar days. + * The Astronomy library approximates UT1 and UTC as being the same thing. + * This gives sufficient accuracy for the precision requirements of this project. + * + * @property {number} tt + * Terrestrial Time in fractional days since the J2000 epoch. + * TT represents a continuously flowing ephemeris timescale independent of + * any variations of the Earth's rotation, and is adjusted from UT + * using a best-fit piecewise polynomial model devised by + * [Espenak and Meeus](https://eclipse.gsfc.nasa.gov/SEhelp/deltatpoly2004.html). + */ +export class AstroTime { + /** + * @param {FlexibleDateTime} date + * A JavaScript Date object, a numeric UTC value expressed in J2000 days, or another AstroTime object. + */ + constructor(date) { + if (date instanceof AstroTime) { + // Construct a clone of the AstroTime passed in. + this.date = date.date; + this.ut = date.ut; + this.tt = date.tt; + return; + } + const MillisPerDay = 1000 * 3600 * 24; + if ((date instanceof Date) && Number.isFinite(date.getTime())) { + this.date = date; + this.ut = (date.getTime() - J2000.getTime()) / MillisPerDay; + this.tt = TerrestrialTime(this.ut); + return; + } + if (Number.isFinite(date)) { + this.date = new Date(J2000.getTime() + date * MillisPerDay); + this.ut = date; + this.tt = TerrestrialTime(this.ut); + return; + } + throw 'Argument must be a Date object, an AstroTime object, or a numeric UTC Julian date.'; + } + /** + * @brief Creates an `AstroTime` value from a Terrestrial Time (TT) day value. + * + * This function can be used in rare cases where a time must be based + * on Terrestrial Time (TT) rather than Universal Time (UT). + * Most developers will want to invoke `new AstroTime(ut)` with a universal time + * instead of this function, because usually time is based on civil time adjusted + * by leap seconds to match the Earth's rotation, rather than the uniformly + * flowing TT used to calculate solar system dynamics. In rare cases + * where the caller already knows TT, this function is provided to create + * an `AstroTime` value that can be passed to Astronomy Engine functions. + * + * @param {number} tt + * The number of days since the J2000 epoch as expressed in Terrestrial Time. + * + * @returns {AstroTime} + * An `AstroTime` object for the specified terrestrial time. + */ + static FromTerrestrialTime(tt) { + let time = new AstroTime(tt); + for (;;) { + const err = tt - time.tt; + if (Math.abs(err) < 1.0e-12) + return time; + time = time.AddDays(err); + } + } + /** + * Formats an `AstroTime` object as an [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) + * date/time string in UTC, to millisecond resolution. + * Example: `2018-08-17T17:22:04.050Z` + * @returns {string} + */ + toString() { + return this.date.toISOString(); + } + /** + * Returns a new `AstroTime` object adjusted by the floating point number of days. + * Does NOT modify the original `AstroTime` object. + * + * @param {number} days + * The floating point number of days by which to adjust the given date and time. + * Positive values adjust the date toward the future, and + * negative values adjust the date toward the past. + * + * @returns {AstroTime} + */ + AddDays(days) { + // This is slightly wrong, but the error is tiny. + // We really should be adding to TT, not to UT. + // But using TT would require creating an inverse function for DeltaT, + // which would be quite a bit of extra calculation. + // I estimate the error is in practice on the order of 10^(-7) + // times the value of 'days'. + // This is based on a typical drift of 1 second per year between UT and TT. + return new AstroTime(this.ut + days); + } +} +function InterpolateTime(time1, time2, fraction) { + return new AstroTime(time1.ut + fraction * (time2.ut - time1.ut)); +} +/** + * @brief A `Date`, `number`, or `AstroTime` value that specifies the date and time of an astronomical event. + * + * `FlexibleDateTime` is a placeholder type that represents three different types + * that may be passed to many Astronomy Engine functions: a JavaScript `Date` object, + * a number representing the real-valued number of UT days since the J2000 epoch, + * or an {@link AstroTime} object. + * + * This flexibility is for convenience of outside callers. + * Internally, Astronomy Engine always converts a `FlexibleDateTime` parameter + * to an `AstroTime` object by calling {@link MakeTime}. + * + * @typedef {Date | number | AstroTime} FlexibleDateTime + */ +/** + * @brief Converts multiple date/time formats to `AstroTime` format. + * + * Given a Date object or a number days since noon (12:00) on January 1, 2000 (UTC), + * this function creates an {@link AstroTime} object. + * + * Given an {@link AstroTime} object, returns the same object unmodified. + * Use of this function is not required for any of the other exposed functions in this library, + * because they all guarantee converting date/time parameters to `AstroTime` + * as needed. However, it may be convenient for callers who need to understand + * the difference between UTC and TT (Terrestrial Time). In some use cases, + * converting once to `AstroTime` format and passing the result into multiple + * function calls may be more efficient than passing in native JavaScript Date objects. + * + * @param {FlexibleDateTime} date + * A Date object, a number of UTC days since the J2000 epoch (noon on January 1, 2000), + * or an AstroTime object. See remarks above. + * + * @returns {AstroTime} + */ +export function MakeTime(date) { + if (date instanceof AstroTime) { + return date; + } + return new AstroTime(date); +} +function iau2000b(time) { + function mod(x) { + return (x % ASEC360) * ASEC2RAD; + } + const t = time.tt / 36525; + const elp = mod(1287104.79305 + t * 129596581.0481); + const f = mod(335779.526232 + t * 1739527262.8478); + const d = mod(1072260.70369 + t * 1602961601.2090); + const om = mod(450160.398036 - t * 6962890.5431); + let sarg = Math.sin(om); + let carg = Math.cos(om); + let dp = (-172064161.0 - 174666.0 * t) * sarg + 33386.0 * carg; + let de = (92052331.0 + 9086.0 * t) * carg + 15377.0 * sarg; + let arg = 2.0 * (f - d + om); + sarg = Math.sin(arg); + carg = Math.cos(arg); + dp += (-13170906.0 - 1675.0 * t) * sarg - 13696.0 * carg; + de += (5730336.0 - 3015.0 * t) * carg - 4587.0 * sarg; + arg = 2.0 * (f + om); + sarg = Math.sin(arg); + carg = Math.cos(arg); + dp += (-2276413.0 - 234.0 * t) * sarg + 2796.0 * carg; + de += (978459.0 - 485.0 * t) * carg + 1374.0 * sarg; + arg = 2.0 * om; + sarg = Math.sin(arg); + carg = Math.cos(arg); + dp += (2074554.0 + 207.0 * t) * sarg - 698.0 * carg; + de += (-897492.0 + 470.0 * t) * carg - 291.0 * sarg; + sarg = Math.sin(elp); + carg = Math.cos(elp); + dp += (1475877.0 - 3633.0 * t) * sarg + 11817.0 * carg; + de += (73871.0 - 184.0 * t) * carg - 1924.0 * sarg; + return { + dpsi: -0.000135 + (dp * 1.0e-7), + deps: +0.000388 + (de * 1.0e-7) + }; +} +function mean_obliq(time) { + var t = time.tt / 36525; + var asec = (((((-0.0000000434 * t + - 0.000000576) * t + + 0.00200340) * t + - 0.0001831) * t + - 46.836769) * t + 84381.406); + return asec / 3600.0; +} +var cache_e_tilt; +export function e_tilt(time) { + if (!cache_e_tilt || Math.abs(cache_e_tilt.tt - time.tt) > 1.0e-6) { + const nut = iau2000b(time); + const mean_ob = mean_obliq(time); + const true_ob = mean_ob + (nut.deps / 3600); + cache_e_tilt = { + tt: time.tt, + dpsi: nut.dpsi, + deps: nut.deps, + ee: nut.dpsi * Math.cos(mean_ob * DEG2RAD) / 15, + mobl: mean_ob, + tobl: true_ob + }; + } + return cache_e_tilt; +} +function obl_ecl2equ_vec(oblDegrees, pos) { + const obl = oblDegrees * DEG2RAD; + const cos_obl = Math.cos(obl); + const sin_obl = Math.sin(obl); + return [ + pos[0], + pos[1] * cos_obl - pos[2] * sin_obl, + pos[1] * sin_obl + pos[2] * cos_obl + ]; +} +function ecl2equ_vec(time, pos) { + return obl_ecl2equ_vec(mean_obliq(time), pos); +} +export let CalcMoonCount = 0; +function CalcMoon(time) { + ++CalcMoonCount; + const T = time.tt / 36525; + function DeclareArray1(xmin, xmax) { + const array = []; + let i; + for (i = 0; i <= xmax - xmin; ++i) { + array.push(0); + } + return { min: xmin, array: array }; + } + function DeclareArray2(xmin, xmax, ymin, ymax) { + const array = []; + for (let i = 0; i <= xmax - xmin; ++i) { + array.push(DeclareArray1(ymin, ymax)); + } + return { min: xmin, array: array }; + } + function ArrayGet2(a, x, y) { + const m = a.array[x - a.min]; + return m.array[y - m.min]; + } + function ArraySet2(a, x, y, v) { + const m = a.array[x - a.min]; + m.array[y - m.min] = v; + } + let S, MAX, ARG, FAC, I, J, T2, DGAM, DLAM, N, GAM1C, SINPI, L0, L, LS, F, D, DL0, DL, DLS, DF, DD, DS; + let coArray = DeclareArray2(-6, 6, 1, 4); + let siArray = DeclareArray2(-6, 6, 1, 4); + function CO(x, y) { + return ArrayGet2(coArray, x, y); + } + function SI(x, y) { + return ArrayGet2(siArray, x, y); + } + function SetCO(x, y, v) { + return ArraySet2(coArray, x, y, v); + } + function SetSI(x, y, v) { + return ArraySet2(siArray, x, y, v); + } + function AddThe(c1, s1, c2, s2, func) { + func(c1 * c2 - s1 * s2, s1 * c2 + c1 * s2); + } + function Sine(phi) { + return Math.sin(PI2 * phi); + } + T2 = T * T; + DLAM = 0; + DS = 0; + GAM1C = 0; + SINPI = 3422.7000; + var S1 = Sine(0.19833 + 0.05611 * T); + var S2 = Sine(0.27869 + 0.04508 * T); + var S3 = Sine(0.16827 - 0.36903 * T); + var S4 = Sine(0.34734 - 5.37261 * T); + var S5 = Sine(0.10498 - 5.37899 * T); + var S6 = Sine(0.42681 - 0.41855 * T); + var S7 = Sine(0.14943 - 5.37511 * T); + DL0 = 0.84 * S1 + 0.31 * S2 + 14.27 * S3 + 7.26 * S4 + 0.28 * S5 + 0.24 * S6; + DL = 2.94 * S1 + 0.31 * S2 + 14.27 * S3 + 9.34 * S4 + 1.12 * S5 + 0.83 * S6; + DLS = -6.40 * S1 - 1.89 * S6; + DF = 0.21 * S1 + 0.31 * S2 + 14.27 * S3 - 88.70 * S4 - 15.30 * S5 + 0.24 * S6 - 1.86 * S7; + DD = DL0 - DLS; + DGAM = (-3332E-9 * Sine(0.59734 - 5.37261 * T) + - 539E-9 * Sine(0.35498 - 5.37899 * T) + - 64E-9 * Sine(0.39943 - 5.37511 * T)); + L0 = PI2 * Frac(0.60643382 + 1336.85522467 * T - 0.00000313 * T2) + DL0 / ARC; + L = PI2 * Frac(0.37489701 + 1325.55240982 * T + 0.00002565 * T2) + DL / ARC; + LS = PI2 * Frac(0.99312619 + 99.99735956 * T - 0.00000044 * T2) + DLS / ARC; + F = PI2 * Frac(0.25909118 + 1342.22782980 * T - 0.00000892 * T2) + DF / ARC; + D = PI2 * Frac(0.82736186 + 1236.85308708 * T - 0.00000397 * T2) + DD / ARC; + for (I = 1; I <= 4; ++I) { + switch (I) { + case 1: + ARG = L; + MAX = 4; + FAC = 1.000002208; + break; + case 2: + ARG = LS; + MAX = 3; + FAC = 0.997504612 - 0.002495388 * T; + break; + case 3: + ARG = F; + MAX = 4; + FAC = 1.000002708 + 139.978 * DGAM; + break; + case 4: + ARG = D; + MAX = 6; + FAC = 1.0; + break; + default: throw `Internal error: I = ${I}`; // persuade TypeScript that ARG, ... are all initialized before use. + } + SetCO(0, I, 1); + SetCO(1, I, Math.cos(ARG) * FAC); + SetSI(0, I, 0); + SetSI(1, I, Math.sin(ARG) * FAC); + for (J = 2; J <= MAX; ++J) { + AddThe(CO(J - 1, I), SI(J - 1, I), CO(1, I), SI(1, I), (c, s) => (SetCO(J, I, c), SetSI(J, I, s))); + } + for (J = 1; J <= MAX; ++J) { + SetCO(-J, I, CO(J, I)); + SetSI(-J, I, -SI(J, I)); + } + } + function Term(p, q, r, s) { + var result = { x: 1, y: 0 }; + var I = [0, p, q, r, s]; // I[0] is not used; it is a placeholder + for (var k = 1; k <= 4; ++k) + if (I[k] !== 0) + AddThe(result.x, result.y, CO(I[k], k), SI(I[k], k), (c, s) => (result.x = c, result.y = s)); + return result; + } + function AddSol(coeffl, coeffs, coeffg, coeffp, p, q, r, s) { + var result = Term(p, q, r, s); + DLAM += coeffl * result.y; + DS += coeffs * result.y; + GAM1C += coeffg * result.x; + SINPI += coeffp * result.x; + } + AddSol(13.9020, 14.0600, -0.0010, 0.2607, 0, 0, 0, 4); + AddSol(0.4030, -4.0100, 0.3940, 0.0023, 0, 0, 0, 3); + AddSol(2369.9120, 2373.3600, 0.6010, 28.2333, 0, 0, 0, 2); + AddSol(-125.1540, -112.7900, -0.7250, -0.9781, 0, 0, 0, 1); + AddSol(1.9790, 6.9800, -0.4450, 0.0433, 1, 0, 0, 4); + AddSol(191.9530, 192.7200, 0.0290, 3.0861, 1, 0, 0, 2); + AddSol(-8.4660, -13.5100, 0.4550, -0.1093, 1, 0, 0, 1); + AddSol(22639.5000, 22609.0700, 0.0790, 186.5398, 1, 0, 0, 0); + AddSol(18.6090, 3.5900, -0.0940, 0.0118, 1, 0, 0, -1); + AddSol(-4586.4650, -4578.1300, -0.0770, 34.3117, 1, 0, 0, -2); + AddSol(3.2150, 5.4400, 0.1920, -0.0386, 1, 0, 0, -3); + AddSol(-38.4280, -38.6400, 0.0010, 0.6008, 1, 0, 0, -4); + AddSol(-0.3930, -1.4300, -0.0920, 0.0086, 1, 0, 0, -6); + AddSol(-0.2890, -1.5900, 0.1230, -0.0053, 0, 1, 0, 4); + AddSol(-24.4200, -25.1000, 0.0400, -0.3000, 0, 1, 0, 2); + AddSol(18.0230, 17.9300, 0.0070, 0.1494, 0, 1, 0, 1); + AddSol(-668.1460, -126.9800, -1.3020, -0.3997, 0, 1, 0, 0); + AddSol(0.5600, 0.3200, -0.0010, -0.0037, 0, 1, 0, -1); + AddSol(-165.1450, -165.0600, 0.0540, 1.9178, 0, 1, 0, -2); + AddSol(-1.8770, -6.4600, -0.4160, 0.0339, 0, 1, 0, -4); + AddSol(0.2130, 1.0200, -0.0740, 0.0054, 2, 0, 0, 4); + AddSol(14.3870, 14.7800, -0.0170, 0.2833, 2, 0, 0, 2); + AddSol(-0.5860, -1.2000, 0.0540, -0.0100, 2, 0, 0, 1); + AddSol(769.0160, 767.9600, 0.1070, 10.1657, 2, 0, 0, 0); + AddSol(1.7500, 2.0100, -0.0180, 0.0155, 2, 0, 0, -1); + AddSol(-211.6560, -152.5300, 5.6790, -0.3039, 2, 0, 0, -2); + AddSol(1.2250, 0.9100, -0.0300, -0.0088, 2, 0, 0, -3); + AddSol(-30.7730, -34.0700, -0.3080, 0.3722, 2, 0, 0, -4); + AddSol(-0.5700, -1.4000, -0.0740, 0.0109, 2, 0, 0, -6); + AddSol(-2.9210, -11.7500, 0.7870, -0.0484, 1, 1, 0, 2); + AddSol(1.2670, 1.5200, -0.0220, 0.0164, 1, 1, 0, 1); + AddSol(-109.6730, -115.1800, 0.4610, -0.9490, 1, 1, 0, 0); + AddSol(-205.9620, -182.3600, 2.0560, 1.4437, 1, 1, 0, -2); + AddSol(0.2330, 0.3600, 0.0120, -0.0025, 1, 1, 0, -3); + AddSol(-4.3910, -9.6600, -0.4710, 0.0673, 1, 1, 0, -4); + AddSol(0.2830, 1.5300, -0.1110, 0.0060, 1, -1, 0, 4); + AddSol(14.5770, 31.7000, -1.5400, 0.2302, 1, -1, 0, 2); + AddSol(147.6870, 138.7600, 0.6790, 1.1528, 1, -1, 0, 0); + AddSol(-1.0890, 0.5500, 0.0210, 0.0000, 1, -1, 0, -1); + AddSol(28.4750, 23.5900, -0.4430, -0.2257, 1, -1, 0, -2); + AddSol(-0.2760, -0.3800, -0.0060, -0.0036, 1, -1, 0, -3); + AddSol(0.6360, 2.2700, 0.1460, -0.0102, 1, -1, 0, -4); + AddSol(-0.1890, -1.6800, 0.1310, -0.0028, 0, 2, 0, 2); + AddSol(-7.4860, -0.6600, -0.0370, -0.0086, 0, 2, 0, 0); + AddSol(-8.0960, -16.3500, -0.7400, 0.0918, 0, 2, 0, -2); + AddSol(-5.7410, -0.0400, 0.0000, -0.0009, 0, 0, 2, 2); + AddSol(0.2550, 0.0000, 0.0000, 0.0000, 0, 0, 2, 1); + AddSol(-411.6080, -0.2000, 0.0000, -0.0124, 0, 0, 2, 0); + AddSol(0.5840, 0.8400, 0.0000, 0.0071, 0, 0, 2, -1); + AddSol(-55.1730, -52.1400, 0.0000, -0.1052, 0, 0, 2, -2); + AddSol(0.2540, 0.2500, 0.0000, -0.0017, 0, 0, 2, -3); + AddSol(0.0250, -1.6700, 0.0000, 0.0031, 0, 0, 2, -4); + AddSol(1.0600, 2.9600, -0.1660, 0.0243, 3, 0, 0, 2); + AddSol(36.1240, 50.6400, -1.3000, 0.6215, 3, 0, 0, 0); + AddSol(-13.1930, -16.4000, 0.2580, -0.1187, 3, 0, 0, -2); + AddSol(-1.1870, -0.7400, 0.0420, 0.0074, 3, 0, 0, -4); + AddSol(-0.2930, -0.3100, -0.0020, 0.0046, 3, 0, 0, -6); + AddSol(-0.2900, -1.4500, 0.1160, -0.0051, 2, 1, 0, 2); + AddSol(-7.6490, -10.5600, 0.2590, -0.1038, 2, 1, 0, 0); + AddSol(-8.6270, -7.5900, 0.0780, -0.0192, 2, 1, 0, -2); + AddSol(-2.7400, -2.5400, 0.0220, 0.0324, 2, 1, 0, -4); + AddSol(1.1810, 3.3200, -0.2120, 0.0213, 2, -1, 0, 2); + AddSol(9.7030, 11.6700, -0.1510, 0.1268, 2, -1, 0, 0); + AddSol(-0.3520, -0.3700, 0.0010, -0.0028, 2, -1, 0, -1); + AddSol(-2.4940, -1.1700, -0.0030, -0.0017, 2, -1, 0, -2); + AddSol(0.3600, 0.2000, -0.0120, -0.0043, 2, -1, 0, -4); + AddSol(-1.1670, -1.2500, 0.0080, -0.0106, 1, 2, 0, 0); + AddSol(-7.4120, -6.1200, 0.1170, 0.0484, 1, 2, 0, -2); + AddSol(-0.3110, -0.6500, -0.0320, 0.0044, 1, 2, 0, -4); + AddSol(0.7570, 1.8200, -0.1050, 0.0112, 1, -2, 0, 2); + AddSol(2.5800, 2.3200, 0.0270, 0.0196, 1, -2, 0, 0); + AddSol(2.5330, 2.4000, -0.0140, -0.0212, 1, -2, 0, -2); + AddSol(-0.3440, -0.5700, -0.0250, 0.0036, 0, 3, 0, -2); + AddSol(-0.9920, -0.0200, 0.0000, 0.0000, 1, 0, 2, 2); + AddSol(-45.0990, -0.0200, 0.0000, -0.0010, 1, 0, 2, 0); + AddSol(-0.1790, -9.5200, 0.0000, -0.0833, 1, 0, 2, -2); + AddSol(-0.3010, -0.3300, 0.0000, 0.0014, 1, 0, 2, -4); + AddSol(-6.3820, -3.3700, 0.0000, -0.0481, 1, 0, -2, 2); + AddSol(39.5280, 85.1300, 0.0000, -0.7136, 1, 0, -2, 0); + AddSol(9.3660, 0.7100, 0.0000, -0.0112, 1, 0, -2, -2); + AddSol(0.2020, 0.0200, 0.0000, 0.0000, 1, 0, -2, -4); + AddSol(0.4150, 0.1000, 0.0000, 0.0013, 0, 1, 2, 0); + AddSol(-2.1520, -2.2600, 0.0000, -0.0066, 0, 1, 2, -2); + AddSol(-1.4400, -1.3000, 0.0000, 0.0014, 0, 1, -2, 2); + AddSol(0.3840, -0.0400, 0.0000, 0.0000, 0, 1, -2, -2); + AddSol(1.9380, 3.6000, -0.1450, 0.0401, 4, 0, 0, 0); + AddSol(-0.9520, -1.5800, 0.0520, -0.0130, 4, 0, 0, -2); + AddSol(-0.5510, -0.9400, 0.0320, -0.0097, 3, 1, 0, 0); + AddSol(-0.4820, -0.5700, 0.0050, -0.0045, 3, 1, 0, -2); + AddSol(0.6810, 0.9600, -0.0260, 0.0115, 3, -1, 0, 0); + AddSol(-0.2970, -0.2700, 0.0020, -0.0009, 2, 2, 0, -2); + AddSol(0.2540, 0.2100, -0.0030, 0.0000, 2, -2, 0, -2); + AddSol(-0.2500, -0.2200, 0.0040, 0.0014, 1, 3, 0, -2); + AddSol(-3.9960, 0.0000, 0.0000, 0.0004, 2, 0, 2, 0); + AddSol(0.5570, -0.7500, 0.0000, -0.0090, 2, 0, 2, -2); + AddSol(-0.4590, -0.3800, 0.0000, -0.0053, 2, 0, -2, 2); + AddSol(-1.2980, 0.7400, 0.0000, 0.0004, 2, 0, -2, 0); + AddSol(0.5380, 1.1400, 0.0000, -0.0141, 2, 0, -2, -2); + AddSol(0.2630, 0.0200, 0.0000, 0.0000, 1, 1, 2, 0); + AddSol(0.4260, 0.0700, 0.0000, -0.0006, 1, 1, -2, -2); + AddSol(-0.3040, 0.0300, 0.0000, 0.0003, 1, -1, 2, 0); + AddSol(-0.3720, -0.1900, 0.0000, -0.0027, 1, -1, -2, 2); + AddSol(0.4180, 0.0000, 0.0000, 0.0000, 0, 0, 4, 0); + AddSol(-0.3300, -0.0400, 0.0000, 0.0000, 3, 0, 2, 0); + function ADDN(coeffn, p, q, r, s) { + return coeffn * Term(p, q, r, s).y; + } + N = 0; + N += ADDN(-526.069, 0, 0, 1, -2); + N += ADDN(-3.352, 0, 0, 1, -4); + N += ADDN(+44.297, +1, 0, 1, -2); + N += ADDN(-6.000, +1, 0, 1, -4); + N += ADDN(+20.599, -1, 0, 1, 0); + N += ADDN(-30.598, -1, 0, 1, -2); + N += ADDN(-24.649, -2, 0, 1, 0); + N += ADDN(-2.000, -2, 0, 1, -2); + N += ADDN(-22.571, 0, +1, 1, -2); + N += ADDN(+10.985, 0, -1, 1, -2); + DLAM += (+0.82 * Sine(0.7736 - 62.5512 * T) + 0.31 * Sine(0.0466 - 125.1025 * T) + + 0.35 * Sine(0.5785 - 25.1042 * T) + 0.66 * Sine(0.4591 + 1335.8075 * T) + + 0.64 * Sine(0.3130 - 91.5680 * T) + 1.14 * Sine(0.1480 + 1331.2898 * T) + + 0.21 * Sine(0.5918 + 1056.5859 * T) + 0.44 * Sine(0.5784 + 1322.8595 * T) + + 0.24 * Sine(0.2275 - 5.7374 * T) + 0.28 * Sine(0.2965 + 2.6929 * T) + + 0.33 * Sine(0.3132 + 6.3368 * T)); + S = F + DS / ARC; + let lat_seconds = (1.000002708 + 139.978 * DGAM) * (18518.511 + 1.189 + GAM1C) * Math.sin(S) - 6.24 * Math.sin(3 * S) + N; + return { + geo_eclip_lon: PI2 * Frac((L0 + DLAM / ARC) / PI2), + geo_eclip_lat: (Math.PI / (180 * 3600)) * lat_seconds, + distance_au: (ARC * EARTH_EQUATORIAL_RADIUS_AU) / (0.999953253 * SINPI) + }; +} +/** + * @brief Lunar libration angles, returned by {@link Libration}. + * + * @property {number} elat + * Sub-Earth libration ecliptic latitude angle, in degrees. + * @property {number} elon + * Sub-Earth libration ecliptic longitude angle, in degrees. + * @property {number} mlat + * Moon's geocentric ecliptic latitude, in degrees. + * @property {number} mlon + * Moon's geocentric ecliptic longitude, in degrees. + * @property {number} dist_km + * Distance between the centers of the Earth and Moon in kilometers. + * @property {number} diam_deg + * The apparent angular diameter of the Moon, in degrees, as seen from the center of the Earth. + */ +export class LibrationInfo { + constructor(elat, elon, mlat, mlon, dist_km, diam_deg) { + this.elat = elat; + this.elon = elon; + this.mlat = mlat; + this.mlon = mlon; + this.dist_km = dist_km; + this.diam_deg = diam_deg; + } +} +/** + * @brief Calculates the Moon's libration angles at a given moment in time. + * + * Libration is an observed back-and-forth wobble of the portion of the + * Moon visible from the Earth. It is caused by the imperfect tidal locking + * of the Moon's fixed rotation rate, compared to its variable angular speed + * of orbit around the Earth. + * + * This function calculates a pair of perpendicular libration angles, + * one representing rotation of the Moon in ecliptic longitude `elon`, the other + * in ecliptic latitude `elat`, both relative to the Moon's mean Earth-facing position. + * + * This function also returns the geocentric position of the Moon + * expressed in ecliptic longitude `mlon`, ecliptic latitude `mlat`, the + * distance `dist_km` between the centers of the Earth and Moon expressed in kilometers, + * and the apparent angular diameter of the Moon `diam_deg`. + * + * @param {FlexibleDateTime} date + * A Date object, a number of UTC days since the J2000 epoch (noon on January 1, 2000), + * or an AstroTime object. + * + * @returns {LibrationInfo} + */ +export function Libration(date) { + const time = MakeTime(date); + const t = time.tt / 36525.0; + const t2 = t * t; + const t3 = t2 * t; + const t4 = t2 * t2; + const moon = CalcMoon(time); + const mlon = moon.geo_eclip_lon; + const mlat = moon.geo_eclip_lat; + const dist_km = moon.distance_au * KM_PER_AU; + // Inclination angle + const I = DEG2RAD * 1.543; + // Moon's argument of latitude in radians. + const f = DEG2RAD * NormalizeLongitude(93.2720950 + 483202.0175233 * t - 0.0036539 * t2 - t3 / 3526000 + t4 / 863310000); + // Moon's ascending node's mean longitude in radians. + const omega = DEG2RAD * NormalizeLongitude(125.0445479 - 1934.1362891 * t + 0.0020754 * t2 + t3 / 467441 - t4 / 60616000); + // Sun's mean anomaly. + const m = DEG2RAD * NormalizeLongitude(357.5291092 + 35999.0502909 * t - 0.0001536 * t2 + t3 / 24490000); + // Moon's mean anomaly. + const mdash = DEG2RAD * NormalizeLongitude(134.9633964 + 477198.8675055 * t + 0.0087414 * t2 + t3 / 69699 - t4 / 14712000); + // Moon's mean elongation. + const d = DEG2RAD * NormalizeLongitude(297.8501921 + 445267.1114034 * t - 0.0018819 * t2 + t3 / 545868 - t4 / 113065000); + // Eccentricity of the Earth's orbit. + const e = 1.0 - 0.002516 * t - 0.0000074 * t2; + // Optical librations + const w = mlon - omega; + const a = Math.atan2(Math.sin(w) * Math.cos(mlat) * Math.cos(I) - Math.sin(mlat) * Math.sin(I), Math.cos(w) * Math.cos(mlat)); + const ldash = LongitudeOffset(RAD2DEG * (a - f)); + const bdash = Math.asin(-Math.sin(w) * Math.cos(mlat) * Math.sin(I) - Math.sin(mlat) * Math.cos(I)); + // Physical librations + const k1 = DEG2RAD * (119.75 + 131.849 * t); + const k2 = DEG2RAD * (72.56 + 20.186 * t); + const rho = (-0.02752 * Math.cos(mdash) + + -0.02245 * Math.sin(f) + + +0.00684 * Math.cos(mdash - 2 * f) + + -0.00293 * Math.cos(2 * f) + + -0.00085 * Math.cos(2 * f - 2 * d) + + -0.00054 * Math.cos(mdash - 2 * d) + + -0.00020 * Math.sin(mdash + f) + + -0.00020 * Math.cos(mdash + 2 * f) + + -0.00020 * Math.cos(mdash - f) + + +0.00014 * Math.cos(mdash + 2 * f - 2 * d)); + const sigma = (-0.02816 * Math.sin(mdash) + + +0.02244 * Math.cos(f) + + -0.00682 * Math.sin(mdash - 2 * f) + + -0.00279 * Math.sin(2 * f) + + -0.00083 * Math.sin(2 * f - 2 * d) + + +0.00069 * Math.sin(mdash - 2 * d) + + +0.00040 * Math.cos(mdash + f) + + -0.00025 * Math.sin(2 * mdash) + + -0.00023 * Math.sin(mdash + 2 * f) + + +0.00020 * Math.cos(mdash - f) + + +0.00019 * Math.sin(mdash - f) + + +0.00013 * Math.sin(mdash + 2 * f - 2 * d) + + -0.00010 * Math.cos(mdash - 3 * f)); + const tau = (+0.02520 * e * Math.sin(m) + + +0.00473 * Math.sin(2 * mdash - 2 * f) + + -0.00467 * Math.sin(mdash) + + +0.00396 * Math.sin(k1) + + +0.00276 * Math.sin(2 * mdash - 2 * d) + + +0.00196 * Math.sin(omega) + + -0.00183 * Math.cos(mdash - f) + + +0.00115 * Math.sin(mdash - 2 * d) + + -0.00096 * Math.sin(mdash - d) + + +0.00046 * Math.sin(2 * f - 2 * d) + + -0.00039 * Math.sin(mdash - f) + + -0.00032 * Math.sin(mdash - m - d) + + +0.00027 * Math.sin(2 * mdash - m - 2 * d) + + +0.00023 * Math.sin(k2) + + -0.00014 * Math.sin(2 * d) + + +0.00014 * Math.cos(2 * mdash - 2 * f) + + -0.00012 * Math.sin(mdash - 2 * f) + + -0.00012 * Math.sin(2 * mdash) + + +0.00011 * Math.sin(2 * mdash - 2 * m - 2 * d)); + const ldash2 = -tau + (rho * Math.cos(a) + sigma * Math.sin(a)) * Math.tan(bdash); + const bdash2 = sigma * Math.cos(a) - rho * Math.sin(a); + const diam_deg = 2.0 * RAD2DEG * Math.atan(MOON_MEAN_RADIUS_KM / Math.sqrt(dist_km * dist_km - MOON_MEAN_RADIUS_KM * MOON_MEAN_RADIUS_KM)); + return new LibrationInfo(RAD2DEG * bdash + bdash2, ldash + ldash2, RAD2DEG * mlat, RAD2DEG * mlon, dist_km, diam_deg); +} +function rotate(rot, vec) { + return [ + rot.rot[0][0] * vec[0] + rot.rot[1][0] * vec[1] + rot.rot[2][0] * vec[2], + rot.rot[0][1] * vec[0] + rot.rot[1][1] * vec[1] + rot.rot[2][1] * vec[2], + rot.rot[0][2] * vec[0] + rot.rot[1][2] * vec[1] + rot.rot[2][2] * vec[2] + ]; +} +function precession(pos, time, dir) { + const r = precession_rot(time, dir); + return rotate(r, pos); +} +function precession_posvel(state, time, dir) { + const r = precession_rot(time, dir); + return RotateState(r, state); +} +function precession_rot(time, dir) { + const t = time.tt / 36525; + let eps0 = 84381.406; + let psia = (((((-0.0000000951 * t + + 0.000132851) * t + - 0.00114045) * t + - 1.0790069) * t + + 5038.481507) * t); + let omegaa = (((((+0.0000003337 * t + - 0.000000467) * t + - 0.00772503) * t + + 0.0512623) * t + - 0.025754) * t + eps0); + let chia = (((((-0.0000000560 * t + + 0.000170663) * t + - 0.00121197) * t + - 2.3814292) * t + + 10.556403) * t); + eps0 *= ASEC2RAD; + psia *= ASEC2RAD; + omegaa *= ASEC2RAD; + chia *= ASEC2RAD; + const sa = Math.sin(eps0); + const ca = Math.cos(eps0); + const sb = Math.sin(-psia); + const cb = Math.cos(-psia); + const sc = Math.sin(-omegaa); + const cc = Math.cos(-omegaa); + const sd = Math.sin(chia); + const cd = Math.cos(chia); + const xx = cd * cb - sb * sd * cc; + const yx = cd * sb * ca + sd * cc * cb * ca - sa * sd * sc; + const zx = cd * sb * sa + sd * cc * cb * sa + ca * sd * sc; + const xy = -sd * cb - sb * cd * cc; + const yy = -sd * sb * ca + cd * cc * cb * ca - sa * cd * sc; + const zy = -sd * sb * sa + cd * cc * cb * sa + ca * cd * sc; + const xz = sb * sc; + const yz = -sc * cb * ca - sa * cc; + const zz = -sc * cb * sa + cc * ca; + if (dir === PrecessDirection.Into2000) { + // Perform rotation from epoch to J2000.0. + return new RotationMatrix([ + [xx, yx, zx], + [xy, yy, zy], + [xz, yz, zz] + ]); + } + if (dir === PrecessDirection.From2000) { + // Perform rotation from J2000.0 to epoch. + return new RotationMatrix([ + [xx, xy, xz], + [yx, yy, yz], + [zx, zy, zz] + ]); + } + throw 'Invalid precess direction'; +} +function era(time) { + const thet1 = 0.7790572732640 + 0.00273781191135448 * time.ut; + const thet3 = time.ut % 1; + let theta = 360 * ((thet1 + thet3) % 1); + if (theta < 0) { + theta += 360; + } + return theta; +} +let sidereal_time_cache; +function sidereal_time(time) { + if (!sidereal_time_cache || sidereal_time_cache.tt !== time.tt) { + const t = time.tt / 36525; + let eqeq = 15 * e_tilt(time).ee; // Replace with eqeq=0 to get GMST instead of GAST (if we ever need it) + const theta = era(time); + const st = (eqeq + 0.014506 + + ((((-0.0000000368 * t + - 0.000029956) * t + - 0.00000044) * t + + 1.3915817) * t + + 4612.156534) * t); + let gst = ((st / 3600 + theta) % 360) / 15; + if (gst < 0) { + gst += 24; + } + sidereal_time_cache = { + tt: time.tt, + st: gst + }; + } + return sidereal_time_cache.st; // return sidereal hours in the half-open range [0, 24). +} +/** + * @brief Calculates Greenwich Apparent Sidereal Time (GAST). + * + * Given a date and time, this function calculates the rotation of the + * Earth, represented by the equatorial angle of the Greenwich prime meridian + * with respect to distant stars (not the Sun, which moves relative to background + * stars by almost one degree per day). + * This angle is called Greenwich Apparent Sidereal Time (GAST). + * GAST is measured in sidereal hours in the half-open range [0, 24). + * When GAST = 0, it means the prime meridian is aligned with the of-date equinox, + * corrected at that time for precession and nutation of the Earth's axis. + * In this context, the "equinox" is the direction in space where the Earth's + * orbital plane (the ecliptic) intersects with the plane of the Earth's equator, + * at the location on the Earth's orbit of the (seasonal) March equinox. + * As the Earth rotates, GAST increases from 0 up to 24 sidereal hours, + * then starts over at 0. + * To convert to degrees, multiply the return value by 15. + * + * @param {FlexibleDateTime} date + * The date and time for which to find GAST. + * + * @returns {number} + */ +export function SiderealTime(date) { + const time = MakeTime(date); + return sidereal_time(time); +} +function inverse_terra(ovec, st) { + // Convert from AU to kilometers + const x = ovec[0] * KM_PER_AU; + const y = ovec[1] * KM_PER_AU; + const z = ovec[2] * KM_PER_AU; + const p = Math.hypot(x, y); + let lon_deg, lat_deg, height_km; + if (p < 1.0e-6) { + // Special case: within 1 millimeter of a pole! + // Use arbitrary longitude, and latitude determined by polarity of z. + lon_deg = 0; + lat_deg = (z > 0.0) ? +90 : -90; + // Elevation is calculated directly from z. + height_km = Math.abs(z) - EARTH_POLAR_RADIUS_KM; + } + else { + const stlocl = Math.atan2(y, x); + // Calculate exact longitude. + lon_deg = (RAD2DEG * stlocl) - (15.0 * st); + // Normalize longitude to the range (-180, +180]. + while (lon_deg <= -180) + lon_deg += 360; + while (lon_deg > +180) + lon_deg -= 360; + // Numerically solve for exact latitude, using Newton's Method. + // Start with initial latitude estimate, based on a spherical Earth. + let lat = Math.atan2(z, p); + let cos, sin, denom; + let count = 0; + for (;;) { + if (++count > 10) + throw `inverse_terra failed to converge.`; + // Calculate the error function W(lat). + // We try to find the root of W, meaning where the error is 0. + cos = Math.cos(lat); + sin = Math.sin(lat); + const factor = (EARTH_FLATTENING_SQUARED - 1) * EARTH_EQUATORIAL_RADIUS_KM; + const cos2 = cos * cos; + const sin2 = sin * sin; + const radicand = cos2 + EARTH_FLATTENING_SQUARED * sin2; + denom = Math.sqrt(radicand); + const W = (factor * sin * cos) / denom - z * cos + p * sin; + if (Math.abs(W) < 1.0e-8) + break; // The error is now negligible + // Error is still too large. Find the next estimate. + // Calculate D = the derivative of W with respect to lat. + const D = factor * ((cos2 - sin2) / denom - sin2 * cos2 * (EARTH_FLATTENING_SQUARED - 1) / (factor * radicand)) + z * sin + p * cos; + lat -= W / D; + } + // We now have a solution for the latitude in radians. + lat_deg = RAD2DEG * lat; + // Solve for exact height in meters. + // There are two formulas I can use. Use whichever has the less risky denominator. + const adjust = EARTH_EQUATORIAL_RADIUS_KM / denom; + if (Math.abs(sin) > Math.abs(cos)) + height_km = z / sin - EARTH_FLATTENING_SQUARED * adjust; + else + height_km = p / cos - adjust; + } + return new Observer(lat_deg, lon_deg, 1000 * height_km); +} +function terra(observer, st) { + const phi = observer.latitude * DEG2RAD; + const sinphi = Math.sin(phi); + const cosphi = Math.cos(phi); + const c = 1 / Math.hypot(cosphi, EARTH_FLATTENING * sinphi); + const s = EARTH_FLATTENING_SQUARED * c; + const ht_km = observer.height / 1000; + const ach = EARTH_EQUATORIAL_RADIUS_KM * c + ht_km; + const ash = EARTH_EQUATORIAL_RADIUS_KM * s + ht_km; + const stlocl = (15 * st + observer.longitude) * DEG2RAD; + const sinst = Math.sin(stlocl); + const cosst = Math.cos(stlocl); + return { + pos: [ach * cosphi * cosst / KM_PER_AU, ach * cosphi * sinst / KM_PER_AU, ash * sinphi / KM_PER_AU], + vel: [-ANGVEL * ach * cosphi * sinst * 86400 / KM_PER_AU, ANGVEL * ach * cosphi * cosst * 86400 / KM_PER_AU, 0] + }; +} +function nutation(pos, time, dir) { + const r = nutation_rot(time, dir); + return rotate(r, pos); +} +function nutation_posvel(state, time, dir) { + const r = nutation_rot(time, dir); + return RotateState(r, state); +} +function nutation_rot(time, dir) { + const tilt = e_tilt(time); + const oblm = tilt.mobl * DEG2RAD; + const oblt = tilt.tobl * DEG2RAD; + const psi = tilt.dpsi * ASEC2RAD; + const cobm = Math.cos(oblm); + const sobm = Math.sin(oblm); + const cobt = Math.cos(oblt); + const sobt = Math.sin(oblt); + const cpsi = Math.cos(psi); + const spsi = Math.sin(psi); + const xx = cpsi; + const yx = -spsi * cobm; + const zx = -spsi * sobm; + const xy = spsi * cobt; + const yy = cpsi * cobm * cobt + sobm * sobt; + const zy = cpsi * sobm * cobt - cobm * sobt; + const xz = spsi * sobt; + const yz = cpsi * cobm * sobt - sobm * cobt; + const zz = cpsi * sobm * sobt + cobm * cobt; + if (dir === PrecessDirection.From2000) { + // convert J2000 to of-date + return new RotationMatrix([ + [xx, xy, xz], + [yx, yy, yz], + [zx, zy, zz] + ]); + } + if (dir === PrecessDirection.Into2000) { + // convert of-date to J2000 + return new RotationMatrix([ + [xx, yx, zx], + [xy, yy, zy], + [xz, yz, zz] + ]); + } + throw 'Invalid precess direction'; +} +function gyration(pos, time, dir) { + // Combine nutation and precession into a single operation I call "gyration". + // The order they are composed depends on the direction, + // because both directions are mutual inverse functions. + return (dir === PrecessDirection.Into2000) ? + precession(nutation(pos, time, dir), time, dir) : + nutation(precession(pos, time, dir), time, dir); +} +function gyration_posvel(state, time, dir) { + // Combine nutation and precession into a single operation I call "gyration". + // The order they are composed depends on the direction, + // because both directions are mutual inverse functions. + return (dir === PrecessDirection.Into2000) ? + precession_posvel(nutation_posvel(state, time, dir), time, dir) : + nutation_posvel(precession_posvel(state, time, dir), time, dir); +} +function geo_pos(time, observer) { + const gast = sidereal_time(time); + const pos = terra(observer, gast).pos; + return gyration(pos, time, PrecessDirection.Into2000); +} +/** + * @brief A 3D Cartesian vector with a time attached to it. + * + * Holds the Cartesian coordinates of a vector in 3D space, + * along with the time at which the vector is valid. + * + * @property {number} x The x-coordinate expressed in astronomical units (AU). + * @property {number} y The y-coordinate expressed in astronomical units (AU). + * @property {number} z The z-coordinate expressed in astronomical units (AU). + * @property {AstroTime} t The time at which the vector is valid. + */ +export class Vector { + constructor(x, y, z, t) { + this.x = x; + this.y = y; + this.z = z; + this.t = t; + } + /** + * Returns the length of the vector in astronomical units (AU). + * @returns {number} + */ + Length() { + return Math.hypot(this.x, this.y, this.z); + } +} +/** + * @brief A combination of a position vector, a velocity vector, and a time. + * + * Holds the state vector of a body at a given time, including its position, + * velocity, and the time they are valid. + * + * @property {number} x The position x-coordinate expressed in astronomical units (AU). + * @property {number} y The position y-coordinate expressed in astronomical units (AU). + * @property {number} z The position z-coordinate expressed in astronomical units (AU). + * @property {number} vx The velocity x-coordinate expressed in AU/day. + * @property {number} vy The velocity y-coordinate expressed in AU/day. + * @property {number} vz The velocity z-coordinate expressed in AU/day. + * @property {AstroTime} t The time at which the vector is valid. + */ +export class StateVector { + constructor(x, y, z, vx, vy, vz, t) { + this.x = x; + this.y = y; + this.z = z; + this.vx = vx; + this.vy = vy; + this.vz = vz; + this.t = t; + } +} +/** + * @brief Holds spherical coordinates: latitude, longitude, distance. + * + * Spherical coordinates represent the location of + * a point using two angles and a distance. + * + * @property {number} lat The latitude angle: -90..+90 degrees. + * @property {number} lon The longitude angle: 0..360 degrees. + * @property {number} dist Distance in AU. + */ +export class Spherical { + constructor(lat, lon, dist) { + this.lat = VerifyNumber(lat); + this.lon = VerifyNumber(lon); + this.dist = VerifyNumber(dist); + } +} +/** + * @brief Holds right ascension, declination, and distance of a celestial object. + * + * @property {number} ra + * Right ascension in sidereal hours: [0, 24). + * + * @property {number} dec + * Declination in degrees: [-90, +90]. + * + * @property {number} dist + * Distance to the celestial object expressed in + * astronomical units (AU). + * + * @property {Vector} vec + * The equatorial coordinates in cartesian form, using AU distance units. + * x = direction of the March equinox, + * y = direction of the June solstice, + * z = north. + */ +export class EquatorialCoordinates { + constructor(ra, dec, dist, vec) { + this.ra = VerifyNumber(ra); + this.dec = VerifyNumber(dec); + this.dist = VerifyNumber(dist); + this.vec = vec; + } +} +function IsValidRotationArray(rot) { + if (!(rot instanceof Array) || (rot.length !== 3)) + return false; + for (let i = 0; i < 3; ++i) { + if (!(rot[i] instanceof Array) || (rot[i].length !== 3)) + return false; + for (let j = 0; j < 3; ++j) + if (!Number.isFinite(rot[i][j])) + return false; + } + return true; +} +/** + * @brief Contains a rotation matrix that can be used to transform one coordinate system to another. + * + * @property {number[][]} rot + * A normalized 3x3 rotation matrix. For example, the identity matrix is represented + * as `[[1, 0, 0], [0, 1, 0], [0, 0, 1]]`. + */ +export class RotationMatrix { + constructor(rot) { + this.rot = rot; + } +} +/** + * @brief Creates a rotation matrix that can be used to transform one coordinate system to another. + * + * This function verifies that the `rot` parameter is of the correct format: + * a number[3][3] array. It throws an exception if `rot` is not of that shape. + * Otherwise it creates a new {@link RotationMatrix} object based on `rot`. + * + * @param {number[][]} rot + * An array [3][3] of numbers. Defines a rotation matrix used to premultiply + * a 3D vector to reorient it into another coordinate system. + * + * @returns {RotationMatrix} + */ +export function MakeRotation(rot) { + if (!IsValidRotationArray(rot)) + throw 'Argument must be a [3][3] array of numbers'; + return new RotationMatrix(rot); +} +/** + * @brief Represents the location of an object seen by an observer on the Earth. + * + * Holds azimuth (compass direction) and altitude (angle above/below the horizon) + * of a celestial object as seen by an observer at a particular location on the Earth's surface. + * Also holds right ascension and declination of the same object. + * All of these coordinates are optionally adjusted for atmospheric refraction; + * therefore the right ascension and declination values may not exactly match + * those found inside a corresponding {@link EquatorialCoordinates} object. + * + * @property {number} azimuth + * A horizontal compass direction angle in degrees measured starting at north + * and increasing positively toward the east. + * The value is in the range [0, 360). + * North = 0, east = 90, south = 180, west = 270. + * + * @property {number} altitude + * A vertical angle in degrees above (positive) or below (negative) the horizon. + * The value is in the range [-90, +90]. + * The altitude angle is optionally adjusted upward due to atmospheric refraction. + * + * @property {number} ra + * The right ascension of the celestial body in sidereal hours. + * The value is in the reange [0, 24). + * If `altitude` was adjusted for atmospheric reaction, `ra` + * is likewise adjusted. + * + * @property {number} dec + * The declination of of the celestial body in degrees. + * The value in the range [-90, +90]. + * If `altitude` was adjusted for atmospheric reaction, `dec` + * is likewise adjusted. + */ +export class HorizontalCoordinates { + constructor(azimuth, altitude, ra, dec) { + this.azimuth = VerifyNumber(azimuth); + this.altitude = VerifyNumber(altitude); + this.ra = VerifyNumber(ra); + this.dec = VerifyNumber(dec); + } +} +/** + * @brief Ecliptic coordinates of a celestial body. + * + * The origin and date of the coordinate system may vary depending on the caller's usage. + * In general, ecliptic coordinates are measured with respect to the mean plane of the Earth's + * orbit around the Sun. + * Includes Cartesian coordinates `(ex, ey, ez)` measured in + * astronomical units (AU) + * and spherical coordinates `(elon, elat)` measured in degrees. + * + * @property {Vector} vec + * Ecliptic cartesian vector with components measured in astronomical units (AU). + * The x-axis is within the ecliptic plane and is oriented in the direction of the + * equinox. + * The y-axis is within the ecliptic plane and is oriented 90 degrees + * counterclockwise from the equinox, as seen from above the Sun's north pole. + * The z-axis is oriented perpendicular to the ecliptic plane, + * along the direction of the Sun's north pole. + * + * @property {number} elat + * The ecliptic latitude of the body in degrees. + * This is the angle north or south of the ecliptic plane. + * The value is in the range [-90, +90]. + * Positive values are north and negative values are south. + * + * @property {number} elon + * The ecliptic longitude of the body in degrees. + * This is the angle measured counterclockwise around the ecliptic plane, + * as seen from above the Sun's north pole. + * This is the same direction that the Earth orbits around the Sun. + * The angle is measured starting at 0 from the equinox and increases + * up to 360 degrees. + */ +export class EclipticCoordinates { + constructor(vec, elat, elon) { + this.vec = vec; + this.elat = VerifyNumber(elat); + this.elon = VerifyNumber(elon); + } +} +function VectorFromArray(av, time) { + return new Vector(av[0], av[1], av[2], time); +} +function vector2radec(pos, time) { + const vec = VectorFromArray(pos, time); + const xyproj = vec.x * vec.x + vec.y * vec.y; + const dist = Math.sqrt(xyproj + vec.z * vec.z); + if (xyproj === 0) { + if (vec.z === 0) + throw 'Indeterminate sky coordinates'; + return new EquatorialCoordinates(0, (vec.z < 0) ? -90 : +90, dist, vec); + } + let ra = RAD2HOUR * Math.atan2(vec.y, vec.x); + if (ra < 0) + ra += 24; + const dec = RAD2DEG * Math.atan2(pos[2], Math.sqrt(xyproj)); + return new EquatorialCoordinates(ra, dec, dist, vec); +} +function spin(angle, pos) { + const angr = angle * DEG2RAD; + const c = Math.cos(angr); + const s = Math.sin(angr); + return [c * pos[0] + s * pos[1], c * pos[1] - s * pos[0], pos[2]]; +} +/** + * @brief Converts equatorial coordinates to horizontal coordinates. + * + * Given a date and time, a geographic location of an observer on the Earth, and + * equatorial coordinates (right ascension and declination) of a celestial body, + * returns horizontal coordinates (azimuth and altitude angles) for that body + * as seen by that observer. Allows optional correction for atmospheric refraction. + * + * @param {FlexibleDateTime} date + * The date and time for which to find horizontal coordinates. + * + * @param {Observer} observer + * The location of the observer for which to find horizontal coordinates. + * + * @param {number} ra + * Right ascension in sidereal hours of the celestial object, + * referred to the mean equinox of date for the J2000 epoch. + * + * @param {number} dec + * Declination in degrees of the celestial object, + * referred to the mean equator of date for the J2000 epoch. + * Positive values are north of the celestial equator and negative values are south. + * + * @param {string} refraction + * If omitted or has a false-like value (false, null, undefined, etc.) + * the calculations are performed without any correction for atmospheric + * refraction. If the value is the string `"normal"`, + * uses the recommended refraction correction based on Meeus "Astronomical Algorithms" + * with a linear taper more than 1 degree below the horizon. The linear + * taper causes the refraction to linearly approach 0 as the altitude of the + * body approaches the nadir (-90 degrees). + * If the value is the string `"jplhor"`, uses a JPL Horizons + * compatible formula. This is the same algorithm as `"normal"`, + * only without linear tapering; this can result in physically impossible + * altitudes of less than -90 degrees, which may cause problems for some applications. + * (The `"jplhor"` option was created for unit testing against data + * generated by JPL Horizons, and is otherwise not recommended for use.) + * + * @returns {HorizontalCoordinates} + */ +export function Horizon(date, observer, ra, dec, refraction) { + // based on NOVAS equ2hor() + let time = MakeTime(date); + VerifyObserver(observer); + VerifyNumber(ra); + VerifyNumber(dec); + const sinlat = Math.sin(observer.latitude * DEG2RAD); + const coslat = Math.cos(observer.latitude * DEG2RAD); + const sinlon = Math.sin(observer.longitude * DEG2RAD); + const coslon = Math.cos(observer.longitude * DEG2RAD); + const sindc = Math.sin(dec * DEG2RAD); + const cosdc = Math.cos(dec * DEG2RAD); + const sinra = Math.sin(ra * HOUR2RAD); + const cosra = Math.cos(ra * HOUR2RAD); + // Calculate three mutually perpendicular unit vectors + // in equatorial coordinates: uze, une, uwe. + // + // uze = The direction of the observer's local zenith (straight up). + // une = The direction toward due north on the observer's horizon. + // uwe = The direction toward due west on the observer's horizon. + // + // HOWEVER, these are uncorrected for the Earth's rotation due to the time of day. + // + // The components of these 3 vectors are as follows: + // x = direction from center of Earth toward 0 degrees longitude (the prime meridian) on equator. + // y = direction from center of Earth toward 90 degrees west longitude on equator. + // z = direction from center of Earth toward the north pole. + let uze = [coslat * coslon, coslat * sinlon, sinlat]; + let une = [-sinlat * coslon, -sinlat * sinlon, coslat]; + let uwe = [sinlon, -coslon, 0]; + // Correct the vectors uze, une, uwe for the Earth's rotation by calculating + // sidereal time. Call spin() for each uncorrected vector to rotate about + // the Earth's axis to yield corrected unit vectors uz, un, uw. + // Multiply sidereal hours by -15 to convert to degrees and flip eastward + // rotation of the Earth to westward apparent movement of objects with time. + const spin_angle = -15 * sidereal_time(time); + let uz = spin(spin_angle, uze); + let un = spin(spin_angle, une); + let uw = spin(spin_angle, uwe); + // Convert angular equatorial coordinates (RA, DEC) to + // cartesian equatorial coordinates in 'p', using the + // same orientation system as uze, une, uwe. + let p = [cosdc * cosra, cosdc * sinra, sindc]; + // Use dot products of p with the zenith, north, and west + // vectors to obtain the cartesian coordinates of the body in + // the observer's horizontal orientation system. + // pz = zenith component [-1, +1] + // pn = north component [-1, +1] + // pw = west component [-1, +1] + const pz = p[0] * uz[0] + p[1] * uz[1] + p[2] * uz[2]; + const pn = p[0] * un[0] + p[1] * un[1] + p[2] * un[2]; + const pw = p[0] * uw[0] + p[1] * uw[1] + p[2] * uw[2]; + // proj is the "shadow" of the body vector along the observer's flat ground. + let proj = Math.hypot(pn, pw); + // Calculate az = azimuth (compass direction clockwise from East.) + let az; + if (proj > 0) { + // If the body is not exactly straight up/down, it has an azimuth. + // Invert the angle to produce degrees eastward from north. + az = -RAD2DEG * Math.atan2(pw, pn); + if (az < 0) + az += 360; + } + else { + // The body is straight up/down, so it does not have an azimuth. + // Report an arbitrary but reasonable value. + az = 0; + } + // zd = the angle of the body away from the observer's zenith, in degrees. + let zd = RAD2DEG * Math.atan2(proj, pz); + let out_ra = ra; + let out_dec = dec; + if (refraction) { + let zd0 = zd; + let refr = Refraction(refraction, 90 - zd); + zd -= refr; + if (refr > 0.0 && zd > 3.0e-4) { + const sinzd = Math.sin(zd * DEG2RAD); + const coszd = Math.cos(zd * DEG2RAD); + const sinzd0 = Math.sin(zd0 * DEG2RAD); + const coszd0 = Math.cos(zd0 * DEG2RAD); + const pr = []; + for (let j = 0; j < 3; ++j) { + pr.push(((p[j] - coszd0 * uz[j]) / sinzd0) * sinzd + uz[j] * coszd); + } + proj = Math.hypot(pr[0], pr[1]); + if (proj > 0) { + out_ra = RAD2HOUR * Math.atan2(pr[1], pr[0]); + if (out_ra < 0) { + out_ra += 24; + } + } + else { + out_ra = 0; + } + out_dec = RAD2DEG * Math.atan2(pr[2], proj); + } + } + return new HorizontalCoordinates(az, 90 - zd, out_ra, out_dec); +} +function VerifyObserver(observer) { + if (!(observer instanceof Observer)) { + throw `Not an instance of the Observer class: ${observer}`; + } + VerifyNumber(observer.latitude); + VerifyNumber(observer.longitude); + VerifyNumber(observer.height); + if (observer.latitude < -90 || observer.latitude > +90) { + throw `Latitude ${observer.latitude} is out of range. Must be -90..+90.`; + } + return observer; +} +/** + * @brief Represents the geographic location of an observer on the surface of the Earth. + * + * @property {number} latitude + * The observer's geographic latitude in degrees north of the Earth's equator. + * The value is negative for observers south of the equator. + * Must be in the range -90 to +90. + * + * @property {number} longitude + * The observer's geographic longitude in degrees east of the prime meridian + * passing through Greenwich, England. + * The value is negative for observers west of the prime meridian. + * The value should be kept in the range -180 to +180 to minimize floating point errors. + * + * @property {number} height + * The observer's elevation above mean sea level, expressed in meters. + */ +export class Observer { + constructor(latitude, longitude, height) { + this.latitude = latitude; + this.longitude = longitude; + this.height = height; + VerifyObserver(this); + } +} +/** + * @brief Returns apparent geocentric true ecliptic coordinates of date for the Sun. + * + * This function is used for calculating the times of equinoxes and solstices. + * + * Geocentric means coordinates as the Sun would appear to a hypothetical observer + * at the center of the Earth. + * Ecliptic coordinates of date are measured along the plane of the Earth's mean + * orbit around the Sun, using the + * equinox + * of the Earth as adjusted for precession and nutation of the Earth's + * axis of rotation on the given date. + * + * @param {FlexibleDateTime} date + * The date and time at which to calculate the Sun's apparent location as seen from + * the center of the Earth. + * + * @returns {EclipticCoordinates} + */ +export function SunPosition(date) { + // Correct for light travel time from the Sun. + // This is really the same as correcting for aberration. + // Otherwise season calculations (equinox, solstice) will all be early by about 8 minutes! + const time = MakeTime(date).AddDays(-1 / C_AUDAY); + // Get heliocentric cartesian coordinates of Earth in J2000. + const earth2000 = CalcVsop(vsop.Earth, time); + // Convert to geocentric location of the Sun. + const sun2000 = [-earth2000.x, -earth2000.y, -earth2000.z]; + // Convert to equator-of-date equatorial cartesian coordinates. + const [gx, gy, gz] = gyration(sun2000, time, PrecessDirection.From2000); + // Convert to ecliptic coordinates of date. + const true_obliq = DEG2RAD * e_tilt(time).tobl; + const cos_ob = Math.cos(true_obliq); + const sin_ob = Math.sin(true_obliq); + const vec = new Vector(gx, gy, gz, time); + const sun_ecliptic = RotateEquatorialToEcliptic(vec, cos_ob, sin_ob); + return sun_ecliptic; +} +/** + * @brief Calculates equatorial coordinates of a Solar System body at a given time. + * + * Returns topocentric equatorial coordinates (right ascension and declination) + * in one of two different systems: J2000 or true-equator-of-date. + * Allows optional correction for aberration. + * Always corrects for light travel time (represents the object as seen by the observer + * with light traveling to the Earth at finite speed, not where the object is right now). + * Topocentric refers to a position as seen by an observer on the surface of the Earth. + * This function corrects for + * parallax + * of the object between a geocentric observer and a topocentric observer. + * This is most significant for the Moon, because it is so close to the Earth. + * However, it can have a small effect on the apparent positions of other bodies. + * + * @param {Body} body + * The body for which to find equatorial coordinates. + * Not allowed to be `Body.Earth`. + * + * @param {FlexibleDateTime} date + * Specifies the date and time at which the body is to be observed. + * + * @param {Observer} observer + * The location on the Earth of the observer. + * + * @param {bool} ofdate + * Pass `true` to return equatorial coordinates of date, + * i.e. corrected for precession and nutation at the given date. + * This is needed to get correct horizontal coordinates when you call + * {@link Horizon}. + * Pass `false` to return equatorial coordinates in the J2000 system. + * + * @param {bool} aberration + * Pass `true` to correct for + * aberration, + * or `false` to leave uncorrected. + * + * @returns {EquatorialCoordinates} + * The topocentric coordinates of the body as adjusted for the given observer. + */ +export function Equator(body, date, observer, ofdate, aberration) { + VerifyObserver(observer); + VerifyBoolean(ofdate); + VerifyBoolean(aberration); + const time = MakeTime(date); + const gc_observer = geo_pos(time, observer); + const gc = GeoVector(body, time, aberration); + const j2000 = [ + gc.x - gc_observer[0], + gc.y - gc_observer[1], + gc.z - gc_observer[2] + ]; + if (!ofdate) + return vector2radec(j2000, time); + const datevect = gyration(j2000, time, PrecessDirection.From2000); + return vector2radec(datevect, time); +} +/** + * @brief Calculates geocentric equatorial coordinates of an observer on the surface of the Earth. + * + * This function calculates a vector from the center of the Earth to + * a point on or near the surface of the Earth, expressed in equatorial + * coordinates. It takes into account the rotation of the Earth at the given + * time, along with the given latitude, longitude, and elevation of the observer. + * + * The caller may pass `ofdate` as `true` to return coordinates relative to the Earth's + * equator at the specified time, or `false` to use the J2000 equator. + * + * The returned vector has components expressed in astronomical units (AU). + * To convert to kilometers, multiply the `x`, `y`, and `z` values by + * the constant value {@link KM_PER_AU}. + * + * The inverse of this function is also available: {@link VectorObserver}. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the observer's position vector. + * + * @param {Observer} observer + * The geographic location of a point on or near the surface of the Earth. + * + * @param {boolean} ofdate + * Selects the date of the Earth's equator in which to express the equatorial coordinates. + * The caller may pass `false` to use the orientation of the Earth's equator + * at noon UTC on January 1, 2000, in which case this function corrects for precession + * and nutation of the Earth as it was at the moment specified by the `time` parameter. + * Or the caller may pass `true` to use the Earth's equator at `time` + * as the orientation. + * + * @returns {Vector} + * An equatorial vector from the center of the Earth to the specified location + * on (or near) the Earth's surface. + */ +export function ObserverVector(date, observer, ofdate) { + const time = MakeTime(date); + const gast = sidereal_time(time); + let ovec = terra(observer, gast).pos; + if (!ofdate) + ovec = gyration(ovec, time, PrecessDirection.Into2000); + return VectorFromArray(ovec, time); +} +/** + * @brief Calculates geocentric equatorial position and velocity of an observer on the surface of the Earth. + * + * This function calculates position and velocity vectors of an observer + * on or near the surface of the Earth, expressed in equatorial + * coordinates. It takes into account the rotation of the Earth at the given + * time, along with the given latitude, longitude, and elevation of the observer. + * + * The caller may pass `ofdate` as `true` to return coordinates relative to the Earth's + * equator at the specified time, or `false` to use the J2000 equator. + * + * The returned position vector has components expressed in astronomical units (AU). + * To convert to kilometers, multiply the `x`, `y`, and `z` values by + * the constant value {@link KM_PER_AU}. + * The returned velocity vector has components expressed in AU/day. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the observer's position and velocity vectors. + * + * @param {Observer} observer + * The geographic location of a point on or near the surface of the Earth. + * + * @param {boolean} ofdate + * Selects the date of the Earth's equator in which to express the equatorial coordinates. + * The caller may pass `false` to use the orientation of the Earth's equator + * at noon UTC on January 1, 2000, in which case this function corrects for precession + * and nutation of the Earth as it was at the moment specified by the `time` parameter. + * Or the caller may pass `true` to use the Earth's equator at `time` + * as the orientation. + * + * @returns {StateVector} + */ +export function ObserverState(date, observer, ofdate) { + const time = MakeTime(date); + const gast = sidereal_time(time); + const svec = terra(observer, gast); + const state = new StateVector(svec.pos[0], svec.pos[1], svec.pos[2], svec.vel[0], svec.vel[1], svec.vel[2], time); + if (!ofdate) + return gyration_posvel(state, time, PrecessDirection.Into2000); + return state; +} +/** + * @brief Calculates the geographic location corresponding to an equatorial vector. + * + * This is the inverse function of {@link ObserverVector}. + * Given a geocentric equatorial vector, it returns the geographic + * latitude, longitude, and elevation for that vector. + * + * @param {Vector} vector + * The geocentric equatorial position vector for which to find geographic coordinates. + * The components are expressed in Astronomical Units (AU). + * You can calculate AU by dividing kilometers by the constant {@link KM_PER_AU}. + * The time `vector.t` determines the Earth's rotation. + * + * @param {boolean} ofdate + * Selects the date of the Earth's equator in which `vector` is expressed. + * The caller may select `false` to use the orientation of the Earth's equator + * at noon UTC on January 1, 2000, in which case this function corrects for precession + * and nutation of the Earth as it was at the moment specified by `vector.t`. + * Or the caller may select `true` to use the Earth's equator at `vector.t` + * as the orientation. + * + * @returns {Observer} + * The geographic latitude, longitude, and elevation above sea level + * that corresponds to the given equatorial vector. + */ +export function VectorObserver(vector, ofdate) { + const gast = sidereal_time(vector.t); + let ovec = [vector.x, vector.y, vector.z]; + if (!ofdate) { + ovec = precession(ovec, vector.t, PrecessDirection.From2000); + ovec = nutation(ovec, vector.t, PrecessDirection.From2000); + } + return inverse_terra(ovec, gast); +} +/** + * @brief Calculates the gravitational acceleration experienced by an observer on the Earth. + * + * This function implements the WGS 84 Ellipsoidal Gravity Formula. + * The result is a combination of inward gravitational acceleration + * with outward centrifugal acceleration, as experienced by an observer + * in the Earth's rotating frame of reference. + * The resulting value increases toward the Earth's poles and decreases + * toward the equator, consistent with changes of the weight measured + * by a spring scale of a fixed mass moved to different latitudes and heights + * on the Earth. + * + * @param {number} latitude + * The latitude of the observer in degrees north or south of the equator. + * By formula symmetry, positive latitudes give the same answer as negative + * latitudes, so the sign does not matter. + * + * @param {number} height + * The height above the sea level geoid in meters. + * No range checking is done; however, accuracy is only valid in the + * range 0 to 100000 meters. + * + * @returns {number} + * The effective gravitational acceleration expressed in meters per second squared [m/s^2]. + */ +export function ObserverGravity(latitude, height) { + const s = Math.sin(latitude * DEG2RAD); + const s2 = s * s; + const g0 = 9.7803253359 * (1.0 + 0.00193185265241 * s2) / Math.sqrt(1.0 - 0.00669437999013 * s2); + return g0 * (1.0 - (3.15704e-07 - 2.10269e-09 * s2) * height + 7.37452e-14 * height * height); +} +function RotateEquatorialToEcliptic(equ, cos_ob, sin_ob) { + // Rotate equatorial vector to obtain ecliptic vector. + const ex = equ.x; + const ey = equ.y * cos_ob + equ.z * sin_ob; + const ez = -equ.y * sin_ob + equ.z * cos_ob; + const xyproj = Math.hypot(ex, ey); + let elon = 0; + if (xyproj > 0) { + elon = RAD2DEG * Math.atan2(ey, ex); + if (elon < 0) + elon += 360; + } + let elat = RAD2DEG * Math.atan2(ez, xyproj); + let ecl = new Vector(ex, ey, ez, equ.t); + return new EclipticCoordinates(ecl, elat, elon); +} +/** + * @brief Converts a J2000 mean equator (EQJ) vector to a true ecliptic of date (ETC) vector and angles. + * + * Given coordinates relative to the Earth's equator at J2000 (the instant of noon UTC + * on 1 January 2000), this function converts those coordinates to true ecliptic coordinates + * that are relative to the plane of the Earth's orbit around the Sun on that date. + * + * @param {Vector} eqj + * Equatorial coordinates in the EQJ frame of reference. + * You can call {@link GeoVector} to obtain suitable equatorial coordinates. + * + * @returns {EclipticCoordinates} + */ +export function Ecliptic(eqj) { + // Calculate nutation and obliquity for this time. + // As an optimization, the nutation angles are cached in `time`, + // and reused below when the `nutation` function is called. + const et = e_tilt(eqj.t); + // Convert mean J2000 equator (EQJ) to true equator of date (EQD). + const eqj_pos = [eqj.x, eqj.y, eqj.z]; + const mean_pos = precession(eqj_pos, eqj.t, PrecessDirection.From2000); + const [x, y, z] = nutation(mean_pos, eqj.t, PrecessDirection.From2000); + const eqd = new Vector(x, y, z, eqj.t); + // Rotate from EQD to true ecliptic of date (ECT). + const tobl = et.tobl * DEG2RAD; + return RotateEquatorialToEcliptic(eqd, Math.cos(tobl), Math.sin(tobl)); +} +/** + * @brief Calculates equatorial geocentric Cartesian coordinates for the Moon. + * + * Given a time of observation, calculates the Moon's position as a vector. + * The vector gives the location of the Moon's center relative to the Earth's center + * with x-, y-, and z-components measured in astronomical units. + * The coordinates are oriented with respect to the Earth's equator at the J2000 epoch. + * In Astronomy Engine, this orientation is called EQJ. + * Based on the Nautical Almanac Office's Improved Lunar Ephemeris of 1954, + * which in turn derives from E. W. Brown's lunar theories. + * Adapted from Turbo Pascal code from the book + * Astronomy on the Personal Computer + * by Montenbruck and Pfleger. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the Moon's geocentric position. + * + * @returns {Vector} + */ +export function GeoMoon(date) { + const time = MakeTime(date); + const moon = CalcMoon(time); + // Convert geocentric ecliptic spherical coords to cartesian coords. + const dist_cos_lat = moon.distance_au * Math.cos(moon.geo_eclip_lat); + const gepos = [ + dist_cos_lat * Math.cos(moon.geo_eclip_lon), + dist_cos_lat * Math.sin(moon.geo_eclip_lon), + moon.distance_au * Math.sin(moon.geo_eclip_lat) + ]; + // Convert ecliptic coordinates to equatorial coordinates, both in mean equinox of date. + const mpos1 = ecl2equ_vec(time, gepos); + // Convert from mean equinox of date to J2000... + const mpos2 = precession(mpos1, time, PrecessDirection.Into2000); + return new Vector(mpos2[0], mpos2[1], mpos2[2], time); +} +/** + * @brief Calculates spherical ecliptic geocentric position of the Moon. + * + * Given a time of observation, calculates the Moon's geocentric position + * in ecliptic spherical coordinates. Provides the ecliptic latitude and + * longitude in degrees, and the geocentric distance in astronomical units (AU). + * + * The ecliptic angles are measured in "ECT": relative to the true ecliptic plane and + * equatorial plane at the specified time. This means the Earth's equator + * is corrected for precession and nutation, and the plane of the Earth's + * orbit is corrected for gradual obliquity drift. + * + * This algorithm is based on the Nautical Almanac Office's Improved Lunar Ephemeris of 1954, + * which in turn derives from E. W. Brown's lunar theories from the early twentieth century. + * It is adapted from Turbo Pascal code from the book + * Astronomy on the Personal Computer + * by Montenbruck and Pfleger. + * + * To calculate a J2000 mean equator vector instead, use {@link GeoMoon}. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the Moon's position. + * + * @returns {Spherical} + */ +export function EclipticGeoMoon(date) { + const time = MakeTime(date); + const moon = CalcMoon(time); + // Convert spherical coordinates to a vector. + // The MoonResult angles are already expressed in radians. + const dist_cos_lat = moon.distance_au * Math.cos(moon.geo_eclip_lat); + const ecm = [ + dist_cos_lat * Math.cos(moon.geo_eclip_lon), + dist_cos_lat * Math.sin(moon.geo_eclip_lon), + moon.distance_au * Math.sin(moon.geo_eclip_lat) + ]; + // Obtain true and mean obliquity angles for the given time. + // This serves to pre-calculate the nutation also, and cache it in `time`. + const et = e_tilt(time); + // Convert ecliptic coordinates to equatorial coordinates, both in mean equinox of date. + const eqm = obl_ecl2equ_vec(et.mobl, ecm); + // Add nutation to convert ECM to true equatorial coordinates of date (EQD). + const eqd = nutation(eqm, time, PrecessDirection.From2000); + const eqd_vec = VectorFromArray(eqd, time); + // Convert back to ecliptic, this time in true equinox of date (ECT). + const toblRad = et.tobl * DEG2RAD; + const cos_tobl = Math.cos(toblRad); + const sin_tobl = Math.sin(toblRad); + const eclip = RotateEquatorialToEcliptic(eqd_vec, cos_tobl, sin_tobl); + return new Spherical(eclip.elat, eclip.elon, moon.distance_au); +} +/** + * @brief Calculates equatorial geocentric position and velocity of the Moon at a given time. + * + * Given a time of observation, calculates the Moon's position and velocity vectors. + * The position and velocity are of the Moon's center relative to the Earth's center. + * The position (x, y, z) components are expressed in AU (astronomical units). + * The velocity (vx, vy, vz) components are expressed in AU/day. + * The coordinates are oriented with respect to the Earth's equator at the J2000 epoch. + * In Astronomy Engine, this orientation is called EQJ. + * If you need the Moon's position only, and not its velocity, + * it is much more efficient to use {@link GeoMoon} instead. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the Moon's geocentric state. + * + * @returns {StateVector} + */ +export function GeoMoonState(date) { + const time = MakeTime(date); + // This is a hack, because trying to figure out how to derive a time + // derivative for CalcMoon() would be extremely painful! + // Calculate just before and just after the given time. + // Average to find position, subtract to find velocity. + const dt = 1.0e-5; // 0.864 seconds + const t1 = time.AddDays(-dt); + const t2 = time.AddDays(+dt); + const r1 = GeoMoon(t1); + const r2 = GeoMoon(t2); + return new StateVector((r1.x + r2.x) / 2, (r1.y + r2.y) / 2, (r1.z + r2.z) / 2, (r2.x - r1.x) / (2 * dt), (r2.y - r1.y) / (2 * dt), (r2.z - r1.z) / (2 * dt), time); +} +/** + * @brief Calculates the geocentric position and velocity of the Earth/Moon barycenter. + * + * Given a time of observation, calculates the geocentric position and velocity vectors + * of the Earth/Moon barycenter (EMB). + * The position (x, y, z) components are expressed in AU (astronomical units). + * The velocity (vx, vy, vz) components are expressed in AU/day. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the EMB's geocentric state. + * + * @returns {StateVector} + */ +export function GeoEmbState(date) { + const time = MakeTime(date); + const s = GeoMoonState(time); + const d = 1.0 + EARTH_MOON_MASS_RATIO; + return new StateVector(s.x / d, s.y / d, s.z / d, s.vx / d, s.vy / d, s.vz / d, time); +} +function VsopFormula(formula, t, clamp_angle) { + let tpower = 1; + let coord = 0; + for (let series of formula) { + let sum = 0; + for (let [ampl, phas, freq] of series) + sum += ampl * Math.cos(phas + (t * freq)); + let incr = tpower * sum; + if (clamp_angle) + incr %= PI2; // improve precision for longitudes: they can be hundreds of radians + coord += incr; + tpower *= t; + } + return coord; +} +function VsopDeriv(formula, t) { + let tpower = 1; // t^s + let dpower = 0; // t^(s-1) + let deriv = 0; + let s = 0; + for (let series of formula) { + let sin_sum = 0; + let cos_sum = 0; + for (let [ampl, phas, freq] of series) { + let angle = phas + (t * freq); + sin_sum += ampl * freq * Math.sin(angle); + if (s > 0) + cos_sum += ampl * Math.cos(angle); + } + deriv += (s * dpower * cos_sum) - (tpower * sin_sum); + dpower = tpower; + tpower *= t; + ++s; + } + return deriv; +} +const DAYS_PER_MILLENNIUM = 365250; +const LON_INDEX = 0; +const LAT_INDEX = 1; +const RAD_INDEX = 2; +function VsopRotate(eclip) { + // Convert ecliptic cartesian coordinates to equatorial cartesian coordinates. + return new TerseVector(eclip[0] + 0.000000440360 * eclip[1] - 0.000000190919 * eclip[2], -0.000000479966 * eclip[0] + 0.917482137087 * eclip[1] - 0.397776982902 * eclip[2], 0.397776982902 * eclip[1] + 0.917482137087 * eclip[2]); +} +function VsopSphereToRect(lon, lat, radius) { + // Convert spherical coordinates to ecliptic cartesian coordinates. + const r_coslat = radius * Math.cos(lat); + const coslon = Math.cos(lon); + const sinlon = Math.sin(lon); + return [ + r_coslat * coslon, + r_coslat * sinlon, + radius * Math.sin(lat) + ]; +} +function CalcVsop(model, time) { + const t = time.tt / DAYS_PER_MILLENNIUM; // millennia since 2000 + const lon = VsopFormula(model[LON_INDEX], t, true); + const lat = VsopFormula(model[LAT_INDEX], t, false); + const rad = VsopFormula(model[RAD_INDEX], t, false); + const eclip = VsopSphereToRect(lon, lat, rad); + return VsopRotate(eclip).ToAstroVector(time); +} +function CalcVsopPosVel(model, tt) { + const t = tt / DAYS_PER_MILLENNIUM; + // Calculate the VSOP "B" trigonometric series to obtain ecliptic spherical coordinates. + const lon = VsopFormula(model[LON_INDEX], t, true); + const lat = VsopFormula(model[LAT_INDEX], t, false); + const rad = VsopFormula(model[RAD_INDEX], t, false); + const dlon_dt = VsopDeriv(model[LON_INDEX], t); + const dlat_dt = VsopDeriv(model[LAT_INDEX], t); + const drad_dt = VsopDeriv(model[RAD_INDEX], t); + // Use spherical coords and spherical derivatives to calculate + // the velocity vector in rectangular coordinates. + const coslon = Math.cos(lon); + const sinlon = Math.sin(lon); + const coslat = Math.cos(lat); + const sinlat = Math.sin(lat); + const vx = (+(drad_dt * coslat * coslon) + - (rad * sinlat * coslon * dlat_dt) + - (rad * coslat * sinlon * dlon_dt)); + const vy = (+(drad_dt * coslat * sinlon) + - (rad * sinlat * sinlon * dlat_dt) + + (rad * coslat * coslon * dlon_dt)); + const vz = (+(drad_dt * sinlat) + + (rad * coslat * dlat_dt)); + const eclip_pos = VsopSphereToRect(lon, lat, rad); + // Convert speed units from [AU/millennium] to [AU/day]. + const eclip_vel = [ + vx / DAYS_PER_MILLENNIUM, + vy / DAYS_PER_MILLENNIUM, + vz / DAYS_PER_MILLENNIUM + ]; + // Rotate the vectors from ecliptic to equatorial coordinates. + const equ_pos = VsopRotate(eclip_pos); + const equ_vel = VsopRotate(eclip_vel); + return new body_state_t(tt, equ_pos, equ_vel); +} +function AdjustBarycenter(ssb, time, body, pmass) { + const shift = pmass / (pmass + SUN_GM); + const planet = CalcVsop(vsop[body], time); + ssb.x += shift * planet.x; + ssb.y += shift * planet.y; + ssb.z += shift * planet.z; +} +function CalcSolarSystemBarycenter(time) { + const ssb = new Vector(0.0, 0.0, 0.0, time); + AdjustBarycenter(ssb, time, Body.Jupiter, JUPITER_GM); + AdjustBarycenter(ssb, time, Body.Saturn, SATURN_GM); + AdjustBarycenter(ssb, time, Body.Uranus, URANUS_GM); + AdjustBarycenter(ssb, time, Body.Neptune, NEPTUNE_GM); + return ssb; +} +// Pluto integrator begins ---------------------------------------------------- +const PLUTO_NUM_STATES = 51; +const PLUTO_TIME_STEP = 29200; +const PLUTO_DT = 146; +const PLUTO_NSTEPS = 201; +const PlutoStateTable = [ + [-730000.0, [-26.118207232108, -14.376168177825, 3.384402515299], [1.6339372163656e-03, -2.7861699588508e-03, -1.3585880229445e-03]], + [-700800.0, [41.974905202127, -0.448502952929, -12.770351505989], [7.3458569351457e-04, 2.2785014891658e-03, 4.8619778602049e-04]], + [-671600.0, [14.706930780744, 44.269110540027, 9.353698474772], [-2.1000147999800e-03, 2.2295915939915e-04, 7.0143443551414e-04]], + [-642400.0, [-29.441003929957, -6.430161530570, 6.858481011305], [8.4495803960544e-04, -3.0783914758711e-03, -1.2106305981192e-03]], + [-613200.0, [39.444396946234, -6.557989760571, -13.913760296463], [1.1480029005873e-03, 2.2400006880665e-03, 3.5168075922288e-04]], + [-584000.0, [20.230380950700, 43.266966657189, 7.382966091923], [-1.9754081700585e-03, 5.3457141292226e-04, 7.5929169129793e-04]], + [-554800.0, [-30.658325364620, 2.093818874552, 9.880531138071], [6.1010603013347e-05, -3.1326500935382e-03, -9.9346125151067e-04]], + [-525600.0, [35.737703251673, -12.587706024764, -14.677847247563], [1.5802939375649e-03, 2.1347678412429e-03, 1.9074436384343e-04]], + [-496400.0, [25.466295188546, 41.367478338417, 5.216476873382], [-1.8054401046468e-03, 8.3283083599510e-04, 8.0260156912107e-04]], + [-467200.0, [-29.847174904071, 10.636426313081, 12.297904180106], [-6.3257063052907e-04, -2.9969577578221e-03, -7.4476074151596e-04]], + [-438000.0, [30.774692107687, -18.236637015304, -14.945535879896], [2.0113162005465e-03, 1.9353827024189e-03, -2.0937793168297e-06]], + [-408800.0, [30.243153324028, 38.656267888503, 2.938501750218], [-1.6052508674468e-03, 1.1183495337525e-03, 8.3333973416824e-04]], + [-379600.0, [-27.288984772533, 18.643162147874, 14.023633623329], [-1.1856388898191e-03, -2.7170609282181e-03, -4.9015526126399e-04]], + [-350400.0, [24.519605196774, -23.245756064727, -14.626862367368], [2.4322321483154e-03, 1.6062008146048e-03, -2.3369181613312e-04]], + [-321200.0, [34.505274805875, 35.125338586954, 0.557361475637], [-1.3824391637782e-03, 1.3833397561817e-03, 8.4823598806262e-04]], + [-292000.0, [-23.275363915119, 25.818514298769, 15.055381588598], [-1.6062295460975e-03, -2.3395961498533e-03, -2.4377362639479e-04]], + [-262800.0, [17.050384798092, -27.180376290126, -13.608963321694], [2.8175521080578e-03, 1.1358749093955e-03, -4.9548725258825e-04]], + [-233600.0, [38.093671910285, 30.880588383337, -1.843688067413], [-1.1317697153459e-03, 1.6128814698472e-03, 8.4177586176055e-04]], + [-204400.0, [-18.197852930878, 31.932869934309, 15.438294826279], [-1.9117272501813e-03, -1.9146495909842e-03, -1.9657304369835e-05]], + [-175200.0, [8.528924039997, -29.618422200048, -11.805400994258], [3.1034370787005e-03, 5.1393633292430e-04, -7.7293066202546e-04]], + [-146000.0, [40.946857258640, 25.904973592021, -4.256336240499], [-8.3652705194051e-04, 1.8129497136404e-03, 8.1564228273060e-04]], + [-116800.0, [-12.326958895325, 36.881883446292, 15.217158258711], [-2.1166103705038e-03, -1.4814420035990e-03, 1.7401209844705e-04]], + [-87600.0, [-0.633258375909, -30.018759794709, -9.171932874950], [3.2016994581737e-03, -2.5279858672148e-04, -1.0411088271861e-03]], + [-58400.0, [42.936048423883, 20.344685584452, -6.588027007912], [-5.0525450073192e-04, 1.9910074335507e-03, 7.7440196540269e-04]], + [-29200.0, [-5.975910552974, 40.611809958460, 14.470131723673], [-2.2184202156107e-03, -1.0562361130164e-03, 3.3652250216211e-04]], + [0.0, [-9.875369580774, -27.978926224737, -5.753711824704], [3.0287533248818e-03, -1.1276087003636e-03, -1.2651326732361e-03]], + [29200.0, [43.958831986165, 14.214147973292, -8.808306227163], [-1.4717608981871e-04, 2.1404187242141e-03, 7.1486567806614e-04]], + [58400.0, [0.678136763520, 43.094461639362, 13.243238780721], [-2.2358226110718e-03, -6.3233636090933e-04, 4.7664798895648e-04]], + [87600.0, [-18.282602096834, -23.305039586660, -1.766620508028], [2.5567245263557e-03, -1.9902940754171e-03, -1.3943491701082e-03]], + [116800.0, [43.873338744526, 7.700705617215, -10.814273666425], [2.3174803055677e-04, 2.2402163127924e-03, 6.2988756452032e-04]], + [146000.0, [7.392949027906, 44.382678951534, 11.629500214854], [-2.1932815453830e-03, -2.1751799585364e-04, 5.9556516201114e-04]], + [175200.0, [-24.981690229261, -16.204012851426, 2.466457544298], [1.8193989149580e-03, -2.6765419531201e-03, -1.3848283502247e-03]], + [204400.0, [42.530187039511, 0.845935508021, -12.554907527683], [6.5059779150669e-04, 2.2725657282262e-03, 5.1133743202822e-04]], + [233600.0, [13.999526486822, 44.462363044894, 9.669418486465], [-2.1079296569252e-03, 1.7533423831993e-04, 6.9128485798076e-04]], + [262800.0, [-29.184024803031, -7.371243995762, 6.493275957928], [9.3581363109681e-04, -3.0610357109184e-03, -1.2364201089345e-03]], + [292000.0, [39.831980671753, -6.078405766765, -13.909815358656], [1.1117769689167e-03, 2.2362097830152e-03, 3.6230548231153e-04]], + [321200.0, [20.294955108476, 43.417190420251, 7.450091985932], [-1.9742157451535e-03, 5.3102050468554e-04, 7.5938408813008e-04]], + [350400.0, [-30.669992302160, 2.318743558955, 9.973480913858], [4.5605107450676e-05, -3.1308219926928e-03, -9.9066533301924e-04]], + [379600.0, [35.626122155983, -12.897647509224, -14.777586508444], [1.6015684949743e-03, 2.1171931182284e-03, 1.8002516202204e-04]], + [408800.0, [26.133186148561, 41.232139187599, 5.006401326220], [-1.7857704419579e-03, 8.6046232702817e-04, 8.0614690298954e-04]], + [438000.0, [-29.576740229230, 11.863535943587, 12.631323039872], [-7.2292830060955e-04, -2.9587820140709e-03, -7.0824296450300e-04]], + [467200.0, [29.910805787391, -19.159019294000, -15.013363865194], [2.0871080437997e-03, 1.8848372554514e-03, -3.8528655083926e-05]], + [496400.0, [31.375957451819, 38.050372720763, 2.433138343754], [-1.5546055556611e-03, 1.1699815465629e-03, 8.3565439266001e-04]], + [525600.0, [-26.360071336928, 20.662505904952, 14.414696258958], [-1.3142373118349e-03, -2.6236647854842e-03, -4.2542017598193e-04]], + [554800.0, [22.599441488648, -24.508879898306, -14.484045731468], [2.5454108304806e-03, 1.4917058755191e-03, -3.0243665086079e-04]], + [584000.0, [35.877864013014, 33.894226366071, -0.224524636277], [-1.2941245730845e-03, 1.4560427668319e-03, 8.4762160640137e-04]], + [613200.0, [-21.538149762417, 28.204068269761, 15.321973799534], [-1.7312117409010e-03, -2.1939631314577e-03, -1.6316913275180e-04]], + [642400.0, [13.971521374415, -28.339941764789, -13.083792871886], [2.9334630526035e-03, 9.1860931752944e-04, -5.9939422488627e-04]], + [671600.0, [39.526942044143, 28.939897360110, -2.872799527539], [-1.0068481658095e-03, 1.7021132888090e-03, 8.3578230511981e-04]], + [700800.0, [-15.576200701394, 34.399412961275, 15.466033737854], [-2.0098814612884e-03, -1.7191109825989e-03, 7.0414782780416e-05]], + [730000.0, [4.243252837090, -30.118201690825, -10.707441231349], [3.1725847067411e-03, 1.6098461202270e-04, -9.0672150593868e-04]] +]; +class TerseVector { + constructor(x, y, z) { + this.x = x; + this.y = y; + this.z = z; + } + clone() { + return new TerseVector(this.x, this.y, this.z); + } + ToAstroVector(t) { + return new Vector(this.x, this.y, this.z, t); + } + static zero() { + return new TerseVector(0, 0, 0); + } + quadrature() { + return this.x * this.x + this.y * this.y + this.z * this.z; + } + add(other) { + return new TerseVector(this.x + other.x, this.y + other.y, this.z + other.z); + } + sub(other) { + return new TerseVector(this.x - other.x, this.y - other.y, this.z - other.z); + } + incr(other) { + this.x += other.x; + this.y += other.y; + this.z += other.z; + } + decr(other) { + this.x -= other.x; + this.y -= other.y; + this.z -= other.z; + } + mul(scalar) { + return new TerseVector(scalar * this.x, scalar * this.y, scalar * this.z); + } + div(scalar) { + return new TerseVector(this.x / scalar, this.y / scalar, this.z / scalar); + } + mean(other) { + return new TerseVector((this.x + other.x) / 2, (this.y + other.y) / 2, (this.z + other.z) / 2); + } + neg() { + return new TerseVector(-this.x, -this.y, -this.z); + } +} +class body_state_t { + constructor(tt, r, v) { + this.tt = tt; + this.r = r; + this.v = v; + } + clone() { + return new body_state_t(this.tt, this.r, this.v); + } + sub(other) { + return new body_state_t(this.tt, this.r.sub(other.r), this.v.sub(other.v)); + } +} +function BodyStateFromTable(entry) { + let [tt, [rx, ry, rz], [vx, vy, vz]] = entry; + return new body_state_t(tt, new TerseVector(rx, ry, rz), new TerseVector(vx, vy, vz)); +} +function AdjustBarycenterPosVel(ssb, tt, body, planet_gm) { + const shift = planet_gm / (planet_gm + SUN_GM); + const planet = CalcVsopPosVel(vsop[body], tt); + ssb.r.incr(planet.r.mul(shift)); + ssb.v.incr(planet.v.mul(shift)); + return planet; +} +function AccelerationIncrement(small_pos, gm, major_pos) { + const delta = major_pos.sub(small_pos); + const r2 = delta.quadrature(); + return delta.mul(gm / (r2 * Math.sqrt(r2))); +} +class major_bodies_t { + constructor(tt) { + // Accumulate the Solar System Barycenter position. + let ssb = new body_state_t(tt, new TerseVector(0, 0, 0), new TerseVector(0, 0, 0)); + this.Jupiter = AdjustBarycenterPosVel(ssb, tt, Body.Jupiter, JUPITER_GM); + this.Saturn = AdjustBarycenterPosVel(ssb, tt, Body.Saturn, SATURN_GM); + this.Uranus = AdjustBarycenterPosVel(ssb, tt, Body.Uranus, URANUS_GM); + this.Neptune = AdjustBarycenterPosVel(ssb, tt, Body.Neptune, NEPTUNE_GM); + // Convert planets' [pos, vel] vectors from heliocentric to barycentric. + this.Jupiter.r.decr(ssb.r); + this.Jupiter.v.decr(ssb.v); + this.Saturn.r.decr(ssb.r); + this.Saturn.v.decr(ssb.v); + this.Uranus.r.decr(ssb.r); + this.Uranus.v.decr(ssb.v); + this.Neptune.r.decr(ssb.r); + this.Neptune.v.decr(ssb.v); + // Convert heliocentric SSB to barycentric Sun. + this.Sun = new body_state_t(tt, ssb.r.mul(-1), ssb.v.mul(-1)); + } + Acceleration(pos) { + // Use barycentric coordinates of the Sun and major planets to calculate + // the gravitational acceleration vector experienced at location 'pos'. + let acc = AccelerationIncrement(pos, SUN_GM, this.Sun.r); + acc.incr(AccelerationIncrement(pos, JUPITER_GM, this.Jupiter.r)); + acc.incr(AccelerationIncrement(pos, SATURN_GM, this.Saturn.r)); + acc.incr(AccelerationIncrement(pos, URANUS_GM, this.Uranus.r)); + acc.incr(AccelerationIncrement(pos, NEPTUNE_GM, this.Neptune.r)); + return acc; + } +} +/** + * @ignore + * + * @brief The state of a body at an incremental step in a gravity simulation. + * + * This is an internal data structure used to represent the + * position, velocity, and acceleration vectors of a body + * in a gravity simulation at a given moment in time. + * + * @property tt + * The J2000 terrestrial time of the state [days]. + * + * @property r + * The position vector [au]. + * + * @property v + * The velocity vector [au/day]. + * + * @property a + * The acceleration vector [au/day^2]. + */ +class body_grav_calc_t { + constructor(tt, r, v, a) { + this.tt = tt; + this.r = r; + this.v = v; + this.a = a; + } + clone() { + return new body_grav_calc_t(this.tt, this.r.clone(), this.v.clone(), this.a.clone()); + } +} +class grav_sim_t { + constructor(bary, grav) { + this.bary = bary; + this.grav = grav; + } +} +function UpdatePosition(dt, r, v, a) { + return new TerseVector(r.x + dt * (v.x + dt * a.x / 2), r.y + dt * (v.y + dt * a.y / 2), r.z + dt * (v.z + dt * a.z / 2)); +} +function UpdateVelocity(dt, v, a) { + return new TerseVector(v.x + dt * a.x, v.y + dt * a.y, v.z + dt * a.z); +} +function GravSim(tt2, calc1) { + const dt = tt2 - calc1.tt; + // Calculate where the major bodies (Sun, Jupiter...Neptune) will be at tt2. + const bary2 = new major_bodies_t(tt2); + // Estimate position of small body as if current acceleration applies across the whole time interval. + const approx_pos = UpdatePosition(dt, calc1.r, calc1.v, calc1.a); + // Calculate the average acceleration of the endpoints. + // This becomes our estimate of the mean effective acceleration over the whole interval. + const mean_acc = bary2.Acceleration(approx_pos).mean(calc1.a); + // Refine the estimates of [pos, vel, acc] at tt2 using the mean acceleration. + const pos = UpdatePosition(dt, calc1.r, calc1.v, mean_acc); + const vel = calc1.v.add(mean_acc.mul(dt)); + const acc = bary2.Acceleration(pos); + const grav = new body_grav_calc_t(tt2, pos, vel, acc); + return new grav_sim_t(bary2, grav); +} +const pluto_cache = []; +function ClampIndex(frac, nsteps) { + const index = Math.floor(frac); + if (index < 0) + return 0; + if (index >= nsteps) + return nsteps - 1; + return index; +} +function GravFromState(entry) { + const state = BodyStateFromTable(entry); + const bary = new major_bodies_t(state.tt); + const r = state.r.add(bary.Sun.r); + const v = state.v.add(bary.Sun.v); + const a = bary.Acceleration(r); + const grav = new body_grav_calc_t(state.tt, r, v, a); + return new grav_sim_t(bary, grav); +} +function GetSegment(cache, tt) { + const t0 = PlutoStateTable[0][0]; + if (tt < t0 || tt > PlutoStateTable[PLUTO_NUM_STATES - 1][0]) { + // Don't bother calculating a segment. Let the caller crawl backward/forward to this time. + return null; + } + const seg_index = ClampIndex((tt - t0) / PLUTO_TIME_STEP, PLUTO_NUM_STATES - 1); + if (!cache[seg_index]) { + const seg = cache[seg_index] = []; + // Each endpoint is exact. + seg[0] = GravFromState(PlutoStateTable[seg_index]).grav; + seg[PLUTO_NSTEPS - 1] = GravFromState(PlutoStateTable[seg_index + 1]).grav; + // Simulate forwards from the lower time bound. + let i; + let step_tt = seg[0].tt; + for (i = 1; i < PLUTO_NSTEPS - 1; ++i) + seg[i] = GravSim(step_tt += PLUTO_DT, seg[i - 1]).grav; + // Simulate backwards from the upper time bound. + step_tt = seg[PLUTO_NSTEPS - 1].tt; + var reverse = []; + reverse[PLUTO_NSTEPS - 1] = seg[PLUTO_NSTEPS - 1]; + for (i = PLUTO_NSTEPS - 2; i > 0; --i) + reverse[i] = GravSim(step_tt -= PLUTO_DT, reverse[i + 1]).grav; + // Fade-mix the two series so that there are no discontinuities. + for (i = PLUTO_NSTEPS - 2; i > 0; --i) { + const ramp = i / (PLUTO_NSTEPS - 1); + seg[i].r = seg[i].r.mul(1 - ramp).add(reverse[i].r.mul(ramp)); + seg[i].v = seg[i].v.mul(1 - ramp).add(reverse[i].v.mul(ramp)); + seg[i].a = seg[i].a.mul(1 - ramp).add(reverse[i].a.mul(ramp)); + } + } + return cache[seg_index]; +} +function CalcPlutoOneWay(entry, target_tt, dt) { + let sim = GravFromState(entry); + const n = Math.ceil((target_tt - sim.grav.tt) / dt); + for (let i = 0; i < n; ++i) + sim = GravSim((i + 1 === n) ? target_tt : (sim.grav.tt + dt), sim.grav); + return sim; +} +function CalcPluto(time, helio) { + let r, v, bary; + const seg = GetSegment(pluto_cache, time.tt); + if (!seg) { + // The target time is outside the year range 0000..4000. + // Calculate it by crawling backward from 0000 or forward from 4000. + // FIXFIXFIX - This is super slow. Could optimize this with extra caching if needed. + let sim; + if (time.tt < PlutoStateTable[0][0]) + sim = CalcPlutoOneWay(PlutoStateTable[0], time.tt, -PLUTO_DT); + else + sim = CalcPlutoOneWay(PlutoStateTable[PLUTO_NUM_STATES - 1], time.tt, +PLUTO_DT); + r = sim.grav.r; + v = sim.grav.v; + bary = sim.bary; + } + else { + const left = ClampIndex((time.tt - seg[0].tt) / PLUTO_DT, PLUTO_NSTEPS - 1); + const s1 = seg[left]; + const s2 = seg[left + 1]; + // Find mean acceleration vector over the interval. + const acc = s1.a.mean(s2.a); + // Use Newtonian mechanics to extrapolate away from t1 in the positive time direction. + const ra = UpdatePosition(time.tt - s1.tt, s1.r, s1.v, acc); + const va = UpdateVelocity(time.tt - s1.tt, s1.v, acc); + // Use Newtonian mechanics to extrapolate away from t2 in the negative time direction. + const rb = UpdatePosition(time.tt - s2.tt, s2.r, s2.v, acc); + const vb = UpdateVelocity(time.tt - s2.tt, s2.v, acc); + // Use fade in/out idea to blend the two position estimates. + const ramp = (time.tt - s1.tt) / PLUTO_DT; + r = ra.mul(1 - ramp).add(rb.mul(ramp)); + v = va.mul(1 - ramp).add(vb.mul(ramp)); + } + if (helio) { + // Convert barycentric vectors to heliocentric vectors. + if (!bary) + bary = new major_bodies_t(time.tt); + r = r.sub(bary.Sun.r); + v = v.sub(bary.Sun.v); + } + return new StateVector(r.x, r.y, r.z, v.x, v.y, v.z, time); +} +; +const Rotation_JUP_EQJ = new RotationMatrix([ + [9.99432765338654e-01, -3.36771074697641e-02, 0.00000000000000e+00], + [3.03959428906285e-02, 9.02057912352809e-01, 4.30543388542295e-01], + [-1.44994559663353e-02, -4.30299169409101e-01, 9.02569881273754e-01] +]); +const JupiterMoonModel = [ + // [0] Io + { + mu: 2.8248942843381399e-07, + al: [1.4462132960212239e+00, 3.5515522861824000e+00], + a: [ + [0.0028210960212903, 0.0000000000000000e+00, 0.0000000000000000e+00] + ], + l: [ + [-0.0001925258348666, 4.9369589722644998e+00, 1.3584836583050000e-02], + [-0.0000970803596076, 4.3188796477322002e+00, 1.3034138432430000e-02], + [-0.0000898817416500, 1.9080016428616999e+00, 3.0506486715799999e-03], + [-0.0000553101050262, 1.4936156681568999e+00, 1.2938928911549999e-02] + ], + z: [ + [0.0041510849668155, 4.0899396355450000e+00, -1.2906864146660001e-02], + [0.0006260521444113, 1.4461888986270000e+00, 3.5515522949801999e+00], + [0.0000352747346169, 2.1256287034577999e+00, 1.2727416566999999e-04] + ], + zeta: [ + [0.0003142172466014, 2.7964219722923001e+00, -2.3150960980000000e-03], + [0.0000904169207946, 1.0477061879627001e+00, -5.6920638196000003e-04] + ] + }, + // [1] Europa + { + mu: 2.8248327439289299e-07, + al: [-3.7352634374713622e-01, 1.7693227111234699e+00], + a: [ + [0.0044871037804314, 0.0000000000000000e+00, 0.0000000000000000e+00], + [0.0000004324367498, 1.8196456062910000e+00, 1.7822295777568000e+00] + ], + l: [ + [0.0008576433172936, 4.3188693178264002e+00, 1.3034138308049999e-02], + [0.0004549582875086, 1.4936531751079001e+00, 1.2938928819619999e-02], + [0.0003248939825174, 1.8196494533458001e+00, 1.7822295777568000e+00], + [-0.0003074250079334, 4.9377037005910998e+00, 1.3584832867240000e-02], + [0.0001982386144784, 1.9079869054759999e+00, 3.0510121286900001e-03], + [0.0001834063551804, 2.1402853388529000e+00, 1.4500978933800000e-03], + [-0.0001434383188452, 5.6222140366630002e+00, 8.9111478887838003e-01], + [-0.0000771939140944, 4.3002724372349999e+00, 2.6733443704265998e+00] + ], + z: [ + [-0.0093589104136341, 4.0899396509038999e+00, -1.2906864146660001e-02], + [0.0002988994545555, 5.9097265185595003e+00, 1.7693227079461999e+00], + [0.0002139036390350, 2.1256289300016000e+00, 1.2727418406999999e-04], + [0.0001980963564781, 2.7435168292649998e+00, 6.7797343008999997e-04], + [0.0001210388158965, 5.5839943711203004e+00, 3.2056614899999997e-05], + [0.0000837042048393, 1.6094538368039000e+00, -9.0402165808846002e-01], + [0.0000823525166369, 1.4461887708689001e+00, 3.5515522949801999e+00] + ], + zeta: [ + [0.0040404917832303, 1.0477063169425000e+00, -5.6920640539999997e-04], + [0.0002200421034564, 3.3368857864364001e+00, -1.2491307306999999e-04], + [0.0001662544744719, 2.4134862374710999e+00, 0.0000000000000000e+00], + [0.0000590282470983, 5.9719930968366004e+00, -3.0561602250000000e-05] + ] + }, + // [2] Ganymede + { + mu: 2.8249818418472298e-07, + al: [2.8740893911433479e-01, 8.7820792358932798e-01], + a: [ + [0.0071566594572575, 0.0000000000000000e+00, 0.0000000000000000e+00], + [0.0000013930299110, 1.1586745884981000e+00, 2.6733443704265998e+00] + ], + l: [ + [0.0002310797886226, 2.1402987195941998e+00, 1.4500978438400001e-03], + [-0.0001828635964118, 4.3188672736968003e+00, 1.3034138282630000e-02], + [0.0001512378778204, 4.9373102372298003e+00, 1.3584834812520000e-02], + [-0.0001163720969778, 4.3002659861490002e+00, 2.6733443704265998e+00], + [-0.0000955478069846, 1.4936612842567001e+00, 1.2938928798570001e-02], + [0.0000815246854464, 5.6222137132535002e+00, 8.9111478887838003e-01], + [-0.0000801219679602, 1.2995922951532000e+00, 1.0034433456728999e+00], + [-0.0000607017260182, 6.4978769669238001e-01, 5.0172167043264004e-01] + ], + z: [ + [0.0014289811307319, 2.1256295942738999e+00, 1.2727413029000001e-04], + [0.0007710931226760, 5.5836330003496002e+00, 3.2064341100000001e-05], + [0.0005925911780766, 4.0899396636447998e+00, -1.2906864146660001e-02], + [0.0002045597496146, 5.2713683670371996e+00, -1.2523544076106000e-01], + [0.0001785118648258, 2.8743156721063001e-01, 8.7820792442520001e-01], + [0.0001131999784893, 1.4462127277818000e+00, 3.5515522949801999e+00], + [-0.0000658778169210, 2.2702423990985001e+00, -1.7951364394536999e+00], + [0.0000497058888328, 5.9096792204858000e+00, 1.7693227129285001e+00] + ], + zeta: [ + [0.0015932721570848, 3.3368862796665000e+00, -1.2491307058000000e-04], + [0.0008533093128905, 2.4133881688166001e+00, 0.0000000000000000e+00], + [0.0003513347911037, 5.9720789850126996e+00, -3.0561017709999999e-05], + [-0.0001441929255483, 1.0477061764435001e+00, -5.6920632124000004e-04] + ] + }, + // [3] Callisto + { + mu: 2.8249214488990899e-07, + al: [-3.6203412913757038e-01, 3.7648623343382798e-01], + a: [ + [0.0125879701715314, 0.0000000000000000e+00, 0.0000000000000000e+00], + [0.0000035952049470, 6.4965776007116005e-01, 5.0172168165034003e-01], + [0.0000027580210652, 1.8084235781510001e+00, 3.1750660413359002e+00] + ], + l: [ + [0.0005586040123824, 2.1404207189814999e+00, 1.4500979323100001e-03], + [-0.0003805813868176, 2.7358844897852999e+00, 2.9729650620000000e-05], + [0.0002205152863262, 6.4979652596399995e-01, 5.0172167243580001e-01], + [0.0001877895151158, 1.8084787604004999e+00, 3.1750660413359002e+00], + [0.0000766916975242, 6.2720114319754998e+00, 1.3928364636651001e+00], + [0.0000747056855106, 1.2995916202344000e+00, 1.0034433456728999e+00] + ], + z: [ + [0.0073755808467977, 5.5836071576083999e+00, 3.2065099140000001e-05], + [0.0002065924169942, 5.9209831565786004e+00, 3.7648624194703001e-01], + [0.0001589869764021, 2.8744006242622999e-01, 8.7820792442520001e-01], + [-0.0001561131605348, 2.1257397865089001e+00, 1.2727441285000001e-04], + [0.0001486043380971, 1.4462134301023000e+00, 3.5515522949801999e+00], + [0.0000635073108731, 5.9096803285953996e+00, 1.7693227129285001e+00], + [0.0000599351698525, 4.1125517584797997e+00, -2.7985797954588998e+00], + [0.0000540660842731, 5.5390350845569003e+00, 2.8683408228299999e-03], + [-0.0000489596900866, 4.6218149483337996e+00, -6.2695712529518999e-01] + ], + zeta: [ + [0.0038422977898495, 2.4133922085556998e+00, 0.0000000000000000e+00], + [0.0022453891791894, 5.9721736773277003e+00, -3.0561255249999997e-05], + [-0.0002604479450559, 3.3368746306408998e+00, -1.2491309972000001e-04], + [0.0000332112143230, 5.5604137742336999e+00, 2.9003768850700000e-03] + ] + } +]; +/** + * @brief Holds the positions and velocities of Jupiter's major 4 moons. + * + * The {@link JupiterMoons} function returns an object of this type + * to report position and velocity vectors for Jupiter's largest 4 moons + * Io, Europa, Ganymede, and Callisto. Each position vector is relative + * to the center of Jupiter. Both position and velocity are oriented in + * the EQJ system (that is, using Earth's equator at the J2000 epoch). + * The positions are expressed in astronomical units (AU), + * and the velocities in AU/day. + * + * @property {StateVector} io + * The position and velocity of Jupiter's moon Io. + * + * @property {StateVector} europa + * The position and velocity of Jupiter's moon Europa. + * + * @property {StateVector} ganymede + * The position and velocity of Jupiter's moon Ganymede. + * + * @property {StateVector} callisto + * The position and velocity of Jupiter's moon Callisto. + */ +export class JupiterMoonsInfo { + constructor(io, europa, ganymede, callisto) { + this.io = io; + this.europa = europa; + this.ganymede = ganymede; + this.callisto = callisto; + } +} +function JupiterMoon_elem2pv(time, mu, elem) { + // Translation of FORTRAN subroutine ELEM2PV from: + // https://ftp.imcce.fr/pub/ephem/satel/galilean/L1/L1.2/ + const A = elem[0]; + const AL = elem[1]; + const K = elem[2]; + const H = elem[3]; + const Q = elem[4]; + const P = elem[5]; + const AN = Math.sqrt(mu / (A * A * A)); + let CE, SE, DE; + let EE = AL + K * Math.sin(AL) - H * Math.cos(AL); + do { + CE = Math.cos(EE); + SE = Math.sin(EE); + DE = (AL - EE + K * SE - H * CE) / (1.0 - K * CE - H * SE); + EE += DE; + } while (Math.abs(DE) >= 1.0e-12); + CE = Math.cos(EE); + SE = Math.sin(EE); + const DLE = H * CE - K * SE; + const RSAM1 = -K * CE - H * SE; + const ASR = 1.0 / (1.0 + RSAM1); + const PHI = Math.sqrt(1.0 - K * K - H * H); + const PSI = 1.0 / (1.0 + PHI); + const X1 = A * (CE - K - PSI * H * DLE); + const Y1 = A * (SE - H + PSI * K * DLE); + const VX1 = AN * ASR * A * (-SE - PSI * H * RSAM1); + const VY1 = AN * ASR * A * (+CE + PSI * K * RSAM1); + const F2 = 2.0 * Math.sqrt(1.0 - Q * Q - P * P); + const P2 = 1.0 - 2.0 * P * P; + const Q2 = 1.0 - 2.0 * Q * Q; + const PQ = 2.0 * P * Q; + return new StateVector(X1 * P2 + Y1 * PQ, X1 * PQ + Y1 * Q2, (Q * Y1 - X1 * P) * F2, VX1 * P2 + VY1 * PQ, VX1 * PQ + VY1 * Q2, (Q * VY1 - VX1 * P) * F2, time); +} +function CalcJupiterMoon(time, m) { + // This is a translation of FORTRAN code by Duriez, Lainey, and Vienne: + // https://ftp.imcce.fr/pub/ephem/satel/galilean/L1/L1.2/ + const t = time.tt + 18262.5; // number of days since 1950-01-01T00:00:00Z + // Calculate 6 orbital elements at the given time t + const elem = [0, m.al[0] + (t * m.al[1]), 0, 0, 0, 0]; + for (let [amplitude, phase, frequency] of m.a) + elem[0] += amplitude * Math.cos(phase + (t * frequency)); + for (let [amplitude, phase, frequency] of m.l) + elem[1] += amplitude * Math.sin(phase + (t * frequency)); + elem[1] %= PI2; + if (elem[1] < 0) + elem[1] += PI2; + for (let [amplitude, phase, frequency] of m.z) { + const arg = phase + (t * frequency); + elem[2] += amplitude * Math.cos(arg); + elem[3] += amplitude * Math.sin(arg); + } + for (let [amplitude, phase, frequency] of m.zeta) { + const arg = phase + (t * frequency); + elem[4] += amplitude * Math.cos(arg); + elem[5] += amplitude * Math.sin(arg); + } + // Convert the oribital elements into position vectors in the Jupiter equatorial system (JUP). + const state = JupiterMoon_elem2pv(time, m.mu, elem); + // Re-orient position and velocity vectors from Jupiter-equatorial (JUP) to Earth-equatorial in J2000 (EQJ). + return RotateState(Rotation_JUP_EQJ, state); +} +/** + * @brief Calculates jovicentric positions and velocities of Jupiter's largest 4 moons. + * + * Calculates position and velocity vectors for Jupiter's moons + * Io, Europa, Ganymede, and Callisto, at the given date and time. + * The vectors are jovicentric (relative to the center of Jupiter). + * Their orientation is the Earth's equatorial system at the J2000 epoch (EQJ). + * The position components are expressed in astronomical units (AU), and the + * velocity components are in AU/day. + * + * To convert to heliocentric vectors, call {@link HelioVector} + * with `Astronomy.Body.Jupiter` to get Jupiter's heliocentric position, then + * add the jovicentric vectors. Likewise, you can call {@link GeoVector} + * to convert to geocentric vectors. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate Jupiter's moons. + * + * @return {JupiterMoonsInfo} + * Position and velocity vectors of Jupiter's largest 4 moons. + */ +export function JupiterMoons(date) { + const time = new AstroTime(date); + return new JupiterMoonsInfo(CalcJupiterMoon(time, JupiterMoonModel[0]), CalcJupiterMoon(time, JupiterMoonModel[1]), CalcJupiterMoon(time, JupiterMoonModel[2]), CalcJupiterMoon(time, JupiterMoonModel[3])); +} +// Jupiter Moons ends -------------------------------------------------------- +/** + * @brief Calculates a vector from the center of the Sun to the given body at the given time. + * + * Calculates heliocentric (i.e., with respect to the center of the Sun) + * Cartesian coordinates in the J2000 equatorial system of a celestial + * body at a specified time. The position is not corrected for light travel time or aberration. + * + * @param {Body} body + * One of the following values: + * `Body.Sun`, `Body.Moon`, `Body.Mercury`, `Body.Venus`, + * `Body.Earth`, `Body.Mars`, `Body.Jupiter`, `Body.Saturn`, + * `Body.Uranus`, `Body.Neptune`, `Body.Pluto`, + * `Body.SSB`, or `Body.EMB`. + * Also allowed to be a user-defined star created by {@link DefineStar}. + * + * @param {FlexibleDateTime} date + * The date and time for which the body's position is to be calculated. + * + * @returns {Vector} + */ +export function HelioVector(body, date) { + var time = MakeTime(date); + if (body in vsop) + return CalcVsop(vsop[body], time); + if (body === Body.Pluto) { + const p = CalcPluto(time, true); + return new Vector(p.x, p.y, p.z, time); + } + if (body === Body.Sun) + return new Vector(0, 0, 0, time); + if (body === Body.Moon) { + var e = CalcVsop(vsop.Earth, time); + var m = GeoMoon(time); + return new Vector(e.x + m.x, e.y + m.y, e.z + m.z, time); + } + if (body === Body.EMB) { + const e = CalcVsop(vsop.Earth, time); + const m = GeoMoon(time); + const denom = 1.0 + EARTH_MOON_MASS_RATIO; + return new Vector(e.x + (m.x / denom), e.y + (m.y / denom), e.z + (m.z / denom), time); + } + if (body === Body.SSB) + return CalcSolarSystemBarycenter(time); + const star = UserDefinedStar(body); + if (star) { + const sphere = new Spherical(star.dec, 15 * star.ra, star.dist); + return VectorFromSphere(sphere, time); + } + throw `HelioVector: Unknown body "${body}"`; +} +; +/** + * @brief Calculates the distance between a body and the Sun at a given time. + * + * Given a date and time, this function calculates the distance between + * the center of `body` and the center of the Sun. + * For the planets Mercury through Neptune, this function is significantly + * more efficient than calling {@link HelioVector} followed by taking the length + * of the resulting vector. + * + * @param {Body} body + * A body for which to calculate a heliocentric distance: + * the Sun, Moon, any of the planets, or a user-defined star. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the heliocentric distance. + * + * @returns {number} + * The heliocentric distance in AU. + */ +export function HelioDistance(body, date) { + const star = UserDefinedStar(body); + if (star) + return star.dist; + const time = MakeTime(date); + if (body in vsop) + return VsopFormula(vsop[body][RAD_INDEX], time.tt / DAYS_PER_MILLENNIUM, false); + return HelioVector(body, time).Length(); +} +/** + * Solve for light travel time of a vector function. + * + * When observing a distant object, for example Jupiter as seen from Earth, + * the amount of time it takes for light to travel from the object to the + * observer can significantly affect the object's apparent position. + * This function is a generic solver that figures out how long in the + * past light must have left the observed object to reach the observer + * at the specified observation time. It requires passing in `func` + * to express an arbitrary position vector as a function of time. + * + * `CorrectLightTravel` repeatedly calls `func`, passing a series of time + * estimates in the past. Then `func` must return a relative position vector between + * the observer and the target. `CorrectLightTravel` keeps calling + * `func` with more and more refined estimates of the time light must have + * left the target to arrive at the observer. + * + * For common use cases, it is simpler to use {@link BackdatePosition} + * for calculating the light travel time correction of one body observing another body. + * + * For geocentric calculations, {@link GeoVector} also backdates the returned + * position vector for light travel time, only it returns the observation time in + * the returned vector's `t` field rather than the backdated time. + * + * @param {function(AstroTime): number} func + * An arbitrary position vector as a function of time: + * function({@link AstroTime}) => {@link Vector}. + * + * @param {AstroTime} time + * The observation time for which to solve for light travel delay. + * + * @returns {AstroVector} + * The position vector at the solved backdated time. + * The `t` field holds the time that light left the observed + * body to arrive at the observer at the observation time. + */ +export function CorrectLightTravel(func, time) { + let ltime = time; + let dt = 0; + for (let iter = 0; iter < 10; ++iter) { + const pos = func(ltime); + const lt = pos.Length() / C_AUDAY; + // This solver does not support more than one light-day of distance, + // because that would cause convergence problems and inaccurate + // values for stellar aberration angles. + if (lt > 1.0) + throw `Object is too distant for light-travel solver.`; + const ltime2 = time.AddDays(-lt); + dt = Math.abs(ltime2.tt - ltime.tt); + if (dt < 1.0e-9) // 86.4 microseconds + return pos; + ltime = ltime2; + } + throw `Light-travel time solver did not converge: dt = ${dt}`; +} +class BodyPosition { + constructor(observerBody, targetBody, aberration, observerPos) { + this.observerBody = observerBody; + this.targetBody = targetBody; + this.aberration = aberration; + this.observerPos = observerPos; + } + Position(time) { + if (this.aberration) { + // The following discussion is worded with the observer body being the Earth, + // which is often the case. However, the same reasoning applies to any observer body + // without loss of generality. + // + // To include aberration, make a good first-order approximation + // by backdating the Earth's position also. + // This is confusing, but it works for objects within the Solar System + // because the distance the Earth moves in that small amount of light + // travel time (a few minutes to a few hours) is well approximated + // by a line segment that substends the angle seen from the remote + // body viewing Earth. That angle is pretty close to the aberration + // angle of the moving Earth viewing the remote body. + // In other words, both of the following approximate the aberration angle: + // (transverse distance Earth moves) / (distance to body) + // (transverse speed of Earth) / (speed of light). + this.observerPos = HelioVector(this.observerBody, time); + } + else { + // No aberration, so use the pre-calculated initial position of + // the observer body that is already stored in `observerPos`. + } + const targetPos = HelioVector(this.targetBody, time); + return new Vector(targetPos.x - this.observerPos.x, targetPos.y - this.observerPos.y, targetPos.z - this.observerPos.z, time); + } +} +/** + * @brief Solve for light travel time correction of apparent position. + * + * When observing a distant object, for example Jupiter as seen from Earth, + * the amount of time it takes for light to travel from the object to the + * observer can significantly affect the object's apparent position. + * + * This function solves the light travel time correction for the apparent + * relative position vector of a target body as seen by an observer body + * at a given observation time. + * + * For geocentric calculations, {@link GeoVector} also includes light + * travel time correction, but the time `t` embedded in its returned vector + * refers to the observation time, not the backdated time that light left + * the observed body. Thus `BackdatePosition` provides direct + * access to the light departure time for callers that need it. + * + * For a more generalized light travel correction solver, see {@link CorrectLightTravel}. + * + * @param {FlexibleDateTime} date + * The time of observation. + * + * @param {Body} observerBody + * The body to be used as the observation location. + * + * @param {Body} targetBody + * The body to be observed. + * + * @param {boolean} aberration + * `true` to correct for aberration, or `false` to leave uncorrected. + * + * @returns {Vector} + * The position vector at the solved backdated time. + * The `t` field holds the time that light left the observed + * body to arrive at the observer at the observation time. + */ +export function BackdatePosition(date, observerBody, targetBody, aberration) { + VerifyBoolean(aberration); + const time = MakeTime(date); + if (UserDefinedStar(targetBody)) { + // This is a user-defined star, which must be treated as a special case. + // First, we assume its heliocentric position does not change with time. + // Second, we assume its heliocentric position has already been corrected + // for light-travel time, its coordinates given as it appears on Earth at the present. + // Therefore, no backdating is applied. + const tvec = HelioVector(targetBody, time); + if (aberration) { + // (Observer velocity) - (light vector) = (Aberration-corrected direction to target body). + // Note that this is an approximation, because technically the light vector should + // be measured in barycentric coordinates, not heliocentric. The error is very small. + const ostate = HelioState(observerBody, time); + const rvec = new Vector(tvec.x - ostate.x, tvec.y - ostate.y, tvec.z - ostate.z, time); + const s = C_AUDAY / rvec.Length(); // conversion factor from relative distance to speed of light + return new Vector(rvec.x + ostate.vx / s, rvec.y + ostate.vy / s, rvec.z + ostate.vz / s, time); + } + // No correction is needed. Simply return the star's current position as seen from the observer. + const ovec = HelioVector(observerBody, time); + return new Vector(tvec.x - ovec.x, tvec.y - ovec.y, tvec.z - ovec.z, time); + } + let observerPos; + if (aberration) { + // With aberration, `BackdatePosition` will calculate `observerPos` at different times. + // Therefore, do not waste time calculating it now. + // Create a placeholder value that will be ignored. + observerPos = new Vector(0, 0, 0, time); + } + else { + observerPos = HelioVector(observerBody, time); + } + const bpos = new BodyPosition(observerBody, targetBody, aberration, observerPos); + return CorrectLightTravel(t => bpos.Position(t), time); +} +/** + * @brief Calculates a vector from the center of the Earth to the given body at the given time. + * + * Calculates geocentric (i.e., with respect to the center of the Earth) + * Cartesian coordinates in the J2000 equatorial system of a celestial + * body at a specified time. The position is always corrected for light travel time: + * this means the position of the body is "back-dated" based on how long it + * takes light to travel from the body to an observer on the Earth. + * Also, the position can optionally be corrected for aberration, an effect + * causing the apparent direction of the body to be shifted based on + * transverse movement of the Earth with respect to the rays of light + * coming from that body. + * + * @param {Body} body + * One of the following values: + * `Body.Sun`, `Body.Moon`, `Body.Mercury`, `Body.Venus`, + * `Body.Earth`, `Body.Mars`, `Body.Jupiter`, `Body.Saturn`, + * `Body.Uranus`, `Body.Neptune`, or `Body.Pluto`. + * Also allowed to be a user-defined star created with {@link DefineStar}. + * + * @param {FlexibleDateTime} date + * The date and time for which the body's position is to be calculated. + * + * @param {boolean} aberration + * Pass `true` to correct for + * aberration, + * or `false` to leave uncorrected. + * + * @returns {Vector} + */ +export function GeoVector(body, date, aberration) { + VerifyBoolean(aberration); + const time = MakeTime(date); + switch (body) { + case Body.Earth: + return new Vector(0, 0, 0, time); + case Body.Moon: + return GeoMoon(time); + default: + const vec = BackdatePosition(time, Body.Earth, body, aberration); + vec.t = time; // tricky: return the observation time, not the backdated time + return vec; + } +} +function ExportState(terse, time) { + return new StateVector(terse.r.x, terse.r.y, terse.r.z, terse.v.x, terse.v.y, terse.v.z, time); +} +/** + * @brief Calculates barycentric position and velocity vectors for the given body. + * + * Given a body and a time, calculates the barycentric position and velocity + * vectors for the center of that body at that time. + * The vectors are expressed in J2000 mean equator coordinates (EQJ). + * + * @param {Body} body + * The celestial body whose barycentric state vector is to be calculated. + * Supported values are `Body.Sun`, `Body.Moon`, `Body.EMB`, `Body.SSB`, and all planets: + * `Body.Mercury`, `Body.Venus`, `Body.Earth`, `Body.Mars`, `Body.Jupiter`, + * `Body.Saturn`, `Body.Uranus`, `Body.Neptune`, `Body.Pluto`. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate position and velocity. + * + * @returns {StateVector} + * An object that contains barycentric position and velocity vectors. + */ +export function BaryState(body, date) { + const time = MakeTime(date); + if (body === Body.SSB) { + // Trivial case: the solar system barycenter itself. + return new StateVector(0, 0, 0, 0, 0, 0, time); + } + if (body === Body.Pluto) { + return CalcPluto(time, false); + } + // Find the barycentric positions and velocities for the 5 major bodies: + // Sun, Jupiter, Saturn, Uranus, Neptune. + const bary = new major_bodies_t(time.tt); + switch (body) { + case Body.Sun: return ExportState(bary.Sun, time); + case Body.Jupiter: return ExportState(bary.Jupiter, time); + case Body.Saturn: return ExportState(bary.Saturn, time); + case Body.Uranus: return ExportState(bary.Uranus, time); + case Body.Neptune: return ExportState(bary.Neptune, time); + case Body.Moon: + case Body.EMB: + const earth = CalcVsopPosVel(vsop[Body.Earth], time.tt); + const state = (body === Body.Moon) ? GeoMoonState(time) : GeoEmbState(time); + return new StateVector(state.x + bary.Sun.r.x + earth.r.x, state.y + bary.Sun.r.y + earth.r.y, state.z + bary.Sun.r.z + earth.r.z, state.vx + bary.Sun.v.x + earth.v.x, state.vy + bary.Sun.v.y + earth.v.y, state.vz + bary.Sun.v.z + earth.v.z, time); + } + // Handle the remaining VSOP bodies: Mercury, Venus, Earth, Mars. + if (body in vsop) { + const planet = CalcVsopPosVel(vsop[body], time.tt); + return new StateVector(bary.Sun.r.x + planet.r.x, bary.Sun.r.y + planet.r.y, bary.Sun.r.z + planet.r.z, bary.Sun.v.x + planet.v.x, bary.Sun.v.y + planet.v.y, bary.Sun.v.z + planet.v.z, time); + } + throw `BaryState: Unsupported body "${body}"`; +} +/** + * @brief Calculates heliocentric position and velocity vectors for the given body. + * + * Given a body and a time, calculates the position and velocity + * vectors for the center of that body at that time, relative to the center of the Sun. + * The vectors are expressed in J2000 mean equator coordinates (EQJ). + * If you need the position vector only, it is more efficient to call {@link HelioVector}. + * The Sun's center is a non-inertial frame of reference. In other words, the Sun + * experiences acceleration due to gravitational forces, mostly from the larger + * planets (Jupiter, Saturn, Uranus, and Neptune). If you want to calculate momentum, + * kinetic energy, or other quantities that require a non-accelerating frame + * of reference, consider using {@link BaryState} instead. + * + * @param {Body} body + * The celestial body whose heliocentric state vector is to be calculated. + * Supported values are `Body.Sun`, `Body.Moon`, `Body.EMB`, `Body.SSB`, and all planets: + * `Body.Mercury`, `Body.Venus`, `Body.Earth`, `Body.Mars`, `Body.Jupiter`, + * `Body.Saturn`, `Body.Uranus`, `Body.Neptune`, `Body.Pluto`. + * Also allowed to be a user-defined star created by {@link DefineStar}. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate position and velocity. + * + * @returns {StateVector} + * An object that contains heliocentric position and velocity vectors. + */ +export function HelioState(body, date) { + const time = MakeTime(date); + switch (body) { + case Body.Sun: + // Trivial case: the Sun is the origin of the heliocentric frame. + return new StateVector(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, time); + case Body.SSB: + // Calculate the barycentric Sun. Then the negative of that is the heliocentric SSB. + const bary = new major_bodies_t(time.tt); + return new StateVector(-bary.Sun.r.x, -bary.Sun.r.y, -bary.Sun.r.z, -bary.Sun.v.x, -bary.Sun.v.y, -bary.Sun.v.z, time); + case Body.Mercury: + case Body.Venus: + case Body.Earth: + case Body.Mars: + case Body.Jupiter: + case Body.Saturn: + case Body.Uranus: + case Body.Neptune: + // Planets included in the VSOP87 model. + const planet = CalcVsopPosVel(vsop[body], time.tt); + return ExportState(planet, time); + case Body.Pluto: + return CalcPluto(time, true); + case Body.Moon: + case Body.EMB: + const earth = CalcVsopPosVel(vsop.Earth, time.tt); + const state = (body == Body.Moon) ? GeoMoonState(time) : GeoEmbState(time); + return new StateVector(state.x + earth.r.x, state.y + earth.r.y, state.z + earth.r.z, state.vx + earth.v.x, state.vy + earth.v.y, state.vz + earth.v.z, time); + default: + if (UserDefinedStar(body)) { + const vec = HelioVector(body, time); + return new StateVector(vec.x, vec.y, vec.z, 0, 0, 0, time); + } + throw `HelioState: Unsupported body "${body}"`; + } +} +function QuadInterp(tm, dt, fa, fm, fb) { + let Q = (fb + fa) / 2 - fm; + let R = (fb - fa) / 2; + let S = fm; + let x; + if (Q == 0) { + // This is a line, not a parabola. + if (R == 0) { + // This is a HORIZONTAL line... can't make progress! + return null; + } + x = -S / R; + if (x < -1 || x > +1) + return null; // out of bounds + } + else { + // It really is a parabola. Find roots x1, x2. + let u = R * R - 4 * Q * S; + if (u <= 0) + return null; + let ru = Math.sqrt(u); + let x1 = (-R + ru) / (2 * Q); + let x2 = (-R - ru) / (2 * Q); + if (-1 <= x1 && x1 <= +1) { + if (-1 <= x2 && x2 <= +1) + return null; + x = x1; + } + else if (-1 <= x2 && x2 <= +1) { + x = x2; + } + else { + return null; + } + } + let t = tm + x * dt; + let df_dt = (2 * Q * x + R) / dt; + return { t: t, df_dt: df_dt }; +} +/** + * @brief Options for the {@link Search} function. + * + * @typedef {object} SearchOptions + * + * @property {number | undefined} dt_tolerance_seconds + * The number of seconds for a time window smaller than which the search + * is considered successful. Using too large a tolerance can result in + * an inaccurate time estimate. Using too small a tolerance can cause + * excessive computation, or can even cause the search to fail because of + * limited floating-point resolution. Defaults to 1 second. + * + * @property {number | undefined} init_f1 + * As an optimization, if the caller of {@link Search} + * has already calculated the value of the function being searched (the parameter `func`) + * at the time coordinate `t1`, it can pass in that value as `init_f1`. + * For very expensive calculations, this can measurably improve performance. + * + * @property {number | undefined} init_f2 + * The same as `init_f1`, except this is the optional initial value of `func(t2)` + * instead of `func(t1)`. + * + * @property {number | undefined} iter_limit + */ +/** + * @brief Finds the time when a function ascends through zero. + * + * Search for next time t (such that t is between `t1` and `t2`) + * that `func(t)` crosses from a negative value to a non-negative value. + * The given function must have "smooth" behavior over the entire inclusive range [`t1`, `t2`], + * meaning that it behaves like a continuous differentiable function. + * It is not required that `t1` < `t2`; `t1` > `t2` + * allows searching backward in time. + * Note: `t1` and `t2` must be chosen such that there is no possibility + * of more than one zero-crossing (ascending or descending), or it is possible + * that the "wrong" event will be found (i.e. not the first event after t1) + * or even that the function will return `null`, indicating that no event was found. + * + * @param {function(AstroTime): number} func + * The function to find an ascending zero crossing for. + * The function must accept a single parameter of type {@link AstroTime} + * and return a numeric value: + * function({@link AstroTime}) => `number` + * + * @param {AstroTime} t1 + * The lower time bound of a search window. + * + * @param {AstroTime} t2 + * The upper time bound of a search window. + * + * @param {SearchOptions | undefined} options + * Options that can tune the behavior of the search. + * Most callers can omit this argument. + * + * @returns {AstroTime | null} + * If the search is successful, returns the date and time of the solution. + * If the search fails, returns `null`. + */ +export function Search(f, t1, t2, options) { + const dt_tolerance_seconds = VerifyNumber((options && options.dt_tolerance_seconds) || 1); + const dt_days = Math.abs(dt_tolerance_seconds / SECONDS_PER_DAY); + let f1 = (options && options.init_f1) || f(t1); + let f2 = (options && options.init_f2) || f(t2); + let fmid = NaN; + let iter = 0; + let iter_limit = (options && options.iter_limit) || 20; + let calc_fmid = true; + while (true) { + if (++iter > iter_limit) + throw `Excessive iteration in Search()`; + let tmid = InterpolateTime(t1, t2, 0.5); + let dt = tmid.ut - t1.ut; + if (Math.abs(dt) < dt_days) { + // We are close enough to the event to stop the search. + return tmid; + } + if (calc_fmid) + fmid = f(tmid); + else + calc_fmid = true; // we already have the correct value of fmid from the previous loop + // Quadratic interpolation: + // Try to find a parabola that passes through the 3 points we have sampled: + // (t1,f1), (tmid,fmid), (t2,f2). + let q = QuadInterp(tmid.ut, t2.ut - tmid.ut, f1, fmid, f2); + // Did we find an approximate root-crossing? + if (q) { + // Evaluate the function at our candidate solution. + let tq = MakeTime(q.t); + let fq = f(tq); + if (q.df_dt !== 0) { + if (Math.abs(fq / q.df_dt) < dt_days) { + // The estimated time error is small enough that we can quit now. + return tq; + } + // Try guessing a tighter boundary with the interpolated root at the center. + let dt_guess = 1.2 * Math.abs(fq / q.df_dt); + if (dt_guess < dt / 10) { + let tleft = tq.AddDays(-dt_guess); + let tright = tq.AddDays(+dt_guess); + if ((tleft.ut - t1.ut) * (tleft.ut - t2.ut) < 0) { + if ((tright.ut - t1.ut) * (tright.ut - t2.ut) < 0) { + let fleft = f(tleft); + let fright = f(tright); + if (fleft < 0 && fright >= 0) { + f1 = fleft; + f2 = fright; + t1 = tleft; + t2 = tright; + fmid = fq; + calc_fmid = false; + continue; + } + } + } + } + } + } + if (f1 < 0 && fmid >= 0) { + t2 = tmid; + f2 = fmid; + continue; + } + if (fmid < 0 && f2 >= 0) { + t1 = tmid; + f1 = fmid; + continue; + } + // Either there is no ascending zero-crossing in this range + // or the search window is too wide. + return null; + } +} +function LongitudeOffset(diff) { + let offset = diff; + while (offset <= -180) + offset += 360; + while (offset > 180) + offset -= 360; + return offset; +} +function NormalizeLongitude(lon) { + while (lon < 0) + lon += 360; + while (lon >= 360) + lon -= 360; + return lon; +} +/** + * @brief Searches for when the Sun reaches a given ecliptic longitude. + * + * Searches for the moment in time when the center of the Sun reaches a given apparent + * ecliptic longitude, as seen from the center of the Earth, within a given range of dates. + * This function can be used to determine equinoxes and solstices. + * However, it is usually more convenient and efficient to call {@link Seasons} + * to calculate equinoxes and solstices for a given calendar year. + * `SearchSunLongitude` is more general in that it allows searching for arbitrary longitude values. + * + * @param {number} targetLon + * The desired ecliptic longitude of date in degrees. + * This may be any value in the range [0, 360), although certain + * values have conventional meanings: + * + * When `targetLon` is 0, finds the March equinox, + * which is the moment spring begins in the northern hemisphere + * and the beginning of autumn in the southern hemisphere. + * + * When `targetLon` is 180, finds the September equinox, + * which is the moment autumn begins in the northern hemisphere and + * spring begins in the southern hemisphere. + * + * When `targetLon` is 90, finds the northern solstice, which is the + * moment summer begins in the northern hemisphere and winter + * begins in the southern hemisphere. + * + * When `targetLon` is 270, finds the southern solstice, which is the + * moment winter begins in the northern hemisphere and summer + * begins in the southern hemisphere. + * + * @param {FlexibleDateTime} dateStart + * A date and time known to be earlier than the desired longitude event. + * + * @param {number} limitDays + * A floating point number of days, which when added to `dateStart`, + * yields a date and time known to be after the desired longitude event. + * + * @returns {AstroTime | null} + * The date and time when the Sun reaches the apparent ecliptic longitude `targetLon` + * within the range of times specified by `dateStart` and `limitDays`. + * If the Sun does not reach the target longitude within the specified time range, or the + * time range is excessively wide, the return value is `null`. + * To avoid a `null` return value, the caller must pick a time window around + * the event that is within a few days but not so small that the event might fall outside the window. + */ +export function SearchSunLongitude(targetLon, dateStart, limitDays) { + function sun_offset(t) { + let pos = SunPosition(t); + return LongitudeOffset(pos.elon - targetLon); + } + VerifyNumber(targetLon); + VerifyNumber(limitDays); + let t1 = MakeTime(dateStart); + let t2 = t1.AddDays(limitDays); + return Search(sun_offset, t1, t2, { dt_tolerance_seconds: 0.01 }); +} +/** + * @brief Returns one body's ecliptic longitude with respect to another, as seen from the Earth. + * + * This function determines where one body appears around the ecliptic plane + * (the plane of the Earth's orbit around the Sun) as seen from the Earth, + * relative to the another body's apparent position. + * The function returns an angle in the half-open range [0, 360) degrees. + * The value is the ecliptic longitude of `body1` relative to the ecliptic + * longitude of `body2`. + * + * The angle is 0 when the two bodies are at the same ecliptic longitude + * as seen from the Earth. The angle increases in the prograde direction + * (the direction that the planets orbit the Sun and the Moon orbits the Earth). + * + * When the angle is 180 degrees, it means the two bodies appear on opposite sides + * of the sky for an Earthly observer. + * + * Neither `body1` nor `body2` is allowed to be `Body.Earth`. + * If this happens, the function throws an exception. + * + * @param {Body} body1 + * The first body, whose longitude is to be found relative to the second body. + * + * @param {Body} body2 + * The second body, relative to which the longitude of the first body is to be found. + * + * @param {FlexibleDateTime} date + * The date and time of the observation. + * + * @returns {number} + * An angle in the range [0, 360), expressed in degrees. + */ +export function PairLongitude(body1, body2, date) { + if (body1 === Body.Earth || body2 === Body.Earth) + throw 'The Earth does not have a longitude as seen from itself.'; + const time = MakeTime(date); + const vector1 = GeoVector(body1, time, false); + const eclip1 = Ecliptic(vector1); + const vector2 = GeoVector(body2, time, false); + const eclip2 = Ecliptic(vector2); + return NormalizeLongitude(eclip1.elon - eclip2.elon); +} +/** + * @brief Calculates the angular separation between the Sun and the given body. + * + * Returns the full angle seen from + * the Earth, between the given body and the Sun. + * Unlike {@link PairLongitude}, this function does not + * project the body's "shadow" onto the ecliptic; + * the angle is measured in 3D space around the plane that + * contains the centers of the Earth, the Sun, and `body`. + * + * @param {Body} body + * The name of a supported celestial body other than the Earth. + * + * @param {FlexibleDateTime} date + * The time at which the angle from the Sun is to be found. + * + * @returns {number} + * An angle in degrees in the range [0, 180]. + */ +export function AngleFromSun(body, date) { + if (body == Body.Earth) + throw 'The Earth does not have an angle as seen from itself.'; + const time = MakeTime(date); + const sv = GeoVector(Body.Sun, time, true); + const bv = GeoVector(body, time, true); + const angle = AngleBetween(sv, bv); + return angle; +} +/** + * @brief Calculates heliocentric ecliptic longitude of a body. + * + * This function calculates the angle around the plane of the Earth's orbit + * of a celestial body, as seen from the center of the Sun. + * The angle is measured prograde (in the direction of the Earth's orbit around the Sun) + * in degrees from the true equinox of date. The ecliptic longitude is always in the range [0, 360). + * + * @param {Body} body + * A body other than the Sun. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the ecliptic longitude. + * + * @returns {number} + */ +export function EclipticLongitude(body, date) { + if (body === Body.Sun) + throw 'Cannot calculate heliocentric longitude of the Sun.'; + const hv = HelioVector(body, date); + const eclip = Ecliptic(hv); + return eclip.elon; +} +function VisualMagnitude(body, phase, helio_dist, geo_dist) { + // For Mercury and Venus, see: https://iopscience.iop.org/article/10.1086/430212 + let c0, c1 = 0, c2 = 0, c3 = 0; + switch (body) { + case Body.Mercury: + c0 = -0.60; + c1 = +4.98; + c2 = -4.88; + c3 = +3.02; + break; + case Body.Venus: + if (phase < 163.6) { + c0 = -4.47; + c1 = +1.03; + c2 = +0.57; + c3 = +0.13; + } + else { + c0 = 0.98; + c1 = -1.02; + } + break; + case Body.Mars: + c0 = -1.52; + c1 = +1.60; + break; + case Body.Jupiter: + c0 = -9.40; + c1 = +0.50; + break; + case Body.Uranus: + c0 = -7.19; + c1 = +0.25; + break; + case Body.Neptune: + c0 = -6.87; + break; + case Body.Pluto: + c0 = -1.00; + c1 = +4.00; + break; + default: throw `VisualMagnitude: unsupported body ${body}`; + } + const x = phase / 100; + let mag = c0 + x * (c1 + x * (c2 + x * c3)); + mag += 5 * Math.log10(helio_dist * geo_dist); + return mag; +} +function SaturnMagnitude(phase, helio_dist, geo_dist, gc, time) { + // Based on formulas by Paul Schlyter found here: + // http://www.stjarnhimlen.se/comp/ppcomp.html#15 + // We must handle Saturn's rings as a major component of its visual magnitude. + // Find geocentric ecliptic coordinates of Saturn. + const eclip = Ecliptic(gc); + const ir = DEG2RAD * 28.06; // tilt of Saturn's rings to the ecliptic, in radians + const Nr = DEG2RAD * (169.51 + (3.82e-5 * time.tt)); // ascending node of Saturn's rings, in radians + // Find tilt of Saturn's rings, as seen from Earth. + const lat = DEG2RAD * eclip.elat; + const lon = DEG2RAD * eclip.elon; + const tilt = Math.asin(Math.sin(lat) * Math.cos(ir) - Math.cos(lat) * Math.sin(ir) * Math.sin(lon - Nr)); + const sin_tilt = Math.sin(Math.abs(tilt)); + let mag = -9.0 + 0.044 * phase; + mag += sin_tilt * (-2.6 + 1.2 * sin_tilt); + mag += 5 * Math.log10(helio_dist * geo_dist); + return { mag: mag, ring_tilt: RAD2DEG * tilt }; +} +function MoonMagnitude(phase, helio_dist, geo_dist) { + // https://astronomy.stackexchange.com/questions/10246/is-there-a-simple-analytical-formula-for-the-lunar-phase-brightness-curve + let rad = phase * DEG2RAD; + let rad2 = rad * rad; + let rad4 = rad2 * rad2; + let mag = -12.717 + 1.49 * Math.abs(rad) + 0.0431 * rad4; + const moon_mean_distance_au = 385000.6 / KM_PER_AU; + let geo_au = geo_dist / moon_mean_distance_au; + mag += 5 * Math.log10(helio_dist * geo_au); + return mag; +} +/** + * @brief Information about the apparent brightness and sunlit phase of a celestial object. + * + * @property {AstroTime} time + * The date and time pertaining to the other calculated values in this object. + * + * @property {number} mag + * The apparent visual magnitude of the celestial body. + * + * @property {number} phase_angle + * The angle in degrees as seen from the center of the celestial body between the Sun and the Earth. + * The value is always in the range 0 to 180. + * The phase angle provides a measure of what fraction of the body's face appears + * illuminated by the Sun as seen from the Earth. + * When the observed body is the Sun, the `phase` property is set to 0, + * although this has no physical meaning because the Sun emits, rather than reflects, light. + * When the phase is near 0 degrees, the body appears "full". + * When it is 90 degrees, the body appears "half full". + * And when it is 180 degrees, the body appears "new" and is very difficult to see + * because it is both dim and lost in the Sun's glare as seen from the Earth. + * + * @property {number} phase_fraction + * The fraction of the body's face that is illuminated by the Sun, as seen from the Earth. + * Calculated from `phase_angle` for convenience. + * This value ranges from 0 to 1. + * + * @property {number} helio_dist + * The distance between the center of the Sun and the center of the body in + * astronomical units (AU). + * + * @property {number} geo_dist + * The distance between the center of the Earth and the center of the body in AU. + * + * @property {Vector} gc + * Geocentric coordinates: the 3D vector from the center of the Earth to the center of the body. + * The components are in expressed in AU and are oriented with respect to the J2000 equatorial plane. + * + * @property {Vector} hc + * Heliocentric coordinates: The 3D vector from the center of the Sun to the center of the body. + * Like `gc`, `hc` is expressed in AU and oriented with respect + * to the J2000 equatorial plane. + * + * @property {number | undefined} ring_tilt + * For Saturn, this is the angular tilt of the planet's rings in degrees away + * from the line of sight from the Earth. When the value is near 0, the rings + * appear edge-on from the Earth and are therefore difficult to see. + * When `ring_tilt` approaches its maximum value (about 27 degrees), + * the rings appear widest and brightest from the Earth. + * Unlike the JPL Horizons online tool, + * this library includes the effect of the ring tilt angle in the calculated value + * for Saturn's visual magnitude. + * For all bodies other than Saturn, the value of `ring_tilt` is `undefined`. + */ +export class IlluminationInfo { + constructor(time, mag, phase_angle, helio_dist, geo_dist, gc, hc, ring_tilt) { + this.time = time; + this.mag = mag; + this.phase_angle = phase_angle; + this.helio_dist = helio_dist; + this.geo_dist = geo_dist; + this.gc = gc; + this.hc = hc; + this.ring_tilt = ring_tilt; + this.phase_fraction = (1 + Math.cos(DEG2RAD * phase_angle)) / 2; + } +} +/** + * @brief Calculates visual magnitude and related information about a body. + * + * Calculates the phase angle, visual magnitude, + * and other values relating to the body's illumination + * at the given date and time, as seen from the Earth. + * + * @param {Body} body + * The name of the celestial body being observed. + * Not allowed to be `Body.Earth`. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the illumination data for the given body. + * + * @returns {IlluminationInfo} + */ +export function Illumination(body, date) { + if (body === Body.Earth) + throw `The illumination of the Earth is not defined.`; + const time = MakeTime(date); + const earth = CalcVsop(vsop.Earth, time); + let phase; // phase angle in degrees between Earth and Sun as seen from body + let hc; // vector from Sun to body + let gc; // vector from Earth to body + let mag; // visual magnitude + if (body === Body.Sun) { + gc = new Vector(-earth.x, -earth.y, -earth.z, time); + hc = new Vector(0, 0, 0, time); + phase = 0; // a placeholder value; the Sun does not have an illumination phase because it emits, rather than reflects, light. + } + else { + if (body === Body.Moon) { + // For extra numeric precision, use geocentric moon formula directly. + gc = GeoMoon(time); + hc = new Vector(earth.x + gc.x, earth.y + gc.y, earth.z + gc.z, time); + } + else { + // For planets, heliocentric vector is most direct to calculate. + hc = HelioVector(body, date); + gc = new Vector(hc.x - earth.x, hc.y - earth.y, hc.z - earth.z, time); + } + phase = AngleBetween(gc, hc); + } + let geo_dist = gc.Length(); // distance from body to center of Earth + let helio_dist = hc.Length(); // distance from body to center of Sun + let ring_tilt; // only reported for Saturn + if (body === Body.Sun) { + mag = SUN_MAG_1AU + 5 * Math.log10(geo_dist); + } + else if (body === Body.Moon) { + mag = MoonMagnitude(phase, helio_dist, geo_dist); + } + else if (body === Body.Saturn) { + const saturn = SaturnMagnitude(phase, helio_dist, geo_dist, gc, time); + mag = saturn.mag; + ring_tilt = saturn.ring_tilt; + } + else { + mag = VisualMagnitude(body, phase, helio_dist, geo_dist); + } + return new IlluminationInfo(time, mag, phase, helio_dist, geo_dist, gc, hc, ring_tilt); +} +function SynodicPeriod(body) { + if (body === Body.Earth) + throw 'The Earth does not have a synodic period as seen from itself.'; + if (body === Body.Moon) + return MEAN_SYNODIC_MONTH; + // Calculate the synodic period of the planet from its and the Earth's sidereal periods. + // The sidereal period of a planet is how long it takes to go around the Sun in days, on average. + // The synodic period of a planet is how long it takes between consecutive oppositions + // or conjunctions, on average. + let planet = Planet[body]; + if (!planet) + throw `Not a valid planet name: ${body}`; + // See here for explanation of the formula: + // https://en.wikipedia.org/wiki/Elongation_(astronomy)#Elongation_period + const Te = Planet.Earth.OrbitalPeriod; + const Tp = planet.OrbitalPeriod; + const synodicPeriod = Math.abs(Te / (Te / Tp - 1)); + return synodicPeriod; +} +/** + * @brief Searches for when the Earth and a given body reach a relative ecliptic longitude separation. + * + * Searches for the date and time the relative ecliptic longitudes of + * the specified body and the Earth, as seen from the Sun, reach a certain + * difference. This function is useful for finding conjunctions and oppositions + * of the planets. For the opposition of a superior planet (Mars, Jupiter, ..., Pluto), + * or the inferior conjunction of an inferior planet (Mercury, Venus), + * call with `targetRelLon` = 0. The 0 value indicates that both + * planets are on the same ecliptic longitude line, ignoring the other planet's + * distance above or below the plane of the Earth's orbit. + * For superior conjunctions, call with `targetRelLon` = 180. + * This means the Earth and the other planet are on opposite sides of the Sun. + * + * @param {Body} body + * Any planet other than the Earth. + * + * @param {number} targetRelLon + * The desired angular difference in degrees between the ecliptic longitudes + * of `body` and the Earth. Must be in the range (-180, +180]. + * + * @param {FlexibleDateTime} startDate + * The date and time after which to find the next occurrence of the + * body and the Earth reaching the desired relative longitude. + * + * @returns {AstroTime} + * The time when the Earth and the body next reach the specified relative longitudes. + */ +export function SearchRelativeLongitude(body, targetRelLon, startDate) { + VerifyNumber(targetRelLon); + const planet = Planet[body]; + if (!planet) + throw `Cannot search relative longitude because body is not a planet: ${body}`; + if (body === Body.Earth) + throw 'Cannot search relative longitude for the Earth (it is always 0)'; + // Determine whether the Earth "gains" (+1) on the planet or "loses" (-1) + // as both race around the Sun. + const direction = (planet.OrbitalPeriod > Planet.Earth.OrbitalPeriod) ? +1 : -1; + function offset(t) { + const plon = EclipticLongitude(body, t); + const elon = EclipticLongitude(Body.Earth, t); + const diff = direction * (elon - plon); + return LongitudeOffset(diff - targetRelLon); + } + let syn = SynodicPeriod(body); + let time = MakeTime(startDate); + // Iterate until we converge on the desired event. + // Calculate the error angle, which will be a negative number of degrees, + // meaning we are "behind" the target relative longitude. + let error_angle = offset(time); + if (error_angle > 0) + error_angle -= 360; // force searching forward in time + for (let iter = 0; iter < 100; ++iter) { + // Estimate how many days in the future (positive) or past (negative) + // we have to go to get closer to the target relative longitude. + let day_adjust = (-error_angle / 360) * syn; + time = time.AddDays(day_adjust); + if (Math.abs(day_adjust) * SECONDS_PER_DAY < 1) + return time; + let prev_angle = error_angle; + error_angle = offset(time); + if (Math.abs(prev_angle) < 30) { + // Improve convergence for Mercury/Mars (eccentric orbits) + // by adjusting the synodic period to more closely match the + // variable speed of both planets in this part of their respective orbits. + if (prev_angle !== error_angle) { + let ratio = prev_angle / (prev_angle - error_angle); + if (ratio > 0.5 && ratio < 2.0) + syn *= ratio; + } + } + } + throw `Relative longitude search failed to converge for ${body} near ${time.toString()} (error_angle = ${error_angle}).`; +} +/** + * @brief Determines the moon's phase expressed as an ecliptic longitude. + * + * @param {FlexibleDateTime} date + * The date and time for which to calculate the moon's phase. + * + * @returns {number} + * A value in the range [0, 360) indicating the difference + * in ecliptic longitude between the center of the Sun and the + * center of the Moon, as seen from the center of the Earth. + * Certain longitude values have conventional meanings: + * + * * 0 = new moon + * * 90 = first quarter + * * 180 = full moon + * * 270 = third quarter + */ +export function MoonPhase(date) { + return PairLongitude(Body.Moon, Body.Sun, date); +} +/** + * @brief Searches for the date and time that the Moon reaches a specified phase. + * + * Lunar phases are defined in terms of geocentric ecliptic longitudes + * with respect to the Sun. When the Moon and the Sun have the same ecliptic + * longitude, that is defined as a new moon. When the two ecliptic longitudes + * are 180 degrees apart, that is defined as a full moon. + * To enumerate quarter lunar phases, it is simpler to call + * {@link SearchMoonQuarter} once, followed by repeatedly calling + * {@link NextMoonQuarter}. `SearchMoonPhase` is only + * necessary for finding other lunar phases than the usual quarter phases. + * + * @param {number} targetLon + * The difference in geocentric ecliptic longitude between the Sun and Moon + * that specifies the lunar phase being sought. This can be any value + * in the range [0, 360). Here are some helpful examples: + * 0 = new moon, + * 90 = first quarter, + * 180 = full moon, + * 270 = third quarter. + * + * @param {FlexibleDateTime} dateStart + * The beginning of the window of time in which to search. + * + * @param {number} limitDays + * The floating point number of days away from `dateStart` + * that limits the window of time in which to search. + * If the value is negative, the search is performed into the past from `startTime`. + * Otherwise, the search is performed into the future from `startTime`. + * + * @returns {AstroTime | null} + * If successful, returns the date and time the moon reaches the phase specified by `targetlon`. + * This function will return `null` if the phase does not occur within `limitDays` of `startTime`; + * that is, if the search window is too small. + */ +export function SearchMoonPhase(targetLon, dateStart, limitDays) { + function moon_offset(t) { + let mlon = MoonPhase(t); + return LongitudeOffset(mlon - targetLon); + } + VerifyNumber(targetLon); + VerifyNumber(limitDays); + // To avoid discontinuities in the moon_offset function causing problems, + // we need to approximate when that function will next return 0. + // We probe it with the start time and take advantage of the fact + // that every lunar phase repeats roughly every 29.5 days. + // There is a surprising uncertainty in the quarter timing, + // due to the eccentricity of the moon's orbit. + // I have seen more than 0.9 days away from the simple prediction. + // To be safe, we take the predicted time of the event and search + // +/-1.5 days around it (a 3.0-day wide window). + // But we must return null if the final result goes beyond limitDays after dateStart. + const uncertainty = 1.5; + const ta = MakeTime(dateStart); + let ya = moon_offset(ta); + let est_dt, dt1, dt2; + if (limitDays < 0) { + // Search backward in time. + if (ya < 0) + ya += 360; + est_dt = -(MEAN_SYNODIC_MONTH * ya) / 360; + dt2 = est_dt + uncertainty; + if (dt2 < limitDays) + return null; // not possible for moon phase to occur within the specified window + dt1 = Math.max(limitDays, est_dt - uncertainty); + } + else { + // Search forward in time. + if (ya > 0) + ya -= 360; + est_dt = -(MEAN_SYNODIC_MONTH * ya) / 360; + dt1 = est_dt - uncertainty; + if (dt1 > limitDays) + return null; // not possible for moon phase to occur within the specified window + dt2 = Math.min(limitDays, est_dt + uncertainty); + } + const t1 = ta.AddDays(dt1); + const t2 = ta.AddDays(dt2); + return Search(moon_offset, t1, t2, { dt_tolerance_seconds: 0.1 }); +} +/** + * @brief A quarter lunar phase, along with when it occurs. + * + * @property {number} quarter + * An integer as follows: + * 0 = new moon, + * 1 = first quarter, + * 2 = full moon, + * 3 = third quarter. + * + * @property {AstroTime} time + * The date and time of the quarter lunar phase. + */ +export class MoonQuarter { + constructor(quarter, time) { + this.quarter = quarter; + this.time = time; + } +} +/** + * @brief Finds the first quarter lunar phase after the specified date and time. + * + * The quarter lunar phases are: new moon, first quarter, full moon, and third quarter. + * To enumerate quarter lunar phases, call `SearchMoonQuarter` once, + * then pass its return value to {@link NextMoonQuarter} to find the next + * `MoonQuarter`. Keep calling `NextMoonQuarter` in a loop, + * passing the previous return value as the argument to the next call. + * + * @param {FlexibleDateTime} dateStart + * The date and time after which to find the first quarter lunar phase. + * + * @returns {MoonQuarter} + */ +export function SearchMoonQuarter(dateStart) { + // Determine what the next quarter phase will be. + let phaseStart = MoonPhase(dateStart); + let quarterStart = Math.floor(phaseStart / 90); + let quarter = (quarterStart + 1) % 4; + let time = SearchMoonPhase(90 * quarter, dateStart, 10); + if (!time) + throw 'Cannot find moon quarter'; + return new MoonQuarter(quarter, time); +} +/** + * @brief Finds the next quarter lunar phase in a series. + * + * Given a {@link MoonQuarter} object, finds the next consecutive + * quarter lunar phase. See remarks in {@link SearchMoonQuarter} + * for explanation of usage. + * + * @param {MoonQuarter} mq + * The return value of a prior call to {@link MoonQuarter} or `NextMoonQuarter`. + * + * @returns {MoonQuarter} + */ +export function NextMoonQuarter(mq) { + // Skip 6 days past the previous found moon quarter to find the next one. + // This is less than the minimum possible increment. + // So far I have seen the interval well contained by the range (6.5, 8.3) days. + let date = new Date(mq.time.date.getTime() + 6 * MILLIS_PER_DAY); + return SearchMoonQuarter(date); +} +/** + * @brief Information about idealized atmospheric variables at a given elevation. + * + * @property {number} pressure + * Atmospheric pressure in pascals. + * + * @property {number} temperature + * Atmospheric temperature in kelvins. + * + * @property {number} density + * Atmospheric density relative to sea level. + */ +export class AtmosphereInfo { + constructor(pressure, temperature, density) { + this.pressure = pressure; + this.temperature = temperature; + this.density = density; + } +} +/** + * @brief Calculates U.S. Standard Atmosphere (1976) variables as a function of elevation. + * + * This function calculates idealized values of pressure, temperature, and density + * using the U.S. Standard Atmosphere (1976) model. + * 1. COESA, U.S. Standard Atmosphere, 1976, U.S. Government Printing Office, Washington, DC, 1976. + * 2. Jursa, A. S., Ed., Handbook of Geophysics and the Space Environment, Air Force Geophysics Laboratory, 1985. + * See: + * https://hbcp.chemnetbase.com/faces/documents/14_12/14_12_0001.xhtml + * https://ntrs.nasa.gov/api/citations/19770009539/downloads/19770009539.pdf + * https://www.ngdc.noaa.gov/stp/space-weather/online-publications/miscellaneous/us-standard-atmosphere-1976/us-standard-atmosphere_st76-1562_noaa.pdf + * + * @param {number} elevationMeters + * The elevation above sea level at which to calculate atmospheric variables. + * Must be in the range -500 to +100000, or an exception will occur. + * + * @returns {AtmosphereInfo} + */ +export function Atmosphere(elevationMeters) { + const P0 = 101325.0; // pressure at sea level [pascals] + const T0 = 288.15; // temperature at sea level [kelvins] + const T1 = 216.65; // temperature between 20 km and 32 km [kelvins] + if (!Number.isFinite(elevationMeters) || elevationMeters < -500.0 || elevationMeters > 100000.0) + throw `Invalid elevation: ${elevationMeters}`; + let temperature; + let pressure; + if (elevationMeters <= 11000.0) { + temperature = T0 - 0.0065 * elevationMeters; + pressure = P0 * Math.pow(T0 / temperature, -5.25577); + } + else if (elevationMeters <= 20000.0) { + temperature = T1; + pressure = 22632.0 * Math.exp(-0.00015768832 * (elevationMeters - 11000.0)); + } + else { + temperature = T1 + 0.001 * (elevationMeters - 20000.0); + pressure = 5474.87 * Math.pow(T1 / temperature, 34.16319); + } + // The density is calculated relative to the sea level value. + // Using the ideal gas law PV=nRT, we deduce that density is proportional to P/T. + const density = (pressure / temperature) / (P0 / T0); + return new AtmosphereInfo(pressure, temperature, density); +} +function HorizonDipAngle(observer, metersAboveGround) { + // Calculate the effective radius of the Earth at ground level below the observer. + // Correct for the Earth's oblateness. + const phi = observer.latitude * DEG2RAD; + const sinphi = Math.sin(phi); + const cosphi = Math.cos(phi); + const c = 1.0 / Math.hypot(cosphi, sinphi * EARTH_FLATTENING); + const s = c * (EARTH_FLATTENING * EARTH_FLATTENING); + const ht_km = (observer.height - metersAboveGround) / 1000.0; // height of ground above sea level + const ach = EARTH_EQUATORIAL_RADIUS_KM * c + ht_km; + const ash = EARTH_EQUATORIAL_RADIUS_KM * s + ht_km; + const radius_m = 1000.0 * Math.hypot(ach * cosphi, ash * sinphi); + // Correct refraction of a ray of light traveling tangent to the Earth's surface. + // Based on: https://www.largeformatphotography.info/sunmooncalc/SMCalc.js + // which in turn derives from: + // Sweer, John. 1938. The Path of a Ray of Light Tangent to the Surface of the Earth. + // Journal of the Optical Society of America 28 (September):327-329. + // k = refraction index + const k = 0.175 * Math.pow(1.0 - (6.5e-3 / 283.15) * (observer.height - (2.0 / 3.0) * metersAboveGround), 3.256); + // Calculate how far below the observer's horizontal plane the observed horizon dips. + return RAD2DEG * -(Math.sqrt(2 * (1 - k) * metersAboveGround / radius_m) / (1 - k)); +} +function BodyRadiusAu(body) { + // For the purposes of calculating rise/set times, + // only the Sun and Moon appear large enough to an observer + // on the Earth for their radius to matter. + // All other bodies are treated as points. + switch (body) { + case Body.Sun: return SUN_RADIUS_AU; + case Body.Moon: return MOON_EQUATORIAL_RADIUS_AU; + default: return 0; + } +} +/** + * @brief Searches for the next time a celestial body rises or sets as seen by an observer on the Earth. + * + * This function finds the next rise or set time of the Sun, Moon, or planet other than the Earth. + * Rise time is when the body first starts to be visible above the horizon. + * For example, sunrise is the moment that the top of the Sun first appears to peek above the horizon. + * Set time is the moment when the body appears to vanish below the horizon. + * Therefore, this function adjusts for the apparent angular radius of the observed body + * (significant only for the Sun and Moon). + * + * This function corrects for a typical value of atmospheric refraction, which causes celestial + * bodies to appear higher above the horizon than they would if the Earth had no atmosphere. + * Astronomy Engine uses a correction of 34 arcminutes. Real-world refraction varies based + * on air temperature, pressure, and humidity; such weather-based conditions are outside + * the scope of Astronomy Engine. + * + * Note that rise or set may not occur in every 24 hour period. + * For example, near the Earth's poles, there are long periods of time where + * the Sun stays below the horizon, never rising. + * Also, it is possible for the Moon to rise just before midnight but not set during the subsequent 24-hour day. + * This is because the Moon sets nearly an hour later each day due to orbiting the Earth a + * significant amount during each rotation of the Earth. + * Therefore callers must not assume that the function will always succeed. + * + * @param {Body} body + * The Sun, Moon, any planet other than the Earth, + * or a user-defined star that was created by a call to {@link DefineStar}. + * + * @param {Observer} observer + * Specifies the geographic coordinates and elevation above sea level of the observer. + * + * @param {number} direction + * Either +1 to find rise time or -1 to find set time. + * Any other value will cause an exception to be thrown. + * + * @param {FlexibleDateTime} dateStart + * The date and time after which the specified rise or set time is to be found. + * + * @param {number} limitDays + * Limits how many days to search for a rise or set time, and defines + * the direction in time to search. When `limitDays` is positive, the + * search is performed into the future, after `dateStart`. + * When negative, the search is performed into the past, before `dateStart`. + * To limit a rise or set time to the same day, you can use a value of 1 day. + * In cases where you want to find the next rise or set time no matter how far + * in the future (for example, for an observer near the south pole), you can + * pass in a larger value like 365. + * + * @param {number?} metersAboveGround + * Defaults to 0.0 if omitted. + * Usually the observer is located at ground level. Then this parameter + * should be zero. But if the observer is significantly higher than ground + * level, for example in an airplane, this parameter should be a positive + * number indicating how far above the ground the observer is. + * An exception occurs if `metersAboveGround` is negative. + * + * @returns {AstroTime | null} + * The date and time of the rise or set event, or null if no such event + * occurs within the specified time window. + */ +export function SearchRiseSet(body, observer, direction, dateStart, limitDays, metersAboveGround = 0.0) { + if (!Number.isFinite(metersAboveGround) || (metersAboveGround < 0.0)) + throw `Invalid value for metersAboveGround: ${metersAboveGround}`; + // We want to find when the top of the body crosses the horizon, not the body's center. + // Therefore, we need to know the body's radius. + const body_radius_au = BodyRadiusAu(body); + // Calculate atmospheric density at ground level. + const atmos = Atmosphere(observer.height - metersAboveGround); + // Calculate the apparent angular dip of the horizon. + const dip = HorizonDipAngle(observer, metersAboveGround); + // Correct refraction for objects near the horizon, using atmospheric density at the ground. + const altitude = dip - (REFRACTION_NEAR_HORIZON * atmos.density); + // Search for the top of the body crossing the corrected altitude angle. + return InternalSearchAltitude(body, observer, direction, dateStart, limitDays, body_radius_au, altitude); +} +/** + * @brief Finds the next time the center of a body passes through a given altitude. + * + * Finds when the center of the given body ascends or descends through a given + * altitude angle, as seen by an observer at the specified location on the Earth. + * By using the appropriate combination of `direction` and `altitude` parameters, + * this function can be used to find when civil, nautical, or astronomical twilight + * begins (dawn) or ends (dusk). + * + * Civil dawn begins before sunrise when the Sun ascends through 6 degrees below + * the horizon. To find civil dawn, pass +1 for `direction` and -6 for `altitude`. + * + * Civil dusk ends after sunset when the Sun descends through 6 degrees below the horizon. + * To find civil dusk, pass -1 for `direction` and -6 for `altitude`. + * + * Nautical twilight is similar to civil twilight, only the `altitude` value should be -12 degrees. + * + * Astronomical twilight uses -18 degrees as the `altitude` value. + * + * By convention for twilight time calculations, the altitude is not corrected for + * atmospheric refraction. This is because the target altitudes are below the horizon, + * and refraction is not directly observable. + * + * `SearchAltitude` is not intended to find rise/set times of a body for two reasons: + * (1) Rise/set times of the Sun or Moon are defined by their topmost visible portion, not their centers. + * (2) Rise/set times are affected significantly by atmospheric refraction. + * Therefore, it is better to use {@link SearchRiseSet} to find rise/set times, which + * corrects for both of these considerations. + * + * `SearchAltitude` will not work reliably for altitudes at or near the body's + * maximum or minimum altitudes. To find the time a body reaches minimum or maximum altitude + * angles, use {@link SearchHourAngle}. + * + * @param {Body} body + * The Sun, Moon, any planet other than the Earth, + * or a user-defined star that was created by a call to {@link DefineStar}. + * + * @param {Observer} observer + * Specifies the geographic coordinates and elevation above sea level of the observer. + * + * @param {number} direction + * Either +1 to find when the body ascends through the altitude, + * or -1 for when the body descends through the altitude. + * Any other value will cause an exception to be thrown. + * + * @param {FlexibleDateTime} dateStart + * The date and time after which the specified altitude event is to be found. + * + * @param {number} limitDays + * Limits how many days to search for the body reaching the altitude angle, + * and defines the direction in time to search. When `limitDays` is positive, the + * search is performed into the future, after `dateStart`. + * When negative, the search is performed into the past, before `dateStart`. + * To limit the search to the same day, you can use a value of 1 day. + * In cases where you want to find the altitude event no matter how far + * in the future (for example, for an observer near the south pole), you can + * pass in a larger value like 365. + * + * @param {number} altitude + * The desired altitude angle of the body's center above (positive) + * or below (negative) the observer's local horizon, expressed in degrees. + * Must be in the range [-90, +90]. + * + * @returns {AstroTime | null} + * The date and time of the altitude event, or null if no such event + * occurs within the specified time window. + */ +export function SearchAltitude(body, observer, direction, dateStart, limitDays, altitude) { + if (!Number.isFinite(altitude) || altitude < -90 || altitude > +90) + throw `Invalid altitude angle: ${altitude}`; + return InternalSearchAltitude(body, observer, direction, dateStart, limitDays, 0, altitude); +} +class AscentInfo { + constructor(tx, ty, ax, ay) { + this.tx = tx; + this.ty = ty; + this.ax = ax; + this.ay = ay; + } +} +function FindAscent(depth, altdiff, max_deriv_alt, t1, t2, a1, a2) { + // See if we can find any time interval where the altitude-diff function + // rises from non-positive to positive. + if (a1 < 0.0 && a2 >= 0.0) { + // Trivial success case: the endpoints already rise through zero. + return new AscentInfo(t1, t2, a1, a2); + } + if (a1 >= 0.0 && a2 < 0.0) { + // Trivial failure case: Assume Nyquist condition prevents an ascent. + return null; + } + if (depth > 17) { + // Safety valve: do not allow unlimited recursion. + // This should never happen if the rest of the logic is working correctly, + // so fail the whole search if it does happen. It's a bug! + throw `Excessive recursion in rise/set ascent search.`; + } + // Both altitudes are on the same side of zero: both are negative, or both are non-negative. + // There could be a convex "hill" or a concave "valley" that passes through zero. + // In polar regions sometimes there is a rise/set or set/rise pair within minutes of each other. + // For example, the Moon can be below the horizon, then the very top of it becomes + // visible (moonrise) for a few minutes, then it moves sideways and down below + // the horizon again (moonset). We want to catch these cases. + // However, for efficiency and practicality concerns, because the rise/set search itself + // has a 0.1 second threshold, we do not worry about rise/set pairs that are less than + // one second apart. These are marginal cases that are rendered highly uncertain + // anyway, due to unpredictable atmospheric refraction conditions (air temperature and pressure). + const dt = t2.ut - t1.ut; + if (dt * SECONDS_PER_DAY < 1.0) + return null; + // Is it possible to reach zero from the altitude that is closer to zero? + const da = Math.min(Math.abs(a1), Math.abs(a2)); + // Without loss of generality, assume |a1| <= |a2|. + // (Reverse the argument in the case |a2| < |a1|.) + // Imagine you have to "drive" from a1 to 0, then back to a2. + // You can't go faster than max_deriv_alt. If you can't reach 0 in half the time, + // you certainly don't have time to reach 0, turn around, and still make your way + // back up to a2 (which is at least as far from 0 than a1 is) in the time interval dt. + // Therefore, the time threshold is half the time interval, or dt/2. + if (da > max_deriv_alt * (dt / 2)) { + // Prune: the altitude cannot change fast enough to reach zero. + return null; + } + // Bisect the time interval and evaluate the altitude at the midpoint. + const tmid = new AstroTime((t1.ut + t2.ut) / 2); + const amid = altdiff(tmid); + // Use recursive bisection to search for a solution bracket. + return (FindAscent(1 + depth, altdiff, max_deriv_alt, t1, tmid, a1, amid) || + FindAscent(1 + depth, altdiff, max_deriv_alt, tmid, t2, amid, a2)); +} +function MaxAltitudeSlope(body, latitude) { + // Calculate the maximum possible rate that this body's altitude + // could change [degrees/day] as seen by this observer. + // First use experimentally determined extreme bounds for this body + // of how much topocentric RA and DEC can ever change per rate of time. + // We need minimum possible d(RA)/dt, and maximum possible magnitude of d(DEC)/dt. + // Conservatively, we round d(RA)/dt down, d(DEC)/dt up. + // Then calculate the resulting maximum possible altitude change rate. + if (latitude < -90 || latitude > +90) + throw `Invalid geographic latitude: ${latitude}`; + let deriv_ra; + let deriv_dec; + switch (body) { + case Body.Moon: + deriv_ra = +4.5; + deriv_dec = +8.2; + break; + case Body.Sun: + deriv_ra = +0.8; + deriv_dec = +0.5; + break; + case Body.Mercury: + deriv_ra = -1.6; + deriv_dec = +1.0; + break; + case Body.Venus: + deriv_ra = -0.8; + deriv_dec = +0.6; + break; + case Body.Mars: + deriv_ra = -0.5; + deriv_dec = +0.4; + break; + case Body.Jupiter: + case Body.Saturn: + case Body.Uranus: + case Body.Neptune: + case Body.Pluto: + deriv_ra = -0.2; + deriv_dec = +0.2; + break; + case Body.Star1: + case Body.Star2: + case Body.Star3: + case Body.Star4: + case Body.Star5: + case Body.Star6: + case Body.Star7: + case Body.Star8: + // The minimum allowed heliocentric distance of a user-defined star + // is one light-year. This can cause a tiny amount of parallax (about 0.001 degrees). + // Also, including stellar aberration (22 arcsec = 0.006 degrees), we provide a + // generous safety buffer of 0.008 degrees. + deriv_ra = -0.008; + deriv_dec = +0.008; + break; + default: + throw `Body not allowed for altitude search: ${body}`; + } + const latrad = DEG2RAD * latitude; + return Math.abs(((360.0 / SOLAR_DAYS_PER_SIDEREAL_DAY) - deriv_ra) * Math.cos(latrad)) + Math.abs(deriv_dec * Math.sin(latrad)); +} +function InternalSearchAltitude(body, observer, direction, dateStart, limitDays, bodyRadiusAu, targetAltitude) { + VerifyObserver(observer); + VerifyNumber(limitDays); + VerifyNumber(bodyRadiusAu); + VerifyNumber(targetAltitude); + if (targetAltitude < -90 || targetAltitude > +90) + throw `Invalid target altitude angle: ${targetAltitude}`; + const RISE_SET_DT = 0.42; // 10.08 hours: Nyquist-safe for 22-hour period. + const max_deriv_alt = MaxAltitudeSlope(body, observer.latitude); + function altdiff(time) { + const ofdate = Equator(body, time, observer, true, true); + const hor = Horizon(time, observer, ofdate.ra, ofdate.dec); + const altitude = hor.altitude + RAD2DEG * Math.asin(bodyRadiusAu / ofdate.dist); + return direction * (altitude - targetAltitude); + } + // We allow searching forward or backward in time. + // But we want to keep t1 < t2, so we need a few if/else statements. + const startTime = MakeTime(dateStart); + let t1 = startTime; + let t2 = startTime; + let a1 = altdiff(t1); + let a2 = a1; + for (;;) { + if (limitDays < 0.0) { + t1 = t2.AddDays(-RISE_SET_DT); + a1 = altdiff(t1); + } + else { + t2 = t1.AddDays(+RISE_SET_DT); + a2 = altdiff(t2); + } + const ascent = FindAscent(0, altdiff, max_deriv_alt, t1, t2, a1, a2); + if (ascent) { + // We found a time interval [t1, t2] that contains an alt-diff + // rising from negative a1 to non-negative a2. + // Search for the time where the root occurs. + const time = Search(altdiff, ascent.tx, ascent.ty, { + dt_tolerance_seconds: 0.1, + init_f1: ascent.ax, + init_f2: ascent.ay + }); + if (time) { + // Now that we have a solution, we have to check whether it goes outside the time bounds. + if (limitDays < 0.0) { + if (time.ut < startTime.ut + limitDays) + return null; + } + else { + if (time.ut > startTime.ut + limitDays) + return null; + } + return time; // success! + } + // The search should have succeeded. Something is wrong with the ascent finder! + throw `Rise/set search failed after finding ascent: t1=${t1}, t2=${t2}, a1=${a1}, a2=${a2}`; + } + // There is no ascent in this interval, so keep searching. + if (limitDays < 0.0) { + if (t1.ut < startTime.ut + limitDays) + return null; + t2 = t1; + a2 = a1; + } + else { + if (t2.ut > startTime.ut + limitDays) + return null; + t1 = t2; + a1 = a2; + } + } +} +/** + * @brief Horizontal position of a body upon reaching an hour angle. + * + * Returns information about an occurrence of a celestial body + * reaching a given hour angle as seen by an observer at a given + * location on the surface of the Earth. + * + * @property {AstroTime} time + * The date and time of the celestial body reaching the hour angle. + * + * @property {HorizontalCoordinates} hor + * Topocentric horizontal coordinates for the body + * at the time indicated by the `time` property. + */ +export class HourAngleEvent { + constructor(time, hor) { + this.time = time; + this.hor = hor; + } +} +/** + * @brief Searches for the time when the center of a body reaches a specified hour angle as seen by an observer on the Earth. + * + * The *hour angle* of a celestial body indicates its position in the sky with respect + * to the Earth's rotation. The hour angle depends on the location of the observer on the Earth. + * The hour angle is 0 when the body's center reaches its highest angle above the horizon in a given day. + * The hour angle increases by 1 unit for every sidereal hour that passes after that point, up + * to 24 sidereal hours when it reaches the highest point again. So the hour angle indicates + * the number of hours that have passed since the most recent time that the body has culminated, + * or reached its highest point. + * + * This function searches for the next or previous time a celestial body reaches the given hour angle + * relative to the date and time specified by `dateStart`. + * To find when a body culminates, pass 0 for `hourAngle`. + * To find when a body reaches its lowest point in the sky, pass 12 for `hourAngle`. + * + * Note that, especially close to the Earth's poles, a body as seen on a given day + * may always be above the horizon or always below the horizon, so the caller cannot + * assume that a culminating object is visible nor that an object is below the horizon + * at its minimum altitude. + * + * The function returns the date and time, along with the horizontal coordinates + * of the body at that time, as seen by the given observer. + * + * @param {Body} body + * The Sun, Moon, any planet other than the Earth, + * or a user-defined star that was created by a call to {@link DefineStar}. + * + * @param {Observer} observer + * Specifies the geographic coordinates and elevation above sea level of the observer. + * + * @param {number} hourAngle + * The hour angle expressed in + * sidereal + * hours for which the caller seeks to find the body attain. + * The value must be in the range [0, 24). + * The hour angle represents the number of sidereal hours that have + * elapsed since the most recent time the body crossed the observer's local + * meridian. + * This specifying `hourAngle` = 0 finds the moment in time + * the body reaches the highest angular altitude in a given sidereal day. + * + * @param {FlexibleDateTime} dateStart + * The date and time after which the desired hour angle crossing event + * is to be found. + * + * @param {number} direction + * The direction in time to perform the search: a positive value + * searches forward in time, a negative value searches backward in time. + * The function throws an exception if `direction` is zero. + * + * @returns {HourAngleEvent} + */ +export function SearchHourAngle(body, observer, hourAngle, dateStart, direction = +1) { + VerifyObserver(observer); + let time = MakeTime(dateStart); + let iter = 0; + if (body === Body.Earth) + throw 'Cannot search for hour angle of the Earth.'; + VerifyNumber(hourAngle); + if (hourAngle < 0.0 || hourAngle >= 24.0) + throw `Invalid hour angle ${hourAngle}`; + VerifyNumber(direction); + if (direction === 0) + throw `Direction must be positive or negative.`; + while (true) { + ++iter; + // Calculate Greenwich Apparent Sidereal Time (GAST) at the given time. + let gast = sidereal_time(time); + let ofdate = Equator(body, time, observer, true, true); + // Calculate the adjustment needed in sidereal time to bring + // the hour angle to the desired value. + let delta_sidereal_hours = ((hourAngle + ofdate.ra - observer.longitude / 15) - gast) % 24; + if (iter === 1) { + // On the first iteration, always search in the requested time direction. + if (direction > 0) { + // Search forward in time. + if (delta_sidereal_hours < 0) + delta_sidereal_hours += 24; + } + else { + // Search backward in time. + if (delta_sidereal_hours > 0) + delta_sidereal_hours -= 24; + } + } + else { + // On subsequent iterations, we make the smallest possible adjustment, + // either forward or backward in time. + if (delta_sidereal_hours < -12) + delta_sidereal_hours += 24; + else if (delta_sidereal_hours > +12) + delta_sidereal_hours -= 24; + } + // If the error is tolerable (less than 0.1 seconds), stop searching. + if (Math.abs(delta_sidereal_hours) * 3600 < 0.1) { + const hor = Horizon(time, observer, ofdate.ra, ofdate.dec, 'normal'); + return new HourAngleEvent(time, hor); + } + // We need to loop another time to get more accuracy. + // Update the terrestrial time adjusting by sidereal time. + let delta_days = (delta_sidereal_hours / 24) * SOLAR_DAYS_PER_SIDEREAL_DAY; + time = time.AddDays(delta_days); + } +} +/** + * @brief Finds the hour angle of a body for a given observer and time. + * + * The *hour angle* of a celestial body indicates its position in the sky with respect + * to the Earth's rotation. The hour angle depends on the location of the observer on the Earth. + * The hour angle is 0 when the body's center reaches its highest angle above the horizon in a given day. + * The hour angle increases by 1 unit for every sidereal hour that passes after that point, up + * to 24 sidereal hours when it reaches the highest point again. So the hour angle indicates + * the number of hours that have passed since the most recent time that the body has culminated, + * or reached its highest point. + * + * This function returns the hour angle of the body as seen at the given time and geogrpahic location. + * The hour angle is a number in the half-open range [0, 24). + * + * @param {Body} body + * The body whose observed hour angle is to be found. + * + * @param {FlexibleDateTime} date + * The date and time of the observation. + * + * @param {Observer} observer + * The geographic location where the observation takes place. + * + * @returns {number} + */ +export function HourAngle(body, date, observer) { + const time = MakeTime(date); + const gast = SiderealTime(time); + const ofdate = Equator(body, time, observer, true, true); + let hourAngle = (observer.longitude / 15 + gast - ofdate.ra) % 24; + if (hourAngle < 0.0) + hourAngle += 24.0; + return hourAngle; +} +/** + * @brief When the seasons change for a given calendar year. + * + * Represents the dates and times of the two solstices + * and the two equinoxes in a given calendar year. + * These four events define the changing of the seasons on the Earth. + * + * @property {AstroTime} mar_equinox + * The date and time of the March equinox in the given calendar year. + * This is the moment in March that the plane of the Earth's equator passes + * through the center of the Sun; thus the Sun's declination + * changes from a negative number to a positive number. + * The March equinox defines + * the beginning of spring in the northern hemisphere and + * the beginning of autumn in the southern hemisphere. + * + * @property {AstroTime} jun_solstice + * The date and time of the June solstice in the given calendar year. + * This is the moment in June that the Sun reaches its most positive + * declination value. + * At this moment the Earth's north pole is most tilted most toward the Sun. + * The June solstice defines + * the beginning of summer in the northern hemisphere and + * the beginning of winter in the southern hemisphere. + * + * @property {AstroTime} sep_equinox + * The date and time of the September equinox in the given calendar year. + * This is the moment in September that the plane of the Earth's equator passes + * through the center of the Sun; thus the Sun's declination + * changes from a positive number to a negative number. + * The September equinox defines + * the beginning of autumn in the northern hemisphere and + * the beginning of spring in the southern hemisphere. + * + * @property {AstroTime} dec_solstice + * The date and time of the December solstice in the given calendar year. + * This is the moment in December that the Sun reaches its most negative + * declination value. + * At this moment the Earth's south pole is tilted most toward the Sun. + * The December solstice defines + * the beginning of winter in the northern hemisphere and + * the beginning of summer in the southern hemisphere. + */ +export class SeasonInfo { + constructor(mar_equinox, jun_solstice, sep_equinox, dec_solstice) { + this.mar_equinox = mar_equinox; + this.jun_solstice = jun_solstice; + this.sep_equinox = sep_equinox; + this.dec_solstice = dec_solstice; + } +} +/** + * @brief Finds the equinoxes and solstices for a given calendar year. + * + * @param {number | AstroTime} year + * The integer value or `AstroTime` object that specifies + * the UTC calendar year for which to find equinoxes and solstices. + * + * @returns {SeasonInfo} + */ +export function Seasons(year) { + function find(targetLon, month, day) { + let startDate = new Date(Date.UTC(year, month - 1, day)); + let time = SearchSunLongitude(targetLon, startDate, 20); + if (!time) + throw `Cannot find season change near ${startDate.toISOString()}`; + return time; + } + if ((year instanceof Date) && Number.isFinite(year.getTime())) + year = year.getUTCFullYear(); + if (!Number.isSafeInteger(year)) + throw `Cannot calculate seasons because year argument ${year} is neither a Date nor a safe integer.`; + let mar_equinox = find(0, 3, 10); + let jun_solstice = find(90, 6, 10); + let sep_equinox = find(180, 9, 10); + let dec_solstice = find(270, 12, 10); + return new SeasonInfo(mar_equinox, jun_solstice, sep_equinox, dec_solstice); +} +/** + * @brief The viewing conditions of a body relative to the Sun. + * + * Represents the angular separation of a body from the Sun as seen from the Earth + * and the relative ecliptic longitudes between that body and the Earth as seen from the Sun. + * + * @property {AstroTime} time + * The date and time of the observation. + * + * @property {string} visibility + * Either `"morning"` or `"evening"`, + * indicating when the body is most easily seen. + * + * @property {number} elongation + * The angle in degrees, as seen from the center of the Earth, + * of the apparent separation between the body and the Sun. + * This angle is measured in 3D space and is not projected onto the ecliptic plane. + * When `elongation` is less than a few degrees, the body is very + * difficult to see from the Earth because it is lost in the Sun's glare. + * The elongation is always in the range [0, 180]. + * + * @property {number} ecliptic_separation + * The absolute value of the difference between the body's ecliptic longitude + * and the Sun's ecliptic longitude, both as seen from the center of the Earth. + * This angle measures around the plane of the Earth's orbit (the ecliptic), + * and ignores how far above or below that plane the body is. + * The ecliptic separation is measured in degrees and is always in the range [0, 180]. + * + * @see {@link Elongation} + */ +export class ElongationEvent { + constructor(time, visibility, elongation, ecliptic_separation) { + this.time = time; + this.visibility = visibility; + this.elongation = elongation; + this.ecliptic_separation = ecliptic_separation; + } +} +/** + * @brief Calculates the viewing conditions of a body relative to the Sun. + * + * Calculates angular separation of a body from the Sun as seen from the Earth + * and the relative ecliptic longitudes between that body and the Earth as seen from the Sun. + * See the return type {@link ElongationEvent} for details. + * + * This function is helpful for determining how easy + * it is to view a planet away from the Sun's glare on a given date. + * It also determines whether the object is visible in the morning or evening; + * this is more important the smaller the elongation is. + * It is also used to determine how far a planet is from opposition, conjunction, or quadrature. + * + * @param {Body} body + * The name of the observed body. Not allowed to be `Body.Earth`. + * + * @param {FlexibleDateTime} date + * The date and time of the observation. + * + * @returns {ElongationEvent} + */ +export function Elongation(body, date) { + let time = MakeTime(date); + let lon = PairLongitude(body, Body.Sun, time); + let vis; + if (lon > 180) { + vis = 'morning'; + lon = 360 - lon; + } + else { + vis = 'evening'; + } + let angle = AngleFromSun(body, time); + return new ElongationEvent(time, vis, angle, lon); +} +/** + * @brief Finds the next time Mercury or Venus reaches maximum elongation. + * + * Searches for the next maximum elongation event for Mercury or Venus + * that occurs after the given start date. Calling with other values + * of `body` will result in an exception. + * Maximum elongation occurs when the body has the greatest + * angular separation from the Sun, as seen from the Earth. + * Returns an `ElongationEvent` object containing the date and time of the next + * maximum elongation, the elongation in degrees, and whether + * the body is visible in the morning or evening. + * + * @param {Body} body + * Either `Body.Mercury` or `Body.Venus`. + * + * @param {FlexibleDateTime} startDate + * The date and time after which to search for the next maximum elongation event. + * + * @returns {ElongationEvent} + */ +export function SearchMaxElongation(body, startDate) { + const dt = 0.01; + function neg_slope(t) { + // The slope de/dt goes from positive to negative at the maximum elongation event. + // But Search() is designed for functions that ascend through zero. + // So this function returns the negative slope. + const t1 = t.AddDays(-dt / 2); + const t2 = t.AddDays(+dt / 2); + let e1 = AngleFromSun(body, t1); + let e2 = AngleFromSun(body, t2); + let m = (e1 - e2) / dt; + return m; + } + let startTime = MakeTime(startDate); + const table = { + Mercury: { s1: 50.0, s2: 85.0 }, + Venus: { s1: 40.0, s2: 50.0 } + }; + const planet = table[body]; + if (!planet) + throw 'SearchMaxElongation works for Mercury and Venus only.'; + let iter = 0; + while (++iter <= 2) { + // Find current heliocentric relative longitude between the + // inferior planet and the Earth. + let plon = EclipticLongitude(body, startTime); + let elon = EclipticLongitude(Body.Earth, startTime); + let rlon = LongitudeOffset(plon - elon); // clamp to (-180, +180] + // The slope function is not well-behaved when rlon is near 0 degrees or 180 degrees + // because there is a cusp there that causes a discontinuity in the derivative. + // So we need to guard against searching near such times. + let rlon_lo, rlon_hi, adjust_days; + if (rlon >= -planet.s1 && rlon < +planet.s1) { + // Seek to the window [+s1, +s2]. + adjust_days = 0; + // Search forward for the time t1 when rel lon = +s1. + rlon_lo = +planet.s1; + // Search forward for the time t2 when rel lon = +s2. + rlon_hi = +planet.s2; + } + else if (rlon >= +planet.s2 || rlon < -planet.s2) { + // Seek to the next search window at [-s2, -s1]. + adjust_days = 0; + // Search forward for the time t1 when rel lon = -s2. + rlon_lo = -planet.s2; + // Search forward for the time t2 when rel lon = -s1. + rlon_hi = -planet.s1; + } + else if (rlon >= 0) { + // rlon must be in the middle of the window [+s1, +s2]. + // Search BACKWARD for the time t1 when rel lon = +s1. + adjust_days = -SynodicPeriod(body) / 4; + rlon_lo = +planet.s1; + rlon_hi = +planet.s2; + // Search forward from t1 to find t2 such that rel lon = +s2. + } + else { + // rlon must be in the middle of the window [-s2, -s1]. + // Search BACKWARD for the time t1 when rel lon = -s2. + adjust_days = -SynodicPeriod(body) / 4; + rlon_lo = -planet.s2; + // Search forward from t1 to find t2 such that rel lon = -s1. + rlon_hi = -planet.s1; + } + let t_start = startTime.AddDays(adjust_days); + let t1 = SearchRelativeLongitude(body, rlon_lo, t_start); + let t2 = SearchRelativeLongitude(body, rlon_hi, t1); + // Now we have a time range [t1,t2] that brackets a maximum elongation event. + // Confirm the bracketing. + let m1 = neg_slope(t1); + if (m1 >= 0) + throw `SearchMaxElongation: internal error: m1 = ${m1}`; + let m2 = neg_slope(t2); + if (m2 <= 0) + throw `SearchMaxElongation: internal error: m2 = ${m2}`; + // Use the generic search algorithm to home in on where the slope crosses from negative to positive. + let tx = Search(neg_slope, t1, t2, { init_f1: m1, init_f2: m2, dt_tolerance_seconds: 10 }); + if (!tx) + throw `SearchMaxElongation: failed search iter ${iter} (t1=${t1.toString()}, t2=${t2.toString()})`; + if (tx.tt >= startTime.tt) + return Elongation(body, tx); + // This event is in the past (earlier than startDate). + // We need to search forward from t2 to find the next possible window. + // We never need to search more than twice. + startTime = t2.AddDays(1); + } + throw `SearchMaxElongation: failed to find event after 2 tries.`; +} +/** + * @brief Searches for the date and time Venus will next appear brightest as seen from the Earth. + * + * @param {Body} body + * Currently only `Body.Venus` is supported. + * Mercury's peak magnitude occurs at superior conjunction, when it is impossible to see from Earth, + * so peak magnitude events have little practical value for that planet. + * The Moon reaches peak magnitude very close to full moon, which can be found using + * {@link SearchMoonQuarter} or {@link SearchMoonPhase}. + * The other planets reach peak magnitude very close to opposition, + * which can be found using {@link SearchRelativeLongitude}. + * + * @param {FlexibleDateTime} startDate + * The date and time after which to find the next peak magnitude event. + * + * @returns {IlluminationInfo} + */ +export function SearchPeakMagnitude(body, startDate) { + if (body !== Body.Venus) + throw 'SearchPeakMagnitude currently works for Venus only.'; + const dt = 0.01; + function slope(t) { + // The Search() function finds a transition from negative to positive values. + // The derivative of magnitude y with respect to time t (dy/dt) + // is negative as an object gets brighter, because the magnitude numbers + // get smaller. At peak magnitude dy/dt = 0, then as the object gets dimmer, + // dy/dt > 0. + const t1 = t.AddDays(-dt / 2); + const t2 = t.AddDays(+dt / 2); + const y1 = Illumination(body, t1).mag; + const y2 = Illumination(body, t2).mag; + const m = (y2 - y1) / dt; + return m; + } + let startTime = MakeTime(startDate); + // s1 and s2 are relative longitudes within which peak magnitude of Venus can occur. + const s1 = 10.0; + const s2 = 30.0; + let iter = 0; + while (++iter <= 2) { + // Find current heliocentric relative longitude between the + // inferior planet and the Earth. + let plon = EclipticLongitude(body, startTime); + let elon = EclipticLongitude(Body.Earth, startTime); + let rlon = LongitudeOffset(plon - elon); // clamp to (-180, +180] + // The slope function is not well-behaved when rlon is near 0 degrees or 180 degrees + // because there is a cusp there that causes a discontinuity in the derivative. + // So we need to guard against searching near such times. + let rlon_lo, rlon_hi, adjust_days; + if (rlon >= -s1 && rlon < +s1) { + // Seek to the window [+s1, +s2]. + adjust_days = 0; + // Search forward for the time t1 when rel lon = +s1. + rlon_lo = +s1; + // Search forward for the time t2 when rel lon = +s2. + rlon_hi = +s2; + } + else if (rlon >= +s2 || rlon < -s2) { + // Seek to the next search window at [-s2, -s1]. + adjust_days = 0; + // Search forward for the time t1 when rel lon = -s2. + rlon_lo = -s2; + // Search forward for the time t2 when rel lon = -s1. + rlon_hi = -s1; + } + else if (rlon >= 0) { + // rlon must be in the middle of the window [+s1, +s2]. + // Search BACKWARD for the time t1 when rel lon = +s1. + adjust_days = -SynodicPeriod(body) / 4; + rlon_lo = +s1; + // Search forward from t1 to find t2 such that rel lon = +s2. + rlon_hi = +s2; + } + else { + // rlon must be in the middle of the window [-s2, -s1]. + // Search BACKWARD for the time t1 when rel lon = -s2. + adjust_days = -SynodicPeriod(body) / 4; + rlon_lo = -s2; + // Search forward from t1 to find t2 such that rel lon = -s1. + rlon_hi = -s1; + } + let t_start = startTime.AddDays(adjust_days); + let t1 = SearchRelativeLongitude(body, rlon_lo, t_start); + let t2 = SearchRelativeLongitude(body, rlon_hi, t1); + // Now we have a time range [t1,t2] that brackets a maximum magnitude event. + // Confirm the bracketing. + let m1 = slope(t1); + if (m1 >= 0) + throw `SearchPeakMagnitude: internal error: m1 = ${m1}`; + let m2 = slope(t2); + if (m2 <= 0) + throw `SearchPeakMagnitude: internal error: m2 = ${m2}`; + // Use the generic search algorithm to home in on where the slope crosses from negative to positive. + let tx = Search(slope, t1, t2, { init_f1: m1, init_f2: m2, dt_tolerance_seconds: 10 }); + if (!tx) + throw `SearchPeakMagnitude: failed search iter ${iter} (t1=${t1.toString()}, t2=${t2.toString()})`; + if (tx.tt >= startTime.tt) + return Illumination(body, tx); + // This event is in the past (earlier than startDate). + // We need to search forward from t2 to find the next possible window. + // We never need to search more than twice. + startTime = t2.AddDays(1); + } + throw `SearchPeakMagnitude: failed to find event after 2 tries.`; +} +/** + * @brief The two kinds of apsis: pericenter (closest) and apocenter (farthest). + * + * `Pericenter`: The body is at its closest distance to the object it orbits. + * `Apocenter`: The body is at its farthest distance from the object it orbits. + * + * @enum {number} + */ +export var ApsisKind; +(function (ApsisKind) { + ApsisKind[ApsisKind["Pericenter"] = 0] = "Pericenter"; + ApsisKind[ApsisKind["Apocenter"] = 1] = "Apocenter"; +})(ApsisKind || (ApsisKind = {})); +/** + * @brief A closest or farthest point in a body's orbit around its primary. + * + * For a planet orbiting the Sun, apsis is a perihelion or aphelion, respectively. + * For the Moon orbiting the Earth, apsis is a perigee or apogee, respectively. + * + * @property {AstroTime} time + * The date and time of the apsis. + * + * @property {ApsisKind} kind + * For a closest approach (perigee or perihelion), `kind` is `ApsisKind.Pericenter`. + * For a farthest distance event (apogee or aphelion), `kind` is `ApsisKind.Apocenter`. + * + * @property {number} dist_au + * The distance between the centers of the two bodies in astronomical units (AU). + * + * @property {number} dist_km + * The distance between the centers of the two bodies in kilometers. + * + * @see {@link SearchLunarApsis} + * @see {@link NextLunarApsis} + * @see {@link SearchPlanetApsis} + * @see {@link NextPlanetApsis} + */ +export class Apsis { + constructor(time, kind, dist_au) { + this.time = time; + this.kind = kind; + this.dist_au = dist_au; + this.dist_km = dist_au * KM_PER_AU; + } +} +/** + * @brief Finds the next perigee or apogee of the Moon. + * + * Finds the next perigee (closest approach) or apogee (farthest remove) of the Moon + * that occurs after the specified date and time. + * + * @param {FlexibleDateTime} startDate + * The date and time after which to find the next perigee or apogee. + * + * @returns {Apsis} + */ +export function SearchLunarApsis(startDate) { + const dt = 0.001; + function distance_slope(t) { + let t1 = t.AddDays(-dt / 2); + let t2 = t.AddDays(+dt / 2); + let r1 = CalcMoon(t1).distance_au; + let r2 = CalcMoon(t2).distance_au; + let m = (r2 - r1) / dt; + return m; + } + function negative_distance_slope(t) { + return -distance_slope(t); + } + // Check the rate of change of the distance dr/dt at the start time. + // If it is positive, the Moon is currently getting farther away, + // so start looking for apogee. + // Conversely, if dr/dt < 0, start looking for perigee. + // Either way, the polarity of the slope will change, so the product will be negative. + // Handle the crazy corner case of exactly touching zero by checking for m1*m2 <= 0. + let t1 = MakeTime(startDate); + let m1 = distance_slope(t1); + const increment = 5; // number of days to skip in each iteration + for (var iter = 0; iter * increment < 2 * MEAN_SYNODIC_MONTH; ++iter) { + let t2 = t1.AddDays(increment); + let m2 = distance_slope(t2); + if (m1 * m2 <= 0) { + // The time range [t1, t2] contains an apsis. + // Figure out whether it is perigee or apogee. + if (m1 < 0 || m2 > 0) { + // We found a minimum distance event: perigee. + // Search the time range [t1, t2] for the time when the slope goes + // from negative to positive. + let tx = Search(distance_slope, t1, t2, { init_f1: m1, init_f2: m2 }); + if (!tx) + throw 'SearchLunarApsis INTERNAL ERROR: perigee search failed!'; + let dist = CalcMoon(tx).distance_au; + return new Apsis(tx, 0, dist); + } + if (m1 > 0 || m2 < 0) { + // We found a maximum distance event: apogee. + // Search the time range [t1, t2] for the time when the slope goes + // from positive to negative. + let tx = Search(negative_distance_slope, t1, t2, { init_f1: -m1, init_f2: -m2 }); + if (!tx) + throw 'SearchLunarApsis INTERNAL ERROR: apogee search failed!'; + let dist = CalcMoon(tx).distance_au; + return new Apsis(tx, 1, dist); + } + // This should never happen; it should not be possible for consecutive + // times t1 and t2 to both have zero slope. + throw 'SearchLunarApsis INTERNAL ERROR: cannot classify apsis event!'; + } + t1 = t2; + m1 = m2; + } + // It should not be possible to fail to find an apsis within 2 synodic months. + throw 'SearchLunarApsis INTERNAL ERROR: could not find apsis within 2 synodic months of start date.'; +} +/** + * @brief Finds the next lunar apsis (perigee or apogee) in a series. + * + * Given a lunar apsis returned by an initial call to {@link SearchLunarApsis}, + * or a previous call to `NextLunarApsis`, finds the next lunar apsis. + * If the given apsis is a perigee, this function finds the next apogee, and vice versa. + * + * @param {Apsis} apsis + * A lunar perigee or apogee event. + * + * @returns {Apsis} + * The successor apogee for the given perigee, or the successor perigee for the given apogee. + */ +export function NextLunarApsis(apsis) { + const skip = 11; // number of days to skip to start looking for next apsis event + let next = SearchLunarApsis(apsis.time.AddDays(skip)); + if (next.kind + apsis.kind !== 1) + throw `NextLunarApsis INTERNAL ERROR: did not find alternating apogee/perigee: prev=${apsis.kind} @ ${apsis.time.toString()}, next=${next.kind} @ ${next.time.toString()}`; + return next; +} +function PlanetExtreme(body, kind, start_time, dayspan) { + const direction = (kind === ApsisKind.Apocenter) ? +1.0 : -1.0; + const npoints = 10; + for (;;) { + const interval = dayspan / (npoints - 1); + // iterate until uncertainty is less than one minute + if (interval < 1.0 / 1440.0) { + const apsis_time = start_time.AddDays(interval / 2.0); + const dist_au = HelioDistance(body, apsis_time); + return new Apsis(apsis_time, kind, dist_au); + } + let best_i = -1; + let best_dist = 0.0; + for (let i = 0; i < npoints; ++i) { + const time = start_time.AddDays(i * interval); + const dist = direction * HelioDistance(body, time); + if (i == 0 || dist > best_dist) { + best_i = i; + best_dist = dist; + } + } + /* Narrow in on the extreme point. */ + start_time = start_time.AddDays((best_i - 1) * interval); + dayspan = 2.0 * interval; + } +} +function BruteSearchPlanetApsis(body, startTime) { + /* + Neptune is a special case for two reasons: + 1. Its orbit is nearly circular (low orbital eccentricity). + 2. It is so distant from the Sun that the orbital period is very long. + Put together, this causes wobbling of the Sun around the Solar System Barycenter (SSB) + to be so significant that there are 3 local minima in the distance-vs-time curve + near each apsis. Therefore, unlike for other planets, we can't use an optimized + algorithm for finding dr/dt = 0. + Instead, we use a dumb, brute-force algorithm of sampling and finding min/max + heliocentric distance. + + There is a similar problem in the TOP2013 model for Pluto: + Its position vector has high-frequency oscillations that confuse the + slope-based determination of apsides. + */ + /* + Rewind approximately 30 degrees in the orbit, + then search forward for 270 degrees. + This is a very cautious way to prevent missing an apsis. + Typically we will find two apsides, and we pick whichever + apsis is ealier, but after startTime. + Sample points around this orbital arc and find when the distance + is greatest and smallest. + */ + const npoints = 100; + const t1 = startTime.AddDays(Planet[body].OrbitalPeriod * (-30 / 360)); + const t2 = startTime.AddDays(Planet[body].OrbitalPeriod * (+270 / 360)); + let t_min = t1; + let t_max = t1; + let min_dist = -1.0; + let max_dist = -1.0; + const interval = (t2.ut - t1.ut) / (npoints - 1); + for (let i = 0; i < npoints; ++i) { + const time = t1.AddDays(i * interval); + const dist = HelioDistance(body, time); + if (i === 0) { + max_dist = min_dist = dist; + } + else { + if (dist > max_dist) { + max_dist = dist; + t_max = time; + } + if (dist < min_dist) { + min_dist = dist; + t_min = time; + } + } + } + const perihelion = PlanetExtreme(body, 0, t_min.AddDays(-2 * interval), 4 * interval); + const aphelion = PlanetExtreme(body, 1, t_max.AddDays(-2 * interval), 4 * interval); + if (perihelion.time.tt >= startTime.tt) { + if (aphelion.time.tt >= startTime.tt && aphelion.time.tt < perihelion.time.tt) + return aphelion; + return perihelion; + } + if (aphelion.time.tt >= startTime.tt) + return aphelion; + throw 'Internal error: failed to find Neptune apsis.'; +} +/** + * @brief Finds the next perihelion or aphelion of a planet. + * + * Finds the date and time of a planet's perihelion (closest approach to the Sun) + * or aphelion (farthest distance from the Sun) after a given time. + * + * Given a date and time to start the search in `startTime`, this function finds the + * next date and time that the center of the specified planet reaches the closest or farthest point + * in its orbit with respect to the center of the Sun, whichever comes first + * after `startTime`. + * + * The closest point is called *perihelion* and the farthest point is called *aphelion*. + * The word *apsis* refers to either event. + * + * To iterate through consecutive alternating perihelion and aphelion events, + * call `SearchPlanetApsis` once, then use the return value to call + * {@link NextPlanetApsis}. After that, keep feeding the previous return value + * from `NextPlanetApsis` into another call of `NextPlanetApsis` + * as many times as desired. + * + * @param {Body} body + * The planet for which to find the next perihelion/aphelion event. + * Not allowed to be `Body.Sun` or `Body.Moon`. + * + * @param {FlexibleDateTime} startTime + * The date and time at which to start searching for the next perihelion or aphelion. + * + * @returns {Apsis} + * The next perihelion or aphelion that occurs after `startTime`. + */ +export function SearchPlanetApsis(body, startTime) { + startTime = MakeTime(startTime); + if (body === Body.Neptune || body === Body.Pluto) + return BruteSearchPlanetApsis(body, startTime); + function positive_slope(t) { + const dt = 0.001; + let t1 = t.AddDays(-dt / 2); + let t2 = t.AddDays(+dt / 2); + let r1 = HelioDistance(body, t1); + let r2 = HelioDistance(body, t2); + let m = (r2 - r1) / dt; + return m; + } + function negative_slope(t) { + return -positive_slope(t); + } + const orbit_period_days = Planet[body].OrbitalPeriod; + const increment = orbit_period_days / 6.0; + let t1 = startTime; + let m1 = positive_slope(t1); + for (let iter = 0; iter * increment < 2.0 * orbit_period_days; ++iter) { + const t2 = t1.AddDays(increment); + const m2 = positive_slope(t2); + if (m1 * m2 <= 0.0) { + /* There is a change of slope polarity within the time range [t1, t2]. */ + /* Therefore this time range contains an apsis. */ + /* Figure out whether it is perihelion or aphelion. */ + let slope_func; + let kind; + if (m1 < 0.0 || m2 > 0.0) { + /* We found a minimum-distance event: perihelion. */ + /* Search the time range for the time when the slope goes from negative to positive. */ + slope_func = positive_slope; + kind = ApsisKind.Pericenter; + } + else if (m1 > 0.0 || m2 < 0.0) { + /* We found a maximum-distance event: aphelion. */ + /* Search the time range for the time when the slope goes from positive to negative. */ + slope_func = negative_slope; + kind = ApsisKind.Apocenter; + } + else { + /* This should never happen. It should not be possible for both slopes to be zero. */ + throw "Internal error with slopes in SearchPlanetApsis"; + } + const search = Search(slope_func, t1, t2); + if (!search) + throw "Failed to find slope transition in planetary apsis search."; + const dist = HelioDistance(body, search); + return new Apsis(search, kind, dist); + } + /* We have not yet found a slope polarity change. Keep searching. */ + t1 = t2; + m1 = m2; + } + throw "Internal error: should have found planetary apsis within 2 orbital periods."; +} +/** + * @brief Finds the next planetary perihelion or aphelion event in a series. + * + * This function requires an {@link Apsis} value obtained from a call + * to {@link SearchPlanetApsis} or `NextPlanetApsis`. + * Given an aphelion event, this function finds the next perihelion event, and vice versa. + * See {@link SearchPlanetApsis} for more details. + * + * @param {Body} body + * The planet for which to find the next perihelion/aphelion event. + * Not allowed to be `Body.Sun` or `Body.Moon`. + * Must match the body passed into the call that produced the `apsis` parameter. + * + * @param {Apsis} apsis + * An apsis event obtained from a call to {@link SearchPlanetApsis} or `NextPlanetApsis`. + * + * @returns {Apsis} + * Same as the return value for {@link SearchPlanetApsis}. + */ +export function NextPlanetApsis(body, apsis) { + if (apsis.kind !== ApsisKind.Pericenter && apsis.kind !== ApsisKind.Apocenter) + throw `Invalid apsis kind: ${apsis.kind}`; + /* skip 1/4 of an orbit before starting search again */ + const skip = 0.25 * Planet[body].OrbitalPeriod; + const time = apsis.time.AddDays(skip); + const next = SearchPlanetApsis(body, time); + /* Verify that we found the opposite apsis from the previous one. */ + if (next.kind + apsis.kind !== 1) + throw `Internal error: previous apsis was ${apsis.kind}, but found ${next.kind} for next apsis.`; + return next; +} +/** + * @brief Calculates the inverse of a rotation matrix. + * + * Given a rotation matrix that performs some coordinate transform, + * this function returns the matrix that reverses that transform. + * + * @param {RotationMatrix} rotation + * The rotation matrix to be inverted. + * + * @returns {RotationMatrix} + * The inverse rotation matrix. + */ +export function InverseRotation(rotation) { + return new RotationMatrix([ + [rotation.rot[0][0], rotation.rot[1][0], rotation.rot[2][0]], + [rotation.rot[0][1], rotation.rot[1][1], rotation.rot[2][1]], + [rotation.rot[0][2], rotation.rot[1][2], rotation.rot[2][2]] + ]); +} +/** + * @brief Creates a rotation based on applying one rotation followed by another. + * + * Given two rotation matrices, returns a combined rotation matrix that is + * equivalent to rotating based on the first matrix, followed by the second. + * + * @param {RotationMatrix} a + * The first rotation to apply. + * + * @param {RotationMatrix} b + * The second rotation to apply. + * + * @returns {RotationMatrix} + * The combined rotation matrix. + */ +export function CombineRotation(a, b) { + /* + Use matrix multiplication: c = b*a. + We put 'b' on the left and 'a' on the right because, + just like when you use a matrix M to rotate a vector V, + you put the M on the left in the product M*V. + We can think of this as 'b' rotating all the 3 column vectors in 'a'. + */ + return new RotationMatrix([ + [ + b.rot[0][0] * a.rot[0][0] + b.rot[1][0] * a.rot[0][1] + b.rot[2][0] * a.rot[0][2], + b.rot[0][1] * a.rot[0][0] + b.rot[1][1] * a.rot[0][1] + b.rot[2][1] * a.rot[0][2], + b.rot[0][2] * a.rot[0][0] + b.rot[1][2] * a.rot[0][1] + b.rot[2][2] * a.rot[0][2] + ], + [ + b.rot[0][0] * a.rot[1][0] + b.rot[1][0] * a.rot[1][1] + b.rot[2][0] * a.rot[1][2], + b.rot[0][1] * a.rot[1][0] + b.rot[1][1] * a.rot[1][1] + b.rot[2][1] * a.rot[1][2], + b.rot[0][2] * a.rot[1][0] + b.rot[1][2] * a.rot[1][1] + b.rot[2][2] * a.rot[1][2] + ], + [ + b.rot[0][0] * a.rot[2][0] + b.rot[1][0] * a.rot[2][1] + b.rot[2][0] * a.rot[2][2], + b.rot[0][1] * a.rot[2][0] + b.rot[1][1] * a.rot[2][1] + b.rot[2][1] * a.rot[2][2], + b.rot[0][2] * a.rot[2][0] + b.rot[1][2] * a.rot[2][1] + b.rot[2][2] * a.rot[2][2] + ] + ]); +} +/** + * @brief Creates an identity rotation matrix. + * + * Returns a rotation matrix that has no effect on orientation. + * This matrix can be the starting point for other operations, + * such as using a series of calls to {@link Pivot} to + * create a custom rotation matrix. + * + * @returns {RotationMatrix} + * The identity matrix. + */ +export function IdentityMatrix() { + return new RotationMatrix([ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1] + ]); +} +/** +* @brief Re-orients a rotation matrix by pivoting it by an angle around one of its axes. +* +* Given a rotation matrix, a selected coordinate axis, and an angle in degrees, +* this function pivots the rotation matrix by that angle around that coordinate axis. +* +* For example, if you have rotation matrix that converts ecliptic coordinates (ECL) +* to horizontal coordinates (HOR), but you really want to convert ECL to the orientation +* of a telescope camera pointed at a given body, you can use `Astronomy_Pivot` twice: +* (1) pivot around the zenith axis by the body's azimuth, then (2) pivot around the +* western axis by the body's altitude angle. The resulting rotation matrix will then +* reorient ECL coordinates to the orientation of your telescope camera. +* +* @param {RotationMatrix} rotation +* The input rotation matrix. +* +* @param {number} axis +* An integer that selects which coordinate axis to rotate around: +* 0 = x, 1 = y, 2 = z. Any other value will cause an exception. +* +* @param {number} angle +* An angle in degrees indicating the amount of rotation around the specified axis. +* Positive angles indicate rotation counterclockwise as seen from the positive +* direction along that axis, looking towards the origin point of the orientation system. +* Any finite number of degrees is allowed, but best precision will result from +* keeping `angle` in the range [-360, +360]. +* +* @returns {RotationMatrix} +* A pivoted matrix object. +*/ +export function Pivot(rotation, axis, angle) { + // Check for an invalid coordinate axis. + if (axis !== 0 && axis !== 1 && axis !== 2) + throw `Invalid axis ${axis}. Must be [0, 1, 2].`; + const radians = VerifyNumber(angle) * DEG2RAD; + const c = Math.cos(radians); + const s = Math.sin(radians); + /* + We need to maintain the "right-hand" rule, no matter which + axis was selected. That means we pick (i, j, k) axis order + such that the following vector cross product is satisfied: + i x j = k + */ + const i = (axis + 1) % 3; + const j = (axis + 2) % 3; + const k = axis; + let rot = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]; + rot[i][i] = c * rotation.rot[i][i] - s * rotation.rot[i][j]; + rot[i][j] = s * rotation.rot[i][i] + c * rotation.rot[i][j]; + rot[i][k] = rotation.rot[i][k]; + rot[j][i] = c * rotation.rot[j][i] - s * rotation.rot[j][j]; + rot[j][j] = s * rotation.rot[j][i] + c * rotation.rot[j][j]; + rot[j][k] = rotation.rot[j][k]; + rot[k][i] = c * rotation.rot[k][i] - s * rotation.rot[k][j]; + rot[k][j] = s * rotation.rot[k][i] + c * rotation.rot[k][j]; + rot[k][k] = rotation.rot[k][k]; + return new RotationMatrix(rot); +} +/** + * @brief Converts spherical coordinates to Cartesian coordinates. + * + * Given spherical coordinates and a time at which they are valid, + * returns a vector of Cartesian coordinates. The returned value + * includes the time, as required by `AstroTime`. + * + * @param {Spherical} sphere + * Spherical coordinates to be converted. + * + * @param {FlexibleDateTime} time + * The time that should be included in the returned vector. + * + * @returns {Vector} + * The vector form of the supplied spherical coordinates. + */ +export function VectorFromSphere(sphere, time) { + time = MakeTime(time); + const radlat = sphere.lat * DEG2RAD; + const radlon = sphere.lon * DEG2RAD; + const rcoslat = sphere.dist * Math.cos(radlat); + return new Vector(rcoslat * Math.cos(radlon), rcoslat * Math.sin(radlon), sphere.dist * Math.sin(radlat), time); +} +/** + * @brief Given an equatorial vector, calculates equatorial angular coordinates. + * + * @param {Vector} vec + * A vector in an equatorial coordinate system. + * + * @returns {EquatorialCoordinates} + * Angular coordinates expressed in the same equatorial system as `vec`. + */ +export function EquatorFromVector(vec) { + const sphere = SphereFromVector(vec); + return new EquatorialCoordinates(sphere.lon / 15, sphere.lat, sphere.dist, vec); +} +/** + * @brief Converts Cartesian coordinates to spherical coordinates. + * + * Given a Cartesian vector, returns latitude, longitude, and distance. + * + * @param {Vector} vector + * Cartesian vector to be converted to spherical coordinates. + * + * @returns {Spherical} + * Spherical coordinates that are equivalent to the given vector. + */ +export function SphereFromVector(vector) { + const xyproj = vector.x * vector.x + vector.y * vector.y; + const dist = Math.sqrt(xyproj + vector.z * vector.z); + let lat, lon; + if (xyproj === 0.0) { + if (vector.z === 0.0) + throw 'Zero-length vector not allowed.'; + lon = 0.0; + lat = (vector.z < 0.0) ? -90.0 : +90.0; + } + else { + lon = RAD2DEG * Math.atan2(vector.y, vector.x); + if (lon < 0.0) + lon += 360.0; + lat = RAD2DEG * Math.atan2(vector.z, Math.sqrt(xyproj)); + } + return new Spherical(lat, lon, dist); +} +function ToggleAzimuthDirection(az) { + az = 360.0 - az; + if (az >= 360.0) + az -= 360.0; + else if (az < 0.0) + az += 360.0; + return az; +} +/** + * @brief Converts Cartesian coordinates to horizontal coordinates. + * + * Given a horizontal Cartesian vector, returns horizontal azimuth and altitude. + * + * *IMPORTANT:* This function differs from {@link SphereFromVector} in two ways: + * - `SphereFromVector` returns a `lon` value that represents azimuth defined counterclockwise + * from north (e.g., west = +90), but this function represents a clockwise rotation + * (e.g., east = +90). The difference is because `SphereFromVector` is intended + * to preserve the vector "right-hand rule", while this function defines azimuth in a more + * traditional way as used in navigation and cartography. + * - This function optionally corrects for atmospheric refraction, while `SphereFromVector` does not. + * + * The returned object contains the azimuth in `lon`. + * It is measured in degrees clockwise from north: east = +90 degrees, west = +270 degrees. + * + * The altitude is stored in `lat`. + * + * The distance to the observed object is stored in `dist`, + * and is expressed in astronomical units (AU). + * + * @param {Vector} vector + * Cartesian vector to be converted to horizontal coordinates. + * + * @param {string} refraction + * `"normal"`: correct altitude for atmospheric refraction (recommended). + * `"jplhor"`: for JPL Horizons compatibility testing only; not recommended for normal use. + * `null`: no atmospheric refraction correction is performed. + * + * @returns {Spherical} + */ +export function HorizonFromVector(vector, refraction) { + const sphere = SphereFromVector(vector); + sphere.lon = ToggleAzimuthDirection(sphere.lon); + sphere.lat += Refraction(refraction, sphere.lat); + return sphere; +} +/** + * @brief Given apparent angular horizontal coordinates in `sphere`, calculate horizontal vector. + * + * @param {Spherical} sphere + * A structure that contains apparent horizontal coordinates: + * `lat` holds the refracted altitude angle, + * `lon` holds the azimuth in degrees clockwise from north, + * and `dist` holds the distance from the observer to the object in AU. + * + * @param {FlexibleDateTime} time + * The date and time of the observation. This is needed because the returned + * vector object requires a valid time value when passed to certain other functions. + * + * @param {string} refraction + * `"normal"`: correct altitude for atmospheric refraction (recommended). + * `"jplhor"`: for JPL Horizons compatibility testing only; not recommended for normal use. + * `null`: no atmospheric refraction correction is performed. + * + * @returns {Vector} + * A vector in the horizontal system: `x` = north, `y` = west, and `z` = zenith (up). + */ +export function VectorFromHorizon(sphere, time, refraction) { + time = MakeTime(time); + /* Convert azimuth from clockwise-from-north to counterclockwise-from-north. */ + const lon = ToggleAzimuthDirection(sphere.lon); + /* Reverse any applied refraction. */ + const lat = sphere.lat + InverseRefraction(refraction, sphere.lat); + const xsphere = new Spherical(lat, lon, sphere.dist); + return VectorFromSphere(xsphere, time); +} +/** + * @brief Calculates the amount of "lift" to an altitude angle caused by atmospheric refraction. + * + * Given an altitude angle and a refraction option, calculates + * the amount of "lift" caused by atmospheric refraction. + * This is the number of degrees higher in the sky an object appears + * due to the lensing of the Earth's atmosphere. + * This function works best near sea level. + * To correct for higher elevations, call {@link Atmosphere} for that + * elevation and multiply the refraction angle by the resulting relative density. + * + * @param {string} refraction + * `"normal"`: correct altitude for atmospheric refraction (recommended). + * `"jplhor"`: for JPL Horizons compatibility testing only; not recommended for normal use. + * `null`: no atmospheric refraction correction is performed. + * + * @param {number} altitude + * An altitude angle in a horizontal coordinate system. Must be a value between -90 and +90. + * + * @returns {number} + * The angular adjustment in degrees to be added to the altitude angle to correct for atmospheric lensing. + */ +export function Refraction(refraction, altitude) { + let refr; + VerifyNumber(altitude); + if (altitude < -90.0 || altitude > +90.0) + return 0.0; /* no attempt to correct an invalid altitude */ + if (refraction === 'normal' || refraction === 'jplhor') { + // http://extras.springer.com/1999/978-1-4471-0555-8/chap4/horizons/horizons.pdf + // JPL Horizons says it uses refraction algorithm from + // Meeus "Astronomical Algorithms", 1991, p. 101-102. + // I found the following Go implementation: + // https://github.com/soniakeys/meeus/blob/master/v3/refraction/refract.go + // This is a translation from the function "Saemundsson" there. + // I found experimentally that JPL Horizons clamps the angle to 1 degree below the horizon. + // This is important because the 'refr' formula below goes crazy near hd = -5.11. + let hd = altitude; + if (hd < -1.0) + hd = -1.0; + refr = (1.02 / Math.tan((hd + 10.3 / (hd + 5.11)) * DEG2RAD)) / 60.0; + if (refraction === 'normal' && altitude < -1.0) { + // In "normal" mode we gradually reduce refraction toward the nadir + // so that we never get an altitude angle less than -90 degrees. + // When horizon angle is -1 degrees, the factor is exactly 1. + // As altitude approaches -90 (the nadir), the fraction approaches 0 linearly. + refr *= (altitude + 90.0) / 89.0; + } + } + else if (!refraction) { + // The caller does not want refraction correction. + refr = 0.0; + } + else { + throw `Invalid refraction option: ${refraction}`; + } + return refr; +} +/** + * @brief Calculates the inverse of an atmospheric refraction angle. + * + * Given an observed altitude angle that includes atmospheric refraction, + * calculates the negative angular correction to obtain the unrefracted + * altitude. This is useful for cases where observed horizontal + * coordinates are to be converted to another orientation system, + * but refraction first must be removed from the observed position. + * + * @param {string} refraction + * `"normal"`: correct altitude for atmospheric refraction (recommended). + * `"jplhor"`: for JPL Horizons compatibility testing only; not recommended for normal use. + * `null`: no atmospheric refraction correction is performed. + * + * @param {number} bent_altitude + * The apparent altitude that includes atmospheric refraction. + * + * @returns {number} + * The angular adjustment in degrees to be added to the + * altitude angle to correct for atmospheric lensing. + * This will be less than or equal to zero. + */ +export function InverseRefraction(refraction, bent_altitude) { + if (bent_altitude < -90.0 || bent_altitude > +90.0) + return 0.0; /* no attempt to correct an invalid altitude */ + /* Find the pre-adjusted altitude whose refraction correction leads to 'altitude'. */ + let altitude = bent_altitude - Refraction(refraction, bent_altitude); + for (;;) { + /* See how close we got. */ + let diff = (altitude + Refraction(refraction, altitude)) - bent_altitude; + if (Math.abs(diff) < 1.0e-14) + return altitude - bent_altitude; + altitude -= diff; + } +} +/** + * @brief Applies a rotation to a vector, yielding a rotated vector. + * + * This function transforms a vector in one orientation to a vector + * in another orientation. + * + * @param {RotationMatrix} rotation + * A rotation matrix that specifies how the orientation of the vector is to be changed. + * + * @param {Vector} vector + * The vector whose orientation is to be changed. + * + * @returns {Vector} + * A vector in the orientation specified by `rotation`. + */ +export function RotateVector(rotation, vector) { + return new Vector(rotation.rot[0][0] * vector.x + rotation.rot[1][0] * vector.y + rotation.rot[2][0] * vector.z, rotation.rot[0][1] * vector.x + rotation.rot[1][1] * vector.y + rotation.rot[2][1] * vector.z, rotation.rot[0][2] * vector.x + rotation.rot[1][2] * vector.y + rotation.rot[2][2] * vector.z, vector.t); +} +/** + * @brief Applies a rotation to a state vector, yielding a rotated vector. + * + * This function transforms a state vector in one orientation to a vector + * in another orientation. + * + * @param {RotationMatrix} rotation + * A rotation matrix that specifies how the orientation of the state vector is to be changed. + * + * @param {StateVector} state + * The state vector whose orientation is to be changed. + * Both the position and velocity components are transformed. + * + * @return {StateVector} + * A state vector in the orientation specified by `rotation`. + */ +export function RotateState(rotation, state) { + return new StateVector(rotation.rot[0][0] * state.x + rotation.rot[1][0] * state.y + rotation.rot[2][0] * state.z, rotation.rot[0][1] * state.x + rotation.rot[1][1] * state.y + rotation.rot[2][1] * state.z, rotation.rot[0][2] * state.x + rotation.rot[1][2] * state.y + rotation.rot[2][2] * state.z, rotation.rot[0][0] * state.vx + rotation.rot[1][0] * state.vy + rotation.rot[2][0] * state.vz, rotation.rot[0][1] * state.vx + rotation.rot[1][1] * state.vy + rotation.rot[2][1] * state.vz, rotation.rot[0][2] * state.vx + rotation.rot[1][2] * state.vy + rotation.rot[2][2] * state.vz, state.t); +} +/** + * @brief Calculates a rotation matrix from J2000 mean equator (EQJ) to J2000 mean ecliptic (ECL). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQJ = equatorial system, using equator at J2000 epoch. + * Target: ECL = ecliptic system, using equator at J2000 epoch. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQJ to ECL. + */ +export function Rotation_EQJ_ECL() { + /* ob = mean obliquity of the J2000 ecliptic = 0.40909260059599012 radians. */ + const c = 0.9174821430670688; /* cos(ob) */ + const s = 0.3977769691083922; /* sin(ob) */ + return new RotationMatrix([ + [1, 0, 0], + [0, +c, -s], + [0, +s, +c] + ]); +} +/** + * @brief Calculates a rotation matrix from J2000 mean ecliptic (ECL) to J2000 mean equator (EQJ). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: ECL = ecliptic system, using equator at J2000 epoch. + * Target: EQJ = equatorial system, using equator at J2000 epoch. + * + * @returns {RotationMatrix} + * A rotation matrix that converts ECL to EQJ. + */ +export function Rotation_ECL_EQJ() { + /* ob = mean obliquity of the J2000 ecliptic = 0.40909260059599012 radians. */ + const c = 0.9174821430670688; /* cos(ob) */ + const s = 0.3977769691083922; /* sin(ob) */ + return new RotationMatrix([ + [1, 0, 0], + [0, +c, +s], + [0, -s, +c] + ]); +} +/** + * @brief Calculates a rotation matrix from J2000 mean equator (EQJ) to equatorial of-date (EQD). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQJ = equatorial system, using equator at J2000 epoch. + * Target: EQD = equatorial system, using equator of the specified date/time. + * + * @param {FlexibleDateTime} time + * The date and time at which the Earth's equator defines the target orientation. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQJ to EQD at `time`. + */ +export function Rotation_EQJ_EQD(time) { + time = MakeTime(time); + const prec = precession_rot(time, PrecessDirection.From2000); + const nut = nutation_rot(time, PrecessDirection.From2000); + return CombineRotation(prec, nut); +} +/** + * @brief Calculates a rotation matrix from J2000 mean equator (EQJ) to true ecliptic of date (ECT). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQJ = equatorial system, using equator at J2000 epoch. + * Target: ECT = ecliptic system, using true equinox of the specified date/time. + * + * @param {FlexibleDateTime} time + * The date and time at which the Earth's equator defines the target orientation. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQJ to ECT at `time`. + */ +export function Rotation_EQJ_ECT(time) { + const t = MakeTime(time); + const rot = Rotation_EQJ_EQD(t); + const step = Rotation_EQD_ECT(t); + return CombineRotation(rot, step); +} +/** + * @brief Calculates a rotation matrix from true ecliptic of date (ECT) to J2000 mean equator (EQJ). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: ECT = ecliptic system, using true equinox of the specified date/time. + * Target: EQJ = equatorial system, using equator at J2000 epoch. + * + * @param {FlexibleDateTime} time + * The date and time at which the Earth's equator defines the target orientation. + * + * @returns {RotationMatrix} + * A rotation matrix that converts ECT to EQJ at `time`. + */ +export function Rotation_ECT_EQJ(time) { + const t = MakeTime(time); + const rot = Rotation_ECT_EQD(t); + const step = Rotation_EQD_EQJ(t); + return CombineRotation(rot, step); +} +/** + * @brief Calculates a rotation matrix from equatorial of-date (EQD) to J2000 mean equator (EQJ). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQD = equatorial system, using equator of the specified date/time. + * Target: EQJ = equatorial system, using equator at J2000 epoch. + * + * @param {FlexibleDateTime} time + * The date and time at which the Earth's equator defines the source orientation. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQD at `time` to EQJ. + */ +export function Rotation_EQD_EQJ(time) { + time = MakeTime(time); + const nut = nutation_rot(time, PrecessDirection.Into2000); + const prec = precession_rot(time, PrecessDirection.Into2000); + return CombineRotation(nut, prec); +} +/** + * @brief Calculates a rotation matrix from equatorial of-date (EQD) to horizontal (HOR). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQD = equatorial system, using equator of the specified date/time. + * Target: HOR = horizontal system. + * + * Use `HorizonFromVector` to convert the return value + * to a traditional altitude/azimuth pair. + * + * @param {FlexibleDateTime} time + * The date and time at which the Earth's equator applies. + * + * @param {Observer} observer + * A location near the Earth's mean sea level that defines the observer's horizon. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQD to HOR at `time` and for `observer`. + * The components of the horizontal vector are: + * x = north, y = west, z = zenith (straight up from the observer). + * These components are chosen so that the "right-hand rule" works for the vector + * and so that north represents the direction where azimuth = 0. + */ +export function Rotation_EQD_HOR(time, observer) { + time = MakeTime(time); + const sinlat = Math.sin(observer.latitude * DEG2RAD); + const coslat = Math.cos(observer.latitude * DEG2RAD); + const sinlon = Math.sin(observer.longitude * DEG2RAD); + const coslon = Math.cos(observer.longitude * DEG2RAD); + const uze = [coslat * coslon, coslat * sinlon, sinlat]; + const une = [-sinlat * coslon, -sinlat * sinlon, coslat]; + const uwe = [sinlon, -coslon, 0]; + const spin_angle = -15 * sidereal_time(time); + const uz = spin(spin_angle, uze); + const un = spin(spin_angle, une); + const uw = spin(spin_angle, uwe); + return new RotationMatrix([ + [un[0], uw[0], uz[0]], + [un[1], uw[1], uz[1]], + [un[2], uw[2], uz[2]], + ]); +} +/** + * @brief Calculates a rotation matrix from horizontal (HOR) to equatorial of-date (EQD). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: HOR = horizontal system (x=North, y=West, z=Zenith). + * Target: EQD = equatorial system, using equator of the specified date/time. + * + * @param {FlexibleDateTime} time + * The date and time at which the Earth's equator applies. + * + * @param {Observer} observer + * A location near the Earth's mean sea level that defines the observer's horizon. + * + * @returns {RotationMatrix} + * A rotation matrix that converts HOR to EQD at `time` and for `observer`. + */ +export function Rotation_HOR_EQD(time, observer) { + const rot = Rotation_EQD_HOR(time, observer); + return InverseRotation(rot); +} +/** + * @brief Calculates a rotation matrix from horizontal (HOR) to J2000 equatorial (EQJ). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: HOR = horizontal system (x=North, y=West, z=Zenith). + * Target: EQJ = equatorial system, using equator at the J2000 epoch. + * + * @param {FlexibleDateTime} time + * The date and time of the observation. + * + * @param {Observer} observer + * A location near the Earth's mean sea level that defines the observer's horizon. + * + * @returns {RotationMatrix} + * A rotation matrix that converts HOR to EQJ at `time` and for `observer`. + */ +export function Rotation_HOR_EQJ(time, observer) { + time = MakeTime(time); + const hor_eqd = Rotation_HOR_EQD(time, observer); + const eqd_eqj = Rotation_EQD_EQJ(time); + return CombineRotation(hor_eqd, eqd_eqj); +} +/** + * @brief Calculates a rotation matrix from J2000 mean equator (EQJ) to horizontal (HOR). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQJ = equatorial system, using the equator at the J2000 epoch. + * Target: HOR = horizontal system. + * + * Use {@link HorizonFromVector} to convert the return value + * to a traditional altitude/azimuth pair. + * + * @param {FlexibleDateTime} time + * The date and time of the desired horizontal orientation. + * + * @param {Observer} observer + * A location near the Earth's mean sea level that defines the observer's horizon. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQJ to HOR at `time` and for `observer`. + * The components of the horizontal vector are: + * x = north, y = west, z = zenith (straight up from the observer). + * These components are chosen so that the "right-hand rule" works for the vector + * and so that north represents the direction where azimuth = 0. + */ +export function Rotation_EQJ_HOR(time, observer) { + const rot = Rotation_HOR_EQJ(time, observer); + return InverseRotation(rot); +} +/** + * @brief Calculates a rotation matrix from equatorial of-date (EQD) to J2000 mean ecliptic (ECL). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQD = equatorial system, using equator of date. + * Target: ECL = ecliptic system, using equator at J2000 epoch. + * + * @param {FlexibleDateTime} time + * The date and time of the source equator. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQD to ECL. + */ +export function Rotation_EQD_ECL(time) { + const eqd_eqj = Rotation_EQD_EQJ(time); + const eqj_ecl = Rotation_EQJ_ECL(); + return CombineRotation(eqd_eqj, eqj_ecl); +} +/** + * @brief Calculates a rotation matrix from J2000 mean ecliptic (ECL) to equatorial of-date (EQD). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: ECL = ecliptic system, using equator at J2000 epoch. + * Target: EQD = equatorial system, using equator of date. + * + * @param {FlexibleDateTime} time + * The date and time of the desired equator. + * + * @returns {RotationMatrix} + * A rotation matrix that converts ECL to EQD. + */ +export function Rotation_ECL_EQD(time) { + const rot = Rotation_EQD_ECL(time); + return InverseRotation(rot); +} +/** + * @brief Calculates a rotation matrix from J2000 mean ecliptic (ECL) to horizontal (HOR). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: ECL = ecliptic system, using equator at J2000 epoch. + * Target: HOR = horizontal system. + * + * Use {@link HorizonFromVector} to convert the return value + * to a traditional altitude/azimuth pair. + * + * @param {FlexibleDateTime} time + * The date and time of the desired horizontal orientation. + * + * @param {Observer} observer + * A location near the Earth's mean sea level that defines the observer's horizon. + * + * @returns {RotationMatrix} + * A rotation matrix that converts ECL to HOR at `time` and for `observer`. + * The components of the horizontal vector are: + * x = north, y = west, z = zenith (straight up from the observer). + * These components are chosen so that the "right-hand rule" works for the vector + * and so that north represents the direction where azimuth = 0. + */ +export function Rotation_ECL_HOR(time, observer) { + time = MakeTime(time); + const ecl_eqd = Rotation_ECL_EQD(time); + const eqd_hor = Rotation_EQD_HOR(time, observer); + return CombineRotation(ecl_eqd, eqd_hor); +} +/** + * @brief Calculates a rotation matrix from horizontal (HOR) to J2000 mean ecliptic (ECL). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: HOR = horizontal system. + * Target: ECL = ecliptic system, using equator at J2000 epoch. + * + * @param {FlexibleDateTime} time + * The date and time of the horizontal observation. + * + * @param {Observer} observer + * The location of the horizontal observer. + * + * @returns {RotationMatrix} + * A rotation matrix that converts HOR to ECL. + */ +export function Rotation_HOR_ECL(time, observer) { + const rot = Rotation_ECL_HOR(time, observer); + return InverseRotation(rot); +} +/** + * @brief Calculates a rotation matrix from J2000 mean equator (EQJ) to galactic (GAL). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQJ = equatorial system, using the equator at the J2000 epoch. + * Target: GAL = galactic system (IAU 1958 definition). + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQJ to GAL. + */ +export function Rotation_EQJ_GAL() { + // This rotation matrix was calculated by the following script + // in this same source code repository: + // demo/python/galeqj_matrix.py + return new RotationMatrix([ + [-0.0548624779711344, +0.4941095946388765, -0.8676668813529025], + [-0.8734572784246782, -0.4447938112296831, -0.1980677870294097], + [-0.4838000529948520, +0.7470034631630423, +0.4559861124470794] + ]); +} +/** + * @brief Calculates a rotation matrix from galactic (GAL) to J2000 mean equator (EQJ). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: GAL = galactic system (IAU 1958 definition). + * Target: EQJ = equatorial system, using the equator at the J2000 epoch. + * + * @returns {RotationMatrix} + * A rotation matrix that converts GAL to EQJ. + */ +export function Rotation_GAL_EQJ() { + // This rotation matrix was calculated by the following script + // in this same source code repository: + // demo/python/galeqj_matrix.py + return new RotationMatrix([ + [-0.0548624779711344, -0.8734572784246782, -0.4838000529948520], + [+0.4941095946388765, -0.4447938112296831, +0.7470034631630423], + [-0.8676668813529025, -0.1980677870294097, +0.4559861124470794] + ]); +} +/** + * @brief Calculates a rotation matrix from true ecliptic of date (ECT) to equator of date (EQD). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: ECT = true ecliptic of date + * Target: EQD = equator of date + * + * @param {FlexibleDateTime} time + * The date and time of the ecliptic/equator conversion. + * + * @returns {RotationMatrix} + * A rotation matrix that converts ECT to EQD. + */ +export function Rotation_ECT_EQD(time) { + const et = e_tilt(MakeTime(time)); + const tobl = et.tobl * DEG2RAD; + const c = Math.cos(tobl); + const s = Math.sin(tobl); + return new RotationMatrix([ + [1.0, 0.0, 0.0], + [0.0, +c, +s], + [0.0, -s, +c] + ]); +} +/** + * @brief Calculates a rotation matrix from equator of date (EQD) to true ecliptic of date (ECT). + * + * This is one of the family of functions that returns a rotation matrix + * for converting from one orientation to another. + * Source: EQD = equator of date + * Target: ECT = true ecliptic of date + * + * @param {FlexibleDateTime} time + * The date and time of the equator/ecliptic conversion. + * + * @returns {RotationMatrix} + * A rotation matrix that converts EQD to ECT. + */ +export function Rotation_EQD_ECT(time) { + const et = e_tilt(MakeTime(time)); + const tobl = et.tobl * DEG2RAD; + const c = Math.cos(tobl); + const s = Math.sin(tobl); + return new RotationMatrix([ + [1.0, 0.0, 0.0], + [0.0, +c, -s], + [0.0, +s, +c] + ]); +} +const ConstelNames = [ + ['And', 'Andromeda'] // 0 + , + ['Ant', 'Antila'] // 1 + , + ['Aps', 'Apus'] // 2 + , + ['Aql', 'Aquila'] // 3 + , + ['Aqr', 'Aquarius'] // 4 + , + ['Ara', 'Ara'] // 5 + , + ['Ari', 'Aries'] // 6 + , + ['Aur', 'Auriga'] // 7 + , + ['Boo', 'Bootes'] // 8 + , + ['Cae', 'Caelum'] // 9 + , + ['Cam', 'Camelopardis'] // 10 + , + ['Cap', 'Capricornus'] // 11 + , + ['Car', 'Carina'] // 12 + , + ['Cas', 'Cassiopeia'] // 13 + , + ['Cen', 'Centaurus'] // 14 + , + ['Cep', 'Cepheus'] // 15 + , + ['Cet', 'Cetus'] // 16 + , + ['Cha', 'Chamaeleon'] // 17 + , + ['Cir', 'Circinus'] // 18 + , + ['CMa', 'Canis Major'] // 19 + , + ['CMi', 'Canis Minor'] // 20 + , + ['Cnc', 'Cancer'] // 21 + , + ['Col', 'Columba'] // 22 + , + ['Com', 'Coma Berenices'] // 23 + , + ['CrA', 'Corona Australis'] // 24 + , + ['CrB', 'Corona Borealis'] // 25 + , + ['Crt', 'Crater'] // 26 + , + ['Cru', 'Crux'] // 27 + , + ['Crv', 'Corvus'] // 28 + , + ['CVn', 'Canes Venatici'] // 29 + , + ['Cyg', 'Cygnus'] // 30 + , + ['Del', 'Delphinus'] // 31 + , + ['Dor', 'Dorado'] // 32 + , + ['Dra', 'Draco'] // 33 + , + ['Equ', 'Equuleus'] // 34 + , + ['Eri', 'Eridanus'] // 35 + , + ['For', 'Fornax'] // 36 + , + ['Gem', 'Gemini'] // 37 + , + ['Gru', 'Grus'] // 38 + , + ['Her', 'Hercules'] // 39 + , + ['Hor', 'Horologium'] // 40 + , + ['Hya', 'Hydra'] // 41 + , + ['Hyi', 'Hydrus'] // 42 + , + ['Ind', 'Indus'] // 43 + , + ['Lac', 'Lacerta'] // 44 + , + ['Leo', 'Leo'] // 45 + , + ['Lep', 'Lepus'] // 46 + , + ['Lib', 'Libra'] // 47 + , + ['LMi', 'Leo Minor'] // 48 + , + ['Lup', 'Lupus'] // 49 + , + ['Lyn', 'Lynx'] // 50 + , + ['Lyr', 'Lyra'] // 51 + , + ['Men', 'Mensa'] // 52 + , + ['Mic', 'Microscopium'] // 53 + , + ['Mon', 'Monoceros'] // 54 + , + ['Mus', 'Musca'] // 55 + , + ['Nor', 'Norma'] // 56 + , + ['Oct', 'Octans'] // 57 + , + ['Oph', 'Ophiuchus'] // 58 + , + ['Ori', 'Orion'] // 59 + , + ['Pav', 'Pavo'] // 60 + , + ['Peg', 'Pegasus'] // 61 + , + ['Per', 'Perseus'] // 62 + , + ['Phe', 'Phoenix'] // 63 + , + ['Pic', 'Pictor'] // 64 + , + ['PsA', 'Pisces Austrinus'] // 65 + , + ['Psc', 'Pisces'] // 66 + , + ['Pup', 'Puppis'] // 67 + , + ['Pyx', 'Pyxis'] // 68 + , + ['Ret', 'Reticulum'] // 69 + , + ['Scl', 'Sculptor'] // 70 + , + ['Sco', 'Scorpius'] // 71 + , + ['Sct', 'Scutum'] // 72 + , + ['Ser', 'Serpens'] // 73 + , + ['Sex', 'Sextans'] // 74 + , + ['Sge', 'Sagitta'] // 75 + , + ['Sgr', 'Sagittarius'] // 76 + , + ['Tau', 'Taurus'] // 77 + , + ['Tel', 'Telescopium'] // 78 + , + ['TrA', 'Triangulum Australe'] // 79 + , + ['Tri', 'Triangulum'] // 80 + , + ['Tuc', 'Tucana'] // 81 + , + ['UMa', 'Ursa Major'] // 82 + , + ['UMi', 'Ursa Minor'] // 83 + , + ['Vel', 'Vela'] // 84 + , + ['Vir', 'Virgo'] // 85 + , + ['Vol', 'Volans'] // 86 + , + ['Vul', 'Vulpecula'] // 87 +]; +const ConstelBounds = [ + [83, 0, 8640, 2112] // UMi + , + [83, 2880, 5220, 2076] // UMi + , + [83, 7560, 8280, 2068] // UMi + , + [83, 6480, 7560, 2064] // UMi + , + [15, 0, 2880, 2040] // Cep + , + [10, 3300, 3840, 1968] // Cam + , + [15, 0, 1800, 1920] // Cep + , + [10, 3840, 5220, 1920] // Cam + , + [83, 6300, 6480, 1920] // UMi + , + [33, 7260, 7560, 1920] // Dra + , + [15, 0, 1263, 1848] // Cep + , + [10, 4140, 4890, 1848] // Cam + , + [83, 5952, 6300, 1800] // UMi + , + [15, 7260, 7440, 1800] // Cep + , + [10, 2868, 3300, 1764] // Cam + , + [33, 3300, 4080, 1764] // Dra + , + [83, 4680, 5952, 1680] // UMi + , + [13, 1116, 1230, 1632] // Cas + , + [33, 7350, 7440, 1608] // Dra + , + [33, 4080, 4320, 1596] // Dra + , + [15, 0, 120, 1584] // Cep + , + [83, 5040, 5640, 1584] // UMi + , + [15, 8490, 8640, 1584] // Cep + , + [33, 4320, 4860, 1536] // Dra + , + [33, 4860, 5190, 1512] // Dra + , + [15, 8340, 8490, 1512] // Cep + , + [10, 2196, 2520, 1488] // Cam + , + [33, 7200, 7350, 1476] // Dra + , + [15, 7393.2, 7416, 1462] // Cep + , + [10, 2520, 2868, 1440] // Cam + , + [82, 2868, 3030, 1440] // UMa + , + [33, 7116, 7200, 1428] // Dra + , + [15, 7200, 7393.2, 1428] // Cep + , + [15, 8232, 8340, 1418] // Cep + , + [13, 0, 876, 1404] // Cas + , + [33, 6990, 7116, 1392] // Dra + , + [13, 612, 687, 1380] // Cas + , + [13, 876, 1116, 1368] // Cas + , + [10, 1116, 1140, 1368] // Cam + , + [15, 8034, 8232, 1350] // Cep + , + [10, 1800, 2196, 1344] // Cam + , + [82, 5052, 5190, 1332] // UMa + , + [33, 5190, 6990, 1332] // Dra + , + [10, 1140, 1200, 1320] // Cam + , + [15, 7968, 8034, 1320] // Cep + , + [15, 7416, 7908, 1316] // Cep + , + [13, 0, 612, 1296] // Cas + , + [50, 2196, 2340, 1296] // Lyn + , + [82, 4350, 4860, 1272] // UMa + , + [33, 5490, 5670, 1272] // Dra + , + [15, 7908, 7968, 1266] // Cep + , + [10, 1200, 1800, 1260] // Cam + , + [13, 8232, 8400, 1260] // Cas + , + [33, 5670, 6120, 1236] // Dra + , + [62, 735, 906, 1212] // Per + , + [33, 6120, 6564, 1212] // Dra + , + [13, 0, 492, 1200] // Cas + , + [62, 492, 600, 1200] // Per + , + [50, 2340, 2448, 1200] // Lyn + , + [13, 8400, 8640, 1200] // Cas + , + [82, 4860, 5052, 1164] // UMa + , + [13, 0, 402, 1152] // Cas + , + [13, 8490, 8640, 1152] // Cas + , + [39, 6543, 6564, 1140] // Her + , + [33, 6564, 6870, 1140] // Dra + , + [30, 6870, 6900, 1140] // Cyg + , + [62, 600, 735, 1128] // Per + , + [82, 3030, 3300, 1128] // UMa + , + [13, 60, 312, 1104] // Cas + , + [82, 4320, 4350, 1080] // UMa + , + [50, 2448, 2652, 1068] // Lyn + , + [30, 7887, 7908, 1056] // Cyg + , + [30, 7875, 7887, 1050] // Cyg + , + [30, 6900, 6984, 1044] // Cyg + , + [82, 3300, 3660, 1008] // UMa + , + [82, 3660, 3882, 960] // UMa + , + [8, 5556, 5670, 960] // Boo + , + [39, 5670, 5880, 960] // Her + , + [50, 3330, 3450, 954] // Lyn + , + [0, 0, 906, 882] // And + , + [62, 906, 924, 882] // Per + , + [51, 6969, 6984, 876] // Lyr + , + [62, 1620, 1689, 864] // Per + , + [30, 7824, 7875, 864] // Cyg + , + [44, 7875, 7920, 864] // Lac + , + [7, 2352, 2652, 852] // Aur + , + [50, 2652, 2790, 852] // Lyn + , + [0, 0, 720, 840] // And + , + [44, 7920, 8214, 840] // Lac + , + [44, 8214, 8232, 828] // Lac + , + [0, 8232, 8460, 828] // And + , + [62, 924, 978, 816] // Per + , + [82, 3882, 3960, 816] // UMa + , + [29, 4320, 4440, 816] // CVn + , + [50, 2790, 3330, 804] // Lyn + , + [48, 3330, 3558, 804] // LMi + , + [0, 258, 507, 792] // And + , + [8, 5466, 5556, 792] // Boo + , + [0, 8460, 8550, 770] // And + , + [29, 4440, 4770, 768] // CVn + , + [0, 8550, 8640, 752] // And + , + [29, 5025, 5052, 738] // CVn + , + [80, 870, 978, 736] // Tri + , + [62, 978, 1620, 736] // Per + , + [7, 1620, 1710, 720] // Aur + , + [51, 6543, 6969, 720] // Lyr + , + [82, 3960, 4320, 696] // UMa + , + [30, 7080, 7530, 696] // Cyg + , + [7, 1710, 2118, 684] // Aur + , + [48, 3558, 3780, 684] // LMi + , + [29, 4770, 5025, 684] // CVn + , + [0, 0, 24, 672] // And + , + [80, 507, 600, 672] // Tri + , + [7, 2118, 2352, 672] // Aur + , + [37, 2838, 2880, 672] // Gem + , + [30, 7530, 7824, 672] // Cyg + , + [30, 6933, 7080, 660] // Cyg + , + [80, 690, 870, 654] // Tri + , + [25, 5820, 5880, 648] // CrB + , + [8, 5430, 5466, 624] // Boo + , + [25, 5466, 5820, 624] // CrB + , + [51, 6612, 6792, 624] // Lyr + , + [48, 3870, 3960, 612] // LMi + , + [51, 6792, 6933, 612] // Lyr + , + [80, 600, 690, 600] // Tri + , + [66, 258, 306, 570] // Psc + , + [48, 3780, 3870, 564] // LMi + , + [87, 7650, 7710, 564] // Vul + , + [77, 2052, 2118, 548] // Tau + , + [0, 24, 51, 528] // And + , + [73, 5730, 5772, 528] // Ser + , + [37, 2118, 2238, 516] // Gem + , + [87, 7140, 7290, 510] // Vul + , + [87, 6792, 6930, 506] // Vul + , + [0, 51, 306, 504] // And + , + [87, 7290, 7404, 492] // Vul + , + [37, 2811, 2838, 480] // Gem + , + [87, 7404, 7650, 468] // Vul + , + [87, 6930, 7140, 460] // Vul + , + [6, 1182, 1212, 456] // Ari + , + [75, 6792, 6840, 444] // Sge + , + [59, 2052, 2076, 432] // Ori + , + [37, 2238, 2271, 420] // Gem + , + [75, 6840, 7140, 388] // Sge + , + [77, 1788, 1920, 384] // Tau + , + [39, 5730, 5790, 384] // Her + , + [75, 7140, 7290, 378] // Sge + , + [77, 1662, 1788, 372] // Tau + , + [77, 1920, 2016, 372] // Tau + , + [23, 4620, 4860, 360] // Com + , + [39, 6210, 6570, 344] // Her + , + [23, 4272, 4620, 336] // Com + , + [37, 2700, 2811, 324] // Gem + , + [39, 6030, 6210, 308] // Her + , + [61, 0, 51, 300] // Peg + , + [77, 2016, 2076, 300] // Tau + , + [37, 2520, 2700, 300] // Gem + , + [61, 7602, 7680, 300] // Peg + , + [37, 2271, 2496, 288] // Gem + , + [39, 6570, 6792, 288] // Her + , + [31, 7515, 7578, 284] // Del + , + [61, 7578, 7602, 284] // Peg + , + [45, 4146, 4272, 264] // Leo + , + [59, 2247, 2271, 240] // Ori + , + [37, 2496, 2520, 240] // Gem + , + [21, 2811, 2853, 240] // Cnc + , + [61, 8580, 8640, 240] // Peg + , + [6, 600, 1182, 238] // Ari + , + [31, 7251, 7308, 204] // Del + , + [8, 4860, 5430, 192] // Boo + , + [61, 8190, 8580, 180] // Peg + , + [21, 2853, 3330, 168] // Cnc + , + [45, 3330, 3870, 168] // Leo + , + [58, 6570, 6718.4, 150] // Oph + , + [3, 6718.4, 6792, 150] // Aql + , + [31, 7500, 7515, 144] // Del + , + [20, 2520, 2526, 132] // CMi + , + [73, 6570, 6633, 108] // Ser + , + [39, 5790, 6030, 96] // Her + , + [58, 6570, 6633, 72] // Oph + , + [61, 7728, 7800, 66] // Peg + , + [66, 0, 720, 48] // Psc + , + [73, 6690, 6792, 48] // Ser + , + [31, 7308, 7500, 48] // Del + , + [34, 7500, 7680, 48] // Equ + , + [61, 7680, 7728, 48] // Peg + , + [61, 7920, 8190, 48] // Peg + , + [61, 7800, 7920, 42] // Peg + , + [20, 2526, 2592, 36] // CMi + , + [77, 1290, 1662, 0] // Tau + , + [59, 1662, 1680, 0] // Ori + , + [20, 2592, 2910, 0] // CMi + , + [85, 5280, 5430, 0] // Vir + , + [58, 6420, 6570, 0] // Oph + , + [16, 954, 1182, -42] // Cet + , + [77, 1182, 1290, -42] // Tau + , + [73, 5430, 5856, -78] // Ser + , + [59, 1680, 1830, -96] // Ori + , + [59, 2100, 2247, -96] // Ori + , + [73, 6420, 6468, -96] // Ser + , + [73, 6570, 6690, -96] // Ser + , + [3, 6690, 6792, -96] // Aql + , + [66, 8190, 8580, -96] // Psc + , + [45, 3870, 4146, -144] // Leo + , + [85, 4146, 4260, -144] // Vir + , + [66, 0, 120, -168] // Psc + , + [66, 8580, 8640, -168] // Psc + , + [85, 5130, 5280, -192] // Vir + , + [58, 5730, 5856, -192] // Oph + , + [3, 7200, 7392, -216] // Aql + , + [4, 7680, 7872, -216] // Aqr + , + [58, 6180, 6468, -240] // Oph + , + [54, 2100, 2910, -264] // Mon + , + [35, 1770, 1830, -264] // Eri + , + [59, 1830, 2100, -264] // Ori + , + [41, 2910, 3012, -264] // Hya + , + [74, 3450, 3870, -264] // Sex + , + [85, 4260, 4620, -264] // Vir + , + [58, 6330, 6360, -280] // Oph + , + [3, 6792, 7200, -288.8] // Aql + , + [35, 1740, 1770, -348] // Eri + , + [4, 7392, 7680, -360] // Aqr + , + [73, 6180, 6570, -384] // Ser + , + [72, 6570, 6792, -384] // Sct + , + [41, 3012, 3090, -408] // Hya + , + [58, 5856, 5895, -438] // Oph + , + [41, 3090, 3270, -456] // Hya + , + [26, 3870, 3900, -456] // Crt + , + [71, 5856, 5895, -462] // Sco + , + [47, 5640, 5730, -480] // Lib + , + [28, 4530, 4620, -528] // Crv + , + [85, 4620, 5130, -528] // Vir + , + [41, 3270, 3510, -576] // Hya + , + [16, 600, 954, -585.2] // Cet + , + [35, 954, 1350, -585.2] // Eri + , + [26, 3900, 4260, -588] // Crt + , + [28, 4260, 4530, -588] // Crv + , + [47, 5130, 5370, -588] // Lib + , + [58, 5856, 6030, -590] // Oph + , + [16, 0, 600, -612] // Cet + , + [11, 7680, 7872, -612] // Cap + , + [4, 7872, 8580, -612] // Aqr + , + [16, 8580, 8640, -612] // Cet + , + [41, 3510, 3690, -636] // Hya + , + [35, 1692, 1740, -654] // Eri + , + [46, 1740, 2202, -654] // Lep + , + [11, 7200, 7680, -672] // Cap + , + [41, 3690, 3810, -700] // Hya + , + [41, 4530, 5370, -708] // Hya + , + [47, 5370, 5640, -708] // Lib + , + [71, 5640, 5760, -708] // Sco + , + [35, 1650, 1692, -720] // Eri + , + [58, 6030, 6336, -720] // Oph + , + [76, 6336, 6420, -720] // Sgr + , + [41, 3810, 3900, -748] // Hya + , + [19, 2202, 2652, -792] // CMa + , + [41, 4410, 4530, -792] // Hya + , + [41, 3900, 4410, -840] // Hya + , + [36, 1260, 1350, -864] // For + , + [68, 3012, 3372, -882] // Pyx + , + [35, 1536, 1650, -888] // Eri + , + [76, 6420, 6900, -888] // Sgr + , + [65, 7680, 8280, -888] // PsA + , + [70, 8280, 8400, -888] // Scl + , + [36, 1080, 1260, -950] // For + , + [1, 3372, 3960, -954] // Ant + , + [70, 0, 600, -960] // Scl + , + [36, 600, 1080, -960] // For + , + [35, 1392, 1536, -960] // Eri + , + [70, 8400, 8640, -960] // Scl + , + [14, 5100, 5370, -1008] // Cen + , + [49, 5640, 5760, -1008] // Lup + , + [71, 5760, 5911.5, -1008] // Sco + , + [9, 1740, 1800, -1032] // Cae + , + [22, 1800, 2370, -1032] // Col + , + [67, 2880, 3012, -1032] // Pup + , + [35, 1230, 1392, -1056] // Eri + , + [71, 5911.5, 6420, -1092] // Sco + , + [24, 6420, 6900, -1092] // CrA + , + [76, 6900, 7320, -1092] // Sgr + , + [53, 7320, 7680, -1092] // Mic + , + [35, 1080, 1230, -1104] // Eri + , + [9, 1620, 1740, -1116] // Cae + , + [49, 5520, 5640, -1152] // Lup + , + [63, 0, 840, -1156] // Phe + , + [35, 960, 1080, -1176] // Eri + , + [40, 1470, 1536, -1176] // Hor + , + [9, 1536, 1620, -1176] // Cae + , + [38, 7680, 7920, -1200] // Gru + , + [67, 2160, 2880, -1218] // Pup + , + [84, 2880, 2940, -1218] // Vel + , + [35, 870, 960, -1224] // Eri + , + [40, 1380, 1470, -1224] // Hor + , + [63, 0, 660, -1236] // Phe + , + [12, 2160, 2220, -1260] // Car + , + [84, 2940, 3042, -1272] // Vel + , + [40, 1260, 1380, -1276] // Hor + , + [32, 1380, 1440, -1276] // Dor + , + [63, 0, 570, -1284] // Phe + , + [35, 780, 870, -1296] // Eri + , + [64, 1620, 1800, -1296] // Pic + , + [49, 5418, 5520, -1296] // Lup + , + [84, 3042, 3180, -1308] // Vel + , + [12, 2220, 2340, -1320] // Car + , + [14, 4260, 4620, -1320] // Cen + , + [49, 5100, 5418, -1320] // Lup + , + [56, 5418, 5520, -1320] // Nor + , + [32, 1440, 1560, -1356] // Dor + , + [84, 3180, 3960, -1356] // Vel + , + [14, 3960, 4050, -1356] // Cen + , + [5, 6300, 6480, -1368] // Ara + , + [78, 6480, 7320, -1368] // Tel + , + [38, 7920, 8400, -1368] // Gru + , + [40, 1152, 1260, -1380] // Hor + , + [64, 1800, 1980, -1380] // Pic + , + [12, 2340, 2460, -1392] // Car + , + [63, 0, 480, -1404] // Phe + , + [35, 480, 780, -1404] // Eri + , + [63, 8400, 8640, -1404] // Phe + , + [32, 1560, 1650, -1416] // Dor + , + [56, 5520, 5911.5, -1440] // Nor + , + [43, 7320, 7680, -1440] // Ind + , + [64, 1980, 2160, -1464] // Pic + , + [18, 5460, 5520, -1464] // Cir + , + [5, 5911.5, 5970, -1464] // Ara + , + [18, 5370, 5460, -1526] // Cir + , + [5, 5970, 6030, -1526] // Ara + , + [64, 2160, 2460, -1536] // Pic + , + [12, 2460, 3252, -1536] // Car + , + [14, 4050, 4260, -1536] // Cen + , + [27, 4260, 4620, -1536] // Cru + , + [14, 4620, 5232, -1536] // Cen + , + [18, 4860, 4920, -1560] // Cir + , + [5, 6030, 6060, -1560] // Ara + , + [40, 780, 1152, -1620] // Hor + , + [69, 1152, 1650, -1620] // Ret + , + [18, 5310, 5370, -1620] // Cir + , + [5, 6060, 6300, -1620] // Ara + , + [60, 6300, 6480, -1620] // Pav + , + [81, 7920, 8400, -1620] // Tuc + , + [32, 1650, 2370, -1680] // Dor + , + [18, 4920, 5310, -1680] // Cir + , + [79, 5310, 6120, -1680] // TrA + , + [81, 0, 480, -1800] // Tuc + , + [42, 1260, 1650, -1800] // Hyi + , + [86, 2370, 3252, -1800] // Vol + , + [12, 3252, 4050, -1800] // Car + , + [55, 4050, 4920, -1800] // Mus + , + [60, 6480, 7680, -1800] // Pav + , + [43, 7680, 8400, -1800] // Ind + , + [81, 8400, 8640, -1800] // Tuc + , + [81, 270, 480, -1824] // Tuc + , + [42, 0, 1260, -1980] // Hyi + , + [17, 2760, 4920, -1980] // Cha + , + [2, 4920, 6480, -1980] // Aps + , + [52, 1260, 2760, -2040] // Men + , + [57, 0, 8640, -2160] // Oct +]; +let ConstelRot; +let Epoch2000; +/** + * @brief Reports the constellation that a given celestial point lies within. + * + * @property {string} symbol + * 3-character mnemonic symbol for the constellation, e.g. "Ori". + * + * @property {string} name + * Full name of constellation, e.g. "Orion". + * + * @property {number} ra1875 + * Right ascension expressed in B1875 coordinates. + * + * @property {number} dec1875 + * Declination expressed in B1875 coordinates. + */ +export class ConstellationInfo { + constructor(symbol, name, ra1875, dec1875) { + this.symbol = symbol; + this.name = name; + this.ra1875 = ra1875; + this.dec1875 = dec1875; + } +} +/** + * @brief Determines the constellation that contains the given point in the sky. + * + * Given J2000 equatorial (EQJ) coordinates of a point in the sky, + * determines the constellation that contains that point. + * + * @param {number} ra + * The right ascension (RA) of a point in the sky, using the J2000 equatorial system. + * + * @param {number} dec + * The declination (DEC) of a point in the sky, using the J2000 equatorial system. + * + * @returns {ConstellationInfo} + * An object that contains the 3-letter abbreviation and full name + * of the constellation that contains the given (ra,dec), along with + * the converted B1875 (ra,dec) for that point. + */ +export function Constellation(ra, dec) { + VerifyNumber(ra); + VerifyNumber(dec); + if (dec < -90 || dec > +90) + throw 'Invalid declination angle. Must be -90..+90.'; + // Clamp right ascension to [0, 24) sidereal hours. + ra %= 24.0; + if (ra < 0.0) + ra += 24.0; + // Lazy-initialize rotation matrix. + if (!ConstelRot) { + // Need to calculate the B1875 epoch. Based on this: + // https://en.wikipedia.org/wiki/Epoch_(astronomy)#Besselian_years + // B = 1900 + (JD - 2415020.31352) / 365.242198781 + // I'm interested in using TT instead of JD, giving: + // B = 1900 + ((TT+2451545) - 2415020.31352) / 365.242198781 + // B = 1900 + (TT + 36524.68648) / 365.242198781 + // TT = 365.242198781*(B - 1900) - 36524.68648 = -45655.741449525 + // But the AstroTime constructor wants UT, not TT. + // Near that date, I get a historical correction of ut-tt = 3.2 seconds. + // That gives UT = -45655.74141261017 for the B1875 epoch, + // or 1874-12-31T18:12:21.950Z. + ConstelRot = Rotation_EQJ_EQD(new AstroTime(-45655.74141261017)); + Epoch2000 = new AstroTime(0); + } + // Convert coordinates from J2000 to B1875. + const sph2000 = new Spherical(dec, 15.0 * ra, 1.0); + const vec2000 = VectorFromSphere(sph2000, Epoch2000); + const vec1875 = RotateVector(ConstelRot, vec2000); + const equ1875 = EquatorFromVector(vec1875); + // Search for the constellation using the B1875 coordinates. + const fd = 10 / (4 * 60); // conversion factor from compact units to DEC degrees + const fr = fd / 15; // conversion factor from compact units to RA sidereal hours + for (let b of ConstelBounds) { + // Convert compact angular units to RA in hours, DEC in degrees. + const dec = b[3] * fd; + const ra_lo = b[1] * fr; + const ra_hi = b[2] * fr; + if (dec <= equ1875.dec && ra_lo <= equ1875.ra && equ1875.ra < ra_hi) { + const c = ConstelNames[b[0]]; + return new ConstellationInfo(c[0], c[1], equ1875.ra, equ1875.dec); + } + } + // This should never happen! + throw 'Unable to find constellation for given coordinates.'; +} +/** + * @brief The different kinds of lunar/solar eclipses.. + * + * `Penumbral`: A lunar eclipse in which only the Earth's penumbra falls on the Moon. (Never used for a solar eclipse.) + * `Partial`: A partial lunar/solar eclipse. + * `Annular`: A solar eclipse in which the entire Moon is visible against the Sun, but the Sun appears as a ring around the Moon. (Never used for a lunar eclipse.) + * `Total`: A total lunar/solar eclipse. + * + * @enum {string} + */ +export var EclipseKind; +(function (EclipseKind) { + EclipseKind["Penumbral"] = "penumbral"; + EclipseKind["Partial"] = "partial"; + EclipseKind["Annular"] = "annular"; + EclipseKind["Total"] = "total"; +})(EclipseKind || (EclipseKind = {})); +/** + * @brief Returns information about a lunar eclipse. + * + * Returned by {@link SearchLunarEclipse} or {@link NextLunarEclipse} + * to report information about a lunar eclipse event. + * When a lunar eclipse is found, it is classified as penumbral, partial, or total. + * Penumbral eclipses are difficult to observe, because the Moon is only slightly dimmed + * by the Earth's penumbra; no part of the Moon touches the Earth's umbra. + * Partial eclipses occur when part, but not all, of the Moon touches the Earth's umbra. + * Total eclipses occur when the entire Moon passes into the Earth's umbra. + * + * The `kind` field thus holds one of the enum values `EclipseKind.Penumbral`, `EclipseKind.Partial`, + * or `EclipseKind.Total`, depending on the kind of lunar eclipse found. + * + * The `obscuration` field holds a value in the range [0, 1] that indicates what fraction + * of the Moon's apparent disc area is covered by the Earth's umbra at the eclipse's peak. + * This indicates how dark the peak eclipse appears. For penumbral eclipses, the obscuration + * is 0, because the Moon does not pass through the Earth's umbra. For partial eclipses, + * the obscuration is somewhere between 0 and 1. For total lunar eclipses, the obscuration is 1. + * + * Field `peak` holds the date and time of the peak of the eclipse, when it is at its peak. + * + * Fields `sd_penum`, `sd_partial`, and `sd_total` hold the semi-duration of each phase + * of the eclipse, which is half of the amount of time the eclipse spends in each + * phase (expressed in minutes), or 0 if the eclipse never reaches that phase. + * By converting from minutes to days, and subtracting/adding with `peak`, the caller + * may determine the date and time of the beginning/end of each eclipse phase. + * + * @property {EclipseKind} kind + * The type of lunar eclipse found. + * + * @property {number} obscuration + * The peak fraction of the Moon's apparent disc that is covered by the Earth's umbra. + * + * @property {AstroTime} peak + * The time of the eclipse at its peak. + * + * @property {number} sd_penum + * The semi-duration of the penumbral phase in minutes. + * + * @property {number} sd_partial + * The semi-duration of the penumbral phase in minutes, or 0.0 if none. + * + * @property {number} sd_total + * The semi-duration of the penumbral phase in minutes, or 0.0 if none. + * + */ +export class LunarEclipseInfo { + constructor(kind, obscuration, peak, sd_penum, sd_partial, sd_total) { + this.kind = kind; + this.obscuration = obscuration; + this.peak = peak; + this.sd_penum = sd_penum; + this.sd_partial = sd_partial; + this.sd_total = sd_total; + } +} +/** + * @ignore + * + * @brief Represents the relative alignment of the Earth and another body, and their respective shadows. + * + * This is an internal data structure used to assist calculation of + * lunar eclipses, solar eclipses, and transits of Mercury and Venus. + * + * Definitions: + * + * casting body = A body that casts a shadow of interest, possibly striking another body. + * + * receiving body = A body on which the shadow of another body might land. + * + * shadow axis = The line passing through the center of the Sun and the center of the casting body. + * + * shadow plane = The plane passing through the center of a receiving body, + * and perpendicular to the shadow axis. + * + * @property {AstroTime} time + * The time associated with the shadow calculation. + * + * @property {number} u + * The distance [au] between the center of the casting body and the shadow plane. + * + * @property {number} r + * The distance [km] between center of receiving body and the shadow axis. + * + * @property {number} k + * The umbra radius [km] at the shadow plane. + * + * @property {number} p + * The penumbra radius [km] at the shadow plane. + * + * @property {Vector} target + * The location in space where we are interested in determining how close a shadow falls. + * For example, when calculating lunar eclipses, `target` would be the center of the Moon + * expressed in geocentric coordinates. Then we can evaluate how far the center of the Earth's + * shadow cone approaches the center of the Moon. + * The vector components are expressed in [au]. + * + * @property {Vector} dir + * The direction in space that the shadow points away from the center of a shadow-casting body. + * This vector lies on the shadow axis and points away from the Sun. + * In other words: the direction light from the Sun would be traveling, + * except that the center of a body (Earth, Moon, Mercury, or Venus) is blocking it. + * The distance units do not matter, because the vector will be normalized. + */ +class ShadowInfo { + constructor(time, u, r, k, p, target, dir) { + this.time = time; + this.u = u; + this.r = r; + this.k = k; + this.p = p; + this.target = target; + this.dir = dir; + } +} +function CalcShadow(body_radius_km, time, target, dir) { + const u = (dir.x * target.x + dir.y * target.y + dir.z * target.z) / (dir.x * dir.x + dir.y * dir.y + dir.z * dir.z); + const dx = (u * dir.x) - target.x; + const dy = (u * dir.y) - target.y; + const dz = (u * dir.z) - target.z; + const r = KM_PER_AU * Math.hypot(dx, dy, dz); + const k = +SUN_RADIUS_KM - (1.0 + u) * (SUN_RADIUS_KM - body_radius_km); + const p = -SUN_RADIUS_KM + (1.0 + u) * (SUN_RADIUS_KM + body_radius_km); + return new ShadowInfo(time, u, r, k, p, target, dir); +} +function EarthShadow(time) { + // Light-travel and aberration corrected vector from the Earth to the Sun. + const s = GeoVector(Body.Sun, time, true); + // The vector e = -s is thus the path of sunlight through the center of the Earth. + const e = new Vector(-s.x, -s.y, -s.z, s.t); + // Geocentric moon. + const m = GeoMoon(time); + return CalcShadow(EARTH_ECLIPSE_RADIUS_KM, time, m, e); +} +function MoonShadow(time) { + const s = GeoVector(Body.Sun, time, true); + const m = GeoMoon(time); // geocentric Moon + // Calculate lunacentric Earth. + const e = new Vector(-m.x, -m.y, -m.z, m.t); + // Convert geocentric moon to heliocentric Moon. + m.x -= s.x; + m.y -= s.y; + m.z -= s.z; + return CalcShadow(MOON_MEAN_RADIUS_KM, time, e, m); +} +function LocalMoonShadow(time, observer) { + // Calculate observer's geocentric position. + const pos = geo_pos(time, observer); + // Calculate light-travel and aberration corrected Sun. + const s = GeoVector(Body.Sun, time, true); + // Calculate geocentric Moon. + const m = GeoMoon(time); // geocentric Moon + // Calculate lunacentric location of an observer on the Earth's surface. + const o = new Vector(pos[0] - m.x, pos[1] - m.y, pos[2] - m.z, time); + // Convert geocentric moon to heliocentric Moon. + m.x -= s.x; + m.y -= s.y; + m.z -= s.z; + return CalcShadow(MOON_MEAN_RADIUS_KM, time, o, m); +} +function PlanetShadow(body, planet_radius_km, time) { + // Calculate light-travel-corrected vector from Earth to planet. + const g = GeoVector(body, time, true); + // Calculate light-travel-corrected vector from Earth to Sun. + const e = GeoVector(Body.Sun, time, true); + // Deduce light-travel-corrected vector from Sun to planet. + const p = new Vector(g.x - e.x, g.y - e.y, g.z - e.z, time); + // Calcluate Earth's position from the planet's point of view. + e.x = -g.x; + e.y = -g.y; + e.z = -g.z; + return CalcShadow(planet_radius_km, time, e, p); +} +function ShadowDistanceSlope(shadowfunc, time) { + const dt = 1.0 / 86400.0; + const t1 = time.AddDays(-dt); + const t2 = time.AddDays(+dt); + const shadow1 = shadowfunc(t1); + const shadow2 = shadowfunc(t2); + return (shadow2.r - shadow1.r) / dt; +} +function PlanetShadowSlope(body, planet_radius_km, time) { + const dt = 1.0 / 86400.0; + const shadow1 = PlanetShadow(body, planet_radius_km, time.AddDays(-dt)); + const shadow2 = PlanetShadow(body, planet_radius_km, time.AddDays(+dt)); + return (shadow2.r - shadow1.r) / dt; +} +function PeakEarthShadow(search_center_time) { + const window = 0.03; /* initial search window, in days, before/after given time */ + const t1 = search_center_time.AddDays(-window); + const t2 = search_center_time.AddDays(+window); + const tx = Search((time) => ShadowDistanceSlope(EarthShadow, time), t1, t2); + if (!tx) + throw 'Failed to find peak Earth shadow time.'; + return EarthShadow(tx); +} +function PeakMoonShadow(search_center_time) { + const window = 0.03; /* initial search window, in days, before/after given time */ + const t1 = search_center_time.AddDays(-window); + const t2 = search_center_time.AddDays(+window); + const tx = Search((time) => ShadowDistanceSlope(MoonShadow, time), t1, t2); + if (!tx) + throw 'Failed to find peak Moon shadow time.'; + return MoonShadow(tx); +} +function PeakPlanetShadow(body, planet_radius_km, search_center_time) { + // Search for when the body's shadow is closest to the center of the Earth. + const window = 1.0; // days before/after inferior conjunction to search for minimum shadow distance. + const t1 = search_center_time.AddDays(-window); + const t2 = search_center_time.AddDays(+window); + const tx = Search((time) => PlanetShadowSlope(body, planet_radius_km, time), t1, t2); + if (!tx) + throw 'Failed to find peak planet shadow time.'; + return PlanetShadow(body, planet_radius_km, tx); +} +function PeakLocalMoonShadow(search_center_time, observer) { + // Search for the time near search_center_time that the Moon's shadow comes + // closest to the given observer. + const window = 0.2; + const t1 = search_center_time.AddDays(-window); + const t2 = search_center_time.AddDays(+window); + function shadowfunc(time) { + return LocalMoonShadow(time, observer); + } + const time = Search((time) => ShadowDistanceSlope(shadowfunc, time), t1, t2); + if (!time) + throw `PeakLocalMoonShadow: search failure for search_center_time = ${search_center_time}`; + return LocalMoonShadow(time, observer); +} +function ShadowSemiDurationMinutes(center_time, radius_limit, window_minutes) { + // Search backwards and forwards from the center time until shadow axis distance crosses radius limit. + const window = window_minutes / (24.0 * 60.0); + const before = center_time.AddDays(-window); + const after = center_time.AddDays(+window); + const t1 = Search((time) => -(EarthShadow(time).r - radius_limit), before, center_time); + const t2 = Search((time) => +(EarthShadow(time).r - radius_limit), center_time, after); + if (!t1 || !t2) + throw 'Failed to find shadow semiduration'; + return (t2.ut - t1.ut) * ((24.0 * 60.0) / 2.0); // convert days to minutes and average the semi-durations. +} +function MoonEclipticLatitudeDegrees(time) { + const moon = CalcMoon(time); + return RAD2DEG * moon.geo_eclip_lat; +} +function Obscuration(a, // radius of first disc +b, // radius of second disc +c // distance between the centers of the discs +) { + if (a <= 0.0) + throw 'Radius of first disc must be positive.'; + if (b <= 0.0) + throw 'Radius of second disc must be positive.'; + if (c < 0.0) + throw 'Distance between discs is not allowed to be negative.'; + if (c >= a + b) { + // The discs are too far apart to have any overlapping area. + return 0.0; + } + if (c == 0.0) { + // The discs have a common center. Therefore, one disc is inside the other. + return (a <= b) ? 1.0 : (b * b) / (a * a); + } + const x = (a * a - b * b + c * c) / (2 * c); + const radicand = a * a - x * x; + if (radicand <= 0.0) { + // The circumferences do not intersect, or are tangent. + // We already ruled out the case of non-overlapping discs. + // Therefore, one disc is inside the other. + return (a <= b) ? 1.0 : (b * b) / (a * a); + } + // The discs overlap fractionally in a pair of lens-shaped areas. + const y = Math.sqrt(radicand); + // Return the overlapping fractional area. + // There are two lens-shaped areas, one to the left of x, the other to the right of x. + // Each part is calculated by subtracting a triangular area from a sector's area. + const lens1 = a * a * Math.acos(x / a) - x * y; + const lens2 = b * b * Math.acos((c - x) / b) - (c - x) * y; + // Find the fractional area with respect to the first disc. + return (lens1 + lens2) / (Math.PI * a * a); +} +function SolarEclipseObscuration(hm, // heliocentric Moon +lo // lunacentric observer +) { + // Find heliocentric observer. + const ho = new Vector(hm.x + lo.x, hm.y + lo.y, hm.z + lo.z, hm.t); + // Calculate the apparent angular radius of the Sun for the observer. + const sun_radius = Math.asin(SUN_RADIUS_AU / ho.Length()); + // Calculate the apparent angular radius of the Moon for the observer. + const moon_radius = Math.asin(MOON_POLAR_RADIUS_AU / lo.Length()); + // Calculate the apparent angular separation between the Sun's center and the Moon's center. + const sun_moon_separation = AngleBetween(lo, ho); + // Find the fraction of the Sun's apparent disc area that is covered by the Moon. + const obscuration = Obscuration(sun_radius, moon_radius, sun_moon_separation * DEG2RAD); + // HACK: In marginal cases, we need to clamp obscuration to less than 1.0. + // This function is never called for total eclipses, so it should never return 1.0. + return Math.min(0.9999, obscuration); +} +/** + * @brief Searches for a lunar eclipse. + * + * This function finds the first lunar eclipse that occurs after `startTime`. + * A lunar eclipse may be penumbral, partial, or total. + * See {@link LunarEclipseInfo} for more information. + * To find a series of lunar eclipses, call this function once, + * then keep calling {@link NextLunarEclipse} as many times as desired, + * passing in the `peak` value returned from the previous call. + * + * @param {FlexibleDateTime} date + * The date and time for starting the search for a lunar eclipse. + * + * @returns {LunarEclipseInfo} + */ +export function SearchLunarEclipse(date) { + const PruneLatitude = 1.8; /* full Moon's ecliptic latitude above which eclipse is impossible */ + let fmtime = MakeTime(date); + for (let fmcount = 0; fmcount < 12; ++fmcount) { + /* Search for the next full moon. Any eclipse will be near it. */ + const fullmoon = SearchMoonPhase(180, fmtime, 40); + if (!fullmoon) + throw 'Cannot find full moon.'; + /* + Pruning: if the full Moon's ecliptic latitude is too large, + a lunar eclipse is not possible. Avoid needless work searching for + the minimum moon distance. + */ + const eclip_lat = MoonEclipticLatitudeDegrees(fullmoon); + if (Math.abs(eclip_lat) < PruneLatitude) { + /* Search near the full moon for the time when the center of the Moon */ + /* is closest to the line passing through the centers of the Sun and Earth. */ + const shadow = PeakEarthShadow(fullmoon); + if (shadow.r < shadow.p + MOON_MEAN_RADIUS_KM) { + /* This is at least a penumbral eclipse. We will return a result. */ + let kind = EclipseKind.Penumbral; + let obscuration = 0.0; + let sd_total = 0.0; + let sd_partial = 0.0; + let sd_penum = ShadowSemiDurationMinutes(shadow.time, shadow.p + MOON_MEAN_RADIUS_KM, 200.0); + if (shadow.r < shadow.k + MOON_MEAN_RADIUS_KM) { + /* This is at least a partial eclipse. */ + kind = EclipseKind.Partial; + sd_partial = ShadowSemiDurationMinutes(shadow.time, shadow.k + MOON_MEAN_RADIUS_KM, sd_penum); + if (shadow.r + MOON_MEAN_RADIUS_KM < shadow.k) { + /* This is a total eclipse. */ + kind = EclipseKind.Total; + obscuration = 1.0; + sd_total = ShadowSemiDurationMinutes(shadow.time, shadow.k - MOON_MEAN_RADIUS_KM, sd_partial); + } + else { + obscuration = Obscuration(MOON_MEAN_RADIUS_KM, shadow.k, shadow.r); + } + } + return new LunarEclipseInfo(kind, obscuration, shadow.time, sd_penum, sd_partial, sd_total); + } + } + /* We didn't find an eclipse on this full moon, so search for the next one. */ + fmtime = fullmoon.AddDays(10); + } + /* This should never happen because there are always at least 2 full moons per year. */ + throw 'Failed to find lunar eclipse within 12 full moons.'; +} +/** + * @brief Reports the time and geographic location of the peak of a solar eclipse. + * + * Returned by {@link SearchGlobalSolarEclipse} or {@link NextGlobalSolarEclipse} + * to report information about a solar eclipse event. + * + * The eclipse is classified as partial, annular, or total, depending on the + * maximum amount of the Sun's disc obscured, as seen at the peak location + * on the surface of the Earth. + * + * The `kind` field thus holds one of the values `EclipseKind.Partial`, `EclipseKind.Annular`, or `EclipseKind.Total`. + * A total eclipse is when the peak observer sees the Sun completely blocked by the Moon. + * An annular eclipse is like a total eclipse, but the Moon is too far from the Earth's surface + * to completely block the Sun; instead, the Sun takes on a ring-shaped appearance. + * A partial eclipse is when the Moon blocks part of the Sun's disc, but nobody on the Earth + * observes either a total or annular eclipse. + * + * If `kind` is `EclipseKind.Total` or `EclipseKind.Annular`, the `latitude` and `longitude` + * fields give the geographic coordinates of the center of the Moon's shadow projected + * onto the daytime side of the Earth at the instant of the eclipse's peak. + * If `kind` has any other value, `latitude` and `longitude` are undefined and should + * not be used. + * + * For total or annular eclipses, the `obscuration` field holds the fraction (0, 1] + * of the Sun's apparent disc area that is blocked from view by the Moon's silhouette, + * as seen by an observer located at the geographic coordinates `latitude`, `longitude` + * at the darkest time `peak`. The value will always be 1 for total eclipses, and less than + * 1 for annular eclipses. + * For partial eclipses, `obscuration` is undefined and should not be used. + * This is because there is little practical use for an obscuration value of + * a partial eclipse without supplying a particular observation location. + * Developers who wish to find an obscuration value for partial solar eclipses should therefore use + * {@link SearchLocalSolarEclipse} and provide the geographic coordinates of an observer. + * + * @property {EclipseKind} kind + * One of the following enumeration values: `EclipseKind.Partial`, `EclipseKind.Annular`, `EclipseKind.Total`. + * + * @property {number | undefined} obscuration + * The peak fraction of the Sun's apparent disc area obscured by the Moon (total and annular eclipses only) + * + * @property {AstroTime} peak + * The date and time when the solar eclipse is darkest. + * This is the instant when the axis of the Moon's shadow cone passes closest to the Earth's center. + * + * @property {number} distance + * The distance in kilometers between the axis of the Moon's shadow cone + * and the center of the Earth at the time indicated by `peak`. + * + * @property {number | undefined} latitude + * If `kind` holds `EclipseKind.Total`, the geographic latitude in degrees + * where the center of the Moon's shadow falls on the Earth at the + * time indicated by `peak`; otherwise, `latitude` holds `undefined`. + * + * @property {number | undefined} longitude + * If `kind` holds `EclipseKind.Total`, the geographic longitude in degrees + * where the center of the Moon's shadow falls on the Earth at the + * time indicated by `peak`; otherwise, `longitude` holds `undefined`. + */ +export class GlobalSolarEclipseInfo { + constructor(kind, obscuration, peak, distance, latitude, longitude) { + this.kind = kind; + this.obscuration = obscuration; + this.peak = peak; + this.distance = distance; + this.latitude = latitude; + this.longitude = longitude; + } +} +function EclipseKindFromUmbra(k) { + // The umbra radius tells us what kind of eclipse the observer sees. + // If the umbra radius is positive, this is a total eclipse. Otherwise, it's annular. + // HACK: I added a tiny bias (14 meters) to match Espenak test data. + return (k > 0.014) ? EclipseKind.Total : EclipseKind.Annular; +} +function GeoidIntersect(shadow) { + let kind = EclipseKind.Partial; + let peak = shadow.time; + let distance = shadow.r; + let latitude; // left undefined for partial eclipses + let longitude; // left undefined for partial eclipses + // We want to calculate the intersection of the shadow axis with the Earth's geoid. + // First we must convert EQJ (equator of J2000) coordinates to EQD (equator of date) + // coordinates that are perfectly aligned with the Earth's equator at this + // moment in time. + const rot = Rotation_EQJ_EQD(shadow.time); + const v = RotateVector(rot, shadow.dir); // shadow-axis vector in equator-of-date coordinates + const e = RotateVector(rot, shadow.target); // lunacentric Earth in equator-of-date coordinates + // Convert all distances from AU to km. + // But dilate the z-coordinates so that the Earth becomes a perfect sphere. + // Then find the intersection of the vector with the sphere. + // See p 184 in Montenbruck & Pfleger's "Astronomy on the Personal Computer", second edition. + v.x *= KM_PER_AU; + v.y *= KM_PER_AU; + v.z *= KM_PER_AU / EARTH_FLATTENING; + e.x *= KM_PER_AU; + e.y *= KM_PER_AU; + e.z *= KM_PER_AU / EARTH_FLATTENING; + // Solve the quadratic equation that finds whether and where + // the shadow axis intersects with the Earth in the dilated coordinate system. + const R = EARTH_EQUATORIAL_RADIUS_KM; + const A = v.x * v.x + v.y * v.y + v.z * v.z; + const B = -2.0 * (v.x * e.x + v.y * e.y + v.z * e.z); + const C = (e.x * e.x + e.y * e.y + e.z * e.z) - R * R; + const radic = B * B - 4 * A * C; + let obscuration; + if (radic > 0.0) { + // Calculate the closer of the two intersection points. + // This will be on the day side of the Earth. + const u = (-B - Math.sqrt(radic)) / (2 * A); + // Convert lunacentric dilated coordinates to geocentric coordinates. + const px = u * v.x - e.x; + const py = u * v.y - e.y; + const pz = (u * v.z - e.z) * EARTH_FLATTENING; + // Convert cartesian coordinates into geodetic latitude/longitude. + const proj = Math.hypot(px, py) * EARTH_FLATTENING_SQUARED; + if (proj == 0.0) + latitude = (pz > 0.0) ? +90.0 : -90.0; + else + latitude = RAD2DEG * Math.atan(pz / proj); + // Adjust longitude for Earth's rotation at the given UT. + const gast = sidereal_time(peak); + longitude = (RAD2DEG * Math.atan2(py, px) - (15 * gast)) % 360.0; + if (longitude <= -180.0) + longitude += 360.0; + else if (longitude > +180.0) + longitude -= 360.0; + // We want to determine whether the observer sees a total eclipse or an annular eclipse. + // We need to perform a series of vector calculations... + // Calculate the inverse rotation matrix, so we can convert EQD to EQJ. + const inv = InverseRotation(rot); + // Put the EQD geocentric coordinates of the observer into the vector 'o'. + // Also convert back from kilometers to astronomical units. + let o = new Vector(px / KM_PER_AU, py / KM_PER_AU, pz / KM_PER_AU, shadow.time); + // Rotate the observer's geocentric EQD back to the EQJ system. + o = RotateVector(inv, o); + // Convert geocentric vector to lunacentric vector. + o.x += shadow.target.x; + o.y += shadow.target.y; + o.z += shadow.target.z; + // Recalculate the shadow using a vector from the Moon's center toward the observer. + const surface = CalcShadow(MOON_POLAR_RADIUS_KM, shadow.time, o, shadow.dir); + // If we did everything right, the shadow distance should be very close to zero. + // That's because we already determined the observer 'o' is on the shadow axis! + if (surface.r > 1.0e-9 || surface.r < 0.0) + throw `Unexpected shadow distance from geoid intersection = ${surface.r}`; + kind = EclipseKindFromUmbra(surface.k); + obscuration = (kind === EclipseKind.Total) ? 1.0 : SolarEclipseObscuration(shadow.dir, o); + } + else { + // This is a partial solar eclipse. It does not make practical sense to calculate obscuration. + // Anyone who wants obscuration should use Astronomy.SearchLocalSolarEclipse for a specific location on the Earth. + obscuration = undefined; + } + return new GlobalSolarEclipseInfo(kind, obscuration, peak, distance, latitude, longitude); +} +/** + * @brief Searches for the next lunar eclipse in a series. + * + * After using {@link SearchLunarEclipse} to find the first lunar eclipse + * in a series, you can call this function to find the next consecutive lunar eclipse. + * Pass in the `peak` value from the {@link LunarEclipseInfo} returned by the + * previous call to `SearchLunarEclipse` or `NextLunarEclipse` + * to find the next lunar eclipse. + * + * @param {FlexibleDateTime} prevEclipseTime + * A date and time near a full moon. Lunar eclipse search will start at the next full moon. + * + * @returns {LunarEclipseInfo} + */ +export function NextLunarEclipse(prevEclipseTime) { + prevEclipseTime = MakeTime(prevEclipseTime); + const startTime = prevEclipseTime.AddDays(10); + return SearchLunarEclipse(startTime); +} +/** + * @brief Searches for a solar eclipse visible anywhere on the Earth's surface. + * + * This function finds the first solar eclipse that occurs after `startTime`. + * A solar eclipse may be partial, annular, or total. + * See {@link GlobalSolarEclipseInfo} for more information. + * To find a series of solar eclipses, call this function once, + * then keep calling {@link NextGlobalSolarEclipse} as many times as desired, + * passing in the `peak` value returned from the previous call. + * + * @param {FlexibleDateTime} startTime + * The date and time for starting the search for a solar eclipse. + * + * @returns {GlobalSolarEclipseInfo} + */ +export function SearchGlobalSolarEclipse(startTime) { + startTime = MakeTime(startTime); + const PruneLatitude = 1.8; // Moon's ecliptic latitude beyond which eclipse is impossible + // Iterate through consecutive new moons until we find a solar eclipse visible somewhere on Earth. + let nmtime = startTime; + let nmcount; + for (nmcount = 0; nmcount < 12; ++nmcount) { + // Search for the next new moon. Any eclipse will be near it. + const newmoon = SearchMoonPhase(0.0, nmtime, 40.0); + if (!newmoon) + throw 'Cannot find new moon'; + // Pruning: if the new moon's ecliptic latitude is too large, a solar eclipse is not possible. + const eclip_lat = MoonEclipticLatitudeDegrees(newmoon); + if (Math.abs(eclip_lat) < PruneLatitude) { + // Search near the new moon for the time when the center of the Earth + // is closest to the line passing through the centers of the Sun and Moon. + const shadow = PeakMoonShadow(newmoon); + if (shadow.r < shadow.p + EARTH_MEAN_RADIUS_KM) { + // This is at least a partial solar eclipse visible somewhere on Earth. + // Try to find an intersection between the shadow axis and the Earth's oblate geoid. + return GeoidIntersect(shadow); + } + } + // We didn't find an eclipse on this new moon, so search for the next one. + nmtime = newmoon.AddDays(10.0); + } + // Safety valve to prevent infinite loop. + // This should never happen, because at least 2 solar eclipses happen per year. + throw 'Failed to find solar eclipse within 12 full moons.'; +} +/** + * @brief Searches for the next global solar eclipse in a series. + * + * After using {@link SearchGlobalSolarEclipse} to find the first solar eclipse + * in a series, you can call this function to find the next consecutive solar eclipse. + * Pass in the `peak` value from the {@link GlobalSolarEclipseInfo} returned by the + * previous call to `SearchGlobalSolarEclipse` or `NextGlobalSolarEclipse` + * to find the next solar eclipse. + * + * @param {FlexibleDateTime} prevEclipseTime + * A date and time near a new moon. Solar eclipse search will start at the next new moon. + * + * @returns {GlobalSolarEclipseInfo} + */ +export function NextGlobalSolarEclipse(prevEclipseTime) { + prevEclipseTime = MakeTime(prevEclipseTime); + const startTime = prevEclipseTime.AddDays(10.0); + return SearchGlobalSolarEclipse(startTime); +} +/** + * @brief Holds a time and the observed altitude of the Sun at that time. + * + * When reporting a solar eclipse observed at a specific location on the Earth + * (a "local" solar eclipse), a series of events occur. In addition + * to the time of each event, it is important to know the altitude of the Sun, + * because each event may be invisible to the observer if the Sun is below + * the horizon. + * + * If `altitude` is negative, the event is theoretical only; it would be + * visible if the Earth were transparent, but the observer cannot actually see it. + * If `altitude` is positive but less than a few degrees, visibility will be impaired by + * atmospheric interference (sunrise or sunset conditions). + * + * @property {AstroTime} time + * The date and time of the event. + * + * @property {number} altitude + * The angular altitude of the center of the Sun above/below the horizon, at `time`, + * corrected for atmospheric refraction and expressed in degrees. + */ +export class EclipseEvent { + constructor(time, altitude) { + this.time = time; + this.altitude = altitude; + } +} +/** + * @brief Information about a solar eclipse as seen by an observer at a given time and geographic location. + * + * Returned by {@link SearchLocalSolarEclipse} or {@link NextLocalSolarEclipse} + * to report information about a solar eclipse as seen at a given geographic location. + * + * When a solar eclipse is found, it is classified by setting `kind` + * to `EclipseKind.Partial`, `EclipseKind.Annular`, or `EclipseKind.Total`. + * A partial solar eclipse is when the Moon does not line up directly enough with the Sun + * to completely block the Sun's light from reaching the observer. + * An annular eclipse occurs when the Moon's disc is completely visible against the Sun + * but the Moon is too far away to completely block the Sun's light; this leaves the + * Sun with a ring-like appearance. + * A total eclipse occurs when the Moon is close enough to the Earth and aligned with the + * Sun just right to completely block all sunlight from reaching the observer. + * + * The `obscuration` field reports what fraction of the Sun's disc appears blocked + * by the Moon when viewed by the observer at the peak eclipse time. + * This is a value that ranges from 0 (no blockage) to 1 (total eclipse). + * The obscuration value will be between 0 and 1 for partial eclipses and annular eclipses. + * The value will be exactly 1 for total eclipses. Obscuration gives an indication + * of how dark the eclipse appears. + * + * There are 5 "event" fields, each of which contains a time and a solar altitude. + * Field `peak` holds the date and time of the center of the eclipse, when it is at its peak. + * The fields `partial_begin` and `partial_end` are always set, and indicate when + * the eclipse begins/ends. If the eclipse reaches totality or becomes annular, + * `total_begin` and `total_end` indicate when the total/annular phase begins/ends. + * When an event field is valid, the caller must also check its `altitude` field to + * see whether the Sun is above the horizon at the time indicated by the `time` field. + * See {@link EclipseEvent} for more information. + * + * @property {EclipseKind} kind + * The type of solar eclipse found: `EclipseKind.Partial`, `EclipseKind.Annular`, or `EclipseKind.Total`. + * + * @property {number} obscuration + * The fraction of the Sun's apparent disc area obscured by the Moon at the eclipse peak. + * + * @property {EclipseEvent} partial_begin + * The time and Sun altitude at the beginning of the eclipse. + * + * @property {EclipseEvent | undefined} total_begin + * If this is an annular or a total eclipse, the time and Sun altitude when annular/total phase begins; otherwise undefined. + * + * @property {EclipseEvent} peak + * The time and Sun altitude when the eclipse reaches its peak. + * + * @property {EclipseEvent | undefined} total_end + * If this is an annular or a total eclipse, the time and Sun altitude when annular/total phase ends; otherwise undefined. + * + * @property {EclipseEvent} partial_end + * The time and Sun altitude at the end of the eclipse. + */ +export class LocalSolarEclipseInfo { + constructor(kind, obscuration, partial_begin, total_begin, peak, total_end, partial_end) { + this.kind = kind; + this.obscuration = obscuration; + this.partial_begin = partial_begin; + this.total_begin = total_begin; + this.peak = peak; + this.total_end = total_end; + this.partial_end = partial_end; + } +} +function local_partial_distance(shadow) { + return shadow.p - shadow.r; +} +function local_total_distance(shadow) { + // Must take the absolute value of the umbra radius 'k' + // because it can be negative for an annular eclipse. + return Math.abs(shadow.k) - shadow.r; +} +function LocalEclipse(shadow, observer) { + const PARTIAL_WINDOW = 0.2; + const TOTAL_WINDOW = 0.01; + const peak = CalcEvent(observer, shadow.time); + let t1 = shadow.time.AddDays(-PARTIAL_WINDOW); + let t2 = shadow.time.AddDays(+PARTIAL_WINDOW); + const partial_begin = LocalEclipseTransition(observer, +1.0, local_partial_distance, t1, shadow.time); + const partial_end = LocalEclipseTransition(observer, -1.0, local_partial_distance, shadow.time, t2); + let total_begin; + let total_end; + let kind; + if (shadow.r < Math.abs(shadow.k)) { // take absolute value of 'k' to handle annular eclipses too. + t1 = shadow.time.AddDays(-TOTAL_WINDOW); + t2 = shadow.time.AddDays(+TOTAL_WINDOW); + total_begin = LocalEclipseTransition(observer, +1.0, local_total_distance, t1, shadow.time); + total_end = LocalEclipseTransition(observer, -1.0, local_total_distance, shadow.time, t2); + kind = EclipseKindFromUmbra(shadow.k); + } + else { + kind = EclipseKind.Partial; + } + const obscuration = (kind === EclipseKind.Total) ? 1.0 : SolarEclipseObscuration(shadow.dir, shadow.target); + return new LocalSolarEclipseInfo(kind, obscuration, partial_begin, total_begin, peak, total_end, partial_end); +} +function LocalEclipseTransition(observer, direction, func, t1, t2) { + function evaluate(time) { + const shadow = LocalMoonShadow(time, observer); + return direction * func(shadow); + } + const search = Search(evaluate, t1, t2); + if (!search) + throw "Local eclipse transition search failed."; + return CalcEvent(observer, search); +} +function CalcEvent(observer, time) { + const altitude = SunAltitude(time, observer); + return new EclipseEvent(time, altitude); +} +function SunAltitude(time, observer) { + const equ = Equator(Body.Sun, time, observer, true, true); + const hor = Horizon(time, observer, equ.ra, equ.dec, 'normal'); + return hor.altitude; +} +/** + * @brief Searches for a solar eclipse visible at a specific location on the Earth's surface. + * + * This function finds the first solar eclipse that occurs after `startTime`. + * A solar eclipse may be partial, annular, or total. + * See {@link LocalSolarEclipseInfo} for more information. + * + * To find a series of solar eclipses, call this function once, + * then keep calling {@link NextLocalSolarEclipse} as many times as desired, + * passing in the `peak` value returned from the previous call. + * + * IMPORTANT: An eclipse reported by this function might be partly or + * completely invisible to the observer due to the time of day. + * See {@link LocalSolarEclipseInfo} for more information about this topic. + * + * @param {FlexibleDateTime} startTime + * The date and time for starting the search for a solar eclipse. + * + * @param {Observer} observer + * The geographic location of the observer. + * + * @returns {LocalSolarEclipseInfo} + */ +export function SearchLocalSolarEclipse(startTime, observer) { + startTime = MakeTime(startTime); + VerifyObserver(observer); + const PruneLatitude = 1.8; /* Moon's ecliptic latitude beyond which eclipse is impossible */ + /* Iterate through consecutive new moons until we find a solar eclipse visible somewhere on Earth. */ + let nmtime = startTime; + for (;;) { + /* Search for the next new moon. Any eclipse will be near it. */ + const newmoon = SearchMoonPhase(0.0, nmtime, 40.0); + if (!newmoon) + throw 'Cannot find next new moon'; + /* Pruning: if the new moon's ecliptic latitude is too large, a solar eclipse is not possible. */ + const eclip_lat = MoonEclipticLatitudeDegrees(newmoon); + if (Math.abs(eclip_lat) < PruneLatitude) { + /* Search near the new moon for the time when the observer */ + /* is closest to the line passing through the centers of the Sun and Moon. */ + const shadow = PeakLocalMoonShadow(newmoon, observer); + if (shadow.r < shadow.p) { + /* This is at least a partial solar eclipse for the observer. */ + const eclipse = LocalEclipse(shadow, observer); + /* Ignore any eclipse that happens completely at night. */ + /* More precisely, the center of the Sun must be above the horizon */ + /* at the beginning or the end of the eclipse, or we skip the event. */ + if (eclipse.partial_begin.altitude > 0.0 || eclipse.partial_end.altitude > 0.0) + return eclipse; + } + } + /* We didn't find an eclipse on this new moon, so search for the next one. */ + nmtime = newmoon.AddDays(10.0); + } +} +/** + * @brief Searches for the next local solar eclipse in a series. + * + * After using {@link SearchLocalSolarEclipse} to find the first solar eclipse + * in a series, you can call this function to find the next consecutive solar eclipse. + * Pass in the `peak` value from the {@link LocalSolarEclipseInfo} returned by the + * previous call to `SearchLocalSolarEclipse` or `NextLocalSolarEclipse` + * to find the next solar eclipse. + * This function finds the first solar eclipse that occurs after `startTime`. + * A solar eclipse may be partial, annular, or total. + * See {@link LocalSolarEclipseInfo} for more information. + * + * @param {FlexibleDateTime} prevEclipseTime + * The date and time for starting the search for a solar eclipse. + * + * @param {Observer} observer + * The geographic location of the observer. + * + * @returns {LocalSolarEclipseInfo} + */ +export function NextLocalSolarEclipse(prevEclipseTime, observer) { + prevEclipseTime = MakeTime(prevEclipseTime); + const startTime = prevEclipseTime.AddDays(10.0); + return SearchLocalSolarEclipse(startTime, observer); +} +/** + * @brief Information about a transit of Mercury or Venus, as seen from the Earth. + * + * Returned by {@link SearchTransit} or {@link NextTransit} to report + * information about a transit of Mercury or Venus. + * A transit is when Mercury or Venus passes between the Sun and Earth so that + * the other planet is seen in silhouette against the Sun. + * + * The calculations are performed from the point of view of a geocentric observer. + * + * @property {AstroTime} start + * The date and time at the beginning of the transit. + * This is the moment the planet first becomes visible against the Sun in its background. + * + * @property {AstroTime} peak + * When the planet is most aligned with the Sun, as seen from the Earth. + * + * @property {AstroTime} finish + * The date and time at the end of the transit. + * This is the moment the planet is last seen against the Sun in its background. + * + * @property {number} separation + * The minimum angular separation, in arcminutes, between the centers of the Sun and the planet. + * This angle pertains to the time stored in `peak`. + */ +export class TransitInfo { + constructor(start, peak, finish, separation) { + this.start = start; + this.peak = peak; + this.finish = finish; + this.separation = separation; + } +} +function PlanetShadowBoundary(time, body, planet_radius_km, direction) { + const shadow = PlanetShadow(body, planet_radius_km, time); + return direction * (shadow.r - shadow.p); +} +function PlanetTransitBoundary(body, planet_radius_km, t1, t2, direction) { + // Search for the time the planet's penumbra begins/ends making contact with the center of the Earth. + const tx = Search((time) => PlanetShadowBoundary(time, body, planet_radius_km, direction), t1, t2); + if (!tx) + throw 'Planet transit boundary search failed'; + return tx; +} +/** + * @brief Searches for the first transit of Mercury or Venus after a given date. + * + * Finds the first transit of Mercury or Venus after a specified date. + * A transit is when an inferior planet passes between the Sun and the Earth + * so that the silhouette of the planet is visible against the Sun in the background. + * To continue the search, pass the `finish` time in the returned structure to + * {@link NextTransit}. + * + * @param {Body} body + * The planet whose transit is to be found. Must be `Body.Mercury` or `Body.Venus`. + * + * @param {FlexibleDateTime} startTime + * The date and time for starting the search for a transit. + * + * @returns {TransitInfo} + */ +export function SearchTransit(body, startTime) { + startTime = MakeTime(startTime); + const threshold_angle = 0.4; // maximum angular separation to attempt transit calculation + const dt_days = 1.0; + // Validate the planet and find its mean radius. + let planet_radius_km; + switch (body) { + case Body.Mercury: + planet_radius_km = 2439.7; + break; + case Body.Venus: + planet_radius_km = 6051.8; + break; + default: + throw `Invalid body: ${body}`; + } + let search_time = startTime; + for (;;) { + // Search for the next inferior conjunction of the given planet. + // This is the next time the Earth and the other planet have the same + // ecliptic longitude as seen from the Sun. + const conj = SearchRelativeLongitude(body, 0.0, search_time); + // Calculate the angular separation between the body and the Sun at this time. + const conj_separation = AngleFromSun(body, conj); + if (conj_separation < threshold_angle) { + // The planet's angular separation from the Sun is small enough + // to consider it a transit candidate. + // Search for the moment when the line passing through the Sun + // and planet are closest to the Earth's center. + const shadow = PeakPlanetShadow(body, planet_radius_km, conj); + if (shadow.r < shadow.p) { // does the planet's penumbra touch the Earth's center? + // Find the beginning and end of the penumbral contact. + const time_before = shadow.time.AddDays(-dt_days); + const start = PlanetTransitBoundary(body, planet_radius_km, time_before, shadow.time, -1.0); + const time_after = shadow.time.AddDays(+dt_days); + const finish = PlanetTransitBoundary(body, planet_radius_km, shadow.time, time_after, +1.0); + const min_separation = 60.0 * AngleFromSun(body, shadow.time); + return new TransitInfo(start, shadow.time, finish, min_separation); + } + } + // This inferior conjunction was not a transit. Try the next inferior conjunction. + search_time = conj.AddDays(10.0); + } +} +/** + * @brief Searches for the next transit of Mercury or Venus in a series. + * + * After calling {@link SearchTransit} to find a transit of Mercury or Venus, + * this function finds the next transit after that. + * Keep calling this function as many times as you want to keep finding more transits. + * + * @param {Body} body + * The planet whose transit is to be found. Must be `Body.Mercury` or `Body.Venus`. + * + * @param {FlexibleDateTime} prevTransitTime + * A date and time near the previous transit. + * + * @returns {TransitInfo} + */ +export function NextTransit(body, prevTransitTime) { + prevTransitTime = MakeTime(prevTransitTime); + const startTime = prevTransitTime.AddDays(100.0); + return SearchTransit(body, startTime); +} +/** + * @brief Indicates whether a crossing through the ecliptic plane is ascending or descending. + * + * `Invalid` is a placeholder for an unknown or missing node. + * `Ascending` indicates a body passing through the ecliptic plane from south to north. + * `Descending` indicates a body passing through the ecliptic plane from north to south. + * + * @enum {number} + */ +export var NodeEventKind; +(function (NodeEventKind) { + NodeEventKind[NodeEventKind["Invalid"] = 0] = "Invalid"; + NodeEventKind[NodeEventKind["Ascending"] = 1] = "Ascending"; + NodeEventKind[NodeEventKind["Descending"] = -1] = "Descending"; +})(NodeEventKind || (NodeEventKind = {})); +/** + * @brief Information about an ascending or descending node of a body. + * + * This object is returned by {@link SearchMoonNode} and {@link NextMoonNode} + * to report information about the center of the Moon passing through the ecliptic plane. + * + * @property {NodeEventKind} kind Whether the node is ascending (south to north) or descending (north to south). + * @property {AstroTime} time The time when the body passes through the ecliptic plane. + */ +export class NodeEventInfo { + constructor(kind, time) { + this.kind = kind; + this.time = time; + } +} +const MoonNodeStepDays = +10.0; // a safe number of days to step without missing a Moon node +/** + * @brief Searches for a time when the Moon's center crosses through the ecliptic plane. + * + * Searches for the first ascending or descending node of the Moon after `startTime`. + * An ascending node is when the Moon's center passes through the ecliptic plane + * (the plane of the Earth's orbit around the Sun) from south to north. + * A descending node is when the Moon's center passes through the ecliptic plane + * from north to south. Nodes indicate possible times of solar or lunar eclipses, + * if the Moon also happens to be in the correct phase (new or full, respectively). + * Call `SearchMoonNode` to find the first of a series of nodes. + * Then call {@link NextMoonNode} to find as many more consecutive nodes as desired. + * + * @param {FlexibleDateTime} startTime + * The date and time for starting the search for an ascending or descending node of the Moon. + * + * @returns {NodeEventInfo} + */ +export function SearchMoonNode(startTime) { + // Start at the given moment in time and sample the Moon's ecliptic latitude. + // Step 10 days at a time, searching for an interval where that latitude crosses zero. + let time1 = MakeTime(startTime); + let eclip1 = EclipticGeoMoon(time1); + for (;;) { + const time2 = time1.AddDays(MoonNodeStepDays); + const eclip2 = EclipticGeoMoon(time2); + if (eclip1.lat * eclip2.lat <= 0.0) { + // There is a node somewhere inside this closed time interval. + // Figure out whether it is an ascending node or a descending node. + const kind = (eclip2.lat > eclip1.lat) ? NodeEventKind.Ascending : NodeEventKind.Descending; + const result = Search(t => kind * EclipticGeoMoon(t).lat, time1, time2); + if (!result) + throw `Could not find moon node.`; // should never happen + return new NodeEventInfo(kind, result); + } + time1 = time2; + eclip1 = eclip2; + } +} +/** + * @brief Searches for the next time when the Moon's center crosses through the ecliptic plane. + * + * Call {@link SearchMoonNode} to find the first of a series of nodes. + * Then call `NextMoonNode` to find as many more consecutive nodes as desired. + * + * @param {NodeEventInfo} prevNode + * The previous node found from calling {@link SearchMoonNode} or `NextMoonNode`. + * + * @returns {NodeEventInfo} + */ +export function NextMoonNode(prevNode) { + const time = prevNode.time.AddDays(MoonNodeStepDays); + const node = SearchMoonNode(time); + switch (prevNode.kind) { + case NodeEventKind.Ascending: + if (node.kind !== NodeEventKind.Descending) + throw `Internal error: previous node was ascending, but this node was: ${node.kind}`; + break; + case NodeEventKind.Descending: + if (node.kind !== NodeEventKind.Ascending) + throw `Internal error: previous node was descending, but this node was: ${node.kind}`; + break; + default: + throw `Previous node has an invalid node kind: ${prevNode.kind}`; + } + return node; +} +/** + * @brief Information about a body's rotation axis at a given time. + * + * This structure is returned by {@link RotationAxis} to report + * the orientation of a body's rotation axis at a given moment in time. + * The axis is specified by the direction in space that the body's north pole + * points, using angular equatorial coordinates in the J2000 system (EQJ). + * + * Thus `ra` is the right ascension, and `dec` is the declination, of the + * body's north pole vector at the given moment in time. The north pole + * of a body is defined as the pole that lies on the north side of the + * [Solar System's invariable plane](https://en.wikipedia.org/wiki/Invariable_plane), + * regardless of the body's direction of rotation. + * + * The `spin` field indicates the angular position of a prime meridian + * arbitrarily recommended for the body by the International Astronomical + * Union (IAU). + * + * The fields `ra`, `dec`, and `spin` correspond to the variables + * α0, δ0, and W, respectively, from + * [Report of the IAU Working Group on Cartographic Coordinates and Rotational Elements: 2015](https://astropedia.astrogeology.usgs.gov/download/Docs/WGCCRE/WGCCRE2015reprint.pdf). + * The field `north` is a unit vector pointing in the direction of the body's north pole. + * It is expressed in the J2000 mean equator system (EQJ). + * + * @property {number} ra + * The J2000 right ascension of the body's north pole direction, in sidereal hours. + * + * @property {number} dec + * The J2000 declination of the body's north pole direction, in degrees. + * + * @property {number} spin + * Rotation angle of the body's prime meridian, in degrees. + * + * @property {Vector} north + * A J2000 dimensionless unit vector pointing in the direction of the body's north pole. + */ +export class AxisInfo { + constructor(ra, dec, spin, north) { + this.ra = ra; + this.dec = dec; + this.spin = spin; + this.north = north; + } +} +function EarthRotationAxis(time) { + // Unlike the other planets, we have a model of precession and nutation + // for the Earth's axis that provides a north pole vector. + // So calculate the vector first, then derive the (RA,DEC) angles from the vector. + // Start with a north pole vector in equator-of-date coordinates: (0,0,1). + // Convert the vector into J2000 coordinates. + const pos2 = nutation([0, 0, 1], time, PrecessDirection.Into2000); + const nvec = precession(pos2, time, PrecessDirection.Into2000); + const north = new Vector(nvec[0], nvec[1], nvec[2], time); + // Derive angular values: right ascension and declination. + const equ = EquatorFromVector(north); + // Use a modified version of the era() function that does not trim to 0..360 degrees. + // This expression is also corrected to give the correct angle at the J2000 epoch. + const spin = 190.41375788700253 + (360.9856122880876 * time.ut); + return new AxisInfo(equ.ra, equ.dec, spin, north); +} +/** + * @brief Calculates information about a body's rotation axis at a given time. + * Calculates the orientation of a body's rotation axis, along with + * the rotation angle of its prime meridian, at a given moment in time. + * + * This function uses formulas standardized by the IAU Working Group + * on Cartographics and Rotational Elements 2015 report, as described + * in the following document: + * + * https://astropedia.astrogeology.usgs.gov/download/Docs/WGCCRE/WGCCRE2015reprint.pdf + * + * See {@link AxisInfo} for more detailed information. + * + * @param {Body} body + * One of the following values: + * `Body.Sun`, `Body.Moon`, `Body.Mercury`, `Body.Venus`, `Body.Earth`, `Body.Mars`, + * `Body.Jupiter`, `Body.Saturn`, `Body.Uranus`, `Body.Neptune`, `Body.Pluto`. + * + * @param {FlexibleDateTime} date + * The time at which to calculate the body's rotation axis. + * + * @returns {AxisInfo} + */ +export function RotationAxis(body, date) { + const time = MakeTime(date); + const d = time.tt; + const T = d / 36525.0; + let ra, dec, w; + switch (body) { + case Body.Sun: + ra = 286.13; + dec = 63.87; + w = 84.176 + (14.1844 * d); + break; + case Body.Mercury: + ra = 281.0103 - (0.0328 * T); + dec = 61.4155 - (0.0049 * T); + w = (329.5988 + + (6.1385108 * d) + + (0.01067257 * Math.sin(DEG2RAD * (174.7910857 + 4.092335 * d))) + - (0.00112309 * Math.sin(DEG2RAD * (349.5821714 + 8.184670 * d))) + - (0.00011040 * Math.sin(DEG2RAD * (164.3732571 + 12.277005 * d))) + - (0.00002539 * Math.sin(DEG2RAD * (339.1643429 + 16.369340 * d))) + - (0.00000571 * Math.sin(DEG2RAD * (153.9554286 + 20.461675 * d)))); + break; + case Body.Venus: + ra = 272.76; + dec = 67.16; + w = 160.20 - (1.4813688 * d); + break; + case Body.Earth: + return EarthRotationAxis(time); + case Body.Moon: + // See page 8, Table 2 in: + // https://astropedia.astrogeology.usgs.gov/alfresco/d/d/workspace/SpacesStore/28fd9e81-1964-44d6-a58b-fbbf61e64e15/WGCCRE2009reprint.pdf + const E1 = DEG2RAD * (125.045 - 0.0529921 * d); + const E2 = DEG2RAD * (250.089 - 0.1059842 * d); + const E3 = DEG2RAD * (260.008 + 13.0120009 * d); + const E4 = DEG2RAD * (176.625 + 13.3407154 * d); + const E5 = DEG2RAD * (357.529 + 0.9856003 * d); + const E6 = DEG2RAD * (311.589 + 26.4057084 * d); + const E7 = DEG2RAD * (134.963 + 13.0649930 * d); + const E8 = DEG2RAD * (276.617 + 0.3287146 * d); + const E9 = DEG2RAD * (34.226 + 1.7484877 * d); + const E10 = DEG2RAD * (15.134 - 0.1589763 * d); + const E11 = DEG2RAD * (119.743 + 0.0036096 * d); + const E12 = DEG2RAD * (239.961 + 0.1643573 * d); + const E13 = DEG2RAD * (25.053 + 12.9590088 * d); + ra = (269.9949 + 0.0031 * T + - 3.8787 * Math.sin(E1) + - 0.1204 * Math.sin(E2) + + 0.0700 * Math.sin(E3) + - 0.0172 * Math.sin(E4) + + 0.0072 * Math.sin(E6) + - 0.0052 * Math.sin(E10) + + 0.0043 * Math.sin(E13)); + dec = (66.5392 + 0.0130 * T + + 1.5419 * Math.cos(E1) + + 0.0239 * Math.cos(E2) + - 0.0278 * Math.cos(E3) + + 0.0068 * Math.cos(E4) + - 0.0029 * Math.cos(E6) + + 0.0009 * Math.cos(E7) + + 0.0008 * Math.cos(E10) + - 0.0009 * Math.cos(E13)); + w = (38.3213 + (13.17635815 - 1.4e-12 * d) * d + + 3.5610 * Math.sin(E1) + + 0.1208 * Math.sin(E2) + - 0.0642 * Math.sin(E3) + + 0.0158 * Math.sin(E4) + + 0.0252 * Math.sin(E5) + - 0.0066 * Math.sin(E6) + - 0.0047 * Math.sin(E7) + - 0.0046 * Math.sin(E8) + + 0.0028 * Math.sin(E9) + + 0.0052 * Math.sin(E10) + + 0.0040 * Math.sin(E11) + + 0.0019 * Math.sin(E12) + - 0.0044 * Math.sin(E13)); + break; + case Body.Mars: + ra = (317.269202 - 0.10927547 * T + + 0.000068 * Math.sin(DEG2RAD * (198.991226 + 19139.4819985 * T)) + + 0.000238 * Math.sin(DEG2RAD * (226.292679 + 38280.8511281 * T)) + + 0.000052 * Math.sin(DEG2RAD * (249.663391 + 57420.7251593 * T)) + + 0.000009 * Math.sin(DEG2RAD * (266.183510 + 76560.6367950 * T)) + + 0.419057 * Math.sin(DEG2RAD * (79.398797 + 0.5042615 * T))); + dec = (54.432516 - 0.05827105 * T + + 0.000051 * Math.cos(DEG2RAD * (122.433576 + 19139.9407476 * T)) + + 0.000141 * Math.cos(DEG2RAD * (43.058401 + 38280.8753272 * T)) + + 0.000031 * Math.cos(DEG2RAD * (57.663379 + 57420.7517205 * T)) + + 0.000005 * Math.cos(DEG2RAD * (79.476401 + 76560.6495004 * T)) + + 1.591274 * Math.cos(DEG2RAD * (166.325722 + 0.5042615 * T))); + w = (176.049863 + 350.891982443297 * d + + 0.000145 * Math.sin(DEG2RAD * (129.071773 + 19140.0328244 * T)) + + 0.000157 * Math.sin(DEG2RAD * (36.352167 + 38281.0473591 * T)) + + 0.000040 * Math.sin(DEG2RAD * (56.668646 + 57420.9295360 * T)) + + 0.000001 * Math.sin(DEG2RAD * (67.364003 + 76560.2552215 * T)) + + 0.000001 * Math.sin(DEG2RAD * (104.792680 + 95700.4387578 * T)) + + 0.584542 * Math.sin(DEG2RAD * (95.391654 + 0.5042615 * T))); + break; + case Body.Jupiter: + const Ja = DEG2RAD * (99.360714 + 4850.4046 * T); + const Jb = DEG2RAD * (175.895369 + 1191.9605 * T); + const Jc = DEG2RAD * (300.323162 + 262.5475 * T); + const Jd = DEG2RAD * (114.012305 + 6070.2476 * T); + const Je = DEG2RAD * (49.511251 + 64.3000 * T); + ra = (268.056595 - 0.006499 * T + + 0.000117 * Math.sin(Ja) + + 0.000938 * Math.sin(Jb) + + 0.001432 * Math.sin(Jc) + + 0.000030 * Math.sin(Jd) + + 0.002150 * Math.sin(Je)); + dec = (64.495303 + 0.002413 * T + + 0.000050 * Math.cos(Ja) + + 0.000404 * Math.cos(Jb) + + 0.000617 * Math.cos(Jc) + - 0.000013 * Math.cos(Jd) + + 0.000926 * Math.cos(Je)); + w = 284.95 + 870.536 * d; + break; + case Body.Saturn: + ra = 40.589 - 0.036 * T; + dec = 83.537 - 0.004 * T; + w = 38.90 + 810.7939024 * d; + break; + case Body.Uranus: + ra = 257.311; + dec = -15.175; + w = 203.81 - 501.1600928 * d; + break; + case Body.Neptune: + const N = DEG2RAD * (357.85 + 52.316 * T); + ra = 299.36 + 0.70 * Math.sin(N); + dec = 43.46 - 0.51 * Math.cos(N); + w = 249.978 + 541.1397757 * d - 0.48 * Math.sin(N); + break; + case Body.Pluto: + ra = 132.993; + dec = -6.163; + w = 302.695 + 56.3625225 * d; + break; + default: + throw `Invalid body: ${body}`; + } + // Calculate the north pole vector using the given angles. + const radlat = dec * DEG2RAD; + const radlon = ra * DEG2RAD; + const rcoslat = Math.cos(radlat); + const north = new Vector(rcoslat * Math.cos(radlon), rcoslat * Math.sin(radlon), Math.sin(radlat), time); + return new AxisInfo(ra / 15, dec, w, north); +} +/** + * @brief Calculates one of the 5 Lagrange points for a pair of co-orbiting bodies. + * + * Given a more massive "major" body and a much less massive "minor" body, + * calculates one of the five Lagrange points in relation to the minor body's + * orbit around the major body. The parameter `point` is an integer that + * selects the Lagrange point as follows: + * + * 1 = the Lagrange point between the major body and minor body. + * 2 = the Lagrange point on the far side of the minor body. + * 3 = the Lagrange point on the far side of the major body. + * 4 = the Lagrange point 60 degrees ahead of the minor body's orbital position. + * 5 = the Lagrange point 60 degrees behind the minor body's orbital position. + * + * The function returns the state vector for the selected Lagrange point + * in J2000 mean equator coordinates (EQJ), with respect to the center of the + * major body. + * + * To calculate Sun/Earth Lagrange points, pass in `Body.Sun` for `major_body` + * and `Body.EMB` (Earth/Moon barycenter) for `minor_body`. + * For Lagrange points of the Sun and any other planet, pass in that planet + * (e.g. `Body.Jupiter`) for `minor_body`. + * To calculate Earth/Moon Lagrange points, pass in `Body.Earth` and `Body.Moon` + * for the major and minor bodies respectively. + * + * In some cases, it may be more efficient to call {@link LagrangePointFast}, + * especially when the state vectors have already been calculated, or are needed + * for some other purpose. + * + * @param {number} point + * An integer 1..5 that selects which of the Lagrange points to calculate. + * + * @param {FlexibleDateTime} date + * The time at which the Lagrange point is to be calculated. + * + * @param {Body} major_body + * The more massive of the co-orbiting bodies: `Body.Sun` or `Body.Earth`. + * + * @param {Body} minor_body + * The less massive of the co-orbiting bodies. See main remarks. + * + * @returns {StateVector} + * The position and velocity of the selected Lagrange point with respect to the major body's center. + */ +export function LagrangePoint(point, date, major_body, minor_body) { + const time = MakeTime(date); + const major_mass = MassProduct(major_body); + const minor_mass = MassProduct(minor_body); + let major_state; + let minor_state; + // Calculate the state vectors for the major and minor bodies. + if (major_body === Body.Earth && minor_body === Body.Moon) { + // Use geocentric calculations for more precision. + // The Earth's geocentric state is trivial. + major_state = new StateVector(0, 0, 0, 0, 0, 0, time); + minor_state = GeoMoonState(time); + } + else { + major_state = HelioState(major_body, time); + minor_state = HelioState(minor_body, time); + } + return LagrangePointFast(point, major_state, major_mass, minor_state, minor_mass); +} +/** + * @brief Calculates one of the 5 Lagrange points from body masses and state vectors. + * + * Given a more massive "major" body and a much less massive "minor" body, + * calculates one of the five Lagrange points in relation to the minor body's + * orbit around the major body. The parameter `point` is an integer that + * selects the Lagrange point as follows: + * + * 1 = the Lagrange point between the major body and minor body. + * 2 = the Lagrange point on the far side of the minor body. + * 3 = the Lagrange point on the far side of the major body. + * 4 = the Lagrange point 60 degrees ahead of the minor body's orbital position. + * 5 = the Lagrange point 60 degrees behind the minor body's orbital position. + * + * The caller passes in the state vector and mass for both bodies. + * The state vectors can be in any orientation and frame of reference. + * The body masses are expressed as GM products, where G = the universal + * gravitation constant and M = the body's mass. Thus the units for + * `major_mass` and `minor_mass` must be au^3/day^2. + * Use {@link MassProduct} to obtain GM values for various solar system bodies. + * + * The function returns the state vector for the selected Lagrange point + * using the same orientation as the state vector parameters `major_state` and `minor_state`, + * and the position and velocity components are with respect to the major body's center. + * + * Consider calling {@link LagrangePoint}, instead of this function, for simpler usage in most cases. + * + * @param {number} point + * A value 1..5 that selects which of the Lagrange points to calculate. + * + * @param {StateVector} major_state + * The state vector of the major (more massive) of the pair of bodies. + * + * @param {number} major_mass + * The mass product GM of the major body. + * + * @param {StateVector} minor_state + * The state vector of the minor (less massive) of the pair of bodies. + * + * @param {number} minor_mass + * The mass product GM of the minor body. + * + * @returns {StateVector} + * The position and velocity of the selected Lagrange point with respect to the major body's center. + */ +export function LagrangePointFast(point, major_state, major_mass, minor_state, minor_mass) { + const cos_60 = 0.5; + const sin_60 = 0.8660254037844386; /* sqrt(3) / 2 */ + if (point < 1 || point > 5) + throw `Invalid lagrange point ${point}`; + if (!Number.isFinite(major_mass) || major_mass <= 0.0) + throw 'Major mass must be a positive number.'; + if (!Number.isFinite(minor_mass) || minor_mass <= 0.0) + throw 'Minor mass must be a negative number.'; + // Find the relative position vector . + let dx = minor_state.x - major_state.x; + let dy = minor_state.y - major_state.y; + let dz = minor_state.z - major_state.z; + const R2 = (dx * dx + dy * dy + dz * dz); + // R = Total distance between the bodies. + const R = Math.sqrt(R2); + // Find the relative velocity vector . + const vx = minor_state.vx - major_state.vx; + const vy = minor_state.vy - major_state.vy; + const vz = minor_state.vz - major_state.vz; + let p; + if (point === 4 || point === 5) { + // For L4 and L5, we need to find points 60 degrees away from the + // line connecting the two bodies and in the instantaneous orbital plane. + // Define the instantaneous orbital plane as the unique plane that contains + // both the relative position vector and the relative velocity vector. + // Take the cross product of position and velocity to find a normal vector . + const nx = dy * vz - dz * vy; + const ny = dz * vx - dx * vz; + const nz = dx * vy - dy * vx; + // Take the cross product normal*position to get a tangential vector . + let ux = ny * dz - nz * dy; + let uy = nz * dx - nx * dz; + let uz = nx * dy - ny * dx; + // Convert the tangential direction vector to a unit vector. + const U = Math.sqrt(ux * ux + uy * uy + uz * uz); + ux /= U; + uy /= U; + uz /= U; + // Convert the relative position vector into a unit vector. + dx /= R; + dy /= R; + dz /= R; + // Now we have two perpendicular unit vectors in the orbital plane: 'd' and 'u'. + // Create new unit vectors rotated (+/-)60 degrees from the radius/tangent directions. + const vert = (point == 4) ? +sin_60 : -sin_60; + // Rotated radial vector + const Dx = cos_60 * dx + vert * ux; + const Dy = cos_60 * dy + vert * uy; + const Dz = cos_60 * dz + vert * uz; + // Rotated tangent vector + const Ux = cos_60 * ux - vert * dx; + const Uy = cos_60 * uy - vert * dy; + const Uz = cos_60 * uz - vert * dz; + // Calculate L4/L5 positions relative to the major body. + const px = R * Dx; + const py = R * Dy; + const pz = R * Dz; + // Use dot products to find radial and tangential components of the relative velocity. + const vrad = vx * dx + vy * dy + vz * dz; + const vtan = vx * ux + vy * uy + vz * uz; + // Calculate L4/L5 velocities. + const pvx = vrad * Dx + vtan * Ux; + const pvy = vrad * Dy + vtan * Uy; + const pvz = vrad * Dz + vtan * Uz; + p = new StateVector(px, py, pz, pvx, pvy, pvz, major_state.t); + } + else { + // Calculate the distances of each body from their mutual barycenter. + // r1 = negative distance of major mass from barycenter (e.g. Sun to the left of barycenter) + // r2 = positive distance of minor mass from barycenter (e.g. Earth to the right of barycenter) + const r1 = -R * (minor_mass / (major_mass + minor_mass)); + const r2 = +R * (major_mass / (major_mass + minor_mass)); + // Calculate the square of the angular orbital speed in [rad^2 / day^2]. + const omega2 = (major_mass + minor_mass) / (R2 * R); + // Use Newton's Method to numerically solve for the location where + // outward centrifugal acceleration in the rotating frame of reference + // is equal to net inward gravitational acceleration. + // First derive a good initial guess based on approximate analysis. + let scale, numer1, numer2; + if (point === 1 || point === 2) { + scale = (major_mass / (major_mass + minor_mass)) * Math.cbrt(minor_mass / (3.0 * major_mass)); + numer1 = -major_mass; // The major mass is to the left of L1 and L2. + if (point == 1) { + scale = 1.0 - scale; + numer2 = +minor_mass; // The minor mass is to the right of L1. + } + else { + scale = 1.0 + scale; + numer2 = -minor_mass; // The minor mass is to the left of L2. + } + } + else if (point === 3) { + scale = ((7.0 / 12.0) * minor_mass - major_mass) / (minor_mass + major_mass); + numer1 = +major_mass; // major mass is to the right of L3. + numer2 = +minor_mass; // minor mass is to the right of L3. + } + else { + throw `Invalid Langrage point ${point}. Must be an integer 1..5.`; + } + // Iterate Newton's Method until it converges. + let x = R * scale - r1; + let deltax; + do { + const dr1 = x - r1; + const dr2 = x - r2; + const accel = omega2 * x + numer1 / (dr1 * dr1) + numer2 / (dr2 * dr2); + const deriv = omega2 - 2 * numer1 / (dr1 * dr1 * dr1) - 2 * numer2 / (dr2 * dr2 * dr2); + deltax = accel / deriv; + x -= deltax; + } while (Math.abs(deltax / R) > 1.0e-14); + scale = (x - r1) / R; + p = new StateVector(scale * dx, scale * dy, scale * dz, scale * vx, scale * vy, scale * vz, major_state.t); + } + return p; +} +/** + * @brief A simulation of zero or more small bodies moving through the Solar System. + * + * This class calculates the movement of arbitrary small bodies, + * such as asteroids or comets, that move through the Solar System. + * It does so by calculating the gravitational forces on the small bodies + * from the Sun and planets. The user of this class supplies a + * list of initial positions and velocities for the small bodies. + * Then the class can update the positions and velocities over small + * time steps. + */ +export class GravitySimulator { + /** + * @brief Creates a gravity simulation object. + * + * @param {Body} originBody + * Specifies the origin of the reference frame. + * All position vectors and velocity vectors will use `originBody` + * as the origin of the coordinate system. + * This origin applies to all the input vectors provided in the + * `bodyStates` parameter of this function, along with all + * output vectors returned by {@link GravitySimulator#Update}. + * Most callers will want to provide one of the following: + * `Body.Sun` for heliocentric coordinates, + * `Body.SSB` for solar system barycentric coordinates, + * or `Body.Earth` for geocentric coordinates. Note that the + * gravity simulator does not correct for light travel time; + * all state vectors are tied to a Newtonian "instantaneous" time. + * + * @param {FlexibleDateTime} date + * The initial time at which to start the simulation. + * + * @param {StateVector[]} bodyStates + * An array of zero or more initial state vectors (positions and velocities) + * of the small bodies to be simulated. + * The caller must know the positions and velocities of the small bodies at an initial moment in time. + * Their positions and velocities are expressed with respect to `originBody`, using equatorial + * J2000 orientation (EQJ). + * Positions are expressed in astronomical units (AU). + * Velocities are expressed in AU/day. + * All the times embedded within the state vectors must exactly match `date`, + * or this constructor will throw an exception. + */ + constructor(originBody, date, bodyStates) { + const time = MakeTime(date); + this.originBody = originBody; + // Verify that the state vectors have matching times. + for (let b of bodyStates) { + if (b.t.tt !== time.tt) { + throw 'Inconsistent times in bodyStates'; + } + } + // Create a stub list that we append to later. + // We just need the stub to put into `this.curr`. + const smallBodyList = []; + // Calculate the states of the Sun and planets. + const largeBodyDict = GravitySimulator.CalcSolarSystem(time); + this.curr = new GravSimEndpoint(time, largeBodyDict, smallBodyList); + // Convert origin-centric bodyStates vectors into barycentric body_grav_calc_t array. + const o = this.InternalBodyState(originBody); + for (let b of bodyStates) { + const r = new TerseVector(b.x + o.r.x, b.y + o.r.y, b.z + o.r.z); + const v = new TerseVector(b.vx + o.v.x, b.vy + o.v.y, b.vz + o.v.z); + const a = TerseVector.zero(); + smallBodyList.push(new body_grav_calc_t(time.tt, r, v, a)); + } + // Calculate the net acceleration experienced by the small bodies. + this.CalcBodyAccelerations(); + // To prepare for a possible swap operation, duplicate the current state into the previous state. + this.prev = this.Duplicate(); + } + /** + * @brief The body that was selected as the coordinate origin when this simulator was created. + */ + get OriginBody() { + return this.originBody; + } + /** + * @brief The time represented by the current step of the gravity simulation. + */ + get Time() { + return this.curr.time; + } + /** + * Advances the gravity simulation by a small time step. + * + * Updates the simulation of the user-supplied small bodies + * to the time indicated by the `date` parameter. + * Returns an array of state vectors for the simulated bodies. + * The array is in the same order as the original array that + * was used to construct this simulator object. + * The positions and velocities in the returned array are + * referenced to the `originBody` that was used to construct + * this simulator. + * + * @param {FlexibleDateTime} date + * A time that is a small increment away from the current simulation time. + * It is up to the developer to figure out an appropriate time increment. + * Depending on the trajectories, a smaller or larger increment + * may be needed for the desired accuracy. Some experimentation may be needed. + * Generally, bodies that stay in the outer Solar System and move slowly can + * use larger time steps. Bodies that pass into the inner Solar System and + * move faster will need a smaller time step to maintain accuracy. + * The `date` value may be after or before the current simulation time + * to move forward or backward in time. + * + * @return {StateVector[]} + * An array of state vectors, one for each simulated small body. + */ + Update(date) { + const time = MakeTime(date); + const dt = time.tt - this.curr.time.tt; + if (dt === 0.0) { + // Special case: the time has not changed, so skip the usual physics calculations. + // This allows another way for the caller to query the current body states. + // It is also necessary to avoid dividing by `dt` if `dt` is zero. + // To prepare for a possible swap operation, duplicate the current state into the previous state. + this.prev = this.Duplicate(); + } + else { + // Exchange the current state with the previous state. Then calculate the new current state. + this.Swap(); + // Update the current time. + this.curr.time = time; + // Calculate the positions and velocities of the Sun and planets at the given time. + this.curr.gravitators = GravitySimulator.CalcSolarSystem(time); + // Estimate the positions of the small bodies as if their existing + // accelerations apply across the whole time interval. + for (let i = 0; i < this.curr.bodies.length; ++i) { + const p = this.prev.bodies[i]; + this.curr.bodies[i].r = UpdatePosition(dt, p.r, p.v, p.a); + } + // Calculate the acceleration experienced by the small bodies at + // their respective approximate next locations. + this.CalcBodyAccelerations(); + for (let i = 0; i < this.curr.bodies.length; ++i) { + // Calculate the average of the acceleration vectors + // experienced by the previous body positions and + // their estimated next positions. + // These become estimates of the mean effective accelerations + // over the whole interval. + const p = this.prev.bodies[i]; + const c = this.curr.bodies[i]; + const acc = p.a.mean(c.a); + // Refine the estimates of position and velocity at the next time step, + // using the mean acceleration as a better approximation of the + // continuously changing acceleration acting on each body. + c.tt = time.tt; + c.r = UpdatePosition(dt, p.r, p.v, acc); + c.v = UpdateVelocity(dt, p.v, acc); + } + // Re-calculate accelerations experienced by each body. + // These will be needed for the next simulation step (if any). + // Also, they will be potentially useful if some day we add + // a function to query the acceleration vectors for the bodies. + this.CalcBodyAccelerations(); + } + // Translate our internal calculations of body positions and velocities + // into state vectors that the caller can understand. + // We have to convert the internal type body_grav_calc_t to the public type StateVector. + // Also convert from barycentric coordinates to coordinates based on the selected origin body. + const bodyStates = []; + const ostate = this.InternalBodyState(this.originBody); + for (let bcalc of this.curr.bodies) { + bodyStates.push(new StateVector(bcalc.r.x - ostate.r.x, bcalc.r.y - ostate.r.y, bcalc.r.z - ostate.r.z, bcalc.v.x - ostate.v.x, bcalc.v.y - ostate.v.y, bcalc.v.z - ostate.v.z, time)); + } + return bodyStates; + } + /** + * Exchange the current time step with the previous time step. + * + * Sometimes it is helpful to "explore" various times near a given + * simulation time step, while repeatedly returning to the original + * time step. For example, when backdating a position for light travel + * time, the caller may wish to repeatedly try different amounts of + * backdating. When the backdating solver has converged, the caller + * wants to leave the simulation in its original state. + * + * This function allows a single "undo" of a simulation, and does so + * very efficiently. + * + * Usually this function will be called immediately after a matching + * call to {@link GravitySimulator#Update}. It has the effect of rolling + * back the most recent update. If called twice in a row, it reverts + * the swap and thus has no net effect. + * + * The constructor initializes the current state and previous + * state to be identical. Both states represent the `time` parameter that was + * passed into the constructor. Therefore, `Swap` will + * have no effect from the caller's point of view when passed a simulator + * that has not yet been updated by a call to {@link GravitySimulator#Update}. + */ + Swap() { + const swap = this.curr; + this.curr = this.prev; + this.prev = swap; + } + /** + * Get the position and velocity of a Solar System body included in the simulation. + * + * In order to simulate the movement of small bodies through the Solar System, + * the simulator needs to calculate the state vectors for the Sun and planets. + * + * If an application wants to know the positions of one or more of the planets + * in addition to the small bodies, this function provides a way to obtain + * their state vectors. This is provided for the sake of efficiency, to avoid + * redundant calculations. + * + * The state vector is returned relative to the position and velocity + * of the `originBody` parameter that was passed to this object's constructor. + * + * @param {Body} body + * The Sun, Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, or Neptune. + */ + SolarSystemBodyState(body) { + const bstate = this.InternalBodyState(body); + const ostate = this.InternalBodyState(this.originBody); + return ExportState(bstate.sub(ostate), this.curr.time); + } + InternalBodyState(body) { + if (body === Body.SSB) + return new body_state_t(this.curr.time.tt, TerseVector.zero(), TerseVector.zero()); + const bstate = this.curr.gravitators[body]; + if (bstate) + return bstate; + throw `Invalid body: ${body}`; + } + static CalcSolarSystem(time) { + const dict = {}; + // Start with the SSB at zero position and velocity. + const ssb = new body_state_t(time.tt, TerseVector.zero(), TerseVector.zero()); + // Calculate the heliocentric position of each planet, and adjust the SSB + // based each planet's pull on the Sun. + dict[Body.Mercury] = AdjustBarycenterPosVel(ssb, time.tt, Body.Mercury, MERCURY_GM); + dict[Body.Venus] = AdjustBarycenterPosVel(ssb, time.tt, Body.Venus, VENUS_GM); + dict[Body.Earth] = AdjustBarycenterPosVel(ssb, time.tt, Body.Earth, EARTH_GM + MOON_GM); + dict[Body.Mars] = AdjustBarycenterPosVel(ssb, time.tt, Body.Mars, MARS_GM); + dict[Body.Jupiter] = AdjustBarycenterPosVel(ssb, time.tt, Body.Jupiter, JUPITER_GM); + dict[Body.Saturn] = AdjustBarycenterPosVel(ssb, time.tt, Body.Saturn, SATURN_GM); + dict[Body.Uranus] = AdjustBarycenterPosVel(ssb, time.tt, Body.Uranus, URANUS_GM); + dict[Body.Neptune] = AdjustBarycenterPosVel(ssb, time.tt, Body.Neptune, NEPTUNE_GM); + // Convert planet states from heliocentric to barycentric. + for (let body in dict) { + dict[body].r.decr(ssb.r); + dict[body].v.decr(ssb.v); + } + // Convert heliocentric SSB to barycentric Sun. + dict[Body.Sun] = new body_state_t(time.tt, ssb.r.neg(), ssb.v.neg()); + return dict; + } + CalcBodyAccelerations() { + // Calculate the gravitational acceleration experienced by the simulated small bodies. + for (let b of this.curr.bodies) { + b.a = TerseVector.zero(); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Sun].r, SUN_GM); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Mercury].r, MERCURY_GM); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Venus].r, VENUS_GM); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Earth].r, EARTH_GM + MOON_GM); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Mars].r, MARS_GM); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Jupiter].r, JUPITER_GM); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Saturn].r, SATURN_GM); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Uranus].r, URANUS_GM); + GravitySimulator.AddAcceleration(b.a, b.r, this.curr.gravitators[Body.Neptune].r, NEPTUNE_GM); + } + } + static AddAcceleration(acc, smallPos, majorPos, gm) { + const dx = majorPos.x - smallPos.x; + const dy = majorPos.y - smallPos.y; + const dz = majorPos.z - smallPos.z; + const r2 = dx * dx + dy * dy + dz * dz; + const pull = gm / (r2 * Math.sqrt(r2)); + acc.x += dx * pull; + acc.y += dy * pull; + acc.z += dz * pull; + } + Duplicate() { + // Copy the current state into the previous state, so that both become the same moment in time. + const gravitators = {}; + for (let body in this.curr.gravitators) { + gravitators[body] = this.curr.gravitators[body].clone(); + } + const bodies = []; + for (let b of this.curr.bodies) { + bodies.push(b.clone()); + } + return new GravSimEndpoint(this.curr.time, gravitators, bodies); + } +} +class GravSimEndpoint { + constructor(time, gravitators, bodies) { + this.time = time; + this.gravitators = gravitators; + this.bodies = bodies; + } +} diff --git a/node_modules/astronomy-engine/package.json b/node_modules/astronomy-engine/package.json new file mode 100644 index 0000000..5c768b5 --- /dev/null +++ b/node_modules/astronomy-engine/package.json @@ -0,0 +1,50 @@ +{ + "name": "astronomy-engine", + "version": "2.1.19", + "description": "Astronomy calculation for Sun, Moon, and planets.", + "author": "Donald Cross", + "license": "MIT", + "homepage": "https://github.com/cosinekitty/astronomy#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/cosinekitty/astronomy.git" + }, + "bugs": { + "url": "https://github.com/cosinekitty/astronomy/issues" + }, + "keywords": [ + "astronomy", + "ephemeris", + "planet", + "sun", + "moon", + "solar", + "system", + "sunrise", + "sunset", + "equinox", + "solstice", + "constellation", + "orbit" + ], + "scripts": {}, + "files": [ + "esm/astronomy.js", + "astronomy.d.ts", + "astronomy.js", + "astronomy.min.js", + "astronomy.browser.js", + "astronomy.browser.min.js" + ], + "exports": { + ".": { + "require": "./astronomy.js", + "import": "./esm/astronomy.js", + "types": "./astronomy.d.ts" + } + }, + "main": "./astronomy.js", + "module": "./esm/astronomy.js", + "types": "./astronomy.d.ts", + "sideEffects": false +} diff --git a/node_modules/geomagnetism/LICENSE b/node_modules/geomagnetism/LICENSE new file mode 100644 index 0000000..d9a10c0 --- /dev/null +++ b/node_modules/geomagnetism/LICENSE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/node_modules/geomagnetism/Makefile b/node_modules/geomagnetism/Makefile new file mode 100644 index 0000000..0064415 --- /dev/null +++ b/node_modules/geomagnetism/Makefile @@ -0,0 +1,21 @@ +.PHONY: test release + +_MOCHA=node_modules/.bin/_mocha + +test: + npm run test-ci + +release: test +ifeq ($(strip $(version)),) + @echo "\033[31mERROR:\033[0;39m No version provided" + @echo "\033[1;30mmake release version=1.0.0\033[0;39m" +else +ifneq ($(shell git diff --stat),) + @echo "Changes must be committed before running a release" +else + npm version $(version) + npm publish + git push origin master + git push origin --tags +endif +endif diff --git a/node_modules/geomagnetism/README.md b/node_modules/geomagnetism/README.md new file mode 100644 index 0000000..5bb4693 --- /dev/null +++ b/node_modules/geomagnetism/README.md @@ -0,0 +1,93 @@ +# geomagnetism +[![NPM version](http://img.shields.io/npm/v/geomagnetism.svg?style=flat)](https://www.npmjs.org/package/geomagnetism) +[![Coverage Status](http://img.shields.io/coveralls/naturalatlas/geomagnetism/master.svg?style=flat)](https://coveralls.io/r/naturalatlas/geomagnetism) + +`geomagnetism` provides a convenient interface for retrieving the Earth's magnetic declination (variation between magnetic north and true north) at a given location and date. It leverages NOAA's [World Magnetic Model (WMM)](https://www.ngdc.noaa.gov/geomag/WMM/) to compute properties such as declination, inclination, horizontal intensity, and more. + +``` sh +$ npm install geomagnetism --save +``` + +### Usage + +The main entry point is the `model()` function. If you pass it a Date object, it will compute results for that specific date. If you do **not** pass a date, it will default to the current date. Once you have a model, you can query it using the `point()` method, which expects an array representing latitude and longitude. Optionally, you can provide an altitude as a third element in the array. + +- Latitude and longitude are required: `[lat, lon]` +- Altitude (optional) can be provided: `[lat, lon, altitude_in_kilometers]` + +**Example: Current Date** + +```js +const geomagnetism = require('geomagnetism'); + +// If no date is passed, the current date is used +const currentModel = geomagnetism.model(); +const info = currentModel.point([44.53461, -109.05572]); // only lat/lon +console.log('Declination (current date):', info.decl, 'degrees'); +``` + +**Example: Specific Date** + +```js +const geomagnetism = require('geomagnetism'); + +// If a date is passed, that specific date is used +const specificDateModel = geomagnetism.model(new Date('2020-10-05')); +const info = specificDateModel.point([44.53461, -109.05572]); +console.log('Declination on 2020-10-05:', info.decl, 'degrees'); +``` + +**Example: Including Altitude** + +```js +const geomagnetism = require('geomagnetism'); + +// Provide altitude as the third array item (in kilometers above mean sea level) +const model = geomagnetism.model(new Date('2022-01-01')); +const infoWithAltitude = model.point([44.53461, -109.05572, 1.5]); +console.log('Declination at altitude:', infoWithAltitude.decl, 'degrees'); +``` + +## Handling Out-of-Range Dates + +The `geomagnetism.model()` function determines the best available World Magnetic Model for the date you provide. If the given date falls outside the known range of the WMM data files, by default (`allowOutOfBoundsModel = false`), the function will throw an error indicating that no suitable model is found for the given date. + +If you would prefer that the library "fall back" to the closest available model rather than throwing an error, you can explicitly pass true to allowOutOfBoundsModel option. + +```js +geomagnetism.model(date, { allowOutOfBoundsModel: true }); +``` + +- `date`: *(optional)* A JavaScript Date object. Defaults to the current date if not specified. +- `allowOutOfBoundsModel`: *(optional)* A boolean. If not specified or false, throws an error if the date is out of range. If true, falls back to the nearest available model. + +**Examples:** + +```js +const geomagnetism = require('geomagnetism'); + +// Strict behavior (default): If the date is out of range, an error is thrown +try { + let model = geomagnetism.model(new Date('1900-01-01')); // allowOutOfBoundsModel defaults to false + let info = model.point([44.53461, -109.05572]); +} catch (err) { + console.error('Error (strict mode):', err.message); +} + +// Fallback behavior: If the date is out of range, it uses the closest model +let fallbackModel = geomagnetism.model(new Date('1900-01-01'), { allowOutOfBoundsModel: true }); +let fallbackInfo = fallbackModel.point([44.53461, -109.05572]); +console.log('Declination using fallback model:', fallbackInfo.decl); +``` + +## Available Data & Models + +`geomagnetism` ships with multiple versions of the WMM data, each valid for a certain time range. The library automatically picks the correct model based on the date you supply. Older models are included to gracefully handle historical dates when using the fallback behavior. + +## License + +Copyright © 2015–2024 [Natural Atlas, Inc.](https://naturalatlas.com/) & [Contributors](https://github.com/naturalatlas/geomagnetism/graphs/contributors) + +Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. diff --git a/node_modules/geomagnetism/bin/convert.js b/node_modules/geomagnetism/bin/convert.js new file mode 100644 index 0000000..f8b5028 --- /dev/null +++ b/node_modules/geomagnetism/bin/convert.js @@ -0,0 +1,36 @@ +var fs = require('fs'); +var path = require('path'); + +/** + * Converts a coefficients file to a .json file that can be used to initialize a base model + * + * ex: node bin/convert WMM.COF wmm.json + */ + +function exit(err){ + console.log("Error: "+err); + process.exit(1); +} + + +var input_filename = process.argv[2]; +var output_filename = process.argv[3]; +if(!input_filename) exit("Input filename must be provided."); +if(!output_filename) exit("Output filename must be provided."); + +// get parser by input file extension +var ext = path.extname(input_filename).toLowerCase().substr(1); +var parser; +try { + parser = require('../lib/parsers/'+ext); +} catch (err) { + exit("Unable to find parser for ."+ext+" file."); +} + +var data = fs.readFileSync(input_filename, {encoding: 'utf8'}); +var obj = parser(data); +var json = JSON.stringify(obj, null, 2); + +fs.writeFileSync(output_filename, json); + +console.log(output_filename + " successfully created"); \ No newline at end of file diff --git a/node_modules/geomagnetism/data/wmm-2015.json b/node_modules/geomagnetism/data/wmm-2015.json new file mode 100644 index 0000000..974fd11 --- /dev/null +++ b/node_modules/geomagnetism/data/wmm-2015.json @@ -0,0 +1,380 @@ +{ + "main_field_coeff_g": [ + 0, + -29438.5, + -1501.1, + -2445.3, + 3012.5, + 1676.6, + 1351.1, + -2352.3, + 1225.6, + 581.9, + 907.2, + 813.7, + 120.3, + -335, + 70.3, + -232.6, + 360.1, + 192.4, + -141, + -157.4, + 4.3, + 69.5, + 67.4, + 72.8, + -129.8, + -29, + 13.2, + -70.9, + 81.6, + -76.1, + -6.8, + 51.9, + 15, + 9.3, + -2.8, + 6.7, + 24, + 8.6, + -16.9, + -3.2, + -20.6, + 13.3, + 11.7, + -16, + -2, + 5.4, + 8.8, + 3.1, + -3.1, + 0.6, + -13.3, + -0.1, + 8.7, + -9.1, + -10.5, + -1.9, + -6.5, + 0.2, + 0.6, + -0.6, + 1.7, + -0.7, + 2.1, + 2.3, + -1.8, + -3.6, + 3.1, + -1.5, + -2.3, + 2.1, + -0.9, + 0.6, + -0.7, + 0.2, + 1.7, + -0.2, + 0.4, + 3.5, + -2, + -0.3, + 0.4, + 1.3, + -0.9, + 0.9, + 0.1, + 0.5, + -0.4, + -0.4, + 0.2, + -0.9, + 0 + ], + "main_field_coeff_h": [ + 0, + 0, + 4796.2, + 0, + -2845.6, + -642, + 0, + -115.3, + 245, + -538.3, + 0, + 283.4, + -188.6, + 180.9, + -329.5, + 0, + 47.4, + 196.9, + -119.4, + 16.1, + 100.1, + 0, + -20.7, + 33.2, + 58.8, + -66.5, + 7.3, + 62.5, + 0, + -54.1, + -19.4, + 5.6, + 24.4, + 3.3, + -27.5, + -2.3, + 0, + 10.2, + -18.1, + 13.2, + -14.6, + 16.2, + 5.7, + -9.1, + 2.2, + 0, + -21.6, + 10.8, + 11.7, + -6.8, + -6.9, + 7.8, + 1, + -3.9, + 8.5, + 0, + 3.3, + -0.3, + 4.6, + 4.4, + -7.9, + -0.6, + -4.1, + -2.8, + -1.1, + -8.7, + 0, + -0.1, + 2.1, + -0.7, + -1.1, + 0.7, + -0.2, + -2.1, + -1.5, + -2.5, + -2, + -2.3, + 0, + -1, + 0.5, + 1.8, + -2.2, + 0.3, + 0.7, + -0.1, + 0.3, + 0.2, + -0.9, + -0.2, + 0.7 + ], + "secular_var_coeff_g": [ + 0, + 10.7, + 17.9, + -8.6, + -3.3, + 2.4, + 3.1, + -6.2, + -0.4, + -10.4, + -0.4, + 0.8, + -9.2, + 4, + -4.2, + -0.2, + 0.1, + -1.4, + 0, + 1.3, + 3.8, + -0.5, + -0.2, + -0.6, + 2.4, + -1.1, + 0.3, + 1.5, + 0.2, + -0.2, + -0.4, + 1.3, + 0.2, + -0.4, + -0.9, + 0.3, + 0, + 0.1, + -0.5, + 0.5, + -0.2, + 0.4, + 0.2, + -0.4, + 0.3, + 0, + -0.1, + -0.1, + 0.4, + -0.5, + -0.2, + 0.1, + 0, + -0.2, + -0.1, + 0, + 0, + -0.1, + 0.3, + -0.1, + -0.1, + -0.1, + 0, + -0.2, + -0.1, + -0.2, + 0, + 0, + -0.1, + 0.1, + 0, + 0, + 0, + 0, + 0, + 0, + -0.1, + -0.1, + 0.1, + 0, + 0, + 0.1, + -0.1, + 0, + 0.1, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "secular_var_coeff_h": [ + 0, + 0, + -26.8, + 0, + -27.1, + -13.3, + 0, + 8.4, + -0.4, + 2.3, + 0, + -0.6, + 5.3, + 3, + -5.3, + 0, + 0.4, + 1.6, + -1.1, + 3.3, + 0.1, + 0, + 0, + -2.2, + -0.7, + 0.1, + 1, + 1.3, + 0, + 0.7, + 0.5, + -0.2, + -0.1, + -0.7, + 0.1, + 0.1, + 0, + -0.3, + 0.3, + 0.3, + 0.6, + -0.1, + -0.2, + 0.3, + 0, + 0, + -0.2, + -0.1, + -0.2, + 0.1, + 0.1, + 0, + -0.2, + 0.4, + 0.3, + 0, + 0.1, + -0.1, + 0, + 0, + -0.2, + 0.1, + -0.1, + -0.2, + 0.1, + -0.1, + 0, + 0, + 0.1, + 0, + 0.1, + 0, + 0, + 0.1, + 0, + -0.1, + 0, + -0.1, + 0, + 0, + 0, + -0.1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ], + "n_max": 12, + "n_max_sec_var": 12, + "epoch": 2015, + "name": "WMM-2015", + "start_date": "2014-12-15T07:00:00.000Z", + "end_date": "2019-12-15T07:00:00.000Z" +} \ No newline at end of file diff --git a/node_modules/geomagnetism/data/wmm-2015v2.json b/node_modules/geomagnetism/data/wmm-2015v2.json new file mode 100644 index 0000000..2e33cb8 --- /dev/null +++ b/node_modules/geomagnetism/data/wmm-2015v2.json @@ -0,0 +1,380 @@ +{ + "main_field_coeff_g": [ + 0, + -29438.2, + -1493.5, + -2444.5, + 3014.7, + 1679, + 1351.8, + -2351.6, + 1223.6, + 582.3, + 907.5, + 814.8, + 117.8, + -335.6, + 69.7, + -232.9, + 360.1, + 191.7, + -141.3, + -157.2, + 7.7, + 69.4, + 67.7, + 72.3, + -129.1, + -28.4, + 13.6, + -70.3, + 81.7, + -75.9, + -7.1, + 52.2, + 15, + 9.1, + -3, + 5.9, + 24.2, + 8.9, + -16.9, + -3.1, + -20.7, + 13.3, + 11.6, + -16.3, + -2.1, + 5.5, + 8.8, + 3, + -3.2, + 0.6, + -13.2, + -0.1, + 8.7, + -9.1, + -10.4, + -2, + -6.1, + 0.2, + 0.6, + -0.5, + 1.8, + -0.7, + 2.2, + 2.4, + -1.8, + -3.6, + 3, + -1.4, + -2.3, + 2.1, + -0.8, + 0.6, + -0.7, + 0.1, + 1.7, + -0.2, + 0.4, + 3.5, + -2, + -0.1, + 0.5, + 1.2, + -0.9, + 0.9, + 0.1, + 0.6, + -0.4, + -0.5, + 0.2, + -0.9, + 0 + ], + "main_field_coeff_h": [ + 0, + 0, + 4796.3, + 0, + -2842.4, + -638.8, + 0, + -113.7, + 246.5, + -537.4, + 0, + 283.3, + -188.6, + 180.7, + -330, + 0, + 46.9, + 196.5, + -119.9, + 16, + 100.6, + 0, + -20.1, + 32.8, + 59.1, + -67.1, + 8.1, + 61.9, + 0, + -54.3, + -19.5, + 6, + 24.5, + 3.5, + -27.7, + -2.9, + 0, + 10.1, + -18.3, + 13.3, + -14.5, + 16.2, + 6, + -9.2, + 2.4, + 0, + -21.8, + 10.7, + 11.8, + -6.8, + -6.9, + 7.9, + 1, + -3.9, + 8.5, + 0, + 3.3, + -0.4, + 4.6, + 4.4, + -7.9, + -0.6, + -4.2, + -2.9, + -1.1, + -8.8, + 0, + 0, + 2.1, + -0.6, + -1.1, + 0.7, + -0.2, + -2.1, + -1.5, + -2.6, + -2, + -2.3, + 0, + -1, + 0.3, + 1.8, + -2.2, + 0.3, + 0.7, + -0.1, + 0.3, + 0.2, + -0.9, + -0.2, + 0.8 + ], + "secular_var_coeff_g": [ + 0, + 7, + 9, + -11, + -6.2, + 0.3, + 2.4, + -5.7, + 2, + -11, + -0.8, + -0.9, + -6.5, + 5.2, + -4, + -0.3, + 0.6, + -0.8, + 0.1, + 1.2, + 1.4, + -0.8, + -0.5, + -0.1, + 1.6, + -1.6, + 0, + 1.2, + -0.3, + -0.2, + -0.3, + 0.9, + 0.1, + -0.6, + -0.9, + 0.7, + -0.1, + 0.2, + -0.2, + 0.5, + -0.1, + 0.4, + 0.4, + -0.1, + 0.4, + -0.1, + -0.1, + 0, + 0.4, + -0.4, + 0, + 0.3, + 0, + 0, + -0.3, + 0, + 0, + -0.1, + 0.2, + -0.1, + -0.2, + 0, + -0.1, + -0.2, + -0.1, + 0, + 0, + 0, + 0, + 0, + 0, + -0.1, + 0, + 0, + 0, + -0.1, + 0, + -0.1, + 0, + 0, + 0, + 0, + -0.1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -0.1 + ], + "secular_var_coeff_h": [ + 0, + 0, + -30.2, + 0, + -29.6, + -17.3, + 0, + 6.5, + -0.8, + -2, + 0, + -0.4, + 5.8, + 3.8, + -3.5, + 0, + 0.2, + 2.3, + 0, + 3.3, + -0.6, + 0, + 0.3, + -1.5, + -1.2, + 0.4, + 0.2, + 1.3, + 0, + 0.6, + 0.5, + -0.8, + -0.2, + -1.1, + 0.1, + 0.2, + 0, + -0.4, + 0.6, + -0.1, + 0.6, + -0.2, + -0.5, + 0.5, + 0.1, + 0, + -0.3, + 0.1, + -0.4, + 0.3, + 0.1, + 0, + -0.1, + 0.5, + 0.2, + 0, + 0, + 0.1, + -0.2, + 0.1, + -0.1, + 0.1, + 0, + -0.1, + 0.2, + 0, + 0, + 0, + 0.1, + 0, + 0.1, + 0, + 0, + 0.1, + 0, + -0.1, + 0, + -0.1, + 0, + 0, + 0, + -0.1, + 0.1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -0.1 + ], + "n_max": 12, + "n_max_sec_var": 12, + "epoch": 2015, + "name": "WMM-2015v2", + "start_date": "2018-09-18T06:00:00.000Z", + "end_date": "2023-09-18T06:00:00.000Z" +} diff --git a/node_modules/geomagnetism/data/wmm-2020.json b/node_modules/geomagnetism/data/wmm-2020.json new file mode 100644 index 0000000..660ef22 --- /dev/null +++ b/node_modules/geomagnetism/data/wmm-2020.json @@ -0,0 +1,380 @@ +{ + "main_field_coeff_g": [ + 0, + -29404.5, + -1450.7, + -2500, + 2982, + 1676.8, + 1363.9, + -2381, + 1236.2, + 525.7, + 903.1, + 809.4, + 86.2, + -309.4, + 47.9, + -234.4, + 363.1, + 187.8, + -140.7, + -151.2, + 13.7, + 65.9, + 65.6, + 73, + -121.5, + -36.2, + 13.5, + -64.7, + 80.6, + -76.8, + -8.3, + 56.5, + 15.8, + 6.4, + -7.2, + 9.8, + 23.6, + 9.8, + -17.5, + -0.4, + -21.1, + 15.3, + 13.7, + -16.5, + -0.3, + 5, + 8.2, + 2.9, + -1.4, + -1.1, + -13.3, + 1.1, + 8.9, + -9.3, + -11.9, + -1.9, + -6.2, + -0.1, + 1.7, + -0.9, + 0.6, + -0.9, + 1.9, + 1.4, + -2.4, + -3.9, + 3, + -1.4, + -2.5, + 2.4, + -0.9, + 0.3, + -0.7, + -0.1, + 1.4, + -0.6, + 0.2, + 3.1, + -2, + -0.1, + 0.5, + 1.3, + -1.2, + 0.7, + 0.3, + 0.5, + -0.2, + -0.5, + 0.1, + -1.1, + -0.3 + ], + "main_field_coeff_h": [ + 0, + 0, + 4652.9, + 0, + -2991.6, + -734.8, + 0, + -82.2, + 241.8, + -542.9, + 0, + 282, + -158.4, + 199.8, + -350.1, + 0, + 47.7, + 208.4, + -121.3, + 32.2, + 99.1, + 0, + -19.1, + 25, + 52.7, + -64.4, + 9, + 68.1, + 0, + -51.4, + -16.8, + 2.3, + 23.5, + -2.2, + -27.2, + -1.9, + 0, + 8.4, + -15.3, + 12.8, + -11.8, + 14.9, + 3.6, + -6.9, + 2.8, + 0, + -23.3, + 11.1, + 9.8, + -5.1, + -6.2, + 7.8, + 0.4, + -1.5, + 9.7, + 0, + 3.4, + -0.2, + 3.5, + 4.8, + -8.6, + -0.1, + -4.2, + -3.4, + -0.1, + -8.8, + 0, + 0, + 2.6, + -0.5, + -0.4, + 0.6, + -0.2, + -1.7, + -1.6, + -3, + -2, + -2.6, + 0, + -1.2, + 0.5, + 1.3, + -1.8, + 0.1, + 0.7, + -0.1, + 0.6, + 0.2, + -0.9, + 0, + 0.5 + ], + "secular_var_coeff_g": [ + 0, + 6.7, + 7.7, + -11.5, + -7.1, + -2.2, + 2.8, + -6.2, + 3.4, + -12.2, + -1.1, + -1.6, + -6, + 5.4, + -5.5, + -0.3, + 0.6, + -0.7, + 0.1, + 1.2, + 1, + -0.6, + -0.4, + 0.5, + 1.4, + -1.4, + 0, + 0.8, + -0.1, + -0.3, + -0.1, + 0.7, + 0.2, + -0.5, + -0.8, + 1, + -0.1, + 0.1, + -0.1, + 0.5, + -0.1, + 0.4, + 0.5, + 0, + 0.4, + -0.1, + -0.2, + 0, + 0.4, + -0.3, + 0, + 0.3, + 0, + 0, + -0.4, + 0, + 0, + 0, + 0.2, + -0.1, + -0.2, + 0, + -0.1, + -0.2, + -0.1, + 0, + 0, + -0.1, + 0, + 0, + 0, + -0.1, + 0, + 0, + -0.1, + -0.1, + -0.1, + -0.1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -0.1 + ], + "secular_var_coeff_h": [ + 0, + 0, + -25.1, + 0, + -30.2, + -23.9, + 0, + 5.7, + -1, + 1.1, + 0, + 0.2, + 6.9, + 3.7, + -5.6, + 0, + 0.1, + 2.5, + -0.9, + 3, + 0.5, + 0, + 0.1, + -1.8, + -1.4, + 0.9, + 0.1, + 1, + 0, + 0.5, + 0.6, + -0.7, + -0.2, + -1.2, + 0.2, + 0.3, + 0, + -0.3, + 0.7, + -0.2, + 0.5, + -0.3, + -0.5, + 0.4, + 0.1, + 0, + -0.3, + 0.2, + -0.4, + 0.4, + 0.1, + 0, + -0.2, + 0.5, + 0.2, + 0, + 0, + 0.1, + -0.3, + 0.1, + -0.2, + 0.1, + 0, + -0.1, + 0.2, + 0, + 0, + 0, + 0.1, + 0, + 0.2, + 0, + 0, + 0.1, + 0, + -0.1, + 0, + 0, + 0, + 0, + 0, + -0.1, + 0.1, + 0, + 0, + 0, + 0.1, + 0, + 0, + 0, + -0.1 + ], + "n_max": 12, + "n_max_sec_var": 12, + "epoch": 2020, + "name": "WMM-2020", + "start_date": "2019-12-10T08:00:00.000Z", + "end_date": "2024-12-10T08:00:00.000Z" +} \ No newline at end of file diff --git a/node_modules/geomagnetism/data/wmm-2025.json b/node_modules/geomagnetism/data/wmm-2025.json new file mode 100644 index 0000000..ede092c --- /dev/null +++ b/node_modules/geomagnetism/data/wmm-2025.json @@ -0,0 +1,380 @@ +{ + "main_field_coeff_g": [ + 0, + -29351.8, + -1410.8, + -2556.6, + 2951.1, + 1649.3, + 1361, + -2404.1, + 1243.8, + 453.6, + 895, + 799.5, + 55.7, + -281.1, + 12.1, + -233.2, + 368.9, + 187.2, + -138.7, + -142, + 20.9, + 64.4, + 63.8, + 76.9, + -115.7, + -40.9, + 14.9, + -60.7, + 79.5, + -77, + -8.8, + 59.3, + 15.8, + 2.5, + -11.1, + 14.2, + 23.2, + 10.8, + -17.5, + 2, + -21.7, + 16.9, + 15, + -16.8, + 0.9, + 4.6, + 7.8, + 3, + -0.2, + -2.5, + -13.1, + 2.4, + 8.6, + -8.7, + -12.9, + -1.3, + -6.4, + 0.2, + 2, + -1, + -0.6, + -0.9, + 1.5, + 0.9, + -2.7, + -3.9, + 2.9, + -1.5, + -2.5, + 2.4, + -0.6, + -0.1, + -0.6, + -0.1, + 1.1, + -1, + -0.2, + 2.6, + -2, + -0.2, + 0.3, + 1.2, + -1.3, + 0.6, + 0.6, + 0.5, + -0.1, + -0.4, + -0.2, + -1.3, + -0.7 + ], + "main_field_coeff_h": [ + 0, + 0, + 4545.4, + 0, + -3133.6, + -815.1, + 0, + -56.6, + 237.5, + -549.5, + 0, + 278.6, + -133.9, + 212, + -375.6, + 0, + 45.4, + 220.2, + -122.9, + 43, + 106.1, + 0, + -18.4, + 16.8, + 48.8, + -59.8, + 10.9, + 72.7, + 0, + -48.9, + -14.4, + -1, + 23.4, + -7.4, + -25.1, + -2.3, + 0, + 7.1, + -12.6, + 11.4, + -9.7, + 12.7, + 0.7, + -5.2, + 3.9, + 0, + -24.8, + 12.2, + 8.3, + -3.3, + -5.2, + 7.2, + -0.6, + 0.8, + 10, + 0, + 3.3, + 0, + 2.4, + 5.3, + -9.1, + 0.4, + -4.2, + -3.8, + 0.9, + -9.1, + 0, + 0, + 2.9, + -0.6, + 0.2, + 0.5, + -0.3, + -1.2, + -1.7, + -2.9, + -1.8, + -2.3, + 0, + -1.3, + 0.7, + 1, + -1.4, + 0, + 0.6, + -0.1, + 0.8, + 0.1, + -1, + 0.1, + 0.2 + ], + "secular_var_coeff_g": [ + 0, + 12, + 9.7, + -11.6, + -5.2, + -8, + -1.3, + -4.2, + 0.4, + -15.6, + -1.6, + -2.4, + -6, + 5.6, + -7, + 0.6, + 1.4, + 0, + 0.6, + 2.2, + 0.9, + -0.2, + -0.4, + 0.9, + 1.2, + -0.9, + 0.3, + 0.9, + 0, + -0.1, + -0.1, + 0.5, + -0.1, + -0.8, + -0.8, + 0.8, + -0.1, + 0.2, + 0, + 0.5, + -0.1, + 0.3, + 0.2, + 0, + 0.2, + 0, + -0.1, + 0.1, + 0.3, + -0.3, + 0, + 0.3, + -0.1, + 0.1, + -0.1, + 0.1, + 0, + 0.1, + 0.1, + 0, + -0.3, + 0, + -0.1, + -0.1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -0.1, + 0, + 0, + -0.1, + -0.1, + -0.1, + -0.1, + 0, + 0, + 0, + 0, + 0, + 0, + 0.1, + 0, + 0, + 0, + -0.1, + 0, + -0.1 + ], + "secular_var_coeff_h": [ + 0, + 0, + -21.5, + 0, + -27.7, + -12.1, + 0, + 4, + -0.3, + -4.1, + 0, + -1.1, + 4.1, + 1.6, + -4.4, + 0, + -0.5, + 2.2, + 0.4, + 1.7, + 1.9, + 0, + 0.3, + -1.6, + -0.4, + 0.9, + 0.7, + 0.9, + 0, + 0.6, + 0.5, + -0.8, + 0, + -1, + 0.6, + -0.2, + 0, + -0.2, + 0.5, + -0.4, + 0.4, + -0.5, + -0.6, + 0.3, + 0.2, + 0, + -0.3, + 0.3, + -0.3, + 0.3, + 0.2, + -0.1, + -0.2, + 0.4, + 0.1, + 0, + 0, + 0, + -0.2, + 0.1, + -0.1, + 0.1, + 0, + -0.1, + 0.2, + 0, + 0, + 0, + 0.1, + 0, + 0.1, + 0, + 0, + 0.1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -0.1, + 0.1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + -0.1 + ], + "n_max": 12, + "n_max_sec_var": 12, + "epoch": 2025, + "name": "WMM-2025", + "start_date": "2024-11-13T03:00:00.000Z", + "end_date": "2029-11-13T03:00:00.000Z" +} \ No newline at end of file diff --git a/node_modules/geomagnetism/geomagnetism.d.ts b/node_modules/geomagnetism/geomagnetism.d.ts new file mode 100644 index 0000000..44512b6 --- /dev/null +++ b/node_modules/geomagnetism/geomagnetism.d.ts @@ -0,0 +1,30 @@ +declare module "geomagnetism" { + export interface GeomagnetismPoint { + x: number; + y: number; + z: number; + h: number; + f: number; + incl: number; + decl: number; + } + + export interface GeomagnetismModel { + epoch: number; + start_date: Date; + end_date: Date; + name: string; + main_field_coeff_g: number[]; + secular_var_coeff_h: number[]; + n_max: number; + n_max_sec_var: number; + num_terms: number; + point(geoPoint: number[]): GeomagnetismPoint; + } + + export interface GeomagnetismOptions { + allowOutOfBoundsModel: boolean; + } + + export function model(date?: Date, options?: GeomagnetismOptions): GeomagnetismModel; +} diff --git a/node_modules/geomagnetism/index.js b/node_modules/geomagnetism/index.js new file mode 100644 index 0000000..731cb77 --- /dev/null +++ b/node_modules/geomagnetism/index.js @@ -0,0 +1,54 @@ +const Model = require('./lib/model.js'); +const geomagnetism = module.exports = {}; + +const modelData = [ + { + file: require('./data/wmm-2025.json'), + startDate: new Date("2024-11-13T03:00:00.000Z"), + endDate: new Date("2029-11-13T03:00:00.000Z") + }, + { + file: require('./data/wmm-2020.json'), + startDate: new Date("2019-12-10T08:00:00.000Z"), + endDate: new Date("2024-12-10T08:00:00.000Z") + }, + { + file: require('./data/wmm-2015v2.json'), + startDate: new Date("2018-09-18T06:00:00.000Z"), + endDate: new Date("2023-09-18T06:00:00.000Z") + }, + { + file: require('./data/wmm-2015.json'), + startDate: new Date("2014-12-15T07:00:00.000Z"), + endDate: new Date("2019-12-15T07:00:00.000Z") + } +]; + + +geomagnetism.model = function (date, options = {}) { + date = date || new Date(); + const ts = date.getTime(); + + const allowOutOfBoundsModel = (options && options.allowOutOfBoundsModel) || false; + + // Get the latest matching model + let matchingModelData = modelData.find((model) => { + return ts >= model.startDate.getTime() && ts <= model.endDate.getTime(); + }); + + // Get if the date is before the first model or after the last model + if (!matchingModelData && ts < modelData[modelData.length - 1].startDate.getTime()) { + matchingModelData = modelData[modelData.length - 1]; + } else if (!matchingModelData && ts > modelData[0].endDate.getTime()) { + matchingModelData = modelData[0]; + } + + // If no matching model found, use the latest + if (!matchingModelData) { + matchingModelData = modelData[0]; // latest (will throw error if allowOutOfBoundsModel is true) + } + + const matchingModel = new Model(matchingModelData.file); + + return matchingModel.getTimedModel(date, allowOutOfBoundsModel); +}; diff --git a/node_modules/geomagnetism/lib/coords/cartesian.js b/node_modules/geomagnetism/lib/coords/cartesian.js new file mode 100644 index 0000000..b650891 --- /dev/null +++ b/node_modules/geomagnetism/lib/coords/cartesian.js @@ -0,0 +1,46 @@ +var GeodeticCoord = require('./geodetic.js'); + +module.exports = CartesianCoord; + +function CartesianCoord(options){ + this.x = options.x; + this.y = options.y; + this.z = options.z; +} + +CartesianCoord.prototype.toGeodetic = function(ellipsoid){ + var modified_b = this.z < 0 ? -ellipsoid.b : ellipsoid.b; + var x = this.x; + var y = this.y; + var z = this.z; + var r = Math.sqr(x*x + y*y); + var e = (modified_b*z - (ellipsoid.a*ellipsoid.a - modified_b*modified_b)) / (ellipsoid.a*r); + var f = (modified_b*z + (ellipsoid.a*ellipsoid.a - modified_b*modified_b)) / (ellipsoid.a*r); + var p = (4/3) * (e*f+1); + var q = 2 * (e*e + f*f); + var d = p*p*p + q*q; + var v; + if(d > 0) { + v = Math.pow(Math.sqrt(d) - q, 1/3) - Math.pow(Math.sqrt(d) + q, 1/3); + } else { + v = 2 * Math.sqrt(-p) * Math.cos(Math.acos(q / (p * Math.sqrt(-p)) ) / 3); + } + if(v*v < Math.abs(p)) { + v = -(v*v*v + 2*q) / 3*p; + } + var g = (Math.sqrt(e*e + v) + e) / 2; + var t = Math.sqrt(g*g + (f - v*g)/(2*g - e)) - g; + var rlat = Math.atan( (ellipsoid.a*(1 - t*t)) / (2*modified_b*t) ); + var zlong = Math.atan2(y, x); + if(zlong < 0) zlong += 2*Math.PI; + var height_above_ellipsoid = (r - ellipsoid.a*t) * Math.cos(rlat) + (z - modified_b) * Math.sin(rlat); + var lambda = zlong * Math.PI/180; + if(lambda > 180) lambda -= 360; + + return new GeodeticCoord({ + lambda: lambda, + phi: rlat * Math.PI/180, + height_above_ellipsoid: height_above_ellipsoid, + ellipsoid: ellipsoid + }); +}; \ No newline at end of file diff --git a/node_modules/geomagnetism/lib/coords/geodetic.js b/node_modules/geomagnetism/lib/coords/geodetic.js new file mode 100644 index 0000000..1e37ee6 --- /dev/null +++ b/node_modules/geomagnetism/lib/coords/geodetic.js @@ -0,0 +1,31 @@ +var SphericalCoord = require('./spherical.js'); +var Ellipsoid = require('../ellipsoid.js'); + +module.exports = GeodeticCoord; + +function GeodeticCoord(options){ + this.options = options; + this.lambda = options.lambda || options.lon; // longitude + this.phi = options.phi || options.lat; // geodetic latitude + this.height_above_ellipsoid = options.height_above_ellipsoid || 0; + this.ellipsoid = options.ellipsoid || new Ellipsoid(); +} + +GeodeticCoord.prototype.toSpherical = function() { + var ellipsoid = this.ellipsoid; + var coslat = Math.cos(this.phi*Math.PI/180); + var sinlat = Math.sin(this.phi*Math.PI/180); + var rc = ellipsoid.a / Math.sqrt(1 - ellipsoid.epssq * sinlat * sinlat); + var xp = (rc + this.height_above_ellipsoid) * coslat; + var zp = (rc * (1 - ellipsoid.epssq) + this.height_above_ellipsoid) * sinlat; + var r = Math.sqrt(xp*xp + zp*zp); + return new SphericalCoord({ + r: r, + phig: 180/Math.PI*Math.asin(zp / r), + lambda: this.lambda + }); +}; + +GeodeticCoord.prototype.clone = function(){ + return new GeodeticCoord(this.options); +}; \ No newline at end of file diff --git a/node_modules/geomagnetism/lib/coords/index.js b/node_modules/geomagnetism/lib/coords/index.js new file mode 100644 index 0000000..d69697f --- /dev/null +++ b/node_modules/geomagnetism/lib/coords/index.js @@ -0,0 +1,5 @@ +module.exports = { + Cartesian: require('./cartesian.js'), + Spherical: require('./spherical.js'), + Geodetic: require('./geodetic.js') +}; \ No newline at end of file diff --git a/node_modules/geomagnetism/lib/coords/spherical.js b/node_modules/geomagnetism/lib/coords/spherical.js new file mode 100644 index 0000000..abc925c --- /dev/null +++ b/node_modules/geomagnetism/lib/coords/spherical.js @@ -0,0 +1,54 @@ +var CartesianCoord = require('./cartesian.js'); +var LegendreFunction = require('../legendre.js'); + +module.exports = SphericalCoord; + +function SphericalCoord(options){ + this.lambda = options.lambda; // longitude + this.phig = options.phig; // geocentric latitude + this.r = options.r; // distance from center of ellipsoid +} + +SphericalCoord.prototype.toCartesian = function(){ + var radphi = this.phig * Math.PI/180; + var radlambda = this.lambda * Math.PI/180; + return new CartesianCoord({ + x: this.r * cos(radphi) * cos(radlambda), + y: this.r * cos(radphi) * sin(radlambda), + z: this.r * sin(radphi) + }); +}; + +SphericalCoord.prototype.toGeodetic = function(ellipsoid){ + return this.toCartesian().toGeodetic(ellipsoid); +}; + +SphericalCoord.prototype.getHarmonicVariables = function(ellipsoid, n_max){ + var m, n; + var cos_lambda = Math.cos(Math.PI/180 * this.lambda); + var sin_lambda = Math.sin(Math.PI/180 * this.lambda); + + var cos_mlambda = [1.0, cos_lambda]; + var sin_mlambda = [0.0, sin_lambda]; + var relative_radius_power = [ + (ellipsoid.re/this.r) * (ellipsoid.re/this.r) + ]; + + for(n = 1; n <= n_max; n++){ + relative_radius_power[n] = relative_radius_power[n-1] * (ellipsoid.re/this.r); + } + for(m = 2; m <= n_max; m++){ + cos_mlambda[m] = cos_mlambda[m-1]*cos_lambda - sin_mlambda[m-1]*sin_lambda; + sin_mlambda[m] = cos_mlambda[m-1]*sin_lambda + sin_mlambda[m-1]*cos_lambda; + } + + return { + relative_radius_power: relative_radius_power, + cos_mlambda: cos_mlambda, + sin_mlambda: sin_mlambda + }; +}; + +SphericalCoord.prototype.getLegendreFunction = function(n_max) { + return new LegendreFunction(this, n_max); +}; \ No newline at end of file diff --git a/node_modules/geomagnetism/lib/ellipsoid.js b/node_modules/geomagnetism/lib/ellipsoid.js new file mode 100644 index 0000000..72b8cf9 --- /dev/null +++ b/node_modules/geomagnetism/lib/ellipsoid.js @@ -0,0 +1,17 @@ +module.exports = Ellipsoid; + +function Ellipsoid(options) { + options = options || { + a: 6378.137, + b: 6356.7523142, + fla: 1 / 298.257223563, + re: 6371.2 + }; + + this.a = options.a; // semi-major axis + this.b = options.b; // semi-minor axis + this.fla = options.fla; // flattening + this.re = options.re; // mean radius + this.eps = Math.sqrt(1-(this.b*this.b)/(this.a*this.a)); // first eccentricity + this.epssq = this.eps*this.eps; // first eccentricity squared +} \ No newline at end of file diff --git a/node_modules/geomagnetism/lib/legendre.js b/node_modules/geomagnetism/lib/legendre.js new file mode 100644 index 0000000..3b7d75c --- /dev/null +++ b/node_modules/geomagnetism/lib/legendre.js @@ -0,0 +1,168 @@ +module.exports = LegendreFunction; + +function LegendreFunction(coord_spherical, n_max){ + var sin_phi = Math.sin(Math.PI/180 * coord_spherical.phig); + var result; + if(n_max <= 16 || (1 - Math.abs(sin_phi)) < 1e-10){ + result = PcupLow(sin_phi, n_max); + } else { + result = PcupHigh(sin_phi, n_max); + } + this.pcup = result.pcup; + this.dpcup = result.dpcup; +} + +function PcupLow(x, n_max){ + var k, z, n, m, i, i1, i2, num_terms; + var schmidt_quasi_norm = [1.0]; + var pcup = [1.0]; + var dpcup = [0.0]; + + z = Math.sqrt((1-x)*(1+x)); + num_terms = (n_max+1) * (n_max+2) / 2; + + + for(n = 1; n <= n_max; n++) { + for(m = 0; m <= n; m++) { + i = n*(n+1)/2 + m; + if(n == m){ + i1 = (n-1)*n/2 + m - 1; + pcup[i] = z*pcup[i1]; + dpcup[i] = z*dpcup[i1] + x*pcup[i1]; + } else if (n == 1 && m == 0) { + i1 = (n-1)*n/2 + m; + pcup[i] = x*pcup[i1]; + dpcup[i] = x*dpcup[i1] - z*pcup[i1]; + } else if (n > 1 && n != m) { + i1 = (n-2)*(n-1)/2 + m; + i2 = (n-1)*n/2 + m; + if(m > n - 2){ + pcup[i] = x*pcup[i2]; + dpcup[i] = x*dpcup[i2] - z*pcup[i2]; + } else { + k = ((n-1)*(n-1) - m*m) / ((2*n-1)*(2*n-3)); + pcup[i] = x*pcup[i2] - k*pcup[i1]; + dpcup[i] = x*dpcup[i2] - z*pcup[i2] - k*dpcup[i1]; + } + } + } + } + + for(n = 1; n <= n_max; n++) { + i = n*(n+1)/2; + i1 = (n-1)*n/2; + schmidt_quasi_norm[i] = schmidt_quasi_norm[i1] * (2*n-1) / n; + for(m = 1; m <= n; m++){ + i = n*(n+1)/2 + m; + i1 = n*(n+1)/2 + m - 1; + schmidt_quasi_norm[i] = schmidt_quasi_norm[i1] * Math.sqrt(((n - m + 1) * (m == 1 ? 2 : 1)) / (n + m)); + } + } + + for(n = 1; n <= n_max; n++) { + for(m = 0; m <= n; m++) { + i = n*(n+1)/2+m; + pcup[i] *= schmidt_quasi_norm[i]; + dpcup[i] *= -schmidt_quasi_norm[i]; + } + } + + return { + pcup: pcup, + dpcup: dpcup + }; +} + +function PcupHigh(x, n_max){ + if(Math.abs(x) == 1.0){ + throw new Error("Error in PcupHigh: derivative cannot be calculated at poles"); + } + + var n, m, k; + var num_terms = (n_max + 1) * (n_max + 2)/2; + var f1 = []; + var f2 = []; + var pre_sqr = []; + var scalef = 1.0e-280; + + for(n = 0; n <= 2*n_max + 1; ++n){ + pre_sqr[n] = Math.sqrt(n); + } + + k = 2; + for(n = 0; n <= n_max; n++){ + k++; + f1[k] = (2*n - 1) / n; + f2[k] = (n - 1) / n; + for(m = 1; m <= n - 2; m++){ + k++; + f1[k] = (2*n - 1) / pre_sqr[n+m] / pre_sqr[n-m]; + f2[k] = pre_sqr[n-m-1] * pre_sqr[n+m-1] / pre_sqr[n+m] / pre_sqr[n-m]; + } + k += 2; + } + + var z = Math.sqrt((1-x)*(1+x)); + var plm; + var pm1 = x; + var pm2 = 1; + var pcup = [1.0, pm1]; + var dpcup = [0.0, z]; + if(n_max == 0){ + throw new Error("Error in PcupHigh: n_max must be greater than 0"); + } + + k = 1; + for(n = 2; n <= n_max; n++) + { + k = k + n; + plm = f1[k] * x * pm1 - f2[k] * pm2; + pcup[k] = plm; + dpcup[k] = n * (pm1 - x * plm) / z; + pm2 = pm1; + pm1 = plm; + } + + var pmm = pre_sqr[2] * scalef; + var rescalem = 1/scalef; + var kstart = 0; + + for(var m = 1; m <= n_max - 1; ++m){ + rescalem *= z; + + //calculate pcup(m,m) + kstart = kstart + m + 1; + pmm = pmm * pre_sqr[2*m+1] / pre_sqr[2*m]; + pcup[kstart] = pmm * rescalem / pre_sqr[2*m+1]; + dpcup[kstart] = -( m*x*pcup[kstart] /z ); + pm2 = pmm / pre_sqr[2*m + 1]; + + //calculate pcup(m+1,m) + k = kstart + m + 1; + pm1 = x * pre_sqr[2*m+1] * pm2; + pcup[k] = pm1*rescalem; + dpcup[k] = (pm2*rescalem *pre_sqr[2*m+1] - x*(m+1)*pcup[k]) / z; + + //calculate pcup(n,m) + for(n = m + 2; n <= n_max; ++n){ + k = k + n; + plm = x*f1[k]*pm1 - f2[k]*pm2; + pcup[k] = plm*rescalem; + dpcup[k] = (pre_sqr[n+m]*pre_sqr[n-m]*pm1*rescalem - n*x*pcup[k]) / z; + pm2 = pm1; + pm1 = plm; + } + } + + //calculate pcup(n_max,n_max) + rescalem = rescalem*z; + kstart = kstart + m + 1; + pmm = pmm / pre_sqr[2*n_max]; + pcup[kstart] = pmm * rescalem; + dpcup[kstart] = -n_max * x * pcup[kstart] / z; + + return { + pcup: pcup, + dpcup: dpcup + }; +} diff --git a/node_modules/geomagnetism/lib/magnetic_elements.js b/node_modules/geomagnetism/lib/magnetic_elements.js new file mode 100644 index 0000000..b6ff106 --- /dev/null +++ b/node_modules/geomagnetism/lib/magnetic_elements.js @@ -0,0 +1,98 @@ +module.exports = MagneticElements; + +function MagneticElements(options){ + this.x = options.x; + this.y = options.y; + this.z = options.z; + this.h = options.h; + this.f = options.f; + this.incl = options.incl; + this.decl = options.decl; + this.gv = options.gv; + this.xdot = options.xdot; + this.ydot = options.ydot; + this.zdot = options.zdot; + this.hdot = options.hdot; + this.fdot = options.fdot; + this.incldot = options.incldot; + this.decldot = options.decldot; + this.gvdot = options.gvdot; +} + +MagneticElements.prototype.clone = function(){ + return new MagneticElements(this); +}; + +MagneticElements.prototype.scale = function(factor){ + return new MagneticElements({ + x : this.x * factor, + y : this.y * factor, + z : this.z * factor, + h : this.h * factor, + f : this.f * factor, + incl : this.incl * factor, + decl : this.decl * factor, + gv : this.gv * factor, + xdot : this.xdot * factor, + ydot : this.ydot * factor, + zdot : this.zdot * factor, + hdot : this.hdot * factor, + fdot : this.fdot * factor, + incldot : this.incldot * factor, + decldot : this.decldot * factor, + gvdot : this.gvdot * factor + }); +}; + +MagneticElements.prototype.subtract = function(subtrahend){ + return new MagneticElements({ + x : this.x - subtrahend.x, + y : this.y - subtrahend.y, + z : this.z - subtrahend.z, + h : this.h - subtrahend.h, + f : this.f - subtrahend.f, + incl : this.incl - subtrahend.incl, + decl : this.decl - subtrahend.decl, + gv : this.gv - subtrahend.gv, + xdot : this.xdot - subtrahend.xdot, + ydot : this.ydot - subtrahend.ydot, + zdot : this.zdot - subtrahend.zdot, + hdot : this.hdot - subtrahend.hdot, + fdot : this.fdot - subtrahend.fdot, + incldot : this.incldot - subtrahend.incldot, + decldot : this.decldot - subtrahend.decldot, + gvdot : this.gvdot - subtrahend.gvdot + }); +}; + +MagneticElements.fromGeoMagneticVector = function(magnetic_vector){ + var bx = magnetic_vector.bx; + var by = magnetic_vector.by; + var bz = magnetic_vector.bz; + var h = Math.sqrt(bx*bx + by*by); + return new MagneticElements({ + x: bx, + y: by, + z: bz, + h: h, + f: Math.sqrt(h*h + bz*bz), + decl: 180/Math.PI * Math.atan2(by, bx), + incl: 180/Math.PI * Math.atan2(bz, h) + }); +}; + +MagneticElements.fromSecularVariationVector = function(magnetic_variation){ + var bx = magnetic_variation.bx; + var by = magnetic_variation.by; + var bz = magnetic_variation.bz; + return new MagneticElements({ + xdot: bx, + ydot: by, + zdot: bz, + hdot: (this.x*bx + this.y*by) / this.h, + fdot: (this.x*bx + this.y*by + this.z*bz) / this.f, + decldot: 180/Math.PI * (this.x*this.ydot - this.y*this.xdot) / (this.h*this.h), + incldot: 180/Math.PI * (this.h*this.zdot - this.z*this.hdot) / (this.f*this.f), + gvdot: this.decldot + }); +}; \ No newline at end of file diff --git a/node_modules/geomagnetism/lib/magnetic_vector.js b/node_modules/geomagnetism/lib/magnetic_vector.js new file mode 100644 index 0000000..c07b065 --- /dev/null +++ b/node_modules/geomagnetism/lib/magnetic_vector.js @@ -0,0 +1,16 @@ +module.exports = MagneticVector; + +function MagneticVector(options){ + this.bx = options.bx; + this.by = options.by; + this.bz = options.bz; +} + +MagneticVector.prototype.rotate = function(coord_spherical, coord_geodetic) { + var psi = Math.PI/180 * (coord_spherical.phig - coord_geodetic.phi); + return new MagneticVector({ + bz: this.bx*Math.sin(psi) + this.bz*Math.cos(psi), + bx: this.bx*Math.cos(psi) - this.bz*Math.sin(psi), + by: this.by + }); +}; \ No newline at end of file diff --git a/node_modules/geomagnetism/lib/model.js b/node_modules/geomagnetism/lib/model.js new file mode 100644 index 0000000..a4b1e9e --- /dev/null +++ b/node_modules/geomagnetism/lib/model.js @@ -0,0 +1,140 @@ +var GeodeticCoord = require('./coords/geodetic.js'); +var MagneticElements = require('./magnetic_elements.js'); +var MagneticVector = require('./magnetic_vector.js'); + +module.exports = Model; + +function Model(options){ + this.epoch = options.epoch; + this.start_date = new Date(options.start_date); + this.end_date = new Date(options.end_date); + this.name = options.name || ""; + this.main_field_coeff_g = options.main_field_coeff_g || [0]; + this.main_field_coeff_h = options.main_field_coeff_h || [0]; + this.secular_var_coeff_g = options.secular_var_coeff_g || [0]; + this.secular_var_coeff_h = options.secular_var_coeff_h || [0]; + this.n_max = options.n_max || 0; + this.n_max_sec_var = options.n_max_sec_var || 0; + this.num_terms = this.n_max*(this.n_max+1)/2 + this.n_max; +} + +Model.prototype.getTimedModel = function(date, allowOutOfBoundsModel = false){ + var year_int = date.getUTCFullYear(); + var fractional_year = (date.valueOf() - Date.UTC(year_int)) / (1000*3600*24*365); + var year = year_int + fractional_year; + var dyear = year - this.epoch; + + if(date < this.start_date || date > this.end_date){ + if(allowOutOfBoundsModel) { + console.error("Model is only valid from "+this.start_date.toDateString()+" to "+this.end_date.toDateString()); + } else { + throw new Error("Model is only valid from "+this.start_date.toDateString()+" to "+this.end_date.toDateString()); + } + } + + var model = new Model({ + epoch: this.epoch, + n_max: this.n_max, + n_max_sec_var: this.n_max_sec_var, + name: this.name, + start_date: this.start_date, + end_date: this.end_date, + }); + var a = model.n_max_sec_var; + var b = a*(a + 1)/2 + a; + for(var n = 1; n <= this.n_max; n++){ + for(var m = 0; m <= n; m++){ + var i = n * (n + 1)/2 + m; + var hnm = this.main_field_coeff_h[i]; + var gnm = this.main_field_coeff_g[i]; + var dhnm = this.secular_var_coeff_h[i]; + var dgnm = this.secular_var_coeff_g[i]; + if(i <= b){ + model.main_field_coeff_h[i] = hnm + dyear*dhnm; + model.main_field_coeff_g[i] = gnm + dyear*dgnm; + model.secular_var_coeff_h[i] = dhnm; + model.secular_var_coeff_g[i] = dgnm; + } else { + model.main_field_coeff_h[i] = hnm; + model.main_field_coeff_g[i] = gnm; + } + } + } + return model; +}; + +Model.prototype.getSummation = function(legendre, sph_variables, coord_spherical){ + var bx = 0; + var by = 0; + var bz = 0; + var n, m, i, k; + var relative_radius_power = sph_variables.relative_radius_power; + var cos_mlambda = sph_variables.cos_mlambda; + var sin_mlambda = sph_variables.sin_mlambda; + var g = this.main_field_coeff_g; + var h = this.main_field_coeff_h; + + for(n = 1; n <= this.n_max; n++){ + for(m = 0; m <= n; m++){ + i = n*(n+1)/2 + m; + bz -= relative_radius_power[n] * + (g[i]*cos_mlambda[m] + h[i]*sin_mlambda[m]) * + (n+1) * legendre.pcup[i]; + by += relative_radius_power[n] * + (g[i]*sin_mlambda[m] - h[i]*cos_mlambda[m]) * + (m) * legendre.pcup[i]; + bx -= relative_radius_power[n] * + (g[i]*cos_mlambda[m] + h[i]*sin_mlambda[m]) * + legendre.dpcup[i]; + } + } + var cos_phi = Math.cos(Math.PI/180 * coord_spherical.phig); + if(Math.abs(cos_phi) > 1e-10){ + by = by / cos_phi; + } else { + //special calculation around poles + by = 0; + var schmidt_quasi_norm1 = 1.0, schmidt_quasi_norm2, schmidt_quasi_norm3; + var pcup_s = [1]; + var sin_phi = Math.sin(Math.PI/180 * coord_spherical.phig); + + for(n = 1; n <= this.n_max; n++){ + i = n*(n+1)/2 + 1; + schmidt_quasi_norm2 = schmidt_quasi_norm1 * (2*n-1) / n; + schmidt_quasi_norm3 = schmidt_quasi_norm2 * Math.sqrt(2*n/(n+1)); + schmidt_quasi_norm1 = schmidt_quasi_norm2; + if(n == 1){ + pcup_s[n] = pcup_s[n-1]; + } else { + k = ((n-1)*(n-1) - 1) / ((2*n-1)*(2*n-3)); + pcup_s[n] = sin_phi * pcup_s[n-1] - k*pcup_s[n-2]; + } + by += relative_radius_power[n] * + (g[i]*sin_mlambda[1] - h[i]*cos_mlambda[1]) * + pcup_s[n] * schmidt_quasi_norm3; + } + } + return new MagneticVector({ + bx: bx, by: by, bz: bz + }); +}; + +Model.prototype.point = function(coords) { + // Extract altitude if provided, otherwise default to 0 + var altitude = (coords.length > 2 && typeof coords[2] === 'number') ? coords[2] : 0; + + var coord_geodetic = new GeodeticCoord({ + lat: coords[0], + lon: coords[1], + height_above_ellipsoid: altitude + }); + var coord_spherical = coord_geodetic.toSpherical(); + + var legendre = coord_spherical.getLegendreFunction(this.n_max); + var harmonic_variables = coord_spherical.getHarmonicVariables(coord_geodetic.ellipsoid, this.n_max); + + var magnetic_vector_sph = this.getSummation(legendre, harmonic_variables, coord_spherical); + var magnetic_vector_geo = magnetic_vector_sph.rotate(coord_spherical, coord_geodetic); + + return MagneticElements.fromGeoMagneticVector(magnetic_vector_geo); +}; diff --git a/node_modules/geomagnetism/lib/parsers/cof.js b/node_modules/geomagnetism/lib/parsers/cof.js new file mode 100644 index 0000000..a21af47 --- /dev/null +++ b/node_modules/geomagnetism/lib/parsers/cof.js @@ -0,0 +1,40 @@ +module.exports = function(str){ + var result = { + main_field_coeff_g: [0], + main_field_coeff_h: [0], + secular_var_coeff_g: [0], + secular_var_coeff_h: [0], + n_max: 0, + n_max_sec_var: 0 + }; + var lines = str.split(/\r?\n/); + for(var i = 0; i < lines.length; i++) { + var line = lines[i]; + var vals = line.match(/\S+/g); + if(!vals) continue; + if(vals.length === 3){ + result.epoch = parseFloat(vals[0]); + result.name = vals[1]; + result.start_date = new Date(vals[2]); + result.end_date = new Date(vals[2]); + var year = result.start_date.getFullYear(); + result.end_date.setFullYear(year + 5); + } + if(vals.length === 6){ + var n = parseInt(vals[0]); + var m = parseInt(vals[1]); + if(m <= n) { + var i = (n*(n+1)/2+m); + result.main_field_coeff_g[i] = parseFloat(vals[2]); + result.main_field_coeff_h[i] = parseFloat(vals[3]); + result.secular_var_coeff_g[i] = parseFloat(vals[4]); + result.secular_var_coeff_h[i] = parseFloat(vals[5]); + } + if(n > result.n_max){ + result.n_max = n; + result.n_max_sec_var = n; + } + } + } + return result; +}; \ No newline at end of file diff --git a/node_modules/geomagnetism/package.json b/node_modules/geomagnetism/package.json new file mode 100644 index 0000000..9e7fc1d --- /dev/null +++ b/node_modules/geomagnetism/package.json @@ -0,0 +1,34 @@ +{ + "name": "geomagnetism", + "types": "geomagnetism.d.ts", + "version": "0.2.0", + "description": "Computes geomagnetic field information", + "main": "index.js", + "scripts": { + "test": "mocha test", + "test-ci": "mocha -R tap" + }, + "repository": { + "type": "git", + "url": "https://github.com/naturalatlas/geomagnetism.git" + }, + "keywords": [ + "geomag", + "geomagnetic", + "magnetic", + "field", + "north", + "declination", + "wmm" + ], + "devDependencies": { + "mocha": "~5.x", + "chai": "~4.2.0" + }, + "author": "Brandon Reavis", + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/naturalatlas/geomagnetism/issues" + }, + "homepage": "https://github.com/naturalatlas/geomagnetism" +} diff --git a/node_modules/geomagnetism/test/model.test.js b/node_modules/geomagnetism/test/model.test.js new file mode 100644 index 0000000..589c972 --- /dev/null +++ b/node_modules/geomagnetism/test/model.test.js @@ -0,0 +1,96 @@ +var geomagnetism = require('../index.js'); +var assert = require('chai').assert; +var fs = require('fs'); + +var tolerances = { + incl: 0.01, //deg + decl: 0.01, //deg + x: 5, //nT + y: 5, //nT + z: 5, //nT + h: 5, //nT + f: 5 //nT +}; + +function loadTestValues(){ + var str = fs.readFileSync(__dirname + '/values.csv', {encoding: 'utf8'}); + var lines = str.split(/\r?\n/); + var header = lines[0].split(','); + var values = []; + for(var i = 1; i < lines.length; i++){ + var l = lines[i].split(','); + var v = {}; + for(var j = 0; j < header.length; j++){ + v[header[j]] = parseFloat(l[j]); + } + values.push(v); + } + return values; +} + +function getModel(test){ + var t0, t1; + var year = test.date; + var year_int = Math.floor(year); + var year_fpart = year - year_int; + var dms = 1000*3600*24*365*year_fpart; + + t0 = new Date(year_int, 0, 1); + t1 = new Date(t0.valueOf() + dms); + + return geomagnetism.model(t1); +} + +var values = loadTestValues(); + +describe("model", function(){ + describe("point()", function(){ + it("should return expected values", function(){ + values.forEach(function(test){ + var model = getModel(test); + var info = model.point([test.lat, test.lon, test.alt]); + assert.closeTo(info.incl, test.incl, tolerances.incl, 'inclination ' + test.date); + assert.closeTo(info.decl, test.decl, tolerances.decl, 'declination ' + test.date); + assert.closeTo(info.x, test.x, tolerances.x, 'x'); + assert.closeTo(info.y, test.y, tolerances.y, 'y'); + assert.closeTo(info.z, test.z, tolerances.z, 'z'); + assert.closeTo(info.h, test.h, tolerances.h, 'h'); + assert.closeTo(info.f, test.f, tolerances.f, 'f'); + }); + }); + it("should return value for current date", function(){ + var date = new Date(); + geomagnetism.model(date).point([44.53461, -109.05572]); + }); + it("should return value for current date + 1 year", function(){ + var date = new Date(); + date.setFullYear(date.getFullYear() + 1); + geomagnetism.model(date).point([44.53461, -109.05572]); + }); + }); + describe("getTimedModel()", function(){ + it("should throw error if date is outside of valid range and allowOutOfBoundsModel is false", function(){ + assert.throws(function(){ + geomagnetism.model(new Date("1/1/1999")); + }, Error); + }); + it("should log error if date is outside of valid range below and allowOutOfBoundsModel is true", function(){ + var model = geomagnetism.model(new Date("1/1/1999"), { allowOutOfBoundsModel: true }); + assert.equal(model.start_date.getFullYear(), 2014); + }); + it("should log error if date is outside of valid range above and allowOutOfBoundsModel is true", function(){ + var model = geomagnetism.model(new Date("1/1/2030"), { allowOutOfBoundsModel: true }); + assert.equal(model.start_date.getFullYear(), 2024); + }); + it("should get a different model for a different date", function(){ + var pt = [44.53461, -109.05572]; + var model0 = geomagnetism.model(); + var model1 = geomagnetism.model(new Date("3/22/2018")); + var decl0 = model0.point(pt).decl; + var decl1 = model1.point(pt).decl; + assert.notEqual(model0, model1); + assert(Math.abs(decl1 - decl0) > 0.001, 'declination should be different'); + }); + + }); +}); diff --git a/node_modules/geomagnetism/test/values.csv b/node_modules/geomagnetism/test/values.csv new file mode 100644 index 0000000..da5b9e8 --- /dev/null +++ b/node_modules/geomagnetism/test/values.csv @@ -0,0 +1,214 @@ +date,alt,lat,lon,x,y,z,h,f,incl,decl,gv +2015.0,0,80,0,6627.1,-445.9,54432.3,6642.1,54836.0,83.04,-3.85,-3.85 +2015.0,0,0,120,39518.2,392.9,-11252.4,39520.2,41090.9,-15.89,0.57,0.57 +2015.0,0,-80,240,5797.3,15761.1,-52919.1,16793.5,55519.8,-72.39,69.81,309.81 +2015.0,100,80,0,6314.3,-471.6,52269.8,6331.9,52652.0,83.09,-4.27,-4.27 +2015.0,100,0,120,37535.6,364.4,-10773.4,37537.3,39052.7,-16.01,0.56,0.56 +2015.0,100,-80,240,5613.1,14791.5,-50378.6,15820.7,52804.4,-72.57,69.22,309.22 +2017.5,0,80,0,6599.4,-317.1,54459.2,6607.0,54858.5,83.08,-2.75,-2.75 +2017.5,0,0,120,39571.4,222.5,-11030.1,39572.0,41080.5,-15.57,0.32,0.32 +2017.5,0,-80,240,5873.8,15781.4,-52687.9,16839.1,55313.4,-72.28,69.58,309.58 +2017.5,100,80,0,6290.5,-348.5,52292.7,6300.1,52670.9,83.13,-3.17,-3.17 +2017.5,100,0,120,37585.5,209.5,-10564.2,37586.1,39042.5,-15.70,0.32,0.32 +2017.5,100,-80,240,5683.5,14808.8,-50163.0,15862.0,52611.1,-72.45,69.00,309.00 +2015.21096,0,44.5364,-109.0461,18702.1,3663.7,50812.2,19057.5,54268.5,69.44104,11.08386,0 +2020.0,28,89,-121,-575.7,-1396.0,56082.3,1510.0,56102.7,88.46,-112.41,0 +2020.0,48,80,-96,1518.0,-1160.5,55671.9,1910.8,55704.7,88.03,-37.40,0 +2020.0,54,82,87,1555.6,1941.4,56520.5,2487.8,56575.2,87.48,51.30,0 +2020.0,65,43,93,24375.3,303.2,49691.4,24377.2,55348.7,63.87,0.71,0 +2020.0,51,-33,109,21556.3,-2183.2,-52676.0,21666.6,56957.9,-67.64,-5.78,0 +2020.0,39,-59,-8,14369.9,-4063.3,-24679.0,14933.4,28845.4,-58.82,-15.79,0 +2020.0,3,-50,-103,19684.4,10512.2,-31883.6,22315.5,38917.2,-55.01,28.10,0 +2020.0,94,-29,-110,23467.8,6650.9,-19320.7,24392.0,31116.9,-38.38,15.82,0 +2020.0,66,14,143,34916.8,70.2,8114.9,34916.9,35847.5,13.08,0.12,0 +2020.0,18,0,21,29311.2,536.0,-14589.0,29316.1,32745.6,-26.46,1.05,0 +2020.5,6,-36,-137,23948.6,8791.9,-32897.6,25511.4,41630.3,-52.21,20.16,0 +2020.5,63,26,81,34737.7,259.2,30023.4,34738.7,45914.9,40.84,0.43,0 +2020.5,69,38,-144,22647.3,5390.0,35831.9,23279.9,42730.3,56.99,13.39,0 +2020.5,50,-70,-133,8943.1,13981.7,-51628.5,16597.2,54230.7,-72.18,57.40,0 +2020.5,8,-52,-75,19571.7,5387.5,-23769.0,20299.7,31257.7,-49.50,15.39,0 +2020.5,8,-66,17,15247.0,-9734.8,-31062.0,18089.7,35945.6,-59.78,-32.56,0 +2020.5,22,-37,140,21429.0,3451.3,-55415.6,21705.2,59514.7,-68.61,9.15,0 +2020.5,40,-12,-129,28773.9,5503.9,-8221.8,29295.6,30427.4,-15.68,10.83,0 +2020.5,44,33,-118,23414.3,4748.3,38184.5,23890.9,45042.6,57.97,11.46,0 +2020.5,50,-81,-67,16087.9,8788.9,-44780.8,18332.1,48387.8,-67.74,28.65,0 +2021.0,74,-57,3,13228.0,-5423.3,-23859.2,14296.6,27814.7,-59.07,-22.29,0 +2021.0,46,-24,-122,26037.0,6501.8,-18297.4,26836.5,32480.6,-34.29,14.02,0 +2021.0,69,23,63,34450.4,646.9,24869.2,34456.5,42493.9,35.82,1.08,0 +2021.0,33,-3,-147,30690.1,5265.7,-1277.4,31138.6,31164.8,-2.35,9.74,0 +2021.0,47,-72,-22,18352.8,-1946.6,-33665.0,18455.7,38392.0,-61.27,-6.05,0 +2021.0,62,-14,99,33213.0,-990.3,-33354.0,33227.7,47080.5,-45.11,-1.71,0 +2021.0,83,86,-46,2408.8,-1796.2,54184.7,3004.8,54268.0,86.83,-36.71,0 +2021.0,82,-64,87,2249.5,-13907.0,-53526.9,14087.8,55349.8,-75.25,-80.81,0 +2021.0,34,-19,43,19327.6,-4933.5,-25969.5,19947.3,32746.2,-52.47,-14.32,0 +2021.0,56,-81,40,9198.0,-15323.4,-45453.8,17872.0,48841.2,-68.54,-59.03,0 +2021.5,14,0,80,39246.6,-2338.9,-12258.0,39316.2,41182.8,-17.32,-3.41,0 +2021.5,12,-82,-68,15995.1,9368.5,-46308.7,18536.8,49880.9,-68.18,30.36,0 +2021.5,44,-46,-42,14159.0,-2889.8,-19762.2,14450.9,24482.1,-53.82,-11.54,0 +2021.5,43,17,52,35896.1,773.7,15885.6,35904.4,39261.7,23.87,1.23,0 +2021.5,64,10,78,39294.0,-1172.2,5088.1,39311.5,39639.4,7.37,-1.71,0 +2021.5,12,33,-145,24301.2,5327.4,32429.3,24878.3,40872.8,52.51,12.36,0 +2021.5,12,-79,115,-9403.6,-8972.3,-58271.0,12997.3,59702.9,-77.43,-136.34,0 +2021.5,14,-33,-114,23592.3,7712.3,-24163.1,24820.9,34640.0,-44.23,18.10,0 +2021.5,19,29,66,32618.0,1215.2,33763.7,32640.6,46961.7,45.97,2.13,0 +2021.5,86,-11,167,32676.0,5828.1,-20299.1,33191.7,38906.8,-31.45,10.11,0 +2022.0,37,-66,-5,16404.3,-5011.2,-28849.5,17152.6,33563.5,-59.27,-16.99,0 +2022.0,67,72,-115,4532.7,1254.7,55923.4,4703.2,56120.8,85.19,15.47,0 +2022.0,44,22,174,28671.0,3294.9,17967.2,28859.7,33995.6,31.91,6.56,0 +2022.0,54,54,178,20624.8,514.8,45076.8,20631.2,49573.8,65.41,1.43,0 +2022.0,57,-43,50,11344.6,-12349.5,-32850.3,16769.3,36883.0,-62.96,-47.43,0 +2022.0,44,-43,-111,20646.1,9330.1,-29747.5,22656.4,37392.8,-52.71,24.32,0 +2022.0,12,-63,178,6292.0,9718.1,-61429.1,11577.2,62510.5,-79.33,57.08,0 +2022.0,38,27,-169,25896.5,3991.3,24097.4,26202.3,35598.4,42.60,8.76,0 +2022.0,61,59,-77,10098.3,-3208.9,54735.3,10595.8,55751.4,79.04,-17.63,0 +2022.0,67,-47,-32,12663.7,-3178.2,-20600.9,13056.5,24389.9,-57.63,-14.09,0 +2022.5,8,62,53,12336.1,4236.6,54498.1,13043.3,56037.2,76.54,18.95,0 +2022.5,77,-68,-7,16604.7,-4741.2,-29908.6,17268.3,34535.8,-60.00,-15.94,0 +2022.5,98,-5,159,33613.6,4601.1,-14426.9,33927.0,36867.1,-23.04,7.79,0 +2022.5,34,-29,-107,23739.9,6662.3,-19023.5,24657.0,31142.6,-37.65,15.68,0 +2022.5,60,27,65,32938.8,1025.8,30561.3,32954.8,44944.6,42.84,1.78,0 +2022.5,73,-72,95,-2661.0,-13095.2,-55423.4,13362.8,57011.5,-76.44,-101.49,0 +2022.5,96,-46,-85,19136.4,6358.2,-21915.4,20165.1,29781.1,-47.38,18.38,0 +2022.5,0,-13,-59,21797.3,-6520.6,-5425.9,22751.7,23389.8,-13.41,-16.65,0 +2022.5,16,66,-178,13804.5,463.2,54055.4,13812.2,55792.1,75.67,1.92,0 +2022.5,72,-87,38,7132.3,-15063.2,-48550.5,16666.4,51331.5,-71.05,-64.66,0 +2023.0,49,20,167,30099.4,2737.4,15301.2,30223.6,33876.1,26.85,5.20,0 +2023.0,71,5,-13,28217.7,-3592.6,-8905.8,28445.5,29807.1,-17.38,-7.26,0 +2023.0,95,14,65,36804.1,-356.8,11616.0,36805.8,38595.3,17.52,-0.56,0 +2023.0,86,-85,-79,12598.0,11248.0,-47331.2,16888.7,50254.0,-70.36,41.76,0 +2023.0,30,-36,-64,17694.8,-1198.1,-14566.5,17735.3,22950.5,-39.40,-3.87,0 +2023.0,75,79,125,2605.8,-676.0,57085.9,2692.1,57149.3,87.30,-14.54,0 +2023.0,21,6,-32,27630.5,-7515.0,-3646.9,28634.3,28865.6,-7.26,-15.22,0 +2023.0,1,-76,-75,16998.9,9958.1,-42873.8,19700.9,47183.6,-65.32,30.36,0 +2023.0,45,-46,-41,13880.3,-2936.1,-19853.0,14187.4,24401.3,-54.45,-11.94,0 +2023.0,11,-22,-21,12752.8,-5710.4,-21372.4,13972.9,25534.7,-56.82,-24.12,0 +2023.5,28,54,-120,14556.6,4230.3,52945.6,15158.8,55072.9,74.02,16.20,0 +2023.5,68,-58,156,7015.1,5987.8,-62459.5,9223.1,63136.8,-81.60,40.48,0 +2023.5,39,-65,-88,18024.0,10347.2,-36415.6,20783.0,41928.8,-60.29,29.86,0 +2023.5,27,-23,81,24811.0,-6176.1,-41759.2,25568.2,48965.0,-58.52,-13.98,0 +2023.5,11,34,0,29033.7,545.3,30807.0,29038.8,42335.9,46.69,1.08,0 +2023.5,72,-62,65,6836.8,-16092.9,-44111.8,17485.0,47450.8,-68.38,-66.98,0 +2023.5,55,86,70,1168.7,2124.7,55750.6,2424.9,55803.4,87.51,61.19,0 +2023.5,59,32,163,28170.0,176.0,26318.3,28170.6,38551.7,43.05,0.36,0 +2023.5,65,48,148,23356.8,-3861.2,43968.0,23673.8,49936.3,61.70,-9.39,0 +2023.5,95,30,28,29663.3,2331.2,28857.6,29754.7,41450.1,44.12,4.49,0 +2024.0,95,-60,-59,18099.3,2821.2,-26193.2,18317.9,31962.9,-55.03,8.86,0 +2024.0,95,-70,42,10615.3,-14769.3,-38293.4,18188.3,42393.4,-64.59,-54.29,0 +2024.0,50,87,-154,80.9,-592.4,55904.6,597.9,55907.8,89.39,-82.22,0 +2024.0,58,32,19,29331.6,2019.5,30329.8,29401.0,42241.2,45.89,3.94,0 +2024.0,57,34,-13,28158.7,-1290.8,29015.5,28188.3,40453.4,45.83,-2.62,0 +2024.0,38,-76,49,8218.0,-16491.7,-44260.7,18425.8,47942.9,-67.40,-63.51,0 +2024.0,49,-50,-179,15431.4,9482.7,-53818.3,18112.2,56784.4,-71.40,31.57,0 +2024.0,90,-55,-171,12918.7,10118.6,-53373.5,16409.7,55839.2,-72.91,38.07,0 +2024.0,41,42,-19,24317.3,-2127.0,36981.3,24410.2,44311.1,56.57,-5.00,0 +2024.0,19,46,-22,22384.7,-2590.4,40713.3,22534.0,46533.4,61.04,-6.60,0 +2024.5,31,13,-132,28046.9,4548.8,17417.2,28413.4,33326.9,31.51,9.21,0 +2024.5,93,-2,158,33858.1,4253.5,-10940.3,34124.3,35835.1,-17.78,7.16,0 +2024.5,51,-76,40,10459.6,-15294.7,-42141.5,18529.2,46035.2,-66.27,-55.63,0 +2024.5,64,22,-132,25808.9,4792.5,25239.1,26250.1,36415.3,43.88,10.52,0 +2024.5,26,-65,55,8607.6,-16603.5,-41366.0,18702.1,45397.3,-65.67,-62.60,0 +2024.5,66,-21,32,15510.7,-3677.9,-24502.7,15940.8,29231.7,-56.95,-13.34,0 +2024.5,18,9,-172,30615.4,5065.5,8768.5,31031.6,32246.7,15.78,9.39,0 +2024.5,63,88,26,2189.6,1254.6,55156.1,2523.6,55213.8,87.38,29.81,0 +2024.5,33,17,5,34060.9,362.9,8230.6,34062.9,35043.1,13.58,0.61,0 +2024.5,77,-18,138,31722.0,2569.6,-34986.2,31825.9,47296.1,-47.71,4.63,0 +2025.000000,28,89,-121,-255.388723,-1482.460628,56194.288771,1504.298146,56214.419888,88.47,-99.77,0 +2025.000000,48,80,-96,1875.982280,-1079.269389,55623.044051,2164.285547,55665.134163,87.77,-29.91,0 +2025.000000,54,82,87,1324.336929,1883.428620,56740.772059,2302.427342,56787.466800,87.68,54.89,0 +2025.000000,65,43,93,24299.852822,210.517066,50037.923998,24300.764692,55626.621348,64.10,0.50,0 +2025.000000,51,-33,109,21737.778822,-2090.274098,-52710.003920,21838.046477,57054.752538,-67.50,-5.49,0 +2025.000000,39,-59,-8,14358.095523,-4049.107540,-24389.086374,14918.115796,28589.818346,-58.55,-15.75,0 +2025.000000,3,-50,-103,19526.532799,10362.990980,-31437.562789,22106.041373,38431.724126,-54.89,27.96,0 +2025.000000,94,-29,-110,23275.471080,6559.046509,-19063.605287,24181.990098,30792.688931,-38.25,15.74,0 +2025.000000,66,14,143,35003.441364,-116.624818,7966.315182,35003.635649,35898.700342,12.82,-0.19,0 +2025.000000,18,0,21,29274.811882,659.800118,-14316.722540,29282.246275,32594.761714,-26.06,1.29,0 +2025.500000,6,-36,-137,23781.930678,8786.698927,-32577.518648,25353.230658,41280.516301,-52.11,20.28,0 +2025.500000,63,26,81,34802.613433,308.431881,30332.056989,34803.980117,46166.554053,41.07,0.51,0 +2025.500000,69,38,-144,22510.804524,5167.636206,35525.990264,23096.337032,42373.774537,56.97,12.93,0 +2025.500000,50,-70,-133,9021.847823,14001.865232,-51084.838301,16656.709403,53731.803175,-71.94,57.21,0 +2025.500000,8,-52,-75,19331.857134,5147.774727,-23532.664273,20005.506364,30886.996822,-49.63,14.91,0 +2025.500000,8,-66,17,15201.438652,-9925.501123,-30881.123197,18154.870136,35822.382382,-59.55,-33.14,0 +2025.500000,22,-37,140,21404.761773,3498.897430,-55397.587760,21688.847590,59492.006517,-68.62,9.28,0 +2025.500000,40,-12,-129,28594.451238,5432.201489,-8052.525092,29105.866326,30199.248583,-15.46,10.76,0 +2025.500000,44,33,-118,23235.835850,4558.379362,37727.715752,23678.743422,44542.826874,57.89,11.10,0 +2025.500000,50,-81,-67,16132.682326,8623.494405,-44412.283868,18292.842720,48032.062762,-67.61,28.13,0 +2026.000000,74,-57,3,13268.119649,-5498.179626,-23576.062921,14362.206593,27606.226129,-58.65,-22.51,0 +2026.000000,46,-24,-122,25846.118652,6448.863284,-18080.399376,26638.500090,32194.883578,-34.17,14.01,0 +2026.000000,69,23,63,34558.605297,708.078839,25043.405885,34565.858527,42684.549360,35.92,1.17,0 +2026.000000,33,-3,-147,30514.086409,5221.840663,-1146.978999,30957.666082,30978.906535,-2.12,9.71,0 +2026.000000,47,-72,-22,18280.800055,-2024.105320,-33397.486160,18392.516222,38127.112857,-61.16,-6.32,0 +2026.000000,62,-14,99,33437.828630,-835.919473,-33100.922253,33448.275663,47058.030120,-44.70,-1.43,0 +2026.000000,83,86,-46,2582.099403,-1527.839829,54279.308437,3000.255301,54362.163830,86.84,-30.61,0 +2026.000000,82,-64,87,2007.074870,-13829.362571,-53663.514288,13974.248411,55453.154865,-75.40,-81.74,0 +2026.000000,34,-19,43,19525.694050,-5224.017527,-26182.862330,20212.448819,33076.961273,-52.33,-14.98,0 +2026.000000,56,-81,40,9000.536024,-15446.900890,-45267.890393,17877.818542,48670.301997,-68.45,-59.77,0 +2026.500000,14,0,80,39431.415992,-2133.456168,-12188.838466,39489.089663,41327.424134,-17.15,-3.10,0 +2026.500000,12,-82,-68,16052.819558,9190.416754,-45940.146795,18497.480257,49524.275496,-68.07,29.79,0 +2026.500000,44,-46,-42,13863.176808,-2785.834358,-19744.304022,14140.316272,24285.511845,-54.39,-11.36,0 +2026.500000,43,17,52,35994.907968,747.876551,15990.895993,36002.676553,39394.180708,23.95,1.19,0 +2026.500000,64,10,78,39427.724480,-1049.971869,5214.811025,39441.702532,39784.948821,7.53,-1.53,0 +2026.500000,12,33,-145,24136.839639,5112.225422,32162.934508,24672.289649,40536.110231,52.51,11.96,0 +2026.500000,12,-79,115,-9613.650418,-8785.714482,-58104.306533,13023.480845,59545.961164,-77.37,-137.58,0 +2026.500000,14,-33,-114,23393.133584,7653.110952,-23854.293436,24613.183584,34275.882505,-44.10,18.12,0 +2026.500000,19,29,66,32725.000691,1278.343380,33958.454002,32749.959268,47177.711160,46.04,2.24,0 +2026.500000,86,-11,167,32578.377044,5882.794932,-20368.224196,33105.255278,38869.300019,-31.60,10.24,0 +2027.000000,37,-66,-5,16390.771268,-5079.626554,-28608.243575,17159.836500,33360.029814,-59.04,-17.22,0 +2027.000000,67,72,-115,4883.287833,1192.857435,55689.615237,5026.868699,55916.032175,84.84,13.73,0 +2027.000000,44,22,174,28683.972510,3249.857362,17961.198575,28867.487799,33999.066253,31.89,6.46,0 +2027.000000,54,54,178,20615.871559,225.041793,45149.631876,20617.099795,49634.202547,65.46,0.63,0 +2027.000000,57,-43,50,11203.748204,-12563.437494,-33221.366617,16833.417225,37242.759503,-63.13,-48.27,0 +2027.000000,44,-43,-111,20471.522067,9245.505620,-29347.556906,22462.470699,36957.295441,-52.57,24.31,0 +2027.000000,12,-63,178,6233.774935,9925.455386,-61075.730989,11720.691727,62190.188377,-79.14,57.87,0 +2027.000000,38,27,-169,25821.061601,3851.701313,24058.365347,26106.758229,35501.658671,42.66,8.48,0 +2027.000000,61,59,-77,10437.775689,-3087.391846,54397.713552,10884.812802,55476.034370,78.68,-16.48,0 +2027.000000,67,-47,-32,12450.832543,-2994.148743,-20475.298079,12805.786103,24150.072239,-57.98,-13.52,0 +2027.500000,8,62,53,12260.425578,4315.497527,54849.810218,12997.751893,56368.814385,76.67,19.39,0 +2027.500000,77,-68,-7,16578.099495,-4813.676173,-29680.383821,17262.817301,34335.550744,-59.82,-16.19,0 +2027.500000,98,-5,159,33544.960996,4589.735713,-14525.780052,33857.496691,36841.937629,-23.22,7.79,0 +2027.500000,34,-29,-107,23540.396213,6592.363667,-18723.097084,24446.053109,30792.269761,-37.45,15.64,0 +2027.500000,60,27,65,33062.159421,1068.555172,30667.425573,33079.422542,45108.083389,42.83,1.85,0 +2027.500000,73,-72,95,-2912.418045,-12984.118939,-55399.217725,13306.747292,56974.931751,-76.49,-102.64,0 +2027.500000,96,-46,-85,18947.658009,6129.590452,-21631.434316,19914.457641,29402.458634,-47.37,17.93,0 +2027.500000,0,-13,-59,21365.849306,-6732.560620,-6112.313520,22401.493010,23220.406233,-15.26,-17.49,0 +2027.500000,16,66,-178,13821.326215,89.244328,54092.646409,13821.614337,55830.559897,75.67,0.37,0 +2027.500000,72,-87,38,6926.051596,-15153.941754,-48295.635435,16661.696834,51088.947370,-70.97,-65.44,0 +2028.000000,49,20,167,30131.436134,2689.876669,15295.611788,30251.262453,33898.298187,26.82,5.10,0 +2028.000000,71,5,-13,28142.647915,-3192.970202,-9017.928693,28323.200567,29724.177504,-17.66,-6.47,0 +2028.000000,95,14,65,36932.466767,-329.910612,11601.180703,36933.940251,38713.089985,17.44,-0.51,0 +2028.000000,86,-85,-79,12713.115116,11085.480728,-46988.258092,16867.459172,49924.018042,-70.25,41.09,0 +2028.000000,30,-36,-64,17341.333537,-1411.102609,-14639.967305,17398.651081,22738.551012,-40.08,-4.65,0 +2028.000000,75,79,125,2447.595900,-823.235047,57308.751756,2582.332595,57366.902212,87.42,-18.59,0 +2028.000000,21,6,-32,27567.094260,-7045.034525,-4352.046687,28453.070088,28783.980055,-8.70,-14.34,0 +2028.000000,1,-76,-75,16993.742946,9761.147808,-42479.847250,19597.635210,46782.525885,-65.23,29.87,0 +2028.000000,45,-46,-41,13609.973828,-2812.623735,-19816.196211,13897.562372,24203.798713,-54.96,-11.68,0 +2028.000000,11,-22,-21,12430.606447,-5337.987778,-21373.837958,13528.270036,25295.356080,-57.67,-23.24,0 +2028.500000,28,54,-120,14735.145798,4066.959949,52393.678137,15286.094495,54578.037650,73.74,15.43,0 +2028.500000,68,-58,156,6944.959164,6159.591995,-62264.415929,9282.943032,62952.605366,-81.52,41.57,0 +2028.500000,39,-65,-88,17946.905687,10131.662696,-35982.872979,20609.270068,41466.964689,-60.20,29.45,0 +2028.500000,27,-23,81,24940.672257,-5883.907569,-41948.733657,25625.329284,49156.421313,-58.58,-13.27,0 +2028.500000,11,34,0,29078.234597,798.434048,30945.577813,29089.194286,42471.284539,46.77,1.57,0 +2028.500000,72,-62,65,6567.891205,-16150.440331,-44267.327811,17434.847799,47576.992646,-68.50,-67.87,0 +2028.500000,55,86,70,901.741754,2192.139033,55926.154052,2370.361097,55976.363930,87.57,67.64,0 +2028.500000,59,32,163,28217.104175,75.200106,26405.862611,28217.204381,38645.571587,43.10,0.15,0 +2028.500000,65,48,148,23365.167010,-3931.047029,44177.553125,23693.546804,50130.233993,61.79,-9.55,0 +2028.500000,95,30,28,29692.133298,2367.965026,29039.808439,29786.406936,41599.765773,44.27,4.56,0 +2029.000000,95,-60,-59,17893.018948,2700.105868,-26011.845842,18095.598879,31687.013474,-55.17,8.58,0 +2029.000000,95,-70,42,10426.249753,-14920.796381,-38237.047006,18202.660480,42348.655378,-64.54,-55.06,0 +2029.000000,50,87,-154,257.877420,-869.484879,55992.308183,906.920459,55999.652503,89.07,-73.48,0 +2029.000000,58,32,19,29359.395781,2108.188210,30508.465542,29434.989012,42393.219362,46.03,4.11,0 +2029.000000,57,34,-13,28241.863242,-933.225495,28997.458189,28257.277809,40488.595068,45.74,-1.89,0 +2029.000000,38,-76,49,7991.121323,-16588.167977,-44151.303941,18412.640681,47836.837024,-67.36,-64.28,0 +2029.000000,49,-50,-179,15315.042731,9610.272521,-53522.651338,18080.593790,56494.088877,-71.33,32.11,0 +2029.000000,90,-55,-171,12821.507915,10252.398258,-52995.143972,16416.538468,55479.618058,-72.79,38.65,0 +2029.000000,41,42,-19,24439.977735,-1762.893879,36929.897501,24503.475397,44319.720622,56.44,-4.13,0 +2029.000000,19,46,-22,22522.142232,-2227.393290,40651.688191,22632.016516,46527.066578,60.89,-5.65,0 +2029.500000,31,13,-132,27795.620707,4421.061344,17187.983590,28145.022897,32978.312476,31.41,9.04,0 +2029.500000,93,-2,158,33806.520595,4207.156292,-10964.647547,34067.301020,35788.329028,-17.84,7.09,0 +2029.500000,51,-76,40,10263.650094,-15412.758102,-42018.541264,18517.441118,45917.898858,-66.22,-56.34,0 +2029.500000,64,22,-132,25601.266218,4619.955329,24914.378368,26014.780783,36020.758857,43.76,10.23,0 +2029.500000,26,-65,55,8347.198524,-16728.868464,-41431.528035,18695.741849,45454.397791,-65.71,-63.48,0 +2029.500000,66,-21,32,15578.335534,-4066.430831,-24494.877642,16100.322907,29312.444941,-56.68,-14.63,0 +2029.500000,18,9,-172,30520.999126,4966.941695,8779.472279,30922.514410,32144.689001,15.85,9.24,0 +2029.500000,63,88,26,2041.140972,1511.567287,55286.620082,2539.900024,55344.931586,87.37,36.52,0 +2029.500000,33,17,5,34021.976056,531.446418,8341.137769,34026.126581,35033.582023,13.77,0.89,0 +2029.500000,77,-18,138,31751.497580,2472.257962,-34817.395113,31847.600506,47186.021876,-47.55,4.45,0 \ No newline at end of file diff --git a/node_modules/satellite.js/BENCHMARK-RESULTS.md b/node_modules/satellite.js/BENCHMARK-RESULTS.md new file mode 100644 index 0000000..37e3a37 --- /dev/null +++ b/node_modules/satellite.js/BENCHMARK-RESULTS.md @@ -0,0 +1,27 @@ +Savage Benchmark (100 runs) Double Precision +-------------------------------------------- +The first four are from [TS Kelso's System Benchmarking column](http://celestrak.com/columns/v02n04/) +The Core i7 is Shashwat Kandadai's personal laptop +``` + Value: Avg Time: +386DX-33 2500.00000000117734 6.81 s 33 MHz : MS-DOS 6.20 +486DX2-66 " 1.26 s 66 MHz : Windows 95 +Pentium 90 " 0.55 s 90 MHz : Windows 95 +Pentium 133 " 0.38 s 133 MHz : Windows 95 +Core i7 2500.0000000025643 0.58 ms 2.0 GHz : Mac OS X +``` + + +Full day propagation results (1440 propagations) +------------------------------------------------- +``` +Honeywell-6000 (from Space-Track Report #3) + init ms prpgtion ms +SGP4 1.9 2.5 +SDP4 5.1 3.6 + +Core i7 (Shashwat Kandadai's personal computer) + init ms prpgtion ms +SGP4 0.074 0.0017 +SDP4 0.092 0.0046 +``` diff --git a/node_modules/satellite.js/CHANGELOG.md b/node_modules/satellite.js/CHANGELOG.md new file mode 100644 index 0000000..816ce0f --- /dev/null +++ b/node_modules/satellite.js/CHANGELOG.md @@ -0,0 +1,130 @@ +# Changelog + +## 6.0.2 + +- fix: `twoline2satrec` couldn't parse eccentricity padded with spaces instead of zeros +(this only affects TLE generated by rare specialized software; see #153) + +## 6.0.1 (2025-07-04) + +- fix: `json2satrec` couldn't parse OMM `EPOCH` that was ending with Z +- fix: `OMMJsonObject.REV_AT_EPOCH` is made optional according to OMM spec + +## 6.0.0 (2025-04-06) + +- chore: The library is rewritten to TypeScript and type definitions are now not hand-written +but compiled from source code. +- feature: New `json2satrec` function that allows parsing orbital elements in +[OMM](https://www.nasa.gov/wp-content/uploads/2017/12/orbit_data_messages.pdf) format, +**encoded as JSON**. Orbital elements in OMM format are already available for download +from Celestrak and Space-Track. `json2satrec` supports both of these sources and aims +to support all sources of properly formatted OMM data. + +To obtain OMM as JSON from Celestrak, select "JSON" option at the top of "Current GP +Element Sets" page or follow +[this link](https://celestrak.org/NORAD/elements/index.php?FORMAT=json) where it will +be already selected. + +Space-Track doesn't expose the JSON format in their UI, so to get JSON encoded OMM, +on "Recent ELSETs" page, from "Current Catalog Files", copy a URL for the needed category +and change the ending part of the URL from `/format/xml` to be `/format/json`. +- **BREAKING**: The return type of the `sgp4` and `propagate` functions is changed from: +```ts +{ + position: EciVec3 | false + velocity: EciVec3 | false +} +``` +to: +```ts +null | { + position: EciVec3 + velocity: EciVec3 + meanElements: MeanElements +} +``` +Where, if propagation failed, `null` is returned instead of individual keys set to `false`. +- **BREAKING**: removed overloads of `gstime` and return types of `sgp4` and `propagate` that +were not documented by TypeScript definitions as of v5.0.0, but could happen in runtime with v5.0.0. +- feature: New `SatRecError` enum that lists all error codes that can be set on `SatRec.error`. +- feature: `sgp4` and `propagate` function result object returns `meanElements` key, +which is orbit parameters as they have evolved at the propagation moment. Since they are always +internally calculated by SGP4 model, this doesn't impact performance. +- feature: New `sunPos` function that calculates Sun position at date, useful to calculate if +a satellite is in Earth umbra. Its accuracy is within 0.01 angular degree between years +1950 and 2050. +- feature: Many additional properties of `SatRec` are documented +- fix: `dopplerFactor` produces correct results depending on if the satellite is moving +towards or away from the observer. + +## 5.0.0 (2023-01-06) + +- Errors in calculations are fixed, WGS72 is used instead of WGS84 (#107). +- Dependencies are upgraded. + +## 4.1.4 (2022-07-18) + +- TypeScript definition for `ecfToEci` function is added. + +## 4.1.3 (2020-12-18) + +- Fixed calculation of Doppler effect (`dopplerFactor`). + +## 4.1.2 (2020-10-13) + +- Expose `error` in TypeScript definition of `SatRec`. +- Fix TypeScript definition for `PositionAndVelocity` to allow error handling. + +## 4.1.1 (2020-09-15) + +- Fix TypeScript definition for `gstime` (#73). +- Fix documentation and TypeScript definition for `degreesLong` and `degreesLat` (#74). + +## 4.1.0 (2020-09-14) + +- TypeScript support is added via new TypeScript definitions file (#71). +- Rollup and some other dependencies are upgraded. + +## 4.0.0 (2020-01-21) + +- Node.js 12 support is added. Node.js 6 and Node.js 8 support is dropped (breaking change). +- Mocha, Chai and Istanbul are replaced by [Jest](https://jestjs.io/). +- Dependencies are upgraded. + +## 3.0.1 (2019-03-14) + +- Unnecessary calculations in `sgp4` function are reduced (#47). +- `vkmpersec` calculation is moved to constants (#50). +- `degreesToRadians` function is used in docs instead of `deg2rad` constant (#53). +- Typos' fixes (#54). + +## 3.0.0 (2018-11-26) + +- Node.js 4 support is dropped (breaking change). +- Deprecated functions `gstimeFromJday` and `gstimeFromDate` are removed (breaking change). +- New transformation functions are added: `radiansToDegrees`, `degreesToRadians`, `radiansLat`, `radiansLong`. + +## 2.0.3 (2018-09-15) + +- `satrec` object is not cloned in `sgp4` and `sgp4init` functions due to [performance reasons](https://github.com/shashwatak/satellite-js/issues/45). + +## 2.0.2 (2018-04-16) + +- [Wrong predictions for Molniya 3-47 orbits](https://github.com/shashwatak/satellite-js/issues/43) are fixed. Special thanks to [@nhamer](https://github.com/nhamer). + +## 2.0.1 (2018-03-01) + +- `sgp4` function's call result is used in `sgp4init`. +- Longitude of `eciToGeodetic` result is in [-PI; PI] range now. + +## 2.0.0 (2017-12-23) + +- Library became ES and Common.js compatible. +- Source code is reorganized to match [original Python library](https://pypi.python.org/pypi/sgp4/). +- `degreesLat` and `degreesLong` don't adjust input radians value and throw `RangeError` if it's out of bounds (breaking change). +- `invjday` function is added. +- [Julian day calculations take account of milliseconds](https://github.com/shashwatak/satellite-js/issues/31) +([#38](https://github.com/shashwatak/satellite-js/pull/38)). +- [Incorrect position and velocity bug](https://github.com/shashwatak/satellite-js/issues/26) for times not close to TLE epoch is fixed ([#37](https://github.com/shashwatak/satellite-js/pull/37)). +- Continuous integration and test coverage are provided. +- [Bower support is dropped](https://github.com/shashwatak/satellite-js/issues/40). diff --git a/node_modules/satellite.js/LICENSE.md b/node_modules/satellite.js/LICENSE.md new file mode 100644 index 0000000..2243f86 --- /dev/null +++ b/node_modules/satellite.js/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (C) 2013 Shashwat Kandadai, UCSC Jack Baskin School of Engineering + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/satellite.js/ORIGINAL-PKG-INFO b/node_modules/satellite.js/ORIGINAL-PKG-INFO new file mode 100644 index 0000000..d983fb4 --- /dev/null +++ b/node_modules/satellite.js/ORIGINAL-PKG-INFO @@ -0,0 +1,130 @@ +Metadata-Version: 1.0 +Name: sgp4 +Version: 1.1 +Summary: Track earth satellite TLE orbits using up-to-date 2010 version of SGP4 +Home-page: https://github.com/brandon-rhodes/python-sgp4 +Author: Brandon Rhodes +Author-email: brandon@rhodesmill.org +License: MIT +Description: + This Python package computes the position and velocity of an + earth-orbiting satellite, given the satellite's TLE orbital elements + from a source like `Celestrak `_. It implements + the most recent version of SGP4, and is regularly run against the SGP4 + test suite to make sure that its satellite position predictions **agree + to within 1 µm** of the predictions of the standard C++ implementation + of the algorithm. This error is far less than the 1–3 km/day by which + satellites themselves deviate from the ideal orbits described in TLE + files. + + The C++ function names have been retained, since users may already be + familiar with this library in other languages. Here is how to compute + the x,y,z position and velocity for Vanguard 1 at 12:50:19 on 29 + June 2000: + + >>> from sgp4.earth_gravity import wgs72 + >>> from sgp4.io import twoline2rv + >>> line1 = ('1 00005U 58002B 00179.78495062 ' + ... '.00000023 00000-0 28098-4 0 4753') + >>> line2 = ('2 00005 34.2682 348.7242 1859667 ' + ... '331.7664 19.3264 10.82419157413667') + >>> + >>> satellite = twoline2rv(line1, line2, wgs72) + >>> position, velocity = satellite.propagate( + ... 2000, 6, 29, 12, 50, 19) + >>> + >>> position + [5576.056952400586, -3999.371134576452, -1521.9571594376037] + >>> velocity + [4.772627303379319, 5.119817120959591, 4.275553909172126] + + The position vector measures the satellite position in **meters** from + the center of the earth. The velocity is the rate at which those same + three parameters are changing, expressed in **meters per second**. + + There are three gravity models available that you can import from the + ``earth_gravity`` module: + + * ``wgs72`` + * ``wgs72old`` + * ``wgs84`` + + The ``wgs72`` model seems to be the most commonly used in the satellite + tracking community, and is probably the model behind most TLE elements + that are available for download. + + The ``twoline2rv()`` function returns a ``Satellite`` object whose + attributes carry the data loaded from the TLE entry. + Most of this class's hundred-plus attributes are intermediate values + of interest only to the propagation algorithm itself. Here are the + attributes set by ``sgp4.io.twoline2rv()`` in which users are likely + to be interested: + + ``satnum`` + Unique satellite number given in the TLE file. + ``epochyr`` + Full four-digit year of this element set's epoch moment. + ``epochdays`` + Fractional days into the year of the epoch moment. + ``jdsatepoch`` + Julian date of the epoch (computed from ``epochyr`` and ``epochdays``). + ``ndot`` + First time derivative of the mean motion (ignored by SGP4). + ``nddot`` + Second time derivative of the mean motion (ignored by SGP4). + ``bstar`` + Ballistic drag coefficient B* in inverse earth radii. + ``inclo`` + Inclination in radians. + ``nodeo`` + Right ascension of ascending node in radians. + ``ecco`` + Eccentricity. + ``argpo`` + Argument of perigee in radians. + ``mo`` + Mean anomaly in radians. + ``no`` + Mean motion in radians per minute. + + + + This implementation passes all of the automated tests in the August 2010 + release of the reference implementation of SGP4 by Vallado et al., who + originally published their revision of SGP4 in 2006: + + Vallado, David A., Paul Crawford, Richard Hujsak, and T.S. Kelso, “Revisiting Spacetrack Report #3,” presented at the AIAA/AAS Astrodynamics Specialist Conference, Keystone, CO, 2006 August 21–24. + + If you would like to review the paper, it is `available online + `_. You can + always download the latest version of their code for comparison against + this Python module (or other implementations) at `AIAA-2006-6753.zip + `_. + + This module was adapted from Vallado's C++ code since its revision date + was the most recently updated SGP4 implementation in their zip file: + + * C++, August 2010 + * Fortran, August 2008 + * Pascal, August 2008 + * Matlab, May 2008 + * Java, July 2005 + + Changelog + --------- + + | 2012-11-22 — 1.1 — Python 3 compatibility; more documentation + | 2012-08-27 — 1.0 — Initial release + + +Platform: UNKNOWN +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: MIT License +Classifier: Programming Language :: Python :: 2 +Classifier: Programming Language :: Python :: 2.6 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.1 +Classifier: Programming Language :: Python :: 3.2 +Classifier: Topic :: Scientific/Engineering :: Astronomy diff --git a/node_modules/satellite.js/README.md b/node_modules/satellite.js/README.md new file mode 100644 index 0000000..c651ca3 --- /dev/null +++ b/node_modules/satellite.js/README.md @@ -0,0 +1,568 @@ +# satellite.js + +[![NPM version](https://img.shields.io/npm/v/satellite.js.svg)](https://www.npmjs.com/package/satellite.js) +[![Downloads/month](https://img.shields.io/npm/dm/satellite.js.svg)](https://www.npmjs.com/package/satellite.js) +[![License](https://img.shields.io/github/license/mashape/apistatus.svg)](LICENSE.md) + +## Introduction + +A library to make satellite propagation via TLEs or [OMM](https://www.nasa.gov/wp-content/uploads/2017/12/orbit_data_messages.pdf) +possible in the web. Provides the functions necessary for SGP4/SDP4 calculations, as callable javascript. Also provides +functions for coordinate transforms. + +The internals of this library are nearly identical to +[Brandon Rhode's sgp4 python library](https://pypi.python.org/pypi/sgp4/). + +Special thanks to all contributors for improving usability and bug fixes :) + +- [ezze (Dmitriy Pushkov)](https://github.com/ezze) +- [davidcalhoun (David Calhoun)](https://github.com/davidcalhoun) +- [tikhonovits (Nikos Sagias)](https://github.com/tikhonovits) +- [dangodev (Drew Powers)](https://github.com/dangodev) +- [thkruz (Theodore Kruczek)](https://github.com/thkruz) +- [bakercp (Christopher Baker)](https://github.com/bakercp) +- [kylegmaxwell (Kyle G. Maxwell)](https://github.com/kylegmaxwell) +- [iamthechad (Chad Johnston)](https://github.com/iamthechad) +- [drom (Aliaksei Chapyzhenka)](https://github.com/drom) +- [PeterDaveHello (Peter Dave Hello)](https://github.com/PeterDaveHello) +- [Alesha72003](https://github.com/Alesha72003) +- [nhamer](https://github.com/nhamer) +- [owntheweb](https://github.com/owntheweb) +- [Zigone](https://github.com/Zigone) + +Sites using the library can be found [here](https://github.com/shashwatak/satellite-js/wiki/Sites-using-satellite.js). + +## Installation + +```bash +npm install satellite.js +``` + +```bash +yarn add satellite.js +``` + +## Usage + +### ES Modules + +```js +import { sgp4 } from 'satellite.js'; +... +const positionAndVelocity = sgp4(satrec, time); +``` + +### Common.js ([Node.js](https://nodejs.org)) + +```js +const satellite = require('satellite.js'); +... +const positionAndVelocity = satellite.sgp4(satrec, time); +``` + +### AMD ([Require.js](http://requirejs.org/)) + +```js +define(['path/to/dist/satellite'], function(satellite) { + ... + var positionAndVelocity = satellite.sgp4(satrec, time); +}); +``` + +### Script tag + +Include `dist/satellite.min.js` as a script in your html: + +```html + +``` + +`satellite` object will be available in global scope: + +```js +const positionAndVelocity = satellite.sgp4(satrec, time); +``` + +## Sample Usage: calculate Look Angles, Geodetic Position etc + +```js +// Sample TLE +const tleLine1 = '1 25544U 98067A 19156.50900463 .00003075 00000-0 59442-4 0 9992', + tleLine2 = '2 25544 51.6433 59.2583 0008217 16.4489 347.6017 15.51174618173442'; + +// Initialize a satellite record +const satrec = satellite.twoline2satrec(tleLine1, tleLine2); + +// Or sample OMM - preferred for new applications +const omm = { + "OBJECT_NAME": "HELIOS 2A", + "OBJECT_ID": "2004-049A", + "EPOCH": "2025-03-26T05:19:34.116960", + "MEAN_MOTION": 15.00555103, + "ECCENTRICITY": 0.000583, + "INCLINATION": 98.3164, + "RA_OF_ASC_NODE": 103.8411, + "ARG_OF_PERICENTER": 20.5667, + "MEAN_ANOMALY": 339.5789, + "EPHEMERIS_TYPE": 0, + "CLASSIFICATION_TYPE": "U", + "NORAD_CAT_ID": 28492, + "ELEMENT_SET_NO": 999, + "REV_AT_EPOCH": 8655, + "BSTAR": 0.00048021, + "MEAN_MOTION_DOT": 0.00005995, + "MEAN_MOTION_DDOT": 0 +}; + +const satrecFromOmm = satellite.json2satrec(omm); + +// Propagate satellite using time since epoch (in minutes). +const positionAndVelocity = satellite.sgp4(satrec, timeSinceTleEpochMinutes); + +// Or you can use a JavaScript Date +const positionAndVelocity = satellite.propagate(satrec, new Date()); + +// if the result is `null`, it means that the propagation failed; +// consult `satrec.error` property for a specific reason. +if (positionAndVelocity === null) { + switch (satrec.error) { + // all possible values are listed in SatRecError enum: + case satellite.SatRecError.Decayed: + console.log('The satellite has decayed') + // ... + } +} + +// The positionAndVelocity result is a pair of ECI coordinates. +// These are the base results from which all other coordinates are derived. +const positionEci = positionAndVelocity.position, + velocityEci = positionAndVelocity.velocity; + +// Set the Observer at 122.03 West by 36.96 North, in RADIANS +const observerGd = { + longitude: satellite.degreesToRadians(-122.0308), + latitude: satellite.degreesToRadians(36.9613422), + height: 0.370 +}; + +// You will need GMST for some of the coordinate transforms. +// http://en.wikipedia.org/wiki/Sidereal_time#Definition +const gmst = satellite.gstime(new Date()); + +// You can get ECF, Geodetic, Look Angles, and Doppler Factor. +const positionEcf = satellite.eciToEcf(positionEci, gmst), + observerEcf = satellite.geodeticToEcf(observerGd), + positionGd = satellite.eciToGeodetic(positionEci, gmst), + lookAngles = satellite.ecfToLookAngles(observerGd, positionEcf), + dopplerFactor = satellite.dopplerFactor(observerCoordsEcf, positionEcf, velocityEcf); + +// The coordinates are all stored in key-value pairs. +// ECI and ECF are accessed by `x`, `y`, `z` properties. +const satelliteX = positionEci.x, + satelliteY = positionEci.y, + satelliteZ = positionEci.z; + +// Look Angles may be accessed by `azimuth`, `elevation`, `rangeSat` properties. +const azimuth = lookAngles.azimuth, + elevation = lookAngles.elevation, + rangeSat = lookAngles.rangeSat; + +// Geodetic coords are accessed via `longitude`, `latitude`, `height`. +const longitude = positionGd.longitude, + latitude = positionGd.latitude, + height = positionGd.height; + +// Convert the RADIANS to DEGREES. +const longitudeDeg = satellite.degreesLong(longitude), + latitudeDeg = satellite.degreesLat(latitude); +``` + +## Resources + +- [TS Kelso's Columns for Satellite Times](http://celestrak.com/columns/), Orbital Propagation Parts I and II a must! +- [Wikipedia: Simplified Perturbations Model](http://en.wikipedia.org/wiki/Simplified_perturbations_models) +- [SpaceTrack Report #3, by Hoots and Roehrich](http://celestrak.com/NORAD/documentation/spacetrk.pdf). + +The TypeScript in this library is heavily based (propagation procedures straight copied) from: + +- The python [sgp4 1.1 by Brandon Rhodes](https://pypi.python.org/pypi/sgp4/) +- The C++ code by [David Vallado, et al](http://www.celestrak.com/publications/AIAA/2006-6753/) + +The original PKG-INFO file from the python library is included. + +The coordinate transforms are based off T.S. Kelso's columns: + +- [Part I](http://celestrak.com/columns/v02n01/) +- [Part II](http://celestrak.com/columns/v02n02/) +- [Part III](http://celestrak.com/columns/v02n03/) + +And the coursework for UC Boulder's ASEN students +- [Coodinate Transforms @ UC Boulder](http://ccar.colorado.edu/ASEN5070/handouts/coordsys.doc) + +I would recommend anybody interested in satellite tracking or orbital propagation to read +[all of TS Kelso's columns](http://celestrak.com/columns/). Without his work, this project would not be possible. + +Get a free [Space Track account](https://www.space-track.org/auth/login) and download your own up to date TLEs or OMM +for use with this library. + +## Exposed Objects + +### SatRec + +The `SatRec` object comes from the original code by Rhodes as well as Vallado. It is immense and complex, but the +most important values it contains are the Keplerian Elements and the other values pulled from the TLE/OMM. I do not +suggest that anybody try to simplify it unless they have absolute understanding of Orbital Mechanics. + +- `satnum` Unique satellite number given in the TLE file. +- `epochyr` Full four-digit year of this element set's epoch moment. +- `epochdays` Fractional days into the year of the epoch moment. +- `jdsatepoch` Julian date of the epoch (computed from `epochyr` and `epochdays`). +- `ndot` First time derivative of the mean motion (ignored by SGP4). +- `nddot` Second time derivative of the mean motion (ignored by SGP4). +- `bstar` Ballistic drag coefficient B* in inverse earth radii. +- `inclo` Inclination in radians. +- `nodeo` Right ascension of ascending node in radians. +- `ecco` Eccentricity. +- `argpo` Argument of perigee in radians. +- `mo` Mean anomaly in radians. +- `no` Mean motion in radians per minute. +- `error` The error code that is set by SGP4 model in case when propagation fails. + +### SatRecError + +The enum that lists all possible error codes in `SatRec.error property: +- `None` - No error, propagation for the last supplied date is successful +- `MeanEccentricityOutOfRange` - Mean eccentricity is out of range 0 ≤ e < 1 +- `MeanMotionBelowZero` - Mean motion has fallen below zero +- `PerturbedEccentricityOutOfRange` - Perturbed eccentricity is out of range 0 ≤ e < 1 +- `SemiLatusRectumBelowZero` - Length of the orbit’s semi-latus rectum has fallen below zero +- `Decayed` - Orbit has decayed: the computed position is underground + +## Exposed Functions + +### Initialization + +NOTE! You are responsible for providing OMM or TLE. +[Get your free Space Track account here.](https://www.space-track.org/auth/login) +If you use Space Track, there should be no problem. + +#### From OMM (preferred for new applications) + +```js +const satrec = satellite.json2satrec(ommObject); +``` + +returns satrec object, created from JSON object that follows +[OMM format](https://www.nasa.gov/wp-content/uploads/2017/12/orbit_data_messages.pdf). +**OMM is a preferred default method for new applications**, since TLE format is constrained +to 5 digits in NORAD section and the number of catalogued objects quickly approches 100 000. + +To obtain OMM as JSON from Celestrak, select "JSON" option at the top of "Current GP +Element Sets" page or follow +[this link](https://celestrak.org/NORAD/elements/index.php?FORMAT=json) where it will +be already selected. + +Space-Track doesn't expose the JSON format in their UI, so to get JSON encoded OMM, +on "Recent ELSETs" page, from "Current Catalog Files", copy a URL for the needed category +and change the ending part of the URL from `/format/xml` to be `/format/json`. + +#### From TLE + +```js +const satrec = satellite.twoline2satrec(longstr1, longstr2); +``` + +returns satrec object, created from the TLEs passed in. longstr1 and longstr2 are the two lines of the TLE, +properly formatted by NASA and NORAD standards. + +___ + +The satrec object is vastly complicated, but you don't have to do anything with it, except pass it around. + +### Propagation + +Both `propagate()` and `sgp4()` functions return position and velocity; as well as mean elements: + +```json +{ + "position": { "x" : 1, "y" : 1, "z" : 1 }, + "velocity": { "x" : 1, "y" : 1, "z" : 1 }, + "meanElements": { + "Om": 2.2835713400168607, + "am": 1.3043985097733939, + "em": 0.166565, + "im": 0.5743651675510579, + "mm": -4.361270622785478, + "nm": 0.049918822378349076, + "om": 4.074394344293675, + } +} +``` + +position is in km, velocity is in km/s, both the ECI coordinate frame. Mean elements are satellite orbit elements as they +evolved at the propagation date: `am` (semi-major axis, Earth radii), `em` (eccentricity), `im` (inclination, radians), +`Om` (right ascension of ascending node, radians), `om` (argument of perigee, radians), +`nm` (mean motion, radians per minute). + +```js +const positionAndVelocity = satellite.propagate(satrec, new Date()); +``` + +Returns position and velocity, given a satrec and the calendar date. Is merely a wrapper for `sgp4()`, converts the +calendar day to Julian time since satellite epoch. Sometimes it's better to ask for position and velocity given +a specific date. + +```js +const positionAndVelocity = satellite.sgp4(satrec, timeSinceTleEpochMinutes); +``` + +Returns position and velocity, given a satrec and the time in minutes since epoch. Sometimes it's better to ask for +position and velocity given the time elapsed since epoch. + +### Doppler + +You can get the satellites current Doppler factor, relative to your position, using the `dopplerFactor()` function. +Use either ECI or ECF coordinates, but don't mix them. + +```js +const dopplerFactor = satellite.dopplerFactor(observer, position, velocity); +``` + +See the section on Coordinate Transforms to see how to get ECF/ECI/Geodetic coordinates. + +### Coordinate Transforms + +#### Greenwich Mean Sidereal Time + +You'll need to provide some of the coordinate transform functions with your current GMST aka GSTIME. You can use +Julian Day: + +```js +const gmst = satellite.gstime(julianDay); +``` + +or a JavaScript Date: + +```js +const gmst = satellite.gstime(new Date()); +``` + +#### Transforms + +Most of these are self explanatory from their names. Coords are arrays of three floats EX: [1.1, 1.2, 1.3] in +kilometers. Once again, read the following first. + +The coordinate transforms are based off T.S. Kelso's columns: +* [Part I](http://celestrak.com/columns/v02n01/) +* [Part II](http://celestrak.com/columns/v02n02/) +* [Part III](http://celestrak.com/columns/v02n03/) + +And the coursework for UC Boulder's ASEN students +* [Coodinate Transforms @ UC Boulder](http://ccar.colorado.edu/ASEN5070/handouts/coordsys.doc) + +These four are used to convert between ECI, ECF, and Geodetic, as you need them. ECI and ECF coordinates are in +km or km/s. Geodetic coords are in radians. + +```js +const ecfCoords = satellite.eciToEcf(eciCoords, gmst); +``` + +```js +const eciCoords = satellite.ecfToEci(ecfCoords, gmst); +``` + +```js +const geodeticCoords = satellite.eciToGeodetic(eciCoords, gmst); +``` + +```js +const ecfCoords = satellite.geodeticToEcf(geodeticCoords); +``` + +These function is used to compute the look angle, from your geodetic position to a satellite in ECF coordinates. +Make sure you convert the ECI output from sgp4() and propagate() to ECF first. + +```js +const lookAngles = satellite.ecfToLookAngles(observerGeodetic, satelliteEcf); +``` + +#### Latitude and Longitude + +These two functions will return human readable Latitude or Longitude strings (Ex: "125.35W" or "45.565N") +from `geodeticCoords`: + +```js +const latitudeStr = satellite.degreesLat(geodeticRadians), + longitudeStr = satellite.degreesLong(geodeticRadians); +``` + +#### Sun position + +This function returns Sun position at the given date. This is useful to further calculate if a given satellite +is in Earth umbra. Position is returned as geocentric equatorial vector pointing at the sun, +along with Right Ascension and Declination. This is the low precision formula and is valid for years from 1950 +to 2050. Accuracy of apparent coordinates is 0.01 degrees. +```js +const jday = satellite.jday(new Date()) +const sunPosition = satellite.sunPos(jday) + +{ + rsun: [1, 1, 1], // x, y, z; astronomical units + rtasc: 0.5, // radians + decl: 0.5 // radians +} +``` + +## Contributing + +This repo follows [Gitflow Workflow](https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow). +Before starting a work on new [pull request](https://github.com/shashwatak/satellite-js/compare), please, checkout your +feature or bugfix branch from `develop` branch: + +```bash +git checkout develop +git fetch origin +git merge origin/develop +git checkout -b my-feature +``` + +Make sure that your changes don't break the existing code by running + +```bash +npm test +``` + +and that your code follows [Airbnb](https://www.npmjs.com/package/eslint-config-airbnb-base) style + +```bash +npm run lint +npm run lint:test +``` + +Implementing new functions or features, please, if possible, provide tests to cover them and mention your works in +[Changelog](CHANGELOG.md). Please don't change version number in `package.json` and don't add it to `CHANGELOG.md`. +All these things should be done later with [raise-version](https://github.com/ezze/node-raise-version) when +merging to `master`: + +```bash +npm run raise major +``` + +or + +```bash +npm run raise minor +``` + +or + +```bash +npm run raise patch +``` + +In order to get test code coverage run the following: + +```bash +npm run test:coverage +``` + +## Building + +The source code is written in [TypeScript](https://www.typescriptlang.org/) and uses a strict tsconfig. + +In order to build the library follow these steps: + +- install [Node.js](https://nodejs.org/) and [Node Package Manager](https://www.npmjs.com/); + +- install all required packages with NPM by running the following command from repository's root directory: + + ```bash + npm install + ``` + +- run the following NPM script to build everything: + + ```bash + npm run build + ``` + +- run the following NPM script to run test specs `test/*.spec.js` files with [Mocha](https://mochajs.org/): + + ```bash + npm test + ``` + +These is a full list of all available NPM scripts: + +- `build` builds everything; +- `transpile` transpiles ES source files located in `src` directory to Common.js compatible modules and saves + the resulting files in `lib` directory; +- `dist` builds ES and UMD modules in `dist` directory; +- `dist:es` builds ES module in `dist` directory; +- `dist:umd` builds [UMD](https://github.com/umdjs/umd) module in `dist` directory (both non-compressed and + compressed versions); +- `dist:umd:dev` builds non-compressed version of UMD module in `dist` directory; +- `dist:umd:prod` builds compressed version of UMD module in `dist` directory; +- `watch:es` watches for changes in `src` directory and automatically rebuilds ES module; +- `copy` copies built library from `dist` to [SGP4 verification](#benchmarking) application's directory; +- `lint` lints sources code located in `src` directory with [ESLint](http://eslint.org/) with + [Airbnb shared configuration]((https://www.npmjs.com/package/eslint-config-airbnb)); +- `lint:test` lints tests located in `test` directory with ESLint; +- `test` runs tests; +- `test:coverage` runs tests with [Istanbul](https://github.com/gotwarlost/istanbul) coverage summary; + +## ES5 and satellite.min.js + +Only the "src" directory is included in the Git repository, "dist" and "lib" directories are ignored. It's done intentionally to retain the size of the repository as small as possible. A full detailed explanation of why is located [here](https://github.com/shashwatak/satellite-js/issues/80#issuecomment-749225324). + +You should install satellite.js with your package manager (npm or yarn) and then find satellite.js and satellite.min.js in node_modules/satellite.js/dist directory. + +## Note about Code Conventions + +Like Brandon Rhodes before me, I chose to maintain as little difference between this implementation and the prior +works. This is to make adapting future changes suggested by Vallado much simpler. Thus, some of the conventions +used in this library are very weird. + +## How this was written + +I took advantage of the fact that Python and JavaScript are nearly semantically identical. Most of the code is +just copied straight from Python. Brandon Rhodes did me the favor of including semi-colons on most of the lines of +code. JavaScript doesn't support multiple values returned per statement, so I had to rewrite the function calls. +Absolutely none of the mathematical logic had to be rewritten. + +## Benchmarking + +I've included a small testing app, that provides some benchmarking tools and verifies SGP4 and SDP4 using the +Test Criteria provided by SpaceTrack Report #3, and is based off +[System Benchmarking](http://celestrak.com/columns/v02n04/) by TS Kelso. + +The testing app is a Chrome Packaged App that uses the `angular.js` framework. + +Before running the app build the library and copy resulting files from `dist` directory to app's directory with +the following command: + +```bash +npm run copy +``` + +To run the test, open up Chrome, go to the extensions page, and check "Developer Mode". Then, click "Load Unpacked App", +and select the `sgp4_verification` folder. Then run the app from within Chrome. The test file is located within +the `sgp4_verification` directory, as a JSON file called `spacetrack-report-3.json`. + +## Acknowledgments + +Major thanks go to Brandon Rhodes, TS Kelso, and David Vallado's team. Also, I'd like to thank Professor Steve +Petersen (AC6P) of UCSC for pointing me in the correct directions. + +## License + +All files marked with the License header at the top are Licensed. Any files unmarked by me or others are +unlicensed, and are kept only as a resource for [Shashwat Kandadai and other developers] for testing. + +I chose the [MIT License](LICENSE.md) because this library is a derivative work off +[Brandon Rhodes sgp4](https://pypi.python.org/pypi/sgp4/), and that is licensed with MIT. + +I worked in the Dining Hall at UCSC for a month, which means I signed a form that gives UCSC partial ownership of +anything I make while under their aegis, so I included them as owners of the copyright. + +Please email all complaints to help@ucsc.edu diff --git a/node_modules/satellite.js/dist/satellite.es.js b/node_modules/satellite.js/dist/satellite.es.js new file mode 100644 index 0000000..8c09b0c --- /dev/null +++ b/node_modules/satellite.js/dist/satellite.es.js @@ -0,0 +1,3110 @@ +var pi = Math.PI; +var twoPi = pi * 2; +var deg2rad = pi / 180.0; +var rad2deg = 180 / pi; +var minutesPerDay = 1440.0; +var mu = 398600.8; // in km3 / s2 +var earthRadius = 6378.135; // in km +var xke = 60.0 / Math.sqrt(earthRadius * earthRadius * earthRadius / mu); +var vkmpersec = earthRadius * xke / 60.0; +var tumin = 1.0 / xke; +var j2 = 0.001082616; +var j3 = -0.00000253881; +var j4 = -0.00000165597; +var j3oj2 = j3 / j2; +var x2o3 = 2.0 / 3.0; +var xpdotp = 1440.0 / (2.0 * pi); // 229.1831180523293; + +var constants = /*#__PURE__*/Object.freeze({ + __proto__: null, + deg2rad: deg2rad, + earthRadius: earthRadius, + j2: j2, + j3: j3, + j3oj2: j3oj2, + j4: j4, + minutesPerDay: minutesPerDay, + mu: mu, + pi: pi, + rad2deg: rad2deg, + tumin: tumin, + twoPi: twoPi, + vkmpersec: vkmpersec, + x2o3: x2o3, + xke: xke, + xpdotp: xpdotp +}); + +/* ----------------------------------------------------------------------------- + * + * procedure days2mdhms + * + * this procedure converts the day of the year, days, to the equivalent month + * day, hour, minute and second. + * + * algorithm : set up array for the number of days per month + * find leap year - use 1900 because 2000 is a leap year + * loop through a temp value while the value is < the days + * perform int conversions to the correct day and month + * convert remainder into h m s using type conversions + * + * author : david vallado 719-573-2600 1 mar 2001 + * + * inputs description range / units + * year - year 1900 .. 2100 + * days - julian day of the year 0.0 .. 366.0 + * + * outputs : + * mon - month 1 .. 12 + * day - day 1 .. 28,29,30,31 + * hr - hour 0 .. 23 + * min - minute 0 .. 59 + * sec - second 0.0 .. 59.999 + * + * locals : + * dayofyr - day of year + * temp - temporary extended values + * inttemp - temporary int value + * i - index + * lmonth[12] - int array containing the number of days per month + * + * coupling : + * none. + * --------------------------------------------------------------------------- */ +function days2mdhms(year, days) { + var lmonth = [31, year % 4 === 0 ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + var dayofyr = Math.floor(days); + // ----------------- find month and day of month ---------------- + var i = 1; + var inttemp = 0; + // i starts from 1 so no null check is needed + while (dayofyr > inttemp + lmonth[i - 1] && i < 12) { + inttemp += lmonth[i - 1]; + i += 1; + } + var mon = i; + var day = dayofyr - inttemp; + // ----------------- find hours minutes and seconds ------------- + var temp = (days - dayofyr) * 24.0; + var hr = Math.floor(temp); + temp = (temp - hr) * 60.0; + var minute = Math.floor(temp); + var sec = (temp - minute) * 60.0; + return { + mon: mon, + day: day, + hr: hr, + minute: minute, + sec: sec + }; +} +/* ----------------------------------------------------------------------------- + * + * procedure jday + * + * this procedure finds the julian date given the year, month, day, and time. + * the julian date is defined by each elapsed day since noon, jan 1, 4713 bc. + * + * algorithm : calculate the answer in one step for efficiency + * + * author : david vallado 719-573-2600 1 mar 2001 + * + * inputs description range / units + * year - year 1900 .. 2100 + * mon - month 1 .. 12 + * day - day 1 .. 28,29,30,31 + * hr - universal time hour 0 .. 23 + * min - universal time min 0 .. 59 + * sec - universal time sec 0.0 .. 59.999 + * + * outputs : + * jd - julian date days from 4713 bc + * + * locals : + * none. + * + * coupling : + * none. + * + * references : + * vallado 2007, 189, alg 14, ex 3-14 + * + * --------------------------------------------------------------------------- */ +function jdayInternal(year, mon, day, hr, minute, sec) { + var msec = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0; + return 367.0 * year - Math.floor(7 * (year + Math.floor((mon + 9) / 12.0)) * 0.25) + Math.floor(275 * mon / 9.0) + day + 1721013.5 + ((msec / 60000 + sec / 60.0 + minute) / 60.0 + hr) / 24.0 // ut in days + // # - 0.5*sgn(100.0*year + mon - 190002.5) + 0.5; + ; +} +function jday(yearOrDate, mon, day, hr, minute, sec) { + var msec = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0; + if (yearOrDate instanceof Date) { + var date = yearOrDate; + return jdayInternal(date.getUTCFullYear(), date.getUTCMonth() + 1, + // Note, this function requires months in range 1-12. + date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds()); + } + return jdayInternal(yearOrDate, mon, day, hr, minute, sec, msec); +} +function invjday(jd, asArray) { + // --------------- find year and days of the year - + var temp = jd - 2415019.5; + var tu = temp / 365.25; + var year = 1900 + Math.floor(tu); + var leapyrs = Math.floor((year - 1901) * 0.25); + // optional nudge by 8.64x10-7 sec to get even outputs + var days = temp - ((year - 1900) * 365.0 + leapyrs) + 0.00000000001; + // ------------ check for case of beginning of a year ----------- + if (days < 1.0) { + year -= 1; + leapyrs = Math.floor((year - 1901) * 0.25); + days = temp - ((year - 1900) * 365.0 + leapyrs); + } + // ----------------- find remaing data ------------------------- + var mdhms = days2mdhms(year, days); + var mon = mdhms.mon, + day = mdhms.day, + hr = mdhms.hr, + minute = mdhms.minute; + var sec = mdhms.sec - 0.00000086400; + if (asArray) { + return [year, mon, day, hr, minute, Math.floor(sec)]; + } + return new Date(Date.UTC(year, mon - 1, day, hr, minute, Math.floor(sec))); +} + +/* ----------------------------------------------------------------------------- + * + * procedure dpper + * + * this procedure provides deep space long period periodic contributions + * to the mean elements. by design, these periodics are zero at epoch. + * this used to be dscom which included initialization, but it's really a + * recurring function. + * + * author : david vallado 719-573-2600 28 jun 2005 + * + * inputs : + * e3 - + * ee2 - + * peo - + * pgho - + * pho - + * pinco - + * plo - + * se2 , se3 , sgh2, sgh3, sgh4, sh2, sh3, si2, si3, sl2, sl3, sl4 - + * t - + * xh2, xh3, xi2, xi3, xl2, xl3, xl4 - + * zmol - + * zmos - + * ep - eccentricity 0.0 - 1.0 + * inclo - inclination - needed for lyddane modification + * nodep - right ascension of ascending node + * argpp - argument of perigee + * mp - mean anomaly + * + * outputs : + * ep - eccentricity 0.0 - 1.0 + * inclp - inclination + * nodep - right ascension of ascending node + * argpp - argument of perigee + * mp - mean anomaly + * + * locals : + * alfdp - + * betdp - + * cosip , sinip , cosop , sinop , + * dalf - + * dbet - + * dls - + * f2, f3 - + * pe - + * pgh - + * ph - + * pinc - + * pl - + * sel , ses , sghl , sghs , shl , shs , sil , sinzf , sis , + * sll , sls + * xls - + * xnoh - + * zf - + * zm - + * + * coupling : + * none. + * + * references : + * hoots, roehrich, norad spacetrack report #3 1980 + * hoots, norad spacetrack report #6 1986 + * hoots, schumacher and glover 2004 + * vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ +function dpper(satrec, options) { + var e3 = satrec.e3, + ee2 = satrec.ee2, + peo = satrec.peo, + pgho = satrec.pgho, + pho = satrec.pho, + pinco = satrec.pinco, + plo = satrec.plo, + se2 = satrec.se2, + se3 = satrec.se3, + sgh2 = satrec.sgh2, + sgh3 = satrec.sgh3, + sgh4 = satrec.sgh4, + sh2 = satrec.sh2, + sh3 = satrec.sh3, + si2 = satrec.si2, + si3 = satrec.si3, + sl2 = satrec.sl2, + sl3 = satrec.sl3, + sl4 = satrec.sl4, + t = satrec.t, + xgh2 = satrec.xgh2, + xgh3 = satrec.xgh3, + xgh4 = satrec.xgh4, + xh2 = satrec.xh2, + xh3 = satrec.xh3, + xi2 = satrec.xi2, + xi3 = satrec.xi3, + xl2 = satrec.xl2, + xl3 = satrec.xl3, + xl4 = satrec.xl4, + zmol = satrec.zmol, + zmos = satrec.zmos; + var init = options.init, + opsmode = options.opsmode; + var ep = options.ep, + inclp = options.inclp, + nodep = options.nodep, + argpp = options.argpp, + mp = options.mp; + // Copy satellite attributes into local variables for convenience + // and symmetry in writing formulae. + var alfdp; + var betdp; + var cosip; + var sinip; + var cosop; + var sinop; + var dalf; + var dbet; + var dls; + var f2; + var f3; + var pe; + var pgh; + var ph; + var pinc; + var pl; + var sinzf; + var xls; + var xnoh; + var zf; + var zm; + // ---------------------- constants ----------------------------- + var zns = 1.19459e-5; + var zes = 0.01675; + var znl = 1.5835218e-4; + var zel = 0.05490; + // --------------- calculate time varying periodics ----------- + zm = zmos + zns * t; + // be sure that the initial call has time set to zero + if (init === 'y') { + zm = zmos; + } + zf = zm + 2.0 * zes * Math.sin(zm); + sinzf = Math.sin(zf); + f2 = 0.5 * sinzf * sinzf - 0.25; + f3 = -0.5 * sinzf * Math.cos(zf); + var ses = se2 * f2 + se3 * f3; + var sis = si2 * f2 + si3 * f3; + var sls = sl2 * f2 + sl3 * f3 + sl4 * sinzf; + var sghs = sgh2 * f2 + sgh3 * f3 + sgh4 * sinzf; + var shs = sh2 * f2 + sh3 * f3; + zm = zmol + znl * t; + if (init === 'y') { + zm = zmol; + } + zf = zm + 2.0 * zel * Math.sin(zm); + sinzf = Math.sin(zf); + f2 = 0.5 * sinzf * sinzf - 0.25; + f3 = -0.5 * sinzf * Math.cos(zf); + var sel = ee2 * f2 + e3 * f3; + var sil = xi2 * f2 + xi3 * f3; + var sll = xl2 * f2 + xl3 * f3 + xl4 * sinzf; + var sghl = xgh2 * f2 + xgh3 * f3 + xgh4 * sinzf; + var shll = xh2 * f2 + xh3 * f3; + pe = ses + sel; + pinc = sis + sil; + pl = sls + sll; + pgh = sghs + sghl; + ph = shs + shll; + if (init === 'n') { + pe -= peo; + pinc -= pinco; + pl -= plo; + pgh -= pgho; + ph -= pho; + inclp += pinc; + ep += pe; + sinip = Math.sin(inclp); + cosip = Math.cos(inclp); + /* ----------------- apply periodics directly ------------ */ + // sgp4fix for lyddane choice + // strn3 used original inclination - this is technically feasible + // gsfc used perturbed inclination - also technically feasible + // probably best to readjust the 0.2 limit value and limit discontinuity + // 0.2 rad = 11.45916 deg + // use next line for original strn3 approach and original inclination + // if (inclo >= 0.2) + // use next line for gsfc version and perturbed inclination + if (inclp >= 0.2) { + ph /= sinip; + pgh -= cosip * ph; + argpp += pgh; + nodep += ph; + mp += pl; + } else { + // ---- apply periodics with lyddane modification ---- + sinop = Math.sin(nodep); + cosop = Math.cos(nodep); + alfdp = sinip * sinop; + betdp = sinip * cosop; + dalf = ph * cosop + pinc * cosip * sinop; + dbet = -ph * sinop + pinc * cosip * cosop; + alfdp += dalf; + betdp += dbet; + nodep %= twoPi; + // sgp4fix for afspc written intrinsic functions + // nodep used without a trigonometric function ahead + if (nodep < 0.0 && opsmode === 'a') { + nodep += twoPi; + } + xls = mp + argpp + cosip * nodep; + dls = pl + pgh - pinc * nodep * sinip; + xls += dls; + xnoh = nodep; + nodep = Math.atan2(alfdp, betdp); + // sgp4fix for afspc written intrinsic functions + // nodep used without a trigonometric function ahead + if (nodep < 0.0 && opsmode === 'a') { + nodep += twoPi; + } + if (Math.abs(xnoh - nodep) > pi) { + if (nodep < xnoh) { + nodep += twoPi; + } else { + nodep -= twoPi; + } + } + mp += pl; + argpp = xls - mp - cosip * nodep; + } + } + return { + ep: ep, + inclp: inclp, + nodep: nodep, + argpp: argpp, + mp: mp + }; +} + +/*----------------------------------------------------------------------------- + * + * procedure dscom + * + * this procedure provides deep space common items used by both the secular + * and periodics subroutines. input is provided as shown. this routine + * used to be called dpper, but the functions inside weren't well organized. + * + * author : david vallado 719-573-2600 28 jun 2005 + * + * inputs : + * epoch - + * ep - eccentricity + * argpp - argument of perigee + * tc - + * inclp - inclination + * nodep - right ascension of ascending node + * np - mean motion + * + * outputs : + * sinim , cosim , sinomm , cosomm , snodm , cnodm + * day - + * e3 - + * ee2 - + * em - eccentricity + * emsq - eccentricity squared + * gam - + * peo - + * pgho - + * pho - + * pinco - + * plo - + * rtemsq - + * se2, se3 - + * sgh2, sgh3, sgh4 - + * sh2, sh3, si2, si3, sl2, sl3, sl4 - + * s1, s2, s3, s4, s5, s6, s7 - + * ss1, ss2, ss3, ss4, ss5, ss6, ss7, sz1, sz2, sz3 - + * sz11, sz12, sz13, sz21, sz22, sz23, sz31, sz32, sz33 - + * xgh2, xgh3, xgh4, xh2, xh3, xi2, xi3, xl2, xl3, xl4 - + * nm - mean motion + * z1, z2, z3, z11, z12, z13, z21, z22, z23, z31, z32, z33 - + * zmol - + * zmos - + * + * locals : + * a1, a2, a3, a4, a5, a6, a7, a8, a9, a10 - + * betasq - + * cc - + * ctem, stem - + * x1, x2, x3, x4, x5, x6, x7, x8 - + * xnodce - + * xnoi - + * zcosg , zsing , zcosgl , zsingl , zcosh , zsinh , zcoshl , zsinhl , + * zcosi , zsini , zcosil , zsinil , + * zx - + * zy - + * + * coupling : + * none. + * + * references : + * hoots, roehrich, norad spacetrack report #3 1980 + * hoots, norad spacetrack report #6 1986 + * hoots, schumacher and glover 2004 + * vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ +function dscom(options) { + var epoch = options.epoch, + ep = options.ep, + argpp = options.argpp, + tc = options.tc, + inclp = options.inclp, + nodep = options.nodep, + np = options.np; + var a1; + var a2; + var a3; + var a4; + var a5; + var a6; + var a7; + var a8; + var a9; + var a10; + var cc; + var x1; + var x2; + var x3; + var x4; + var x5; + var x6; + var x7; + var x8; + var zcosg; + var zsing; + var zcosh; + var zsinh; + var zcosi; + var zsini; + var ss1; + var ss2; + var ss3; + var ss4; + var ss5; + var ss6; + var ss7; + var sz1; + var sz2; + var sz3; + var sz11; + var sz12; + var sz13; + var sz21; + var sz22; + var sz23; + var sz31; + var sz32; + var sz33; + var s1; + var s2; + var s3; + var s4; + var s5; + var s6; + var s7; + var z1; + var z2; + var z3; + var z11; + var z12; + var z13; + var z21; + var z22; + var z23; + var z31; + var z32; + var z33; + // -------------------------- constants ------------------------- + var zes = 0.01675; + var zel = 0.05490; + var c1ss = 2.9864797e-6; + var c1l = 4.7968065e-7; + var zsinis = 0.39785416; + var zcosis = 0.91744867; + var zcosgs = 0.1945905; + var zsings = -0.98088458; + // --------------------- local variables ------------------------ + var nm = np; + var em = ep; + var snodm = Math.sin(nodep); + var cnodm = Math.cos(nodep); + var sinomm = Math.sin(argpp); + var cosomm = Math.cos(argpp); + var sinim = Math.sin(inclp); + var cosim = Math.cos(inclp); + var emsq = em * em; + var betasq = 1.0 - emsq; + var rtemsq = Math.sqrt(betasq); + // ----------------- initialize lunar solar terms --------------- + var peo = 0.0; + var pinco = 0.0; + var plo = 0.0; + var pgho = 0.0; + var pho = 0.0; + var day = epoch + 18261.5 + tc / 1440.0; + var xnodce = (4.5236020 - 9.2422029e-4 * day) % twoPi; + var stem = Math.sin(xnodce); + var ctem = Math.cos(xnodce); + var zcosil = 0.91375164 - 0.03568096 * ctem; + var zsinil = Math.sqrt(1.0 - zcosil * zcosil); + var zsinhl = 0.089683511 * stem / zsinil; + var zcoshl = Math.sqrt(1.0 - zsinhl * zsinhl); + var gam = 5.8351514 + 0.0019443680 * day; + var zx = 0.39785416 * stem / zsinil; + var zy = zcoshl * ctem + 0.91744867 * zsinhl * stem; + zx = Math.atan2(zx, zy); + zx += gam - xnodce; + var zcosgl = Math.cos(zx); + var zsingl = Math.sin(zx); + // ------------------------- do solar terms --------------------- + zcosg = zcosgs; + zsing = zsings; + zcosi = zcosis; + zsini = zsinis; + zcosh = cnodm; + zsinh = snodm; + cc = c1ss; + var xnoi = 1.0 / nm; + var lsflg = 0; + while (lsflg < 2) { + lsflg += 1; + a1 = zcosg * zcosh + zsing * zcosi * zsinh; + a3 = -zsing * zcosh + zcosg * zcosi * zsinh; + a7 = -zcosg * zsinh + zsing * zcosi * zcosh; + a8 = zsing * zsini; + a9 = zsing * zsinh + zcosg * zcosi * zcosh; + a10 = zcosg * zsini; + a2 = cosim * a7 + sinim * a8; + a4 = cosim * a9 + sinim * a10; + a5 = -sinim * a7 + cosim * a8; + a6 = -sinim * a9 + cosim * a10; + x1 = a1 * cosomm + a2 * sinomm; + x2 = a3 * cosomm + a4 * sinomm; + x3 = -a1 * sinomm + a2 * cosomm; + x4 = -a3 * sinomm + a4 * cosomm; + x5 = a5 * sinomm; + x6 = a6 * sinomm; + x7 = a5 * cosomm; + x8 = a6 * cosomm; + z31 = 12.0 * x1 * x1 - 3.0 * x3 * x3; + z32 = 24.0 * x1 * x2 - 6.0 * x3 * x4; + z33 = 12.0 * x2 * x2 - 3.0 * x4 * x4; + z1 = 3.0 * (a1 * a1 + a2 * a2) + z31 * emsq; + z2 = 6.0 * (a1 * a3 + a2 * a4) + z32 * emsq; + z3 = 3.0 * (a3 * a3 + a4 * a4) + z33 * emsq; + z11 = -6.0 * a1 * a5 + emsq * (-24.0 * x1 * x7 - 6.0 * x3 * x5); + z12 = -6.0 * (a1 * a6 + a3 * a5) + emsq * (-24.0 * (x2 * x7 + x1 * x8) + -6.0 * (x3 * x6 + x4 * x5)); + z13 = -6.0 * a3 * a6 + emsq * (-24.0 * x2 * x8 - 6.0 * x4 * x6); + z21 = 6.0 * a2 * a5 + emsq * (24.0 * x1 * x5 - 6.0 * x3 * x7); + z22 = 6.0 * (a4 * a5 + a2 * a6) + emsq * (24.0 * (x2 * x5 + x1 * x6) - 6.0 * (x4 * x7 + x3 * x8)); + z23 = 6.0 * a4 * a6 + emsq * (24.0 * x2 * x6 - 6.0 * x4 * x8); + z1 = z1 + z1 + betasq * z31; + z2 = z2 + z2 + betasq * z32; + z3 = z3 + z3 + betasq * z33; + s3 = cc * xnoi; + s2 = -0.5 * s3 / rtemsq; + s4 = s3 * rtemsq; + s1 = -15.0 * em * s4; + s5 = x1 * x3 + x2 * x4; + s6 = x2 * x3 + x1 * x4; + s7 = x2 * x4 - x1 * x3; + // ----------------------- do lunar terms ------------------- + if (lsflg === 1) { + ss1 = s1; + ss2 = s2; + ss3 = s3; + ss4 = s4; + ss5 = s5; + ss6 = s6; + ss7 = s7; + sz1 = z1; + sz2 = z2; + sz3 = z3; + sz11 = z11; + sz12 = z12; + sz13 = z13; + sz21 = z21; + sz22 = z22; + sz23 = z23; + sz31 = z31; + sz32 = z32; + sz33 = z33; + zcosg = zcosgl; + zsing = zsingl; + zcosi = zcosil; + zsini = zsinil; + zcosh = zcoshl * cnodm + zsinhl * snodm; + zsinh = snodm * zcoshl - cnodm * zsinhl; + cc = c1l; + } + } + var zmol = (4.7199672 + (0.22997150 * day - gam)) % twoPi; + var zmos = (6.2565837 + 0.017201977 * day) % twoPi; + // ------------------------ do solar terms ---------------------- + var se2 = 2.0 * ss1 * ss6; + var se3 = 2.0 * ss1 * ss7; + var si2 = 2.0 * ss2 * sz12; + var si3 = 2.0 * ss2 * (sz13 - sz11); + var sl2 = -2.0 * ss3 * sz2; + var sl3 = -2.0 * ss3 * (sz3 - sz1); + var sl4 = -2.0 * ss3 * (-21.0 - 9.0 * emsq) * zes; + var sgh2 = 2.0 * ss4 * sz32; + var sgh3 = 2.0 * ss4 * (sz33 - sz31); + var sgh4 = -18.0 * ss4 * zes; + var sh2 = -2.0 * ss2 * sz22; + var sh3 = -2.0 * ss2 * (sz23 - sz21); + // ------------------------ do lunar terms ---------------------- + var ee2 = 2.0 * s1 * s6; + var e3 = 2.0 * s1 * s7; + var xi2 = 2.0 * s2 * z12; + var xi3 = 2.0 * s2 * (z13 - z11); + var xl2 = -2.0 * s3 * z2; + var xl3 = -2.0 * s3 * (z3 - z1); + var xl4 = -2.0 * s3 * (-21.0 - 9.0 * emsq) * zel; + var xgh2 = 2.0 * s4 * z32; + var xgh3 = 2.0 * s4 * (z33 - z31); + var xgh4 = -18.0 * s4 * zel; + var xh2 = -2.0 * s2 * z22; + var xh3 = -2.0 * s2 * (z23 - z21); + return { + snodm: snodm, + cnodm: cnodm, + sinim: sinim, + cosim: cosim, + sinomm: sinomm, + cosomm: cosomm, + day: day, + e3: e3, + ee2: ee2, + em: em, + emsq: emsq, + gam: gam, + peo: peo, + pgho: pgho, + pho: pho, + pinco: pinco, + plo: plo, + rtemsq: rtemsq, + se2: se2, + se3: se3, + sgh2: sgh2, + sgh3: sgh3, + sgh4: sgh4, + sh2: sh2, + sh3: sh3, + si2: si2, + si3: si3, + sl2: sl2, + sl3: sl3, + sl4: sl4, + s1: s1, + s2: s2, + s3: s3, + s4: s4, + s5: s5, + s6: s6, + s7: s7, + ss1: ss1, + ss2: ss2, + ss3: ss3, + ss4: ss4, + ss5: ss5, + ss6: ss6, + ss7: ss7, + sz1: sz1, + sz2: sz2, + sz3: sz3, + sz11: sz11, + sz12: sz12, + sz13: sz13, + sz21: sz21, + sz22: sz22, + sz23: sz23, + sz31: sz31, + sz32: sz32, + sz33: sz33, + xgh2: xgh2, + xgh3: xgh3, + xgh4: xgh4, + xh2: xh2, + xh3: xh3, + xi2: xi2, + xi3: xi3, + xl2: xl2, + xl3: xl3, + xl4: xl4, + nm: nm, + z1: z1, + z2: z2, + z3: z3, + z11: z11, + z12: z12, + z13: z13, + z21: z21, + z22: z22, + z23: z23, + z31: z31, + z32: z32, + z33: z33, + zmol: zmol, + zmos: zmos + }; +} + +/*----------------------------------------------------------------------------- + * + * procedure dsinit + * + * this procedure provides deep space contributions to mean motion dot due + * to geopotential resonance with half day and one day orbits. + * + * author : david vallado 719-573-2600 28 jun 2005 + * + * inputs : + * cosim, sinim- + * emsq - eccentricity squared + * argpo - argument of perigee + * s1, s2, s3, s4, s5 - + * ss1, ss2, ss3, ss4, ss5 - + * sz1, sz3, sz11, sz13, sz21, sz23, sz31, sz33 - + * t - time + * tc - + * gsto - greenwich sidereal time rad + * mo - mean anomaly + * mdot - mean anomaly dot (rate) + * no - mean motion + * nodeo - right ascension of ascending node + * nodedot - right ascension of ascending node dot (rate) + * xpidot - + * z1, z3, z11, z13, z21, z23, z31, z33 - + * eccm - eccentricity + * argpm - argument of perigee + * inclm - inclination + * mm - mean anomaly + * xn - mean motion + * nodem - right ascension of ascending node + * + * outputs : + * em - eccentricity + * argpm - argument of perigee + * inclm - inclination + * mm - mean anomaly + * nm - mean motion + * nodem - right ascension of ascending node + * irez - flag for resonance 0-none, 1-one day, 2-half day + * atime - + * d2201, d2211, d3210, d3222, d4410, d4422, d5220, d5232, d5421, d5433 - + * dedt - + * didt - + * dmdt - + * dndt - + * dnodt - + * domdt - + * del1, del2, del3 - + * ses , sghl , sghs , sgs , shl , shs , sis , sls + * theta - + * xfact - + * xlamo - + * xli - + * xni + * + * locals : + * ainv2 - + * aonv - + * cosisq - + * eoc - + * f220, f221, f311, f321, f322, f330, f441, f442, f522, f523, f542, f543 - + * g200, g201, g211, g300, g310, g322, g410, g422, g520, g521, g532, g533 - + * sini2 - + * temp - + * temp1 - + * theta - + * xno2 - + * + * coupling : + * getgravconst + * + * references : + * hoots, roehrich, norad spacetrack report #3 1980 + * hoots, norad spacetrack report #6 1986 + * hoots, schumacher and glover 2004 + * vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ +function dsinit(options) { + var cosim = options.cosim, + argpo = options.argpo, + s1 = options.s1, + s2 = options.s2, + s3 = options.s3, + s4 = options.s4, + s5 = options.s5, + sinim = options.sinim, + ss1 = options.ss1, + ss2 = options.ss2, + ss3 = options.ss3, + ss4 = options.ss4, + ss5 = options.ss5, + sz1 = options.sz1, + sz3 = options.sz3, + sz11 = options.sz11, + sz13 = options.sz13, + sz21 = options.sz21, + sz23 = options.sz23, + sz31 = options.sz31, + sz33 = options.sz33, + t = options.t, + tc = options.tc, + gsto = options.gsto, + mo = options.mo, + mdot = options.mdot, + no = options.no, + nodeo = options.nodeo, + nodedot = options.nodedot, + xpidot = options.xpidot, + z1 = options.z1, + z3 = options.z3, + z11 = options.z11, + z13 = options.z13, + z21 = options.z21, + z23 = options.z23, + z31 = options.z31, + z33 = options.z33, + ecco = options.ecco, + eccsq = options.eccsq; + var emsq = options.emsq, + em = options.em, + argpm = options.argpm, + inclm = options.inclm, + mm = options.mm, + nm = options.nm, + nodem = options.nodem, + irez = options.irez, + atime = options.atime, + d2201 = options.d2201, + d2211 = options.d2211, + d3210 = options.d3210, + d3222 = options.d3222, + d4410 = options.d4410, + d4422 = options.d4422, + d5220 = options.d5220, + d5232 = options.d5232, + d5421 = options.d5421, + d5433 = options.d5433, + dedt = options.dedt, + didt = options.didt, + dmdt = options.dmdt, + dnodt = options.dnodt, + domdt = options.domdt, + del1 = options.del1, + del2 = options.del2, + del3 = options.del3, + xfact = options.xfact, + xlamo = options.xlamo, + xli = options.xli, + xni = options.xni; + var f220; + var f221; + var f311; + var f321; + var f322; + var f330; + var f441; + var f442; + var f522; + var f523; + var f542; + var f543; + var g200; + var g201; + var g211; + var g300; + var g310; + var g322; + var g410; + var g422; + var g520; + var g521; + var g532; + var g533; + var sini2; + var temp; + var temp1; + var xno2; + var ainv2; + var aonv; + var cosisq; + var eoc; + var q22 = 1.7891679e-6; + var q31 = 2.1460748e-6; + var q33 = 2.2123015e-7; + var root22 = 1.7891679e-6; + var root44 = 7.3636953e-9; + var root54 = 2.1765803e-9; + // eslint-disable-next-line no-loss-of-precision + var rptim = 4.37526908801129966e-3; // equates to 7.29211514668855e-5 rad/sec + var root32 = 3.7393792e-7; + var root52 = 1.1428639e-7; + var znl = 1.5835218e-4; + var zns = 1.19459e-5; + // -------------------- deep space initialization ------------ + irez = 0; + if (nm < 0.0052359877 && nm > 0.0034906585) { + irez = 1; + } + if (nm >= 8.26e-3 && nm <= 9.24e-3 && em >= 0.5) { + irez = 2; + } + // ------------------------ do solar terms ------------------- + var ses = ss1 * zns * ss5; + var sis = ss2 * zns * (sz11 + sz13); + var sls = -zns * ss3 * (sz1 + sz3 - 14.0 - 6.0 * emsq); + var sghs = ss4 * zns * (sz31 + sz33 - 6.0); + var shs = -zns * ss2 * (sz21 + sz23); + // sgp4fix for 180 deg incl + if (inclm < 5.2359877e-2 || inclm > pi - 5.2359877e-2) { + shs = 0.0; + } + if (sinim !== 0.0) { + shs /= sinim; + } + var sgs = sghs - cosim * shs; + // ------------------------- do lunar terms ------------------ + dedt = ses + s1 * znl * s5; + didt = sis + s2 * znl * (z11 + z13); + dmdt = sls - znl * s3 * (z1 + z3 - 14.0 - 6.0 * emsq); + var sghl = s4 * znl * (z31 + z33 - 6.0); + var shll = -znl * s2 * (z21 + z23); + // sgp4fix for 180 deg incl + if (inclm < 5.2359877e-2 || inclm > pi - 5.2359877e-2) { + shll = 0.0; + } + domdt = sgs + sghl; + dnodt = shs; + if (sinim !== 0.0) { + domdt -= cosim / sinim * shll; + dnodt += shll / sinim; + } + // ----------- calculate deep space resonance effects -------- + var dndt = 0.0; + var theta = (gsto + tc * rptim) % twoPi; + em += dedt * t; + inclm += didt * t; + argpm += domdt * t; + nodem += dnodt * t; + mm += dmdt * t; + // sgp4fix for negative inclinations + // the following if statement should be commented out + // if (inclm < 0.0) + // { + // inclm = -inclm; + // argpm = argpm - pi; + // nodem = nodem + pi; + // } + // -------------- initialize the resonance terms ------------- + if (irez !== 0) { + aonv = Math.pow(nm / xke, x2o3); + // ---------- geopotential resonance for 12 hour orbits ------ + if (irez === 2) { + cosisq = cosim * cosim; + var emo = em; + em = ecco; + var emsqo = emsq; + emsq = eccsq; + eoc = em * emsq; + g201 = -0.306 - (em - 0.64) * 0.440; + if (em <= 0.65) { + g211 = 3.616 - 13.2470 * em + 16.2900 * emsq; + g310 = -19.302 + 117.3900 * em - 228.4190 * emsq + 156.5910 * eoc; + g322 = -18.9068 + 109.7927 * em - 214.6334 * emsq + 146.5816 * eoc; + g410 = -41.122 + 242.6940 * em - 471.0940 * emsq + 313.9530 * eoc; + g422 = -146.407 + 841.8800 * em - 1629.014 * emsq + 1083.4350 * eoc; + g520 = -532.114 + 3017.977 * em - 5740.032 * emsq + 3708.2760 * eoc; + } else { + g211 = -72.099 + 331.819 * em - 508.738 * emsq + 266.724 * eoc; + g310 = -346.844 + 1582.851 * em - 2415.925 * emsq + 1246.113 * eoc; + g322 = -342.585 + 1554.908 * em - 2366.899 * emsq + 1215.972 * eoc; + g410 = -1052.797 + 4758.686 * em - 7193.992 * emsq + 3651.957 * eoc; + g422 = -3581.690 + 16178.110 * em - 24462.770 * emsq + 12422.520 * eoc; + if (em > 0.715) { + g520 = -5149.66 + 29936.92 * em - 54087.36 * emsq + 31324.56 * eoc; + } else { + g520 = 1464.74 - 4664.75 * em + 3763.64 * emsq; + } + } + if (em < 0.7) { + g533 = -919.22770 + 4988.6100 * em - 9064.7700 * emsq + 5542.21 * eoc; + g521 = -822.71072 + 4568.6173 * em - 8491.4146 * emsq + 5337.524 * eoc; + g532 = -853.66600 + 4690.2500 * em - 8624.7700 * emsq + 5341.4 * eoc; + } else { + g533 = -37995.780 + 161616.52 * em - 229838.20 * emsq + 109377.94 * eoc; + g521 = -51752.104 + 218913.95 * em - 309468.16 * emsq + 146349.42 * eoc; + g532 = -40023.880 + 170470.89 * em - 242699.48 * emsq + 115605.82 * eoc; + } + sini2 = sinim * sinim; + f220 = 0.75 * (1.0 + 2.0 * cosim + cosisq); + f221 = 1.5 * sini2; + f321 = 1.875 * sinim * (1.0 - 2.0 * cosim - 3.0 * cosisq); + f322 = -1.875 * sinim * (1.0 + 2.0 * cosim - 3.0 * cosisq); + f441 = 35.0 * sini2 * f220; + f442 = 39.3750 * sini2 * sini2; + f522 = 9.84375 * sinim * (sini2 * (1.0 - 2.0 * cosim - 5.0 * cosisq) + 0.33333333 * (-2.0 + 4.0 * cosim + 6.0 * cosisq)); + f523 = sinim * (4.92187512 * sini2 * (-2.0 - 4.0 * cosim + 10.0 * cosisq) + 6.56250012 * (1.0 + 2.0 * cosim - 3.0 * cosisq)); + f542 = 29.53125 * sinim * (2.0 - 8.0 * cosim + cosisq * (-12.0 + 8.0 * cosim + 10.0 * cosisq)); + f543 = 29.53125 * sinim * (-2.0 - 8.0 * cosim + cosisq * (12.0 + 8.0 * cosim - 10.0 * cosisq)); + xno2 = nm * nm; + ainv2 = aonv * aonv; + temp1 = 3.0 * xno2 * ainv2; + temp = temp1 * root22; + d2201 = temp * f220 * g201; + d2211 = temp * f221 * g211; + temp1 *= aonv; + temp = temp1 * root32; + d3210 = temp * f321 * g310; + d3222 = temp * f322 * g322; + temp1 *= aonv; + temp = 2.0 * temp1 * root44; + d4410 = temp * f441 * g410; + d4422 = temp * f442 * g422; + temp1 *= aonv; + temp = temp1 * root52; + d5220 = temp * f522 * g520; + d5232 = temp * f523 * g532; + temp = 2.0 * temp1 * root54; + d5421 = temp * f542 * g521; + d5433 = temp * f543 * g533; + xlamo = (mo + nodeo + nodeo - (theta + theta)) % twoPi; + xfact = mdot + dmdt + 2.0 * (nodedot + dnodt - rptim) - no; + em = emo; + emsq = emsqo; + } + // ---------------- synchronous resonance terms -------------- + if (irez === 1) { + g200 = 1.0 + emsq * (-2.5 + 0.8125 * emsq); + g310 = 1.0 + 2.0 * emsq; + g300 = 1.0 + emsq * (-6.0 + 6.60937 * emsq); + f220 = 0.75 * (1.0 + cosim) * (1.0 + cosim); + f311 = 0.9375 * sinim * sinim * (1.0 + 3.0 * cosim) - 0.75 * (1.0 + cosim); + f330 = 1.0 + cosim; + f330 *= 1.875 * f330 * f330; + del1 = 3.0 * nm * nm * aonv * aonv; + del2 = 2.0 * del1 * f220 * g200 * q22; + del3 = 3.0 * del1 * f330 * g300 * q33 * aonv; + del1 = del1 * f311 * g310 * q31 * aonv; + xlamo = (mo + nodeo + argpo - theta) % twoPi; + xfact = mdot + xpidot + dmdt + domdt + dnodt - (no + rptim); + } + // ------------ for sgp4, initialize the integrator ---------- + xli = xlamo; + xni = no; + atime = 0.0; + nm = no + dndt; + } + return { + em: em, + argpm: argpm, + inclm: inclm, + mm: mm, + nm: nm, + nodem: nodem, + irez: irez, + atime: atime, + d2201: d2201, + d2211: d2211, + d3210: d3210, + d3222: d3222, + d4410: d4410, + d4422: d4422, + d5220: d5220, + d5232: d5232, + d5421: d5421, + d5433: d5433, + dedt: dedt, + didt: didt, + dmdt: dmdt, + dndt: dndt, + dnodt: dnodt, + domdt: domdt, + del1: del1, + del2: del2, + del3: del3, + xfact: xfact, + xlamo: xlamo, + xli: xli, + xni: xni + }; +} + +/* ----------------------------------------------------------------------------- + * + * function gstime + * + * this function finds the greenwich sidereal time. + * + * author : david vallado 719-573-2600 1 mar 2001 + * + * inputs description range / units + * jdut1 - julian date in ut1 days from 4713 bc + * + * outputs : + * gstime - greenwich sidereal time 0 to 2pi rad + * + * locals : + * temp - temporary variable for doubles rad + * tut1 - julian centuries from the + * jan 1, 2000 12 h epoch (ut1) + * + * coupling : + * none + * + * references : + * vallado 2004, 191, eq 3-45 + * --------------------------------------------------------------------------- */ +function gstimeInternal(jdut1) { + var tut1 = (jdut1 - 2451545.0) / 36525.0; + var temp = -6.2e-6 * tut1 * tut1 * tut1 + 0.093104 * tut1 * tut1 + (876600.0 * 3600 + 8640184.812866) * tut1 + 67310.54841; // # sec + temp = temp * deg2rad / 240.0 % twoPi; // 360/86400 = 1/240, to deg, to rad + // ------------------------ check quadrants --------------------- + if (temp < 0.0) { + temp += twoPi; + } + return temp; +} +function gstime(first, month, day, hour, minute, second, millisecond) { + if (first instanceof Date) { + return gstimeInternal(jday(first)); + } else if (month !== undefined) { + return gstimeInternal(jday(first, month, day, hour, minute, second, millisecond)); + } else { + return gstimeInternal(first); + } +} + +/*----------------------------------------------------------------------------- + * + * procedure initl + * + * this procedure initializes the sgp4 propagator. all the initialization is + * consolidated here instead of having multiple loops inside other routines. + * + * author : david vallado 719-573-2600 28 jun 2005 + * + * inputs : + * ecco - eccentricity 0.0 - 1.0 + * epoch - epoch time in days from jan 0, 1950. 0 hr + * inclo - inclination of satellite + * no - mean motion of satellite + * satn - satellite number + * + * outputs : + * ainv - 1.0 / a + * ao - semi major axis + * con41 - + * con42 - 1.0 - 5.0 cos(i) + * cosio - cosine of inclination + * cosio2 - cosio squared + * eccsq - eccentricity squared + * method - flag for deep space 'd', 'n' + * omeosq - 1.0 - ecco * ecco + * posq - semi-parameter squared + * rp - radius of perigee + * rteosq - square root of (1.0 - ecco*ecco) + * sinio - sine of inclination + * gsto - gst at time of observation rad + * no - mean motion of satellite + * + * locals : + * ak - + * d1 - + * del - + * adel - + * po - + * + * coupling : + * getgravconst + * gstime - find greenwich sidereal time from the julian date + * + * references : + * hoots, roehrich, norad spacetrack report #3 1980 + * hoots, norad spacetrack report #6 1986 + * hoots, schumacher and glover 2004 + * vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ +function initl(options) { + var ecco = options.ecco, + epoch = options.epoch, + inclo = options.inclo, + opsmode = options.opsmode; + var no = options.no; + // sgp4fix use old way of finding gst + // ----------------------- earth constants --------------------- + // sgp4fix identify constants and allow alternate values + // ------------- calculate auxillary epoch quantities ---------- + var eccsq = ecco * ecco; + var omeosq = 1.0 - eccsq; + var rteosq = Math.sqrt(omeosq); + var cosio = Math.cos(inclo); + var cosio2 = cosio * cosio; + // ------------------ un-kozai the mean motion ----------------- + var ak = Math.pow(xke / no, x2o3); + var d1 = 0.75 * j2 * (3.0 * cosio2 - 1.0) / (rteosq * omeosq); + var delPrime = d1 / (ak * ak); + var adel = ak * (1.0 - delPrime * delPrime - delPrime * (1.0 / 3.0 + 134.0 * delPrime * delPrime / 81.0)); + delPrime = d1 / (adel * adel); + no /= 1.0 + delPrime; + var ao = Math.pow(xke / no, x2o3); + var sinio = Math.sin(inclo); + var po = ao * omeosq; + var con42 = 1.0 - 5.0 * cosio2; + var con41 = -con42 - cosio2 - cosio2; + var ainv = 1.0 / ao; + var posq = po * po; + var rp = ao * (1.0 - ecco); + var method = 'n'; + // sgp4fix modern approach to finding sidereal time + var gsto; + if (opsmode === 'a') { + // sgp4fix use old way of finding gst + // count integer number of days from 0 jan 1970 + var ts70 = epoch - 7305.0; + var ds70 = Math.floor(ts70 + 1.0e-8); + var tfrac = ts70 - ds70; + // find greenwich location at epoch + var c1 = 1.72027916940703639e-2; // eslint-disable-line no-loss-of-precision + var thgr70 = 1.7321343856509374; // eslint-disable-line no-loss-of-precision + var fk5r = 5.07551419432269442e-15; // eslint-disable-line no-loss-of-precision + var c1p2p = c1 + twoPi; + gsto = (thgr70 + c1 * ds70 + c1p2p * tfrac + ts70 * ts70 * fk5r) % twoPi; + if (gsto < 0.0) { + gsto += twoPi; + } + } else { + gsto = gstime(epoch + 2433281.5); + } + return { + no: no, + method: method, + ainv: ainv, + ao: ao, + con41: con41, + con42: con42, + cosio: cosio, + cosio2: cosio2, + eccsq: eccsq, + omeosq: omeosq, + posq: posq, + rp: rp, + rteosq: rteosq, + sinio: sinio, + gsto: gsto + }; +} + +/*----------------------------------------------------------------------------- + * + * procedure dspace + * + * this procedure provides deep space contributions to mean elements for + * perturbing third body. these effects have been averaged over one + * revolution of the sun and moon. for earth resonance effects, the + * effects have been averaged over no revolutions of the satellite. + * (mean motion) + * + * author : david vallado 719-573-2600 28 jun 2005 + * + * inputs : + * d2201, d2211, d3210, d3222, d4410, d4422, d5220, d5232, d5421, d5433 - + * dedt - + * del1, del2, del3 - + * didt - + * dmdt - + * dnodt - + * domdt - + * irez - flag for resonance 0-none, 1-one day, 2-half day + * argpo - argument of perigee + * argpdot - argument of perigee dot (rate) + * t - time + * tc - + * gsto - gst + * xfact - + * xlamo - + * no - mean motion + * atime - + * em - eccentricity + * ft - + * argpm - argument of perigee + * inclm - inclination + * xli - + * mm - mean anomaly + * xni - mean motion + * nodem - right ascension of ascending node + * + * outputs : + * atime - + * em - eccentricity + * argpm - argument of perigee + * inclm - inclination + * xli - + * mm - mean anomaly + * xni - + * nodem - right ascension of ascending node + * dndt - + * nm - mean motion + * + * locals : + * delt - + * ft - + * theta - + * x2li - + * x2omi - + * xl - + * xldot - + * xnddt - + * xndt - + * xomi - + * + * coupling : + * none - + * + * references : + * hoots, roehrich, norad spacetrack report #3 1980 + * hoots, norad spacetrack report #6 1986 + * hoots, schumacher and glover 2004 + * vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ +function dspace(options) { + var irez = options.irez, + d2201 = options.d2201, + d2211 = options.d2211, + d3210 = options.d3210, + d3222 = options.d3222, + d4410 = options.d4410, + d4422 = options.d4422, + d5220 = options.d5220, + d5232 = options.d5232, + d5421 = options.d5421, + d5433 = options.d5433, + dedt = options.dedt, + del1 = options.del1, + del2 = options.del2, + del3 = options.del3, + didt = options.didt, + dmdt = options.dmdt, + dnodt = options.dnodt, + domdt = options.domdt, + argpo = options.argpo, + argpdot = options.argpdot, + t = options.t, + tc = options.tc, + gsto = options.gsto, + xfact = options.xfact, + xlamo = options.xlamo, + no = options.no; + var atime = options.atime, + em = options.em, + argpm = options.argpm, + inclm = options.inclm, + xli = options.xli, + mm = options.mm, + xni = options.xni, + nodem = options.nodem, + nm = options.nm; + var fasx2 = 0.13130908; + var fasx4 = 2.8843198; + var fasx6 = 0.37448087; + var g22 = 5.7686396; + var g32 = 0.95240898; + var g44 = 1.8014998; + var g52 = 1.0508330; + var g54 = 4.4108898; + // eslint-disable-next-line no-loss-of-precision + var rptim = 4.37526908801129966e-3; // equates to 7.29211514668855e-5 rad/sec + var stepp = 720.0; + var stepn = -720.0; + var step2 = 259200.0; + var delt; + var x2li; + var x2omi; + var xl; + var xldot; + var xnddt; + var xndt; + var xomi; + var dndt = 0.0; + var ft = 0.0; + // ----------- calculate deep space resonance effects ----------- + var theta = (gsto + tc * rptim) % twoPi; + em += dedt * t; + inclm += didt * t; + argpm += domdt * t; + nodem += dnodt * t; + mm += dmdt * t; + // sgp4fix for negative inclinations + // the following if statement should be commented out + // if (inclm < 0.0) + // { + // inclm = -inclm; + // argpm = argpm - pi; + // nodem = nodem + pi; + // } + /* - update resonances : numerical (euler-maclaurin) integration - */ + /* ------------------------- epoch restart ---------------------- */ + // sgp4fix for propagator problems + // the following integration works for negative time steps and periods + // the specific changes are unknown because the original code was so convoluted + // sgp4fix take out atime = 0.0 and fix for faster operation + if (irez !== 0) { + // sgp4fix streamline check + if (atime === 0.0 || t * atime <= 0.0 || Math.abs(t) < Math.abs(atime)) { + atime = 0.0; + xni = no; + xli = xlamo; + } + // sgp4fix move check outside loop + if (t > 0.0) { + delt = stepp; + } else { + delt = stepn; + } + var iretn = 381; // added for do loop + while (iretn === 381) { + // ------------------- dot terms calculated ------------- + // ----------- near - synchronous resonance terms ------- + if (irez !== 2) { + xndt = del1 * Math.sin(xli - fasx2) + del2 * Math.sin(2.0 * (xli - fasx4)) + del3 * Math.sin(3.0 * (xli - fasx6)); + xldot = xni + xfact; + xnddt = del1 * Math.cos(xli - fasx2) + 2.0 * del2 * Math.cos(2.0 * (xli - fasx4)) + 3.0 * del3 * Math.cos(3.0 * (xli - fasx6)); + xnddt *= xldot; + } else { + // --------- near - half-day resonance terms -------- + xomi = argpo + argpdot * atime; + x2omi = xomi + xomi; + x2li = xli + xli; + xndt = d2201 * Math.sin(x2omi + xli - g22) + d2211 * Math.sin(xli - g22) + d3210 * Math.sin(xomi + xli - g32) + d3222 * Math.sin(-xomi + xli - g32) + d4410 * Math.sin(x2omi + x2li - g44) + d4422 * Math.sin(x2li - g44) + d5220 * Math.sin(xomi + xli - g52) + d5232 * Math.sin(-xomi + xli - g52) + d5421 * Math.sin(xomi + x2li - g54) + d5433 * Math.sin(-xomi + x2li - g54); + xldot = xni + xfact; + xnddt = d2201 * Math.cos(x2omi + xli - g22) + d2211 * Math.cos(xli - g22) + d3210 * Math.cos(xomi + xli - g32) + d3222 * Math.cos(-xomi + xli - g32) + d5220 * Math.cos(xomi + xli - g52) + d5232 * Math.cos(-xomi + xli - g52) + 2.0 * (d4410 * Math.cos(x2omi + x2li - g44) + d4422 * Math.cos(x2li - g44) + d5421 * Math.cos(xomi + x2li - g54) + d5433 * Math.cos(-xomi + x2li - g54)); + xnddt *= xldot; + } + // ----------------------- integrator ------------------- + // sgp4fix move end checks to end of routine + if (Math.abs(t - atime) >= stepp) { + iretn = 381; + } else { + ft = t - atime; + iretn = 0; + } + if (iretn === 381) { + xli += xldot * delt + xndt * step2; + xni += xndt * delt + xnddt * step2; + atime += delt; + } + } + nm = xni + xndt * ft + xnddt * ft * ft * 0.5; + xl = xli + xldot * ft + xndt * ft * ft * 0.5; + if (irez !== 1) { + mm = xl - 2.0 * nodem + 2.0 * theta; + dndt = nm - no; + } else { + mm = xl - nodem - argpm + theta; + dndt = nm - no; + } + nm = no + dndt; + } + return { + atime: atime, + em: em, + argpm: argpm, + inclm: inclm, + xli: xli, + mm: mm, + xni: xni, + nodem: nodem, + dndt: dndt, + nm: nm + }; +} + +var SatRecError; +(function (SatRecError) { + /** + * No error, propagation for the last supplied date is successful + */ + SatRecError[SatRecError["None"] = 0] = "None"; + /** + * Mean eccentricity is out of range 0 ≤ e < 1 + */ + SatRecError[SatRecError["MeanEccentricityOutOfRange"] = 1] = "MeanEccentricityOutOfRange"; + /** + * Mean motion has fallen below zero. + */ + SatRecError[SatRecError["MeanMotionBelowZero"] = 2] = "MeanMotionBelowZero"; + /** + * Perturbed eccentricity is out of range 0 ≤ e < 1 + */ + SatRecError[SatRecError["PerturbedEccentricityOutOfRange"] = 3] = "PerturbedEccentricityOutOfRange"; + /** + * Length of the orbit’s semi-latus rectum has fallen below zero. + */ + SatRecError[SatRecError["SemiLatusRectumBelowZero"] = 4] = "SemiLatusRectumBelowZero"; + // 5 is not used + /** + * Orbit has decayed: the computed position is underground. + */ + SatRecError[SatRecError["Decayed"] = 6] = "Decayed"; +})(SatRecError || (SatRecError = {})); + +/*---------------------------------------------------------------------------- + * + * procedure sgp4 + * + * this procedure is the sgp4 prediction model from space command. this is an + * updated and combined version of sgp4 and sdp4, which were originally + * published separately in spacetrack report //3. this version follows the + * methodology from the aiaa paper (2006) describing the history and + * development of the code. + * + * author : david vallado 719-573-2600 28 jun 2005 + * + * inputs : + * satrec - initialised structure from sgp4init() call. + * tsince - time since epoch (minutes) + * + * outputs : + * r - position vector km + * v - velocity km/sec + * return code - non-zero on error. + * 1 - mean elements, ecc >= 1.0 or ecc < -0.001 or a < 0.95 er + * 2 - mean motion less than 0.0 + * 3 - pert elements, ecc < 0.0 or ecc > 1.0 + * 4 - semi-latus rectum < 0.0 + * 5 - epoch elements are sub-orbital + * 6 - satellite has decayed + * + * locals : + * am - + * axnl, aynl - + * betal - + * cosim , sinim , cosomm , sinomm , cnod , snod , cos2u , + * sin2u , coseo1 , sineo1 , cosi , sini , cosip , sinip , + * cosisq , cossu , sinsu , cosu , sinu + * delm - + * delomg - + * dndt - + * eccm - + * emsq - + * ecose - + * el2 - + * eo1 - + * eccp - + * esine - + * argpm - + * argpp - + * omgadf - + * pl - + * r - + * rtemsq - + * rdotl - + * rl - + * rvdot - + * rvdotl - + * su - + * t2 , t3 , t4 , tc + * tem5, temp , temp1 , temp2 , tempa , tempe , templ + * u , ux , uy , uz , vx , vy , vz + * inclm - inclination + * mm - mean anomaly + * nm - mean motion + * nodem - right asc of ascending node + * xinc - + * xincp - + * xl - + * xlm - + * mp - + * xmdf - + * xmx - + * xmy - + * nodedf - + * xnode - + * nodep - + * np - + * + * coupling : + * getgravconst- + * dpper + * dspace + * + * references : + * hoots, roehrich, norad spacetrack report //3 1980 + * hoots, norad spacetrack report //6 1986 + * hoots, schumacher and glover 2004 + * vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ +function sgp4(satrec, tsince) { + var coseo1; + var sineo1; + var cosip; + var sinip; + var cosisq; + var delm; + var delomg; + var eo1; + var argpm; + var argpp; + var su; + var t3; + var t4; + var tc; + var tem5; + var temp; + var tempa; + var tempe; + var templ; + var inclm; + var mm; + var nm; + var nodem; + var xincp; + var xlm; + var mp; + var nodep; + /* ------------------ set mathematical constants --------------- */ + // sgp4fix divisor for divide by zero check on inclination + // the old check used 1.0 + cos(pi-1.0e-9), but then compared it to + // 1.5 e-12, so the threshold was changed to 1.5e-12 for consistency + var temp4 = 1.5e-12; + // --------------------- clear sgp4 error flag ----------------- + satrec.t = tsince; + satrec.error = SatRecError.None; + // ------- update for secular gravity and atmospheric drag ----- + var xmdf = satrec.mo + satrec.mdot * satrec.t; + var argpdf = satrec.argpo + satrec.argpdot * satrec.t; + var nodedf = satrec.nodeo + satrec.nodedot * satrec.t; + argpm = argpdf; + mm = xmdf; + var t2 = satrec.t * satrec.t; + nodem = nodedf + satrec.nodecf * t2; + tempa = 1.0 - satrec.cc1 * satrec.t; + tempe = satrec.bstar * satrec.cc4 * satrec.t; + templ = satrec.t2cof * t2; + if (satrec.isimp !== 1) { + delomg = satrec.omgcof * satrec.t; + // sgp4fix use mutliply for speed instead of pow + var delmtemp = 1.0 + satrec.eta * Math.cos(xmdf); + delm = satrec.xmcof * (delmtemp * delmtemp * delmtemp - satrec.delmo); + temp = delomg + delm; + mm = xmdf + temp; + argpm = argpdf - temp; + t3 = t2 * satrec.t; + t4 = t3 * satrec.t; + tempa = tempa - satrec.d2 * t2 - satrec.d3 * t3 - satrec.d4 * t4; + tempe += satrec.bstar * satrec.cc5 * (Math.sin(mm) - satrec.sinmao); + templ = templ + satrec.t3cof * t3 + t4 * (satrec.t4cof + satrec.t * satrec.t5cof); + } + nm = satrec.no; + var em = satrec.ecco; + inclm = satrec.inclo; + if (satrec.method === 'd') { + tc = satrec.t; + var dspaceOptions = { + irez: satrec.irez, + d2201: satrec.d2201, + d2211: satrec.d2211, + d3210: satrec.d3210, + d3222: satrec.d3222, + d4410: satrec.d4410, + d4422: satrec.d4422, + d5220: satrec.d5220, + d5232: satrec.d5232, + d5421: satrec.d5421, + d5433: satrec.d5433, + dedt: satrec.dedt, + del1: satrec.del1, + del2: satrec.del2, + del3: satrec.del3, + didt: satrec.didt, + dmdt: satrec.dmdt, + dnodt: satrec.dnodt, + domdt: satrec.domdt, + argpo: satrec.argpo, + argpdot: satrec.argpdot, + t: satrec.t, + tc: tc, + gsto: satrec.gsto, + xfact: satrec.xfact, + xlamo: satrec.xlamo, + no: satrec.no, + atime: satrec.atime, + em: em, + argpm: argpm, + inclm: inclm, + xli: satrec.xli, + mm: mm, + xni: satrec.xni, + nodem: nodem, + nm: nm + }; + var dspaceResult = dspace(dspaceOptions); + em = dspaceResult.em; + argpm = dspaceResult.argpm; + inclm = dspaceResult.inclm; + mm = dspaceResult.mm; + nodem = dspaceResult.nodem; + nm = dspaceResult.nm; + } + if (nm <= 0.0) { + // printf("// error nm %f\n", nm); + satrec.error = SatRecError.MeanMotionBelowZero; + // sgp4fix add return + return null; + } + var am = Math.pow(xke / nm, x2o3) * tempa * tempa; + nm = xke / Math.pow(am, 1.5); + em -= tempe; + // fix tolerance for error recognition + // sgp4fix am is fixed from the previous nm check + if (em >= 1.0 || em < -0.001) { + // || (am < 0.95) + // printf("// error em %f\n", em); + satrec.error = SatRecError.MeanEccentricityOutOfRange; + // sgp4fix to return if there is an error in eccentricity + return null; + } + // sgp4fix fix tolerance to avoid a divide by zero + if (em < 1.0e-6) { + em = 1.0e-6; + } + mm += satrec.no * templ; + xlm = mm + argpm + nodem; + nodem %= twoPi; + argpm %= twoPi; + xlm %= twoPi; + mm = (xlm - argpm - nodem) % twoPi; + var meanElements = { + am: am, + em: em, + im: inclm, + Om: nodem, + om: argpm, + mm: mm, + nm: nm + }; + // ----------------- compute extra mean quantities ------------- + var sinim = Math.sin(inclm); + var cosim = Math.cos(inclm); + // -------------------- add lunar-solar periodics -------------- + var ep = em; + xincp = inclm; + argpp = argpm; + nodep = nodem; + mp = mm; + sinip = sinim; + cosip = cosim; + if (satrec.method === 'd') { + var dpperParameters = { + inclo: satrec.inclo, + init: 'n', + ep: ep, + inclp: xincp, + nodep: nodep, + argpp: argpp, + mp: mp, + opsmode: satrec.operationmode + }; + var dpperResult = dpper(satrec, dpperParameters); + ep = dpperResult.ep; + nodep = dpperResult.nodep; + argpp = dpperResult.argpp; + mp = dpperResult.mp; + xincp = dpperResult.inclp; + if (xincp < 0.0) { + xincp = -xincp; + nodep += pi; + argpp -= pi; + } + if (ep < 0.0 || ep > 1.0) { + // printf("// error ep %f\n", ep); + satrec.error = SatRecError.PerturbedEccentricityOutOfRange; + // sgp4fix add return + return null; + } + } + // -------------------- long period periodics ------------------ + if (satrec.method === 'd') { + sinip = Math.sin(xincp); + cosip = Math.cos(xincp); + satrec.aycof = -0.5 * j3oj2 * sinip; + // sgp4fix for divide by zero for xincp = 180 deg + if (Math.abs(cosip + 1.0) > 1.5e-12) { + satrec.xlcof = -0.25 * j3oj2 * sinip * (3.0 + 5.0 * cosip) / (1.0 + cosip); + } else { + satrec.xlcof = -0.25 * j3oj2 * sinip * (3.0 + 5.0 * cosip) / temp4; + } + } + var axnl = ep * Math.cos(argpp); + temp = 1.0 / (am * (1.0 - ep * ep)); + var aynl = ep * Math.sin(argpp) + temp * satrec.aycof; + var xl = mp + argpp + nodep + temp * satrec.xlcof * axnl; + // --------------------- solve kepler's equation --------------- + var u = (xl - nodep) % twoPi; + eo1 = u; + tem5 = 9999.9; + var ktr = 1; + // sgp4fix for kepler iteration + // the following iteration needs better limits on corrections + while (Math.abs(tem5) >= 1.0e-12 && ktr <= 10) { + sineo1 = Math.sin(eo1); + coseo1 = Math.cos(eo1); + tem5 = 1.0 - coseo1 * axnl - sineo1 * aynl; + tem5 = (u - aynl * coseo1 + axnl * sineo1 - eo1) / tem5; + if (Math.abs(tem5) >= 0.95) { + if (tem5 > 0.0) { + tem5 = 0.95; + } else { + tem5 = -0.95; + } + } + eo1 += tem5; + ktr += 1; + } + // ------------- short period preliminary quantities ----------- + var ecose = axnl * coseo1 + aynl * sineo1; + var esine = axnl * sineo1 - aynl * coseo1; + var el2 = axnl * axnl + aynl * aynl; + var pl = am * (1.0 - el2); + if (pl < 0.0) { + // printf("// error pl %f\n", pl); + satrec.error = SatRecError.SemiLatusRectumBelowZero; + // sgp4fix add return + return null; + } + var rl = am * (1.0 - ecose); + var rdotl = Math.sqrt(am) * esine / rl; + var rvdotl = Math.sqrt(pl) / rl; + var betal = Math.sqrt(1.0 - el2); + temp = esine / (1.0 + betal); + var sinu = am / rl * (sineo1 - aynl - axnl * temp); + var cosu = am / rl * (coseo1 - axnl + aynl * temp); + su = Math.atan2(sinu, cosu); + var sin2u = (cosu + cosu) * sinu; + var cos2u = 1.0 - 2.0 * sinu * sinu; + temp = 1.0 / pl; + var temp1 = 0.5 * j2 * temp; + var temp2 = temp1 * temp; + // -------------- update for short period periodics ------------ + if (satrec.method === 'd') { + cosisq = cosip * cosip; + satrec.con41 = 3.0 * cosisq - 1.0; + satrec.x1mth2 = 1.0 - cosisq; + satrec.x7thm1 = 7.0 * cosisq - 1.0; + } + var mrt = rl * (1.0 - 1.5 * temp2 * betal * satrec.con41) + 0.5 * temp1 * satrec.x1mth2 * cos2u; + // sgp4fix for decaying satellites + if (mrt < 1.0) { + // printf("// decay condition %11.6f \n",mrt); + satrec.error = SatRecError.Decayed; + return null; + } + su -= 0.25 * temp2 * satrec.x7thm1 * sin2u; + var xnode = nodep + 1.5 * temp2 * cosip * sin2u; + var xinc = xincp + 1.5 * temp2 * cosip * sinip * cos2u; + var mvt = rdotl - nm * temp1 * satrec.x1mth2 * sin2u / xke; + var rvdot = rvdotl + nm * temp1 * (satrec.x1mth2 * cos2u + 1.5 * satrec.con41) / xke; + // --------------------- orientation vectors ------------------- + var sinsu = Math.sin(su); + var cossu = Math.cos(su); + var snod = Math.sin(xnode); + var cnod = Math.cos(xnode); + var sini = Math.sin(xinc); + var cosi = Math.cos(xinc); + var xmx = -snod * cosi; + var xmy = cnod * cosi; + var ux = xmx * sinsu + cnod * cossu; + var uy = xmy * sinsu + snod * cossu; + var uz = sini * sinsu; + var vx = xmx * cossu - cnod * sinsu; + var vy = xmy * cossu - snod * sinsu; + var vz = sini * cossu; + // --------- position and velocity (in km and km/sec) ---------- + var r = { + x: mrt * ux * earthRadius, + y: mrt * uy * earthRadius, + z: mrt * uz * earthRadius + }; + var v = { + x: (mvt * ux + rvdot * vx) * vkmpersec, + y: (mvt * uy + rvdot * vy) * vkmpersec, + z: (mvt * uz + rvdot * vz) * vkmpersec + }; + return { + position: r, + velocity: v, + meanElements: meanElements + }; +} + +/*----------------------------------------------------------------------------- + * + * procedure sgp4init + * + * this procedure initializes variables for sgp4. + * + * author : david vallado 719-573-2600 28 jun 2005 + * author : david vallado 719-573-2600 28 jun 2005 + * + * inputs : + * opsmode - mode of operation afspc or improved 'a', 'i' + * satn - satellite number + * bstar - sgp4 type drag coefficient kg/m2er + * ecco - eccentricity + * epoch - epoch time in days from jan 0, 1950. 0 hr + * argpo - argument of perigee (output if ds) + * inclo - inclination + * mo - mean anomaly (output if ds) + * no - mean motion + * nodeo - right ascension of ascending node + * + * outputs : + * rec - common values for subsequent calls + * return code - non-zero on error. + * 1 - mean elements, ecc >= 1.0 or ecc < -0.001 or a < 0.95 er + * 2 - mean motion less than 0.0 + * 3 - pert elements, ecc < 0.0 or ecc > 1.0 + * 4 - semi-latus rectum < 0.0 + * 5 - epoch elements are sub-orbital + * 6 - satellite has decayed + * + * locals : + * cnodm , snodm , cosim , sinim , cosomm , sinomm + * cc1sq , cc2 , cc3 + * coef , coef1 + * cosio4 - + * day - + * dndt - + * em - eccentricity + * emsq - eccentricity squared + * eeta - + * etasq - + * gam - + * argpm - argument of perigee + * nodem - + * inclm - inclination + * mm - mean anomaly + * nm - mean motion + * perige - perigee + * pinvsq - + * psisq - + * qzms24 - + * rtemsq - + * s1, s2, s3, s4, s5, s6, s7 - + * sfour - + * ss1, ss2, ss3, ss4, ss5, ss6, ss7 - + * sz1, sz2, sz3 + * sz11, sz12, sz13, sz21, sz22, sz23, sz31, sz32, sz33 - + * tc - + * temp - + * temp1, temp2, temp3 - + * tsi - + * xpidot - + * xhdot1 - + * z1, z2, z3 - + * z11, z12, z13, z21, z22, z23, z31, z32, z33 - + * + * coupling : + * getgravconst- + * initl - + * dscom - + * dpper - + * dsinit - + * sgp4 - + * + * references : + * hoots, roehrich, norad spacetrack report #3 1980 + * hoots, norad spacetrack report #6 1986 + * hoots, schumacher and glover 2004 + * vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ +function sgp4init(satrecInit, options) { + var opsmode = options.opsmode, + satn = options.satn, + epoch = options.epoch, + xbstar = options.xbstar, + xecco = options.xecco, + xargpo = options.xargpo, + xinclo = options.xinclo, + xmo = options.xmo, + xno = options.xno, + xnodeo = options.xnodeo; + var cosim; + var sinim; + var cc1sq; + var cc2; + var cc3; + var coef; + var coef1; + var cosio4; + var em; + var emsq; + var eeta; + var etasq; + var argpm; + var nodem; + var inclm; + var mm; + var nm; + var perige; + var pinvsq; + var psisq; + var qzms24; + var s1; + var s2; + var s3; + var s4; + var s5; + var sfour; + var ss1; + var ss2; + var ss3; + var ss4; + var ss5; + var sz1; + var sz3; + var sz11; + var sz13; + var sz21; + var sz23; + var sz31; + var sz33; + var tc; + var temp; + var temp1; + var temp2; + var temp3; + var tsi; + var xpidot; + var xhdot1; + var z1; + var z3; + var z11; + var z13; + var z21; + var z23; + var z31; + var z33; + /* ------------------------ initialization --------------------- */ + // sgp4fix divisor for divide by zero check on inclination + // the old check used 1.0 + Math.cos(pi-1.0e-9), but then compared it to + // 1.5 e-12, so the threshold was changed to 1.5e-12 for consistency + var temp4 = 1.5e-12; + var satrec = satrecInit; + // ----------- set all near earth variables to zero ------------ + satrec.isimp = 0; + satrec.method = 'n'; + satrec.aycof = 0.0; + satrec.con41 = 0.0; + satrec.cc1 = 0.0; + satrec.cc4 = 0.0; + satrec.cc5 = 0.0; + satrec.d2 = 0.0; + satrec.d3 = 0.0; + satrec.d4 = 0.0; + satrec.delmo = 0.0; + satrec.eta = 0.0; + satrec.argpdot = 0.0; + satrec.omgcof = 0.0; + satrec.sinmao = 0.0; + satrec.t = 0.0; + satrec.t2cof = 0.0; + satrec.t3cof = 0.0; + satrec.t4cof = 0.0; + satrec.t5cof = 0.0; + satrec.x1mth2 = 0.0; + satrec.x7thm1 = 0.0; + satrec.mdot = 0.0; + satrec.nodedot = 0.0; + satrec.xlcof = 0.0; + satrec.xmcof = 0.0; + satrec.nodecf = 0.0; + // ----------- set all deep space variables to zero ------------ + satrec.irez = 0; + satrec.d2201 = 0.0; + satrec.d2211 = 0.0; + satrec.d3210 = 0.0; + satrec.d3222 = 0.0; + satrec.d4410 = 0.0; + satrec.d4422 = 0.0; + satrec.d5220 = 0.0; + satrec.d5232 = 0.0; + satrec.d5421 = 0.0; + satrec.d5433 = 0.0; + satrec.dedt = 0.0; + satrec.del1 = 0.0; + satrec.del2 = 0.0; + satrec.del3 = 0.0; + satrec.didt = 0.0; + satrec.dmdt = 0.0; + satrec.dnodt = 0.0; + satrec.domdt = 0.0; + satrec.e3 = 0.0; + satrec.ee2 = 0.0; + satrec.peo = 0.0; + satrec.pgho = 0.0; + satrec.pho = 0.0; + satrec.pinco = 0.0; + satrec.plo = 0.0; + satrec.se2 = 0.0; + satrec.se3 = 0.0; + satrec.sgh2 = 0.0; + satrec.sgh3 = 0.0; + satrec.sgh4 = 0.0; + satrec.sh2 = 0.0; + satrec.sh3 = 0.0; + satrec.si2 = 0.0; + satrec.si3 = 0.0; + satrec.sl2 = 0.0; + satrec.sl3 = 0.0; + satrec.sl4 = 0.0; + satrec.gsto = 0.0; + satrec.xfact = 0.0; + satrec.xgh2 = 0.0; + satrec.xgh3 = 0.0; + satrec.xgh4 = 0.0; + satrec.xh2 = 0.0; + satrec.xh3 = 0.0; + satrec.xi2 = 0.0; + satrec.xi3 = 0.0; + satrec.xl2 = 0.0; + satrec.xl3 = 0.0; + satrec.xl4 = 0.0; + satrec.xlamo = 0.0; + satrec.zmol = 0.0; + satrec.zmos = 0.0; + satrec.atime = 0.0; + satrec.xli = 0.0; + satrec.xni = 0.0; + // sgp4fix - note the following variables are also passed directly via satrec. + // it is possible to streamline the sgp4init call by deleting the "x" + // variables, but the user would need to set the satrec.* values first. we + // include the additional assignments in case twoline2rv is not used. + satrec.bstar = xbstar; + satrec.ecco = xecco; + satrec.argpo = xargpo; + satrec.inclo = xinclo; + satrec.mo = xmo; + satrec.no = xno; + satrec.nodeo = xnodeo; + // sgp4fix add opsmode + satrec.operationmode = opsmode; + // ------------------------ earth constants ----------------------- + // sgp4fix identify constants and allow alternate values + var ss = 78.0 / earthRadius + 1.0; + // sgp4fix use multiply for speed instead of pow + var qzms2ttemp = (120.0 - 78.0) / earthRadius; + var qzms2t = qzms2ttemp * qzms2ttemp * qzms2ttemp * qzms2ttemp; + satrec.init = 'y'; + satrec.t = 0.0; + var initlOptions = { + satn: satn, + ecco: satrec.ecco, + epoch: epoch, + inclo: satrec.inclo, + no: satrec.no, + method: satrec.method, + opsmode: satrec.operationmode + }; + var initlResult = initl(initlOptions); + var ao = initlResult.ao, + con42 = initlResult.con42, + cosio = initlResult.cosio, + cosio2 = initlResult.cosio2, + eccsq = initlResult.eccsq, + omeosq = initlResult.omeosq, + posq = initlResult.posq, + rp = initlResult.rp, + rteosq = initlResult.rteosq, + sinio = initlResult.sinio; + satrec.no = initlResult.no; + satrec.con41 = initlResult.con41; + satrec.gsto = initlResult.gsto; + satrec.a = Math.pow(satrec.no * tumin, -2.0 / 3.0); + satrec.alta = satrec.a * (1.0 + satrec.ecco) - 1.0; + satrec.altp = satrec.a * (1.0 - satrec.ecco) - 1.0; + satrec.error = 0; + // sgp4fix remove this check as it is unnecessary + // the mrt check in sgp4 handles decaying satellite cases even if the starting + // condition is below the surface of te earth + // if (rp < 1.0) + // { + // printf("// *** satn%d epoch elts sub-orbital ***\n", satn); + // satrec.error = 5; + // } + if (omeosq >= 0.0 || satrec.no >= 0.0) { + satrec.isimp = 0; + if (rp < 220.0 / earthRadius + 1.0) { + satrec.isimp = 1; + } + sfour = ss; + qzms24 = qzms2t; + perige = (rp - 1.0) * earthRadius; + // - for perigees below 156 km, s and qoms2t are altered - + if (perige < 156.0) { + sfour = perige - 78.0; + if (perige < 98.0) { + sfour = 20.0; + } + // sgp4fix use multiply for speed instead of pow + var qzms24temp = (120.0 - sfour) / earthRadius; + qzms24 = qzms24temp * qzms24temp * qzms24temp * qzms24temp; + sfour = sfour / earthRadius + 1.0; + } + pinvsq = 1.0 / posq; + tsi = 1.0 / (ao - sfour); + satrec.eta = ao * satrec.ecco * tsi; + etasq = satrec.eta * satrec.eta; + eeta = satrec.ecco * satrec.eta; + psisq = Math.abs(1.0 - etasq); + coef = qzms24 * Math.pow(tsi, 4.0); + coef1 = coef / Math.pow(psisq, 3.5); + cc2 = coef1 * satrec.no * (ao * (1.0 + 1.5 * etasq + eeta * (4.0 + etasq)) + 0.375 * j2 * tsi / psisq * satrec.con41 * (8.0 + 3.0 * etasq * (8.0 + etasq))); + satrec.cc1 = satrec.bstar * cc2; + cc3 = 0.0; + if (satrec.ecco > 1.0e-4) { + cc3 = -2.0 * coef * tsi * j3oj2 * satrec.no * sinio / satrec.ecco; + } + satrec.x1mth2 = 1.0 - cosio2; + satrec.cc4 = 2.0 * satrec.no * coef1 * ao * omeosq * (satrec.eta * (2.0 + 0.5 * etasq) + satrec.ecco * (0.5 + 2.0 * etasq) - j2 * tsi / (ao * psisq) * (-3.0 * satrec.con41 * (1.0 - 2.0 * eeta + etasq * (1.5 - 0.5 * eeta)) + 0.75 * satrec.x1mth2 * (2.0 * etasq - eeta * (1.0 + etasq)) * Math.cos(2.0 * satrec.argpo))); + satrec.cc5 = 2.0 * coef1 * ao * omeosq * (1.0 + 2.75 * (etasq + eeta) + eeta * etasq); + cosio4 = cosio2 * cosio2; + temp1 = 1.5 * j2 * pinvsq * satrec.no; + temp2 = 0.5 * temp1 * j2 * pinvsq; + temp3 = -0.46875 * j4 * pinvsq * pinvsq * satrec.no; + satrec.mdot = satrec.no + 0.5 * temp1 * rteosq * satrec.con41 + 0.0625 * temp2 * rteosq * (13.0 - 78.0 * cosio2 + 137.0 * cosio4); + satrec.argpdot = -0.5 * temp1 * con42 + 0.0625 * temp2 * (7.0 - 114.0 * cosio2 + 395.0 * cosio4) + temp3 * (3.0 - 36.0 * cosio2 + 49.0 * cosio4); + xhdot1 = -temp1 * cosio; + satrec.nodedot = xhdot1 + (0.5 * temp2 * (4.0 - 19.0 * cosio2) + 2.0 * temp3 * (3.0 - 7.0 * cosio2)) * cosio; + xpidot = satrec.argpdot + satrec.nodedot; + satrec.omgcof = satrec.bstar * cc3 * Math.cos(satrec.argpo); + satrec.xmcof = 0.0; + if (satrec.ecco > 1.0e-4) { + satrec.xmcof = -x2o3 * coef * satrec.bstar / eeta; + } + satrec.nodecf = 3.5 * omeosq * xhdot1 * satrec.cc1; + satrec.t2cof = 1.5 * satrec.cc1; + // sgp4fix for divide by zero with xinco = 180 deg + if (Math.abs(cosio + 1.0) > 1.5e-12) { + satrec.xlcof = -0.25 * j3oj2 * sinio * (3.0 + 5.0 * cosio) / (1.0 + cosio); + } else { + satrec.xlcof = -0.25 * j3oj2 * sinio * (3.0 + 5.0 * cosio) / temp4; + } + satrec.aycof = -0.5 * j3oj2 * sinio; + // sgp4fix use multiply for speed instead of pow + var delmotemp = 1.0 + satrec.eta * Math.cos(satrec.mo); + satrec.delmo = delmotemp * delmotemp * delmotemp; + satrec.sinmao = Math.sin(satrec.mo); + satrec.x7thm1 = 7.0 * cosio2 - 1.0; + // --------------- deep space initialization ------------- + if (2 * pi / satrec.no >= 225.0) { + satrec.method = 'd'; + satrec.isimp = 1; + tc = 0.0; + inclm = satrec.inclo; + var dscomOptions = { + epoch: epoch, + ep: satrec.ecco, + argpp: satrec.argpo, + tc: tc, + inclp: satrec.inclo, + nodep: satrec.nodeo, + np: satrec.no, + e3: satrec.e3, + ee2: satrec.ee2, + peo: satrec.peo, + pgho: satrec.pgho, + pho: satrec.pho, + pinco: satrec.pinco, + plo: satrec.plo, + se2: satrec.se2, + se3: satrec.se3, + sgh2: satrec.sgh2, + sgh3: satrec.sgh3, + sgh4: satrec.sgh4, + sh2: satrec.sh2, + sh3: satrec.sh3, + si2: satrec.si2, + si3: satrec.si3, + sl2: satrec.sl2, + sl3: satrec.sl3, + sl4: satrec.sl4, + xgh2: satrec.xgh2, + xgh3: satrec.xgh3, + xgh4: satrec.xgh4, + xh2: satrec.xh2, + xh3: satrec.xh3, + xi2: satrec.xi2, + xi3: satrec.xi3, + xl2: satrec.xl2, + xl3: satrec.xl3, + xl4: satrec.xl4, + zmol: satrec.zmol, + zmos: satrec.zmos + }; + var dscomResult = dscom(dscomOptions); + satrec.e3 = dscomResult.e3; + satrec.ee2 = dscomResult.ee2; + satrec.peo = dscomResult.peo; + satrec.pgho = dscomResult.pgho; + satrec.pho = dscomResult.pho; + satrec.pinco = dscomResult.pinco; + satrec.plo = dscomResult.plo; + satrec.se2 = dscomResult.se2; + satrec.se3 = dscomResult.se3; + satrec.sgh2 = dscomResult.sgh2; + satrec.sgh3 = dscomResult.sgh3; + satrec.sgh4 = dscomResult.sgh4; + satrec.sh2 = dscomResult.sh2; + satrec.sh3 = dscomResult.sh3; + satrec.si2 = dscomResult.si2; + satrec.si3 = dscomResult.si3; + satrec.sl2 = dscomResult.sl2; + satrec.sl3 = dscomResult.sl3; + satrec.sl4 = dscomResult.sl4; + sinim = dscomResult.sinim; + cosim = dscomResult.cosim; + em = dscomResult.em; + emsq = dscomResult.emsq; + s1 = dscomResult.s1; + s2 = dscomResult.s2; + s3 = dscomResult.s3; + s4 = dscomResult.s4; + s5 = dscomResult.s5; + ss1 = dscomResult.ss1; + ss2 = dscomResult.ss2; + ss3 = dscomResult.ss3; + ss4 = dscomResult.ss4; + ss5 = dscomResult.ss5; + sz1 = dscomResult.sz1; + sz3 = dscomResult.sz3; + sz11 = dscomResult.sz11; + sz13 = dscomResult.sz13; + sz21 = dscomResult.sz21; + sz23 = dscomResult.sz23; + sz31 = dscomResult.sz31; + sz33 = dscomResult.sz33; + satrec.xgh2 = dscomResult.xgh2; + satrec.xgh3 = dscomResult.xgh3; + satrec.xgh4 = dscomResult.xgh4; + satrec.xh2 = dscomResult.xh2; + satrec.xh3 = dscomResult.xh3; + satrec.xi2 = dscomResult.xi2; + satrec.xi3 = dscomResult.xi3; + satrec.xl2 = dscomResult.xl2; + satrec.xl3 = dscomResult.xl3; + satrec.xl4 = dscomResult.xl4; + satrec.zmol = dscomResult.zmol; + satrec.zmos = dscomResult.zmos; + nm = dscomResult.nm; + z1 = dscomResult.z1; + z3 = dscomResult.z3; + z11 = dscomResult.z11; + z13 = dscomResult.z13; + z21 = dscomResult.z21; + z23 = dscomResult.z23; + z31 = dscomResult.z31; + z33 = dscomResult.z33; + var dpperOptions = { + inclo: inclm, + init: satrec.init, + ep: satrec.ecco, + inclp: satrec.inclo, + nodep: satrec.nodeo, + argpp: satrec.argpo, + mp: satrec.mo, + opsmode: satrec.operationmode + }; + var dpperResult = dpper(satrec, dpperOptions); + satrec.ecco = dpperResult.ep; + satrec.inclo = dpperResult.inclp; + satrec.nodeo = dpperResult.nodep; + satrec.argpo = dpperResult.argpp; + satrec.mo = dpperResult.mp; + argpm = 0.0; + nodem = 0.0; + mm = 0.0; + var dsinitOptions = { + cosim: cosim, + emsq: emsq, + argpo: satrec.argpo, + s1: s1, + s2: s2, + s3: s3, + s4: s4, + s5: s5, + sinim: sinim, + ss1: ss1, + ss2: ss2, + ss3: ss3, + ss4: ss4, + ss5: ss5, + sz1: sz1, + sz3: sz3, + sz11: sz11, + sz13: sz13, + sz21: sz21, + sz23: sz23, + sz31: sz31, + sz33: sz33, + t: satrec.t, + tc: tc, + gsto: satrec.gsto, + mo: satrec.mo, + mdot: satrec.mdot, + no: satrec.no, + nodeo: satrec.nodeo, + nodedot: satrec.nodedot, + xpidot: xpidot, + z1: z1, + z3: z3, + z11: z11, + z13: z13, + z21: z21, + z23: z23, + z31: z31, + z33: z33, + ecco: satrec.ecco, + eccsq: eccsq, + em: em, + argpm: argpm, + inclm: inclm, + mm: mm, + nm: nm, + nodem: nodem, + irez: satrec.irez, + atime: satrec.atime, + d2201: satrec.d2201, + d2211: satrec.d2211, + d3210: satrec.d3210, + d3222: satrec.d3222, + d4410: satrec.d4410, + d4422: satrec.d4422, + d5220: satrec.d5220, + d5232: satrec.d5232, + d5421: satrec.d5421, + d5433: satrec.d5433, + dedt: satrec.dedt, + didt: satrec.didt, + dmdt: satrec.dmdt, + dnodt: satrec.dnodt, + domdt: satrec.domdt, + del1: satrec.del1, + del2: satrec.del2, + del3: satrec.del3, + xfact: satrec.xfact, + xlamo: satrec.xlamo, + xli: satrec.xli, + xni: satrec.xni + }; + var dsinitResult = dsinit(dsinitOptions); + satrec.irez = dsinitResult.irez; + satrec.atime = dsinitResult.atime; + satrec.d2201 = dsinitResult.d2201; + satrec.d2211 = dsinitResult.d2211; + satrec.d3210 = dsinitResult.d3210; + satrec.d3222 = dsinitResult.d3222; + satrec.d4410 = dsinitResult.d4410; + satrec.d4422 = dsinitResult.d4422; + satrec.d5220 = dsinitResult.d5220; + satrec.d5232 = dsinitResult.d5232; + satrec.d5421 = dsinitResult.d5421; + satrec.d5433 = dsinitResult.d5433; + satrec.dedt = dsinitResult.dedt; + satrec.didt = dsinitResult.didt; + satrec.dmdt = dsinitResult.dmdt; + satrec.dnodt = dsinitResult.dnodt; + satrec.domdt = dsinitResult.domdt; + satrec.del1 = dsinitResult.del1; + satrec.del2 = dsinitResult.del2; + satrec.del3 = dsinitResult.del3; + satrec.xfact = dsinitResult.xfact; + satrec.xlamo = dsinitResult.xlamo; + satrec.xli = dsinitResult.xli; + satrec.xni = dsinitResult.xni; + } + // ----------- set variables if not deep space ----------- + if (satrec.isimp !== 1) { + cc1sq = satrec.cc1 * satrec.cc1; + satrec.d2 = 4.0 * ao * tsi * cc1sq; + temp = satrec.d2 * tsi * satrec.cc1 / 3.0; + satrec.d3 = (17.0 * ao + sfour) * temp; + satrec.d4 = 0.5 * temp * ao * tsi * (221.0 * ao + 31.0 * sfour) * satrec.cc1; + satrec.t3cof = satrec.d2 + 2.0 * cc1sq; + satrec.t4cof = 0.25 * (3.0 * satrec.d3 + satrec.cc1 * (12.0 * satrec.d2 + 10.0 * cc1sq)); + satrec.t5cof = 0.2 * (3.0 * satrec.d4 + 12.0 * satrec.cc1 * satrec.d3 + 6.0 * satrec.d2 * satrec.d2 + 15.0 * cc1sq * (2.0 * satrec.d2 + cc1sq)); + } + /* finally propogate to zero epoch to initialize all others. */ + // sgp4fix take out check to let satellites process until they are actually below earth surface + // if(satrec.error == 0) + } + sgp4(satrec, 0); + satrec.init = 'n'; +} + +/* ----------------------------------------------------------------------------- + * + * function twoline2satrec + * + * this function converts the two line element set character string data to + * variables and initializes the sgp4 variables. several intermediate varaibles + * and quantities are determined. note that the result is a structure so multiple + * satellites can be processed simultaneously without having to reinitialize. the + * verification mode is an important option that permits quick checks of any + * changes to the underlying technical theory. this option works using a + * modified tle file in which the start, stop, and delta time values are + * included at the end of the second line of data. this only works with the + * verification mode. the catalog mode simply propagates from -1440 to 1440 min + * from epoch and is useful when performing entire catalog runs. + * + * author : david vallado 719-573-2600 1 mar 2001 + * + * inputs : + * longstr1 - first line of the tle + * longstr2 - second line of the tle + * typerun - type of run verification 'v', catalog 'c', + * manual 'm' + * typeinput - type of manual input mfe 'm', epoch 'e', dayofyr 'd' + * opsmode - mode of operation afspc or improved 'a', 'i' + * whichconst - which set of constants to use 72, 84 + * + * outputs : + * satrec - structure containing all the sgp4 satellite information + * + * coupling : + * getgravconst- + * days2mdhms - conversion of days to month, day, hour, minute, second + * jday - convert day month year hour minute second into julian date + * sgp4init - initialize the sgp4 variables + * + * references : + * norad spacetrack report #3 + * vallado, crawford, hujsak, kelso 2006 + --------------------------------------------------------------------------- */ +/** + * Return a Satellite imported from two lines of TLE data. + * + * Provide the two TLE lines as strings `tleLine1` and `tleLine2`, + * and select which standard set of gravitational constants you want + * by providing `gravity_constants`: + * + * `sgp4.propagation.wgs72` - Standard WGS 72 model + * `sgp4.propagation.wgs84` - More recent WGS 84 model + * `sgp4.propagation.wgs72old` - Legacy support for old SGP4 behavior + * + * Normally, computations are made using letious recent improvements + * to the algorithm. If you want to turn some of these off and go + * back into "afspc" mode, then set `afspc_mode` to `True`. + */ +function twoline2satrec(longstr1, longstr2) { + var opsmode = 'i'; + var error = 0; + var satnum = longstr1.substring(2, 7); + var epochyr = parseInt(longstr1.substring(18, 20), 10); + var epochdays = parseFloat(longstr1.substring(20, 32)); + var ndot = parseFloat(longstr1.substring(33, 43)); + var nddot = parseFloat("".concat(longstr1.substring(44, 45), ".").concat(longstr1.substring(45, 50), "E").concat(longstr1.substring(50, 52))); + var bstar = parseFloat("".concat(longstr1.substring(53, 54), ".").concat(longstr1.substring(54, 59), "E").concat(longstr1.substring(59, 61))); + // satrec.satnum = longstr2.substring(2, 7); + // ---- find standard orbital elements ---- + var inclo = parseFloat(longstr2.substring(8, 16)) * deg2rad; + var nodeo = parseFloat(longstr2.substring(17, 25)) * deg2rad; + var ecco = parseFloat(".".concat(longstr2.substring(26, 33).replace(/\s/g, '0'))); + var argpo = parseFloat(longstr2.substring(34, 42)) * deg2rad; + var mo = parseFloat(longstr2.substring(43, 51)) * deg2rad; + // ---- find no, ndot, nddot ---- + var no = parseFloat(longstr2.substring(52, 63)) / xpdotp; + // satrec.nddot= satrec.nddot * Math.pow(10.0, nexp); + // satrec.bstar= satrec.bstar * Math.pow(10.0, ibexp); + // ---- convert to sgp4 units ---- + // satrec.ndot /= (xpdotp * 1440.0); // ? * minperday + // satrec.nddot /= (xpdotp * 1440.0 * 1440); + // ---------------------------------------------------------------- + // find sgp4epoch time of element set + // remember that sgp4 uses units of days from 0 jan 1950 (sgp4epoch) + // and minutes from the epoch (time) + // ---------------------------------------------------------------- + // ---------------- temp fix for years from 1957-2056 ------------------- + // --------- correct fix will occur when year is 4-digit in tle --------- + var year = epochyr < 57 ? epochyr + 2000 : epochyr + 1900; + var mdhmsResult = days2mdhms(year, epochdays); + var mon = mdhmsResult.mon, + day = mdhmsResult.day, + hr = mdhmsResult.hr, + minute = mdhmsResult.minute, + sec = mdhmsResult.sec; + var jdsatepoch = jday(year, mon, day, hr, minute, sec); + var satrec = { + error: error, + satnum: satnum, + epochyr: epochyr, + epochdays: epochdays, + ndot: ndot, + nddot: nddot, + bstar: bstar, + inclo: inclo, + nodeo: nodeo, + ecco: ecco, + argpo: argpo, + mo: mo, + no: no, + jdsatepoch: jdsatepoch + }; + // ---------------- initialize the orbit at sgp4epoch ------------------- + sgp4init(satrec, { + opsmode: opsmode, + satn: satrec.satnum, + epoch: satrec.jdsatepoch - 2433281.5, + xbstar: satrec.bstar, + xecco: satrec.ecco, + xargpo: satrec.argpo, + xinclo: satrec.inclo, + xmo: satrec.mo, + xno: satrec.no, + xnodeo: satrec.nodeo + }); + return satrec; +} +/* ----------------------------------------------------------------------------- + * + * function json2satrec + * + * this function converts the OMM json data to variables and initializes the sgp4 + * variables. several intermediate varaibles and quantities are determined. note + * that the result is a structure so multiple satellites can be processed + * simultaneously without having to reinitialize. the verification mode is an + * important option that permits quick checks of any changes to the underlying + * technical theory. this option works using a modified tle file in which the + * start, stop, and delta time values are included at the end of the second line + * of data. this only works with the verification mode. the catalog mode simply + * propagates from -1440 to 1440 min from epoch and is useful when performing + * entire catalog runs. + * + * author : Hariharan Vitaladevuni 18 Aug 2023 + * Theodore Kruczek 19 Aug 2023 + * + * inputs : + * jsonobj - OMM json data + * opsmode - mode of operation afspc or improved 'a', 'i'. Default: 'i'. + * + * outputs : + * satrec - structure containing all the sgp4 satellite information + * + * coupling : + * days2mdhms - conversion of days to month, day, hour, minute, second + * jday - convert day month year hour minute second into julian date + * sgp4init - initialize the sgp4 variables + * + * warning : the epoch date in OMM format is more accurate than TLE format! + * this will result in extremely close, but different + * position/velocity values. Depending on your use case, it may + * be better to use twoline2satrec, but for the average user this + * will provide comparable results. + * + * references : + * https://celestrak.org/NORAD/documentation/gp-data-formats.php + --------------------------------------------------------------------------- */ +function json2satrec(jsonobj) { + var opsmode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'i'; + var error = 0; + var satnum = jsonobj.NORAD_CAT_ID.toString(); + var epoch = new Date(jsonobj.EPOCH.endsWith('Z') ? jsonobj.EPOCH : jsonobj.EPOCH + 'Z'); + var year = epoch.getUTCFullYear(); + var epochyr = Number(year.toString().slice(-2)); + var epochdays = (epoch.valueOf() - new Date(Date.UTC(year, 0, 1, 0, 0, 0)).valueOf()) / (86400 * 1000) + 1; + var ndot = Number(jsonobj.MEAN_MOTION_DOT); + var nddot = Number(jsonobj.MEAN_MOTION_DDOT); + var bstar = Number(jsonobj.BSTAR); + var inclo = Number(jsonobj.INCLINATION) * deg2rad; + var nodeo = Number(jsonobj.RA_OF_ASC_NODE) * deg2rad; + var ecco = Number(jsonobj.ECCENTRICITY); + var argpo = Number(jsonobj.ARG_OF_PERICENTER) * deg2rad; + var mo = Number(jsonobj.MEAN_ANOMALY) * deg2rad; + var no = Number(jsonobj.MEAN_MOTION) / xpdotp; + // ---------------------------------------------------------------- + // find sgp4epoch time of element set + // remember that sgp4 uses units of days from 0 jan 1950 (sgp4epoch) + // and minutes from the epoch (time) + // ---------------------------------------------------------------- + var mdhmsResult = days2mdhms(year, epochdays); + var mon = mdhmsResult.mon, + day = mdhmsResult.day, + hr = mdhmsResult.hr, + minute = mdhmsResult.minute, + sec = mdhmsResult.sec; + var jdsatepoch = jday(year, mon, day, hr, minute, sec); + var satrec = { + error: error, + satnum: satnum, + epochyr: epochyr, + epochdays: epochdays, + ndot: ndot, + nddot: nddot, + bstar: bstar, + inclo: inclo, + nodeo: nodeo, + ecco: ecco, + argpo: argpo, + mo: mo, + no: no, + jdsatepoch: jdsatepoch + }; + // ---------------- initialize the orbit at sgp4epoch ------------------- + sgp4init(satrec, { + opsmode: opsmode, + satn: satrec.satnum, + epoch: satrec.jdsatepoch - 2433281.5, + xbstar: satrec.bstar, + xecco: satrec.ecco, + xargpo: satrec.argpo, + xinclo: satrec.inclo, + xmo: satrec.mo, + xno: satrec.no, + xnodeo: satrec.nodeo + }); + return satrec; +} + +function propagate(satrec) { + for (var _len = arguments.length, jdayArgs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + jdayArgs[_key - 1] = arguments[_key]; + } + // Return a position and velocity vector for a given date and time. + var j = jday.apply(void 0, jdayArgs); + var m = (j - satrec.jdsatepoch) * minutesPerDay; + return sgp4(satrec, m); +} + +var earthRotation = 7.292115E-5; +var c = 299792.458; // Speed of light in km/s +/** + * Negative range rate means the satellite is moving towards the observer and + * its frequency is shifted higher because 1 minus a negative range rate is + * positive. If the range rate is positive, the satellite is moving away from + * the observer and its frequency is shifted lower. + */ +function dopplerFactor(observerCoordsEcf, positionEcf, velocityEcf) { + var rangeX = positionEcf.x - observerCoordsEcf.x; + var rangeY = positionEcf.y - observerCoordsEcf.y; + var rangeZ = positionEcf.z - observerCoordsEcf.z; + var length = Math.sqrt(Math.pow(rangeX, 2) + Math.pow(rangeY, 2) + Math.pow(rangeZ, 2)); + var rangeVel = { + x: velocityEcf.x + earthRotation * observerCoordsEcf.y, + y: velocityEcf.y - earthRotation * observerCoordsEcf.x, + z: velocityEcf.z + }; + var rangeRate = (rangeX * rangeVel.x + rangeY * rangeVel.y + rangeZ * rangeVel.z) / length; + return 1 - rangeRate / c; +} + +function radiansToDegrees(radians) { + return radians * rad2deg; +} +function degreesToRadians(degrees) { + return degrees * deg2rad; +} +function degreesLat(radians) { + if (radians < -pi / 2 || radians > pi / 2) { + throw new RangeError('Latitude radians must be in range [-pi/2; pi/2].'); + } + return radiansToDegrees(radians); +} +function degreesLong(radians) { + if (radians < -pi || radians > pi) { + throw new RangeError('Longitude radians must be in range [-pi; pi].'); + } + return radiansToDegrees(radians); +} +function radiansLat(degrees) { + if (degrees < -90 || degrees > 90) { + throw new RangeError('Latitude degrees must be in range [-90; 90].'); + } + return degreesToRadians(degrees); +} +function radiansLong(degrees) { + if (degrees < -180 || degrees > 180) { + throw new RangeError('Longitude degrees must be in range [-180; 180].'); + } + return degreesToRadians(degrees); +} +function geodeticToEcf(_ref) { + var longitude = _ref.longitude, + latitude = _ref.latitude, + height = _ref.height; + var a = 6378.137; + var b = 6356.7523142; + var f = (a - b) / a; + var e2 = 2 * f - f * f; + var normal = a / Math.sqrt(1 - e2 * (Math.sin(latitude) * Math.sin(latitude))); + var x = (normal + height) * Math.cos(latitude) * Math.cos(longitude); + var y = (normal + height) * Math.cos(latitude) * Math.sin(longitude); + var z = (normal * (1 - e2) + height) * Math.sin(latitude); + return { + x: x, + y: y, + z: z + }; +} +function eciToGeodetic(eci, gmst) { + // http://www.celestrak.com/columns/v02n03/ + var a = 6378.137; + var b = 6356.7523142; + var R = Math.sqrt(eci.x * eci.x + eci.y * eci.y); + var f = (a - b) / a; + var e2 = 2 * f - f * f; + var longitude = Math.atan2(eci.y, eci.x) - gmst; + while (longitude < -pi) { + longitude += twoPi; + } + while (longitude > pi) { + longitude -= twoPi; + } + var kmax = 20; + var k = 0; + var latitude = Math.atan2(eci.z, Math.sqrt(eci.x * eci.x + eci.y * eci.y)); + var C; + while (k++ < kmax) { + C = 1 / Math.sqrt(1 - e2 * (Math.sin(latitude) * Math.sin(latitude))); + latitude = Math.atan2(eci.z + a * C * e2 * Math.sin(latitude), R); + } + var height = R / Math.cos(latitude) - a * C; + return { + longitude: longitude, + latitude: latitude, + height: height + }; +} +function ecfToEci(ecf, gmst) { + // ccar.colorado.edu/ASEN5070/handouts/coordsys.doc + // + // [X] [C -S 0][X] + // [Y] = [S C 0][Y] + // [Z]eci [0 0 1][Z]ecf + // + var X = ecf.x * Math.cos(gmst) - ecf.y * Math.sin(gmst); + var Y = ecf.x * Math.sin(gmst) + ecf.y * Math.cos(gmst); + var Z = ecf.z; + return { + x: X, + y: Y, + z: Z + }; +} +function eciToEcf(eci, gmst) { + // ccar.colorado.edu/ASEN5070/handouts/coordsys.doc + // + // [X] [C -S 0][X] + // [Y] = [S C 0][Y] + // [Z]eci [0 0 1][Z]ecf + // + // + // Inverse: + // [X] [C S 0][X] + // [Y] = [-S C 0][Y] + // [Z]ecf [0 0 1][Z]eci + var x = eci.x * Math.cos(gmst) + eci.y * Math.sin(gmst); + var y = eci.x * -Math.sin(gmst) + eci.y * Math.cos(gmst); + var z = eci.z; + return { + x: x, + y: y, + z: z + }; +} +function topocentric(observerGeodetic, satelliteEcf) { + // http://www.celestrak.com/columns/v02n02/ + // TS Kelso's method, except I'm using ECF frame + // and he uses ECI. + var longitude = observerGeodetic.longitude, + latitude = observerGeodetic.latitude; + var observerEcf = geodeticToEcf(observerGeodetic); + var rx = satelliteEcf.x - observerEcf.x; + var ry = satelliteEcf.y - observerEcf.y; + var rz = satelliteEcf.z - observerEcf.z; + var topS = Math.sin(latitude) * Math.cos(longitude) * rx + Math.sin(latitude) * Math.sin(longitude) * ry - Math.cos(latitude) * rz; + var topE = -Math.sin(longitude) * rx + Math.cos(longitude) * ry; + var topZ = Math.cos(latitude) * Math.cos(longitude) * rx + Math.cos(latitude) * Math.sin(longitude) * ry + Math.sin(latitude) * rz; + return { + topS: topS, + topE: topE, + topZ: topZ + }; +} +function topocentricToLookAngles(tc) { + var topS = tc.topS, + topE = tc.topE, + topZ = tc.topZ; + var rangeSat = Math.sqrt(topS * topS + topE * topE + topZ * topZ); + var El = Math.asin(topZ / rangeSat); + var Az = Math.atan2(-topE, topS) + pi; + return { + azimuth: Az, + elevation: El, + rangeSat: rangeSat // Range in km + }; +} +function ecfToLookAngles(observerGeodetic, satelliteEcf) { + var topocentricCoords = topocentric(observerGeodetic, satelliteEcf); + return topocentricToLookAngles(topocentricCoords); +} + +//////////////////////////////////////////////////////////////////////////////////// +/* Line by Line MATLAB-to-Javascript conversion of "sun.mat" from Vallado package */ +//////////////////////////////////////////////////////////////////////////////////// +/* ----------------------------------------------------------------------------- + * + * function sunPos + * + * this function calculates the geocentric equatorial position vector + * the sun given the julian date. this is the low precision formula and + * is valid for years from 1950 to 2050. accuaracy of apparent coordinates + * is 0.01 degrees. notice many of the calculations are performed in + * degrees, and are not changed until later. this is due to the fact that + * the almanac uses degrees exclusively in their formulations. + * + * author : david vallado 719-573-2600 1 mar 2001 + * + * inputs description range / units + * jd - julian date days from 4713 bc + * + * outputs : + * rsun - ijk position vector of the sun au + * rtasc - right ascension rad + * decl - declination rad + * + * coupling : + * - + * + * references : + * VALLADO, DAVID A. (2022) ‘Computer software in MATLAB’, in Fundamentals of astrodynamics and applications. 5th edn. + * Computer software in MATLAB: http://celestrak.org/software/vallado-sw.php + * --------------------------------------------------------------------------- */ +function sunPos(jday) { + // ------------------------- implementation ----------------- + // ------------------- initialize values -------------------- + var tut1 = (jday - 2451545) / 36525; + var meanlong = (280.460 + 36000.77 * tut1) % 360; //deg + var ttdb = tut1; // is this declaration required instead of replacing `ttdb` with `tut1` + var meananomaly = (357.5277233 + 35999.05034 * ttdb * deg2rad) % twoPi; //rad + if (meananomaly < 0) { + meananomaly += twoPi; + } + var eclplong_raw = (meanlong + 1.914666471 * Math.sin(meananomaly) + 0.019994643 * Math.sin(2.0 * meananomaly)) % 360.0 * deg2rad; //rad + var obliquity = (23.439291 - 0.0130042 * ttdb) * deg2rad; //rad + // --------- find magnitude of sun vector, and it's components ------ + var magr = 1.000140612 - 0.016708617 * Math.cos(meananomaly) - 0.000139589 * Math.cos(2.0 * meananomaly); // in au's + var rsun = [magr * Math.cos(eclplong_raw), magr * Math.cos(obliquity) * Math.sin(eclplong_raw), magr * Math.sin(obliquity) * Math.sin(eclplong_raw)]; + var rtasc_raw = Math.atan(Math.cos(obliquity) * Math.tan(eclplong_raw)); + var rtasc = rtasc_raw; + if (Math.abs(eclplong_raw - rtasc) > pi * 0.5) { + rtasc += 0.5 * pi * Math.round((eclplong_raw - rtasc_raw) / (0.5 * pi)); + } + var decl = Math.asin(Math.sin(obliquity) * Math.sin(eclplong_raw)); + return { + rsun: rsun, + rtasc: rtasc, + decl: decl + }; +} +/* Original MATLAB code for Sun position from Vallado package (sun.mat) */ +/* +function [rsun,rtasc,decl] = sun ( jd ); + + twopi = 2.0*pi; + deg2rad = pi/180.0; + show = 'n'; + + % ------------------------- implementation ----------------- + % ------------------- initialize values -------------------- + tut1= ( jd - 2451545.0 )/ 36525.0; + + if show == 'y' + fprintf(1,'tut1 %14.9f \n',tut1); + end + + meanlong= 280.460 + 36000.77*tut1; + meanlong= rem( meanlong,360.0 ); %deg + + ttdb= tut1; + meananomaly= 357.5277233 + 35999.05034 *ttdb; + meananomaly= rem( meananomaly*deg2rad,twopi ); %rad + if ( meananomaly < 0.0 ) + meananomaly= twopi + meananomaly; + end + + eclplong_raw= meanlong + 1.914666471 *sin(meananomaly) ... + + 0.019994643 *sin(2.0 *meananomaly); %deg + eclplong_raw= rem( eclplong_raw,360.0 ); %deg + + obliquity= 23.439291 - 0.0130042 *ttdb; %deg + + eclplong_raw = eclplong_raw *deg2rad; + obliquity= obliquity *deg2rad; + + % --------- find magnitude of sun vector, ) components ------ + magr= 1.000140612 - 0.016708617 *cos( meananomaly ) ... + - 0.000139589 *cos( 2.0 *meananomaly ); % in au's + + rsun(1)= magr*cos( eclplong_raw ); + rsun(2)= magr*cos(obliquity)*sin(eclplong_raw); + rsun(3)= magr*sin(obliquity)*sin(eclplong_raw); + + if show == 'y' + fprintf(1,'meanlon %11.6f meanan %11.6f eclplon %11.6f obli %11.6f \n', ... + meanlong,meananomaly/deg2rad,eclplong_raw/deg2rad,obliquity/deg2rad); + fprintf(1,'rs %11.9f %11.9f %11.9f \n',rsun); + fprintf(1,'magr %14.7f \n',magr); + end + + rtasc= atan( cos(obliquity)*tan(eclplong_raw) ); + + % --- check that rtasc is in the same quadrant as eclplong_raw ---- + if ( eclplong_raw < 0.0 ) + eclplong_raw= eclplong_raw + twopi; % make sure it's in 0 to 2pi range + end + if ( abs( eclplong_raw-rtasc ) > pi*0.5 ) + rtasc= rtasc + 0.5 *pi*round( (eclplong_raw-rtasc)/(0.5 *pi)); + end + decl = asin( sin(obliquity)*sin(eclplong_raw) ); +*/ + +export { SatRecError, constants, degreesLat, degreesLong, degreesToRadians, dopplerFactor, ecfToEci, ecfToLookAngles, eciToEcf, eciToGeodetic, geodeticToEcf, gstime, invjday, jday, json2satrec, propagate, radiansLat, radiansLong, radiansToDegrees, sgp4, sunPos, twoline2satrec }; diff --git a/node_modules/satellite.js/dist/satellite.js b/node_modules/satellite.js/dist/satellite.js new file mode 100644 index 0000000..3028abf --- /dev/null +++ b/node_modules/satellite.js/dist/satellite.js @@ -0,0 +1,3151 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.satellite = factory()); +})(this, (function () { 'use strict'; + + var pi = Math.PI; + var twoPi = pi * 2; + var deg2rad = pi / 180.0; + var rad2deg = 180 / pi; + var minutesPerDay = 1440.0; + var mu = 398600.8; // in km3 / s2 + var earthRadius = 6378.135; // in km + var xke = 60.0 / Math.sqrt(earthRadius * earthRadius * earthRadius / mu); + var vkmpersec = earthRadius * xke / 60.0; + var tumin = 1.0 / xke; + var j2 = 0.001082616; + var j3 = -0.00000253881; + var j4 = -0.00000165597; + var j3oj2 = j3 / j2; + var x2o3 = 2.0 / 3.0; + var xpdotp = 1440.0 / (2.0 * pi); // 229.1831180523293; + + var constants = /*#__PURE__*/Object.freeze({ + __proto__: null, + deg2rad: deg2rad, + earthRadius: earthRadius, + j2: j2, + j3: j3, + j3oj2: j3oj2, + j4: j4, + minutesPerDay: minutesPerDay, + mu: mu, + pi: pi, + rad2deg: rad2deg, + tumin: tumin, + twoPi: twoPi, + vkmpersec: vkmpersec, + x2o3: x2o3, + xke: xke, + xpdotp: xpdotp + }); + + /* ----------------------------------------------------------------------------- + * + * procedure days2mdhms + * + * this procedure converts the day of the year, days, to the equivalent month + * day, hour, minute and second. + * + * algorithm : set up array for the number of days per month + * find leap year - use 1900 because 2000 is a leap year + * loop through a temp value while the value is < the days + * perform int conversions to the correct day and month + * convert remainder into h m s using type conversions + * + * author : david vallado 719-573-2600 1 mar 2001 + * + * inputs description range / units + * year - year 1900 .. 2100 + * days - julian day of the year 0.0 .. 366.0 + * + * outputs : + * mon - month 1 .. 12 + * day - day 1 .. 28,29,30,31 + * hr - hour 0 .. 23 + * min - minute 0 .. 59 + * sec - second 0.0 .. 59.999 + * + * locals : + * dayofyr - day of year + * temp - temporary extended values + * inttemp - temporary int value + * i - index + * lmonth[12] - int array containing the number of days per month + * + * coupling : + * none. + * --------------------------------------------------------------------------- */ + function days2mdhms(year, days) { + var lmonth = [31, year % 4 === 0 ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + var dayofyr = Math.floor(days); + // ----------------- find month and day of month ---------------- + var i = 1; + var inttemp = 0; + // i starts from 1 so no null check is needed + while (dayofyr > inttemp + lmonth[i - 1] && i < 12) { + inttemp += lmonth[i - 1]; + i += 1; + } + var mon = i; + var day = dayofyr - inttemp; + // ----------------- find hours minutes and seconds ------------- + var temp = (days - dayofyr) * 24.0; + var hr = Math.floor(temp); + temp = (temp - hr) * 60.0; + var minute = Math.floor(temp); + var sec = (temp - minute) * 60.0; + return { + mon: mon, + day: day, + hr: hr, + minute: minute, + sec: sec + }; + } + /* ----------------------------------------------------------------------------- + * + * procedure jday + * + * this procedure finds the julian date given the year, month, day, and time. + * the julian date is defined by each elapsed day since noon, jan 1, 4713 bc. + * + * algorithm : calculate the answer in one step for efficiency + * + * author : david vallado 719-573-2600 1 mar 2001 + * + * inputs description range / units + * year - year 1900 .. 2100 + * mon - month 1 .. 12 + * day - day 1 .. 28,29,30,31 + * hr - universal time hour 0 .. 23 + * min - universal time min 0 .. 59 + * sec - universal time sec 0.0 .. 59.999 + * + * outputs : + * jd - julian date days from 4713 bc + * + * locals : + * none. + * + * coupling : + * none. + * + * references : + * vallado 2007, 189, alg 14, ex 3-14 + * + * --------------------------------------------------------------------------- */ + function jdayInternal(year, mon, day, hr, minute, sec) { + var msec = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0; + return 367.0 * year - Math.floor(7 * (year + Math.floor((mon + 9) / 12.0)) * 0.25) + Math.floor(275 * mon / 9.0) + day + 1721013.5 + ((msec / 60000 + sec / 60.0 + minute) / 60.0 + hr) / 24.0 // ut in days + // # - 0.5*sgn(100.0*year + mon - 190002.5) + 0.5; + ; + } + function jday(yearOrDate, mon, day, hr, minute, sec) { + var msec = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0; + if (yearOrDate instanceof Date) { + var date = yearOrDate; + return jdayInternal(date.getUTCFullYear(), date.getUTCMonth() + 1, + // Note, this function requires months in range 1-12. + date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds()); + } + return jdayInternal(yearOrDate, mon, day, hr, minute, sec, msec); + } + function invjday(jd, asArray) { + // --------------- find year and days of the year - + var temp = jd - 2415019.5; + var tu = temp / 365.25; + var year = 1900 + Math.floor(tu); + var leapyrs = Math.floor((year - 1901) * 0.25); + // optional nudge by 8.64x10-7 sec to get even outputs + var days = temp - ((year - 1900) * 365.0 + leapyrs) + 0.00000000001; + // ------------ check for case of beginning of a year ----------- + if (days < 1.0) { + year -= 1; + leapyrs = Math.floor((year - 1901) * 0.25); + days = temp - ((year - 1900) * 365.0 + leapyrs); + } + // ----------------- find remaing data ------------------------- + var mdhms = days2mdhms(year, days); + var mon = mdhms.mon, + day = mdhms.day, + hr = mdhms.hr, + minute = mdhms.minute; + var sec = mdhms.sec - 0.00000086400; + if (asArray) { + return [year, mon, day, hr, minute, Math.floor(sec)]; + } + return new Date(Date.UTC(year, mon - 1, day, hr, minute, Math.floor(sec))); + } + + /* ----------------------------------------------------------------------------- + * + * procedure dpper + * + * this procedure provides deep space long period periodic contributions + * to the mean elements. by design, these periodics are zero at epoch. + * this used to be dscom which included initialization, but it's really a + * recurring function. + * + * author : david vallado 719-573-2600 28 jun 2005 + * + * inputs : + * e3 - + * ee2 - + * peo - + * pgho - + * pho - + * pinco - + * plo - + * se2 , se3 , sgh2, sgh3, sgh4, sh2, sh3, si2, si3, sl2, sl3, sl4 - + * t - + * xh2, xh3, xi2, xi3, xl2, xl3, xl4 - + * zmol - + * zmos - + * ep - eccentricity 0.0 - 1.0 + * inclo - inclination - needed for lyddane modification + * nodep - right ascension of ascending node + * argpp - argument of perigee + * mp - mean anomaly + * + * outputs : + * ep - eccentricity 0.0 - 1.0 + * inclp - inclination + * nodep - right ascension of ascending node + * argpp - argument of perigee + * mp - mean anomaly + * + * locals : + * alfdp - + * betdp - + * cosip , sinip , cosop , sinop , + * dalf - + * dbet - + * dls - + * f2, f3 - + * pe - + * pgh - + * ph - + * pinc - + * pl - + * sel , ses , sghl , sghs , shl , shs , sil , sinzf , sis , + * sll , sls + * xls - + * xnoh - + * zf - + * zm - + * + * coupling : + * none. + * + * references : + * hoots, roehrich, norad spacetrack report #3 1980 + * hoots, norad spacetrack report #6 1986 + * hoots, schumacher and glover 2004 + * vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ + function dpper(satrec, options) { + var e3 = satrec.e3, + ee2 = satrec.ee2, + peo = satrec.peo, + pgho = satrec.pgho, + pho = satrec.pho, + pinco = satrec.pinco, + plo = satrec.plo, + se2 = satrec.se2, + se3 = satrec.se3, + sgh2 = satrec.sgh2, + sgh3 = satrec.sgh3, + sgh4 = satrec.sgh4, + sh2 = satrec.sh2, + sh3 = satrec.sh3, + si2 = satrec.si2, + si3 = satrec.si3, + sl2 = satrec.sl2, + sl3 = satrec.sl3, + sl4 = satrec.sl4, + t = satrec.t, + xgh2 = satrec.xgh2, + xgh3 = satrec.xgh3, + xgh4 = satrec.xgh4, + xh2 = satrec.xh2, + xh3 = satrec.xh3, + xi2 = satrec.xi2, + xi3 = satrec.xi3, + xl2 = satrec.xl2, + xl3 = satrec.xl3, + xl4 = satrec.xl4, + zmol = satrec.zmol, + zmos = satrec.zmos; + var init = options.init, + opsmode = options.opsmode; + var ep = options.ep, + inclp = options.inclp, + nodep = options.nodep, + argpp = options.argpp, + mp = options.mp; + // Copy satellite attributes into local variables for convenience + // and symmetry in writing formulae. + var alfdp; + var betdp; + var cosip; + var sinip; + var cosop; + var sinop; + var dalf; + var dbet; + var dls; + var f2; + var f3; + var pe; + var pgh; + var ph; + var pinc; + var pl; + var sinzf; + var xls; + var xnoh; + var zf; + var zm; + // ---------------------- constants ----------------------------- + var zns = 1.19459e-5; + var zes = 0.01675; + var znl = 1.5835218e-4; + var zel = 0.05490; + // --------------- calculate time varying periodics ----------- + zm = zmos + zns * t; + // be sure that the initial call has time set to zero + if (init === 'y') { + zm = zmos; + } + zf = zm + 2.0 * zes * Math.sin(zm); + sinzf = Math.sin(zf); + f2 = 0.5 * sinzf * sinzf - 0.25; + f3 = -0.5 * sinzf * Math.cos(zf); + var ses = se2 * f2 + se3 * f3; + var sis = si2 * f2 + si3 * f3; + var sls = sl2 * f2 + sl3 * f3 + sl4 * sinzf; + var sghs = sgh2 * f2 + sgh3 * f3 + sgh4 * sinzf; + var shs = sh2 * f2 + sh3 * f3; + zm = zmol + znl * t; + if (init === 'y') { + zm = zmol; + } + zf = zm + 2.0 * zel * Math.sin(zm); + sinzf = Math.sin(zf); + f2 = 0.5 * sinzf * sinzf - 0.25; + f3 = -0.5 * sinzf * Math.cos(zf); + var sel = ee2 * f2 + e3 * f3; + var sil = xi2 * f2 + xi3 * f3; + var sll = xl2 * f2 + xl3 * f3 + xl4 * sinzf; + var sghl = xgh2 * f2 + xgh3 * f3 + xgh4 * sinzf; + var shll = xh2 * f2 + xh3 * f3; + pe = ses + sel; + pinc = sis + sil; + pl = sls + sll; + pgh = sghs + sghl; + ph = shs + shll; + if (init === 'n') { + pe -= peo; + pinc -= pinco; + pl -= plo; + pgh -= pgho; + ph -= pho; + inclp += pinc; + ep += pe; + sinip = Math.sin(inclp); + cosip = Math.cos(inclp); + /* ----------------- apply periodics directly ------------ */ + // sgp4fix for lyddane choice + // strn3 used original inclination - this is technically feasible + // gsfc used perturbed inclination - also technically feasible + // probably best to readjust the 0.2 limit value and limit discontinuity + // 0.2 rad = 11.45916 deg + // use next line for original strn3 approach and original inclination + // if (inclo >= 0.2) + // use next line for gsfc version and perturbed inclination + if (inclp >= 0.2) { + ph /= sinip; + pgh -= cosip * ph; + argpp += pgh; + nodep += ph; + mp += pl; + } else { + // ---- apply periodics with lyddane modification ---- + sinop = Math.sin(nodep); + cosop = Math.cos(nodep); + alfdp = sinip * sinop; + betdp = sinip * cosop; + dalf = ph * cosop + pinc * cosip * sinop; + dbet = -ph * sinop + pinc * cosip * cosop; + alfdp += dalf; + betdp += dbet; + nodep %= twoPi; + // sgp4fix for afspc written intrinsic functions + // nodep used without a trigonometric function ahead + if (nodep < 0.0 && opsmode === 'a') { + nodep += twoPi; + } + xls = mp + argpp + cosip * nodep; + dls = pl + pgh - pinc * nodep * sinip; + xls += dls; + xnoh = nodep; + nodep = Math.atan2(alfdp, betdp); + // sgp4fix for afspc written intrinsic functions + // nodep used without a trigonometric function ahead + if (nodep < 0.0 && opsmode === 'a') { + nodep += twoPi; + } + if (Math.abs(xnoh - nodep) > pi) { + if (nodep < xnoh) { + nodep += twoPi; + } else { + nodep -= twoPi; + } + } + mp += pl; + argpp = xls - mp - cosip * nodep; + } + } + return { + ep: ep, + inclp: inclp, + nodep: nodep, + argpp: argpp, + mp: mp + }; + } + + /*----------------------------------------------------------------------------- + * + * procedure dscom + * + * this procedure provides deep space common items used by both the secular + * and periodics subroutines. input is provided as shown. this routine + * used to be called dpper, but the functions inside weren't well organized. + * + * author : david vallado 719-573-2600 28 jun 2005 + * + * inputs : + * epoch - + * ep - eccentricity + * argpp - argument of perigee + * tc - + * inclp - inclination + * nodep - right ascension of ascending node + * np - mean motion + * + * outputs : + * sinim , cosim , sinomm , cosomm , snodm , cnodm + * day - + * e3 - + * ee2 - + * em - eccentricity + * emsq - eccentricity squared + * gam - + * peo - + * pgho - + * pho - + * pinco - + * plo - + * rtemsq - + * se2, se3 - + * sgh2, sgh3, sgh4 - + * sh2, sh3, si2, si3, sl2, sl3, sl4 - + * s1, s2, s3, s4, s5, s6, s7 - + * ss1, ss2, ss3, ss4, ss5, ss6, ss7, sz1, sz2, sz3 - + * sz11, sz12, sz13, sz21, sz22, sz23, sz31, sz32, sz33 - + * xgh2, xgh3, xgh4, xh2, xh3, xi2, xi3, xl2, xl3, xl4 - + * nm - mean motion + * z1, z2, z3, z11, z12, z13, z21, z22, z23, z31, z32, z33 - + * zmol - + * zmos - + * + * locals : + * a1, a2, a3, a4, a5, a6, a7, a8, a9, a10 - + * betasq - + * cc - + * ctem, stem - + * x1, x2, x3, x4, x5, x6, x7, x8 - + * xnodce - + * xnoi - + * zcosg , zsing , zcosgl , zsingl , zcosh , zsinh , zcoshl , zsinhl , + * zcosi , zsini , zcosil , zsinil , + * zx - + * zy - + * + * coupling : + * none. + * + * references : + * hoots, roehrich, norad spacetrack report #3 1980 + * hoots, norad spacetrack report #6 1986 + * hoots, schumacher and glover 2004 + * vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ + function dscom(options) { + var epoch = options.epoch, + ep = options.ep, + argpp = options.argpp, + tc = options.tc, + inclp = options.inclp, + nodep = options.nodep, + np = options.np; + var a1; + var a2; + var a3; + var a4; + var a5; + var a6; + var a7; + var a8; + var a9; + var a10; + var cc; + var x1; + var x2; + var x3; + var x4; + var x5; + var x6; + var x7; + var x8; + var zcosg; + var zsing; + var zcosh; + var zsinh; + var zcosi; + var zsini; + var ss1; + var ss2; + var ss3; + var ss4; + var ss5; + var ss6; + var ss7; + var sz1; + var sz2; + var sz3; + var sz11; + var sz12; + var sz13; + var sz21; + var sz22; + var sz23; + var sz31; + var sz32; + var sz33; + var s1; + var s2; + var s3; + var s4; + var s5; + var s6; + var s7; + var z1; + var z2; + var z3; + var z11; + var z12; + var z13; + var z21; + var z22; + var z23; + var z31; + var z32; + var z33; + // -------------------------- constants ------------------------- + var zes = 0.01675; + var zel = 0.05490; + var c1ss = 2.9864797e-6; + var c1l = 4.7968065e-7; + var zsinis = 0.39785416; + var zcosis = 0.91744867; + var zcosgs = 0.1945905; + var zsings = -0.98088458; + // --------------------- local variables ------------------------ + var nm = np; + var em = ep; + var snodm = Math.sin(nodep); + var cnodm = Math.cos(nodep); + var sinomm = Math.sin(argpp); + var cosomm = Math.cos(argpp); + var sinim = Math.sin(inclp); + var cosim = Math.cos(inclp); + var emsq = em * em; + var betasq = 1.0 - emsq; + var rtemsq = Math.sqrt(betasq); + // ----------------- initialize lunar solar terms --------------- + var peo = 0.0; + var pinco = 0.0; + var plo = 0.0; + var pgho = 0.0; + var pho = 0.0; + var day = epoch + 18261.5 + tc / 1440.0; + var xnodce = (4.5236020 - 9.2422029e-4 * day) % twoPi; + var stem = Math.sin(xnodce); + var ctem = Math.cos(xnodce); + var zcosil = 0.91375164 - 0.03568096 * ctem; + var zsinil = Math.sqrt(1.0 - zcosil * zcosil); + var zsinhl = 0.089683511 * stem / zsinil; + var zcoshl = Math.sqrt(1.0 - zsinhl * zsinhl); + var gam = 5.8351514 + 0.0019443680 * day; + var zx = 0.39785416 * stem / zsinil; + var zy = zcoshl * ctem + 0.91744867 * zsinhl * stem; + zx = Math.atan2(zx, zy); + zx += gam - xnodce; + var zcosgl = Math.cos(zx); + var zsingl = Math.sin(zx); + // ------------------------- do solar terms --------------------- + zcosg = zcosgs; + zsing = zsings; + zcosi = zcosis; + zsini = zsinis; + zcosh = cnodm; + zsinh = snodm; + cc = c1ss; + var xnoi = 1.0 / nm; + var lsflg = 0; + while (lsflg < 2) { + lsflg += 1; + a1 = zcosg * zcosh + zsing * zcosi * zsinh; + a3 = -zsing * zcosh + zcosg * zcosi * zsinh; + a7 = -zcosg * zsinh + zsing * zcosi * zcosh; + a8 = zsing * zsini; + a9 = zsing * zsinh + zcosg * zcosi * zcosh; + a10 = zcosg * zsini; + a2 = cosim * a7 + sinim * a8; + a4 = cosim * a9 + sinim * a10; + a5 = -sinim * a7 + cosim * a8; + a6 = -sinim * a9 + cosim * a10; + x1 = a1 * cosomm + a2 * sinomm; + x2 = a3 * cosomm + a4 * sinomm; + x3 = -a1 * sinomm + a2 * cosomm; + x4 = -a3 * sinomm + a4 * cosomm; + x5 = a5 * sinomm; + x6 = a6 * sinomm; + x7 = a5 * cosomm; + x8 = a6 * cosomm; + z31 = 12.0 * x1 * x1 - 3.0 * x3 * x3; + z32 = 24.0 * x1 * x2 - 6.0 * x3 * x4; + z33 = 12.0 * x2 * x2 - 3.0 * x4 * x4; + z1 = 3.0 * (a1 * a1 + a2 * a2) + z31 * emsq; + z2 = 6.0 * (a1 * a3 + a2 * a4) + z32 * emsq; + z3 = 3.0 * (a3 * a3 + a4 * a4) + z33 * emsq; + z11 = -6.0 * a1 * a5 + emsq * (-24.0 * x1 * x7 - 6.0 * x3 * x5); + z12 = -6.0 * (a1 * a6 + a3 * a5) + emsq * (-24.0 * (x2 * x7 + x1 * x8) + -6.0 * (x3 * x6 + x4 * x5)); + z13 = -6.0 * a3 * a6 + emsq * (-24.0 * x2 * x8 - 6.0 * x4 * x6); + z21 = 6.0 * a2 * a5 + emsq * (24.0 * x1 * x5 - 6.0 * x3 * x7); + z22 = 6.0 * (a4 * a5 + a2 * a6) + emsq * (24.0 * (x2 * x5 + x1 * x6) - 6.0 * (x4 * x7 + x3 * x8)); + z23 = 6.0 * a4 * a6 + emsq * (24.0 * x2 * x6 - 6.0 * x4 * x8); + z1 = z1 + z1 + betasq * z31; + z2 = z2 + z2 + betasq * z32; + z3 = z3 + z3 + betasq * z33; + s3 = cc * xnoi; + s2 = -0.5 * s3 / rtemsq; + s4 = s3 * rtemsq; + s1 = -15.0 * em * s4; + s5 = x1 * x3 + x2 * x4; + s6 = x2 * x3 + x1 * x4; + s7 = x2 * x4 - x1 * x3; + // ----------------------- do lunar terms ------------------- + if (lsflg === 1) { + ss1 = s1; + ss2 = s2; + ss3 = s3; + ss4 = s4; + ss5 = s5; + ss6 = s6; + ss7 = s7; + sz1 = z1; + sz2 = z2; + sz3 = z3; + sz11 = z11; + sz12 = z12; + sz13 = z13; + sz21 = z21; + sz22 = z22; + sz23 = z23; + sz31 = z31; + sz32 = z32; + sz33 = z33; + zcosg = zcosgl; + zsing = zsingl; + zcosi = zcosil; + zsini = zsinil; + zcosh = zcoshl * cnodm + zsinhl * snodm; + zsinh = snodm * zcoshl - cnodm * zsinhl; + cc = c1l; + } + } + var zmol = (4.7199672 + (0.22997150 * day - gam)) % twoPi; + var zmos = (6.2565837 + 0.017201977 * day) % twoPi; + // ------------------------ do solar terms ---------------------- + var se2 = 2.0 * ss1 * ss6; + var se3 = 2.0 * ss1 * ss7; + var si2 = 2.0 * ss2 * sz12; + var si3 = 2.0 * ss2 * (sz13 - sz11); + var sl2 = -2.0 * ss3 * sz2; + var sl3 = -2.0 * ss3 * (sz3 - sz1); + var sl4 = -2.0 * ss3 * (-21.0 - 9.0 * emsq) * zes; + var sgh2 = 2.0 * ss4 * sz32; + var sgh3 = 2.0 * ss4 * (sz33 - sz31); + var sgh4 = -18.0 * ss4 * zes; + var sh2 = -2.0 * ss2 * sz22; + var sh3 = -2.0 * ss2 * (sz23 - sz21); + // ------------------------ do lunar terms ---------------------- + var ee2 = 2.0 * s1 * s6; + var e3 = 2.0 * s1 * s7; + var xi2 = 2.0 * s2 * z12; + var xi3 = 2.0 * s2 * (z13 - z11); + var xl2 = -2.0 * s3 * z2; + var xl3 = -2.0 * s3 * (z3 - z1); + var xl4 = -2.0 * s3 * (-21.0 - 9.0 * emsq) * zel; + var xgh2 = 2.0 * s4 * z32; + var xgh3 = 2.0 * s4 * (z33 - z31); + var xgh4 = -18.0 * s4 * zel; + var xh2 = -2.0 * s2 * z22; + var xh3 = -2.0 * s2 * (z23 - z21); + return { + snodm: snodm, + cnodm: cnodm, + sinim: sinim, + cosim: cosim, + sinomm: sinomm, + cosomm: cosomm, + day: day, + e3: e3, + ee2: ee2, + em: em, + emsq: emsq, + gam: gam, + peo: peo, + pgho: pgho, + pho: pho, + pinco: pinco, + plo: plo, + rtemsq: rtemsq, + se2: se2, + se3: se3, + sgh2: sgh2, + sgh3: sgh3, + sgh4: sgh4, + sh2: sh2, + sh3: sh3, + si2: si2, + si3: si3, + sl2: sl2, + sl3: sl3, + sl4: sl4, + s1: s1, + s2: s2, + s3: s3, + s4: s4, + s5: s5, + s6: s6, + s7: s7, + ss1: ss1, + ss2: ss2, + ss3: ss3, + ss4: ss4, + ss5: ss5, + ss6: ss6, + ss7: ss7, + sz1: sz1, + sz2: sz2, + sz3: sz3, + sz11: sz11, + sz12: sz12, + sz13: sz13, + sz21: sz21, + sz22: sz22, + sz23: sz23, + sz31: sz31, + sz32: sz32, + sz33: sz33, + xgh2: xgh2, + xgh3: xgh3, + xgh4: xgh4, + xh2: xh2, + xh3: xh3, + xi2: xi2, + xi3: xi3, + xl2: xl2, + xl3: xl3, + xl4: xl4, + nm: nm, + z1: z1, + z2: z2, + z3: z3, + z11: z11, + z12: z12, + z13: z13, + z21: z21, + z22: z22, + z23: z23, + z31: z31, + z32: z32, + z33: z33, + zmol: zmol, + zmos: zmos + }; + } + + /*----------------------------------------------------------------------------- + * + * procedure dsinit + * + * this procedure provides deep space contributions to mean motion dot due + * to geopotential resonance with half day and one day orbits. + * + * author : david vallado 719-573-2600 28 jun 2005 + * + * inputs : + * cosim, sinim- + * emsq - eccentricity squared + * argpo - argument of perigee + * s1, s2, s3, s4, s5 - + * ss1, ss2, ss3, ss4, ss5 - + * sz1, sz3, sz11, sz13, sz21, sz23, sz31, sz33 - + * t - time + * tc - + * gsto - greenwich sidereal time rad + * mo - mean anomaly + * mdot - mean anomaly dot (rate) + * no - mean motion + * nodeo - right ascension of ascending node + * nodedot - right ascension of ascending node dot (rate) + * xpidot - + * z1, z3, z11, z13, z21, z23, z31, z33 - + * eccm - eccentricity + * argpm - argument of perigee + * inclm - inclination + * mm - mean anomaly + * xn - mean motion + * nodem - right ascension of ascending node + * + * outputs : + * em - eccentricity + * argpm - argument of perigee + * inclm - inclination + * mm - mean anomaly + * nm - mean motion + * nodem - right ascension of ascending node + * irez - flag for resonance 0-none, 1-one day, 2-half day + * atime - + * d2201, d2211, d3210, d3222, d4410, d4422, d5220, d5232, d5421, d5433 - + * dedt - + * didt - + * dmdt - + * dndt - + * dnodt - + * domdt - + * del1, del2, del3 - + * ses , sghl , sghs , sgs , shl , shs , sis , sls + * theta - + * xfact - + * xlamo - + * xli - + * xni + * + * locals : + * ainv2 - + * aonv - + * cosisq - + * eoc - + * f220, f221, f311, f321, f322, f330, f441, f442, f522, f523, f542, f543 - + * g200, g201, g211, g300, g310, g322, g410, g422, g520, g521, g532, g533 - + * sini2 - + * temp - + * temp1 - + * theta - + * xno2 - + * + * coupling : + * getgravconst + * + * references : + * hoots, roehrich, norad spacetrack report #3 1980 + * hoots, norad spacetrack report #6 1986 + * hoots, schumacher and glover 2004 + * vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ + function dsinit(options) { + var cosim = options.cosim, + argpo = options.argpo, + s1 = options.s1, + s2 = options.s2, + s3 = options.s3, + s4 = options.s4, + s5 = options.s5, + sinim = options.sinim, + ss1 = options.ss1, + ss2 = options.ss2, + ss3 = options.ss3, + ss4 = options.ss4, + ss5 = options.ss5, + sz1 = options.sz1, + sz3 = options.sz3, + sz11 = options.sz11, + sz13 = options.sz13, + sz21 = options.sz21, + sz23 = options.sz23, + sz31 = options.sz31, + sz33 = options.sz33, + t = options.t, + tc = options.tc, + gsto = options.gsto, + mo = options.mo, + mdot = options.mdot, + no = options.no, + nodeo = options.nodeo, + nodedot = options.nodedot, + xpidot = options.xpidot, + z1 = options.z1, + z3 = options.z3, + z11 = options.z11, + z13 = options.z13, + z21 = options.z21, + z23 = options.z23, + z31 = options.z31, + z33 = options.z33, + ecco = options.ecco, + eccsq = options.eccsq; + var emsq = options.emsq, + em = options.em, + argpm = options.argpm, + inclm = options.inclm, + mm = options.mm, + nm = options.nm, + nodem = options.nodem, + irez = options.irez, + atime = options.atime, + d2201 = options.d2201, + d2211 = options.d2211, + d3210 = options.d3210, + d3222 = options.d3222, + d4410 = options.d4410, + d4422 = options.d4422, + d5220 = options.d5220, + d5232 = options.d5232, + d5421 = options.d5421, + d5433 = options.d5433, + dedt = options.dedt, + didt = options.didt, + dmdt = options.dmdt, + dnodt = options.dnodt, + domdt = options.domdt, + del1 = options.del1, + del2 = options.del2, + del3 = options.del3, + xfact = options.xfact, + xlamo = options.xlamo, + xli = options.xli, + xni = options.xni; + var f220; + var f221; + var f311; + var f321; + var f322; + var f330; + var f441; + var f442; + var f522; + var f523; + var f542; + var f543; + var g200; + var g201; + var g211; + var g300; + var g310; + var g322; + var g410; + var g422; + var g520; + var g521; + var g532; + var g533; + var sini2; + var temp; + var temp1; + var xno2; + var ainv2; + var aonv; + var cosisq; + var eoc; + var q22 = 1.7891679e-6; + var q31 = 2.1460748e-6; + var q33 = 2.2123015e-7; + var root22 = 1.7891679e-6; + var root44 = 7.3636953e-9; + var root54 = 2.1765803e-9; + // eslint-disable-next-line no-loss-of-precision + var rptim = 4.37526908801129966e-3; // equates to 7.29211514668855e-5 rad/sec + var root32 = 3.7393792e-7; + var root52 = 1.1428639e-7; + var znl = 1.5835218e-4; + var zns = 1.19459e-5; + // -------------------- deep space initialization ------------ + irez = 0; + if (nm < 0.0052359877 && nm > 0.0034906585) { + irez = 1; + } + if (nm >= 8.26e-3 && nm <= 9.24e-3 && em >= 0.5) { + irez = 2; + } + // ------------------------ do solar terms ------------------- + var ses = ss1 * zns * ss5; + var sis = ss2 * zns * (sz11 + sz13); + var sls = -zns * ss3 * (sz1 + sz3 - 14.0 - 6.0 * emsq); + var sghs = ss4 * zns * (sz31 + sz33 - 6.0); + var shs = -zns * ss2 * (sz21 + sz23); + // sgp4fix for 180 deg incl + if (inclm < 5.2359877e-2 || inclm > pi - 5.2359877e-2) { + shs = 0.0; + } + if (sinim !== 0.0) { + shs /= sinim; + } + var sgs = sghs - cosim * shs; + // ------------------------- do lunar terms ------------------ + dedt = ses + s1 * znl * s5; + didt = sis + s2 * znl * (z11 + z13); + dmdt = sls - znl * s3 * (z1 + z3 - 14.0 - 6.0 * emsq); + var sghl = s4 * znl * (z31 + z33 - 6.0); + var shll = -znl * s2 * (z21 + z23); + // sgp4fix for 180 deg incl + if (inclm < 5.2359877e-2 || inclm > pi - 5.2359877e-2) { + shll = 0.0; + } + domdt = sgs + sghl; + dnodt = shs; + if (sinim !== 0.0) { + domdt -= cosim / sinim * shll; + dnodt += shll / sinim; + } + // ----------- calculate deep space resonance effects -------- + var dndt = 0.0; + var theta = (gsto + tc * rptim) % twoPi; + em += dedt * t; + inclm += didt * t; + argpm += domdt * t; + nodem += dnodt * t; + mm += dmdt * t; + // sgp4fix for negative inclinations + // the following if statement should be commented out + // if (inclm < 0.0) + // { + // inclm = -inclm; + // argpm = argpm - pi; + // nodem = nodem + pi; + // } + // -------------- initialize the resonance terms ------------- + if (irez !== 0) { + aonv = Math.pow(nm / xke, x2o3); + // ---------- geopotential resonance for 12 hour orbits ------ + if (irez === 2) { + cosisq = cosim * cosim; + var emo = em; + em = ecco; + var emsqo = emsq; + emsq = eccsq; + eoc = em * emsq; + g201 = -0.306 - (em - 0.64) * 0.440; + if (em <= 0.65) { + g211 = 3.616 - 13.2470 * em + 16.2900 * emsq; + g310 = -19.302 + 117.3900 * em - 228.4190 * emsq + 156.5910 * eoc; + g322 = -18.9068 + 109.7927 * em - 214.6334 * emsq + 146.5816 * eoc; + g410 = -41.122 + 242.6940 * em - 471.0940 * emsq + 313.9530 * eoc; + g422 = -146.407 + 841.8800 * em - 1629.014 * emsq + 1083.4350 * eoc; + g520 = -532.114 + 3017.977 * em - 5740.032 * emsq + 3708.2760 * eoc; + } else { + g211 = -72.099 + 331.819 * em - 508.738 * emsq + 266.724 * eoc; + g310 = -346.844 + 1582.851 * em - 2415.925 * emsq + 1246.113 * eoc; + g322 = -342.585 + 1554.908 * em - 2366.899 * emsq + 1215.972 * eoc; + g410 = -1052.797 + 4758.686 * em - 7193.992 * emsq + 3651.957 * eoc; + g422 = -3581.690 + 16178.110 * em - 24462.770 * emsq + 12422.520 * eoc; + if (em > 0.715) { + g520 = -5149.66 + 29936.92 * em - 54087.36 * emsq + 31324.56 * eoc; + } else { + g520 = 1464.74 - 4664.75 * em + 3763.64 * emsq; + } + } + if (em < 0.7) { + g533 = -919.22770 + 4988.6100 * em - 9064.7700 * emsq + 5542.21 * eoc; + g521 = -822.71072 + 4568.6173 * em - 8491.4146 * emsq + 5337.524 * eoc; + g532 = -853.66600 + 4690.2500 * em - 8624.7700 * emsq + 5341.4 * eoc; + } else { + g533 = -37995.780 + 161616.52 * em - 229838.20 * emsq + 109377.94 * eoc; + g521 = -51752.104 + 218913.95 * em - 309468.16 * emsq + 146349.42 * eoc; + g532 = -40023.880 + 170470.89 * em - 242699.48 * emsq + 115605.82 * eoc; + } + sini2 = sinim * sinim; + f220 = 0.75 * (1.0 + 2.0 * cosim + cosisq); + f221 = 1.5 * sini2; + f321 = 1.875 * sinim * (1.0 - 2.0 * cosim - 3.0 * cosisq); + f322 = -1.875 * sinim * (1.0 + 2.0 * cosim - 3.0 * cosisq); + f441 = 35.0 * sini2 * f220; + f442 = 39.3750 * sini2 * sini2; + f522 = 9.84375 * sinim * (sini2 * (1.0 - 2.0 * cosim - 5.0 * cosisq) + 0.33333333 * (-2.0 + 4.0 * cosim + 6.0 * cosisq)); + f523 = sinim * (4.92187512 * sini2 * (-2.0 - 4.0 * cosim + 10.0 * cosisq) + 6.56250012 * (1.0 + 2.0 * cosim - 3.0 * cosisq)); + f542 = 29.53125 * sinim * (2.0 - 8.0 * cosim + cosisq * (-12.0 + 8.0 * cosim + 10.0 * cosisq)); + f543 = 29.53125 * sinim * (-2.0 - 8.0 * cosim + cosisq * (12.0 + 8.0 * cosim - 10.0 * cosisq)); + xno2 = nm * nm; + ainv2 = aonv * aonv; + temp1 = 3.0 * xno2 * ainv2; + temp = temp1 * root22; + d2201 = temp * f220 * g201; + d2211 = temp * f221 * g211; + temp1 *= aonv; + temp = temp1 * root32; + d3210 = temp * f321 * g310; + d3222 = temp * f322 * g322; + temp1 *= aonv; + temp = 2.0 * temp1 * root44; + d4410 = temp * f441 * g410; + d4422 = temp * f442 * g422; + temp1 *= aonv; + temp = temp1 * root52; + d5220 = temp * f522 * g520; + d5232 = temp * f523 * g532; + temp = 2.0 * temp1 * root54; + d5421 = temp * f542 * g521; + d5433 = temp * f543 * g533; + xlamo = (mo + nodeo + nodeo - (theta + theta)) % twoPi; + xfact = mdot + dmdt + 2.0 * (nodedot + dnodt - rptim) - no; + em = emo; + emsq = emsqo; + } + // ---------------- synchronous resonance terms -------------- + if (irez === 1) { + g200 = 1.0 + emsq * (-2.5 + 0.8125 * emsq); + g310 = 1.0 + 2.0 * emsq; + g300 = 1.0 + emsq * (-6.0 + 6.60937 * emsq); + f220 = 0.75 * (1.0 + cosim) * (1.0 + cosim); + f311 = 0.9375 * sinim * sinim * (1.0 + 3.0 * cosim) - 0.75 * (1.0 + cosim); + f330 = 1.0 + cosim; + f330 *= 1.875 * f330 * f330; + del1 = 3.0 * nm * nm * aonv * aonv; + del2 = 2.0 * del1 * f220 * g200 * q22; + del3 = 3.0 * del1 * f330 * g300 * q33 * aonv; + del1 = del1 * f311 * g310 * q31 * aonv; + xlamo = (mo + nodeo + argpo - theta) % twoPi; + xfact = mdot + xpidot + dmdt + domdt + dnodt - (no + rptim); + } + // ------------ for sgp4, initialize the integrator ---------- + xli = xlamo; + xni = no; + atime = 0.0; + nm = no + dndt; + } + return { + em: em, + argpm: argpm, + inclm: inclm, + mm: mm, + nm: nm, + nodem: nodem, + irez: irez, + atime: atime, + d2201: d2201, + d2211: d2211, + d3210: d3210, + d3222: d3222, + d4410: d4410, + d4422: d4422, + d5220: d5220, + d5232: d5232, + d5421: d5421, + d5433: d5433, + dedt: dedt, + didt: didt, + dmdt: dmdt, + dndt: dndt, + dnodt: dnodt, + domdt: domdt, + del1: del1, + del2: del2, + del3: del3, + xfact: xfact, + xlamo: xlamo, + xli: xli, + xni: xni + }; + } + + /* ----------------------------------------------------------------------------- + * + * function gstime + * + * this function finds the greenwich sidereal time. + * + * author : david vallado 719-573-2600 1 mar 2001 + * + * inputs description range / units + * jdut1 - julian date in ut1 days from 4713 bc + * + * outputs : + * gstime - greenwich sidereal time 0 to 2pi rad + * + * locals : + * temp - temporary variable for doubles rad + * tut1 - julian centuries from the + * jan 1, 2000 12 h epoch (ut1) + * + * coupling : + * none + * + * references : + * vallado 2004, 191, eq 3-45 + * --------------------------------------------------------------------------- */ + function gstimeInternal(jdut1) { + var tut1 = (jdut1 - 2451545.0) / 36525.0; + var temp = -6.2e-6 * tut1 * tut1 * tut1 + 0.093104 * tut1 * tut1 + (876600.0 * 3600 + 8640184.812866) * tut1 + 67310.54841; // # sec + temp = temp * deg2rad / 240.0 % twoPi; // 360/86400 = 1/240, to deg, to rad + // ------------------------ check quadrants --------------------- + if (temp < 0.0) { + temp += twoPi; + } + return temp; + } + function gstime(first, month, day, hour, minute, second, millisecond) { + if (first instanceof Date) { + return gstimeInternal(jday(first)); + } else if (month !== undefined) { + return gstimeInternal(jday(first, month, day, hour, minute, second, millisecond)); + } else { + return gstimeInternal(first); + } + } + + /*----------------------------------------------------------------------------- + * + * procedure initl + * + * this procedure initializes the sgp4 propagator. all the initialization is + * consolidated here instead of having multiple loops inside other routines. + * + * author : david vallado 719-573-2600 28 jun 2005 + * + * inputs : + * ecco - eccentricity 0.0 - 1.0 + * epoch - epoch time in days from jan 0, 1950. 0 hr + * inclo - inclination of satellite + * no - mean motion of satellite + * satn - satellite number + * + * outputs : + * ainv - 1.0 / a + * ao - semi major axis + * con41 - + * con42 - 1.0 - 5.0 cos(i) + * cosio - cosine of inclination + * cosio2 - cosio squared + * eccsq - eccentricity squared + * method - flag for deep space 'd', 'n' + * omeosq - 1.0 - ecco * ecco + * posq - semi-parameter squared + * rp - radius of perigee + * rteosq - square root of (1.0 - ecco*ecco) + * sinio - sine of inclination + * gsto - gst at time of observation rad + * no - mean motion of satellite + * + * locals : + * ak - + * d1 - + * del - + * adel - + * po - + * + * coupling : + * getgravconst + * gstime - find greenwich sidereal time from the julian date + * + * references : + * hoots, roehrich, norad spacetrack report #3 1980 + * hoots, norad spacetrack report #6 1986 + * hoots, schumacher and glover 2004 + * vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ + function initl(options) { + var ecco = options.ecco, + epoch = options.epoch, + inclo = options.inclo, + opsmode = options.opsmode; + var no = options.no; + // sgp4fix use old way of finding gst + // ----------------------- earth constants --------------------- + // sgp4fix identify constants and allow alternate values + // ------------- calculate auxillary epoch quantities ---------- + var eccsq = ecco * ecco; + var omeosq = 1.0 - eccsq; + var rteosq = Math.sqrt(omeosq); + var cosio = Math.cos(inclo); + var cosio2 = cosio * cosio; + // ------------------ un-kozai the mean motion ----------------- + var ak = Math.pow(xke / no, x2o3); + var d1 = 0.75 * j2 * (3.0 * cosio2 - 1.0) / (rteosq * omeosq); + var delPrime = d1 / (ak * ak); + var adel = ak * (1.0 - delPrime * delPrime - delPrime * (1.0 / 3.0 + 134.0 * delPrime * delPrime / 81.0)); + delPrime = d1 / (adel * adel); + no /= 1.0 + delPrime; + var ao = Math.pow(xke / no, x2o3); + var sinio = Math.sin(inclo); + var po = ao * omeosq; + var con42 = 1.0 - 5.0 * cosio2; + var con41 = -con42 - cosio2 - cosio2; + var ainv = 1.0 / ao; + var posq = po * po; + var rp = ao * (1.0 - ecco); + var method = 'n'; + // sgp4fix modern approach to finding sidereal time + var gsto; + if (opsmode === 'a') { + // sgp4fix use old way of finding gst + // count integer number of days from 0 jan 1970 + var ts70 = epoch - 7305.0; + var ds70 = Math.floor(ts70 + 1.0e-8); + var tfrac = ts70 - ds70; + // find greenwich location at epoch + var c1 = 1.72027916940703639e-2; // eslint-disable-line no-loss-of-precision + var thgr70 = 1.7321343856509374; // eslint-disable-line no-loss-of-precision + var fk5r = 5.07551419432269442e-15; // eslint-disable-line no-loss-of-precision + var c1p2p = c1 + twoPi; + gsto = (thgr70 + c1 * ds70 + c1p2p * tfrac + ts70 * ts70 * fk5r) % twoPi; + if (gsto < 0.0) { + gsto += twoPi; + } + } else { + gsto = gstime(epoch + 2433281.5); + } + return { + no: no, + method: method, + ainv: ainv, + ao: ao, + con41: con41, + con42: con42, + cosio: cosio, + cosio2: cosio2, + eccsq: eccsq, + omeosq: omeosq, + posq: posq, + rp: rp, + rteosq: rteosq, + sinio: sinio, + gsto: gsto + }; + } + + /*----------------------------------------------------------------------------- + * + * procedure dspace + * + * this procedure provides deep space contributions to mean elements for + * perturbing third body. these effects have been averaged over one + * revolution of the sun and moon. for earth resonance effects, the + * effects have been averaged over no revolutions of the satellite. + * (mean motion) + * + * author : david vallado 719-573-2600 28 jun 2005 + * + * inputs : + * d2201, d2211, d3210, d3222, d4410, d4422, d5220, d5232, d5421, d5433 - + * dedt - + * del1, del2, del3 - + * didt - + * dmdt - + * dnodt - + * domdt - + * irez - flag for resonance 0-none, 1-one day, 2-half day + * argpo - argument of perigee + * argpdot - argument of perigee dot (rate) + * t - time + * tc - + * gsto - gst + * xfact - + * xlamo - + * no - mean motion + * atime - + * em - eccentricity + * ft - + * argpm - argument of perigee + * inclm - inclination + * xli - + * mm - mean anomaly + * xni - mean motion + * nodem - right ascension of ascending node + * + * outputs : + * atime - + * em - eccentricity + * argpm - argument of perigee + * inclm - inclination + * xli - + * mm - mean anomaly + * xni - + * nodem - right ascension of ascending node + * dndt - + * nm - mean motion + * + * locals : + * delt - + * ft - + * theta - + * x2li - + * x2omi - + * xl - + * xldot - + * xnddt - + * xndt - + * xomi - + * + * coupling : + * none - + * + * references : + * hoots, roehrich, norad spacetrack report #3 1980 + * hoots, norad spacetrack report #6 1986 + * hoots, schumacher and glover 2004 + * vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ + function dspace(options) { + var irez = options.irez, + d2201 = options.d2201, + d2211 = options.d2211, + d3210 = options.d3210, + d3222 = options.d3222, + d4410 = options.d4410, + d4422 = options.d4422, + d5220 = options.d5220, + d5232 = options.d5232, + d5421 = options.d5421, + d5433 = options.d5433, + dedt = options.dedt, + del1 = options.del1, + del2 = options.del2, + del3 = options.del3, + didt = options.didt, + dmdt = options.dmdt, + dnodt = options.dnodt, + domdt = options.domdt, + argpo = options.argpo, + argpdot = options.argpdot, + t = options.t, + tc = options.tc, + gsto = options.gsto, + xfact = options.xfact, + xlamo = options.xlamo, + no = options.no; + var atime = options.atime, + em = options.em, + argpm = options.argpm, + inclm = options.inclm, + xli = options.xli, + mm = options.mm, + xni = options.xni, + nodem = options.nodem, + nm = options.nm; + var fasx2 = 0.13130908; + var fasx4 = 2.8843198; + var fasx6 = 0.37448087; + var g22 = 5.7686396; + var g32 = 0.95240898; + var g44 = 1.8014998; + var g52 = 1.0508330; + var g54 = 4.4108898; + // eslint-disable-next-line no-loss-of-precision + var rptim = 4.37526908801129966e-3; // equates to 7.29211514668855e-5 rad/sec + var stepp = 720.0; + var stepn = -720.0; + var step2 = 259200.0; + var delt; + var x2li; + var x2omi; + var xl; + var xldot; + var xnddt; + var xndt; + var xomi; + var dndt = 0.0; + var ft = 0.0; + // ----------- calculate deep space resonance effects ----------- + var theta = (gsto + tc * rptim) % twoPi; + em += dedt * t; + inclm += didt * t; + argpm += domdt * t; + nodem += dnodt * t; + mm += dmdt * t; + // sgp4fix for negative inclinations + // the following if statement should be commented out + // if (inclm < 0.0) + // { + // inclm = -inclm; + // argpm = argpm - pi; + // nodem = nodem + pi; + // } + /* - update resonances : numerical (euler-maclaurin) integration - */ + /* ------------------------- epoch restart ---------------------- */ + // sgp4fix for propagator problems + // the following integration works for negative time steps and periods + // the specific changes are unknown because the original code was so convoluted + // sgp4fix take out atime = 0.0 and fix for faster operation + if (irez !== 0) { + // sgp4fix streamline check + if (atime === 0.0 || t * atime <= 0.0 || Math.abs(t) < Math.abs(atime)) { + atime = 0.0; + xni = no; + xli = xlamo; + } + // sgp4fix move check outside loop + if (t > 0.0) { + delt = stepp; + } else { + delt = stepn; + } + var iretn = 381; // added for do loop + while (iretn === 381) { + // ------------------- dot terms calculated ------------- + // ----------- near - synchronous resonance terms ------- + if (irez !== 2) { + xndt = del1 * Math.sin(xli - fasx2) + del2 * Math.sin(2.0 * (xli - fasx4)) + del3 * Math.sin(3.0 * (xli - fasx6)); + xldot = xni + xfact; + xnddt = del1 * Math.cos(xli - fasx2) + 2.0 * del2 * Math.cos(2.0 * (xli - fasx4)) + 3.0 * del3 * Math.cos(3.0 * (xli - fasx6)); + xnddt *= xldot; + } else { + // --------- near - half-day resonance terms -------- + xomi = argpo + argpdot * atime; + x2omi = xomi + xomi; + x2li = xli + xli; + xndt = d2201 * Math.sin(x2omi + xli - g22) + d2211 * Math.sin(xli - g22) + d3210 * Math.sin(xomi + xli - g32) + d3222 * Math.sin(-xomi + xli - g32) + d4410 * Math.sin(x2omi + x2li - g44) + d4422 * Math.sin(x2li - g44) + d5220 * Math.sin(xomi + xli - g52) + d5232 * Math.sin(-xomi + xli - g52) + d5421 * Math.sin(xomi + x2li - g54) + d5433 * Math.sin(-xomi + x2li - g54); + xldot = xni + xfact; + xnddt = d2201 * Math.cos(x2omi + xli - g22) + d2211 * Math.cos(xli - g22) + d3210 * Math.cos(xomi + xli - g32) + d3222 * Math.cos(-xomi + xli - g32) + d5220 * Math.cos(xomi + xli - g52) + d5232 * Math.cos(-xomi + xli - g52) + 2.0 * (d4410 * Math.cos(x2omi + x2li - g44) + d4422 * Math.cos(x2li - g44) + d5421 * Math.cos(xomi + x2li - g54) + d5433 * Math.cos(-xomi + x2li - g54)); + xnddt *= xldot; + } + // ----------------------- integrator ------------------- + // sgp4fix move end checks to end of routine + if (Math.abs(t - atime) >= stepp) { + iretn = 381; + } else { + ft = t - atime; + iretn = 0; + } + if (iretn === 381) { + xli += xldot * delt + xndt * step2; + xni += xndt * delt + xnddt * step2; + atime += delt; + } + } + nm = xni + xndt * ft + xnddt * ft * ft * 0.5; + xl = xli + xldot * ft + xndt * ft * ft * 0.5; + if (irez !== 1) { + mm = xl - 2.0 * nodem + 2.0 * theta; + dndt = nm - no; + } else { + mm = xl - nodem - argpm + theta; + dndt = nm - no; + } + nm = no + dndt; + } + return { + atime: atime, + em: em, + argpm: argpm, + inclm: inclm, + xli: xli, + mm: mm, + xni: xni, + nodem: nodem, + dndt: dndt, + nm: nm + }; + } + + var SatRecError; + (function (SatRecError) { + /** + * No error, propagation for the last supplied date is successful + */ + SatRecError[SatRecError["None"] = 0] = "None"; + /** + * Mean eccentricity is out of range 0 ≤ e < 1 + */ + SatRecError[SatRecError["MeanEccentricityOutOfRange"] = 1] = "MeanEccentricityOutOfRange"; + /** + * Mean motion has fallen below zero. + */ + SatRecError[SatRecError["MeanMotionBelowZero"] = 2] = "MeanMotionBelowZero"; + /** + * Perturbed eccentricity is out of range 0 ≤ e < 1 + */ + SatRecError[SatRecError["PerturbedEccentricityOutOfRange"] = 3] = "PerturbedEccentricityOutOfRange"; + /** + * Length of the orbit’s semi-latus rectum has fallen below zero. + */ + SatRecError[SatRecError["SemiLatusRectumBelowZero"] = 4] = "SemiLatusRectumBelowZero"; + // 5 is not used + /** + * Orbit has decayed: the computed position is underground. + */ + SatRecError[SatRecError["Decayed"] = 6] = "Decayed"; + })(SatRecError || (SatRecError = {})); + + /*---------------------------------------------------------------------------- + * + * procedure sgp4 + * + * this procedure is the sgp4 prediction model from space command. this is an + * updated and combined version of sgp4 and sdp4, which were originally + * published separately in spacetrack report //3. this version follows the + * methodology from the aiaa paper (2006) describing the history and + * development of the code. + * + * author : david vallado 719-573-2600 28 jun 2005 + * + * inputs : + * satrec - initialised structure from sgp4init() call. + * tsince - time since epoch (minutes) + * + * outputs : + * r - position vector km + * v - velocity km/sec + * return code - non-zero on error. + * 1 - mean elements, ecc >= 1.0 or ecc < -0.001 or a < 0.95 er + * 2 - mean motion less than 0.0 + * 3 - pert elements, ecc < 0.0 or ecc > 1.0 + * 4 - semi-latus rectum < 0.0 + * 5 - epoch elements are sub-orbital + * 6 - satellite has decayed + * + * locals : + * am - + * axnl, aynl - + * betal - + * cosim , sinim , cosomm , sinomm , cnod , snod , cos2u , + * sin2u , coseo1 , sineo1 , cosi , sini , cosip , sinip , + * cosisq , cossu , sinsu , cosu , sinu + * delm - + * delomg - + * dndt - + * eccm - + * emsq - + * ecose - + * el2 - + * eo1 - + * eccp - + * esine - + * argpm - + * argpp - + * omgadf - + * pl - + * r - + * rtemsq - + * rdotl - + * rl - + * rvdot - + * rvdotl - + * su - + * t2 , t3 , t4 , tc + * tem5, temp , temp1 , temp2 , tempa , tempe , templ + * u , ux , uy , uz , vx , vy , vz + * inclm - inclination + * mm - mean anomaly + * nm - mean motion + * nodem - right asc of ascending node + * xinc - + * xincp - + * xl - + * xlm - + * mp - + * xmdf - + * xmx - + * xmy - + * nodedf - + * xnode - + * nodep - + * np - + * + * coupling : + * getgravconst- + * dpper + * dspace + * + * references : + * hoots, roehrich, norad spacetrack report //3 1980 + * hoots, norad spacetrack report //6 1986 + * hoots, schumacher and glover 2004 + * vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ + function sgp4(satrec, tsince) { + var coseo1; + var sineo1; + var cosip; + var sinip; + var cosisq; + var delm; + var delomg; + var eo1; + var argpm; + var argpp; + var su; + var t3; + var t4; + var tc; + var tem5; + var temp; + var tempa; + var tempe; + var templ; + var inclm; + var mm; + var nm; + var nodem; + var xincp; + var xlm; + var mp; + var nodep; + /* ------------------ set mathematical constants --------------- */ + // sgp4fix divisor for divide by zero check on inclination + // the old check used 1.0 + cos(pi-1.0e-9), but then compared it to + // 1.5 e-12, so the threshold was changed to 1.5e-12 for consistency + var temp4 = 1.5e-12; + // --------------------- clear sgp4 error flag ----------------- + satrec.t = tsince; + satrec.error = SatRecError.None; + // ------- update for secular gravity and atmospheric drag ----- + var xmdf = satrec.mo + satrec.mdot * satrec.t; + var argpdf = satrec.argpo + satrec.argpdot * satrec.t; + var nodedf = satrec.nodeo + satrec.nodedot * satrec.t; + argpm = argpdf; + mm = xmdf; + var t2 = satrec.t * satrec.t; + nodem = nodedf + satrec.nodecf * t2; + tempa = 1.0 - satrec.cc1 * satrec.t; + tempe = satrec.bstar * satrec.cc4 * satrec.t; + templ = satrec.t2cof * t2; + if (satrec.isimp !== 1) { + delomg = satrec.omgcof * satrec.t; + // sgp4fix use mutliply for speed instead of pow + var delmtemp = 1.0 + satrec.eta * Math.cos(xmdf); + delm = satrec.xmcof * (delmtemp * delmtemp * delmtemp - satrec.delmo); + temp = delomg + delm; + mm = xmdf + temp; + argpm = argpdf - temp; + t3 = t2 * satrec.t; + t4 = t3 * satrec.t; + tempa = tempa - satrec.d2 * t2 - satrec.d3 * t3 - satrec.d4 * t4; + tempe += satrec.bstar * satrec.cc5 * (Math.sin(mm) - satrec.sinmao); + templ = templ + satrec.t3cof * t3 + t4 * (satrec.t4cof + satrec.t * satrec.t5cof); + } + nm = satrec.no; + var em = satrec.ecco; + inclm = satrec.inclo; + if (satrec.method === 'd') { + tc = satrec.t; + var dspaceOptions = { + irez: satrec.irez, + d2201: satrec.d2201, + d2211: satrec.d2211, + d3210: satrec.d3210, + d3222: satrec.d3222, + d4410: satrec.d4410, + d4422: satrec.d4422, + d5220: satrec.d5220, + d5232: satrec.d5232, + d5421: satrec.d5421, + d5433: satrec.d5433, + dedt: satrec.dedt, + del1: satrec.del1, + del2: satrec.del2, + del3: satrec.del3, + didt: satrec.didt, + dmdt: satrec.dmdt, + dnodt: satrec.dnodt, + domdt: satrec.domdt, + argpo: satrec.argpo, + argpdot: satrec.argpdot, + t: satrec.t, + tc: tc, + gsto: satrec.gsto, + xfact: satrec.xfact, + xlamo: satrec.xlamo, + no: satrec.no, + atime: satrec.atime, + em: em, + argpm: argpm, + inclm: inclm, + xli: satrec.xli, + mm: mm, + xni: satrec.xni, + nodem: nodem, + nm: nm + }; + var dspaceResult = dspace(dspaceOptions); + em = dspaceResult.em; + argpm = dspaceResult.argpm; + inclm = dspaceResult.inclm; + mm = dspaceResult.mm; + nodem = dspaceResult.nodem; + nm = dspaceResult.nm; + } + if (nm <= 0.0) { + // printf("// error nm %f\n", nm); + satrec.error = SatRecError.MeanMotionBelowZero; + // sgp4fix add return + return null; + } + var am = Math.pow(xke / nm, x2o3) * tempa * tempa; + nm = xke / Math.pow(am, 1.5); + em -= tempe; + // fix tolerance for error recognition + // sgp4fix am is fixed from the previous nm check + if (em >= 1.0 || em < -0.001) { + // || (am < 0.95) + // printf("// error em %f\n", em); + satrec.error = SatRecError.MeanEccentricityOutOfRange; + // sgp4fix to return if there is an error in eccentricity + return null; + } + // sgp4fix fix tolerance to avoid a divide by zero + if (em < 1.0e-6) { + em = 1.0e-6; + } + mm += satrec.no * templ; + xlm = mm + argpm + nodem; + nodem %= twoPi; + argpm %= twoPi; + xlm %= twoPi; + mm = (xlm - argpm - nodem) % twoPi; + var meanElements = { + am: am, + em: em, + im: inclm, + Om: nodem, + om: argpm, + mm: mm, + nm: nm + }; + // ----------------- compute extra mean quantities ------------- + var sinim = Math.sin(inclm); + var cosim = Math.cos(inclm); + // -------------------- add lunar-solar periodics -------------- + var ep = em; + xincp = inclm; + argpp = argpm; + nodep = nodem; + mp = mm; + sinip = sinim; + cosip = cosim; + if (satrec.method === 'd') { + var dpperParameters = { + inclo: satrec.inclo, + init: 'n', + ep: ep, + inclp: xincp, + nodep: nodep, + argpp: argpp, + mp: mp, + opsmode: satrec.operationmode + }; + var dpperResult = dpper(satrec, dpperParameters); + ep = dpperResult.ep; + nodep = dpperResult.nodep; + argpp = dpperResult.argpp; + mp = dpperResult.mp; + xincp = dpperResult.inclp; + if (xincp < 0.0) { + xincp = -xincp; + nodep += pi; + argpp -= pi; + } + if (ep < 0.0 || ep > 1.0) { + // printf("// error ep %f\n", ep); + satrec.error = SatRecError.PerturbedEccentricityOutOfRange; + // sgp4fix add return + return null; + } + } + // -------------------- long period periodics ------------------ + if (satrec.method === 'd') { + sinip = Math.sin(xincp); + cosip = Math.cos(xincp); + satrec.aycof = -0.5 * j3oj2 * sinip; + // sgp4fix for divide by zero for xincp = 180 deg + if (Math.abs(cosip + 1.0) > 1.5e-12) { + satrec.xlcof = -0.25 * j3oj2 * sinip * (3.0 + 5.0 * cosip) / (1.0 + cosip); + } else { + satrec.xlcof = -0.25 * j3oj2 * sinip * (3.0 + 5.0 * cosip) / temp4; + } + } + var axnl = ep * Math.cos(argpp); + temp = 1.0 / (am * (1.0 - ep * ep)); + var aynl = ep * Math.sin(argpp) + temp * satrec.aycof; + var xl = mp + argpp + nodep + temp * satrec.xlcof * axnl; + // --------------------- solve kepler's equation --------------- + var u = (xl - nodep) % twoPi; + eo1 = u; + tem5 = 9999.9; + var ktr = 1; + // sgp4fix for kepler iteration + // the following iteration needs better limits on corrections + while (Math.abs(tem5) >= 1.0e-12 && ktr <= 10) { + sineo1 = Math.sin(eo1); + coseo1 = Math.cos(eo1); + tem5 = 1.0 - coseo1 * axnl - sineo1 * aynl; + tem5 = (u - aynl * coseo1 + axnl * sineo1 - eo1) / tem5; + if (Math.abs(tem5) >= 0.95) { + if (tem5 > 0.0) { + tem5 = 0.95; + } else { + tem5 = -0.95; + } + } + eo1 += tem5; + ktr += 1; + } + // ------------- short period preliminary quantities ----------- + var ecose = axnl * coseo1 + aynl * sineo1; + var esine = axnl * sineo1 - aynl * coseo1; + var el2 = axnl * axnl + aynl * aynl; + var pl = am * (1.0 - el2); + if (pl < 0.0) { + // printf("// error pl %f\n", pl); + satrec.error = SatRecError.SemiLatusRectumBelowZero; + // sgp4fix add return + return null; + } + var rl = am * (1.0 - ecose); + var rdotl = Math.sqrt(am) * esine / rl; + var rvdotl = Math.sqrt(pl) / rl; + var betal = Math.sqrt(1.0 - el2); + temp = esine / (1.0 + betal); + var sinu = am / rl * (sineo1 - aynl - axnl * temp); + var cosu = am / rl * (coseo1 - axnl + aynl * temp); + su = Math.atan2(sinu, cosu); + var sin2u = (cosu + cosu) * sinu; + var cos2u = 1.0 - 2.0 * sinu * sinu; + temp = 1.0 / pl; + var temp1 = 0.5 * j2 * temp; + var temp2 = temp1 * temp; + // -------------- update for short period periodics ------------ + if (satrec.method === 'd') { + cosisq = cosip * cosip; + satrec.con41 = 3.0 * cosisq - 1.0; + satrec.x1mth2 = 1.0 - cosisq; + satrec.x7thm1 = 7.0 * cosisq - 1.0; + } + var mrt = rl * (1.0 - 1.5 * temp2 * betal * satrec.con41) + 0.5 * temp1 * satrec.x1mth2 * cos2u; + // sgp4fix for decaying satellites + if (mrt < 1.0) { + // printf("// decay condition %11.6f \n",mrt); + satrec.error = SatRecError.Decayed; + return null; + } + su -= 0.25 * temp2 * satrec.x7thm1 * sin2u; + var xnode = nodep + 1.5 * temp2 * cosip * sin2u; + var xinc = xincp + 1.5 * temp2 * cosip * sinip * cos2u; + var mvt = rdotl - nm * temp1 * satrec.x1mth2 * sin2u / xke; + var rvdot = rvdotl + nm * temp1 * (satrec.x1mth2 * cos2u + 1.5 * satrec.con41) / xke; + // --------------------- orientation vectors ------------------- + var sinsu = Math.sin(su); + var cossu = Math.cos(su); + var snod = Math.sin(xnode); + var cnod = Math.cos(xnode); + var sini = Math.sin(xinc); + var cosi = Math.cos(xinc); + var xmx = -snod * cosi; + var xmy = cnod * cosi; + var ux = xmx * sinsu + cnod * cossu; + var uy = xmy * sinsu + snod * cossu; + var uz = sini * sinsu; + var vx = xmx * cossu - cnod * sinsu; + var vy = xmy * cossu - snod * sinsu; + var vz = sini * cossu; + // --------- position and velocity (in km and km/sec) ---------- + var r = { + x: mrt * ux * earthRadius, + y: mrt * uy * earthRadius, + z: mrt * uz * earthRadius + }; + var v = { + x: (mvt * ux + rvdot * vx) * vkmpersec, + y: (mvt * uy + rvdot * vy) * vkmpersec, + z: (mvt * uz + rvdot * vz) * vkmpersec + }; + return { + position: r, + velocity: v, + meanElements: meanElements + }; + } + + /*----------------------------------------------------------------------------- + * + * procedure sgp4init + * + * this procedure initializes variables for sgp4. + * + * author : david vallado 719-573-2600 28 jun 2005 + * author : david vallado 719-573-2600 28 jun 2005 + * + * inputs : + * opsmode - mode of operation afspc or improved 'a', 'i' + * satn - satellite number + * bstar - sgp4 type drag coefficient kg/m2er + * ecco - eccentricity + * epoch - epoch time in days from jan 0, 1950. 0 hr + * argpo - argument of perigee (output if ds) + * inclo - inclination + * mo - mean anomaly (output if ds) + * no - mean motion + * nodeo - right ascension of ascending node + * + * outputs : + * rec - common values for subsequent calls + * return code - non-zero on error. + * 1 - mean elements, ecc >= 1.0 or ecc < -0.001 or a < 0.95 er + * 2 - mean motion less than 0.0 + * 3 - pert elements, ecc < 0.0 or ecc > 1.0 + * 4 - semi-latus rectum < 0.0 + * 5 - epoch elements are sub-orbital + * 6 - satellite has decayed + * + * locals : + * cnodm , snodm , cosim , sinim , cosomm , sinomm + * cc1sq , cc2 , cc3 + * coef , coef1 + * cosio4 - + * day - + * dndt - + * em - eccentricity + * emsq - eccentricity squared + * eeta - + * etasq - + * gam - + * argpm - argument of perigee + * nodem - + * inclm - inclination + * mm - mean anomaly + * nm - mean motion + * perige - perigee + * pinvsq - + * psisq - + * qzms24 - + * rtemsq - + * s1, s2, s3, s4, s5, s6, s7 - + * sfour - + * ss1, ss2, ss3, ss4, ss5, ss6, ss7 - + * sz1, sz2, sz3 + * sz11, sz12, sz13, sz21, sz22, sz23, sz31, sz32, sz33 - + * tc - + * temp - + * temp1, temp2, temp3 - + * tsi - + * xpidot - + * xhdot1 - + * z1, z2, z3 - + * z11, z12, z13, z21, z22, z23, z31, z32, z33 - + * + * coupling : + * getgravconst- + * initl - + * dscom - + * dpper - + * dsinit - + * sgp4 - + * + * references : + * hoots, roehrich, norad spacetrack report #3 1980 + * hoots, norad spacetrack report #6 1986 + * hoots, schumacher and glover 2004 + * vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ + function sgp4init(satrecInit, options) { + var opsmode = options.opsmode, + satn = options.satn, + epoch = options.epoch, + xbstar = options.xbstar, + xecco = options.xecco, + xargpo = options.xargpo, + xinclo = options.xinclo, + xmo = options.xmo, + xno = options.xno, + xnodeo = options.xnodeo; + var cosim; + var sinim; + var cc1sq; + var cc2; + var cc3; + var coef; + var coef1; + var cosio4; + var em; + var emsq; + var eeta; + var etasq; + var argpm; + var nodem; + var inclm; + var mm; + var nm; + var perige; + var pinvsq; + var psisq; + var qzms24; + var s1; + var s2; + var s3; + var s4; + var s5; + var sfour; + var ss1; + var ss2; + var ss3; + var ss4; + var ss5; + var sz1; + var sz3; + var sz11; + var sz13; + var sz21; + var sz23; + var sz31; + var sz33; + var tc; + var temp; + var temp1; + var temp2; + var temp3; + var tsi; + var xpidot; + var xhdot1; + var z1; + var z3; + var z11; + var z13; + var z21; + var z23; + var z31; + var z33; + /* ------------------------ initialization --------------------- */ + // sgp4fix divisor for divide by zero check on inclination + // the old check used 1.0 + Math.cos(pi-1.0e-9), but then compared it to + // 1.5 e-12, so the threshold was changed to 1.5e-12 for consistency + var temp4 = 1.5e-12; + var satrec = satrecInit; + // ----------- set all near earth variables to zero ------------ + satrec.isimp = 0; + satrec.method = 'n'; + satrec.aycof = 0.0; + satrec.con41 = 0.0; + satrec.cc1 = 0.0; + satrec.cc4 = 0.0; + satrec.cc5 = 0.0; + satrec.d2 = 0.0; + satrec.d3 = 0.0; + satrec.d4 = 0.0; + satrec.delmo = 0.0; + satrec.eta = 0.0; + satrec.argpdot = 0.0; + satrec.omgcof = 0.0; + satrec.sinmao = 0.0; + satrec.t = 0.0; + satrec.t2cof = 0.0; + satrec.t3cof = 0.0; + satrec.t4cof = 0.0; + satrec.t5cof = 0.0; + satrec.x1mth2 = 0.0; + satrec.x7thm1 = 0.0; + satrec.mdot = 0.0; + satrec.nodedot = 0.0; + satrec.xlcof = 0.0; + satrec.xmcof = 0.0; + satrec.nodecf = 0.0; + // ----------- set all deep space variables to zero ------------ + satrec.irez = 0; + satrec.d2201 = 0.0; + satrec.d2211 = 0.0; + satrec.d3210 = 0.0; + satrec.d3222 = 0.0; + satrec.d4410 = 0.0; + satrec.d4422 = 0.0; + satrec.d5220 = 0.0; + satrec.d5232 = 0.0; + satrec.d5421 = 0.0; + satrec.d5433 = 0.0; + satrec.dedt = 0.0; + satrec.del1 = 0.0; + satrec.del2 = 0.0; + satrec.del3 = 0.0; + satrec.didt = 0.0; + satrec.dmdt = 0.0; + satrec.dnodt = 0.0; + satrec.domdt = 0.0; + satrec.e3 = 0.0; + satrec.ee2 = 0.0; + satrec.peo = 0.0; + satrec.pgho = 0.0; + satrec.pho = 0.0; + satrec.pinco = 0.0; + satrec.plo = 0.0; + satrec.se2 = 0.0; + satrec.se3 = 0.0; + satrec.sgh2 = 0.0; + satrec.sgh3 = 0.0; + satrec.sgh4 = 0.0; + satrec.sh2 = 0.0; + satrec.sh3 = 0.0; + satrec.si2 = 0.0; + satrec.si3 = 0.0; + satrec.sl2 = 0.0; + satrec.sl3 = 0.0; + satrec.sl4 = 0.0; + satrec.gsto = 0.0; + satrec.xfact = 0.0; + satrec.xgh2 = 0.0; + satrec.xgh3 = 0.0; + satrec.xgh4 = 0.0; + satrec.xh2 = 0.0; + satrec.xh3 = 0.0; + satrec.xi2 = 0.0; + satrec.xi3 = 0.0; + satrec.xl2 = 0.0; + satrec.xl3 = 0.0; + satrec.xl4 = 0.0; + satrec.xlamo = 0.0; + satrec.zmol = 0.0; + satrec.zmos = 0.0; + satrec.atime = 0.0; + satrec.xli = 0.0; + satrec.xni = 0.0; + // sgp4fix - note the following variables are also passed directly via satrec. + // it is possible to streamline the sgp4init call by deleting the "x" + // variables, but the user would need to set the satrec.* values first. we + // include the additional assignments in case twoline2rv is not used. + satrec.bstar = xbstar; + satrec.ecco = xecco; + satrec.argpo = xargpo; + satrec.inclo = xinclo; + satrec.mo = xmo; + satrec.no = xno; + satrec.nodeo = xnodeo; + // sgp4fix add opsmode + satrec.operationmode = opsmode; + // ------------------------ earth constants ----------------------- + // sgp4fix identify constants and allow alternate values + var ss = 78.0 / earthRadius + 1.0; + // sgp4fix use multiply for speed instead of pow + var qzms2ttemp = (120.0 - 78.0) / earthRadius; + var qzms2t = qzms2ttemp * qzms2ttemp * qzms2ttemp * qzms2ttemp; + satrec.init = 'y'; + satrec.t = 0.0; + var initlOptions = { + satn: satn, + ecco: satrec.ecco, + epoch: epoch, + inclo: satrec.inclo, + no: satrec.no, + method: satrec.method, + opsmode: satrec.operationmode + }; + var initlResult = initl(initlOptions); + var ao = initlResult.ao, + con42 = initlResult.con42, + cosio = initlResult.cosio, + cosio2 = initlResult.cosio2, + eccsq = initlResult.eccsq, + omeosq = initlResult.omeosq, + posq = initlResult.posq, + rp = initlResult.rp, + rteosq = initlResult.rteosq, + sinio = initlResult.sinio; + satrec.no = initlResult.no; + satrec.con41 = initlResult.con41; + satrec.gsto = initlResult.gsto; + satrec.a = Math.pow(satrec.no * tumin, -2.0 / 3.0); + satrec.alta = satrec.a * (1.0 + satrec.ecco) - 1.0; + satrec.altp = satrec.a * (1.0 - satrec.ecco) - 1.0; + satrec.error = 0; + // sgp4fix remove this check as it is unnecessary + // the mrt check in sgp4 handles decaying satellite cases even if the starting + // condition is below the surface of te earth + // if (rp < 1.0) + // { + // printf("// *** satn%d epoch elts sub-orbital ***\n", satn); + // satrec.error = 5; + // } + if (omeosq >= 0.0 || satrec.no >= 0.0) { + satrec.isimp = 0; + if (rp < 220.0 / earthRadius + 1.0) { + satrec.isimp = 1; + } + sfour = ss; + qzms24 = qzms2t; + perige = (rp - 1.0) * earthRadius; + // - for perigees below 156 km, s and qoms2t are altered - + if (perige < 156.0) { + sfour = perige - 78.0; + if (perige < 98.0) { + sfour = 20.0; + } + // sgp4fix use multiply for speed instead of pow + var qzms24temp = (120.0 - sfour) / earthRadius; + qzms24 = qzms24temp * qzms24temp * qzms24temp * qzms24temp; + sfour = sfour / earthRadius + 1.0; + } + pinvsq = 1.0 / posq; + tsi = 1.0 / (ao - sfour); + satrec.eta = ao * satrec.ecco * tsi; + etasq = satrec.eta * satrec.eta; + eeta = satrec.ecco * satrec.eta; + psisq = Math.abs(1.0 - etasq); + coef = qzms24 * Math.pow(tsi, 4.0); + coef1 = coef / Math.pow(psisq, 3.5); + cc2 = coef1 * satrec.no * (ao * (1.0 + 1.5 * etasq + eeta * (4.0 + etasq)) + 0.375 * j2 * tsi / psisq * satrec.con41 * (8.0 + 3.0 * etasq * (8.0 + etasq))); + satrec.cc1 = satrec.bstar * cc2; + cc3 = 0.0; + if (satrec.ecco > 1.0e-4) { + cc3 = -2.0 * coef * tsi * j3oj2 * satrec.no * sinio / satrec.ecco; + } + satrec.x1mth2 = 1.0 - cosio2; + satrec.cc4 = 2.0 * satrec.no * coef1 * ao * omeosq * (satrec.eta * (2.0 + 0.5 * etasq) + satrec.ecco * (0.5 + 2.0 * etasq) - j2 * tsi / (ao * psisq) * (-3.0 * satrec.con41 * (1.0 - 2.0 * eeta + etasq * (1.5 - 0.5 * eeta)) + 0.75 * satrec.x1mth2 * (2.0 * etasq - eeta * (1.0 + etasq)) * Math.cos(2.0 * satrec.argpo))); + satrec.cc5 = 2.0 * coef1 * ao * omeosq * (1.0 + 2.75 * (etasq + eeta) + eeta * etasq); + cosio4 = cosio2 * cosio2; + temp1 = 1.5 * j2 * pinvsq * satrec.no; + temp2 = 0.5 * temp1 * j2 * pinvsq; + temp3 = -0.46875 * j4 * pinvsq * pinvsq * satrec.no; + satrec.mdot = satrec.no + 0.5 * temp1 * rteosq * satrec.con41 + 0.0625 * temp2 * rteosq * (13.0 - 78.0 * cosio2 + 137.0 * cosio4); + satrec.argpdot = -0.5 * temp1 * con42 + 0.0625 * temp2 * (7.0 - 114.0 * cosio2 + 395.0 * cosio4) + temp3 * (3.0 - 36.0 * cosio2 + 49.0 * cosio4); + xhdot1 = -temp1 * cosio; + satrec.nodedot = xhdot1 + (0.5 * temp2 * (4.0 - 19.0 * cosio2) + 2.0 * temp3 * (3.0 - 7.0 * cosio2)) * cosio; + xpidot = satrec.argpdot + satrec.nodedot; + satrec.omgcof = satrec.bstar * cc3 * Math.cos(satrec.argpo); + satrec.xmcof = 0.0; + if (satrec.ecco > 1.0e-4) { + satrec.xmcof = -x2o3 * coef * satrec.bstar / eeta; + } + satrec.nodecf = 3.5 * omeosq * xhdot1 * satrec.cc1; + satrec.t2cof = 1.5 * satrec.cc1; + // sgp4fix for divide by zero with xinco = 180 deg + if (Math.abs(cosio + 1.0) > 1.5e-12) { + satrec.xlcof = -0.25 * j3oj2 * sinio * (3.0 + 5.0 * cosio) / (1.0 + cosio); + } else { + satrec.xlcof = -0.25 * j3oj2 * sinio * (3.0 + 5.0 * cosio) / temp4; + } + satrec.aycof = -0.5 * j3oj2 * sinio; + // sgp4fix use multiply for speed instead of pow + var delmotemp = 1.0 + satrec.eta * Math.cos(satrec.mo); + satrec.delmo = delmotemp * delmotemp * delmotemp; + satrec.sinmao = Math.sin(satrec.mo); + satrec.x7thm1 = 7.0 * cosio2 - 1.0; + // --------------- deep space initialization ------------- + if (2 * pi / satrec.no >= 225.0) { + satrec.method = 'd'; + satrec.isimp = 1; + tc = 0.0; + inclm = satrec.inclo; + var dscomOptions = { + epoch: epoch, + ep: satrec.ecco, + argpp: satrec.argpo, + tc: tc, + inclp: satrec.inclo, + nodep: satrec.nodeo, + np: satrec.no, + e3: satrec.e3, + ee2: satrec.ee2, + peo: satrec.peo, + pgho: satrec.pgho, + pho: satrec.pho, + pinco: satrec.pinco, + plo: satrec.plo, + se2: satrec.se2, + se3: satrec.se3, + sgh2: satrec.sgh2, + sgh3: satrec.sgh3, + sgh4: satrec.sgh4, + sh2: satrec.sh2, + sh3: satrec.sh3, + si2: satrec.si2, + si3: satrec.si3, + sl2: satrec.sl2, + sl3: satrec.sl3, + sl4: satrec.sl4, + xgh2: satrec.xgh2, + xgh3: satrec.xgh3, + xgh4: satrec.xgh4, + xh2: satrec.xh2, + xh3: satrec.xh3, + xi2: satrec.xi2, + xi3: satrec.xi3, + xl2: satrec.xl2, + xl3: satrec.xl3, + xl4: satrec.xl4, + zmol: satrec.zmol, + zmos: satrec.zmos + }; + var dscomResult = dscom(dscomOptions); + satrec.e3 = dscomResult.e3; + satrec.ee2 = dscomResult.ee2; + satrec.peo = dscomResult.peo; + satrec.pgho = dscomResult.pgho; + satrec.pho = dscomResult.pho; + satrec.pinco = dscomResult.pinco; + satrec.plo = dscomResult.plo; + satrec.se2 = dscomResult.se2; + satrec.se3 = dscomResult.se3; + satrec.sgh2 = dscomResult.sgh2; + satrec.sgh3 = dscomResult.sgh3; + satrec.sgh4 = dscomResult.sgh4; + satrec.sh2 = dscomResult.sh2; + satrec.sh3 = dscomResult.sh3; + satrec.si2 = dscomResult.si2; + satrec.si3 = dscomResult.si3; + satrec.sl2 = dscomResult.sl2; + satrec.sl3 = dscomResult.sl3; + satrec.sl4 = dscomResult.sl4; + sinim = dscomResult.sinim; + cosim = dscomResult.cosim; + em = dscomResult.em; + emsq = dscomResult.emsq; + s1 = dscomResult.s1; + s2 = dscomResult.s2; + s3 = dscomResult.s3; + s4 = dscomResult.s4; + s5 = dscomResult.s5; + ss1 = dscomResult.ss1; + ss2 = dscomResult.ss2; + ss3 = dscomResult.ss3; + ss4 = dscomResult.ss4; + ss5 = dscomResult.ss5; + sz1 = dscomResult.sz1; + sz3 = dscomResult.sz3; + sz11 = dscomResult.sz11; + sz13 = dscomResult.sz13; + sz21 = dscomResult.sz21; + sz23 = dscomResult.sz23; + sz31 = dscomResult.sz31; + sz33 = dscomResult.sz33; + satrec.xgh2 = dscomResult.xgh2; + satrec.xgh3 = dscomResult.xgh3; + satrec.xgh4 = dscomResult.xgh4; + satrec.xh2 = dscomResult.xh2; + satrec.xh3 = dscomResult.xh3; + satrec.xi2 = dscomResult.xi2; + satrec.xi3 = dscomResult.xi3; + satrec.xl2 = dscomResult.xl2; + satrec.xl3 = dscomResult.xl3; + satrec.xl4 = dscomResult.xl4; + satrec.zmol = dscomResult.zmol; + satrec.zmos = dscomResult.zmos; + nm = dscomResult.nm; + z1 = dscomResult.z1; + z3 = dscomResult.z3; + z11 = dscomResult.z11; + z13 = dscomResult.z13; + z21 = dscomResult.z21; + z23 = dscomResult.z23; + z31 = dscomResult.z31; + z33 = dscomResult.z33; + var dpperOptions = { + inclo: inclm, + init: satrec.init, + ep: satrec.ecco, + inclp: satrec.inclo, + nodep: satrec.nodeo, + argpp: satrec.argpo, + mp: satrec.mo, + opsmode: satrec.operationmode + }; + var dpperResult = dpper(satrec, dpperOptions); + satrec.ecco = dpperResult.ep; + satrec.inclo = dpperResult.inclp; + satrec.nodeo = dpperResult.nodep; + satrec.argpo = dpperResult.argpp; + satrec.mo = dpperResult.mp; + argpm = 0.0; + nodem = 0.0; + mm = 0.0; + var dsinitOptions = { + cosim: cosim, + emsq: emsq, + argpo: satrec.argpo, + s1: s1, + s2: s2, + s3: s3, + s4: s4, + s5: s5, + sinim: sinim, + ss1: ss1, + ss2: ss2, + ss3: ss3, + ss4: ss4, + ss5: ss5, + sz1: sz1, + sz3: sz3, + sz11: sz11, + sz13: sz13, + sz21: sz21, + sz23: sz23, + sz31: sz31, + sz33: sz33, + t: satrec.t, + tc: tc, + gsto: satrec.gsto, + mo: satrec.mo, + mdot: satrec.mdot, + no: satrec.no, + nodeo: satrec.nodeo, + nodedot: satrec.nodedot, + xpidot: xpidot, + z1: z1, + z3: z3, + z11: z11, + z13: z13, + z21: z21, + z23: z23, + z31: z31, + z33: z33, + ecco: satrec.ecco, + eccsq: eccsq, + em: em, + argpm: argpm, + inclm: inclm, + mm: mm, + nm: nm, + nodem: nodem, + irez: satrec.irez, + atime: satrec.atime, + d2201: satrec.d2201, + d2211: satrec.d2211, + d3210: satrec.d3210, + d3222: satrec.d3222, + d4410: satrec.d4410, + d4422: satrec.d4422, + d5220: satrec.d5220, + d5232: satrec.d5232, + d5421: satrec.d5421, + d5433: satrec.d5433, + dedt: satrec.dedt, + didt: satrec.didt, + dmdt: satrec.dmdt, + dnodt: satrec.dnodt, + domdt: satrec.domdt, + del1: satrec.del1, + del2: satrec.del2, + del3: satrec.del3, + xfact: satrec.xfact, + xlamo: satrec.xlamo, + xli: satrec.xli, + xni: satrec.xni + }; + var dsinitResult = dsinit(dsinitOptions); + satrec.irez = dsinitResult.irez; + satrec.atime = dsinitResult.atime; + satrec.d2201 = dsinitResult.d2201; + satrec.d2211 = dsinitResult.d2211; + satrec.d3210 = dsinitResult.d3210; + satrec.d3222 = dsinitResult.d3222; + satrec.d4410 = dsinitResult.d4410; + satrec.d4422 = dsinitResult.d4422; + satrec.d5220 = dsinitResult.d5220; + satrec.d5232 = dsinitResult.d5232; + satrec.d5421 = dsinitResult.d5421; + satrec.d5433 = dsinitResult.d5433; + satrec.dedt = dsinitResult.dedt; + satrec.didt = dsinitResult.didt; + satrec.dmdt = dsinitResult.dmdt; + satrec.dnodt = dsinitResult.dnodt; + satrec.domdt = dsinitResult.domdt; + satrec.del1 = dsinitResult.del1; + satrec.del2 = dsinitResult.del2; + satrec.del3 = dsinitResult.del3; + satrec.xfact = dsinitResult.xfact; + satrec.xlamo = dsinitResult.xlamo; + satrec.xli = dsinitResult.xli; + satrec.xni = dsinitResult.xni; + } + // ----------- set variables if not deep space ----------- + if (satrec.isimp !== 1) { + cc1sq = satrec.cc1 * satrec.cc1; + satrec.d2 = 4.0 * ao * tsi * cc1sq; + temp = satrec.d2 * tsi * satrec.cc1 / 3.0; + satrec.d3 = (17.0 * ao + sfour) * temp; + satrec.d4 = 0.5 * temp * ao * tsi * (221.0 * ao + 31.0 * sfour) * satrec.cc1; + satrec.t3cof = satrec.d2 + 2.0 * cc1sq; + satrec.t4cof = 0.25 * (3.0 * satrec.d3 + satrec.cc1 * (12.0 * satrec.d2 + 10.0 * cc1sq)); + satrec.t5cof = 0.2 * (3.0 * satrec.d4 + 12.0 * satrec.cc1 * satrec.d3 + 6.0 * satrec.d2 * satrec.d2 + 15.0 * cc1sq * (2.0 * satrec.d2 + cc1sq)); + } + /* finally propogate to zero epoch to initialize all others. */ + // sgp4fix take out check to let satellites process until they are actually below earth surface + // if(satrec.error == 0) + } + sgp4(satrec, 0); + satrec.init = 'n'; + } + + /* ----------------------------------------------------------------------------- + * + * function twoline2satrec + * + * this function converts the two line element set character string data to + * variables and initializes the sgp4 variables. several intermediate varaibles + * and quantities are determined. note that the result is a structure so multiple + * satellites can be processed simultaneously without having to reinitialize. the + * verification mode is an important option that permits quick checks of any + * changes to the underlying technical theory. this option works using a + * modified tle file in which the start, stop, and delta time values are + * included at the end of the second line of data. this only works with the + * verification mode. the catalog mode simply propagates from -1440 to 1440 min + * from epoch and is useful when performing entire catalog runs. + * + * author : david vallado 719-573-2600 1 mar 2001 + * + * inputs : + * longstr1 - first line of the tle + * longstr2 - second line of the tle + * typerun - type of run verification 'v', catalog 'c', + * manual 'm' + * typeinput - type of manual input mfe 'm', epoch 'e', dayofyr 'd' + * opsmode - mode of operation afspc or improved 'a', 'i' + * whichconst - which set of constants to use 72, 84 + * + * outputs : + * satrec - structure containing all the sgp4 satellite information + * + * coupling : + * getgravconst- + * days2mdhms - conversion of days to month, day, hour, minute, second + * jday - convert day month year hour minute second into julian date + * sgp4init - initialize the sgp4 variables + * + * references : + * norad spacetrack report #3 + * vallado, crawford, hujsak, kelso 2006 + --------------------------------------------------------------------------- */ + /** + * Return a Satellite imported from two lines of TLE data. + * + * Provide the two TLE lines as strings `tleLine1` and `tleLine2`, + * and select which standard set of gravitational constants you want + * by providing `gravity_constants`: + * + * `sgp4.propagation.wgs72` - Standard WGS 72 model + * `sgp4.propagation.wgs84` - More recent WGS 84 model + * `sgp4.propagation.wgs72old` - Legacy support for old SGP4 behavior + * + * Normally, computations are made using letious recent improvements + * to the algorithm. If you want to turn some of these off and go + * back into "afspc" mode, then set `afspc_mode` to `True`. + */ + function twoline2satrec(longstr1, longstr2) { + var opsmode = 'i'; + var error = 0; + var satnum = longstr1.substring(2, 7); + var epochyr = parseInt(longstr1.substring(18, 20), 10); + var epochdays = parseFloat(longstr1.substring(20, 32)); + var ndot = parseFloat(longstr1.substring(33, 43)); + var nddot = parseFloat("".concat(longstr1.substring(44, 45), ".").concat(longstr1.substring(45, 50), "E").concat(longstr1.substring(50, 52))); + var bstar = parseFloat("".concat(longstr1.substring(53, 54), ".").concat(longstr1.substring(54, 59), "E").concat(longstr1.substring(59, 61))); + // satrec.satnum = longstr2.substring(2, 7); + // ---- find standard orbital elements ---- + var inclo = parseFloat(longstr2.substring(8, 16)) * deg2rad; + var nodeo = parseFloat(longstr2.substring(17, 25)) * deg2rad; + var ecco = parseFloat(".".concat(longstr2.substring(26, 33).replace(/\s/g, '0'))); + var argpo = parseFloat(longstr2.substring(34, 42)) * deg2rad; + var mo = parseFloat(longstr2.substring(43, 51)) * deg2rad; + // ---- find no, ndot, nddot ---- + var no = parseFloat(longstr2.substring(52, 63)) / xpdotp; + // satrec.nddot= satrec.nddot * Math.pow(10.0, nexp); + // satrec.bstar= satrec.bstar * Math.pow(10.0, ibexp); + // ---- convert to sgp4 units ---- + // satrec.ndot /= (xpdotp * 1440.0); // ? * minperday + // satrec.nddot /= (xpdotp * 1440.0 * 1440); + // ---------------------------------------------------------------- + // find sgp4epoch time of element set + // remember that sgp4 uses units of days from 0 jan 1950 (sgp4epoch) + // and minutes from the epoch (time) + // ---------------------------------------------------------------- + // ---------------- temp fix for years from 1957-2056 ------------------- + // --------- correct fix will occur when year is 4-digit in tle --------- + var year = epochyr < 57 ? epochyr + 2000 : epochyr + 1900; + var mdhmsResult = days2mdhms(year, epochdays); + var mon = mdhmsResult.mon, + day = mdhmsResult.day, + hr = mdhmsResult.hr, + minute = mdhmsResult.minute, + sec = mdhmsResult.sec; + var jdsatepoch = jday(year, mon, day, hr, minute, sec); + var satrec = { + error: error, + satnum: satnum, + epochyr: epochyr, + epochdays: epochdays, + ndot: ndot, + nddot: nddot, + bstar: bstar, + inclo: inclo, + nodeo: nodeo, + ecco: ecco, + argpo: argpo, + mo: mo, + no: no, + jdsatepoch: jdsatepoch + }; + // ---------------- initialize the orbit at sgp4epoch ------------------- + sgp4init(satrec, { + opsmode: opsmode, + satn: satrec.satnum, + epoch: satrec.jdsatepoch - 2433281.5, + xbstar: satrec.bstar, + xecco: satrec.ecco, + xargpo: satrec.argpo, + xinclo: satrec.inclo, + xmo: satrec.mo, + xno: satrec.no, + xnodeo: satrec.nodeo + }); + return satrec; + } + /* ----------------------------------------------------------------------------- + * + * function json2satrec + * + * this function converts the OMM json data to variables and initializes the sgp4 + * variables. several intermediate varaibles and quantities are determined. note + * that the result is a structure so multiple satellites can be processed + * simultaneously without having to reinitialize. the verification mode is an + * important option that permits quick checks of any changes to the underlying + * technical theory. this option works using a modified tle file in which the + * start, stop, and delta time values are included at the end of the second line + * of data. this only works with the verification mode. the catalog mode simply + * propagates from -1440 to 1440 min from epoch and is useful when performing + * entire catalog runs. + * + * author : Hariharan Vitaladevuni 18 Aug 2023 + * Theodore Kruczek 19 Aug 2023 + * + * inputs : + * jsonobj - OMM json data + * opsmode - mode of operation afspc or improved 'a', 'i'. Default: 'i'. + * + * outputs : + * satrec - structure containing all the sgp4 satellite information + * + * coupling : + * days2mdhms - conversion of days to month, day, hour, minute, second + * jday - convert day month year hour minute second into julian date + * sgp4init - initialize the sgp4 variables + * + * warning : the epoch date in OMM format is more accurate than TLE format! + * this will result in extremely close, but different + * position/velocity values. Depending on your use case, it may + * be better to use twoline2satrec, but for the average user this + * will provide comparable results. + * + * references : + * https://celestrak.org/NORAD/documentation/gp-data-formats.php + --------------------------------------------------------------------------- */ + function json2satrec(jsonobj) { + var opsmode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'i'; + var error = 0; + var satnum = jsonobj.NORAD_CAT_ID.toString(); + var epoch = new Date(jsonobj.EPOCH.endsWith('Z') ? jsonobj.EPOCH : jsonobj.EPOCH + 'Z'); + var year = epoch.getUTCFullYear(); + var epochyr = Number(year.toString().slice(-2)); + var epochdays = (epoch.valueOf() - new Date(Date.UTC(year, 0, 1, 0, 0, 0)).valueOf()) / (86400 * 1000) + 1; + var ndot = Number(jsonobj.MEAN_MOTION_DOT); + var nddot = Number(jsonobj.MEAN_MOTION_DDOT); + var bstar = Number(jsonobj.BSTAR); + var inclo = Number(jsonobj.INCLINATION) * deg2rad; + var nodeo = Number(jsonobj.RA_OF_ASC_NODE) * deg2rad; + var ecco = Number(jsonobj.ECCENTRICITY); + var argpo = Number(jsonobj.ARG_OF_PERICENTER) * deg2rad; + var mo = Number(jsonobj.MEAN_ANOMALY) * deg2rad; + var no = Number(jsonobj.MEAN_MOTION) / xpdotp; + // ---------------------------------------------------------------- + // find sgp4epoch time of element set + // remember that sgp4 uses units of days from 0 jan 1950 (sgp4epoch) + // and minutes from the epoch (time) + // ---------------------------------------------------------------- + var mdhmsResult = days2mdhms(year, epochdays); + var mon = mdhmsResult.mon, + day = mdhmsResult.day, + hr = mdhmsResult.hr, + minute = mdhmsResult.minute, + sec = mdhmsResult.sec; + var jdsatepoch = jday(year, mon, day, hr, minute, sec); + var satrec = { + error: error, + satnum: satnum, + epochyr: epochyr, + epochdays: epochdays, + ndot: ndot, + nddot: nddot, + bstar: bstar, + inclo: inclo, + nodeo: nodeo, + ecco: ecco, + argpo: argpo, + mo: mo, + no: no, + jdsatepoch: jdsatepoch + }; + // ---------------- initialize the orbit at sgp4epoch ------------------- + sgp4init(satrec, { + opsmode: opsmode, + satn: satrec.satnum, + epoch: satrec.jdsatepoch - 2433281.5, + xbstar: satrec.bstar, + xecco: satrec.ecco, + xargpo: satrec.argpo, + xinclo: satrec.inclo, + xmo: satrec.mo, + xno: satrec.no, + xnodeo: satrec.nodeo + }); + return satrec; + } + + function propagate(satrec) { + for (var _len = arguments.length, jdayArgs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + jdayArgs[_key - 1] = arguments[_key]; + } + // Return a position and velocity vector for a given date and time. + var j = jday.apply(void 0, jdayArgs); + var m = (j - satrec.jdsatepoch) * minutesPerDay; + return sgp4(satrec, m); + } + + var types = /*#__PURE__*/Object.freeze({ + __proto__: null + }); + + var earthRotation = 7.292115E-5; + var c = 299792.458; // Speed of light in km/s + /** + * Negative range rate means the satellite is moving towards the observer and + * its frequency is shifted higher because 1 minus a negative range rate is + * positive. If the range rate is positive, the satellite is moving away from + * the observer and its frequency is shifted lower. + */ + function dopplerFactor(observerCoordsEcf, positionEcf, velocityEcf) { + var rangeX = positionEcf.x - observerCoordsEcf.x; + var rangeY = positionEcf.y - observerCoordsEcf.y; + var rangeZ = positionEcf.z - observerCoordsEcf.z; + var length = Math.sqrt(Math.pow(rangeX, 2) + Math.pow(rangeY, 2) + Math.pow(rangeZ, 2)); + var rangeVel = { + x: velocityEcf.x + earthRotation * observerCoordsEcf.y, + y: velocityEcf.y - earthRotation * observerCoordsEcf.x, + z: velocityEcf.z + }; + var rangeRate = (rangeX * rangeVel.x + rangeY * rangeVel.y + rangeZ * rangeVel.z) / length; + return 1 - rangeRate / c; + } + + function radiansToDegrees(radians) { + return radians * rad2deg; + } + function degreesToRadians(degrees) { + return degrees * deg2rad; + } + function degreesLat(radians) { + if (radians < -pi / 2 || radians > pi / 2) { + throw new RangeError('Latitude radians must be in range [-pi/2; pi/2].'); + } + return radiansToDegrees(radians); + } + function degreesLong(radians) { + if (radians < -pi || radians > pi) { + throw new RangeError('Longitude radians must be in range [-pi; pi].'); + } + return radiansToDegrees(radians); + } + function radiansLat(degrees) { + if (degrees < -90 || degrees > 90) { + throw new RangeError('Latitude degrees must be in range [-90; 90].'); + } + return degreesToRadians(degrees); + } + function radiansLong(degrees) { + if (degrees < -180 || degrees > 180) { + throw new RangeError('Longitude degrees must be in range [-180; 180].'); + } + return degreesToRadians(degrees); + } + function geodeticToEcf(_ref) { + var longitude = _ref.longitude, + latitude = _ref.latitude, + height = _ref.height; + var a = 6378.137; + var b = 6356.7523142; + var f = (a - b) / a; + var e2 = 2 * f - f * f; + var normal = a / Math.sqrt(1 - e2 * (Math.sin(latitude) * Math.sin(latitude))); + var x = (normal + height) * Math.cos(latitude) * Math.cos(longitude); + var y = (normal + height) * Math.cos(latitude) * Math.sin(longitude); + var z = (normal * (1 - e2) + height) * Math.sin(latitude); + return { + x: x, + y: y, + z: z + }; + } + function eciToGeodetic(eci, gmst) { + // http://www.celestrak.com/columns/v02n03/ + var a = 6378.137; + var b = 6356.7523142; + var R = Math.sqrt(eci.x * eci.x + eci.y * eci.y); + var f = (a - b) / a; + var e2 = 2 * f - f * f; + var longitude = Math.atan2(eci.y, eci.x) - gmst; + while (longitude < -pi) { + longitude += twoPi; + } + while (longitude > pi) { + longitude -= twoPi; + } + var kmax = 20; + var k = 0; + var latitude = Math.atan2(eci.z, Math.sqrt(eci.x * eci.x + eci.y * eci.y)); + var C; + while (k++ < kmax) { + C = 1 / Math.sqrt(1 - e2 * (Math.sin(latitude) * Math.sin(latitude))); + latitude = Math.atan2(eci.z + a * C * e2 * Math.sin(latitude), R); + } + var height = R / Math.cos(latitude) - a * C; + return { + longitude: longitude, + latitude: latitude, + height: height + }; + } + function ecfToEci(ecf, gmst) { + // ccar.colorado.edu/ASEN5070/handouts/coordsys.doc + // + // [X] [C -S 0][X] + // [Y] = [S C 0][Y] + // [Z]eci [0 0 1][Z]ecf + // + var X = ecf.x * Math.cos(gmst) - ecf.y * Math.sin(gmst); + var Y = ecf.x * Math.sin(gmst) + ecf.y * Math.cos(gmst); + var Z = ecf.z; + return { + x: X, + y: Y, + z: Z + }; + } + function eciToEcf(eci, gmst) { + // ccar.colorado.edu/ASEN5070/handouts/coordsys.doc + // + // [X] [C -S 0][X] + // [Y] = [S C 0][Y] + // [Z]eci [0 0 1][Z]ecf + // + // + // Inverse: + // [X] [C S 0][X] + // [Y] = [-S C 0][Y] + // [Z]ecf [0 0 1][Z]eci + var x = eci.x * Math.cos(gmst) + eci.y * Math.sin(gmst); + var y = eci.x * -Math.sin(gmst) + eci.y * Math.cos(gmst); + var z = eci.z; + return { + x: x, + y: y, + z: z + }; + } + function topocentric(observerGeodetic, satelliteEcf) { + // http://www.celestrak.com/columns/v02n02/ + // TS Kelso's method, except I'm using ECF frame + // and he uses ECI. + var longitude = observerGeodetic.longitude, + latitude = observerGeodetic.latitude; + var observerEcf = geodeticToEcf(observerGeodetic); + var rx = satelliteEcf.x - observerEcf.x; + var ry = satelliteEcf.y - observerEcf.y; + var rz = satelliteEcf.z - observerEcf.z; + var topS = Math.sin(latitude) * Math.cos(longitude) * rx + Math.sin(latitude) * Math.sin(longitude) * ry - Math.cos(latitude) * rz; + var topE = -Math.sin(longitude) * rx + Math.cos(longitude) * ry; + var topZ = Math.cos(latitude) * Math.cos(longitude) * rx + Math.cos(latitude) * Math.sin(longitude) * ry + Math.sin(latitude) * rz; + return { + topS: topS, + topE: topE, + topZ: topZ + }; + } + function topocentricToLookAngles(tc) { + var topS = tc.topS, + topE = tc.topE, + topZ = tc.topZ; + var rangeSat = Math.sqrt(topS * topS + topE * topE + topZ * topZ); + var El = Math.asin(topZ / rangeSat); + var Az = Math.atan2(-topE, topS) + pi; + return { + azimuth: Az, + elevation: El, + rangeSat: rangeSat // Range in km + }; + } + function ecfToLookAngles(observerGeodetic, satelliteEcf) { + var topocentricCoords = topocentric(observerGeodetic, satelliteEcf); + return topocentricToLookAngles(topocentricCoords); + } + + //////////////////////////////////////////////////////////////////////////////////// + /* Line by Line MATLAB-to-Javascript conversion of "sun.mat" from Vallado package */ + //////////////////////////////////////////////////////////////////////////////////// + /* ----------------------------------------------------------------------------- + * + * function sunPos + * + * this function calculates the geocentric equatorial position vector + * the sun given the julian date. this is the low precision formula and + * is valid for years from 1950 to 2050. accuaracy of apparent coordinates + * is 0.01 degrees. notice many of the calculations are performed in + * degrees, and are not changed until later. this is due to the fact that + * the almanac uses degrees exclusively in their formulations. + * + * author : david vallado 719-573-2600 1 mar 2001 + * + * inputs description range / units + * jd - julian date days from 4713 bc + * + * outputs : + * rsun - ijk position vector of the sun au + * rtasc - right ascension rad + * decl - declination rad + * + * coupling : + * - + * + * references : + * VALLADO, DAVID A. (2022) ‘Computer software in MATLAB’, in Fundamentals of astrodynamics and applications. 5th edn. + * Computer software in MATLAB: http://celestrak.org/software/vallado-sw.php + * --------------------------------------------------------------------------- */ + function sunPos(jday) { + // ------------------------- implementation ----------------- + // ------------------- initialize values -------------------- + var tut1 = (jday - 2451545) / 36525; + var meanlong = (280.460 + 36000.77 * tut1) % 360; //deg + var ttdb = tut1; // is this declaration required instead of replacing `ttdb` with `tut1` + var meananomaly = (357.5277233 + 35999.05034 * ttdb * deg2rad) % twoPi; //rad + if (meananomaly < 0) { + meananomaly += twoPi; + } + var eclplong_raw = (meanlong + 1.914666471 * Math.sin(meananomaly) + 0.019994643 * Math.sin(2.0 * meananomaly)) % 360.0 * deg2rad; //rad + var obliquity = (23.439291 - 0.0130042 * ttdb) * deg2rad; //rad + // --------- find magnitude of sun vector, and it's components ------ + var magr = 1.000140612 - 0.016708617 * Math.cos(meananomaly) - 0.000139589 * Math.cos(2.0 * meananomaly); // in au's + var rsun = [magr * Math.cos(eclplong_raw), magr * Math.cos(obliquity) * Math.sin(eclplong_raw), magr * Math.sin(obliquity) * Math.sin(eclplong_raw)]; + var rtasc_raw = Math.atan(Math.cos(obliquity) * Math.tan(eclplong_raw)); + var rtasc = rtasc_raw; + if (Math.abs(eclplong_raw - rtasc) > pi * 0.5) { + rtasc += 0.5 * pi * Math.round((eclplong_raw - rtasc_raw) / (0.5 * pi)); + } + var decl = Math.asin(Math.sin(obliquity) * Math.sin(eclplong_raw)); + return { + rsun: rsun, + rtasc: rtasc, + decl: decl + }; + } + /* Original MATLAB code for Sun position from Vallado package (sun.mat) */ + /* + function [rsun,rtasc,decl] = sun ( jd ); + + twopi = 2.0*pi; + deg2rad = pi/180.0; + show = 'n'; + + % ------------------------- implementation ----------------- + % ------------------- initialize values -------------------- + tut1= ( jd - 2451545.0 )/ 36525.0; + + if show == 'y' + fprintf(1,'tut1 %14.9f \n',tut1); + end + + meanlong= 280.460 + 36000.77*tut1; + meanlong= rem( meanlong,360.0 ); %deg + + ttdb= tut1; + meananomaly= 357.5277233 + 35999.05034 *ttdb; + meananomaly= rem( meananomaly*deg2rad,twopi ); %rad + if ( meananomaly < 0.0 ) + meananomaly= twopi + meananomaly; + end + + eclplong_raw= meanlong + 1.914666471 *sin(meananomaly) ... + + 0.019994643 *sin(2.0 *meananomaly); %deg + eclplong_raw= rem( eclplong_raw,360.0 ); %deg + + obliquity= 23.439291 - 0.0130042 *ttdb; %deg + + eclplong_raw = eclplong_raw *deg2rad; + obliquity= obliquity *deg2rad; + + % --------- find magnitude of sun vector, ) components ------ + magr= 1.000140612 - 0.016708617 *cos( meananomaly ) ... + - 0.000139589 *cos( 2.0 *meananomaly ); % in au's + + rsun(1)= magr*cos( eclplong_raw ); + rsun(2)= magr*cos(obliquity)*sin(eclplong_raw); + rsun(3)= magr*sin(obliquity)*sin(eclplong_raw); + + if show == 'y' + fprintf(1,'meanlon %11.6f meanan %11.6f eclplon %11.6f obli %11.6f \n', ... + meanlong,meananomaly/deg2rad,eclplong_raw/deg2rad,obliquity/deg2rad); + fprintf(1,'rs %11.9f %11.9f %11.9f \n',rsun); + fprintf(1,'magr %14.7f \n',magr); + end + + rtasc= atan( cos(obliquity)*tan(eclplong_raw) ); + + % --- check that rtasc is in the same quadrant as eclplong_raw ---- + if ( eclplong_raw < 0.0 ) + eclplong_raw= eclplong_raw + twopi; % make sure it's in 0 to 2pi range + end + if ( abs( eclplong_raw-rtasc ) > pi*0.5 ) + rtasc= rtasc + 0.5 *pi*round( (eclplong_raw-rtasc)/(0.5 *pi)); + end + decl = asin( sin(obliquity)*sin(eclplong_raw) ); + */ + + var indexUmd = Object.assign(Object.assign({ + constants: constants, + // Propagation + propagate: propagate, + sgp4: sgp4, + twoline2satrec: twoline2satrec, + json2satrec: json2satrec, + gstime: gstime, + jday: jday, + invjday: invjday, + dopplerFactor: dopplerFactor, + // Coordinate transforms + radiansToDegrees: radiansToDegrees, + degreesToRadians: degreesToRadians, + degreesLat: degreesLat, + degreesLong: degreesLong, + radiansLat: radiansLat, + radiansLong: radiansLong, + geodeticToEcf: geodeticToEcf, + eciToGeodetic: eciToGeodetic, + eciToEcf: eciToEcf, + ecfToEci: ecfToEci, + ecfToLookAngles: ecfToLookAngles, + // Sun Position + sunPos: sunPos + }, types), { + SatRecError: SatRecError + }); + + return indexUmd; + +})); diff --git a/node_modules/satellite.js/dist/satellite.min.js b/node_modules/satellite.js/dist/satellite.min.js new file mode 100644 index 0000000..db39044 --- /dev/null +++ b/node_modules/satellite.js/dist/satellite.min.js @@ -0,0 +1 @@ +!function(o,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(o="undefined"!=typeof globalThis?globalThis:o||self).satellite=t()}(this,(function(){"use strict";var o,t=Math.PI,e=2*t,s=t/180,a=180/t,n=398600.8,d=6378.135,i=60/Math.sqrt(650942.9922085947),r=d*i/60,c=1/i,h=.001082616,m=-253881e-11,l=-165597e-11,p=m/h,M=2/3,x=1440/(2*t),g=Object.freeze({__proto__:null,deg2rad:s,earthRadius:d,j2:h,j3:m,j3oj2:p,j4:l,minutesPerDay:1440,mu:n,pi:t,rad2deg:a,tumin:c,twoPi:e,vkmpersec:r,x2o3:M,xke:i,xpdotp:x});function u(o,t){for(var e=[31,o%4==0?29:28,31,30,31,30,31,31,30,31,30,31],s=Math.floor(t),a=1,n=0;s>n+e[a-1]&&a<12;)n+=e[a-1],a+=1;var d=a,i=s-n,r=24*(t-s),c=Math.floor(r);r=60*(r-c);var h=Math.floor(r);return{mon:d,day:i,hr:c,minute:h,sec:60*(r-h)}}function f(o,t,e,s,a,n){var d=arguments.length>6&&void 0!==arguments[6]?arguments[6]:0;return 367*o-Math.floor(7*(o+Math.floor((t+9)/12))*.25)+Math.floor(275*t/9)+e+1721013.5+((d/6e4+n/60+a)/60+s)/24}function z(o,t,e,s,a,n){var d=arguments.length>6&&void 0!==arguments[6]?arguments[6]:0;if(o instanceof Date){var i=o;return f(i.getUTCFullYear(),i.getUTCMonth()+1,i.getUTCDate(),i.getUTCHours(),i.getUTCMinutes(),i.getUTCSeconds(),i.getUTCMilliseconds())}return f(o,t,e,s,a,n,d)}function v(o,s){var a,n,d,i,r,c,h,m,l,p,M,x,g,u,f,z,v,b,y=o.e3,O=o.ee2,E=o.peo,w=o.pgho,T=o.pho,q=o.pinco,N=o.plo,R=o.se2,_=o.se3,C=o.sgh2,D=o.sgh3,j=o.sgh4,A=o.sh2,F=o.sh3,L=o.si2,I=o.si3,S=o.sl2,P=o.sl3,U=o.sl4,Z=o.t,B=o.xgh2,H=o.xgh3,Y=o.xgh4,k=o.xh2,G=o.xh3,W=o.xi2,J=o.xi3,K=o.xl2,Q=o.xl3,V=o.xl4,X=o.zmol,$=o.zmos,oo=s.init,to=s.opsmode,eo=s.ep,so=s.inclp,ao=s.nodep,no=s.argpp,io=s.mp;b=$+119459e-10*Z,"y"===oo&&(b=$),v=b+.0335*Math.sin(b);var ro=R*(h=.5*(u=Math.sin(v))*u-.25)+_*(m=-.5*u*Math.cos(v)),co=L*h+I*m,ho=S*h+P*m+U*u,mo=C*h+D*m+j*u,lo=A*h+F*m;return b=X+.00015835218*Z,"y"===oo&&(b=X),v=b+.1098*Math.sin(b),l=ro+(O*(h=.5*(u=Math.sin(v))*u-.25)+y*(m=-.5*u*Math.cos(v))),x=co+(W*h+J*m),g=ho+(K*h+Q*m+V*u),p=mo+(B*h+H*m+Y*u),M=lo+(k*h+G*m),"n"===oo&&(g-=N,p-=w,M-=T,so+=x-=q,eo+=l-=E,i=Math.sin(so),d=Math.cos(so),so>=.2?(no+=p-=d*(M/=i),ao+=M,io+=g):(a=i*(c=Math.sin(ao)),n=i*(r=Math.cos(ao)),a+=M*r+x*d*c,n+=-M*c+x*d*r,(ao%=e)<0&&"a"===to&&(ao+=e),f=io+no+d*ao,f+=g+p-x*ao*i,z=ao,(ao=Math.atan2(a,n))<0&&"a"===to&&(ao+=e),Math.abs(z-ao)>t&&(ao0?720:-720;for(var ao=381;381===ao;)2!==h?(r=y*Math.sin(Z-G)+O*Math.sin(2*(Z-W))+E*Math.sin(3*(Z-J)),d=H+A,i=y*Math.cos(Z-G)+2*O*Math.cos(2*(Z-W))+3*E*Math.cos(3*(Z-J)),i*=d):(a=(c=R+_*I)+c,s=Z+Z,r=m*Math.sin(a+Z-K)+l*Math.sin(Z-K)+p*Math.sin(c+Z-Q)+M*Math.sin(-c+Z-Q)+x*Math.sin(a+s-V)+g*Math.sin(s-V)+u*Math.sin(c+Z-X)+f*Math.sin(-c+Z-X)+z*Math.sin(c+s-$)+v*Math.sin(-c+s-$),d=H+A,i=m*Math.cos(a+Z-K)+l*Math.cos(Z-K)+p*Math.cos(c+Z-Q)+M*Math.cos(-c+Z-Q)+u*Math.cos(c+Z-X)+f*Math.cos(-c+Z-X)+2*(x*Math.cos(a+s-V)+g*Math.cos(s-V)+z*Math.cos(c+s-$)+v*Math.cos(-c+s-$)),i*=d),Math.abs(C-I)>=720?ao=381:(eo=C-I,ao=0),381===ao&&(Z+=d*t+r*oo,H+=r*t+i*oo,I+=t);k=H+r*eo+i*eo*eo*.5,n=Z+d*eo+r*eo*eo*.5,1!==h?(B=n-2*Y+2*so,to=k-L):(B=n-Y-P+so,to=k-L),k=L+to}return{atime:I,em:S,argpm:P,inclm:U,xli:Z,mm:B,xni:H,nodem:Y,dndt:to,nm:k}}({irez:s.irez,d2201:s.d2201,d2211:s.d2211,d3210:s.d3210,d3222:s.d3222,d4410:s.d4410,d4422:s.d4422,d5220:s.d5220,d5232:s.d5232,d5421:s.d5421,d5433:s.d5433,dedt:s.dedt,del1:s.del1,del2:s.del2,del3:s.del3,didt:s.didt,dmdt:s.dmdt,dnodt:s.dnodt,domdt:s.domdt,argpo:s.argpo,argpdot:s.argpdot,t:s.t,tc:E,gsto:s.gsto,xfact:s.xfact,xlamo:s.xlamo,no:s.no,atime:s.atime,em:H,argpm:f,inclm:_,xli:s.xli,mm:C,xni:s.xni,nodem:j,nm:D});H=Y.em,f=Y.argpm,_=Y.inclm,C=Y.mm,j=Y.nodem,D=Y.nm}if(D<=0)return s.error=o.MeanMotionBelowZero,null;var k=Math.pow(i/D,M)*q*q;if(D=i/Math.pow(k,1.5),(H-=N)>=1||H<-.001)return s.error=o.MeanEccentricityOutOfRange,null;H<1e-6&&(H=1e-6),F=(C+=s.no*R)+f+j;var G={am:k,em:H,im:_,Om:j%=e,om:f%=e,mm:C=((F%=e)-f-j)%e,nm:D},W=H;if(A=_,z=f,I=j,L=C,l=Math.sin(_),m=Math.cos(_),"d"===s.method){var J=v(s,{inclo:s.inclo,init:"n",ep:W,inclp:A,nodep:I,argpp:z,mp:L,opsmode:s.operationmode});if(W=J.ep,I=J.nodep,z=J.argpp,L=J.mp,(A=J.inclp)<0&&(A=-A,I+=t,z-=t),W<0||W>1)return s.error=o.PerturbedEccentricityOutOfRange,null}"d"===s.method&&(l=Math.sin(A),m=Math.cos(A),s.aycof=-.5*p*l,Math.abs(m+1)>15e-13?s.xlcof=-.25*p*l*(3+5*m)/(1+m):s.xlcof=-.25*p*l*(3+5*m)/15e-13);var K=W*Math.cos(z);T=1/(k*(1-W*W));var Q=W*Math.sin(z)+T*s.aycof,V=(L+z+I+T*s.xlcof*K-I)%e;u=V,w=9999.9;for(var X=1;Math.abs(w)>=1e-12&&X<=10;)c=Math.sin(u),w=(V-Q*(n=Math.cos(u))+K*c-u)/(w=1-n*K-c*Q),Math.abs(w)>=.95&&(w=w>0?.95:-.95),u+=w,X+=1;var $=K*n+Q*c,oo=K*c-Q*n,to=K*K+Q*Q,eo=k*(1-to);if(eo<0)return s.error=o.SemiLatusRectumBelowZero,null;var so=k*(1-$),ao=Math.sqrt(k)*oo/so,no=Math.sqrt(eo)/so,io=Math.sqrt(1-to),ro=k/so*(c-Q-K*(T=oo/(1+io))),co=k/so*(n-K+Q*T);b=Math.atan2(ro,co);var ho=(co+co)*ro,mo=1-2*ro*ro,lo=.5*h*(T=1/eo),po=lo*T;"d"===s.method&&(x=m*m,s.con41=3*x-1,s.x1mth2=1-x,s.x7thm1=7*x-1);var Mo=so*(1-1.5*po*io*s.con41)+.5*lo*s.x1mth2*mo;if(Mo<1)return s.error=o.Decayed,null;b-=.25*po*s.x7thm1*ho;var xo=I+1.5*po*m*ho,go=A+1.5*po*m*l*mo,uo=ao-D*lo*s.x1mth2*ho/i,fo=no+D*lo*(s.x1mth2*mo+1.5*s.con41)/i,zo=Math.sin(b),vo=Math.cos(b),bo=Math.sin(xo),yo=Math.cos(xo),Oo=Math.sin(go),Eo=Math.cos(go),wo=-bo*Eo,To=yo*Eo,qo=wo*zo+yo*vo,No=To*zo+bo*vo,Ro=Oo*zo;return{position:{x:Mo*qo*d,y:Mo*No*d,z:Mo*Ro*d},velocity:{x:(uo*qo+fo*(wo*vo-yo*zo))*r,y:(uo*No+fo*(To*vo-bo*zo))*r,z:(uo*Ro+fo*(Oo*vo))*r},meanElements:G}}function E(o,s){var a,n,r,m,x,g,u,f,z,b,E,w,T,q,N,R,_,C,D,j,A,F,L,I,S,P,U,Z,B,H,Y,k,G,W,J,K,Q,V,X,$,oo,to,eo,so,ao,no,io,ro,co,ho,mo,lo,po=s.opsmode,Mo=s.satn,xo=s.epoch,go=s.xbstar,uo=s.xecco,fo=s.xargpo,zo=s.xinclo,vo=s.xmo,bo=s.xno,yo=s.xnodeo,Oo=o;Oo.isimp=0,Oo.method="n",Oo.aycof=0,Oo.con41=0,Oo.cc1=0,Oo.cc4=0,Oo.cc5=0,Oo.d2=0,Oo.d3=0,Oo.d4=0,Oo.delmo=0,Oo.eta=0,Oo.argpdot=0,Oo.omgcof=0,Oo.sinmao=0,Oo.t=0,Oo.t2cof=0,Oo.t3cof=0,Oo.t4cof=0,Oo.t5cof=0,Oo.x1mth2=0,Oo.x7thm1=0,Oo.mdot=0,Oo.nodedot=0,Oo.xlcof=0,Oo.xmcof=0,Oo.nodecf=0,Oo.irez=0,Oo.d2201=0,Oo.d2211=0,Oo.d3210=0,Oo.d3222=0,Oo.d4410=0,Oo.d4422=0,Oo.d5220=0,Oo.d5232=0,Oo.d5421=0,Oo.d5433=0,Oo.dedt=0,Oo.del1=0,Oo.del2=0,Oo.del3=0,Oo.didt=0,Oo.dmdt=0,Oo.dnodt=0,Oo.domdt=0,Oo.e3=0,Oo.ee2=0,Oo.peo=0,Oo.pgho=0,Oo.pho=0,Oo.pinco=0,Oo.plo=0,Oo.se2=0,Oo.se3=0,Oo.sgh2=0,Oo.sgh3=0,Oo.sgh4=0,Oo.sh2=0,Oo.sh3=0,Oo.si2=0,Oo.si3=0,Oo.sl2=0,Oo.sl3=0,Oo.sl4=0,Oo.gsto=0,Oo.xfact=0,Oo.xgh2=0,Oo.xgh3=0,Oo.xgh4=0,Oo.xh2=0,Oo.xh3=0,Oo.xi2=0,Oo.xi3=0,Oo.xl2=0,Oo.xl3=0,Oo.xl4=0,Oo.xlamo=0,Oo.zmol=0,Oo.zmos=0,Oo.atime=0,Oo.xli=0,Oo.xni=0,Oo.bstar=go,Oo.ecco=uo,Oo.argpo=fo,Oo.inclo=zo,Oo.mo=vo,Oo.no=bo,Oo.nodeo=yo,Oo.operationmode=po;var Eo=78/d+1;Oo.init="y",Oo.t=0;var wo=function(o){var t=o.ecco,s=o.epoch,a=o.inclo,n=o.opsmode,d=o.no,r=t*t,c=1-r,m=Math.sqrt(c),l=Math.cos(a),p=l*l,x=Math.pow(i/d,M),g=.75*h*(3*p-1)/(m*c),u=g/(x*x),f=x*(1-u*u-u*(1/3+134*u*u/81));d/=1+(u=g/(f*f));var z,v=Math.pow(i/d,M),b=Math.sin(a),O=v*c,E=1-5*p,w=-E-p-p,T=1/v,q=O*O,N=v*(1-t);if("a"===n){var R=s-7305,_=Math.floor(R+1e-8),C=.017202791694070362;(z=(1.7321343856509375+C*_+(C+e)*(R-_)+R*R*5075514194322695e-30)%e)<0&&(z+=e)}else z=y(s+2433281.5);return{no:d,method:"n",ainv:T,ao:v,con41:w,con42:E,cosio:l,cosio2:p,eccsq:r,omeosq:c,posq:q,rp:N,rteosq:m,sinio:b,gsto:z}}({satn:Mo,ecco:Oo.ecco,epoch:xo,inclo:Oo.inclo,no:Oo.no,method:Oo.method,opsmode:Oo.operationmode}),To=wo.ao,qo=wo.con42,No=wo.cosio,Ro=wo.cosio2,_o=wo.eccsq,Co=wo.omeosq,Do=wo.posq,jo=wo.rp,Ao=wo.rteosq,Fo=wo.sinio;if(Oo.no=wo.no,Oo.con41=wo.con41,Oo.gsto=wo.gsto,Oo.a=Math.pow(Oo.no*c,-2/3),Oo.alta=Oo.a*(1+Oo.ecco)-1,Oo.altp=Oo.a*(1-Oo.ecco)-1,Oo.error=0,Co>=0||Oo.no>=0){if(Oo.isimp=0,jo<1.034492841559484&&(Oo.isimp=1),I=Eo,C=1.880279159015271e-9,(N=(jo-1)*d)<156){I=N-78,N<98&&(I=20);var Lo=(120-I)/d;C=Lo*Lo*Lo*Lo,I=I/d+1}R=1/Do,to=1/(To-I),Oo.eta=To*Oo.ecco*to,w=Oo.eta*Oo.eta,E=Oo.ecco*Oo.eta,_=Math.abs(1-w),m=(u=(g=C*Math.pow(to,4))/Math.pow(_,3.5))*Oo.no*(To*(1+1.5*w+E*(4+w))+.375*h*to/_*Oo.con41*(8+3*w*(8+w))),Oo.cc1=Oo.bstar*m,x=0,Oo.ecco>1e-4&&(x=-2*g*to*p*Oo.no*Fo/Oo.ecco),Oo.x1mth2=1-Ro,Oo.cc4=2*Oo.no*u*To*Co*(Oo.eta*(2+.5*w)+Oo.ecco*(.5+2*w)-h*to/(To*_)*(-3*Oo.con41*(1-2*E+w*(1.5-.5*E))+.75*Oo.x1mth2*(2*w-E*(1+w))*Math.cos(2*Oo.argpo))),Oo.cc5=2*u*To*Co*(1+2.75*(w+E)+E*w),f=Ro*Ro,$=.5*(X=1.5*h*R*Oo.no)*h*R,oo=-.46875*l*R*R*Oo.no,Oo.mdot=Oo.no+.5*X*Ao*Oo.con41+.0625*$*Ao*(13-78*Ro+137*f),Oo.argpdot=-.5*X*qo+.0625*$*(7-114*Ro+395*f)+oo*(3-36*Ro+49*f),so=-X*No,Oo.nodedot=so+(.5*$*(4-19*Ro)+2*oo*(3-7*Ro))*No,eo=Oo.argpdot+Oo.nodedot,Oo.omgcof=Oo.bstar*x*Math.cos(Oo.argpo),Oo.xmcof=0,Oo.ecco>1e-4&&(Oo.xmcof=-M*g*Oo.bstar/E),Oo.nodecf=3.5*Co*so*Oo.cc1,Oo.t2cof=1.5*Oo.cc1,Math.abs(No+1)>15e-13?Oo.xlcof=-.25*p*Fo*(3+5*No)/(1+No):Oo.xlcof=-.25*p*Fo*(3+5*No)/15e-13,Oo.aycof=-.5*p*Fo;var Io=1+Oo.eta*Math.cos(Oo.mo);if(Oo.delmo=Io*Io*Io,Oo.sinmao=Math.sin(Oo.mo),Oo.x7thm1=7*Ro-1,2*t/Oo.no>=225){Oo.method="d",Oo.isimp=1,T=Oo.inclo;var So=function(o){var t,s,a,n,d,i,r,c,h,m,l,p,M,x,g,u,f,z,v,b,y,O,E,w,T,q,N,R,_,C,D,j,A,F,L,I,S,P,U,Z,B,H,Y,k,G,W,J,K,Q,V,X,$,oo,to,eo,so,ao,no,io,ro,co,ho,mo,lo=o.epoch,po=o.ep,Mo=o.argpp,xo=o.tc,go=o.inclp,uo=o.nodep,fo=.01675,zo=.0549,vo=o.np,bo=po,yo=Math.sin(uo),Oo=Math.cos(uo),Eo=Math.sin(Mo),wo=Math.cos(Mo),To=Math.sin(go),qo=Math.cos(go),No=bo*bo,Ro=1-No,_o=Math.sqrt(Ro),Co=lo+18261.5+xo/1440,Do=(4.523602-.00092422029*Co)%e,jo=Math.sin(Do),Ao=Math.cos(Do),Fo=.91375164-.03568096*Ao,Lo=Math.sqrt(1-Fo*Fo),Io=.089683511*jo/Lo,So=Math.sqrt(1-Io*Io),Po=5.8351514+.001944368*Co,Uo=.39785416*jo/Lo,Zo=So*Ao+.91744867*Io*jo;Uo=Math.atan2(Uo,Zo),Uo+=Po-Do;var Bo=Math.cos(Uo),Ho=Math.sin(Uo);b=.1945905,y=-.98088458,w=.91744867,T=.39785416,O=Oo,E=yo,l=29864797e-13;for(var Yo=1/vo,ko=0;ko<2;)eo=-6*(t=b*O+y*w*E)*(d=-To*(r=-b*E+y*w*O)+qo*(c=y*T))+No*(-24*(p=t*wo+(s=qo*r+To*c)*Eo)*(z=d*wo)-6*(x=-t*Eo+s*wo)*(u=d*Eo)),so=-6*(t*(i=-To*(h=y*E+b*w*O)+qo*(m=b*T))+(a=-y*O+b*w*E)*d)+No*(-24*((M=a*wo+(n=qo*h+To*m)*Eo)*z+p*(v=i*wo))+-6*(x*(f=i*Eo)+(g=-a*Eo+n*wo)*u)),ao=-6*a*i+No*(-24*M*v-6*g*f),no=6*s*d+No*(24*p*u-6*x*z),io=6*(n*d+s*i)+No*(24*(M*u+p*f)-6*(g*z+x*v)),ro=6*n*i+No*(24*M*f-6*g*v),$=($=3*(t*t+s*s)+(co=12*p*p-3*x*x)*No)+$+Ro*co,oo=(oo=6*(t*a+s*n)+(ho=24*p*M-6*x*g)*No)+oo+Ro*ho,to=(to=3*(a*a+n*n)+(mo=12*M*M-3*g*g)*No)+to+Ro*mo,W=-.5*(J=l*Yo)/_o,G=-15*bo*(K=J*_o),Q=p*x+M*g,V=M*x+p*g,X=M*g-p*x,1===(ko+=1)&&(q=G,N=W,R=J,_=K,C=Q,D=V,j=X,A=$,F=oo,L=to,I=eo,S=so,P=ao,U=no,Z=io,B=ro,H=co,Y=ho,k=mo,b=Bo,y=Ho,w=Fo,T=Lo,O=So*Oo+Io*yo,E=yo*So-Oo*Io,l=4.7968065e-7);return{snodm:yo,cnodm:Oo,sinim:To,cosim:qo,sinomm:Eo,cosomm:wo,day:Co,e3:2*G*X,ee2:2*G*V,em:bo,emsq:No,gam:Po,peo:0,pgho:0,pho:0,pinco:0,plo:0,rtemsq:_o,se2:2*q*D,se3:2*q*j,sgh2:2*_*Y,sgh3:2*_*(k-H),sgh4:-18*_*fo,sh2:-2*N*Z,sh3:-2*N*(B-U),si2:2*N*S,si3:2*N*(P-I),sl2:-2*R*F,sl3:-2*R*(L-A),sl4:-2*R*(-21-9*No)*fo,s1:G,s2:W,s3:J,s4:K,s5:Q,s6:V,s7:X,ss1:q,ss2:N,ss3:R,ss4:_,ss5:C,ss6:D,ss7:j,sz1:A,sz2:F,sz3:L,sz11:I,sz12:S,sz13:P,sz21:U,sz22:Z,sz23:B,sz31:H,sz32:Y,sz33:k,xgh2:2*K*ho,xgh3:2*K*(mo-co),xgh4:-18*K*zo,xh2:-2*W*io,xh3:-2*W*(ro-no),xi2:2*W*so,xi3:2*W*(ao-eo),xl2:-2*J*oo,xl3:-2*J*(to-$),xl4:-2*J*(-21-9*No)*zo,nm:vo,z1:$,z2:oo,z3:to,z11:eo,z12:so,z13:ao,z21:no,z22:io,z23:ro,z31:co,z32:ho,z33:mo,zmol:(.2299715*Co-Po+4.7199672)%e,zmos:(6.2565837+.017201977*Co)%e}}({epoch:xo,ep:Oo.ecco,argpp:Oo.argpo,tc:0,inclp:Oo.inclo,nodep:Oo.nodeo,np:Oo.no,e3:Oo.e3,ee2:Oo.ee2,peo:Oo.peo,pgho:Oo.pgho,pho:Oo.pho,pinco:Oo.pinco,plo:Oo.plo,se2:Oo.se2,se3:Oo.se3,sgh2:Oo.sgh2,sgh3:Oo.sgh3,sgh4:Oo.sgh4,sh2:Oo.sh2,sh3:Oo.sh3,si2:Oo.si2,si3:Oo.si3,sl2:Oo.sl2,sl3:Oo.sl3,sl4:Oo.sl4,xgh2:Oo.xgh2,xgh3:Oo.xgh3,xgh4:Oo.xgh4,xh2:Oo.xh2,xh3:Oo.xh3,xi2:Oo.xi2,xi3:Oo.xi3,xl2:Oo.xl2,xl3:Oo.xl3,xl4:Oo.xl4,zmol:Oo.zmol,zmos:Oo.zmos});Oo.e3=So.e3,Oo.ee2=So.ee2,Oo.peo=So.peo,Oo.pgho=So.pgho,Oo.pho=So.pho,Oo.pinco=So.pinco,Oo.plo=So.plo,Oo.se2=So.se2,Oo.se3=So.se3,Oo.sgh2=So.sgh2,Oo.sgh3=So.sgh3,Oo.sgh4=So.sgh4,Oo.sh2=So.sh2,Oo.sh3=So.sh3,Oo.si2=So.si2,Oo.si3=So.si3,Oo.sl2=So.sl2,Oo.sl3=So.sl3,Oo.sl4=So.sl4,n=So.sinim,a=So.cosim,z=So.em,b=So.emsq,D=So.s1,j=So.s2,A=So.s3,F=So.s4,L=So.s5,S=So.ss1,P=So.ss2,U=So.ss3,Z=So.ss4,B=So.ss5,H=So.sz1,Y=So.sz3,k=So.sz11,G=So.sz13,W=So.sz21,J=So.sz23,K=So.sz31,Q=So.sz33,Oo.xgh2=So.xgh2,Oo.xgh3=So.xgh3,Oo.xgh4=So.xgh4,Oo.xh2=So.xh2,Oo.xh3=So.xh3,Oo.xi2=So.xi2,Oo.xi3=So.xi3,Oo.xl2=So.xl2,Oo.xl3=So.xl3,Oo.xl4=So.xl4,Oo.zmol=So.zmol,Oo.zmos=So.zmos,q=So.nm,ao=So.z1,no=So.z3,io=So.z11,ro=So.z13,co=So.z21,ho=So.z23,mo=So.z31,lo=So.z33;var Po=v(Oo,{inclo:T,init:Oo.init,ep:Oo.ecco,inclp:Oo.inclo,nodep:Oo.nodeo,argpp:Oo.argpo,mp:Oo.mo,opsmode:Oo.operationmode});Oo.ecco=Po.ep,Oo.inclo=Po.inclp,Oo.nodeo=Po.nodep,Oo.argpo=Po.argpp,Oo.mo=Po.mp;var Uo=function(o){var s,a,n,d,r,c,h,m,l,p,x,g,u,f,z,v,b,y=o.cosim,O=o.argpo,E=o.s1,w=o.s2,T=o.s3,q=o.s4,N=o.s5,R=o.sinim,_=o.ss1,C=o.ss2,D=o.ss3,j=o.ss4,A=o.ss5,F=o.sz1,L=o.sz3,I=o.sz11,S=o.sz13,P=o.sz21,U=o.sz23,Z=o.sz31,B=o.sz33,H=o.t,Y=o.tc,k=o.gsto,G=o.mo,W=o.mdot,J=o.no,K=o.nodeo,Q=o.nodedot,V=o.xpidot,X=o.z1,$=o.z3,oo=o.z11,to=o.z13,eo=o.z21,so=o.z23,ao=o.z31,no=o.z33,io=o.ecco,ro=o.eccsq,co=o.emsq,ho=o.em,mo=o.argpm,lo=o.inclm,po=o.mm,Mo=o.nm,xo=o.nodem,go=o.irez,uo=o.atime,fo=o.d2201,zo=o.d2211,vo=o.d3210,bo=o.d3222,yo=o.d4410,Oo=o.d4422,Eo=o.d5220,wo=o.d5232,To=o.d5421,qo=o.d5433,No=o.dedt,Ro=o.didt,_o=o.dmdt,Co=o.dnodt,Do=o.domdt,jo=o.del1,Ao=o.del2,Fo=o.del3,Lo=o.xfact,Io=o.xlamo,So=o.xli,Po=o.xni,Uo=.0043752690880113,Zo=.00015835218,Bo=119459e-10;go=0,Mo<.0052359877&&Mo>.0034906585&&(go=1),Mo>=.00826&&Mo<=.00924&&ho>=.5&&(go=2);var Ho=-Bo*C*(P+U);(lo<.052359877||lo>t-.052359877)&&(Ho=0),0!==R&&(Ho/=R);var Yo=-Zo*w*(eo+so);(lo<.052359877||lo>t-.052359877)&&(Yo=0),Do=j*Bo*(Z+B-6)-y*Ho+q*Zo*(ao+no-6),Co=Ho,0!==R&&(Do-=y/R*Yo,Co+=Yo/R);var ko=(k+Y*Uo)%e;if(ho+=(No=_*Bo*A+E*Zo*N)*H,lo+=(Ro=C*Bo*(I+S)+w*Zo*(oo+to))*H,mo+=Do*H,xo+=Co*H,po+=(_o=-Bo*D*(F+L-14-6*co)-Zo*T*(X+$-14-6*co))*H,0!==go){if(z=Math.pow(Mo/i,M),2===go){var Go=ho,Wo=co;b=(ho=io)*(co=ro),ho<=.65?(n=3.616-13.247*ho+16.29*co,d=117.39*ho-19.302-228.419*co+156.591*b,r=109.7927*ho-18.9068-214.6334*co+146.5816*b,c=242.694*ho-41.122-471.094*co+313.953*b,h=841.88*ho-146.407-1629.014*co+1083.435*b,m=3017.977*ho-532.114-5740.032*co+3708.276*b):(n=331.819*ho-72.099-508.738*co+266.724*b,d=1582.851*ho-346.844-2415.925*co+1246.113*b,r=1554.908*ho-342.585-2366.899*co+1215.972*b,c=4758.686*ho-1052.797-7193.992*co+3651.957*b,h=16178.11*ho-3581.69-24462.77*co+12422.52*b,m=ho>.715?29936.92*ho-5149.66-54087.36*co+31324.56*b:1464.74-4664.75*ho+3763.64*co),ho<.7?(x=4988.61*ho-919.2277-9064.77*co+5542.21*b,l=4568.6173*ho-822.71072-8491.4146*co+5337.524*b,p=4690.25*ho-853.666-8624.77*co+5341.4*b):(x=161616.52*ho-37995.78-229838.2*co+109377.94*b,l=218913.95*ho-51752.104-309468.16*co+146349.42*b,p=170470.89*ho-40023.88-242699.48*co+115605.82*b),fo=(u=17891679e-13*(f=Mo*Mo*3*(z*z)))*(s=.75*(1+2*y+(v=y*y)))*(-.306-.44*(ho-.64)),zo=u*(1.5*(g=R*R))*n,vo=(u=3.7393792e-7*(f*=z))*(1.875*R*(1-2*y-3*v))*d,bo=u*(-1.875*R*(1+2*y-3*v))*r,yo=(u=2*(f*=z)*7.3636953e-9)*(35*g*s)*c,Oo=u*(39.375*g*g)*h,Eo=(u=1.1428639e-7*(f*=z))*(9.84375*R*(g*(1-2*y-5*v)+.33333333*(4*y-2+6*v)))*m,wo=u*(R*(4.92187512*g*(-2-4*y+10*v)+6.56250012*(1+2*y-3*v)))*p,To=(u=2*f*2.1765803e-9)*(29.53125*R*(2-8*y+v*(8*y-12+10*v)))*l,qo=u*(29.53125*R*(-2-8*y+v*(12+8*y-10*v)))*x,Io=(G+K+K-(ko+ko))%e,Lo=W+_o+2*(Q+Co-Uo)-J,ho=Go,co=Wo}1===go&&(a=1+y,Ao=2*(jo=3*Mo*Mo*z*z)*(s=.75*(1+y)*(1+y))*(1+co*(.8125*co-2.5))*17891679e-13,Fo=3*jo*(a*=1.875*a*a)*(1+co*(6.60937*co-6))*2.2123015e-7*z,jo=jo*(.9375*R*R*(1+3*y)-.75*(1+y))*(d=1+2*co)*21460748e-13*z,Io=(G+K+O-ko)%e,Lo=W+V+_o+Do+Co-(J+Uo)),So=Io,Po=J,uo=0,Mo=J+0}return{em:ho,argpm:mo,inclm:lo,mm:po,nm:Mo,nodem:xo,irez:go,atime:uo,d2201:fo,d2211:zo,d3210:vo,d3222:bo,d4410:yo,d4422:Oo,d5220:Eo,d5232:wo,d5421:To,d5433:qo,dedt:No,didt:Ro,dmdt:_o,dndt:0,dnodt:Co,domdt:Do,del1:jo,del2:Ao,del3:Fo,xfact:Lo,xlamo:Io,xli:So,xni:Po}}({cosim:a,emsq:b,argpo:Oo.argpo,s1:D,s2:j,s3:A,s4:F,s5:L,sinim:n,ss1:S,ss2:P,ss3:U,ss4:Z,ss5:B,sz1:H,sz3:Y,sz11:k,sz13:G,sz21:W,sz23:J,sz31:K,sz33:Q,t:Oo.t,tc:0,gsto:Oo.gsto,mo:Oo.mo,mdot:Oo.mdot,no:Oo.no,nodeo:Oo.nodeo,nodedot:Oo.nodedot,xpidot:eo,z1:ao,z3:no,z11:io,z13:ro,z21:co,z23:ho,z31:mo,z33:lo,ecco:Oo.ecco,eccsq:_o,em:z,argpm:0,inclm:T,mm:0,nm:q,nodem:0,irez:Oo.irez,atime:Oo.atime,d2201:Oo.d2201,d2211:Oo.d2211,d3210:Oo.d3210,d3222:Oo.d3222,d4410:Oo.d4410,d4422:Oo.d4422,d5220:Oo.d5220,d5232:Oo.d5232,d5421:Oo.d5421,d5433:Oo.d5433,dedt:Oo.dedt,didt:Oo.didt,dmdt:Oo.dmdt,dnodt:Oo.dnodt,domdt:Oo.domdt,del1:Oo.del1,del2:Oo.del2,del3:Oo.del3,xfact:Oo.xfact,xlamo:Oo.xlamo,xli:Oo.xli,xni:Oo.xni});Oo.irez=Uo.irez,Oo.atime=Uo.atime,Oo.d2201=Uo.d2201,Oo.d2211=Uo.d2211,Oo.d3210=Uo.d3210,Oo.d3222=Uo.d3222,Oo.d4410=Uo.d4410,Oo.d4422=Uo.d4422,Oo.d5220=Uo.d5220,Oo.d5232=Uo.d5232,Oo.d5421=Uo.d5421,Oo.d5433=Uo.d5433,Oo.dedt=Uo.dedt,Oo.didt=Uo.didt,Oo.dmdt=Uo.dmdt,Oo.dnodt=Uo.dnodt,Oo.domdt=Uo.domdt,Oo.del1=Uo.del1,Oo.del2=Uo.del2,Oo.del3=Uo.del3,Oo.xfact=Uo.xfact,Oo.xlamo=Uo.xlamo,Oo.xli=Uo.xli,Oo.xni=Uo.xni}1!==Oo.isimp&&(r=Oo.cc1*Oo.cc1,Oo.d2=4*To*to*r,V=Oo.d2*to*Oo.cc1/3,Oo.d3=(17*To+I)*V,Oo.d4=.5*V*To*to*(221*To+31*I)*Oo.cc1,Oo.t3cof=Oo.d2+2*r,Oo.t4cof=.25*(3*Oo.d3+Oo.cc1*(12*Oo.d2+10*r)),Oo.t5cof=.2*(3*Oo.d4+12*Oo.cc1*Oo.d3+6*Oo.d2*Oo.d2+15*r*(2*Oo.d2+r)))}O(Oo,0),Oo.init="n"}!function(o){o[o.None=0]="None",o[o.MeanEccentricityOutOfRange=1]="MeanEccentricityOutOfRange",o[o.MeanMotionBelowZero=2]="MeanMotionBelowZero",o[o.PerturbedEccentricityOutOfRange=3]="PerturbedEccentricityOutOfRange",o[o.SemiLatusRectumBelowZero=4]="SemiLatusRectumBelowZero",o[o.Decayed=6]="Decayed"}(o||(o={}));var w=Object.freeze({__proto__:null}),T=7292115e-11;function q(o){return o*a}function N(o){return o*s}function R(o){var t=o.longitude,e=o.latitude,s=o.height,a=6378.137,n=(a-6356.7523142)/a,d=2*n-n*n,i=a/Math.sqrt(1-d*(Math.sin(e)*Math.sin(e)));return{x:(i+s)*Math.cos(e)*Math.cos(t),y:(i+s)*Math.cos(e)*Math.sin(t),z:(i*(1-d)+s)*Math.sin(e)}}var _=Object.assign(Object.assign({constants:g,propagate:function(o){for(var t=arguments.length,e=new Array(t>1?t-1:0),s=1;s1&&void 0!==arguments[1]?arguments[1]:"i",e=o.NORAD_CAT_ID.toString(),a=new Date(o.EPOCH.endsWith("Z")?o.EPOCH:o.EPOCH+"Z"),n=a.getUTCFullYear(),d=Number(n.toString().slice(-2)),i=(a.valueOf()-new Date(Date.UTC(n,0,1,0,0,0)).valueOf())/864e5+1,r=Number(o.MEAN_MOTION_DOT),c=Number(o.MEAN_MOTION_DDOT),h=Number(o.BSTAR),m=Number(o.INCLINATION)*s,l=Number(o.RA_OF_ASC_NODE)*s,p=Number(o.ECCENTRICITY),M=Number(o.ARG_OF_PERICENTER)*s,g=Number(o.MEAN_ANOMALY)*s,f=Number(o.MEAN_MOTION)/x,v=u(n,i),b={error:0,satnum:e,epochyr:d,epochdays:i,ndot:r,nddot:c,bstar:h,inclo:m,nodeo:l,ecco:p,argpo:M,mo:g,no:f,jdsatepoch:z(n,v.mon,v.day,v.hr,v.minute,v.sec)};return E(b,{opsmode:t,satn:b.satnum,epoch:b.jdsatepoch-2433281.5,xbstar:b.bstar,xecco:b.ecco,xargpo:b.argpo,xinclo:b.inclo,xmo:b.mo,xno:b.no,xnodeo:b.nodeo}),b},gstime:y,jday:z,invjday:function(o,t){var e=o-2415019.5,s=e/365.25,a=1900+Math.floor(s),n=Math.floor(.25*(a-1901)),d=e-(365*(a-1900)+n)+1e-11;d<1&&(d=e-(365*((a-=1)-1900)+(n=Math.floor(.25*(a-1901)))));var i=u(a,d),r=i.mon,c=i.day,h=i.hr,m=i.minute,l=i.sec-864e-9;return t?[a,r,c,h,m,Math.floor(l)]:new Date(Date.UTC(a,r-1,c,h,m,Math.floor(l)))},dopplerFactor:function(o,t,e){var s=t.x-o.x,a=t.y-o.y,n=t.z-o.z,d=Math.sqrt(Math.pow(s,2)+Math.pow(a,2)+Math.pow(n,2));return 1-(s*(e.x+T*o.y)+a*(e.y-T*o.x)+n*e.z)/d/299792.458},radiansToDegrees:q,degreesToRadians:N,degreesLat:function(o){if(o<-t/2||o>t/2)throw new RangeError("Latitude radians must be in range [-pi/2; pi/2].");return q(o)},degreesLong:function(o){if(o<-t||o>t)throw new RangeError("Longitude radians must be in range [-pi; pi].");return q(o)},radiansLat:function(o){if(o<-90||o>90)throw new RangeError("Latitude degrees must be in range [-90; 90].");return N(o)},radiansLong:function(o){if(o<-180||o>180)throw new RangeError("Longitude degrees must be in range [-180; 180].");return N(o)},geodeticToEcf:R,eciToGeodetic:function(o,s){for(var a=6378.137,n=Math.sqrt(o.x*o.x+o.y*o.y),d=(a-6356.7523142)/a,i=2*d-d*d,r=Math.atan2(o.y,o.x)-s;r<-t;)r+=e;for(;r>t;)r-=e;for(var c,h=0,m=Math.atan2(o.z,Math.sqrt(o.x*o.x+o.y*o.y));h++<20;)c=1/Math.sqrt(1-i*(Math.sin(m)*Math.sin(m))),m=Math.atan2(o.z+a*c*i*Math.sin(m),n);return{longitude:r,latitude:m,height:n/Math.cos(m)-a*c}},eciToEcf:function(o,t){return{x:o.x*Math.cos(t)+o.y*Math.sin(t),y:o.x*-Math.sin(t)+o.y*Math.cos(t),z:o.z}},ecfToEci:function(o,t){return{x:o.x*Math.cos(t)-o.y*Math.sin(t),y:o.x*Math.sin(t)+o.y*Math.cos(t),z:o.z}},ecfToLookAngles:function(o,e){var s,a,n,d,i,r,c=function(o,t){var e=o.longitude,s=o.latitude,a=R(o),n=t.x-a.x,d=t.y-a.y,i=t.z-a.z;return{topS:Math.sin(s)*Math.cos(e)*n+Math.sin(s)*Math.sin(e)*d-Math.cos(s)*i,topE:-Math.sin(e)*n+Math.cos(e)*d,topZ:Math.cos(s)*Math.cos(e)*n+Math.cos(s)*Math.sin(e)*d+Math.sin(s)*i}}(o,e);return a=(s=c).topS,n=s.topE,d=s.topZ,i=Math.sqrt(a*a+n*n+d*d),r=Math.asin(d/i),{azimuth:Math.atan2(-n,a)+t,elevation:r,rangeSat:i}},sunPos:function(o){var a=(o-2451545)/36525,n=a,d=(357.5277233+35999.05034*n*s)%e;d<0&&(d+=e);var i=((280.46+36000.77*a)%360+1.914666471*Math.sin(d)+.019994643*Math.sin(2*d))%360*s,r=(23.439291-.0130042*n)*s,c=1.000140612-.016708617*Math.cos(d)-139589e-9*Math.cos(2*d),h=[c*Math.cos(i),c*Math.cos(r)*Math.sin(i),c*Math.sin(r)*Math.sin(i)],m=Math.atan(Math.cos(r)*Math.tan(i)),l=m;return Math.abs(i-l)>.5*t&&(l+=.5*t*Math.round((i-m)/(.5*t))),{rsun:h,rtasc:l,decl:Math.asin(Math.sin(r)*Math.sin(i))}}},w),{SatRecError:o});return _})); diff --git a/node_modules/satellite.js/eslint.config.mjs b/node_modules/satellite.js/eslint.config.mjs new file mode 100644 index 0000000..bd07ae1 --- /dev/null +++ b/node_modules/satellite.js/eslint.config.mjs @@ -0,0 +1,30 @@ +import eslint from '@eslint/js'; +import tseslint from 'typescript-eslint'; + +export default tseslint.config( + eslint.configs.recommended, + tseslint.configs.strict, + tseslint.configs.stylistic, + { + languageOptions: { + parserOptions: { + projectService: true, + tsconfigRootDir: import.meta.dirname, + }, + }, + }, + { + ignores: ['/dist', '/lib', '*.mjs'] + }, + { + rules: { + '@typescript-eslint/unified-signatures': ['error', { + 'ignoreDifferentlyNamedParameters': true + }], + // since much of the propagation code is built on loops and if statements, + // and typescript doesn't follow when a variable is assigned there, + // this rule is disabled + '@typescript-eslint/no-non-null-assertion': 'off' + } + } +); diff --git a/node_modules/satellite.js/lib/common-types.js b/node_modules/satellite.js/lib/common-types.js new file mode 100644 index 0000000..430afc1 --- /dev/null +++ b/node_modules/satellite.js/lib/common-types.js @@ -0,0 +1,5 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); \ No newline at end of file diff --git a/node_modules/satellite.js/lib/constants.js b/node_modules/satellite.js/lib/constants.js new file mode 100644 index 0000000..b5caa54 --- /dev/null +++ b/node_modules/satellite.js/lib/constants.js @@ -0,0 +1,22 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.xpdotp = exports.xke = exports.x2o3 = exports.vkmpersec = exports.twoPi = exports.tumin = exports.rad2deg = exports.pi = exports.mu = exports.minutesPerDay = exports.j4 = exports.j3oj2 = exports.j3 = exports.j2 = exports.earthRadius = exports.deg2rad = void 0; +var pi = exports.pi = Math.PI; +var twoPi = exports.twoPi = pi * 2; +var deg2rad = exports.deg2rad = pi / 180.0; +var rad2deg = exports.rad2deg = 180 / pi; +var minutesPerDay = exports.minutesPerDay = 1440.0; +var mu = exports.mu = 398600.8; // in km3 / s2 +var earthRadius = exports.earthRadius = 6378.135; // in km +var xke = exports.xke = 60.0 / Math.sqrt(earthRadius * earthRadius * earthRadius / mu); +var vkmpersec = exports.vkmpersec = earthRadius * xke / 60.0; +var tumin = exports.tumin = 1.0 / xke; +var j2 = exports.j2 = 0.001082616; +var j3 = exports.j3 = -0.00000253881; +var j4 = exports.j4 = -0.00000165597; +var j3oj2 = exports.j3oj2 = j3 / j2; +var x2o3 = exports.x2o3 = 2.0 / 3.0; +var xpdotp = exports.xpdotp = 1440.0 / (2.0 * pi); // 229.1831180523293; \ No newline at end of file diff --git a/node_modules/satellite.js/lib/dopplerFactor.js b/node_modules/satellite.js/lib/dopplerFactor.js new file mode 100644 index 0000000..e3f7e3a --- /dev/null +++ b/node_modules/satellite.js/lib/dopplerFactor.js @@ -0,0 +1,27 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = dopplerFactor; +var earthRotation = 7.292115E-5; +var c = 299792.458; // Speed of light in km/s +/** + * Negative range rate means the satellite is moving towards the observer and + * its frequency is shifted higher because 1 minus a negative range rate is + * positive. If the range rate is positive, the satellite is moving away from + * the observer and its frequency is shifted lower. + */ +function dopplerFactor(observerCoordsEcf, positionEcf, velocityEcf) { + var rangeX = positionEcf.x - observerCoordsEcf.x; + var rangeY = positionEcf.y - observerCoordsEcf.y; + var rangeZ = positionEcf.z - observerCoordsEcf.z; + var length = Math.sqrt(Math.pow(rangeX, 2) + Math.pow(rangeY, 2) + Math.pow(rangeZ, 2)); + var rangeVel = { + x: velocityEcf.x + earthRotation * observerCoordsEcf.y, + y: velocityEcf.y - earthRotation * observerCoordsEcf.x, + z: velocityEcf.z + }; + var rangeRate = (rangeX * rangeVel.x + rangeY * rangeVel.y + rangeZ * rangeVel.z) / length; + return 1 - rangeRate / c; +} \ No newline at end of file diff --git a/node_modules/satellite.js/lib/ext.js b/node_modules/satellite.js/lib/ext.js new file mode 100644 index 0000000..b63c8e6 --- /dev/null +++ b/node_modules/satellite.js/lib/ext.js @@ -0,0 +1,145 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.days2mdhms = days2mdhms; +exports.invjday = invjday; +exports.jday = jday; +/* ----------------------------------------------------------------------------- + * + * procedure days2mdhms + * + * this procedure converts the day of the year, days, to the equivalent month + * day, hour, minute and second. + * + * algorithm : set up array for the number of days per month + * find leap year - use 1900 because 2000 is a leap year + * loop through a temp value while the value is < the days + * perform int conversions to the correct day and month + * convert remainder into h m s using type conversions + * + * author : david vallado 719-573-2600 1 mar 2001 + * + * inputs description range / units + * year - year 1900 .. 2100 + * days - julian day of the year 0.0 .. 366.0 + * + * outputs : + * mon - month 1 .. 12 + * day - day 1 .. 28,29,30,31 + * hr - hour 0 .. 23 + * min - minute 0 .. 59 + * sec - second 0.0 .. 59.999 + * + * locals : + * dayofyr - day of year + * temp - temporary extended values + * inttemp - temporary int value + * i - index + * lmonth[12] - int array containing the number of days per month + * + * coupling : + * none. + * --------------------------------------------------------------------------- */ +function days2mdhms(year, days) { + var lmonth = [31, year % 4 === 0 ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + var dayofyr = Math.floor(days); + // ----------------- find month and day of month ---------------- + var i = 1; + var inttemp = 0; + // i starts from 1 so no null check is needed + while (dayofyr > inttemp + lmonth[i - 1] && i < 12) { + inttemp += lmonth[i - 1]; + i += 1; + } + var mon = i; + var day = dayofyr - inttemp; + // ----------------- find hours minutes and seconds ------------- + var temp = (days - dayofyr) * 24.0; + var hr = Math.floor(temp); + temp = (temp - hr) * 60.0; + var minute = Math.floor(temp); + var sec = (temp - minute) * 60.0; + return { + mon: mon, + day: day, + hr: hr, + minute: minute, + sec: sec + }; +} +/* ----------------------------------------------------------------------------- + * + * procedure jday + * + * this procedure finds the julian date given the year, month, day, and time. + * the julian date is defined by each elapsed day since noon, jan 1, 4713 bc. + * + * algorithm : calculate the answer in one step for efficiency + * + * author : david vallado 719-573-2600 1 mar 2001 + * + * inputs description range / units + * year - year 1900 .. 2100 + * mon - month 1 .. 12 + * day - day 1 .. 28,29,30,31 + * hr - universal time hour 0 .. 23 + * min - universal time min 0 .. 59 + * sec - universal time sec 0.0 .. 59.999 + * + * outputs : + * jd - julian date days from 4713 bc + * + * locals : + * none. + * + * coupling : + * none. + * + * references : + * vallado 2007, 189, alg 14, ex 3-14 + * + * --------------------------------------------------------------------------- */ +function jdayInternal(year, mon, day, hr, minute, sec) { + var msec = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0; + return 367.0 * year - Math.floor(7 * (year + Math.floor((mon + 9) / 12.0)) * 0.25) + Math.floor(275 * mon / 9.0) + day + 1721013.5 + ((msec / 60000 + sec / 60.0 + minute) / 60.0 + hr) / 24.0 // ut in days + // # - 0.5*sgn(100.0*year + mon - 190002.5) + 0.5; + ; +} +function jday(yearOrDate, mon, day, hr, minute, sec) { + var msec = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 0; + if (yearOrDate instanceof Date) { + var date = yearOrDate; + return jdayInternal(date.getUTCFullYear(), date.getUTCMonth() + 1, + // Note, this function requires months in range 1-12. + date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.getUTCMilliseconds()); + } + return jdayInternal(yearOrDate, mon, day, hr, minute, sec, msec); +} +function invjday(jd, asArray) { + // --------------- find year and days of the year - + var temp = jd - 2415019.5; + var tu = temp / 365.25; + var year = 1900 + Math.floor(tu); + var leapyrs = Math.floor((year - 1901) * 0.25); + // optional nudge by 8.64x10-7 sec to get even outputs + var days = temp - ((year - 1900) * 365.0 + leapyrs) + 0.00000000001; + // ------------ check for case of beginning of a year ----------- + if (days < 1.0) { + year -= 1; + leapyrs = Math.floor((year - 1901) * 0.25); + days = temp - ((year - 1900) * 365.0 + leapyrs); + } + // ----------------- find remaing data ------------------------- + var mdhms = days2mdhms(year, days); + var mon = mdhms.mon, + day = mdhms.day, + hr = mdhms.hr, + minute = mdhms.minute; + var sec = mdhms.sec - 0.00000086400; + if (asArray) { + return [year, mon, day, hr, minute, Math.floor(sec)]; + } + return new Date(Date.UTC(year, mon - 1, day, hr, minute, Math.floor(sec))); +} \ No newline at end of file diff --git a/node_modules/satellite.js/lib/index.js b/node_modules/satellite.js/lib/index.js new file mode 100644 index 0000000..3e9d499 --- /dev/null +++ b/node_modules/satellite.js/lib/index.js @@ -0,0 +1,181 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +var _exportNames = { + constants: true, + jday: true, + invjday: true, + twoline2satrec: true, + json2satrec: true, + propagate: true, + sgp4: true, + gstime: true, + dopplerFactor: true, + radiansToDegrees: true, + degreesToRadians: true, + degreesLat: true, + degreesLong: true, + radiansLat: true, + radiansLong: true, + geodeticToEcf: true, + eciToGeodetic: true, + eciToEcf: true, + ecfToEci: true, + ecfToLookAngles: true, + sunPos: true, + SatRecError: true +}; +Object.defineProperty(exports, "SatRecError", { + enumerable: true, + get: function get() { + return _SatRec.SatRecError; + } +}); +exports.constants = void 0; +Object.defineProperty(exports, "degreesLat", { + enumerable: true, + get: function get() { + return _transforms.degreesLat; + } +}); +Object.defineProperty(exports, "degreesLong", { + enumerable: true, + get: function get() { + return _transforms.degreesLong; + } +}); +Object.defineProperty(exports, "degreesToRadians", { + enumerable: true, + get: function get() { + return _transforms.degreesToRadians; + } +}); +Object.defineProperty(exports, "dopplerFactor", { + enumerable: true, + get: function get() { + return _dopplerFactor["default"]; + } +}); +Object.defineProperty(exports, "ecfToEci", { + enumerable: true, + get: function get() { + return _transforms.ecfToEci; + } +}); +Object.defineProperty(exports, "ecfToLookAngles", { + enumerable: true, + get: function get() { + return _transforms.ecfToLookAngles; + } +}); +Object.defineProperty(exports, "eciToEcf", { + enumerable: true, + get: function get() { + return _transforms.eciToEcf; + } +}); +Object.defineProperty(exports, "eciToGeodetic", { + enumerable: true, + get: function get() { + return _transforms.eciToGeodetic; + } +}); +Object.defineProperty(exports, "geodeticToEcf", { + enumerable: true, + get: function get() { + return _transforms.geodeticToEcf; + } +}); +Object.defineProperty(exports, "gstime", { + enumerable: true, + get: function get() { + return _propagation.gstime; + } +}); +Object.defineProperty(exports, "invjday", { + enumerable: true, + get: function get() { + return _ext.invjday; + } +}); +Object.defineProperty(exports, "jday", { + enumerable: true, + get: function get() { + return _ext.jday; + } +}); +Object.defineProperty(exports, "json2satrec", { + enumerable: true, + get: function get() { + return _io.json2satrec; + } +}); +Object.defineProperty(exports, "propagate", { + enumerable: true, + get: function get() { + return _propagation.propagate; + } +}); +Object.defineProperty(exports, "radiansLat", { + enumerable: true, + get: function get() { + return _transforms.radiansLat; + } +}); +Object.defineProperty(exports, "radiansLong", { + enumerable: true, + get: function get() { + return _transforms.radiansLong; + } +}); +Object.defineProperty(exports, "radiansToDegrees", { + enumerable: true, + get: function get() { + return _transforms.radiansToDegrees; + } +}); +Object.defineProperty(exports, "sgp4", { + enumerable: true, + get: function get() { + return _propagation.sgp4; + } +}); +Object.defineProperty(exports, "sunPos", { + enumerable: true, + get: function get() { + return _sun.sunPos; + } +}); +Object.defineProperty(exports, "twoline2satrec", { + enumerable: true, + get: function get() { + return _io.twoline2satrec; + } +}); +var constants_1 = _interopRequireWildcard(require("./constants")); +exports.constants = constants_1; +var _ext = require("./ext"); +var _io = require("./io"); +var _propagation = require("./propagation"); +var _dopplerFactor = _interopRequireDefault(require("./dopplerFactor")); +var _transforms = require("./transforms"); +var _sun = require("./sun"); +var _SatRec = require("./propagation/SatRec.js"); +var _commonTypes = require("./common-types.js"); +Object.keys(_commonTypes).forEach(function (key) { + if (key === "default" || key === "__esModule") return; + if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return; + if (key in exports && exports[key] === _commonTypes[key]) return; + Object.defineProperty(exports, key, { + enumerable: true, + get: function get() { + return _commonTypes[key]; + } + }); +}); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } \ No newline at end of file diff --git a/node_modules/satellite.js/lib/indexUmd.js b/node_modules/satellite.js/lib/indexUmd.js new file mode 100644 index 0000000..c2b7a81 --- /dev/null +++ b/node_modules/satellite.js/lib/indexUmd.js @@ -0,0 +1,47 @@ +"use strict"; + +function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); } +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var constants = _interopRequireWildcard(require("./constants")); +var _ext = require("./ext"); +var _io = require("./io"); +var _propagation = require("./propagation"); +var _SatRec = require("./propagation/SatRec.js"); +var types = _interopRequireWildcard(require("./common-types.js")); +var _dopplerFactor = _interopRequireDefault(require("./dopplerFactor")); +var _transforms = require("./transforms"); +var _sun = require("./sun"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); } +function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { "default": e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n["default"] = e, t && t.set(e, n), n; } +var _default = exports["default"] = Object.assign(Object.assign({ + constants: constants, + // Propagation + propagate: _propagation.propagate, + sgp4: _propagation.sgp4, + twoline2satrec: _io.twoline2satrec, + json2satrec: _io.json2satrec, + gstime: _propagation.gstime, + jday: _ext.jday, + invjday: _ext.invjday, + dopplerFactor: _dopplerFactor["default"], + // Coordinate transforms + radiansToDegrees: _transforms.radiansToDegrees, + degreesToRadians: _transforms.degreesToRadians, + degreesLat: _transforms.degreesLat, + degreesLong: _transforms.degreesLong, + radiansLat: _transforms.radiansLat, + radiansLong: _transforms.radiansLong, + geodeticToEcf: _transforms.geodeticToEcf, + eciToGeodetic: _transforms.eciToGeodetic, + eciToEcf: _transforms.eciToEcf, + ecfToEci: _transforms.ecfToEci, + ecfToLookAngles: _transforms.ecfToLookAngles, + // Sun Position + sunPos: _sun.sunPos +}, types), { + SatRecError: _SatRec.SatRecError +}); \ No newline at end of file diff --git a/node_modules/satellite.js/lib/io.js b/node_modules/satellite.js/lib/io.js new file mode 100644 index 0000000..679379c --- /dev/null +++ b/node_modules/satellite.js/lib/io.js @@ -0,0 +1,233 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.json2satrec = json2satrec; +exports.twoline2satrec = twoline2satrec; +var _constants = require("./constants"); +var _ext = require("./ext"); +var _sgp4init = _interopRequireDefault(require("./propagation/sgp4init")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/* ----------------------------------------------------------------------------- + * + * function twoline2satrec + * + * this function converts the two line element set character string data to + * variables and initializes the sgp4 variables. several intermediate varaibles + * and quantities are determined. note that the result is a structure so multiple + * satellites can be processed simultaneously without having to reinitialize. the + * verification mode is an important option that permits quick checks of any + * changes to the underlying technical theory. this option works using a + * modified tle file in which the start, stop, and delta time values are + * included at the end of the second line of data. this only works with the + * verification mode. the catalog mode simply propagates from -1440 to 1440 min + * from epoch and is useful when performing entire catalog runs. + * + * author : david vallado 719-573-2600 1 mar 2001 + * + * inputs : + * longstr1 - first line of the tle + * longstr2 - second line of the tle + * typerun - type of run verification 'v', catalog 'c', + * manual 'm' + * typeinput - type of manual input mfe 'm', epoch 'e', dayofyr 'd' + * opsmode - mode of operation afspc or improved 'a', 'i' + * whichconst - which set of constants to use 72, 84 + * + * outputs : + * satrec - structure containing all the sgp4 satellite information + * + * coupling : + * getgravconst- + * days2mdhms - conversion of days to month, day, hour, minute, second + * jday - convert day month year hour minute second into julian date + * sgp4init - initialize the sgp4 variables + * + * references : + * norad spacetrack report #3 + * vallado, crawford, hujsak, kelso 2006 + --------------------------------------------------------------------------- */ +/** + * Return a Satellite imported from two lines of TLE data. + * + * Provide the two TLE lines as strings `tleLine1` and `tleLine2`, + * and select which standard set of gravitational constants you want + * by providing `gravity_constants`: + * + * `sgp4.propagation.wgs72` - Standard WGS 72 model + * `sgp4.propagation.wgs84` - More recent WGS 84 model + * `sgp4.propagation.wgs72old` - Legacy support for old SGP4 behavior + * + * Normally, computations are made using letious recent improvements + * to the algorithm. If you want to turn some of these off and go + * back into "afspc" mode, then set `afspc_mode` to `True`. + */ +function twoline2satrec(longstr1, longstr2) { + var opsmode = 'i'; + var error = 0; + var satnum = longstr1.substring(2, 7); + var epochyr = parseInt(longstr1.substring(18, 20), 10); + var epochdays = parseFloat(longstr1.substring(20, 32)); + var ndot = parseFloat(longstr1.substring(33, 43)); + var nddot = parseFloat("".concat(longstr1.substring(44, 45), ".").concat(longstr1.substring(45, 50), "E").concat(longstr1.substring(50, 52))); + var bstar = parseFloat("".concat(longstr1.substring(53, 54), ".").concat(longstr1.substring(54, 59), "E").concat(longstr1.substring(59, 61))); + // satrec.satnum = longstr2.substring(2, 7); + // ---- find standard orbital elements ---- + var inclo = parseFloat(longstr2.substring(8, 16)) * _constants.deg2rad; + var nodeo = parseFloat(longstr2.substring(17, 25)) * _constants.deg2rad; + var ecco = parseFloat(".".concat(longstr2.substring(26, 33).replace(/\s/g, '0'))); + var argpo = parseFloat(longstr2.substring(34, 42)) * _constants.deg2rad; + var mo = parseFloat(longstr2.substring(43, 51)) * _constants.deg2rad; + // ---- find no, ndot, nddot ---- + var no = parseFloat(longstr2.substring(52, 63)) / _constants.xpdotp; + // satrec.nddot= satrec.nddot * Math.pow(10.0, nexp); + // satrec.bstar= satrec.bstar * Math.pow(10.0, ibexp); + // ---- convert to sgp4 units ---- + // satrec.ndot /= (xpdotp * 1440.0); // ? * minperday + // satrec.nddot /= (xpdotp * 1440.0 * 1440); + // ---------------------------------------------------------------- + // find sgp4epoch time of element set + // remember that sgp4 uses units of days from 0 jan 1950 (sgp4epoch) + // and minutes from the epoch (time) + // ---------------------------------------------------------------- + // ---------------- temp fix for years from 1957-2056 ------------------- + // --------- correct fix will occur when year is 4-digit in tle --------- + var year = epochyr < 57 ? epochyr + 2000 : epochyr + 1900; + var mdhmsResult = (0, _ext.days2mdhms)(year, epochdays); + var mon = mdhmsResult.mon, + day = mdhmsResult.day, + hr = mdhmsResult.hr, + minute = mdhmsResult.minute, + sec = mdhmsResult.sec; + var jdsatepoch = (0, _ext.jday)(year, mon, day, hr, minute, sec); + var satrec = { + error: error, + satnum: satnum, + epochyr: epochyr, + epochdays: epochdays, + ndot: ndot, + nddot: nddot, + bstar: bstar, + inclo: inclo, + nodeo: nodeo, + ecco: ecco, + argpo: argpo, + mo: mo, + no: no, + jdsatepoch: jdsatepoch + }; + // ---------------- initialize the orbit at sgp4epoch ------------------- + (0, _sgp4init["default"])(satrec, { + opsmode: opsmode, + satn: satrec.satnum, + epoch: satrec.jdsatepoch - 2433281.5, + xbstar: satrec.bstar, + xecco: satrec.ecco, + xargpo: satrec.argpo, + xinclo: satrec.inclo, + xmo: satrec.mo, + xno: satrec.no, + xnodeo: satrec.nodeo + }); + return satrec; +} +/* ----------------------------------------------------------------------------- + * + * function json2satrec + * + * this function converts the OMM json data to variables and initializes the sgp4 + * variables. several intermediate varaibles and quantities are determined. note + * that the result is a structure so multiple satellites can be processed + * simultaneously without having to reinitialize. the verification mode is an + * important option that permits quick checks of any changes to the underlying + * technical theory. this option works using a modified tle file in which the + * start, stop, and delta time values are included at the end of the second line + * of data. this only works with the verification mode. the catalog mode simply + * propagates from -1440 to 1440 min from epoch and is useful when performing + * entire catalog runs. + * + * author : Hariharan Vitaladevuni 18 Aug 2023 + * Theodore Kruczek 19 Aug 2023 + * + * inputs : + * jsonobj - OMM json data + * opsmode - mode of operation afspc or improved 'a', 'i'. Default: 'i'. + * + * outputs : + * satrec - structure containing all the sgp4 satellite information + * + * coupling : + * days2mdhms - conversion of days to month, day, hour, minute, second + * jday - convert day month year hour minute second into julian date + * sgp4init - initialize the sgp4 variables + * + * warning : the epoch date in OMM format is more accurate than TLE format! + * this will result in extremely close, but different + * position/velocity values. Depending on your use case, it may + * be better to use twoline2satrec, but for the average user this + * will provide comparable results. + * + * references : + * https://celestrak.org/NORAD/documentation/gp-data-formats.php + --------------------------------------------------------------------------- */ +function json2satrec(jsonobj) { + var opsmode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'i'; + var error = 0; + var satnum = jsonobj.NORAD_CAT_ID.toString(); + var epoch = new Date(jsonobj.EPOCH.endsWith('Z') ? jsonobj.EPOCH : jsonobj.EPOCH + 'Z'); + var year = epoch.getUTCFullYear(); + var epochyr = Number(year.toString().slice(-2)); + var epochdays = (epoch.valueOf() - new Date(Date.UTC(year, 0, 1, 0, 0, 0)).valueOf()) / (86400 * 1000) + 1; + var ndot = Number(jsonobj.MEAN_MOTION_DOT); + var nddot = Number(jsonobj.MEAN_MOTION_DDOT); + var bstar = Number(jsonobj.BSTAR); + var inclo = Number(jsonobj.INCLINATION) * _constants.deg2rad; + var nodeo = Number(jsonobj.RA_OF_ASC_NODE) * _constants.deg2rad; + var ecco = Number(jsonobj.ECCENTRICITY); + var argpo = Number(jsonobj.ARG_OF_PERICENTER) * _constants.deg2rad; + var mo = Number(jsonobj.MEAN_ANOMALY) * _constants.deg2rad; + var no = Number(jsonobj.MEAN_MOTION) / _constants.xpdotp; + // ---------------------------------------------------------------- + // find sgp4epoch time of element set + // remember that sgp4 uses units of days from 0 jan 1950 (sgp4epoch) + // and minutes from the epoch (time) + // ---------------------------------------------------------------- + var mdhmsResult = (0, _ext.days2mdhms)(year, epochdays); + var mon = mdhmsResult.mon, + day = mdhmsResult.day, + hr = mdhmsResult.hr, + minute = mdhmsResult.minute, + sec = mdhmsResult.sec; + var jdsatepoch = (0, _ext.jday)(year, mon, day, hr, minute, sec); + var satrec = { + error: error, + satnum: satnum, + epochyr: epochyr, + epochdays: epochdays, + ndot: ndot, + nddot: nddot, + bstar: bstar, + inclo: inclo, + nodeo: nodeo, + ecco: ecco, + argpo: argpo, + mo: mo, + no: no, + jdsatepoch: jdsatepoch + }; + // ---------------- initialize the orbit at sgp4epoch ------------------- + (0, _sgp4init["default"])(satrec, { + opsmode: opsmode, + satn: satrec.satnum, + epoch: satrec.jdsatepoch - 2433281.5, + xbstar: satrec.bstar, + xecco: satrec.ecco, + xargpo: satrec.argpo, + xinclo: satrec.inclo, + xmo: satrec.mo, + xno: satrec.no, + xnodeo: satrec.nodeo + }); + return satrec; +} \ No newline at end of file diff --git a/node_modules/satellite.js/lib/propagation.js b/node_modules/satellite.js/lib/propagation.js new file mode 100644 index 0000000..40dda53 --- /dev/null +++ b/node_modules/satellite.js/lib/propagation.js @@ -0,0 +1,27 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +Object.defineProperty(exports, "gstime", { + enumerable: true, + get: function get() { + return _gstime["default"]; + } +}); +Object.defineProperty(exports, "propagate", { + enumerable: true, + get: function get() { + return _propagate["default"]; + } +}); +Object.defineProperty(exports, "sgp4", { + enumerable: true, + get: function get() { + return _sgp["default"]; + } +}); +var _propagate = _interopRequireDefault(require("./propagation/propagate")); +var _sgp = _interopRequireDefault(require("./propagation/sgp4")); +var _gstime = _interopRequireDefault(require("./propagation/gstime")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } \ No newline at end of file diff --git a/node_modules/satellite.js/lib/propagation/SatRec.js b/node_modules/satellite.js/lib/propagation/SatRec.js new file mode 100644 index 0000000..68340d7 --- /dev/null +++ b/node_modules/satellite.js/lib/propagation/SatRec.js @@ -0,0 +1,34 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.SatRecError = void 0; +var SatRecError; +(function (SatRecError) { + /** + * No error, propagation for the last supplied date is successful + */ + SatRecError[SatRecError["None"] = 0] = "None"; + /** + * Mean eccentricity is out of range 0 ≤ e < 1 + */ + SatRecError[SatRecError["MeanEccentricityOutOfRange"] = 1] = "MeanEccentricityOutOfRange"; + /** + * Mean motion has fallen below zero. + */ + SatRecError[SatRecError["MeanMotionBelowZero"] = 2] = "MeanMotionBelowZero"; + /** + * Perturbed eccentricity is out of range 0 ≤ e < 1 + */ + SatRecError[SatRecError["PerturbedEccentricityOutOfRange"] = 3] = "PerturbedEccentricityOutOfRange"; + /** + * Length of the orbit’s semi-latus rectum has fallen below zero. + */ + SatRecError[SatRecError["SemiLatusRectumBelowZero"] = 4] = "SemiLatusRectumBelowZero"; + // 5 is not used + /** + * Orbit has decayed: the computed position is underground. + */ + SatRecError[SatRecError["Decayed"] = 6] = "Decayed"; +})(SatRecError || (exports.SatRecError = SatRecError = {})); \ No newline at end of file diff --git a/node_modules/satellite.js/lib/propagation/dpper.js b/node_modules/satellite.js/lib/propagation/dpper.js new file mode 100644 index 0000000..c05c3e5 --- /dev/null +++ b/node_modules/satellite.js/lib/propagation/dpper.js @@ -0,0 +1,244 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = dpper; +var _constants = require("../constants"); +/* ----------------------------------------------------------------------------- + * + * procedure dpper + * + * this procedure provides deep space long period periodic contributions + * to the mean elements. by design, these periodics are zero at epoch. + * this used to be dscom which included initialization, but it's really a + * recurring function. + * + * author : david vallado 719-573-2600 28 jun 2005 + * + * inputs : + * e3 - + * ee2 - + * peo - + * pgho - + * pho - + * pinco - + * plo - + * se2 , se3 , sgh2, sgh3, sgh4, sh2, sh3, si2, si3, sl2, sl3, sl4 - + * t - + * xh2, xh3, xi2, xi3, xl2, xl3, xl4 - + * zmol - + * zmos - + * ep - eccentricity 0.0 - 1.0 + * inclo - inclination - needed for lyddane modification + * nodep - right ascension of ascending node + * argpp - argument of perigee + * mp - mean anomaly + * + * outputs : + * ep - eccentricity 0.0 - 1.0 + * inclp - inclination + * nodep - right ascension of ascending node + * argpp - argument of perigee + * mp - mean anomaly + * + * locals : + * alfdp - + * betdp - + * cosip , sinip , cosop , sinop , + * dalf - + * dbet - + * dls - + * f2, f3 - + * pe - + * pgh - + * ph - + * pinc - + * pl - + * sel , ses , sghl , sghs , shl , shs , sil , sinzf , sis , + * sll , sls + * xls - + * xnoh - + * zf - + * zm - + * + * coupling : + * none. + * + * references : + * hoots, roehrich, norad spacetrack report #3 1980 + * hoots, norad spacetrack report #6 1986 + * hoots, schumacher and glover 2004 + * vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ +function dpper(satrec, options) { + var e3 = satrec.e3, + ee2 = satrec.ee2, + peo = satrec.peo, + pgho = satrec.pgho, + pho = satrec.pho, + pinco = satrec.pinco, + plo = satrec.plo, + se2 = satrec.se2, + se3 = satrec.se3, + sgh2 = satrec.sgh2, + sgh3 = satrec.sgh3, + sgh4 = satrec.sgh4, + sh2 = satrec.sh2, + sh3 = satrec.sh3, + si2 = satrec.si2, + si3 = satrec.si3, + sl2 = satrec.sl2, + sl3 = satrec.sl3, + sl4 = satrec.sl4, + t = satrec.t, + xgh2 = satrec.xgh2, + xgh3 = satrec.xgh3, + xgh4 = satrec.xgh4, + xh2 = satrec.xh2, + xh3 = satrec.xh3, + xi2 = satrec.xi2, + xi3 = satrec.xi3, + xl2 = satrec.xl2, + xl3 = satrec.xl3, + xl4 = satrec.xl4, + zmol = satrec.zmol, + zmos = satrec.zmos; + var init = options.init, + opsmode = options.opsmode; + var ep = options.ep, + inclp = options.inclp, + nodep = options.nodep, + argpp = options.argpp, + mp = options.mp; + // Copy satellite attributes into local variables for convenience + // and symmetry in writing formulae. + var alfdp; + var betdp; + var cosip; + var sinip; + var cosop; + var sinop; + var dalf; + var dbet; + var dls; + var f2; + var f3; + var pe; + var pgh; + var ph; + var pinc; + var pl; + var sinzf; + var xls; + var xnoh; + var zf; + var zm; + // ---------------------- constants ----------------------------- + var zns = 1.19459e-5; + var zes = 0.01675; + var znl = 1.5835218e-4; + var zel = 0.05490; + // --------------- calculate time varying periodics ----------- + zm = zmos + zns * t; + // be sure that the initial call has time set to zero + if (init === 'y') { + zm = zmos; + } + zf = zm + 2.0 * zes * Math.sin(zm); + sinzf = Math.sin(zf); + f2 = 0.5 * sinzf * sinzf - 0.25; + f3 = -0.5 * sinzf * Math.cos(zf); + var ses = se2 * f2 + se3 * f3; + var sis = si2 * f2 + si3 * f3; + var sls = sl2 * f2 + sl3 * f3 + sl4 * sinzf; + var sghs = sgh2 * f2 + sgh3 * f3 + sgh4 * sinzf; + var shs = sh2 * f2 + sh3 * f3; + zm = zmol + znl * t; + if (init === 'y') { + zm = zmol; + } + zf = zm + 2.0 * zel * Math.sin(zm); + sinzf = Math.sin(zf); + f2 = 0.5 * sinzf * sinzf - 0.25; + f3 = -0.5 * sinzf * Math.cos(zf); + var sel = ee2 * f2 + e3 * f3; + var sil = xi2 * f2 + xi3 * f3; + var sll = xl2 * f2 + xl3 * f3 + xl4 * sinzf; + var sghl = xgh2 * f2 + xgh3 * f3 + xgh4 * sinzf; + var shll = xh2 * f2 + xh3 * f3; + pe = ses + sel; + pinc = sis + sil; + pl = sls + sll; + pgh = sghs + sghl; + ph = shs + shll; + if (init === 'n') { + pe -= peo; + pinc -= pinco; + pl -= plo; + pgh -= pgho; + ph -= pho; + inclp += pinc; + ep += pe; + sinip = Math.sin(inclp); + cosip = Math.cos(inclp); + /* ----------------- apply periodics directly ------------ */ + // sgp4fix for lyddane choice + // strn3 used original inclination - this is technically feasible + // gsfc used perturbed inclination - also technically feasible + // probably best to readjust the 0.2 limit value and limit discontinuity + // 0.2 rad = 11.45916 deg + // use next line for original strn3 approach and original inclination + // if (inclo >= 0.2) + // use next line for gsfc version and perturbed inclination + if (inclp >= 0.2) { + ph /= sinip; + pgh -= cosip * ph; + argpp += pgh; + nodep += ph; + mp += pl; + } else { + // ---- apply periodics with lyddane modification ---- + sinop = Math.sin(nodep); + cosop = Math.cos(nodep); + alfdp = sinip * sinop; + betdp = sinip * cosop; + dalf = ph * cosop + pinc * cosip * sinop; + dbet = -ph * sinop + pinc * cosip * cosop; + alfdp += dalf; + betdp += dbet; + nodep %= _constants.twoPi; + // sgp4fix for afspc written intrinsic functions + // nodep used without a trigonometric function ahead + if (nodep < 0.0 && opsmode === 'a') { + nodep += _constants.twoPi; + } + xls = mp + argpp + cosip * nodep; + dls = pl + pgh - pinc * nodep * sinip; + xls += dls; + xnoh = nodep; + nodep = Math.atan2(alfdp, betdp); + // sgp4fix for afspc written intrinsic functions + // nodep used without a trigonometric function ahead + if (nodep < 0.0 && opsmode === 'a') { + nodep += _constants.twoPi; + } + if (Math.abs(xnoh - nodep) > _constants.pi) { + if (nodep < xnoh) { + nodep += _constants.twoPi; + } else { + nodep -= _constants.twoPi; + } + } + mp += pl; + argpp = xls - mp - cosip * nodep; + } + } + return { + ep: ep, + inclp: inclp, + nodep: nodep, + argpp: argpp, + mp: mp + }; +} \ No newline at end of file diff --git a/node_modules/satellite.js/lib/propagation/dscom.js b/node_modules/satellite.js/lib/propagation/dscom.js new file mode 100644 index 0000000..5256aba --- /dev/null +++ b/node_modules/satellite.js/lib/propagation/dscom.js @@ -0,0 +1,381 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = dscom; +var _constants = require("../constants"); +/*----------------------------------------------------------------------------- + * + * procedure dscom + * + * this procedure provides deep space common items used by both the secular + * and periodics subroutines. input is provided as shown. this routine + * used to be called dpper, but the functions inside weren't well organized. + * + * author : david vallado 719-573-2600 28 jun 2005 + * + * inputs : + * epoch - + * ep - eccentricity + * argpp - argument of perigee + * tc - + * inclp - inclination + * nodep - right ascension of ascending node + * np - mean motion + * + * outputs : + * sinim , cosim , sinomm , cosomm , snodm , cnodm + * day - + * e3 - + * ee2 - + * em - eccentricity + * emsq - eccentricity squared + * gam - + * peo - + * pgho - + * pho - + * pinco - + * plo - + * rtemsq - + * se2, se3 - + * sgh2, sgh3, sgh4 - + * sh2, sh3, si2, si3, sl2, sl3, sl4 - + * s1, s2, s3, s4, s5, s6, s7 - + * ss1, ss2, ss3, ss4, ss5, ss6, ss7, sz1, sz2, sz3 - + * sz11, sz12, sz13, sz21, sz22, sz23, sz31, sz32, sz33 - + * xgh2, xgh3, xgh4, xh2, xh3, xi2, xi3, xl2, xl3, xl4 - + * nm - mean motion + * z1, z2, z3, z11, z12, z13, z21, z22, z23, z31, z32, z33 - + * zmol - + * zmos - + * + * locals : + * a1, a2, a3, a4, a5, a6, a7, a8, a9, a10 - + * betasq - + * cc - + * ctem, stem - + * x1, x2, x3, x4, x5, x6, x7, x8 - + * xnodce - + * xnoi - + * zcosg , zsing , zcosgl , zsingl , zcosh , zsinh , zcoshl , zsinhl , + * zcosi , zsini , zcosil , zsinil , + * zx - + * zy - + * + * coupling : + * none. + * + * references : + * hoots, roehrich, norad spacetrack report #3 1980 + * hoots, norad spacetrack report #6 1986 + * hoots, schumacher and glover 2004 + * vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ +function dscom(options) { + var epoch = options.epoch, + ep = options.ep, + argpp = options.argpp, + tc = options.tc, + inclp = options.inclp, + nodep = options.nodep, + np = options.np; + var a1; + var a2; + var a3; + var a4; + var a5; + var a6; + var a7; + var a8; + var a9; + var a10; + var cc; + var x1; + var x2; + var x3; + var x4; + var x5; + var x6; + var x7; + var x8; + var zcosg; + var zsing; + var zcosh; + var zsinh; + var zcosi; + var zsini; + var ss1; + var ss2; + var ss3; + var ss4; + var ss5; + var ss6; + var ss7; + var sz1; + var sz2; + var sz3; + var sz11; + var sz12; + var sz13; + var sz21; + var sz22; + var sz23; + var sz31; + var sz32; + var sz33; + var s1; + var s2; + var s3; + var s4; + var s5; + var s6; + var s7; + var z1; + var z2; + var z3; + var z11; + var z12; + var z13; + var z21; + var z22; + var z23; + var z31; + var z32; + var z33; + // -------------------------- constants ------------------------- + var zes = 0.01675; + var zel = 0.05490; + var c1ss = 2.9864797e-6; + var c1l = 4.7968065e-7; + var zsinis = 0.39785416; + var zcosis = 0.91744867; + var zcosgs = 0.1945905; + var zsings = -0.98088458; + // --------------------- local variables ------------------------ + var nm = np; + var em = ep; + var snodm = Math.sin(nodep); + var cnodm = Math.cos(nodep); + var sinomm = Math.sin(argpp); + var cosomm = Math.cos(argpp); + var sinim = Math.sin(inclp); + var cosim = Math.cos(inclp); + var emsq = em * em; + var betasq = 1.0 - emsq; + var rtemsq = Math.sqrt(betasq); + // ----------------- initialize lunar solar terms --------------- + var peo = 0.0; + var pinco = 0.0; + var plo = 0.0; + var pgho = 0.0; + var pho = 0.0; + var day = epoch + 18261.5 + tc / 1440.0; + var xnodce = (4.5236020 - 9.2422029e-4 * day) % _constants.twoPi; + var stem = Math.sin(xnodce); + var ctem = Math.cos(xnodce); + var zcosil = 0.91375164 - 0.03568096 * ctem; + var zsinil = Math.sqrt(1.0 - zcosil * zcosil); + var zsinhl = 0.089683511 * stem / zsinil; + var zcoshl = Math.sqrt(1.0 - zsinhl * zsinhl); + var gam = 5.8351514 + 0.0019443680 * day; + var zx = 0.39785416 * stem / zsinil; + var zy = zcoshl * ctem + 0.91744867 * zsinhl * stem; + zx = Math.atan2(zx, zy); + zx += gam - xnodce; + var zcosgl = Math.cos(zx); + var zsingl = Math.sin(zx); + // ------------------------- do solar terms --------------------- + zcosg = zcosgs; + zsing = zsings; + zcosi = zcosis; + zsini = zsinis; + zcosh = cnodm; + zsinh = snodm; + cc = c1ss; + var xnoi = 1.0 / nm; + var lsflg = 0; + while (lsflg < 2) { + lsflg += 1; + a1 = zcosg * zcosh + zsing * zcosi * zsinh; + a3 = -zsing * zcosh + zcosg * zcosi * zsinh; + a7 = -zcosg * zsinh + zsing * zcosi * zcosh; + a8 = zsing * zsini; + a9 = zsing * zsinh + zcosg * zcosi * zcosh; + a10 = zcosg * zsini; + a2 = cosim * a7 + sinim * a8; + a4 = cosim * a9 + sinim * a10; + a5 = -sinim * a7 + cosim * a8; + a6 = -sinim * a9 + cosim * a10; + x1 = a1 * cosomm + a2 * sinomm; + x2 = a3 * cosomm + a4 * sinomm; + x3 = -a1 * sinomm + a2 * cosomm; + x4 = -a3 * sinomm + a4 * cosomm; + x5 = a5 * sinomm; + x6 = a6 * sinomm; + x7 = a5 * cosomm; + x8 = a6 * cosomm; + z31 = 12.0 * x1 * x1 - 3.0 * x3 * x3; + z32 = 24.0 * x1 * x2 - 6.0 * x3 * x4; + z33 = 12.0 * x2 * x2 - 3.0 * x4 * x4; + z1 = 3.0 * (a1 * a1 + a2 * a2) + z31 * emsq; + z2 = 6.0 * (a1 * a3 + a2 * a4) + z32 * emsq; + z3 = 3.0 * (a3 * a3 + a4 * a4) + z33 * emsq; + z11 = -6.0 * a1 * a5 + emsq * (-24.0 * x1 * x7 - 6.0 * x3 * x5); + z12 = -6.0 * (a1 * a6 + a3 * a5) + emsq * (-24.0 * (x2 * x7 + x1 * x8) + -6.0 * (x3 * x6 + x4 * x5)); + z13 = -6.0 * a3 * a6 + emsq * (-24.0 * x2 * x8 - 6.0 * x4 * x6); + z21 = 6.0 * a2 * a5 + emsq * (24.0 * x1 * x5 - 6.0 * x3 * x7); + z22 = 6.0 * (a4 * a5 + a2 * a6) + emsq * (24.0 * (x2 * x5 + x1 * x6) - 6.0 * (x4 * x7 + x3 * x8)); + z23 = 6.0 * a4 * a6 + emsq * (24.0 * x2 * x6 - 6.0 * x4 * x8); + z1 = z1 + z1 + betasq * z31; + z2 = z2 + z2 + betasq * z32; + z3 = z3 + z3 + betasq * z33; + s3 = cc * xnoi; + s2 = -0.5 * s3 / rtemsq; + s4 = s3 * rtemsq; + s1 = -15.0 * em * s4; + s5 = x1 * x3 + x2 * x4; + s6 = x2 * x3 + x1 * x4; + s7 = x2 * x4 - x1 * x3; + // ----------------------- do lunar terms ------------------- + if (lsflg === 1) { + ss1 = s1; + ss2 = s2; + ss3 = s3; + ss4 = s4; + ss5 = s5; + ss6 = s6; + ss7 = s7; + sz1 = z1; + sz2 = z2; + sz3 = z3; + sz11 = z11; + sz12 = z12; + sz13 = z13; + sz21 = z21; + sz22 = z22; + sz23 = z23; + sz31 = z31; + sz32 = z32; + sz33 = z33; + zcosg = zcosgl; + zsing = zsingl; + zcosi = zcosil; + zsini = zsinil; + zcosh = zcoshl * cnodm + zsinhl * snodm; + zsinh = snodm * zcoshl - cnodm * zsinhl; + cc = c1l; + } + } + var zmol = (4.7199672 + (0.22997150 * day - gam)) % _constants.twoPi; + var zmos = (6.2565837 + 0.017201977 * day) % _constants.twoPi; + // ------------------------ do solar terms ---------------------- + var se2 = 2.0 * ss1 * ss6; + var se3 = 2.0 * ss1 * ss7; + var si2 = 2.0 * ss2 * sz12; + var si3 = 2.0 * ss2 * (sz13 - sz11); + var sl2 = -2.0 * ss3 * sz2; + var sl3 = -2.0 * ss3 * (sz3 - sz1); + var sl4 = -2.0 * ss3 * (-21.0 - 9.0 * emsq) * zes; + var sgh2 = 2.0 * ss4 * sz32; + var sgh3 = 2.0 * ss4 * (sz33 - sz31); + var sgh4 = -18.0 * ss4 * zes; + var sh2 = -2.0 * ss2 * sz22; + var sh3 = -2.0 * ss2 * (sz23 - sz21); + // ------------------------ do lunar terms ---------------------- + var ee2 = 2.0 * s1 * s6; + var e3 = 2.0 * s1 * s7; + var xi2 = 2.0 * s2 * z12; + var xi3 = 2.0 * s2 * (z13 - z11); + var xl2 = -2.0 * s3 * z2; + var xl3 = -2.0 * s3 * (z3 - z1); + var xl4 = -2.0 * s3 * (-21.0 - 9.0 * emsq) * zel; + var xgh2 = 2.0 * s4 * z32; + var xgh3 = 2.0 * s4 * (z33 - z31); + var xgh4 = -18.0 * s4 * zel; + var xh2 = -2.0 * s2 * z22; + var xh3 = -2.0 * s2 * (z23 - z21); + return { + snodm: snodm, + cnodm: cnodm, + sinim: sinim, + cosim: cosim, + sinomm: sinomm, + cosomm: cosomm, + day: day, + e3: e3, + ee2: ee2, + em: em, + emsq: emsq, + gam: gam, + peo: peo, + pgho: pgho, + pho: pho, + pinco: pinco, + plo: plo, + rtemsq: rtemsq, + se2: se2, + se3: se3, + sgh2: sgh2, + sgh3: sgh3, + sgh4: sgh4, + sh2: sh2, + sh3: sh3, + si2: si2, + si3: si3, + sl2: sl2, + sl3: sl3, + sl4: sl4, + s1: s1, + s2: s2, + s3: s3, + s4: s4, + s5: s5, + s6: s6, + s7: s7, + ss1: ss1, + ss2: ss2, + ss3: ss3, + ss4: ss4, + ss5: ss5, + ss6: ss6, + ss7: ss7, + sz1: sz1, + sz2: sz2, + sz3: sz3, + sz11: sz11, + sz12: sz12, + sz13: sz13, + sz21: sz21, + sz22: sz22, + sz23: sz23, + sz31: sz31, + sz32: sz32, + sz33: sz33, + xgh2: xgh2, + xgh3: xgh3, + xgh4: xgh4, + xh2: xh2, + xh3: xh3, + xi2: xi2, + xi3: xi3, + xl2: xl2, + xl3: xl3, + xl4: xl4, + nm: nm, + z1: z1, + z2: z2, + z3: z3, + z11: z11, + z12: z12, + z13: z13, + z21: z21, + z22: z22, + z23: z23, + z31: z31, + z32: z32, + z33: z33, + zmol: zmol, + zmos: zmos + }; +} \ No newline at end of file diff --git a/node_modules/satellite.js/lib/propagation/dsinit.js b/node_modules/satellite.js/lib/propagation/dsinit.js new file mode 100644 index 0000000..86cc4ec --- /dev/null +++ b/node_modules/satellite.js/lib/propagation/dsinit.js @@ -0,0 +1,389 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = dsinit; +var _constants = require("../constants"); +/*----------------------------------------------------------------------------- + * + * procedure dsinit + * + * this procedure provides deep space contributions to mean motion dot due + * to geopotential resonance with half day and one day orbits. + * + * author : david vallado 719-573-2600 28 jun 2005 + * + * inputs : + * cosim, sinim- + * emsq - eccentricity squared + * argpo - argument of perigee + * s1, s2, s3, s4, s5 - + * ss1, ss2, ss3, ss4, ss5 - + * sz1, sz3, sz11, sz13, sz21, sz23, sz31, sz33 - + * t - time + * tc - + * gsto - greenwich sidereal time rad + * mo - mean anomaly + * mdot - mean anomaly dot (rate) + * no - mean motion + * nodeo - right ascension of ascending node + * nodedot - right ascension of ascending node dot (rate) + * xpidot - + * z1, z3, z11, z13, z21, z23, z31, z33 - + * eccm - eccentricity + * argpm - argument of perigee + * inclm - inclination + * mm - mean anomaly + * xn - mean motion + * nodem - right ascension of ascending node + * + * outputs : + * em - eccentricity + * argpm - argument of perigee + * inclm - inclination + * mm - mean anomaly + * nm - mean motion + * nodem - right ascension of ascending node + * irez - flag for resonance 0-none, 1-one day, 2-half day + * atime - + * d2201, d2211, d3210, d3222, d4410, d4422, d5220, d5232, d5421, d5433 - + * dedt - + * didt - + * dmdt - + * dndt - + * dnodt - + * domdt - + * del1, del2, del3 - + * ses , sghl , sghs , sgs , shl , shs , sis , sls + * theta - + * xfact - + * xlamo - + * xli - + * xni + * + * locals : + * ainv2 - + * aonv - + * cosisq - + * eoc - + * f220, f221, f311, f321, f322, f330, f441, f442, f522, f523, f542, f543 - + * g200, g201, g211, g300, g310, g322, g410, g422, g520, g521, g532, g533 - + * sini2 - + * temp - + * temp1 - + * theta - + * xno2 - + * + * coupling : + * getgravconst + * + * references : + * hoots, roehrich, norad spacetrack report #3 1980 + * hoots, norad spacetrack report #6 1986 + * hoots, schumacher and glover 2004 + * vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ +function dsinit(options) { + var cosim = options.cosim, + argpo = options.argpo, + s1 = options.s1, + s2 = options.s2, + s3 = options.s3, + s4 = options.s4, + s5 = options.s5, + sinim = options.sinim, + ss1 = options.ss1, + ss2 = options.ss2, + ss3 = options.ss3, + ss4 = options.ss4, + ss5 = options.ss5, + sz1 = options.sz1, + sz3 = options.sz3, + sz11 = options.sz11, + sz13 = options.sz13, + sz21 = options.sz21, + sz23 = options.sz23, + sz31 = options.sz31, + sz33 = options.sz33, + t = options.t, + tc = options.tc, + gsto = options.gsto, + mo = options.mo, + mdot = options.mdot, + no = options.no, + nodeo = options.nodeo, + nodedot = options.nodedot, + xpidot = options.xpidot, + z1 = options.z1, + z3 = options.z3, + z11 = options.z11, + z13 = options.z13, + z21 = options.z21, + z23 = options.z23, + z31 = options.z31, + z33 = options.z33, + ecco = options.ecco, + eccsq = options.eccsq; + var emsq = options.emsq, + em = options.em, + argpm = options.argpm, + inclm = options.inclm, + mm = options.mm, + nm = options.nm, + nodem = options.nodem, + irez = options.irez, + atime = options.atime, + d2201 = options.d2201, + d2211 = options.d2211, + d3210 = options.d3210, + d3222 = options.d3222, + d4410 = options.d4410, + d4422 = options.d4422, + d5220 = options.d5220, + d5232 = options.d5232, + d5421 = options.d5421, + d5433 = options.d5433, + dedt = options.dedt, + didt = options.didt, + dmdt = options.dmdt, + dnodt = options.dnodt, + domdt = options.domdt, + del1 = options.del1, + del2 = options.del2, + del3 = options.del3, + xfact = options.xfact, + xlamo = options.xlamo, + xli = options.xli, + xni = options.xni; + var f220; + var f221; + var f311; + var f321; + var f322; + var f330; + var f441; + var f442; + var f522; + var f523; + var f542; + var f543; + var g200; + var g201; + var g211; + var g300; + var g310; + var g322; + var g410; + var g422; + var g520; + var g521; + var g532; + var g533; + var sini2; + var temp; + var temp1; + var xno2; + var ainv2; + var aonv; + var cosisq; + var eoc; + var q22 = 1.7891679e-6; + var q31 = 2.1460748e-6; + var q33 = 2.2123015e-7; + var root22 = 1.7891679e-6; + var root44 = 7.3636953e-9; + var root54 = 2.1765803e-9; + // eslint-disable-next-line no-loss-of-precision + var rptim = 4.37526908801129966e-3; // equates to 7.29211514668855e-5 rad/sec + var root32 = 3.7393792e-7; + var root52 = 1.1428639e-7; + var znl = 1.5835218e-4; + var zns = 1.19459e-5; + // -------------------- deep space initialization ------------ + irez = 0; + if (nm < 0.0052359877 && nm > 0.0034906585) { + irez = 1; + } + if (nm >= 8.26e-3 && nm <= 9.24e-3 && em >= 0.5) { + irez = 2; + } + // ------------------------ do solar terms ------------------- + var ses = ss1 * zns * ss5; + var sis = ss2 * zns * (sz11 + sz13); + var sls = -zns * ss3 * (sz1 + sz3 - 14.0 - 6.0 * emsq); + var sghs = ss4 * zns * (sz31 + sz33 - 6.0); + var shs = -zns * ss2 * (sz21 + sz23); + // sgp4fix for 180 deg incl + if (inclm < 5.2359877e-2 || inclm > _constants.pi - 5.2359877e-2) { + shs = 0.0; + } + if (sinim !== 0.0) { + shs /= sinim; + } + var sgs = sghs - cosim * shs; + // ------------------------- do lunar terms ------------------ + dedt = ses + s1 * znl * s5; + didt = sis + s2 * znl * (z11 + z13); + dmdt = sls - znl * s3 * (z1 + z3 - 14.0 - 6.0 * emsq); + var sghl = s4 * znl * (z31 + z33 - 6.0); + var shll = -znl * s2 * (z21 + z23); + // sgp4fix for 180 deg incl + if (inclm < 5.2359877e-2 || inclm > _constants.pi - 5.2359877e-2) { + shll = 0.0; + } + domdt = sgs + sghl; + dnodt = shs; + if (sinim !== 0.0) { + domdt -= cosim / sinim * shll; + dnodt += shll / sinim; + } + // ----------- calculate deep space resonance effects -------- + var dndt = 0.0; + var theta = (gsto + tc * rptim) % _constants.twoPi; + em += dedt * t; + inclm += didt * t; + argpm += domdt * t; + nodem += dnodt * t; + mm += dmdt * t; + // sgp4fix for negative inclinations + // the following if statement should be commented out + // if (inclm < 0.0) + // { + // inclm = -inclm; + // argpm = argpm - pi; + // nodem = nodem + pi; + // } + // -------------- initialize the resonance terms ------------- + if (irez !== 0) { + aonv = Math.pow(nm / _constants.xke, _constants.x2o3); + // ---------- geopotential resonance for 12 hour orbits ------ + if (irez === 2) { + cosisq = cosim * cosim; + var emo = em; + em = ecco; + var emsqo = emsq; + emsq = eccsq; + eoc = em * emsq; + g201 = -0.306 - (em - 0.64) * 0.440; + if (em <= 0.65) { + g211 = 3.616 - 13.2470 * em + 16.2900 * emsq; + g310 = -19.302 + 117.3900 * em - 228.4190 * emsq + 156.5910 * eoc; + g322 = -18.9068 + 109.7927 * em - 214.6334 * emsq + 146.5816 * eoc; + g410 = -41.122 + 242.6940 * em - 471.0940 * emsq + 313.9530 * eoc; + g422 = -146.407 + 841.8800 * em - 1629.014 * emsq + 1083.4350 * eoc; + g520 = -532.114 + 3017.977 * em - 5740.032 * emsq + 3708.2760 * eoc; + } else { + g211 = -72.099 + 331.819 * em - 508.738 * emsq + 266.724 * eoc; + g310 = -346.844 + 1582.851 * em - 2415.925 * emsq + 1246.113 * eoc; + g322 = -342.585 + 1554.908 * em - 2366.899 * emsq + 1215.972 * eoc; + g410 = -1052.797 + 4758.686 * em - 7193.992 * emsq + 3651.957 * eoc; + g422 = -3581.690 + 16178.110 * em - 24462.770 * emsq + 12422.520 * eoc; + if (em > 0.715) { + g520 = -5149.66 + 29936.92 * em - 54087.36 * emsq + 31324.56 * eoc; + } else { + g520 = 1464.74 - 4664.75 * em + 3763.64 * emsq; + } + } + if (em < 0.7) { + g533 = -919.22770 + 4988.6100 * em - 9064.7700 * emsq + 5542.21 * eoc; + g521 = -822.71072 + 4568.6173 * em - 8491.4146 * emsq + 5337.524 * eoc; + g532 = -853.66600 + 4690.2500 * em - 8624.7700 * emsq + 5341.4 * eoc; + } else { + g533 = -37995.780 + 161616.52 * em - 229838.20 * emsq + 109377.94 * eoc; + g521 = -51752.104 + 218913.95 * em - 309468.16 * emsq + 146349.42 * eoc; + g532 = -40023.880 + 170470.89 * em - 242699.48 * emsq + 115605.82 * eoc; + } + sini2 = sinim * sinim; + f220 = 0.75 * (1.0 + 2.0 * cosim + cosisq); + f221 = 1.5 * sini2; + f321 = 1.875 * sinim * (1.0 - 2.0 * cosim - 3.0 * cosisq); + f322 = -1.875 * sinim * (1.0 + 2.0 * cosim - 3.0 * cosisq); + f441 = 35.0 * sini2 * f220; + f442 = 39.3750 * sini2 * sini2; + f522 = 9.84375 * sinim * (sini2 * (1.0 - 2.0 * cosim - 5.0 * cosisq) + 0.33333333 * (-2.0 + 4.0 * cosim + 6.0 * cosisq)); + f523 = sinim * (4.92187512 * sini2 * (-2.0 - 4.0 * cosim + 10.0 * cosisq) + 6.56250012 * (1.0 + 2.0 * cosim - 3.0 * cosisq)); + f542 = 29.53125 * sinim * (2.0 - 8.0 * cosim + cosisq * (-12.0 + 8.0 * cosim + 10.0 * cosisq)); + f543 = 29.53125 * sinim * (-2.0 - 8.0 * cosim + cosisq * (12.0 + 8.0 * cosim - 10.0 * cosisq)); + xno2 = nm * nm; + ainv2 = aonv * aonv; + temp1 = 3.0 * xno2 * ainv2; + temp = temp1 * root22; + d2201 = temp * f220 * g201; + d2211 = temp * f221 * g211; + temp1 *= aonv; + temp = temp1 * root32; + d3210 = temp * f321 * g310; + d3222 = temp * f322 * g322; + temp1 *= aonv; + temp = 2.0 * temp1 * root44; + d4410 = temp * f441 * g410; + d4422 = temp * f442 * g422; + temp1 *= aonv; + temp = temp1 * root52; + d5220 = temp * f522 * g520; + d5232 = temp * f523 * g532; + temp = 2.0 * temp1 * root54; + d5421 = temp * f542 * g521; + d5433 = temp * f543 * g533; + xlamo = (mo + nodeo + nodeo - (theta + theta)) % _constants.twoPi; + xfact = mdot + dmdt + 2.0 * (nodedot + dnodt - rptim) - no; + em = emo; + emsq = emsqo; + } + // ---------------- synchronous resonance terms -------------- + if (irez === 1) { + g200 = 1.0 + emsq * (-2.5 + 0.8125 * emsq); + g310 = 1.0 + 2.0 * emsq; + g300 = 1.0 + emsq * (-6.0 + 6.60937 * emsq); + f220 = 0.75 * (1.0 + cosim) * (1.0 + cosim); + f311 = 0.9375 * sinim * sinim * (1.0 + 3.0 * cosim) - 0.75 * (1.0 + cosim); + f330 = 1.0 + cosim; + f330 *= 1.875 * f330 * f330; + del1 = 3.0 * nm * nm * aonv * aonv; + del2 = 2.0 * del1 * f220 * g200 * q22; + del3 = 3.0 * del1 * f330 * g300 * q33 * aonv; + del1 = del1 * f311 * g310 * q31 * aonv; + xlamo = (mo + nodeo + argpo - theta) % _constants.twoPi; + xfact = mdot + xpidot + dmdt + domdt + dnodt - (no + rptim); + } + // ------------ for sgp4, initialize the integrator ---------- + xli = xlamo; + xni = no; + atime = 0.0; + nm = no + dndt; + } + return { + em: em, + argpm: argpm, + inclm: inclm, + mm: mm, + nm: nm, + nodem: nodem, + irez: irez, + atime: atime, + d2201: d2201, + d2211: d2211, + d3210: d3210, + d3222: d3222, + d4410: d4410, + d4422: d4422, + d5220: d5220, + d5232: d5232, + d5421: d5421, + d5433: d5433, + dedt: dedt, + didt: didt, + dmdt: dmdt, + dndt: dndt, + dnodt: dnodt, + domdt: domdt, + del1: del1, + del2: del2, + del3: del3, + xfact: xfact, + xlamo: xlamo, + xli: xli, + xni: xni + }; +} \ No newline at end of file diff --git a/node_modules/satellite.js/lib/propagation/dspace.js b/node_modules/satellite.js/lib/propagation/dspace.js new file mode 100644 index 0000000..0fb030a --- /dev/null +++ b/node_modules/satellite.js/lib/propagation/dspace.js @@ -0,0 +1,230 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = dspace; +var _constants = require("../constants"); +/*----------------------------------------------------------------------------- + * + * procedure dspace + * + * this procedure provides deep space contributions to mean elements for + * perturbing third body. these effects have been averaged over one + * revolution of the sun and moon. for earth resonance effects, the + * effects have been averaged over no revolutions of the satellite. + * (mean motion) + * + * author : david vallado 719-573-2600 28 jun 2005 + * + * inputs : + * d2201, d2211, d3210, d3222, d4410, d4422, d5220, d5232, d5421, d5433 - + * dedt - + * del1, del2, del3 - + * didt - + * dmdt - + * dnodt - + * domdt - + * irez - flag for resonance 0-none, 1-one day, 2-half day + * argpo - argument of perigee + * argpdot - argument of perigee dot (rate) + * t - time + * tc - + * gsto - gst + * xfact - + * xlamo - + * no - mean motion + * atime - + * em - eccentricity + * ft - + * argpm - argument of perigee + * inclm - inclination + * xli - + * mm - mean anomaly + * xni - mean motion + * nodem - right ascension of ascending node + * + * outputs : + * atime - + * em - eccentricity + * argpm - argument of perigee + * inclm - inclination + * xli - + * mm - mean anomaly + * xni - + * nodem - right ascension of ascending node + * dndt - + * nm - mean motion + * + * locals : + * delt - + * ft - + * theta - + * x2li - + * x2omi - + * xl - + * xldot - + * xnddt - + * xndt - + * xomi - + * + * coupling : + * none - + * + * references : + * hoots, roehrich, norad spacetrack report #3 1980 + * hoots, norad spacetrack report #6 1986 + * hoots, schumacher and glover 2004 + * vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ +function dspace(options) { + var irez = options.irez, + d2201 = options.d2201, + d2211 = options.d2211, + d3210 = options.d3210, + d3222 = options.d3222, + d4410 = options.d4410, + d4422 = options.d4422, + d5220 = options.d5220, + d5232 = options.d5232, + d5421 = options.d5421, + d5433 = options.d5433, + dedt = options.dedt, + del1 = options.del1, + del2 = options.del2, + del3 = options.del3, + didt = options.didt, + dmdt = options.dmdt, + dnodt = options.dnodt, + domdt = options.domdt, + argpo = options.argpo, + argpdot = options.argpdot, + t = options.t, + tc = options.tc, + gsto = options.gsto, + xfact = options.xfact, + xlamo = options.xlamo, + no = options.no; + var atime = options.atime, + em = options.em, + argpm = options.argpm, + inclm = options.inclm, + xli = options.xli, + mm = options.mm, + xni = options.xni, + nodem = options.nodem, + nm = options.nm; + var fasx2 = 0.13130908; + var fasx4 = 2.8843198; + var fasx6 = 0.37448087; + var g22 = 5.7686396; + var g32 = 0.95240898; + var g44 = 1.8014998; + var g52 = 1.0508330; + var g54 = 4.4108898; + // eslint-disable-next-line no-loss-of-precision + var rptim = 4.37526908801129966e-3; // equates to 7.29211514668855e-5 rad/sec + var stepp = 720.0; + var stepn = -720.0; + var step2 = 259200.0; + var delt; + var x2li; + var x2omi; + var xl; + var xldot; + var xnddt; + var xndt; + var xomi; + var dndt = 0.0; + var ft = 0.0; + // ----------- calculate deep space resonance effects ----------- + var theta = (gsto + tc * rptim) % _constants.twoPi; + em += dedt * t; + inclm += didt * t; + argpm += domdt * t; + nodem += dnodt * t; + mm += dmdt * t; + // sgp4fix for negative inclinations + // the following if statement should be commented out + // if (inclm < 0.0) + // { + // inclm = -inclm; + // argpm = argpm - pi; + // nodem = nodem + pi; + // } + /* - update resonances : numerical (euler-maclaurin) integration - */ + /* ------------------------- epoch restart ---------------------- */ + // sgp4fix for propagator problems + // the following integration works for negative time steps and periods + // the specific changes are unknown because the original code was so convoluted + // sgp4fix take out atime = 0.0 and fix for faster operation + if (irez !== 0) { + // sgp4fix streamline check + if (atime === 0.0 || t * atime <= 0.0 || Math.abs(t) < Math.abs(atime)) { + atime = 0.0; + xni = no; + xli = xlamo; + } + // sgp4fix move check outside loop + if (t > 0.0) { + delt = stepp; + } else { + delt = stepn; + } + var iretn = 381; // added for do loop + while (iretn === 381) { + // ------------------- dot terms calculated ------------- + // ----------- near - synchronous resonance terms ------- + if (irez !== 2) { + xndt = del1 * Math.sin(xli - fasx2) + del2 * Math.sin(2.0 * (xli - fasx4)) + del3 * Math.sin(3.0 * (xli - fasx6)); + xldot = xni + xfact; + xnddt = del1 * Math.cos(xli - fasx2) + 2.0 * del2 * Math.cos(2.0 * (xli - fasx4)) + 3.0 * del3 * Math.cos(3.0 * (xli - fasx6)); + xnddt *= xldot; + } else { + // --------- near - half-day resonance terms -------- + xomi = argpo + argpdot * atime; + x2omi = xomi + xomi; + x2li = xli + xli; + xndt = d2201 * Math.sin(x2omi + xli - g22) + d2211 * Math.sin(xli - g22) + d3210 * Math.sin(xomi + xli - g32) + d3222 * Math.sin(-xomi + xli - g32) + d4410 * Math.sin(x2omi + x2li - g44) + d4422 * Math.sin(x2li - g44) + d5220 * Math.sin(xomi + xli - g52) + d5232 * Math.sin(-xomi + xli - g52) + d5421 * Math.sin(xomi + x2li - g54) + d5433 * Math.sin(-xomi + x2li - g54); + xldot = xni + xfact; + xnddt = d2201 * Math.cos(x2omi + xli - g22) + d2211 * Math.cos(xli - g22) + d3210 * Math.cos(xomi + xli - g32) + d3222 * Math.cos(-xomi + xli - g32) + d5220 * Math.cos(xomi + xli - g52) + d5232 * Math.cos(-xomi + xli - g52) + 2.0 * (d4410 * Math.cos(x2omi + x2li - g44) + d4422 * Math.cos(x2li - g44) + d5421 * Math.cos(xomi + x2li - g54) + d5433 * Math.cos(-xomi + x2li - g54)); + xnddt *= xldot; + } + // ----------------------- integrator ------------------- + // sgp4fix move end checks to end of routine + if (Math.abs(t - atime) >= stepp) { + iretn = 381; + } else { + ft = t - atime; + iretn = 0; + } + if (iretn === 381) { + xli += xldot * delt + xndt * step2; + xni += xndt * delt + xnddt * step2; + atime += delt; + } + } + nm = xni + xndt * ft + xnddt * ft * ft * 0.5; + xl = xli + xldot * ft + xndt * ft * ft * 0.5; + if (irez !== 1) { + mm = xl - 2.0 * nodem + 2.0 * theta; + dndt = nm - no; + } else { + mm = xl - nodem - argpm + theta; + dndt = nm - no; + } + nm = no + dndt; + } + return { + atime: atime, + em: em, + argpm: argpm, + inclm: inclm, + xli: xli, + mm: mm, + xni: xni, + nodem: nodem, + dndt: dndt, + nm: nm + }; +} \ No newline at end of file diff --git a/node_modules/satellite.js/lib/propagation/gstime.js b/node_modules/satellite.js/lib/propagation/gstime.js new file mode 100644 index 0000000..d745191 --- /dev/null +++ b/node_modules/satellite.js/lib/propagation/gstime.js @@ -0,0 +1,53 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; +var _constants = require("../constants"); +var _ext = require("../ext"); +/* ----------------------------------------------------------------------------- + * + * function gstime + * + * this function finds the greenwich sidereal time. + * + * author : david vallado 719-573-2600 1 mar 2001 + * + * inputs description range / units + * jdut1 - julian date in ut1 days from 4713 bc + * + * outputs : + * gstime - greenwich sidereal time 0 to 2pi rad + * + * locals : + * temp - temporary variable for doubles rad + * tut1 - julian centuries from the + * jan 1, 2000 12 h epoch (ut1) + * + * coupling : + * none + * + * references : + * vallado 2004, 191, eq 3-45 + * --------------------------------------------------------------------------- */ +function gstimeInternal(jdut1) { + var tut1 = (jdut1 - 2451545.0) / 36525.0; + var temp = -6.2e-6 * tut1 * tut1 * tut1 + 0.093104 * tut1 * tut1 + (876600.0 * 3600 + 8640184.812866) * tut1 + 67310.54841; // # sec + temp = temp * _constants.deg2rad / 240.0 % _constants.twoPi; // 360/86400 = 1/240, to deg, to rad + // ------------------------ check quadrants --------------------- + if (temp < 0.0) { + temp += _constants.twoPi; + } + return temp; +} +function gstime(first, month, day, hour, minute, second, millisecond) { + if (first instanceof Date) { + return gstimeInternal((0, _ext.jday)(first)); + } else if (month !== undefined) { + return gstimeInternal((0, _ext.jday)(first, month, day, hour, minute, second, millisecond)); + } else { + return gstimeInternal(first); + } +} +var _default = exports["default"] = gstime; \ No newline at end of file diff --git a/node_modules/satellite.js/lib/propagation/initl.js b/node_modules/satellite.js/lib/propagation/initl.js new file mode 100644 index 0000000..d11d48c --- /dev/null +++ b/node_modules/satellite.js/lib/propagation/initl.js @@ -0,0 +1,128 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = initl; +var _constants = require("../constants"); +var _gstime = _interopRequireDefault(require("./gstime")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/*----------------------------------------------------------------------------- + * + * procedure initl + * + * this procedure initializes the sgp4 propagator. all the initialization is + * consolidated here instead of having multiple loops inside other routines. + * + * author : david vallado 719-573-2600 28 jun 2005 + * + * inputs : + * ecco - eccentricity 0.0 - 1.0 + * epoch - epoch time in days from jan 0, 1950. 0 hr + * inclo - inclination of satellite + * no - mean motion of satellite + * satn - satellite number + * + * outputs : + * ainv - 1.0 / a + * ao - semi major axis + * con41 - + * con42 - 1.0 - 5.0 cos(i) + * cosio - cosine of inclination + * cosio2 - cosio squared + * eccsq - eccentricity squared + * method - flag for deep space 'd', 'n' + * omeosq - 1.0 - ecco * ecco + * posq - semi-parameter squared + * rp - radius of perigee + * rteosq - square root of (1.0 - ecco*ecco) + * sinio - sine of inclination + * gsto - gst at time of observation rad + * no - mean motion of satellite + * + * locals : + * ak - + * d1 - + * del - + * adel - + * po - + * + * coupling : + * getgravconst + * gstime - find greenwich sidereal time from the julian date + * + * references : + * hoots, roehrich, norad spacetrack report #3 1980 + * hoots, norad spacetrack report #6 1986 + * hoots, schumacher and glover 2004 + * vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ +function initl(options) { + var ecco = options.ecco, + epoch = options.epoch, + inclo = options.inclo, + opsmode = options.opsmode; + var no = options.no; + // sgp4fix use old way of finding gst + // ----------------------- earth constants --------------------- + // sgp4fix identify constants and allow alternate values + // ------------- calculate auxillary epoch quantities ---------- + var eccsq = ecco * ecco; + var omeosq = 1.0 - eccsq; + var rteosq = Math.sqrt(omeosq); + var cosio = Math.cos(inclo); + var cosio2 = cosio * cosio; + // ------------------ un-kozai the mean motion ----------------- + var ak = Math.pow(_constants.xke / no, _constants.x2o3); + var d1 = 0.75 * _constants.j2 * (3.0 * cosio2 - 1.0) / (rteosq * omeosq); + var delPrime = d1 / (ak * ak); + var adel = ak * (1.0 - delPrime * delPrime - delPrime * (1.0 / 3.0 + 134.0 * delPrime * delPrime / 81.0)); + delPrime = d1 / (adel * adel); + no /= 1.0 + delPrime; + var ao = Math.pow(_constants.xke / no, _constants.x2o3); + var sinio = Math.sin(inclo); + var po = ao * omeosq; + var con42 = 1.0 - 5.0 * cosio2; + var con41 = -con42 - cosio2 - cosio2; + var ainv = 1.0 / ao; + var posq = po * po; + var rp = ao * (1.0 - ecco); + var method = 'n'; + // sgp4fix modern approach to finding sidereal time + var gsto; + if (opsmode === 'a') { + // sgp4fix use old way of finding gst + // count integer number of days from 0 jan 1970 + var ts70 = epoch - 7305.0; + var ds70 = Math.floor(ts70 + 1.0e-8); + var tfrac = ts70 - ds70; + // find greenwich location at epoch + var c1 = 1.72027916940703639e-2; // eslint-disable-line no-loss-of-precision + var thgr70 = 1.7321343856509374; // eslint-disable-line no-loss-of-precision + var fk5r = 5.07551419432269442e-15; // eslint-disable-line no-loss-of-precision + var c1p2p = c1 + _constants.twoPi; + gsto = (thgr70 + c1 * ds70 + c1p2p * tfrac + ts70 * ts70 * fk5r) % _constants.twoPi; + if (gsto < 0.0) { + gsto += _constants.twoPi; + } + } else { + gsto = (0, _gstime["default"])(epoch + 2433281.5); + } + return { + no: no, + method: method, + ainv: ainv, + ao: ao, + con41: con41, + con42: con42, + cosio: cosio, + cosio2: cosio2, + eccsq: eccsq, + omeosq: omeosq, + posq: posq, + rp: rp, + rteosq: rteosq, + sinio: sinio, + gsto: gsto + }; +} \ No newline at end of file diff --git a/node_modules/satellite.js/lib/propagation/propagate.js b/node_modules/satellite.js/lib/propagation/propagate.js new file mode 100644 index 0000000..86b05ea --- /dev/null +++ b/node_modules/satellite.js/lib/propagation/propagate.js @@ -0,0 +1,19 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = propagate; +var _constants = require("../constants"); +var _ext = require("../ext"); +var _sgp = _interopRequireDefault(require("./sgp4")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +function propagate(satrec) { + for (var _len = arguments.length, jdayArgs = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + jdayArgs[_key - 1] = arguments[_key]; + } + // Return a position and velocity vector for a given date and time. + var j = _ext.jday.apply(void 0, jdayArgs); + var m = (j - satrec.jdsatepoch) * _constants.minutesPerDay; + return (0, _sgp["default"])(satrec, m); +} \ No newline at end of file diff --git a/node_modules/satellite.js/lib/propagation/sgp4.js b/node_modules/satellite.js/lib/propagation/sgp4.js new file mode 100644 index 0000000..7348038 --- /dev/null +++ b/node_modules/satellite.js/lib/propagation/sgp4.js @@ -0,0 +1,399 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = sgp4; +var _constants = require("../constants"); +var _dpper = _interopRequireDefault(require("./dpper")); +var _dspace = _interopRequireDefault(require("./dspace")); +var _SatRec = require("./SatRec.js"); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/*---------------------------------------------------------------------------- + * + * procedure sgp4 + * + * this procedure is the sgp4 prediction model from space command. this is an + * updated and combined version of sgp4 and sdp4, which were originally + * published separately in spacetrack report //3. this version follows the + * methodology from the aiaa paper (2006) describing the history and + * development of the code. + * + * author : david vallado 719-573-2600 28 jun 2005 + * + * inputs : + * satrec - initialised structure from sgp4init() call. + * tsince - time since epoch (minutes) + * + * outputs : + * r - position vector km + * v - velocity km/sec + * return code - non-zero on error. + * 1 - mean elements, ecc >= 1.0 or ecc < -0.001 or a < 0.95 er + * 2 - mean motion less than 0.0 + * 3 - pert elements, ecc < 0.0 or ecc > 1.0 + * 4 - semi-latus rectum < 0.0 + * 5 - epoch elements are sub-orbital + * 6 - satellite has decayed + * + * locals : + * am - + * axnl, aynl - + * betal - + * cosim , sinim , cosomm , sinomm , cnod , snod , cos2u , + * sin2u , coseo1 , sineo1 , cosi , sini , cosip , sinip , + * cosisq , cossu , sinsu , cosu , sinu + * delm - + * delomg - + * dndt - + * eccm - + * emsq - + * ecose - + * el2 - + * eo1 - + * eccp - + * esine - + * argpm - + * argpp - + * omgadf - + * pl - + * r - + * rtemsq - + * rdotl - + * rl - + * rvdot - + * rvdotl - + * su - + * t2 , t3 , t4 , tc + * tem5, temp , temp1 , temp2 , tempa , tempe , templ + * u , ux , uy , uz , vx , vy , vz + * inclm - inclination + * mm - mean anomaly + * nm - mean motion + * nodem - right asc of ascending node + * xinc - + * xincp - + * xl - + * xlm - + * mp - + * xmdf - + * xmx - + * xmy - + * nodedf - + * xnode - + * nodep - + * np - + * + * coupling : + * getgravconst- + * dpper + * dspace + * + * references : + * hoots, roehrich, norad spacetrack report //3 1980 + * hoots, norad spacetrack report //6 1986 + * hoots, schumacher and glover 2004 + * vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ +function sgp4(satrec, tsince) { + var coseo1; + var sineo1; + var cosip; + var sinip; + var cosisq; + var delm; + var delomg; + var eo1; + var argpm; + var argpp; + var su; + var t3; + var t4; + var tc; + var tem5; + var temp; + var tempa; + var tempe; + var templ; + var inclm; + var mm; + var nm; + var nodem; + var xincp; + var xlm; + var mp; + var nodep; + /* ------------------ set mathematical constants --------------- */ + // sgp4fix divisor for divide by zero check on inclination + // the old check used 1.0 + cos(pi-1.0e-9), but then compared it to + // 1.5 e-12, so the threshold was changed to 1.5e-12 for consistency + var temp4 = 1.5e-12; + // --------------------- clear sgp4 error flag ----------------- + satrec.t = tsince; + satrec.error = _SatRec.SatRecError.None; + // ------- update for secular gravity and atmospheric drag ----- + var xmdf = satrec.mo + satrec.mdot * satrec.t; + var argpdf = satrec.argpo + satrec.argpdot * satrec.t; + var nodedf = satrec.nodeo + satrec.nodedot * satrec.t; + argpm = argpdf; + mm = xmdf; + var t2 = satrec.t * satrec.t; + nodem = nodedf + satrec.nodecf * t2; + tempa = 1.0 - satrec.cc1 * satrec.t; + tempe = satrec.bstar * satrec.cc4 * satrec.t; + templ = satrec.t2cof * t2; + if (satrec.isimp !== 1) { + delomg = satrec.omgcof * satrec.t; + // sgp4fix use mutliply for speed instead of pow + var delmtemp = 1.0 + satrec.eta * Math.cos(xmdf); + delm = satrec.xmcof * (delmtemp * delmtemp * delmtemp - satrec.delmo); + temp = delomg + delm; + mm = xmdf + temp; + argpm = argpdf - temp; + t3 = t2 * satrec.t; + t4 = t3 * satrec.t; + tempa = tempa - satrec.d2 * t2 - satrec.d3 * t3 - satrec.d4 * t4; + tempe += satrec.bstar * satrec.cc5 * (Math.sin(mm) - satrec.sinmao); + templ = templ + satrec.t3cof * t3 + t4 * (satrec.t4cof + satrec.t * satrec.t5cof); + } + nm = satrec.no; + var em = satrec.ecco; + inclm = satrec.inclo; + if (satrec.method === 'd') { + tc = satrec.t; + var dspaceOptions = { + irez: satrec.irez, + d2201: satrec.d2201, + d2211: satrec.d2211, + d3210: satrec.d3210, + d3222: satrec.d3222, + d4410: satrec.d4410, + d4422: satrec.d4422, + d5220: satrec.d5220, + d5232: satrec.d5232, + d5421: satrec.d5421, + d5433: satrec.d5433, + dedt: satrec.dedt, + del1: satrec.del1, + del2: satrec.del2, + del3: satrec.del3, + didt: satrec.didt, + dmdt: satrec.dmdt, + dnodt: satrec.dnodt, + domdt: satrec.domdt, + argpo: satrec.argpo, + argpdot: satrec.argpdot, + t: satrec.t, + tc: tc, + gsto: satrec.gsto, + xfact: satrec.xfact, + xlamo: satrec.xlamo, + no: satrec.no, + atime: satrec.atime, + em: em, + argpm: argpm, + inclm: inclm, + xli: satrec.xli, + mm: mm, + xni: satrec.xni, + nodem: nodem, + nm: nm + }; + var dspaceResult = (0, _dspace["default"])(dspaceOptions); + em = dspaceResult.em; + argpm = dspaceResult.argpm; + inclm = dspaceResult.inclm; + mm = dspaceResult.mm; + nodem = dspaceResult.nodem; + nm = dspaceResult.nm; + } + if (nm <= 0.0) { + // printf("// error nm %f\n", nm); + satrec.error = _SatRec.SatRecError.MeanMotionBelowZero; + // sgp4fix add return + return null; + } + var am = Math.pow(_constants.xke / nm, _constants.x2o3) * tempa * tempa; + nm = _constants.xke / Math.pow(am, 1.5); + em -= tempe; + // fix tolerance for error recognition + // sgp4fix am is fixed from the previous nm check + if (em >= 1.0 || em < -0.001) { + // || (am < 0.95) + // printf("// error em %f\n", em); + satrec.error = _SatRec.SatRecError.MeanEccentricityOutOfRange; + // sgp4fix to return if there is an error in eccentricity + return null; + } + // sgp4fix fix tolerance to avoid a divide by zero + if (em < 1.0e-6) { + em = 1.0e-6; + } + mm += satrec.no * templ; + xlm = mm + argpm + nodem; + nodem %= _constants.twoPi; + argpm %= _constants.twoPi; + xlm %= _constants.twoPi; + mm = (xlm - argpm - nodem) % _constants.twoPi; + var meanElements = { + am: am, + em: em, + im: inclm, + Om: nodem, + om: argpm, + mm: mm, + nm: nm + }; + // ----------------- compute extra mean quantities ------------- + var sinim = Math.sin(inclm); + var cosim = Math.cos(inclm); + // -------------------- add lunar-solar periodics -------------- + var ep = em; + xincp = inclm; + argpp = argpm; + nodep = nodem; + mp = mm; + sinip = sinim; + cosip = cosim; + if (satrec.method === 'd') { + var dpperParameters = { + inclo: satrec.inclo, + init: 'n', + ep: ep, + inclp: xincp, + nodep: nodep, + argpp: argpp, + mp: mp, + opsmode: satrec.operationmode + }; + var dpperResult = (0, _dpper["default"])(satrec, dpperParameters); + ep = dpperResult.ep; + nodep = dpperResult.nodep; + argpp = dpperResult.argpp; + mp = dpperResult.mp; + xincp = dpperResult.inclp; + if (xincp < 0.0) { + xincp = -xincp; + nodep += _constants.pi; + argpp -= _constants.pi; + } + if (ep < 0.0 || ep > 1.0) { + // printf("// error ep %f\n", ep); + satrec.error = _SatRec.SatRecError.PerturbedEccentricityOutOfRange; + // sgp4fix add return + return null; + } + } + // -------------------- long period periodics ------------------ + if (satrec.method === 'd') { + sinip = Math.sin(xincp); + cosip = Math.cos(xincp); + satrec.aycof = -0.5 * _constants.j3oj2 * sinip; + // sgp4fix for divide by zero for xincp = 180 deg + if (Math.abs(cosip + 1.0) > 1.5e-12) { + satrec.xlcof = -0.25 * _constants.j3oj2 * sinip * (3.0 + 5.0 * cosip) / (1.0 + cosip); + } else { + satrec.xlcof = -0.25 * _constants.j3oj2 * sinip * (3.0 + 5.0 * cosip) / temp4; + } + } + var axnl = ep * Math.cos(argpp); + temp = 1.0 / (am * (1.0 - ep * ep)); + var aynl = ep * Math.sin(argpp) + temp * satrec.aycof; + var xl = mp + argpp + nodep + temp * satrec.xlcof * axnl; + // --------------------- solve kepler's equation --------------- + var u = (xl - nodep) % _constants.twoPi; + eo1 = u; + tem5 = 9999.9; + var ktr = 1; + // sgp4fix for kepler iteration + // the following iteration needs better limits on corrections + while (Math.abs(tem5) >= 1.0e-12 && ktr <= 10) { + sineo1 = Math.sin(eo1); + coseo1 = Math.cos(eo1); + tem5 = 1.0 - coseo1 * axnl - sineo1 * aynl; + tem5 = (u - aynl * coseo1 + axnl * sineo1 - eo1) / tem5; + if (Math.abs(tem5) >= 0.95) { + if (tem5 > 0.0) { + tem5 = 0.95; + } else { + tem5 = -0.95; + } + } + eo1 += tem5; + ktr += 1; + } + // ------------- short period preliminary quantities ----------- + var ecose = axnl * coseo1 + aynl * sineo1; + var esine = axnl * sineo1 - aynl * coseo1; + var el2 = axnl * axnl + aynl * aynl; + var pl = am * (1.0 - el2); + if (pl < 0.0) { + // printf("// error pl %f\n", pl); + satrec.error = _SatRec.SatRecError.SemiLatusRectumBelowZero; + // sgp4fix add return + return null; + } + var rl = am * (1.0 - ecose); + var rdotl = Math.sqrt(am) * esine / rl; + var rvdotl = Math.sqrt(pl) / rl; + var betal = Math.sqrt(1.0 - el2); + temp = esine / (1.0 + betal); + var sinu = am / rl * (sineo1 - aynl - axnl * temp); + var cosu = am / rl * (coseo1 - axnl + aynl * temp); + su = Math.atan2(sinu, cosu); + var sin2u = (cosu + cosu) * sinu; + var cos2u = 1.0 - 2.0 * sinu * sinu; + temp = 1.0 / pl; + var temp1 = 0.5 * _constants.j2 * temp; + var temp2 = temp1 * temp; + // -------------- update for short period periodics ------------ + if (satrec.method === 'd') { + cosisq = cosip * cosip; + satrec.con41 = 3.0 * cosisq - 1.0; + satrec.x1mth2 = 1.0 - cosisq; + satrec.x7thm1 = 7.0 * cosisq - 1.0; + } + var mrt = rl * (1.0 - 1.5 * temp2 * betal * satrec.con41) + 0.5 * temp1 * satrec.x1mth2 * cos2u; + // sgp4fix for decaying satellites + if (mrt < 1.0) { + // printf("// decay condition %11.6f \n",mrt); + satrec.error = _SatRec.SatRecError.Decayed; + return null; + } + su -= 0.25 * temp2 * satrec.x7thm1 * sin2u; + var xnode = nodep + 1.5 * temp2 * cosip * sin2u; + var xinc = xincp + 1.5 * temp2 * cosip * sinip * cos2u; + var mvt = rdotl - nm * temp1 * satrec.x1mth2 * sin2u / _constants.xke; + var rvdot = rvdotl + nm * temp1 * (satrec.x1mth2 * cos2u + 1.5 * satrec.con41) / _constants.xke; + // --------------------- orientation vectors ------------------- + var sinsu = Math.sin(su); + var cossu = Math.cos(su); + var snod = Math.sin(xnode); + var cnod = Math.cos(xnode); + var sini = Math.sin(xinc); + var cosi = Math.cos(xinc); + var xmx = -snod * cosi; + var xmy = cnod * cosi; + var ux = xmx * sinsu + cnod * cossu; + var uy = xmy * sinsu + snod * cossu; + var uz = sini * sinsu; + var vx = xmx * cossu - cnod * sinsu; + var vy = xmy * cossu - snod * sinsu; + var vz = sini * cossu; + // --------- position and velocity (in km and km/sec) ---------- + var r = { + x: mrt * ux * _constants.earthRadius, + y: mrt * uy * _constants.earthRadius, + z: mrt * uz * _constants.earthRadius + }; + var v = { + x: (mvt * ux + rvdot * vx) * _constants.vkmpersec, + y: (mvt * uy + rvdot * vy) * _constants.vkmpersec, + z: (mvt * uz + rvdot * vz) * _constants.vkmpersec + }; + return { + position: r, + velocity: v, + meanElements: meanElements + }; +} \ No newline at end of file diff --git a/node_modules/satellite.js/lib/propagation/sgp4init.js b/node_modules/satellite.js/lib/propagation/sgp4init.js new file mode 100644 index 0000000..97f8333 --- /dev/null +++ b/node_modules/satellite.js/lib/propagation/sgp4init.js @@ -0,0 +1,617 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = sgp4init; +var _constants = require("../constants"); +var _dpper = _interopRequireDefault(require("./dpper")); +var _dscom = _interopRequireDefault(require("./dscom")); +var _dsinit = _interopRequireDefault(require("./dsinit")); +var _initl = _interopRequireDefault(require("./initl")); +var _sgp = _interopRequireDefault(require("./sgp4")); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; } +/*----------------------------------------------------------------------------- + * + * procedure sgp4init + * + * this procedure initializes variables for sgp4. + * + * author : david vallado 719-573-2600 28 jun 2005 + * author : david vallado 719-573-2600 28 jun 2005 + * + * inputs : + * opsmode - mode of operation afspc or improved 'a', 'i' + * satn - satellite number + * bstar - sgp4 type drag coefficient kg/m2er + * ecco - eccentricity + * epoch - epoch time in days from jan 0, 1950. 0 hr + * argpo - argument of perigee (output if ds) + * inclo - inclination + * mo - mean anomaly (output if ds) + * no - mean motion + * nodeo - right ascension of ascending node + * + * outputs : + * rec - common values for subsequent calls + * return code - non-zero on error. + * 1 - mean elements, ecc >= 1.0 or ecc < -0.001 or a < 0.95 er + * 2 - mean motion less than 0.0 + * 3 - pert elements, ecc < 0.0 or ecc > 1.0 + * 4 - semi-latus rectum < 0.0 + * 5 - epoch elements are sub-orbital + * 6 - satellite has decayed + * + * locals : + * cnodm , snodm , cosim , sinim , cosomm , sinomm + * cc1sq , cc2 , cc3 + * coef , coef1 + * cosio4 - + * day - + * dndt - + * em - eccentricity + * emsq - eccentricity squared + * eeta - + * etasq - + * gam - + * argpm - argument of perigee + * nodem - + * inclm - inclination + * mm - mean anomaly + * nm - mean motion + * perige - perigee + * pinvsq - + * psisq - + * qzms24 - + * rtemsq - + * s1, s2, s3, s4, s5, s6, s7 - + * sfour - + * ss1, ss2, ss3, ss4, ss5, ss6, ss7 - + * sz1, sz2, sz3 + * sz11, sz12, sz13, sz21, sz22, sz23, sz31, sz32, sz33 - + * tc - + * temp - + * temp1, temp2, temp3 - + * tsi - + * xpidot - + * xhdot1 - + * z1, z2, z3 - + * z11, z12, z13, z21, z22, z23, z31, z32, z33 - + * + * coupling : + * getgravconst- + * initl - + * dscom - + * dpper - + * dsinit - + * sgp4 - + * + * references : + * hoots, roehrich, norad spacetrack report #3 1980 + * hoots, norad spacetrack report #6 1986 + * hoots, schumacher and glover 2004 + * vallado, crawford, hujsak, kelso 2006 + ----------------------------------------------------------------------------*/ +function sgp4init(satrecInit, options) { + var opsmode = options.opsmode, + satn = options.satn, + epoch = options.epoch, + xbstar = options.xbstar, + xecco = options.xecco, + xargpo = options.xargpo, + xinclo = options.xinclo, + xmo = options.xmo, + xno = options.xno, + xnodeo = options.xnodeo; + var cosim; + var sinim; + var cc1sq; + var cc2; + var cc3; + var coef; + var coef1; + var cosio4; + var em; + var emsq; + var eeta; + var etasq; + var argpm; + var nodem; + var inclm; + var mm; + var nm; + var perige; + var pinvsq; + var psisq; + var qzms24; + var s1; + var s2; + var s3; + var s4; + var s5; + var sfour; + var ss1; + var ss2; + var ss3; + var ss4; + var ss5; + var sz1; + var sz3; + var sz11; + var sz13; + var sz21; + var sz23; + var sz31; + var sz33; + var tc; + var temp; + var temp1; + var temp2; + var temp3; + var tsi; + var xpidot; + var xhdot1; + var z1; + var z3; + var z11; + var z13; + var z21; + var z23; + var z31; + var z33; + /* ------------------------ initialization --------------------- */ + // sgp4fix divisor for divide by zero check on inclination + // the old check used 1.0 + Math.cos(pi-1.0e-9), but then compared it to + // 1.5 e-12, so the threshold was changed to 1.5e-12 for consistency + var temp4 = 1.5e-12; + var satrec = satrecInit; + // ----------- set all near earth variables to zero ------------ + satrec.isimp = 0; + satrec.method = 'n'; + satrec.aycof = 0.0; + satrec.con41 = 0.0; + satrec.cc1 = 0.0; + satrec.cc4 = 0.0; + satrec.cc5 = 0.0; + satrec.d2 = 0.0; + satrec.d3 = 0.0; + satrec.d4 = 0.0; + satrec.delmo = 0.0; + satrec.eta = 0.0; + satrec.argpdot = 0.0; + satrec.omgcof = 0.0; + satrec.sinmao = 0.0; + satrec.t = 0.0; + satrec.t2cof = 0.0; + satrec.t3cof = 0.0; + satrec.t4cof = 0.0; + satrec.t5cof = 0.0; + satrec.x1mth2 = 0.0; + satrec.x7thm1 = 0.0; + satrec.mdot = 0.0; + satrec.nodedot = 0.0; + satrec.xlcof = 0.0; + satrec.xmcof = 0.0; + satrec.nodecf = 0.0; + // ----------- set all deep space variables to zero ------------ + satrec.irez = 0; + satrec.d2201 = 0.0; + satrec.d2211 = 0.0; + satrec.d3210 = 0.0; + satrec.d3222 = 0.0; + satrec.d4410 = 0.0; + satrec.d4422 = 0.0; + satrec.d5220 = 0.0; + satrec.d5232 = 0.0; + satrec.d5421 = 0.0; + satrec.d5433 = 0.0; + satrec.dedt = 0.0; + satrec.del1 = 0.0; + satrec.del2 = 0.0; + satrec.del3 = 0.0; + satrec.didt = 0.0; + satrec.dmdt = 0.0; + satrec.dnodt = 0.0; + satrec.domdt = 0.0; + satrec.e3 = 0.0; + satrec.ee2 = 0.0; + satrec.peo = 0.0; + satrec.pgho = 0.0; + satrec.pho = 0.0; + satrec.pinco = 0.0; + satrec.plo = 0.0; + satrec.se2 = 0.0; + satrec.se3 = 0.0; + satrec.sgh2 = 0.0; + satrec.sgh3 = 0.0; + satrec.sgh4 = 0.0; + satrec.sh2 = 0.0; + satrec.sh3 = 0.0; + satrec.si2 = 0.0; + satrec.si3 = 0.0; + satrec.sl2 = 0.0; + satrec.sl3 = 0.0; + satrec.sl4 = 0.0; + satrec.gsto = 0.0; + satrec.xfact = 0.0; + satrec.xgh2 = 0.0; + satrec.xgh3 = 0.0; + satrec.xgh4 = 0.0; + satrec.xh2 = 0.0; + satrec.xh3 = 0.0; + satrec.xi2 = 0.0; + satrec.xi3 = 0.0; + satrec.xl2 = 0.0; + satrec.xl3 = 0.0; + satrec.xl4 = 0.0; + satrec.xlamo = 0.0; + satrec.zmol = 0.0; + satrec.zmos = 0.0; + satrec.atime = 0.0; + satrec.xli = 0.0; + satrec.xni = 0.0; + // sgp4fix - note the following variables are also passed directly via satrec. + // it is possible to streamline the sgp4init call by deleting the "x" + // variables, but the user would need to set the satrec.* values first. we + // include the additional assignments in case twoline2rv is not used. + satrec.bstar = xbstar; + satrec.ecco = xecco; + satrec.argpo = xargpo; + satrec.inclo = xinclo; + satrec.mo = xmo; + satrec.no = xno; + satrec.nodeo = xnodeo; + // sgp4fix add opsmode + satrec.operationmode = opsmode; + // ------------------------ earth constants ----------------------- + // sgp4fix identify constants and allow alternate values + var ss = 78.0 / _constants.earthRadius + 1.0; + // sgp4fix use multiply for speed instead of pow + var qzms2ttemp = (120.0 - 78.0) / _constants.earthRadius; + var qzms2t = qzms2ttemp * qzms2ttemp * qzms2ttemp * qzms2ttemp; + satrec.init = 'y'; + satrec.t = 0.0; + var initlOptions = { + satn: satn, + ecco: satrec.ecco, + epoch: epoch, + inclo: satrec.inclo, + no: satrec.no, + method: satrec.method, + opsmode: satrec.operationmode + }; + var initlResult = (0, _initl["default"])(initlOptions); + var ao = initlResult.ao, + con42 = initlResult.con42, + cosio = initlResult.cosio, + cosio2 = initlResult.cosio2, + eccsq = initlResult.eccsq, + omeosq = initlResult.omeosq, + posq = initlResult.posq, + rp = initlResult.rp, + rteosq = initlResult.rteosq, + sinio = initlResult.sinio; + satrec.no = initlResult.no; + satrec.con41 = initlResult.con41; + satrec.gsto = initlResult.gsto; + satrec.a = Math.pow(satrec.no * _constants.tumin, -2.0 / 3.0); + satrec.alta = satrec.a * (1.0 + satrec.ecco) - 1.0; + satrec.altp = satrec.a * (1.0 - satrec.ecco) - 1.0; + satrec.error = 0; + // sgp4fix remove this check as it is unnecessary + // the mrt check in sgp4 handles decaying satellite cases even if the starting + // condition is below the surface of te earth + // if (rp < 1.0) + // { + // printf("// *** satn%d epoch elts sub-orbital ***\n", satn); + // satrec.error = 5; + // } + if (omeosq >= 0.0 || satrec.no >= 0.0) { + satrec.isimp = 0; + if (rp < 220.0 / _constants.earthRadius + 1.0) { + satrec.isimp = 1; + } + sfour = ss; + qzms24 = qzms2t; + perige = (rp - 1.0) * _constants.earthRadius; + // - for perigees below 156 km, s and qoms2t are altered - + if (perige < 156.0) { + sfour = perige - 78.0; + if (perige < 98.0) { + sfour = 20.0; + } + // sgp4fix use multiply for speed instead of pow + var qzms24temp = (120.0 - sfour) / _constants.earthRadius; + qzms24 = qzms24temp * qzms24temp * qzms24temp * qzms24temp; + sfour = sfour / _constants.earthRadius + 1.0; + } + pinvsq = 1.0 / posq; + tsi = 1.0 / (ao - sfour); + satrec.eta = ao * satrec.ecco * tsi; + etasq = satrec.eta * satrec.eta; + eeta = satrec.ecco * satrec.eta; + psisq = Math.abs(1.0 - etasq); + coef = qzms24 * Math.pow(tsi, 4.0); + coef1 = coef / Math.pow(psisq, 3.5); + cc2 = coef1 * satrec.no * (ao * (1.0 + 1.5 * etasq + eeta * (4.0 + etasq)) + 0.375 * _constants.j2 * tsi / psisq * satrec.con41 * (8.0 + 3.0 * etasq * (8.0 + etasq))); + satrec.cc1 = satrec.bstar * cc2; + cc3 = 0.0; + if (satrec.ecco > 1.0e-4) { + cc3 = -2.0 * coef * tsi * _constants.j3oj2 * satrec.no * sinio / satrec.ecco; + } + satrec.x1mth2 = 1.0 - cosio2; + satrec.cc4 = 2.0 * satrec.no * coef1 * ao * omeosq * (satrec.eta * (2.0 + 0.5 * etasq) + satrec.ecco * (0.5 + 2.0 * etasq) - _constants.j2 * tsi / (ao * psisq) * (-3.0 * satrec.con41 * (1.0 - 2.0 * eeta + etasq * (1.5 - 0.5 * eeta)) + 0.75 * satrec.x1mth2 * (2.0 * etasq - eeta * (1.0 + etasq)) * Math.cos(2.0 * satrec.argpo))); + satrec.cc5 = 2.0 * coef1 * ao * omeosq * (1.0 + 2.75 * (etasq + eeta) + eeta * etasq); + cosio4 = cosio2 * cosio2; + temp1 = 1.5 * _constants.j2 * pinvsq * satrec.no; + temp2 = 0.5 * temp1 * _constants.j2 * pinvsq; + temp3 = -0.46875 * _constants.j4 * pinvsq * pinvsq * satrec.no; + satrec.mdot = satrec.no + 0.5 * temp1 * rteosq * satrec.con41 + 0.0625 * temp2 * rteosq * (13.0 - 78.0 * cosio2 + 137.0 * cosio4); + satrec.argpdot = -0.5 * temp1 * con42 + 0.0625 * temp2 * (7.0 - 114.0 * cosio2 + 395.0 * cosio4) + temp3 * (3.0 - 36.0 * cosio2 + 49.0 * cosio4); + xhdot1 = -temp1 * cosio; + satrec.nodedot = xhdot1 + (0.5 * temp2 * (4.0 - 19.0 * cosio2) + 2.0 * temp3 * (3.0 - 7.0 * cosio2)) * cosio; + xpidot = satrec.argpdot + satrec.nodedot; + satrec.omgcof = satrec.bstar * cc3 * Math.cos(satrec.argpo); + satrec.xmcof = 0.0; + if (satrec.ecco > 1.0e-4) { + satrec.xmcof = -_constants.x2o3 * coef * satrec.bstar / eeta; + } + satrec.nodecf = 3.5 * omeosq * xhdot1 * satrec.cc1; + satrec.t2cof = 1.5 * satrec.cc1; + // sgp4fix for divide by zero with xinco = 180 deg + if (Math.abs(cosio + 1.0) > 1.5e-12) { + satrec.xlcof = -0.25 * _constants.j3oj2 * sinio * (3.0 + 5.0 * cosio) / (1.0 + cosio); + } else { + satrec.xlcof = -0.25 * _constants.j3oj2 * sinio * (3.0 + 5.0 * cosio) / temp4; + } + satrec.aycof = -0.5 * _constants.j3oj2 * sinio; + // sgp4fix use multiply for speed instead of pow + var delmotemp = 1.0 + satrec.eta * Math.cos(satrec.mo); + satrec.delmo = delmotemp * delmotemp * delmotemp; + satrec.sinmao = Math.sin(satrec.mo); + satrec.x7thm1 = 7.0 * cosio2 - 1.0; + // --------------- deep space initialization ------------- + if (2 * _constants.pi / satrec.no >= 225.0) { + satrec.method = 'd'; + satrec.isimp = 1; + tc = 0.0; + inclm = satrec.inclo; + var dscomOptions = { + epoch: epoch, + ep: satrec.ecco, + argpp: satrec.argpo, + tc: tc, + inclp: satrec.inclo, + nodep: satrec.nodeo, + np: satrec.no, + e3: satrec.e3, + ee2: satrec.ee2, + peo: satrec.peo, + pgho: satrec.pgho, + pho: satrec.pho, + pinco: satrec.pinco, + plo: satrec.plo, + se2: satrec.se2, + se3: satrec.se3, + sgh2: satrec.sgh2, + sgh3: satrec.sgh3, + sgh4: satrec.sgh4, + sh2: satrec.sh2, + sh3: satrec.sh3, + si2: satrec.si2, + si3: satrec.si3, + sl2: satrec.sl2, + sl3: satrec.sl3, + sl4: satrec.sl4, + xgh2: satrec.xgh2, + xgh3: satrec.xgh3, + xgh4: satrec.xgh4, + xh2: satrec.xh2, + xh3: satrec.xh3, + xi2: satrec.xi2, + xi3: satrec.xi3, + xl2: satrec.xl2, + xl3: satrec.xl3, + xl4: satrec.xl4, + zmol: satrec.zmol, + zmos: satrec.zmos + }; + var dscomResult = (0, _dscom["default"])(dscomOptions); + satrec.e3 = dscomResult.e3; + satrec.ee2 = dscomResult.ee2; + satrec.peo = dscomResult.peo; + satrec.pgho = dscomResult.pgho; + satrec.pho = dscomResult.pho; + satrec.pinco = dscomResult.pinco; + satrec.plo = dscomResult.plo; + satrec.se2 = dscomResult.se2; + satrec.se3 = dscomResult.se3; + satrec.sgh2 = dscomResult.sgh2; + satrec.sgh3 = dscomResult.sgh3; + satrec.sgh4 = dscomResult.sgh4; + satrec.sh2 = dscomResult.sh2; + satrec.sh3 = dscomResult.sh3; + satrec.si2 = dscomResult.si2; + satrec.si3 = dscomResult.si3; + satrec.sl2 = dscomResult.sl2; + satrec.sl3 = dscomResult.sl3; + satrec.sl4 = dscomResult.sl4; + sinim = dscomResult.sinim; + cosim = dscomResult.cosim; + em = dscomResult.em; + emsq = dscomResult.emsq; + s1 = dscomResult.s1; + s2 = dscomResult.s2; + s3 = dscomResult.s3; + s4 = dscomResult.s4; + s5 = dscomResult.s5; + ss1 = dscomResult.ss1; + ss2 = dscomResult.ss2; + ss3 = dscomResult.ss3; + ss4 = dscomResult.ss4; + ss5 = dscomResult.ss5; + sz1 = dscomResult.sz1; + sz3 = dscomResult.sz3; + sz11 = dscomResult.sz11; + sz13 = dscomResult.sz13; + sz21 = dscomResult.sz21; + sz23 = dscomResult.sz23; + sz31 = dscomResult.sz31; + sz33 = dscomResult.sz33; + satrec.xgh2 = dscomResult.xgh2; + satrec.xgh3 = dscomResult.xgh3; + satrec.xgh4 = dscomResult.xgh4; + satrec.xh2 = dscomResult.xh2; + satrec.xh3 = dscomResult.xh3; + satrec.xi2 = dscomResult.xi2; + satrec.xi3 = dscomResult.xi3; + satrec.xl2 = dscomResult.xl2; + satrec.xl3 = dscomResult.xl3; + satrec.xl4 = dscomResult.xl4; + satrec.zmol = dscomResult.zmol; + satrec.zmos = dscomResult.zmos; + nm = dscomResult.nm; + z1 = dscomResult.z1; + z3 = dscomResult.z3; + z11 = dscomResult.z11; + z13 = dscomResult.z13; + z21 = dscomResult.z21; + z23 = dscomResult.z23; + z31 = dscomResult.z31; + z33 = dscomResult.z33; + var dpperOptions = { + inclo: inclm, + init: satrec.init, + ep: satrec.ecco, + inclp: satrec.inclo, + nodep: satrec.nodeo, + argpp: satrec.argpo, + mp: satrec.mo, + opsmode: satrec.operationmode + }; + var dpperResult = (0, _dpper["default"])(satrec, dpperOptions); + satrec.ecco = dpperResult.ep; + satrec.inclo = dpperResult.inclp; + satrec.nodeo = dpperResult.nodep; + satrec.argpo = dpperResult.argpp; + satrec.mo = dpperResult.mp; + argpm = 0.0; + nodem = 0.0; + mm = 0.0; + var dsinitOptions = { + cosim: cosim, + emsq: emsq, + argpo: satrec.argpo, + s1: s1, + s2: s2, + s3: s3, + s4: s4, + s5: s5, + sinim: sinim, + ss1: ss1, + ss2: ss2, + ss3: ss3, + ss4: ss4, + ss5: ss5, + sz1: sz1, + sz3: sz3, + sz11: sz11, + sz13: sz13, + sz21: sz21, + sz23: sz23, + sz31: sz31, + sz33: sz33, + t: satrec.t, + tc: tc, + gsto: satrec.gsto, + mo: satrec.mo, + mdot: satrec.mdot, + no: satrec.no, + nodeo: satrec.nodeo, + nodedot: satrec.nodedot, + xpidot: xpidot, + z1: z1, + z3: z3, + z11: z11, + z13: z13, + z21: z21, + z23: z23, + z31: z31, + z33: z33, + ecco: satrec.ecco, + eccsq: eccsq, + em: em, + argpm: argpm, + inclm: inclm, + mm: mm, + nm: nm, + nodem: nodem, + irez: satrec.irez, + atime: satrec.atime, + d2201: satrec.d2201, + d2211: satrec.d2211, + d3210: satrec.d3210, + d3222: satrec.d3222, + d4410: satrec.d4410, + d4422: satrec.d4422, + d5220: satrec.d5220, + d5232: satrec.d5232, + d5421: satrec.d5421, + d5433: satrec.d5433, + dedt: satrec.dedt, + didt: satrec.didt, + dmdt: satrec.dmdt, + dnodt: satrec.dnodt, + domdt: satrec.domdt, + del1: satrec.del1, + del2: satrec.del2, + del3: satrec.del3, + xfact: satrec.xfact, + xlamo: satrec.xlamo, + xli: satrec.xli, + xni: satrec.xni + }; + var dsinitResult = (0, _dsinit["default"])(dsinitOptions); + satrec.irez = dsinitResult.irez; + satrec.atime = dsinitResult.atime; + satrec.d2201 = dsinitResult.d2201; + satrec.d2211 = dsinitResult.d2211; + satrec.d3210 = dsinitResult.d3210; + satrec.d3222 = dsinitResult.d3222; + satrec.d4410 = dsinitResult.d4410; + satrec.d4422 = dsinitResult.d4422; + satrec.d5220 = dsinitResult.d5220; + satrec.d5232 = dsinitResult.d5232; + satrec.d5421 = dsinitResult.d5421; + satrec.d5433 = dsinitResult.d5433; + satrec.dedt = dsinitResult.dedt; + satrec.didt = dsinitResult.didt; + satrec.dmdt = dsinitResult.dmdt; + satrec.dnodt = dsinitResult.dnodt; + satrec.domdt = dsinitResult.domdt; + satrec.del1 = dsinitResult.del1; + satrec.del2 = dsinitResult.del2; + satrec.del3 = dsinitResult.del3; + satrec.xfact = dsinitResult.xfact; + satrec.xlamo = dsinitResult.xlamo; + satrec.xli = dsinitResult.xli; + satrec.xni = dsinitResult.xni; + } + // ----------- set variables if not deep space ----------- + if (satrec.isimp !== 1) { + cc1sq = satrec.cc1 * satrec.cc1; + satrec.d2 = 4.0 * ao * tsi * cc1sq; + temp = satrec.d2 * tsi * satrec.cc1 / 3.0; + satrec.d3 = (17.0 * ao + sfour) * temp; + satrec.d4 = 0.5 * temp * ao * tsi * (221.0 * ao + 31.0 * sfour) * satrec.cc1; + satrec.t3cof = satrec.d2 + 2.0 * cc1sq; + satrec.t4cof = 0.25 * (3.0 * satrec.d3 + satrec.cc1 * (12.0 * satrec.d2 + 10.0 * cc1sq)); + satrec.t5cof = 0.2 * (3.0 * satrec.d4 + 12.0 * satrec.cc1 * satrec.d3 + 6.0 * satrec.d2 * satrec.d2 + 15.0 * cc1sq * (2.0 * satrec.d2 + cc1sq)); + } + /* finally propogate to zero epoch to initialize all others. */ + // sgp4fix take out check to let satellites process until they are actually below earth surface + // if(satrec.error == 0) + } + (0, _sgp["default"])(satrec, 0); + satrec.init = 'n'; +} \ No newline at end of file diff --git a/node_modules/satellite.js/lib/sun.js b/node_modules/satellite.js/lib/sun.js new file mode 100644 index 0000000..61f1e72 --- /dev/null +++ b/node_modules/satellite.js/lib/sun.js @@ -0,0 +1,131 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.sunPos = sunPos; +var _constants = require("./constants"); +//////////////////////////////////////////////////////////////////////////////////// +/* Line by Line MATLAB-to-Javascript conversion of "sun.mat" from Vallado package */ +//////////////////////////////////////////////////////////////////////////////////// +/* ----------------------------------------------------------------------------- + * + * function sunPos + * + * this function calculates the geocentric equatorial position vector + * the sun given the julian date. this is the low precision formula and + * is valid for years from 1950 to 2050. accuaracy of apparent coordinates + * is 0.01 degrees. notice many of the calculations are performed in + * degrees, and are not changed until later. this is due to the fact that + * the almanac uses degrees exclusively in their formulations. + * + * author : david vallado 719-573-2600 1 mar 2001 + * + * inputs description range / units + * jd - julian date days from 4713 bc + * + * outputs : + * rsun - ijk position vector of the sun au + * rtasc - right ascension rad + * decl - declination rad + * + * coupling : + * - + * + * references : + * VALLADO, DAVID A. (2022) ‘Computer software in MATLAB’, in Fundamentals of astrodynamics and applications. 5th edn. + * Computer software in MATLAB: http://celestrak.org/software/vallado-sw.php + * --------------------------------------------------------------------------- */ +function sunPos(jday) { + // ------------------------- implementation ----------------- + // ------------------- initialize values -------------------- + var tut1 = (jday - 2451545) / 36525; + var meanlong = (280.460 + 36000.77 * tut1) % 360; //deg + var ttdb = tut1; // is this declaration required instead of replacing `ttdb` with `tut1` + var meananomaly = (357.5277233 + 35999.05034 * ttdb * _constants.deg2rad) % _constants.twoPi; //rad + if (meananomaly < 0) { + meananomaly += _constants.twoPi; + } + var eclplong_raw = (meanlong + 1.914666471 * Math.sin(meananomaly) + 0.019994643 * Math.sin(2.0 * meananomaly)) % 360.0 * _constants.deg2rad; //rad + var obliquity = (23.439291 - 0.0130042 * ttdb) * _constants.deg2rad; //rad + // --------- find magnitude of sun vector, and it's components ------ + var magr = 1.000140612 - 0.016708617 * Math.cos(meananomaly) - 0.000139589 * Math.cos(2.0 * meananomaly); // in au's + var rsun = [magr * Math.cos(eclplong_raw), magr * Math.cos(obliquity) * Math.sin(eclplong_raw), magr * Math.sin(obliquity) * Math.sin(eclplong_raw)]; + var rtasc_raw = Math.atan(Math.cos(obliquity) * Math.tan(eclplong_raw)); + // --- check that rtasc is in the same quadrant as eclplong_raw ---- + var eclplong = eclplong_raw; + if (eclplong < 0.0) { + eclplong += _constants.twoPi; // make sure it's in 0 to 2pi range + } + var rtasc = rtasc_raw; + if (Math.abs(eclplong_raw - rtasc) > _constants.pi * 0.5) { + rtasc += 0.5 * _constants.pi * Math.round((eclplong_raw - rtasc_raw) / (0.5 * _constants.pi)); + } + var decl = Math.asin(Math.sin(obliquity) * Math.sin(eclplong_raw)); + return { + rsun: rsun, + rtasc: rtasc, + decl: decl + }; +} +/* Original MATLAB code for Sun position from Vallado package (sun.mat) */ +/* +function [rsun,rtasc,decl] = sun ( jd ); + + twopi = 2.0*pi; + deg2rad = pi/180.0; + show = 'n'; + + % ------------------------- implementation ----------------- + % ------------------- initialize values -------------------- + tut1= ( jd - 2451545.0 )/ 36525.0; + + if show == 'y' + fprintf(1,'tut1 %14.9f \n',tut1); + end + + meanlong= 280.460 + 36000.77*tut1; + meanlong= rem( meanlong,360.0 ); %deg + + ttdb= tut1; + meananomaly= 357.5277233 + 35999.05034 *ttdb; + meananomaly= rem( meananomaly*deg2rad,twopi ); %rad + if ( meananomaly < 0.0 ) + meananomaly= twopi + meananomaly; + end + + eclplong_raw= meanlong + 1.914666471 *sin(meananomaly) ... + + 0.019994643 *sin(2.0 *meananomaly); %deg + eclplong_raw= rem( eclplong_raw,360.0 ); %deg + + obliquity= 23.439291 - 0.0130042 *ttdb; %deg + + eclplong_raw = eclplong_raw *deg2rad; + obliquity= obliquity *deg2rad; + + % --------- find magnitude of sun vector, ) components ------ + magr= 1.000140612 - 0.016708617 *cos( meananomaly ) ... + - 0.000139589 *cos( 2.0 *meananomaly ); % in au's + + rsun(1)= magr*cos( eclplong_raw ); + rsun(2)= magr*cos(obliquity)*sin(eclplong_raw); + rsun(3)= magr*sin(obliquity)*sin(eclplong_raw); + + if show == 'y' + fprintf(1,'meanlon %11.6f meanan %11.6f eclplon %11.6f obli %11.6f \n', ... + meanlong,meananomaly/deg2rad,eclplong_raw/deg2rad,obliquity/deg2rad); + fprintf(1,'rs %11.9f %11.9f %11.9f \n',rsun); + fprintf(1,'magr %14.7f \n',magr); + end + + rtasc= atan( cos(obliquity)*tan(eclplong_raw) ); + + % --- check that rtasc is in the same quadrant as eclplong_raw ---- + if ( eclplong_raw < 0.0 ) + eclplong_raw= eclplong_raw + twopi; % make sure it's in 0 to 2pi range + end + if ( abs( eclplong_raw-rtasc ) > pi*0.5 ) + rtasc= rtasc + 0.5 *pi*round( (eclplong_raw-rtasc)/(0.5 *pi)); + end + decl = asin( sin(obliquity)*sin(eclplong_raw) ); +*/ \ No newline at end of file diff --git a/node_modules/satellite.js/lib/transforms.js b/node_modules/satellite.js/lib/transforms.js new file mode 100644 index 0000000..227d237 --- /dev/null +++ b/node_modules/satellite.js/lib/transforms.js @@ -0,0 +1,167 @@ +"use strict"; + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.degreesLat = degreesLat; +exports.degreesLong = degreesLong; +exports.degreesToRadians = degreesToRadians; +exports.ecfToEci = ecfToEci; +exports.ecfToLookAngles = ecfToLookAngles; +exports.eciToEcf = eciToEcf; +exports.eciToGeodetic = eciToGeodetic; +exports.geodeticToEcf = geodeticToEcf; +exports.radiansLat = radiansLat; +exports.radiansLong = radiansLong; +exports.radiansToDegrees = radiansToDegrees; +var _constants = require("./constants"); +function radiansToDegrees(radians) { + return radians * _constants.rad2deg; +} +function degreesToRadians(degrees) { + return degrees * _constants.deg2rad; +} +function degreesLat(radians) { + if (radians < -_constants.pi / 2 || radians > _constants.pi / 2) { + throw new RangeError('Latitude radians must be in range [-pi/2; pi/2].'); + } + return radiansToDegrees(radians); +} +function degreesLong(radians) { + if (radians < -_constants.pi || radians > _constants.pi) { + throw new RangeError('Longitude radians must be in range [-pi; pi].'); + } + return radiansToDegrees(radians); +} +function radiansLat(degrees) { + if (degrees < -90 || degrees > 90) { + throw new RangeError('Latitude degrees must be in range [-90; 90].'); + } + return degreesToRadians(degrees); +} +function radiansLong(degrees) { + if (degrees < -180 || degrees > 180) { + throw new RangeError('Longitude degrees must be in range [-180; 180].'); + } + return degreesToRadians(degrees); +} +function geodeticToEcf(_ref) { + var longitude = _ref.longitude, + latitude = _ref.latitude, + height = _ref.height; + var a = 6378.137; + var b = 6356.7523142; + var f = (a - b) / a; + var e2 = 2 * f - f * f; + var normal = a / Math.sqrt(1 - e2 * (Math.sin(latitude) * Math.sin(latitude))); + var x = (normal + height) * Math.cos(latitude) * Math.cos(longitude); + var y = (normal + height) * Math.cos(latitude) * Math.sin(longitude); + var z = (normal * (1 - e2) + height) * Math.sin(latitude); + return { + x: x, + y: y, + z: z + }; +} +function eciToGeodetic(eci, gmst) { + // http://www.celestrak.com/columns/v02n03/ + var a = 6378.137; + var b = 6356.7523142; + var R = Math.sqrt(eci.x * eci.x + eci.y * eci.y); + var f = (a - b) / a; + var e2 = 2 * f - f * f; + var longitude = Math.atan2(eci.y, eci.x) - gmst; + while (longitude < -_constants.pi) { + longitude += _constants.twoPi; + } + while (longitude > _constants.pi) { + longitude -= _constants.twoPi; + } + var kmax = 20; + var k = 0; + var latitude = Math.atan2(eci.z, Math.sqrt(eci.x * eci.x + eci.y * eci.y)); + var C; + while (k++ < kmax) { + C = 1 / Math.sqrt(1 - e2 * (Math.sin(latitude) * Math.sin(latitude))); + latitude = Math.atan2(eci.z + a * C * e2 * Math.sin(latitude), R); + } + var height = R / Math.cos(latitude) - a * C; + return { + longitude: longitude, + latitude: latitude, + height: height + }; +} +function ecfToEci(ecf, gmst) { + // ccar.colorado.edu/ASEN5070/handouts/coordsys.doc + // + // [X] [C -S 0][X] + // [Y] = [S C 0][Y] + // [Z]eci [0 0 1][Z]ecf + // + var X = ecf.x * Math.cos(gmst) - ecf.y * Math.sin(gmst); + var Y = ecf.x * Math.sin(gmst) + ecf.y * Math.cos(gmst); + var Z = ecf.z; + return { + x: X, + y: Y, + z: Z + }; +} +function eciToEcf(eci, gmst) { + // ccar.colorado.edu/ASEN5070/handouts/coordsys.doc + // + // [X] [C -S 0][X] + // [Y] = [S C 0][Y] + // [Z]eci [0 0 1][Z]ecf + // + // + // Inverse: + // [X] [C S 0][X] + // [Y] = [-S C 0][Y] + // [Z]ecf [0 0 1][Z]eci + var x = eci.x * Math.cos(gmst) + eci.y * Math.sin(gmst); + var y = eci.x * -Math.sin(gmst) + eci.y * Math.cos(gmst); + var z = eci.z; + return { + x: x, + y: y, + z: z + }; +} +function topocentric(observerGeodetic, satelliteEcf) { + // http://www.celestrak.com/columns/v02n02/ + // TS Kelso's method, except I'm using ECF frame + // and he uses ECI. + var longitude = observerGeodetic.longitude, + latitude = observerGeodetic.latitude; + var observerEcf = geodeticToEcf(observerGeodetic); + var rx = satelliteEcf.x - observerEcf.x; + var ry = satelliteEcf.y - observerEcf.y; + var rz = satelliteEcf.z - observerEcf.z; + var topS = Math.sin(latitude) * Math.cos(longitude) * rx + Math.sin(latitude) * Math.sin(longitude) * ry - Math.cos(latitude) * rz; + var topE = -Math.sin(longitude) * rx + Math.cos(longitude) * ry; + var topZ = Math.cos(latitude) * Math.cos(longitude) * rx + Math.cos(latitude) * Math.sin(longitude) * ry + Math.sin(latitude) * rz; + return { + topS: topS, + topE: topE, + topZ: topZ + }; +} +function topocentricToLookAngles(tc) { + var topS = tc.topS, + topE = tc.topE, + topZ = tc.topZ; + var rangeSat = Math.sqrt(topS * topS + topE * topE + topZ * topZ); + var El = Math.asin(topZ / rangeSat); + var Az = Math.atan2(-topE, topS) + _constants.pi; + return { + azimuth: Az, + elevation: El, + rangeSat: rangeSat // Range in km + }; +} +function ecfToLookAngles(observerGeodetic, satelliteEcf) { + var topocentricCoords = topocentric(observerGeodetic, satelliteEcf); + return topocentricToLookAngles(topocentricCoords); +} \ No newline at end of file diff --git a/node_modules/satellite.js/package.json b/node_modules/satellite.js/package.json new file mode 100644 index 0000000..087066e --- /dev/null +++ b/node_modules/satellite.js/package.json @@ -0,0 +1,83 @@ +{ + "name": "satellite.js", + "version": "6.0.2", + "description": "SGP4/SDP4 calculation library", + "main": "lib/index.js", + "jsnext:main": "dist/satellite.es.js", + "types": "types/index.d.ts", + "module": "dist/satellite.es.js", + "scripts": { + "build": "rimraf lib dist compiled types && tsc && npm run transpile && npm run dist", + "transpile": "babel compiled --out-dir lib --ignore indexUmd.js", + "dist": "npm run dist:es && npm run dist:umd:dev && npm run dist:umd:prod", + "dist:es": "rollup --bundleConfigAsCjs --config rollup.config.es.js", + "dist:umd": "rollup --bundleConfigAsCjs --config rollup.config.js", + "dist:umd:dev": "cross-env NODE_ENV=development npm run dist:umd", + "dist:umd:prod": "cross-env NODE_ENV=production npm run dist:umd", + "watch:es": "node --require @babel/register rollup.watch.es.js", + "copy": "copyfiles -u 1 'dist/**/*' sgp4_verification/lib/sgp4", + "lint": "eslint src", + "lint:test": "eslint test", + "test": "jest", + "test:coverage": "jest --coverage", + "raise": "raise-version" + }, + "repository": { + "type": "git", + "url": "git://github.com/shashwatak/satellite-js" + }, + "keywords": [ + "sgp4", + "sdp4", + "satellite", + "TLE", + "two-line elements", + "OMM", + "sgp4prop" + ], + "author": "Shashwat Kandadai (https://github.com/shashwatak)", + "contributors": [ + "Dmitriy Pushkov (http://www.ezze.org)" + ], + "license": "MIT", + "bugs": { + "url": "https://github.com/shashwatak/satellite-js/issues" + }, + "devDependencies": { + "@babel/cli": "^7.20.7", + "@babel/core": "^7.20.12", + "@babel/plugin-proposal-class-properties": "^7.18.6", + "@babel/plugin-proposal-json-strings": "^7.18.6", + "@babel/plugin-syntax-dynamic-import": "^7.8.3", + "@babel/plugin-syntax-import-meta": "^7.10.4", + "@babel/preset-env": "^7.20.2", + "@babel/register": "^7.18.9", + "@eslint/js": "^9.22.0", + "@rollup/plugin-babel": "^6.0.3", + "@rollup/plugin-terser": "^0.2.1", + "chokidar": "^3.5.3", + "copyfiles": "^2.4.1", + "cross-env": "^7.0.3", + "eslint": "^9.22.0", + "eslint-plugin-import": "^2.26.0", + "glob": "^8.0.3", + "jest": "^29.7.0", + "prepend-file": "^2.0.1", + "raise-version": "^0.5.0", + "rimraf": "^3.0.2", + "rollup": "^3.9.1", + "typescript": "^5.8.2", + "typescript-eslint": "^8.26.1" + }, + "jest": { + "testPathIgnorePatterns": [ + "node_modules", + "test/propagation/sgp4Catalog.test.js" + ] + }, + "homepage": "https://github.com/shashwatak/satellite-js", + "directories": { + "lib": "lib", + "test": "test" + } +} diff --git a/node_modules/satellite.js/satellite.js-6.0.2.tgz b/node_modules/satellite.js/satellite.js-6.0.2.tgz new file mode 100644 index 0000000..ac9d126 Binary files /dev/null and b/node_modules/satellite.js/satellite.js-6.0.2.tgz differ diff --git a/node_modules/satellite.js/tsconfig.json b/node_modules/satellite.js/tsconfig.json new file mode 100644 index 0000000..4cab011 --- /dev/null +++ b/node_modules/satellite.js/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "target": "ES6", + "strict": true, + "allowUnusedLabels": false, + "allowUnreachableCode": false, + "exactOptionalPropertyTypes": true, + "noFallthroughCasesInSwitch": true, + "noImplicitOverride": true, + "noImplicitReturns": true, + "noPropertyAccessFromIndexSignature": true, + "noUncheckedIndexedAccess": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "isolatedModules": true, + "esModuleInterop": true, + "skipLibCheck": true, + "declaration": true, + "declarationDir": "./types", + "outDir": "./compiled", + }, + "$schema": "https://json.schemastore.org/tsconfig", + "display": "Strictest (minus esModuleInterop)", + "include": [ + "src/**.ts", + ], +} diff --git a/node_modules/satellite.js/types/common-types.d.ts b/node_modules/satellite.js/types/common-types.d.ts new file mode 100644 index 0000000..9a359dd --- /dev/null +++ b/node_modules/satellite.js/types/common-types.d.ts @@ -0,0 +1,215 @@ +/** + * Type alias documents units are kilometer (km) + */ +export type Kilometer = number; +/** + * Type alias documents units are kilometer per second (km/s) + */ +export type KilometerPerSecond = number; +/** + * Type alias documents units are radians + */ +export type Radians = number; +/** + * Type alias documents units are degrees + */ +export type Degrees = number; +/** + * Type alias documents units for mean motion are radians per minute + */ +export type RadiansPerMinute = number; +/** + * Type alias documents units for semi-major axis (earth radii) + */ +export type EarthRadii = number; +/** + * Coordinate frame Earth Centered Inertial (ECI) + * https://en.wikipedia.org/wiki/Earth-centered_inertial + */ +export interface EciVec3 { + x: T; + y: T; + z: T; +} +/** + * Coordinate frame Earth Centered Fixed (ECF) + * https://en.wikipedia.org/wiki/ECEF + */ +export interface EcfVec3 { + x: T; + y: T; + z: T; +} +/** + * A set of "singly averaged mean elements" that describe shape of the + * satellite’s orbit at the propagation date. They are averaged + * with respect to the mean anomaly and include the effects of secular + * gravity, atmospheric drag, and - in Deep Space mode - of those + * pertubations from the Sun and Moon that SGP4 averages over an entire + * revolution of each of those bodies. They omit both the shorter-term + * and longer-term periodic pertubations from the Sun and Moon that + * SGP4 applies right before computing each position. + */ +export interface MeanElements { + /** + * Average semi-major axis (earth radii). + */ + am: EarthRadii; + /** + * Average eccentricity. + */ + em: number; + /** + * Average inclination (radians). + */ + im: Radians; + /** + * Average right ascension of ascending node (radians). + */ + Om: Radians; + /** + * Average argument of perigee (radians). + */ + om: Radians; + /** + * Average mean anomaly (radians). + */ + mm: Radians; + /** + * Average mean motion (radians/minute). + */ + nm: RadiansPerMinute; +} +/** + * The position_velocity result is a key-value pair of ECI coordinates. + * These are the base results from which all other coordinates are derived. + * If there is an error the position and velocity will be false. + * The meanElements are the averaged elements of the orbit at the + * moment of propagation. + */ +export interface PositionAndVelocity { + position: EciVec3; + velocity: EciVec3; + meanElements: MeanElements; +} +/** + * https://en.wikipedia.org/wiki/Geographic_coordinate_system#Latitude_and_longitude + */ +export interface GeodeticLocation { + longitude: Radians; + latitude: Radians; + height: Kilometer; +} +/** + * You will need GMST for some of the coordinate transforms. + * GMST - Greenwich Mean Sidereal Time + * http://en.wikipedia.org/wiki/Sidereal_time#Definition + */ +export type GMSTime = number; +/** + * https://en.wikipedia.org/wiki/Azimuth + */ +export interface LookAngles { + azimuth: Radians; + elevation: Radians; + rangeSat: Kilometer; +} +type StartsWith = `${T}${string}`; +/** + * This is the base interface for the OMM JSON object as specified in Orbit Data Messages + * recommended standard, version 3.0. + * + * Note that this is not a 1:1 mapping. Only the fields that are necessary to propagate + * a satellite orbit are made required. For example, CCSDS_OMM_VERS is required by the spec, + * but is not present in Celestrak OMM output, and is not required to propagate the satellite, + * so it is made optional here. + * + * Numeric fields may be represented as strings or numbers in the original json, depending on + * the source. This is because the spec doesn't specify the type, and different sources use + * different types: at the time of writing, Celestrak uses numbers, while SpaceTrack uses strings. + */ +export interface OMMJsonObjectV3 { + /** + * The version is restricted in TypeScript to only among the ones this library supports. + * Versions are incremented on breaking changes, so it is adviced you validate this field. + * + * NOTE: This is required field in OMM spec, but Celestrak omits it, so we make it optional + * and assume version 3.0 if not present. + */ + CCSDS_OMM_VERS?: StartsWith<'3.'>; + COMMENT?: string; + CLASSIFICATION?: string; + OBJECT_NAME: string; + /** + * Recommended, but not required, to be an International spacecraft designator. + */ + OBJECT_ID: string; + /** + * NOTE: This is required field in OMM spec, but Celestrak omits it, so we make it optional. + * If present, it is restricted to only the value this library supports. + */ + CENTER_NAME?: 'EARTH'; + /** + * NOTE: This is required field in OMM spec, but Celestrak omits it, so we make it optional. + * If present, it is restricted to only 'TEME' as it is the only value that can come with + * SGP ephemeris type. + */ + REF_FRAME?: 'TEME'; + /** + * NOTE: This is required field in OMM spec, but Celestrak omits it, so we make it optional + */ + REF_FRAME_EPOCH?: string; + /** + * NOTE: This is required field in OMM spec, but Celestrak omits it, so we make it optional + */ + TIME_SYSTEM?: 'UTC'; + /** + * NOTE: This is required field in OMM spec, but Celestrak omits it, so we make it optional + */ + MEAN_ELEMENT_THEORY?: 'SGP4'; + /** + * NOTE: This is required field in OMM spec, but Celestrak omits it, so we make it optional + */ + CREATION_DATE?: string; + /** + * NOTE: This is required field in OMM spec, but Celestrak omits it, so we make it optional + */ + ORIGINATOR?: string; + /** + * ISO datetime + */ + EPOCH: string; + MEAN_MOTION: string | number; + ECCENTRICITY: string | number; + /** + * Degrees + */ + INCLINATION: number | string; + RA_OF_ASC_NODE: number | string; + /** + * Degrees + */ + ARG_OF_PERICENTER: number | string; + /** + * Degrees + */ + MEAN_ANOMALY: number | string; + /** + * The only value supported by this library + */ + EPHEMERIS_TYPE?: 0 | "0"; + CLASSIFICATION_TYPE?: "U" | "C"; + NORAD_CAT_ID: string | number; + ELEMENT_SET_NO: string | number; + REV_AT_EPOCH?: string | number; + BSTAR: string | number; + MEAN_MOTION_DOT: string | number; + MEAN_MOTION_DDOT: string | number; + /** + * This handles additional metadata, such as OBJECT_TYPE, COUNTRY_CODE etc + */ + [key: string]: unknown; +} +export type OMMJsonObject = OMMJsonObjectV3; +export type SupportedOMMVersion = NonNullable; +export {}; diff --git a/node_modules/satellite.js/types/constants.d.ts b/node_modules/satellite.js/types/constants.d.ts new file mode 100644 index 0000000..59491fd --- /dev/null +++ b/node_modules/satellite.js/types/constants.d.ts @@ -0,0 +1,16 @@ +export declare const pi: number; +export declare const twoPi: number; +export declare const deg2rad: number; +export declare const rad2deg: number; +export declare const minutesPerDay = 1440; +export declare const mu = 398600.8; +export declare const earthRadius = 6378.135; +export declare const xke: number; +export declare const vkmpersec: number; +export declare const tumin: number; +export declare const j2 = 0.001082616; +export declare const j3 = -0.00000253881; +export declare const j4 = -0.00000165597; +export declare const j3oj2: number; +export declare const x2o3: number; +export declare const xpdotp: number; diff --git a/node_modules/satellite.js/types/dopplerFactor.d.ts b/node_modules/satellite.js/types/dopplerFactor.d.ts new file mode 100644 index 0000000..89feddc --- /dev/null +++ b/node_modules/satellite.js/types/dopplerFactor.d.ts @@ -0,0 +1,8 @@ +import { EcfVec3, Kilometer, KilometerPerSecond } from './common-types.js'; +/** + * Negative range rate means the satellite is moving towards the observer and + * its frequency is shifted higher because 1 minus a negative range rate is + * positive. If the range rate is positive, the satellite is moving away from + * the observer and its frequency is shifted lower. + */ +export default function dopplerFactor(observerCoordsEcf: EcfVec3, positionEcf: EcfVec3, velocityEcf: EcfVec3): number; diff --git a/node_modules/satellite.js/types/ext.d.ts b/node_modules/satellite.js/types/ext.d.ts new file mode 100644 index 0000000..f959f76 --- /dev/null +++ b/node_modules/satellite.js/types/ext.d.ts @@ -0,0 +1,12 @@ +export type JDay = number; +export declare function days2mdhms(year: number, days: number): { + mon: number; + day: number; + hr: number; + minute: number; + sec: number; +}; +export declare function jday(year: Date): JDay; +export declare function jday(year: number, mon: number, day: number, hr: number, minute: number, sec: number, msec?: number): JDay; +export declare function invjday(jd: JDay, asArray: true): [year: number, mon: number, day: number, hr: number, minute: number, sec: number]; +export declare function invjday(jd: JDay, asArray?: false): Date; diff --git a/node_modules/satellite.js/types/index.d.ts b/node_modules/satellite.js/types/index.d.ts new file mode 100644 index 0000000..94a36ca --- /dev/null +++ b/node_modules/satellite.js/types/index.d.ts @@ -0,0 +1,9 @@ +export * as constants from './constants'; +export { jday, invjday } from './ext'; +export { twoline2satrec, json2satrec } from './io'; +export { propagate, sgp4, gstime } from './propagation'; +export { default as dopplerFactor } from './dopplerFactor'; +export { radiansToDegrees, degreesToRadians, degreesLat, degreesLong, radiansLat, radiansLong, geodeticToEcf, eciToGeodetic, eciToEcf, ecfToEci, ecfToLookAngles, } from './transforms'; +export { sunPos } from './sun'; +export { type SatRec, SatRecError } from './propagation/SatRec.js'; +export * from './common-types.js'; diff --git a/node_modules/satellite.js/types/indexUmd.d.ts b/node_modules/satellite.js/types/indexUmd.d.ts new file mode 100644 index 0000000..f106112 --- /dev/null +++ b/node_modules/satellite.js/types/indexUmd.d.ts @@ -0,0 +1,33 @@ +import * as constants from './constants'; +import { jday, invjday } from './ext'; +import { twoline2satrec, json2satrec } from './io'; +import { propagate, sgp4, gstime } from './propagation'; +import { SatRecError } from './propagation/SatRec.js'; +import dopplerFactor from './dopplerFactor'; +import { radiansToDegrees, degreesToRadians, degreesLat, degreesLong, radiansLat, radiansLong, geodeticToEcf, eciToGeodetic, eciToEcf, ecfToEci, ecfToLookAngles } from './transforms'; +import { sunPos } from './sun'; +declare const _default: { + SatRecError: typeof SatRecError; + constants: typeof constants; + propagate: typeof propagate; + sgp4: typeof sgp4; + twoline2satrec: typeof twoline2satrec; + json2satrec: typeof json2satrec; + gstime: typeof gstime; + jday: typeof jday; + invjday: typeof invjday; + dopplerFactor: typeof dopplerFactor; + radiansToDegrees: typeof radiansToDegrees; + degreesToRadians: typeof degreesToRadians; + degreesLat: typeof degreesLat; + degreesLong: typeof degreesLong; + radiansLat: typeof radiansLat; + radiansLong: typeof radiansLong; + geodeticToEcf: typeof geodeticToEcf; + eciToGeodetic: typeof eciToGeodetic; + eciToEcf: typeof eciToEcf; + ecfToEci: typeof ecfToEci; + ecfToLookAngles: typeof ecfToLookAngles; + sunPos: typeof sunPos; +}; +export default _default; diff --git a/node_modules/satellite.js/types/io.d.ts b/node_modules/satellite.js/types/io.d.ts new file mode 100644 index 0000000..91f4ac1 --- /dev/null +++ b/node_modules/satellite.js/types/io.d.ts @@ -0,0 +1,18 @@ +import { OMMJsonObject } from './common-types.js'; +/** + * Return a Satellite imported from two lines of TLE data. + * + * Provide the two TLE lines as strings `tleLine1` and `tleLine2`, + * and select which standard set of gravitational constants you want + * by providing `gravity_constants`: + * + * `sgp4.propagation.wgs72` - Standard WGS 72 model + * `sgp4.propagation.wgs84` - More recent WGS 84 model + * `sgp4.propagation.wgs72old` - Legacy support for old SGP4 behavior + * + * Normally, computations are made using letious recent improvements + * to the algorithm. If you want to turn some of these off and go + * back into "afspc" mode, then set `afspc_mode` to `True`. + */ +export declare function twoline2satrec(longstr1: string, longstr2: string): import("./propagation/SatRec.js").SatRec; +export declare function json2satrec(jsonobj: OMMJsonObject, opsmode?: 'a' | 'i'): import("./propagation/SatRec.js").SatRec; diff --git a/node_modules/satellite.js/types/propagation.d.ts b/node_modules/satellite.js/types/propagation.d.ts new file mode 100644 index 0000000..7611df1 --- /dev/null +++ b/node_modules/satellite.js/types/propagation.d.ts @@ -0,0 +1,3 @@ +export { default as propagate } from './propagation/propagate'; +export { default as sgp4 } from './propagation/sgp4'; +export { default as gstime } from './propagation/gstime'; diff --git a/node_modules/satellite.js/types/propagation/SatRec.d.ts b/node_modules/satellite.js/types/propagation/SatRec.d.ts new file mode 100644 index 0000000..11dfa7b --- /dev/null +++ b/node_modules/satellite.js/types/propagation/SatRec.d.ts @@ -0,0 +1,196 @@ +export declare enum SatRecError { + /** + * No error, propagation for the last supplied date is successful + */ + None = 0, + /** + * Mean eccentricity is out of range 0 ≤ e < 1 + */ + MeanEccentricityOutOfRange = 1, + /** + * Mean motion has fallen below zero. + */ + MeanMotionBelowZero = 2, + /** + * Perturbed eccentricity is out of range 0 ≤ e < 1 + */ + PerturbedEccentricityOutOfRange = 3, + /** + * Length of the orbit’s semi-latus rectum has fallen below zero. + */ + SemiLatusRectumBelowZero = 4, + /** + * Orbit has decayed: the computed position is underground. + */ + Decayed = 6 +} +/** + * A structure that contains all the information needed to propagate a satellite's orbit using the SGP4 model. + * + * Mostly you can consider it opaque as you only need to pass it to `propagate` function. + * All properties should be considered read-only as they're used and set by SGP4 model internally. + * + * This interface is a direct translation of C++ struct `elsetrec` from the source code by David Vallado; + * all changes to the original struct are documented. + */ +export interface SatRec { + /** + * Stringified satellite number, usually from NORAD catalog + */ + satnum: string; + /** + * Full four-digit year of this element set's epoch moment + */ + epochyr: number; + epochtynumrev: number; + /** + * Error code produced by the most recent SGP4 propagation you performed with this element set. + */ + error: SatRecError; + /** + * A single character that directs SGP4 to either operate in its modern 'i' improved mode or + * in its legacy 'a' AFSPC mode. + */ + operationmode: 'a' | 'i'; + init: 'y' | 'n'; + /** + * A single character, chosen automatically when the orbital elements were loaded, that + * indicates whether SGP4 has chosen to use its built-in 'n' Near Earth or 'd' Deep Space + * mode for this satellite. + */ + method: 'n' | 'd'; + isimp: number; + aycof: number; + con41: number; + cc1: number; + cc4: number; + cc5: number; + d2: number; + d3: number; + d4: number; + delmo: number; + eta: number; + argpdot: number; + omgcof: number; + sinmao: number; + /** + * The time you gave when you most recently asked SGP4 to compute this satellite’s position, + * measured in minutes before (negative) or after (positive) the satellite’s epoch. + */ + t: number; + t2cof: number; + t3cof: number; + t4cof: number; + t5cof: number; + x1mth2: number; + x7thm1: number; + mdot: number; + nodedot: number; + xlcof: number; + xmcof: number; + nodecf: number; + irez: number; + d2201: number; + d2211: number; + d3210: number; + d3222: number; + d4410: number; + d4422: number; + d5220: number; + d5232: number; + d5421: number; + d5433: number; + dedt: number; + del1: number; + del2: number; + del3: number; + didt: number; + dmdt: number; + dnodt: number; + domdt: number; + e3: number; + ee2: number; + peo: number; + pgho: number; + pho: number; + pinco: number; + plo: number; + se2: number; + se3: number; + sgh2: number; + sgh3: number; + sgh4: number; + sh2: number; + sh3: number; + si2: number; + si3: number; + sl2: number; + sl3: number; + sl4: number; + gsto: number; + xfact: number; + xgh2: number; + xgh3: number; + xgh4: number; + xh2: number; + xh3: number; + xi2: number; + xi3: number; + xl2: number; + xl3: number; + xl4: number; + xlamo: number; + zmol: number; + zmos: number; + atime: number; + xli: number; + xni: number; + a: number; + altp: number; + alta: number; + /** + * Fractional days into the year of the epoch moment in UTC. + */ + epochdays: number; + /** + * Julian date of the epoch (computed from epochyr and epochdays). + */ + jdsatepoch: number; + /** + * Second time derivative of the mean motion (ignored by SGP4). + */ + nddot: number; + /** + * First time derivative of the mean motion (ignored by SGP4). + */ + ndot: number; + /** + * Ballistic drag coefficient B* in inverse earth radii. + */ + bstar: number; + /** + * Inclination in radians. + */ + inclo: number; + /** + * Right ascension of ascending node in radians. + */ + nodeo: number; + /** + * Eccentricity. + */ + ecco: number; + /** + * Argument of perigee in radians. + */ + argpo: number; + /** + * Mean anomaly in radians. + */ + mo: number; + /** + * Mean motion in radians per minute. + */ + no: number; +} +export type SatRecInit = Pick; diff --git a/node_modules/satellite.js/types/propagation/dpper.d.ts b/node_modules/satellite.js/types/propagation/dpper.d.ts new file mode 100644 index 0000000..6dc72fd --- /dev/null +++ b/node_modules/satellite.js/types/propagation/dpper.d.ts @@ -0,0 +1,18 @@ +import { SatRec } from './SatRec.js'; +interface DpperOptions { + init: 'y' | 'n'; + opsmode: 'a' | 'i'; + ep: number; + inclp: number; + nodep: number; + argpp: number; + mp: number; +} +export default function dpper(satrec: SatRec, options: DpperOptions): { + ep: number; + inclp: number; + nodep: number; + argpp: number; + mp: number; +}; +export {}; diff --git a/node_modules/satellite.js/types/propagation/dscom.d.ts b/node_modules/satellite.js/types/propagation/dscom.d.ts new file mode 100644 index 0000000..8f2407c --- /dev/null +++ b/node_modules/satellite.js/types/propagation/dscom.d.ts @@ -0,0 +1,93 @@ +interface DscomOptions { + epoch: number; + ep: number; + argpp: number; + tc: number; + inclp: number; + nodep: number; + np: number; +} +export default function dscom(options: DscomOptions): { + snodm: number; + cnodm: number; + sinim: number; + cosim: number; + sinomm: number; + cosomm: number; + day: number; + e3: number; + ee2: number; + em: number; + emsq: number; + gam: number; + peo: number; + pgho: number; + pho: number; + pinco: number; + plo: number; + rtemsq: number; + se2: number; + se3: number; + sgh2: number; + sgh3: number; + sgh4: number; + sh2: number; + sh3: number; + si2: number; + si3: number; + sl2: number; + sl3: number; + sl4: number; + s1: number | undefined; + s2: number | undefined; + s3: number | undefined; + s4: number | undefined; + s5: number | undefined; + s6: number | undefined; + s7: number | undefined; + ss1: number | undefined; + ss2: number | undefined; + ss3: number | undefined; + ss4: number | undefined; + ss5: number | undefined; + ss6: number | undefined; + ss7: number | undefined; + sz1: number | undefined; + sz2: number | undefined; + sz3: number | undefined; + sz11: number | undefined; + sz12: number | undefined; + sz13: number | undefined; + sz21: number | undefined; + sz22: number | undefined; + sz23: number | undefined; + sz31: number | undefined; + sz32: number | undefined; + sz33: number | undefined; + xgh2: number; + xgh3: number; + xgh4: number; + xh2: number; + xh3: number; + xi2: number; + xi3: number; + xl2: number; + xl3: number; + xl4: number; + nm: number; + z1: number | undefined; + z2: number | undefined; + z3: number | undefined; + z11: number | undefined; + z12: number | undefined; + z13: number | undefined; + z21: number | undefined; + z22: number | undefined; + z23: number | undefined; + z31: number | undefined; + z32: number | undefined; + z33: number | undefined; + zmol: number; + zmos: number; +}; +export {}; diff --git a/node_modules/satellite.js/types/propagation/dsinit.d.ts b/node_modules/satellite.js/types/propagation/dsinit.d.ts new file mode 100644 index 0000000..8c307dd --- /dev/null +++ b/node_modules/satellite.js/types/propagation/dsinit.d.ts @@ -0,0 +1,107 @@ +interface DsinitOptions { + cosim: number; + emsq: number; + argpo: number; + s1: number; + s2: number; + s3: number; + s4: number; + s5: number; + sinim: number; + ss1: number; + ss2: number; + ss3: number; + ss4: number; + ss5: number; + sz1: number; + sz3: number; + sz11: number; + sz13: number; + sz21: number; + sz23: number; + sz31: number; + sz33: number; + t: number; + tc: number; + gsto: number; + mo: number; + mdot: number; + no: number; + nodeo: number; + nodedot: number; + xpidot: number; + z1: number; + z3: number; + z11: number; + z13: number; + z21: number; + z23: number; + z31: number; + z33: number; + ecco: number; + eccsq: number; + em: number; + argpm: number; + inclm: number; + mm: number; + nm: number; + nodem: number; + irez: number; + atime: number; + d2201: number; + d2211: number; + d3210: number; + d3222: number; + d4410: number; + d4422: number; + d5220: number; + d5232: number; + d5421: number; + d5433: number; + dedt: number; + didt: number; + dmdt: number; + dnodt: number; + domdt: number; + del1: number; + del2: number; + del3: number; + xfact: number; + xlamo: number; + xli: number; + xni: number; +} +export default function dsinit(options: DsinitOptions): { + em: number; + argpm: number; + inclm: number; + mm: number; + nm: number; + nodem: number; + irez: number; + atime: number; + d2201: number; + d2211: number; + d3210: number; + d3222: number; + d4410: number; + d4422: number; + d5220: number; + d5232: number; + d5421: number; + d5433: number; + dedt: number; + didt: number; + dmdt: number; + dndt: number; + dnodt: number; + domdt: number; + del1: number; + del2: number; + del3: number; + xfact: number; + xlamo: number; + xli: number; + xni: number; +}; +export {}; diff --git a/node_modules/satellite.js/types/propagation/dspace.d.ts b/node_modules/satellite.js/types/propagation/dspace.d.ts new file mode 100644 index 0000000..b937dbd --- /dev/null +++ b/node_modules/satellite.js/types/propagation/dspace.d.ts @@ -0,0 +1,51 @@ +interface DspaceOptions { + irez: number; + d2201: number; + d2211: number; + d3210: number; + d3222: number; + d4410: number; + d4422: number; + d5220: number; + d5232: number; + d5421: number; + d5433: number; + dedt: number; + del1: number; + del2: number; + del3: number; + didt: number; + dmdt: number; + dnodt: number; + domdt: number; + argpo: number; + argpdot: number; + t: number; + tc: number; + gsto: number; + xfact: number; + xlamo: number; + no: number; + atime: number; + em: number; + argpm: number; + inclm: number; + xli: number; + mm: number; + xni: number; + nodem: number; + nm: number; +} +export default function dspace(options: DspaceOptions): { + atime: number; + em: number; + argpm: number; + inclm: number; + xli: number; + mm: number; + xni: number; + nodem: number; + dndt: number; + nm: number; +}; +export {}; diff --git a/node_modules/satellite.js/types/propagation/gstime.d.ts b/node_modules/satellite.js/types/propagation/gstime.d.ts new file mode 100644 index 0000000..406e979 --- /dev/null +++ b/node_modules/satellite.js/types/propagation/gstime.d.ts @@ -0,0 +1,5 @@ +import { GMSTime } from '../common-types.js'; +declare function gstime(jd: number): GMSTime; +declare function gstime(date: Date): GMSTime; +declare function gstime(year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond?: number): GMSTime; +export default gstime; diff --git a/node_modules/satellite.js/types/propagation/initl.d.ts b/node_modules/satellite.js/types/propagation/initl.d.ts new file mode 100644 index 0000000..a6c7581 --- /dev/null +++ b/node_modules/satellite.js/types/propagation/initl.d.ts @@ -0,0 +1,25 @@ +interface InitlOptions { + opsmode: 'a' | 'i'; + ecco: number; + epoch: number; + inclo: number; + no: number; +} +export default function initl(options: InitlOptions): { + no: number; + method: string; + ainv: number; + ao: number; + con41: number; + con42: number; + cosio: number; + cosio2: number; + eccsq: number; + omeosq: number; + posq: number; + rp: number; + rteosq: number; + sinio: number; + gsto: number; +}; +export {}; diff --git a/node_modules/satellite.js/types/propagation/propagate.d.ts b/node_modules/satellite.js/types/propagation/propagate.d.ts new file mode 100644 index 0000000..38f5bbf --- /dev/null +++ b/node_modules/satellite.js/types/propagation/propagate.d.ts @@ -0,0 +1,5 @@ +import { PositionAndVelocity } from '../common-types.js'; +import { SatRec } from './SatRec.js'; +export declare function propagate(satrec: SatRec, date: Date): PositionAndVelocity; +export declare function propagate(satrec: SatRec, year: number, month: number, day: number, hour: number, minute: number, second: number, ms?: number): PositionAndVelocity; +export default function propagate(satrec: SatRec, ...jdayArgs: [Date] | [number, number, number, number, number, number, (number | undefined)?]): PositionAndVelocity | null; diff --git a/node_modules/satellite.js/types/propagation/sgp4.d.ts b/node_modules/satellite.js/types/propagation/sgp4.d.ts new file mode 100644 index 0000000..2fbd393 --- /dev/null +++ b/node_modules/satellite.js/types/propagation/sgp4.d.ts @@ -0,0 +1,3 @@ +import { PositionAndVelocity } from '../common-types.js'; +import { SatRec } from './SatRec.js'; +export default function sgp4(satrec: SatRec, tsince: number): PositionAndVelocity | null; diff --git a/node_modules/satellite.js/types/propagation/sgp4init.d.ts b/node_modules/satellite.js/types/propagation/sgp4init.d.ts new file mode 100644 index 0000000..91d1b03 --- /dev/null +++ b/node_modules/satellite.js/types/propagation/sgp4init.d.ts @@ -0,0 +1,14 @@ +import { SatRec, SatRecInit } from './SatRec.js'; +export interface Sgp4InitOptions { + opsmode: 'a' | 'i'; + satn: string; + epoch: number; + xbstar: number; + xecco: number; + xargpo: number; + xinclo: number; + xmo: number; + xno: number; + xnodeo: number; +} +export default function sgp4init(satrecInit: SatRecInit, options: Sgp4InitOptions): asserts satrecInit is SatRec; diff --git a/node_modules/satellite.js/types/sun.d.ts b/node_modules/satellite.js/types/sun.d.ts new file mode 100644 index 0000000..033e686 --- /dev/null +++ b/node_modules/satellite.js/types/sun.d.ts @@ -0,0 +1,6 @@ +import { JDay } from './ext.js'; +export declare function sunPos(jday: JDay): { + rsun: number[]; + rtasc: number; + decl: number; +}; diff --git a/node_modules/satellite.js/types/transforms.d.ts b/node_modules/satellite.js/types/transforms.d.ts new file mode 100644 index 0000000..5b50ff2 --- /dev/null +++ b/node_modules/satellite.js/types/transforms.d.ts @@ -0,0 +1,12 @@ +import { Degrees, EcfVec3, EciVec3, GeodeticLocation, GMSTime, Kilometer, LookAngles, Radians } from './common-types.js'; +export declare function radiansToDegrees(radians: Radians): Degrees; +export declare function degreesToRadians(degrees: Degrees): Radians; +export declare function degreesLat(radians: Radians): Degrees; +export declare function degreesLong(radians: Radians): Degrees; +export declare function radiansLat(degrees: Degrees): Radians; +export declare function radiansLong(degrees: Degrees): Radians; +export declare function geodeticToEcf({ longitude, latitude, height, }: GeodeticLocation): EcfVec3; +export declare function eciToGeodetic(eci: EciVec3, gmst: GMSTime): GeodeticLocation; +export declare function ecfToEci(ecf: EcfVec3, gmst: GMSTime): EciVec3; +export declare function eciToEcf(eci: EciVec3, gmst: GMSTime): EcfVec3; +export declare function ecfToLookAngles(observerGeodetic: GeodeticLocation, satelliteEcf: EcfVec3): LookAngles; diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..ff6e101 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,36 @@ +{ + "name": "eye-spy", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "eye-spy", + "dependencies": { + "astronomy-engine": "^2.1.19", + "geomagnetism": "^0.2.0", + "satellite.js": "^6.0.1" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/astronomy-engine": { + "version": "2.1.19", + "resolved": "https://registry.npmjs.org/astronomy-engine/-/astronomy-engine-2.1.19.tgz", + "integrity": "sha512-8yWKNf7UeNbH458h3sAJ6ZgAjE5jTXp/mNNRFoC20j2SHwZIjAQeEsBB2Q3uCFRaTCCJRv33K2XhkhZQMXoX6w==", + "license": "MIT" + }, + "node_modules/geomagnetism": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/geomagnetism/-/geomagnetism-0.2.0.tgz", + "integrity": "sha512-dO8HJrXqah244nMe+pU5m52L90SMoi4lDA0AV3xunRxogloYV+s3aYWCW72VMMfiYis+YSAlhoKktw8aLMiJbw==", + "license": "Apache-2.0" + }, + "node_modules/satellite.js": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/satellite.js/-/satellite.js-6.0.2.tgz", + "integrity": "sha512-XWKxtqVF5xiJ1xAeiYeT/oSSzsukoCLWvk6nO/WFy4un0M3g4djAU9TAtOCqJLtYW9vxx9pkPJ1L9ITOc607GA==", + "license": "MIT" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..6cd61b1 --- /dev/null +++ b/package.json @@ -0,0 +1,12 @@ +{ + "name": "eye-spy", + "private": true, + "type": "module", + "scripts": { "start": "node server.mjs" }, + "engines": { "node": ">=20" }, + "dependencies": { + "astronomy-engine": "^2.1.19", + "geomagnetism": "^0.2.0", + "satellite.js": "^6.0.1" + } +} diff --git a/server.mjs b/server.mjs new file mode 100644 index 0000000..c84ab26 --- /dev/null +++ b/server.mjs @@ -0,0 +1,287 @@ +import { createServer } from 'node:http'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +import { TelemetryService } from './services/telemetry.mjs'; +import { CameraService } from './services/camera.mjs'; +import { CelestialService } from './services/celestial.mjs'; + +const ROOT = path.dirname(fileURLToPath(import.meta.url)); +const DATA_DIR = path.resolve(process.env.DATA_DIR || path.join(ROOT, 'data')); +const PORT = Number(process.env.PORT || 8080); +const HOST = process.env.HOST || '0.0.0.0'; + +const log = Object.fromEntries(['debug', 'info', 'warn', 'error'].map((level) => [ + level, + (...args) => console[level === 'debug' ? 'log' : level]( + `[${new Date().toISOString()}] [${level}]`, + ...args, + ), +])); + +const telemetryConfig = { + python: process.env.PYTHON || 'python3', + script: path.resolve(process.env.MPU_SCRIPT || path.join(ROOT, 'mpu.py')), + bnoAddress: 0x4b, + bnoHz: 20, + staleMs: 3000, + restartAfterMs: 10000, + startTimeoutMs: 10000, + gpsdHost: process.env.GPSD_HOST || '127.0.0.1', + gpsdPort: Number(process.env.GPSD_PORT || 2947), + gpsStaleMs: 5000, + pisugar: { + enabled: process.env.PISUGAR_ENABLED !== 'false', + i2cBus: Number(process.env.PISUGAR_I2C_BUS || 1), + i2cAddress: Number(process.env.PISUGAR_I2C_ADDRESS || 0x75), + pollMs: Number(process.env.PISUGAR_POLL_MS || 5000), + i2cgetBin: process.env.I2CGET || 'i2cget', + }, +}; + +const cameraConfig = { + vidBin: process.env.RPICAM_VID || 'rpicam-vid', + stillBin: process.env.RPICAM_STILL || 'rpicam-still', + ffmpegBin: process.env.FFMPEG || 'ffmpeg', + width: Number(process.env.W || 1280), + height: Number(process.env.H || 720), + fps: Number(process.env.FPS || 30), + streamQuality: 85, + streamMaxShutterUs: 1_000_000, + streamIdleStopMs: 5000, + photoWidth: 0, + photoHeight: 0, + videoWidth: 1280, + videoHeight: 720, + videoFps: 30, + focusMaxSteps: 1000, + remuxMp4: true, +}; + +const fallbackLat = process.env.FALLBACK_LAT === undefined ? null : Number(process.env.FALLBACK_LAT); +const fallbackLon = process.env.FALLBACK_LON === undefined ? null : Number(process.env.FALLBACK_LON); + +const celestialConfig = { + tleBaseUrl: 'https://celestrak.org/NORAD/elements/gp.php', + tleGroups: (process.env.TLE_GROUPS || 'visual,stations').split(',').map((s) => s.trim()).filter(Boolean), + tleMaxAgeHours: 12, + tleRetryMinutes: 360, + maxOrientationAgeMs: 1500, + onTargetDeg: 1, + invertQuat: false, + defaultBoresight: [0, 0, 1], + ...(fallbackLat !== null && fallbackLon !== null && Number.isFinite(fallbackLat) && Number.isFinite(fallbackLon) + ? { fallbackObserver: { lat: fallbackLat, lon: fallbackLon, altM: Number(process.env.FALLBACK_ALT || 0) } } + : {}), +}; + +if (process.env.DECLINATION_DEG !== undefined) { + celestialConfig.declinationDeg = Number(process.env.DECLINATION_DEG); +} + +const telemetry = new TelemetryService(telemetryConfig, { log }); +const celestial = new CelestialService(celestialConfig, { telemetry, log, dataDir: DATA_DIR }); +const camera = new CameraService(cameraConfig, { + log, + dataDir: DATA_DIR, + metaProvider: () => ({ + telemetry: telemetry.getSnapshot(), + pointing: safePointing(), + }), +}); + +function safePointing() { + try { + return celestial.getPointing(); + } catch (err) { + return { available: false, error: err.code || err.message }; + } +} + +function sendJson(res, status, data) { + res.writeHead(status, { + 'Content-Type': 'application/json; charset=utf-8', + 'Cache-Control': 'no-store', + }); + res.end(JSON.stringify(data)); +} + +function readJson(req) { + return new Promise((resolve, reject) => { + let body = ''; + req.setEncoding('utf8'); + + req.on('data', (chunk) => { + body += chunk; + if (body.length > 1_000_000) { + reject(Object.assign(new Error('Request body too large'), { status: 413, code: 'body_too_large' })); + req.destroy(); + } + }); + + req.on('end', () => { + if (!body.trim()) return resolve({}); + try { + resolve(JSON.parse(body)); + } catch { + reject(Object.assign(new Error('Invalid JSON body'), { status: 400, code: 'invalid_json' })); + } + }); + + req.on('error', reject); + }); +} + +async function handle(req, res) { + const url = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`); + + if (req.method === 'GET' && url.pathname === '/') { + return sendJson(res, 200, { + name: 'MRS', + status: 'online', + endpoints: [ + '/stream', + '/api/status', + '/api/telemetry/battery', + '/api/camera/settings', + ], + }); + } + + if (req.method === 'GET' && url.pathname === '/stream') { + return camera.addStreamClient(req, res); + } + + if (req.method === 'GET' && url.pathname === '/api/telemetry/battery') { + return sendJson(res, 200, { battery: telemetry.getBattery() }); + } + + if (req.method === 'GET' && url.pathname === '/api/camera/settings') { + return sendJson(res, 200, { settings: camera.getSettings() }); + } + + if (req.method === 'PATCH' && url.pathname === '/api/camera/settings') { + const body = await readJson(req); + const settings = await camera.applySettings(body); + return sendJson(res, 200, { ok: true, settings }); + } + + if (req.method === 'POST' && url.pathname === '/api/camera/settings/reset') { + const settings = await camera.resetSettings(); + return sendJson(res, 200, { ok: true, settings }); + } + + if (req.method === 'GET' && url.pathname === '/api/status') { + let celestialStatus; + + try { + celestialStatus = celestial.getStatus(); + } catch (err) { + celestialStatus = { error: err.code || 'unavailable', message: err.message }; + } + + return sendJson(res, 200, { + status: 'online', + telemetry: telemetry.getSnapshot(), + camera: camera.getStatus(), + celestial: celestialStatus, + pointing: safePointing(), + }); + } + + if (req.method === 'GET' && url.pathname === '/api/celestial/predict') { + const target = url.searchParams.get('target'); + if (!target) { + return sendJson(res, 400, { + error: 'missing_target', + message: 'Pass ?target=moon, vega, iss, sat:25544, etc.', + }); + } + return sendJson(res, 200, celestial.predict(target)); + } + + if (req.method === 'GET' && url.pathname === '/api/celestial/delta') { + const target = url.searchParams.get('target'); + if (!target) { + return sendJson(res, 400, { + error: 'missing_target', + message: 'Pass ?target=moon, vega, iss, sat:25544, etc.', + }); + } + return sendJson(res, 200, celestial.delta(target)); + } + + if (req.method === 'GET' && url.pathname === '/api/celestial/targets') { + const kind = url.searchParams.get('kind') || undefined; + const q = url.searchParams.get('q') || undefined; + const limit = Math.min(500, Math.max(1, Number(url.searchParams.get('limit') || 100))); + return sendJson(res, 200, { targets: celestial.listTargets({ kind, q, limit }) }); + } + + if (req.method === 'GET' && url.pathname === '/api/celestial/alignment') { + return sendJson(res, 200, celestial.getAlignment()); + } + + if (req.method === 'POST' && url.pathname === '/api/celestial/zero') { + const body = await readJson(req); + if (!body.target) { + return sendJson(res, 400, { + error: 'missing_target', + message: 'Provide JSON {"target":"moon"}.', + }); + } + return sendJson(res, 200, await celestial.zero(body.target)); + } + + if (req.method === 'DELETE' && url.pathname === '/api/celestial/zero') { + return sendJson(res, 200, await celestial.clearZero()); + } + + if (req.method === 'POST' && url.pathname === '/api/celestial/tle/refresh') { + const body = await readJson(req); + return sendJson(res, 200, { results: await celestial.refreshTLEs({ force: body.force !== false }) }); + } + + return sendJson(res, 404, { error: 'not_found', path: url.pathname }); +} + +let server; +let stopping = false; + +async function shutdown(signal) { + if (stopping) return; + stopping = true; + log.info(`received ${signal}; shutting down`); + + if (server) { + server.close(); + server.closeAllConnections?.(); + } + + await Promise.allSettled([camera.shutdown(), celestial.shutdown(), telemetry.stop()]); + log.info('shutdown complete'); +} + +async function main() { + await camera.init(); + telemetry.start(); + await celestial.init(); + + server = createServer((req, res) => { + Promise.resolve(handle(req, res)).catch((err) => { + log.error(err.stack || err.message || err); + if (res.headersSent) return res.destroy(err); + sendJson(res, err.status || 500, { error: err.code || 'internal_error', message: err.message }); + }); + }); + + server.listen(PORT, HOST, () => log.info(`MRS listening at http://${HOST}:${PORT}`)); + process.once('SIGINT', () => shutdown('SIGINT')); + process.once('SIGTERM', () => shutdown('SIGTERM')); +} + +main().catch(async (err) => { + log.error(`startup failed: ${err.stack || err}`); + await Promise.allSettled([camera.shutdown(), celestial.shutdown(), telemetry.stop()]); + process.exitCode = 1; +}); diff --git a/services/camera.mjs b/services/camera.mjs new file mode 100644 index 0000000..93e48e6 --- /dev/null +++ b/services/camera.mjs @@ -0,0 +1,1080 @@ + +// Camera service (rpicam-apps wrapper) +// +// libcamera lets only ONE process own the camera, so everything here goes through a single +// state machine: +// +// ┌──────────── clients connect ────────────┐ +// ▼ │ +// idle ◀──────▶ streaming ──photo()/video()/timelapse()──▶ photo | video | timelapse +// ▲ last client leaves │ +// └────────── job finished (stream auto-resumes if anyone is watching) ◀──┘ +// +// * One shared rpicam-vid MJPEG process fans frames out to every HTTP client. +// * Photo / video / timelapse take exclusive ownership: the stream is stopped (clients stay +// connected and simply freeze), the job runs, then the stream restarts by itself. +// * A second job while one is running is rejected with 409 "camera_busy". +// +// Events: 'state', 'settings', 'focus', 'capture', 'timelapse' +// Camera service (rpicam-apps wrapper) +import { EventEmitter } from 'node:events'; +import { spawn, spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import fsp from 'node:fs/promises'; +import path from 'node:path'; +import { ServiceError } from '../lib/errors.mjs'; + +const BOUNDARY = 'frame'; +const SOI = Buffer.from([0xff, 0xd8]); +const EOI = Buffer.from([0xff, 0xd9]); +const MAX_FRAME_BYTES = 8 * 1024 * 1024; + +const DEFAULT_SETTINGS = { + shutterUs: 0, + gain: 0, + ev: 0, + exposureMode: 'normal', + brightness: 0, + contrast: 1, + saturation: 1, + sharpness: 1, + awb: 'auto', + awbGains: null, + denoise: 'auto', + autofocusMode: 'manual', + autofocusRange: 'normal', + autofocusSpeed: 'normal', + lensPosition: 0, + hflip: false, + vflip: false, + rotation: 0, + quality: 93, + roi: null, +}; + +const num = (min, max) => (key, v) => { + const n = Number(v); + if (v === null || v === '' || !Number.isFinite(n) || n < min || n > max) { + throw new ServiceError('invalid_setting', `"${key}" must be a number between ${min} and ${max}`, 400); + } + return n; +}; + +const oneOf = (...opts) => (key, v) => { + if (!opts.includes(v)) { + throw new ServiceError('invalid_setting', `"${key}" must be one of: ${opts.join(', ')}`, 400); + } + return v; +}; + +const bool = (key, v) => { + if (typeof v !== 'boolean') { + throw new ServiceError('invalid_setting', `"${key}" must be true or false`, 400); + } + return v; +}; + +const SETTING_PARSERS = { + shutterUs: (k, v) => Math.round(num(0, 240_000_000)(k, v)), + gain: num(0, 64), + ev: num(-10, 10), + exposureMode: oneOf('normal', 'sport', 'long'), + brightness: num(-1, 1), + contrast: num(0, 32), + saturation: num(0, 32), + sharpness: num(0, 16), + awb: oneOf('auto', 'incandescent', 'tungsten', 'fluorescent', 'indoor', 'daylight', 'cloudy'), + awbGains: (k, v) => { + if (v === null) return null; + if (!Array.isArray(v) || v.length !== 2) { + throw new ServiceError('invalid_setting', `"${k}" must be [red, blue] or null`, 400); + } + return v.map((x) => num(0.1, 8)(k, x)); + }, + denoise: oneOf('auto', 'off', 'cdn_off', 'cdn_fast', 'cdn_hq'), + autofocusMode: oneOf('manual', 'auto', 'continuous'), + autofocusRange: oneOf('normal', 'macro', 'full'), + autofocusSpeed: oneOf('normal', 'fast'), + lensPosition: (k, v) => (v === null ? null : num(0, 32)(k, v)), + hflip: bool, + vflip: bool, + rotation: oneOf(0, 180), + quality: (k, v) => Math.round(num(1, 100)(k, v)), + roi: (k, v) => { + if (v === null) return null; + if (!Array.isArray(v) || v.length !== 4) { + throw new ServiceError('invalid_setting', `"${k}" must be [x, y, w, h] (0..1) or null`, 400); + } + const r = v.map((x) => num(0, 1)(k, x)); + if (r[2] <= 0 || r[3] <= 0 || r[0] + r[2] > 1.0001 || r[1] + r[3] > 1.0001) { + throw new ServiceError('invalid_setting', `"${k}" region must lie inside the sensor`, 400); + } + return r; + }, +}; + +/** Validate partial settings. ISO is a convenience alias for gain, not an independent sensor control. */ +export function normalizeSettings(patch) { + if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) { + throw new ServiceError('invalid_setting', 'Settings must be a JSON object', 400); + } + + const out = {}; + for (const [key, value] of Object.entries(patch)) { + if (key === 'iso') { + out.gain = value === 0 ? 0 : num(1, 6400)('iso', value) / 100; + continue; + } + + const parse = SETTING_PARSERS[key]; + if (!parse) { + throw new ServiceError('unknown_setting', `Unknown setting "${key}"`, 400, { + valid: [...Object.keys(SETTING_PARSERS), 'iso'], + }); + } + + out[key] = parse(key, value); + } + + return out; +} + +class MjpegParser { + #buf = Buffer.alloc(0); + + constructor(onFrame) { + this.onFrame = onFrame; + } + + push(chunk) { + this.#buf = this.#buf.length ? Buffer.concat([this.#buf, chunk]) : chunk; + + for (;;) { + const soi = this.#buf.indexOf(SOI); + if (soi === -1) { + this.#buf = this.#buf.length && this.#buf[this.#buf.length - 1] === 0xff + ? this.#buf.subarray(-1) + : Buffer.alloc(0); + return; + } + + const eoi = this.#buf.indexOf(EOI, soi + 2); + if (eoi === -1) { + this.#buf = this.#buf.subarray(soi); + if (this.#buf.length > MAX_FRAME_BYTES) this.#buf = Buffer.alloc(0); + return; + } + + this.onFrame(this.#buf.subarray(soi, eoi + 2)); + this.#buf = this.#buf.subarray(eoi + 2); + } + } +} + +const stamp = () => new Date().toISOString().replace(/[-:]/g, '').replace(/\.\d+Z$/, 'Z'); + +const sleepable = () => { + let wake; + const promise = new Promise((resolve) => (wake = resolve)); + return { promise, wake }; +}; + +export class CameraService extends EventEmitter { + #cfg; + #log; + #dirs; + #settingsFile; + #metaProvider; + #settings = { ...DEFAULT_SETTINGS }; + #mode = 'idle'; + #locked = false; + #stream = null; + #clients = new Set(); + #lastFrame = null; + #idleTimer = null; + #restartTimer = null; + #streamFailures = 0; + #job = null; + #activeProc = null; + #lastCapture = null; + #ffmpegAvailable = null; + #focus; + + constructor(cfg, { log, dataDir, metaProvider }) { + super(); + this.#cfg = cfg; + this.#log = log; + this.#metaProvider = metaProvider; + + const base = path.join(dataDir, 'captures'); + this.#dirs = { + base, + photos: path.join(base, 'photos'), + videos: path.join(base, 'videos'), + timelapse: path.join(base, 'timelapse'), + }; + + this.#settingsFile = path.join(dataDir, 'camera-settings.json'); + this.#focus = { + position: 0, + target: 0, + min: 0, + max: cfg.focusMaxSteps, + hardware: false, + moving: false, + }; + } + + get mediaRoot() { + return this.#dirs.base; + } + + async init() { + for (const dir of Object.values(this.#dirs)) await fsp.mkdir(dir, { recursive: true }); + + try { + const saved = JSON.parse(await fsp.readFile(this.#settingsFile, 'utf8')); + this.#settings = { ...DEFAULT_SETTINGS, ...normalizeSettings(saved) }; + this.#log.info('loaded saved camera settings'); + } catch (err) { + if (err.code !== 'ENOENT') this.#log.warn(`ignoring unreadable camera settings: ${err.message}`); + } + } + + async shutdown() { + clearTimeout(this.#idleTimer); + clearTimeout(this.#restartTimer); + if (this.#job?.type === 'timelapse') await this.stopTimelapse().catch(() => {}); + if (this.#job?.type === 'video') await this.stopVideo().catch(() => {}); + await this.#stopStream(); + } + + // ───────────────────────────── status / settings ───────────────────────────── + + getSettings() { + return { + ...this.#settings, + iso: this.#settings.gain ? Math.round(this.#settings.gain * 100) : 0, + }; + } + + getStatus() { + return { + mode: this.#mode, + busy: this.#locked, + streamClients: this.#clients.size, + stream: this.#stream + ? { running: true, fps: this.#stream.fps, width: this.#cfg.width, height: this.#cfg.height } + : { running: false }, + settings: this.getSettings(), + focus: this.getFocus(), + job: this.#jobSummary(), + lastCapture: this.#lastCapture, + }; + } + + /** Patch any subset of settings, persist them, and restart the live stream if needed. */ + async applySettings(patch) { + const clean = normalizeSettings(patch); + this.#settings = { ...this.#settings, ...clean }; + + try { + await fsp.writeFile(this.#settingsFile, JSON.stringify(this.#settings, null, 2)); + } catch (err) { + this.#log.warn(`could not persist camera settings: ${err.message}`); + } + + this.#log.info('camera settings updated', clean); + this.emit('settings', this.getSettings()); + this.#clearError(); + + if (this.#stream && !this.#locked) { + clearTimeout(this.#restartTimer); + this.#restartTimer = setTimeout(async () => { + if (this.#locked) return; + await this.#stopStream(); + this.#ensureStream(); + }, 300); + } + + return this.getSettings(); + } + + /** Restore and persist all defaults. */ + async resetSettings() { + return this.applySettings({ ...DEFAULT_SETTINGS }); + } + + // ───────────────────────────── focuser ───────────────────────────── + + getFocus() { + return { ...this.#focus }; + } + + /** Stub for the telescope focuser hardware interface. */ + async setFocus(position) { + const n = Number(position); + if (!Number.isFinite(n)) { + throw new ServiceError('invalid_focus', '"position" must be a number', 400); + } + + const f = this.#focus; + const target = Math.min(f.max, Math.max(f.min, Math.round(n))); + const delta = target - f.position; + + this.#log.info( + `[focuser:stub] move ${f.position} -> ${target} (${delta >= 0 ? '+' : ''}${delta} steps)` + + (target !== Math.round(n) ? ` (clamped from ${Math.round(n)})` : '') + + ' — no focuser hardware attached', + ); + + f.target = target; + f.position = target; + this.emit('focus', this.getFocus()); + return this.getFocus(); + } + + async nudgeFocus(delta) { + const n = Number(delta); + if (!Number.isFinite(n)) { + throw new ServiceError('invalid_focus', '"delta" must be a number', 400); + } + return this.setFocus(this.#focus.position + n); + } + + // ───────────────────────────── live stream ───────────────────────────── + + addStreamClient(req, res) { + res.writeHead(200, { + 'Content-Type': `multipart/x-mixed-replace; boundary=${BOUNDARY}`, + 'Cache-Control': 'no-store, no-cache, must-revalidate', + Pragma: 'no-cache', + Connection: 'close', + }); + + res.socket?.setNoDelay(true); + this.#clients.add(res); + clearTimeout(this.#idleTimer); + this.#clearError(); + this.#log.debug(`stream client connected (${this.#clients.size})`); + this.emit('state', this.getStatus()); + + if (this.#lastFrame) this.#sendFrame(res, this.#lastFrame); + this.#ensureStream(); + + let gone = false; + const onGone = () => { + if (gone) return; + gone = true; + this.#clients.delete(res); + this.#log.debug(`stream client left (${this.#clients.size})`); + this.#scheduleIdleStop(); + this.emit('state', this.getStatus()); + }; + + req.on('close', onGone); + res.on('error', onGone); + } + + getSnapshot() { + return this.#lastFrame; + } + + #clearError() { + this.#streamFailures = 0; + if (this.#mode === 'error' && !this.#stream && !this.#locked) this.#setMode('idle'); + } + + #ensureStream() { + if (this.#locked || this.#stream || this.#clients.size === 0 || this.#mode === 'error') return; + this.#startStream(); + } + + #scheduleIdleStop() { + if (this.#clients.size > 0) return; + clearTimeout(this.#idleTimer); + this.#idleTimer = setTimeout(async () => { + if (this.#clients.size === 0 && !this.#locked) { + await this.#stopStream(); + this.#setMode('idle'); + } + }, this.#cfg.streamIdleStopMs); + } + + #streamArgs() { + const c = this.#cfg; + const s = this.#settings; + const shutter = s.shutterUs > 0 ? Math.min(s.shutterUs, c.streamMaxShutterUs) : 0; + const fps = shutter > 0 ? Math.min(c.fps, 1_000_000 / shutter) : c.fps; + + return { + fps, + args: [ + '-n', '-t', '0', + '--width', String(c.width), + '--height', String(c.height), + '--framerate', fps.toFixed(3), + '--codec', 'mjpeg', + '-q', String(s.quality), + ...this.#controlArgs(s, { shutterUs: shutter }), + '-o', '-', + ], + }; + } + + #startStream() { + const { fps, args } = this.#streamArgs(); + this.#log.info(`starting live view ${this.#cfg.width}x${this.#cfg.height} @ ${fps.toFixed(1)} fps`); + + const proc = spawn(this.#cfg.vidBin, args, { stdio: ['ignore', 'pipe', 'pipe'] }); + const stream = { proc, fps, expected: false, startedAt: Date.now(), frames: 0, exited: null }; + + stream.exited = new Promise((resolve) => { + proc.once('close', resolve); + proc.once('error', resolve); + }); + + this.#stream = stream; + this.#setMode('streaming'); + + const parser = new MjpegParser((frame) => { + stream.frames += 1; + this.#lastFrame = Buffer.from(frame); + this.#broadcast(this.#lastFrame); + }); + + proc.stdout.on('data', (chunk) => parser.push(chunk)); + proc.stderr.on('data', (data) => { + const message = String(data).trim(); + if (/error|fail|unable|no cameras/i.test(message)) { + this.#log.error(`rpicam-vid: ${message.slice(0, 300)}`); + } + }); + + proc.on('error', (err) => { + this.#log.error(`cannot run ${this.#cfg.vidBin}: ${err.message}`); + if (this.#stream === stream) this.#stream = null; + this.#setMode('error'); + }); + + proc.on('close', (code, signal) => { + if (this.#stream !== stream) return; + this.#stream = null; + this.#lastFrame = null; + this.#streamFailures += 1; + this.#log.warn(`live view exited unexpectedly (code=${code}, signal=${signal}, frames=${stream.frames})`); + + if (this.#streamFailures >= 5) { + this.#log.error('live view failed 5 times in a row; giving up until a new viewer connects or settings change'); + this.#setMode('error'); + return; + } + + this.#setMode('idle'); + if (this.#clients.size && !this.#locked) { + clearTimeout(this.#restartTimer); + this.#restartTimer = setTimeout(() => this.#ensureStream(), 1000 * this.#streamFailures); + } + }); + } + + async #stopStream() { + const stream = this.#stream; + if (!stream) return; + + this.#stream = null; + stream.expected = true; + stream.proc.kill('SIGINT'); + + const killer = setTimeout(() => stream.proc.kill('SIGKILL'), 3000); + await stream.exited; + clearTimeout(killer); + this.#lastFrame = null; + this.#log.debug('live view stopped'); + } + + #broadcast(frame) { + for (const res of this.#clients) this.#sendFrame(res, frame); + } + + #sendFrame(res, frame) { + if (res.writableNeedDrain || res.destroyed) return; + res.write(`--${BOUNDARY}\r\nContent-Type: image/jpeg\r\nContent-Length: ${frame.length}\r\n\r\n`); + res.write(frame); + res.write('\r\n'); + } + + // ───────────────────────────── exclusive jobs ───────────────────────────── + + async #acquire(mode) { + if (this.#locked) { + throw new ServiceError('camera_busy', `Camera is busy (${this.#mode})`, 409, { mode: this.#mode }); + } + + this.#clearError(); + this.#locked = true; + clearTimeout(this.#restartTimer); + clearTimeout(this.#idleTimer); + + try { + await this.#stopStream(); + } catch (err) { + this.#locked = false; + throw err; + } + + this.#setMode(mode); + } + + #release() { + this.#locked = false; + this.#job = null; + this.#setMode('idle'); + this.#ensureStream(); + } + + #setMode(mode) { + if (this.#mode === mode) return; + const previous = this.#mode; + this.#mode = mode; + this.#log.debug(`camera ${previous} -> ${mode}`); + this.emit('state', this.getStatus()); + } + + #meta() { + try { + return this.#metaProvider?.() ?? null; + } catch (err) { + this.#log.warn(`metadata provider failed: ${err.message}`); + return null; + } + } + + #run(bin, args, timeoutMs) { + return new Promise((resolve, reject) => { + const proc = spawn(bin, args, { stdio: ['ignore', 'ignore', 'pipe'] }); + this.#activeProc = proc; + let stderr = ''; + let timedOut = false; + + proc.stderr.on('data', (data) => { + stderr = (stderr + data).slice(-4000); + }); + + const timer = setTimeout(() => { + timedOut = true; + proc.kill('SIGKILL'); + }, timeoutMs); + + proc.on('error', (err) => { + clearTimeout(timer); + this.#activeProc = null; + reject(new ServiceError('camera_spawn_failed', `Cannot run ${bin}: ${err.message}`, 500)); + }); + + proc.on('close', (code, signal) => { + clearTimeout(timer); + this.#activeProc = null; + resolve({ code, signal, stderr, timedOut }); + }); + }); + } + + // ───────────────────────────── photos ───────────────────────────── + + #stillArgs(file, settings, { raw = false } = {}) { + const c = this.#cfg; + const manual = settings.shutterUs > 0 && settings.gain > 0; + + return [ + '-n', + '-o', file, + '-q', String(settings.quality), + ...(manual ? ['--immediate'] : ['-t', '1500']), + ...(raw ? ['--raw'] : []), + ...(c.photoWidth > 0 && c.photoHeight > 0 + ? ['--width', String(c.photoWidth), '--height', String(c.photoHeight)] + : []), + ...this.#controlArgs(settings), + ]; + } + + #stillTimeoutMs(settings) { + return Math.max(30_000, (settings.shutterUs / 1000) * 4 + 30_000); + } + + async #captureStill(file, settings, opts) { + const started = Date.now(); + const result = await this.#run( + this.#cfg.stillBin, + this.#stillArgs(file, settings, opts), + this.#stillTimeoutMs(settings), + ); + + if (result.code !== 0 || !fs.existsSync(file)) { + const reason = result.timedOut + ? 'timed out' + : result.signal + ? `killed (${result.signal})` + : `exit code ${result.code}`; + + throw new ServiceError('capture_failed', `rpicam-still failed: ${reason}`, 500, { + stderr: result.stderr.trim().split('\n').slice(-5).join('\n'), + }); + } + + const stat = await fsp.stat(file); + return { file, bytes: stat.size, durationMs: Date.now() - started }; + } + + async takePhoto(overrides = {}) { + const { raw = false, ...settingOverrides } = overrides; + const settings = { ...this.#settings, ...normalizeSettings(settingOverrides) }; + + await this.#acquire('photo'); + + try { + const base = `photo_${stamp()}`; + const file = path.join(this.#dirs.photos, `${base}.jpg`); + + this.#log.info( + `photo: ${settings.shutterUs ? `${(settings.shutterUs / 1e6).toFixed(2)}s` : 'auto'} exposure, ` + + `gain ${settings.gain || 'auto'}${raw ? ', +RAW' : ''}`, + ); + + const meta = this.#meta(); + const result = await this.#captureStill(file, settings, { raw }); + const info = { + type: 'photo', + name: path.basename(file), + url: `/media/photos/${path.basename(file)}`, + raw: raw ? `/media/photos/${base}.dng` : null, + bytes: result.bytes, + durationMs: result.durationMs, + takenAt: new Date().toISOString(), + settings: { ...settings, iso: settings.gain ? Math.round(settings.gain * 100) : 0 }, + meta, + }; + + await fsp.writeFile(path.join(this.#dirs.photos, `${base}.json`), JSON.stringify(info, null, 2)).catch(() => {}); + this.#lastCapture = { type: 'photo', url: info.url, at: info.takenAt }; + this.#log.info(`photo saved: ${info.name} (${(info.bytes / 1e6).toFixed(1)} MB in ${(info.durationMs / 1000).toFixed(1)}s)`); + this.emit('capture', info); + return info; + } finally { + this.#release(); + } + } + + // ───────────────────────────── video ───────────────────────────── + + async startVideo(opts = {}) { + const { durationSec = 0, width, height, fps, ...settingOverrides } = opts; + const settings = { ...this.#settings, ...normalizeSettings(settingOverrides) }; + const c = this.#cfg; + + if (!Number.isFinite(Number(durationSec)) || durationSec < 0) { + throw new ServiceError('invalid_option', '"durationSec" must be >= 0', 400); + } + + await this.#acquire('video'); + + const w = width || c.videoWidth; + const h = height || c.videoHeight; + const f = fps || c.videoFps; + const base = `video_${stamp()}`; + const rawFile = path.join(this.#dirs.videos, `${base}.h264`); + + let proc; + + try { + const args = [ + '-n', + '-t', String(Math.round(durationSec * 1000)), + '--width', String(w), + '--height', String(h), + '--framerate', String(f), + '--codec', 'h264', + '--inline', + ...this.#controlArgs(settings), + '-o', rawFile, + ]; + + proc = spawn(c.vidBin, args, { stdio: ['ignore', 'ignore', 'pipe'] }); + } catch (err) { + this.#release(); + throw new ServiceError('camera_spawn_failed', `Cannot run ${c.vidBin}: ${err.message}`, 500); + } + + const job = { + type: 'video', + id: base, + file: rawFile, + startedAt: Date.now(), + durationSec, + proc, + stopping: false, + done: null, + }; + + this.#job = job; + let stderr = ''; + + proc.stderr.on('data', (data) => { + stderr = (stderr + data).slice(-2000); + }); + + job.done = new Promise((resolve) => { + const finish = async (code, signal, spawnErr) => { + let info; + + try { + if (spawnErr || !fs.existsSync(rawFile)) { + info = { + type: 'video', + error: spawnErr?.message ?? `rpicam-vid produced no file (code=${code})`, + stderr: stderr.trim().split('\n').slice(-3).join('\n'), + }; + this.#log.error(`video failed: ${info.error}`); + } else { + info = await this.#finishVideo(job, rawFile, base, f); + } + } finally { + this.#release(); + } + + resolve(info); + }; + + proc.once('error', (err) => finish(null, null, err)); + proc.once('close', (code, signal) => finish(code, signal)); + }); + + this.#log.info(`video recording started (${w}x${h} @ ${f} fps${durationSec ? `, ${durationSec}s` : ''})`); + return this.#jobSummary(); + } + + async #finishVideo(job, rawFile, base, fps) { + let finalFile = rawFile; + + if (this.#cfg.remuxMp4 && this.#hasFfmpeg()) { + const mp4 = path.join(this.#dirs.videos, `${base}.mp4`); + const code = await new Promise((resolve) => { + const proc = spawn( + this.#cfg.ffmpegBin, + ['-y', '-loglevel', 'error', '-framerate', String(fps), '-i', rawFile, '-c', 'copy', mp4], + { stdio: 'ignore' }, + ); + proc.on('error', () => resolve(1)); + proc.on('close', resolve); + }); + + if (code === 0 && fs.existsSync(mp4)) { + await fsp.unlink(rawFile).catch(() => {}); + finalFile = mp4; + } else { + this.#log.warn('mp4 remux failed; keeping raw .h264'); + } + } + + const stat = await fsp.stat(finalFile); + const info = { + type: 'video', + name: path.basename(finalFile), + url: `/media/videos/${path.basename(finalFile)}`, + bytes: stat.size, + durationSec: Math.round((Date.now() - job.startedAt) / 100) / 10, + takenAt: new Date(job.startedAt).toISOString(), + meta: this.#meta(), + }; + + this.#lastCapture = { type: 'video', url: info.url, at: new Date().toISOString() }; + this.#log.info(`video saved: ${info.name} (${(info.bytes / 1e6).toFixed(1)} MB, ${info.durationSec}s)`); + this.emit('capture', info); + return info; + } + + #hasFfmpeg() { + if (this.#ffmpegAvailable === null) { + this.#ffmpegAvailable = !spawnSync(this.#cfg.ffmpegBin, ['-version'], { stdio: 'ignore' }).error; + if (!this.#ffmpegAvailable) this.#log.warn('ffmpeg not found; videos stay as raw .h264 (apt install ffmpeg to get .mp4)'); + } + return this.#ffmpegAvailable; + } + + async stopVideo() { + const job = this.#job; + if (!job || job.type !== 'video') { + throw new ServiceError('not_recording', 'No video recording in progress', 409); + } + + if (!job.stopping) { + job.stopping = true; + job.proc.kill('SIGINT'); + const killer = setTimeout(() => job.proc.kill('SIGKILL'), 5000); + job.done.finally(() => clearTimeout(killer)); + } + + return job.done; + } + + // ───────────────────────────── timelapse ───────────────────────────── + + async startTimelapse(opts = {}) { + const { intervalSec, count = 0, durationSec = 0, name, raw = false, ...settingOverrides } = opts; + + if (!(Number(intervalSec) >= 1)) { + throw new ServiceError('invalid_option', '"intervalSec" must be a number >= 1', 400); + } + if (!(Number(count) >= 0) || !(Number(durationSec) >= 0)) { + throw new ServiceError('invalid_option', '"count" and "durationSec" must be >= 0', 400); + } + if (!count && !durationSec) { + throw new ServiceError('invalid_option', 'Provide "count" and/or "durationSec" (use stopTimelapse to end early)', 400); + } + + const settings = { ...this.#settings, ...normalizeSettings(settingOverrides) }; + + if (settings.shutterUs / 1e6 >= intervalSec) { + throw new ServiceError( + 'invalid_option', + `intervalSec (${intervalSec}) must be longer than the exposure (${(settings.shutterUs / 1e6).toFixed(2)}s)`, + 400, + ); + } + + await this.#acquire('timelapse'); + + const id = `${String(name || 'timelapse').replace(/[^\w-]+/g, '_')}_${stamp()}`; + const dir = path.join(this.#dirs.timelapse, id); + + try { + await fsp.mkdir(dir, { recursive: true }); + } catch (err) { + this.#release(); + throw new ServiceError('storage_error', `Cannot create ${dir}: ${err.message}`, 500); + } + + const sleeper = sleepable(); + const job = { + type: 'timelapse', + id, + dir, + intervalSec: Number(intervalSec), + total: Number(count) || null, + endAt: durationSec ? Date.now() + durationSec * 1000 : null, + startedAt: Date.now(), + frames: 0, + failures: 0, + stop: false, + wake: sleeper.wake, + sleeper, + nextAt: null, + done: null, + }; + + this.#job = job; + job.done = this.#timelapseLoop(job, settings, raw) + .catch((err) => this.#log.error(`timelapse aborted: ${err.message}`)) + .then(() => { + const summary = { + type: 'timelapse', + id, + frames: job.frames, + dir: `/media/timelapse/${id}`, + stoppedByUser: job.stop, + }; + + this.#lastCapture = { type: 'timelapse', url: summary.dir, at: new Date().toISOString() }; + this.#log.info(`timelapse finished: ${job.frames} frames in ${id}`); + this.emit('timelapse', { ...summary, state: 'finished' }); + this.emit('capture', summary); + this.#release(); + return summary; + }); + + await fsp.writeFile( + path.join(dir, 'session.json'), + JSON.stringify({ + id, + startedAt: new Date().toISOString(), + intervalSec, + count, + durationSec, + settings, + meta: this.#meta(), + }, null, 2), + ).catch(() => {}); + + this.#log.info( + `timelapse started: every ${intervalSec}s${count ? `, ${count} frames` : ''}${durationSec ? `, ${durationSec}s` : ''} -> ${id}`, + ); + + return this.#jobSummary(); + } + + async #timelapseLoop(job, settings, raw) { + const frameLog = path.join(job.dir, 'frames.jsonl'); + + while (!job.stop) { + const tickStart = Date.now(); + const n = job.frames + 1; + const file = path.join(job.dir, `frame_${String(n).padStart(5, '0')}.jpg`); + + try { + const meta = this.#meta(); + const result = await this.#captureStill(file, settings, { raw }); + + if (job.stop && !fs.existsSync(file)) break; + + job.frames = n; + job.failures = 0; + + await fsp.appendFile( + frameLog, + JSON.stringify({ + n, + file: path.basename(file), + at: new Date().toISOString(), + bytes: result.bytes, + meta, + }) + '\n', + ).catch(() => {}); + + this.emit('timelapse', { id: job.id, state: 'frame', frames: job.frames, total: job.total }); + } catch (err) { + if (job.stop) break; + job.failures += 1; + this.#log.error(`timelapse frame ${n} failed (${job.failures}/3): ${err.message}`); + if (job.failures >= 3) throw new Error('3 consecutive frame failures'); + } + + if (job.total && job.frames >= job.total) break; + + const nextAt = tickStart + job.intervalSec * 1000; + if (job.endAt && nextAt > job.endAt) break; + + const wait = nextAt - Date.now(); + job.nextAt = nextAt; + + if (wait > 0) { + await Promise.race([ + new Promise((resolve) => setTimeout(resolve, wait)), + job.sleeper.promise, + ]); + } else { + this.#log.warn(`timelapse frame took longer than the ${job.intervalSec}s interval; not waiting`); + } + } + } + + async stopTimelapse() { + const job = this.#job; + if (!job || job.type !== 'timelapse') { + throw new ServiceError('no_timelapse', 'No timelapse in progress', 409); + } + + job.stop = true; + job.wake(); + this.#activeProc?.kill('SIGTERM'); + return job.done; + } + + // ───────────────────────────── file listing ───────────────────────────── + + async listFiles({ limit = 50 } = {}) { + const read = async (dir, url) => { + const entries = await fsp.readdir(dir, { withFileTypes: true }).catch(() => []); + const out = []; + + for (const entry of entries) { + if (entry.name.endsWith('.json') || entry.name.endsWith('.jsonl')) continue; + + const fullPath = path.join(dir, entry.name); + const stat = await fsp.stat(fullPath).catch(() => null); + if (!stat) continue; + + if (entry.isDirectory()) { + const frames = (await fsp.readdir(fullPath).catch(() => [])).filter((name) => name.endsWith('.jpg')).length; + out.push({ name: entry.name, url: `${url}/${entry.name}`, frames, mtime: stat.mtime }); + } else { + out.push({ name: entry.name, url: `${url}/${entry.name}`, bytes: stat.size, mtime: stat.mtime }); + } + } + + return out.sort((a, b) => b.mtime - a.mtime).slice(0, limit); + }; + + return { + photos: await read(this.#dirs.photos, '/media/photos'), + videos: await read(this.#dirs.videos, '/media/videos'), + timelapses: await read(this.#dirs.timelapse, '/media/timelapse'), + }; + } + + // ───────────────────────────── rpicam argument builder ───────────────────────────── + + #controlArgs(settings, { shutterUs = settings.shutterUs } = {}) { + const args = []; + + if (shutterUs > 0) args.push('--shutter', String(Math.round(shutterUs))); + if (settings.gain > 0) args.push('--gain', String(settings.gain)); + if (settings.ev) args.push('--ev', String(settings.ev)); + if (settings.exposureMode !== 'normal') args.push('--exposure', settings.exposureMode); + + args.push( + '--brightness', String(settings.brightness), + '--contrast', String(settings.contrast), + '--saturation', String(settings.saturation), + '--sharpness', String(settings.sharpness), + ); + + if (settings.awbGains) args.push('--awbgains', settings.awbGains.join(',')); + else args.push('--awb', settings.awb); + + args.push('--denoise', settings.denoise); + + if (settings.hflip) args.push('--hflip'); + if (settings.vflip) args.push('--vflip'); + if (settings.rotation) args.push('--rotation', String(settings.rotation)); + if (settings.roi) args.push('--roi', settings.roi.join(',')); + + args.push( + '--autofocus-mode', settings.autofocusMode, + '--autofocus-range', settings.autofocusRange, + '--autofocus-speed', settings.autofocusSpeed, + ); + + if (settings.autofocusMode === 'manual' && settings.lensPosition !== null) { + args.push('--lens-position', String(settings.lensPosition)); + } + + return args; + } + + #jobSummary() { + const job = this.#job; + if (!job) return null; + + if (job.type === 'video') { + return { + type: 'video', + id: job.id, + elapsedSec: Math.round((Date.now() - job.startedAt) / 100) / 10, + durationSec: job.durationSec || null, + stopping: job.stopping, + }; + } + + return { + type: 'timelapse', + id: job.id, + frames: job.frames, + total: job.total, + intervalSec: job.intervalSec, + elapsedSec: Math.round((Date.now() - job.startedAt) / 1000), + nextFrameAt: job.nextAt ? new Date(job.nextAt).toISOString() : null, + dir: `/media/timelapse/${job.id}`, + }; + } +} diff --git a/services/celestial.mjs b/services/celestial.mjs new file mode 100644 index 0000000..5cde093 --- /dev/null +++ b/services/celestial.mjs @@ -0,0 +1,531 @@ + +// Celestial service +// +// Targets (string "specs", usable from the HTTP API too): +// sat:25544 sat:ISS (ZARYA) iss Earth satellites, from cached TLEs (Celestrak) + SGP4 +// body:moon moon jupiter … Sun, Moon, planets (astronomy-engine ephemeris) +// star:vega vega ~18 bright stars (J2000 → precessed to date) +// radec:5.919,7.407 any fixed RA (hours) / Dec (degrees) J2000 position +// +// NOTE: TLEs only describe Earth-orbiting satellites. The Moon, planets, stars and deep-sky +// objects are NOT in any TLE set, so they use ephemerides / catalogue coordinates instead. +// +// Public API +// predict(spec, {date?, observer?}) where the target is (az/alt) for the GPS position + OS time +// delta(spec, {date?, observer?}) how far the telescope's current pointing is from the target +// zero(spec) align the IMU to the telescope using a known object you're centred on +// getPointing() current telescope az/alt (IMU + alignment + declination) +// refreshTLEs({force?}) download/cache TLEs +// +// How alignment works +// The IMU sits in the eyepiece at an unknown angle, so a simple "+X° azimuth, +Y° altitude" offset +// only holds near the pose it was measured at. Instead we solve for the telescope's boresight +// direction in the *sensor's own frame*: b = q⁻¹ · d_target +// (q = sensor orientation, d_target = predicted direction of the object you are centred on). +// Afterwards pointing(t) = q(t) · b for ANY orientation, which stays correct however the sensor is +// mounted. The BNO's frame is referenced to MAGNETIC north, so magnetic declination (from the World +// Magnetic Model at the GPS position) is applied to get true azimuth before comparing with the sky. +import { EventEmitter } from 'node:events'; +import fsp from 'node:fs/promises'; +import path from 'node:path'; +import * as satellite from 'satellite.js'; +import * as Astronomy from 'astronomy-engine'; +import { ServiceError } from '../lib/errors.mjs'; +import { STARS } from '../lib/stars.mjs'; +import { + azAltToVec, vecToAzAlt, quatConj, quatRotate, wrap360, wrap180, angularSeparation, rad, deg, +} from '../lib/geo.mjs'; + +const BODIES = { + sun: 'Sun', moon: 'Moon', mercury: 'Mercury', venus: 'Venus', mars: 'Mars', + jupiter: 'Jupiter', saturn: 'Saturn', uranus: 'Uranus', neptune: 'Neptune', pluto: 'Pluto', +}; + +const round = (v, d = 3) => (v === null || v === undefined ? v : Math.round(v * 10 ** d) / 10 ** d); + +function parseTle(text) { + const lines = text.split(/\r?\n/).map((l) => l.trim()).filter(Boolean); + const out = []; + for (let i = 0; i < lines.length; ) { + if (lines[i].startsWith('1 ') && lines[i + 1]?.startsWith('2 ')) { + out.push({ name: `NORAD ${lines[i].slice(2, 7).trim()}`, l1: lines[i], l2: lines[i + 1] }); + i += 2; + } else if (lines[i + 1]?.startsWith('1 ') && lines[i + 2]?.startsWith('2 ')) { + out.push({ name: lines[i].replace(/^0 /, ''), l1: lines[i + 1], l2: lines[i + 2] }); + i += 3; + } else { + i += 1; + } + } + return out; +} + +function tleEpochMs(satrec) { + const year = satrec.epochyr < 57 ? 2000 + satrec.epochyr : 1900 + satrec.epochyr; + return Date.UTC(year, 0, 1) + (satrec.epochdays - 1) * 86_400_000; +} + +export class CelestialService extends EventEmitter { + #cfg; + #log; + #telemetry; + #dir; + #alignmentFile; + + #sats = new Map(); // noradId -> { id, name, satrec, epochMs, group } + #groupInfo = new Map(); // group -> { count, fetchedAt } + #alignment = null; + #geomag = null; + #refreshing = null; + #timer = null; + #lastRefreshError = null; + + constructor(cfg, { telemetry, log, dataDir }) { + super(); + this.#cfg = cfg; + this.#telemetry = telemetry; + this.#log = log; + this.#dir = path.join(dataDir, 'tle'); + this.#alignmentFile = path.join(dataDir, 'alignment.json'); + } + + // ───────────────────────────── lifecycle ───────────────────────────── + + async init() { + await fsp.mkdir(this.#dir, { recursive: true }); + + try { + const mod = await import('geomagnetism'); + this.#geomag = mod.default ?? mod; + } catch { + this.#log.warn('"geomagnetism" not installed: magnetic declination will use DECLINATION_DEG (default 0)'); + } + + try { + this.#alignment = JSON.parse(await fsp.readFile(this.#alignmentFile, 'utf8')); + this.#log.info(`loaded saved alignment (zeroed on ${this.#alignment.target?.label} at ${this.#alignment.createdAt})`); + } catch (err) { + if (err.code !== 'ENOENT') this.#log.warn(`ignoring unreadable alignment file: ${err.message}`); + } + + await this.#loadCache(); + // Refresh in the background: never block startup on the network (we may be in a field with no internet). + this.refreshTLEs().catch(() => {}); + this.#timer = setInterval(() => this.refreshTLEs().catch(() => {}), this.#cfg.tleRetryMinutes * 60_000); + this.#timer.unref(); + } + + shutdown() { + clearInterval(this.#timer); + } + + // ───────────────────────────── TLE cache ───────────────────────────── + + async #loadCache() { + for (const group of this.#cfg.tleGroups) { + const file = path.join(this.#dir, `${group}.tle`); + try { + const [text, st] = await Promise.all([fsp.readFile(file, 'utf8'), fsp.stat(file)]); + this.#groupInfo.set(group, { count: parseTle(text).length, fetchedAt: st.mtimeMs, text }); + } catch (err) { + if (err.code !== 'ENOENT') this.#log.warn(`TLE cache for "${group}" unreadable: ${err.message}`); + } + } + this.#rebuildIndex(); + } + + #rebuildIndex() { + const sats = new Map(); + for (const [group, info] of this.#groupInfo) { + for (const t of parseTle(info.text)) { + let satrec; + try { + satrec = satellite.twoline2satrec(t.l1, t.l2); + } catch { + continue; + } + const id = parseInt(t.l1.slice(2, 7), 10); + if (!Number.isFinite(id) || !Number.isFinite(satrec.no)) continue; + const epochMs = tleEpochMs(satrec); + const prev = sats.get(id); + if (!prev || epochMs > prev.epochMs) sats.set(id, { id, name: t.name, satrec, epochMs, group }); + } + } + this.#sats = sats; + } + + /** + * Download any TLE group that is missing/older than TLE_MAX_AGE_HOURS (or all, with force). + * Failures are non-fatal: cached data keeps being served. + */ + async refreshTLEs({ force = false } = {}) { + if (this.#refreshing) return this.#refreshing; + this.#refreshing = (async () => { + const results = []; + const maxAgeMs = this.#cfg.tleMaxAgeHours * 3_600_000; + for (const group of this.#cfg.tleGroups) { + const info = this.#groupInfo.get(group); + if (!force && info && Date.now() - info.fetchedAt < maxAgeMs) { + results.push({ group, skipped: 'fresh', count: info.count }); + continue; + } + try { + const text = await this.#fetchGroup(group); + const count = parseTle(text).length; + const file = path.join(this.#dir, `${group}.tle`); + await fsp.writeFile(`${file}.tmp`, text); + await fsp.rename(`${file}.tmp`, file); // atomic: never leave a half-written cache + this.#groupInfo.set(group, { count, fetchedAt: Date.now(), text }); + this.#log.info(`TLE group "${group}" updated (${count} objects)`); + results.push({ group, ok: true, count }); + } catch (err) { + this.#lastRefreshError = { at: new Date().toISOString(), message: err.message }; + this.#log.warn(`TLE refresh "${group}" failed: ${err.message}${info ? ' — using cached copy' : ''}`); + results.push({ group, ok: false, error: err.message, usingCache: Boolean(info) }); + } + } + this.#rebuildIndex(); + this.emit('tle', this.getTleStatus()); + return results; + })().finally(() => { + this.#refreshing = null; + }); + return this.#refreshing; + } + + async #fetchGroup(group) { + const url = `${this.#cfg.tleBaseUrl}?GROUP=${encodeURIComponent(group)}&FORMAT=tle`; + const res = await fetch(url, { signal: AbortSignal.timeout(20_000), headers: { 'User-Agent': 'eye-spy/1.0' } }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + const text = await res.text(); + if (parseTle(text).length === 0) throw new Error('response contained no TLEs'); + return text; + } + + getTleStatus() { + const groups = {}; + for (const [g, i] of this.#groupInfo) { + groups[g] = { count: i.count, fetchedAt: new Date(i.fetchedAt).toISOString(), ageHours: round((Date.now() - i.fetchedAt) / 3_600_000, 1) }; + } + const epochs = [...this.#sats.values()].map((s) => s.epochMs); + return { + satellites: this.#sats.size, + groups, + wantedGroups: this.#cfg.tleGroups, + oldestEpoch: epochs.length ? new Date(Math.min(...epochs)).toISOString() : null, + refreshing: Boolean(this.#refreshing), + lastError: this.#lastRefreshError, + }; + } + + // ───────────────────────────── targets ───────────────────────────── + + listTargets({ kind, q, limit = 100 } = {}) { + const query = q?.toLowerCase(); + const match = (t) => !query || t.id.toLowerCase().includes(query) || t.label.toLowerCase().includes(query); + const all = []; + if (!kind || kind === 'body') { + for (const [k, v] of Object.entries(BODIES)) all.push({ kind: 'body', id: `body:${k}`, label: v }); + } + if (!kind || kind === 'star') { + for (const [k, v] of Object.entries(STARS)) all.push({ kind: 'star', id: `star:${k}`, label: v.label }); + } + if (!kind || kind === 'sat') { + for (const s of this.#sats.values()) all.push({ kind: 'sat', id: `sat:${s.id}`, label: s.name }); + } + return all.filter(match).slice(0, limit); + } + + /** Resolve a target spec string into a normalised target object. */ + resolveTarget(spec) { + const raw = String(spec ?? '').trim(); + if (!raw) throw new ServiceError('invalid_target', 'No target given (e.g. "moon", "vega", "iss", "sat:25544", "radec:5.9,7.4")', 400); + + let kind; + let rest; + const m = raw.match(/^(sat|body|star|radec):(.*)$/i); + if (m) { + kind = m[1].toLowerCase(); + rest = m[2].trim(); + } else { + const key = raw.toLowerCase(); + if (key === 'iss') [kind, rest] = ['sat', '25544']; + else if (BODIES[key]) [kind, rest] = ['body', key]; + else if (STARS[key]) [kind, rest] = ['star', key]; + else [kind, rest] = ['sat', raw]; + } + + if (kind === 'body') { + const key = rest.toLowerCase(); + if (!BODIES[key]) throw new ServiceError('unknown_target', `Unknown body "${rest}"`, 404, { valid: Object.keys(BODIES) }); + return { kind, id: `body:${key}`, label: BODIES[key], body: BODIES[key] }; + } + if (kind === 'star') { + const key = rest.toLowerCase(); + const st = STARS[key]; + if (!st) throw new ServiceError('unknown_target', `Unknown star "${rest}"`, 404, { valid: Object.keys(STARS) }); + return { kind, id: `star:${key}`, label: st.label, ra: st.ra, dec: st.dec }; + } + if (kind === 'radec') { + const [ra, dec] = rest.split(',').map(Number); + if (!Number.isFinite(ra) || !Number.isFinite(dec) || ra < 0 || ra >= 24 || dec < -90 || dec > 90) { + throw new ServiceError('invalid_target', 'radec must be "radec:," (J2000)', 400); + } + return { kind, id: `radec:${ra},${dec}`, label: `RA ${ra}h Dec ${dec}°`, ra, dec }; + } + // satellite + if (this.#sats.size === 0) { + throw new ServiceError('no_tle_data', 'No TLE data loaded yet (offline on first run?). Try POST /api/celestial/tle/refresh once online.', 503); + } + const asId = /^\d+$/.test(rest) ? parseInt(rest, 10) : null; + if (asId !== null) { + const s = this.#sats.get(asId); + if (!s) throw new ServiceError('unknown_target', `NORAD ${asId} not in the loaded TLE groups (${this.#cfg.tleGroups.join(', ')})`, 404); + return { kind: 'sat', id: `sat:${s.id}`, label: s.name, norad: s.id }; + } + const q = rest.toLowerCase(); + const all = [...this.#sats.values()]; + const exact = all.filter((s) => s.name.toLowerCase() === q); + const starts = all.filter((s) => s.name.toLowerCase().startsWith(q)); + const includes = all.filter((s) => s.name.toLowerCase().includes(q)); + const hits = exact.length ? exact : starts.length ? starts : includes; + if (hits.length === 0) throw new ServiceError('unknown_target', `No satellite matching "${rest}"`, 404); + if (hits.length > 1 && !exact.length) { + throw new ServiceError('ambiguous_target', `"${rest}" matches ${hits.length} satellites; use a NORAD id`, 400, { + matches: hits.slice(0, 10).map((s) => ({ id: `sat:${s.id}`, name: s.name })), + }); + } + return { kind: 'sat', id: `sat:${hits[0].id}`, label: hits[0].name, norad: hits[0].id }; + } + + // ───────────────────────────── observer / time ───────────────────────────── + + #observer(override) { + if (override) { + const { lat, lon } = override; + if (!Number.isFinite(lat) || !Number.isFinite(lon)) throw new ServiceError('invalid_observer', 'observer needs numeric lat and lon', 400); + return { lat, lon, altM: override.altM ?? 0, source: 'override' }; + } + const p = this.#telemetry.getPosition(); + if (p) return { lat: p.lat, lon: p.lon, altM: p.altM, source: p.live ? 'gps' : 'gps-last-known', ageMs: p.ageMs }; + if (this.#cfg.fallbackObserver) return { ...this.#cfg.fallbackObserver, source: 'config' }; + throw new ServiceError('no_position', 'No GPS fix yet and no FALLBACK_LAT/FALLBACK_LON configured', 503); + } + + #declination(obs, date) { + if (Number.isFinite(this.#cfg.declinationDeg)) return { deg: this.#cfg.declinationDeg, source: 'config' }; + if (this.#geomag) { + try { + const info = this.#geomag.model(date).point([obs.lat, obs.lon]); + if (Number.isFinite(info.decl)) return { deg: info.decl, source: 'wmm' }; + } catch { + /* fall through */ + } + } + return { deg: 0, source: 'none' }; + } + + // ───────────────────────────── prediction ───────────────────────────── + + /** + * Where is the target, from the GPS position, at the OS time? + * @param {string} spec + * @param {{date?: Date, observer?: {lat:number, lon:number, altM?:number}}} [opts] + * @returns {{target, time, observer, az:number, alt:number, aboveHorizon:boolean, rangeKm?:number, tle?:object}} + */ + predict(spec, { date = this.#telemetry.now(), observer } = {}) { + const target = this.resolveTarget(spec); + const obs = this.#observer(observer); + const out = { + target: { kind: target.kind, id: target.id, label: target.label }, + time: date.toISOString(), + observer: { lat: round(obs.lat, 5), lon: round(obs.lon, 5), altM: round(obs.altM, 1), source: obs.source }, + }; + + let pos; + if (target.kind === 'sat') { + const s = this.#sats.get(target.norad); + const pv = satellite.propagate(s.satrec, date); + const p = pv?.position; + if (!p || ![p.x, p.y, p.z].every(Number.isFinite)) { + throw new ServiceError('propagation_failed', `SGP4 could not propagate ${target.label} to ${out.time} (TLE too old or decayed?)`, 422); + } + const ecf = satellite.eciToEcf(p, satellite.gstime(date)); + const look = satellite.ecfToLookAngles({ latitude: rad(obs.lat), longitude: rad(obs.lon), height: obs.altM / 1000 }, ecf); + pos = { az: wrap360(deg(look.azimuth)), alt: deg(look.elevation) }; + out.rangeKm = round(look.rangeSat, 1); + const ageDays = (date.getTime() - s.epochMs) / 86_400_000; + out.tle = { epoch: new Date(s.epochMs).toISOString(), ageDays: round(ageDays, 2), stale: Math.abs(ageDays) > 14 }; + } else { + const astroObs = new Astronomy.Observer(obs.lat, obs.lon, obs.altM); + let ra; + let dec; + if (target.kind === 'body') { + const eq = Astronomy.Equator(target.body, date, astroObs, true, true); // topocentric, of date, with aberration + ra = eq.ra; + dec = eq.dec; + out.distanceAu = round(eq.dist, 5); + } else { + // J2000 catalogue position -> equator of date (precession is ~0.3° by now, which matters at eyepiece scale) + const v = Astronomy.VectorFromSphere(new Astronomy.Spherical(target.dec, target.ra * 15, 1), date); + const eq = Astronomy.EquatorFromVector(Astronomy.RotateVector(Astronomy.Rotation_EQJ_EQD(date), v)); + ra = eq.ra; + dec = eq.dec; + } + const hor = Astronomy.Horizon(date, astroObs, ra, dec, 'normal'); // includes atmospheric refraction + pos = { az: hor.azimuth, alt: hor.altitude }; + out.raHours = round(ra, 5); + out.decDeg = round(dec, 4); + } + + out.az = round(pos.az); + out.alt = round(pos.alt); + out.aboveHorizon = pos.alt > 0; + return out; + } + + // ───────────────────────────── pointing / delta ───────────────────────────── + + #freshOrientation() { + const o = this.#telemetry.getOrientation({ maxAgeMs: this.#cfg.maxOrientationAgeMs }); + if (!o) { + throw new ServiceError('no_orientation', 'No fresh orientation data from the IMU (sensor stale or not running)', 503, { + sensorState: this.#telemetry.getSensorState(), + }); + } + return o; + } + + #bodyQuat(o) { + return this.#cfg.invertQuat ? quatConj(o.quat) : o.quat; + } + + /** Where the telescope is pointing right now (true az / alt). */ + getPointing({ date = this.#telemetry.now(), observer } = {}) { + const o = this.#freshOrientation(); + const obs = this.#observer(observer); + const decl = this.#declination(obs, date); + const boresight = this.#alignment?.boresight ?? this.#cfg.defaultBoresight; + const { az: azMag, alt } = vecToAzAlt(quatRotate(this.#bodyQuat(o), boresight)); + return { + az: round(wrap360(azMag + decl.deg)), + alt: round(alt), + aligned: Boolean(this.#alignment), + declination: { deg: round(decl.deg, 2), source: decl.source }, + orientationAgeMs: o.ageMs, + }; + } + + /** + * How far is the telescope from the target? Positive deltaAz = target is clockwise (right when facing it), + * positive deltaAlt = target is higher than where the telescope points. + */ + delta(spec, opts = {}) { + const date = opts.date ?? this.#telemetry.now(); + const target = this.predict(spec, { ...opts, date }); + const pointing = this.getPointing({ ...opts, date }); + const dAz = wrap180(target.az - pointing.az); + const dAlt = target.alt - pointing.alt; + const sep = angularSeparation(pointing.az, pointing.alt, target.az, target.alt); + return { + target, + pointing, + deltaAz: round(dAz), + deltaAlt: round(dAlt), + deltaAzOnSky: round(dAz * Math.cos(rad((target.alt + pointing.alt) / 2))), // true angular distance along the horizon + separation: round(sep), + onTarget: sep <= this.#cfg.onTargetDeg, + hint: { + azimuth: Math.abs(dAz) < 0.05 ? 'ok' : dAz > 0 ? 'right' : 'left', + altitude: Math.abs(dAlt) < 0.05 ? 'ok' : dAlt > 0 ? 'up' : 'down', + }, + warnings: [ + ...(pointing.aligned ? [] : ['not aligned yet: run zero() on a known object first']), + ...(target.aboveHorizon ? [] : ['target is below the horizon']), + ...(target.tle?.stale ? ['TLE is more than 14 days old; satellite position may be off'] : []), + ], + }; + } + + // ───────────────────────────── zeroing ───────────────────────────── + + /** + * Align the IMU to the telescope. Centre a known object in the eyepiece, hold still, then call this. + * Only the sensor-to-tube mounting is solved; it stays valid for any later orientation. + * Best objects: the Moon, a planet, or a bright star (satellites move too fast to centre and hold). + */ + async zero(spec) { + const date = this.#telemetry.now(); + const o = this.#freshOrientation(); + const predicted = this.predict(spec, { date }); + if (!predicted.aboveHorizon) { + throw new ServiceError('target_below_horizon', `${predicted.target.label} is below the horizon (alt ${predicted.alt}°); you can't be pointing at it`, 422, { predicted }); + } + + // What the telescope *would have* reported before this alignment (so the user sees the size of the correction). + let before = null; + try { + before = this.getPointing({ date }); + } catch { + /* no observer/orientation: skip */ + } + + const obs = this.#observer(); + const decl = this.#declination(obs, date); + const dirMag = azAltToVec(wrap360(predicted.az - decl.deg), predicted.alt); // true -> magnetic frame + const boresight = quatRotate(quatConj(this.#bodyQuat(o)), dirMag); // target direction expressed in the sensor frame + + this.#alignment = { + boresight: boresight.map((v) => round(v, 6)), + createdAt: date.toISOString(), + target: predicted.target, + predicted: { az: predicted.az, alt: predicted.alt }, + sensorAtZero: { yaw: o.yaw, pitch: o.pitch, roll: o.roll }, + declination: decl, + observer: predicted.observer, + }; + await fsp.writeFile(this.#alignmentFile, JSON.stringify(this.#alignment, null, 2)).catch((err) => { + this.#log.warn(`could not persist alignment: ${err.message}`); + }); + + const result = { + aligned: true, + target: predicted.target, + predicted: { az: predicted.az, alt: predicted.alt }, + before: before ? { az: before.az, alt: before.alt } : null, + correction: before + ? { + deltaAz: round(wrap180(predicted.az - before.az)), + deltaAlt: round(predicted.alt - before.alt), + separation: round(angularSeparation(before.az, before.alt, predicted.az, predicted.alt)), + } + : null, + declination: decl, + boresight: this.#alignment.boresight, + }; + this.#log.info( + `zeroed on ${predicted.target.label}: predicted az ${predicted.az}° alt ${predicted.alt}°` + + (result.correction ? `, applied correction ${result.correction.separation}°` : '') + + ` (declination ${round(decl.deg, 1)}° via ${decl.source})`, + ); + this.emit('zero', result); + return result; + } + + async clearZero() { + this.#alignment = null; + await fsp.rm(this.#alignmentFile, { force: true }); + this.#log.info('alignment cleared'); + this.emit('zero', { aligned: false }); + return { aligned: false }; + } + + getAlignment() { + return this.#alignment ? { aligned: true, ...this.#alignment } : { aligned: false }; + } + + getStatus() { + return { alignment: this.getAlignment(), tle: this.getTleStatus() }; + } +} + diff --git a/services/telemetry.mjs b/services/telemetry.mjs new file mode 100644 index 0000000..a76186e --- /dev/null +++ b/services/telemetry.mjs @@ -0,0 +1,516 @@ + +// Telemetry service +// * Orientation: supervises the configured Python MPU script and tracks it with an explicit state machine. +// * Position: talks to gpsd over its JSON TCP protocol (no extra dependency). +// * Time: the OS clock (already disciplined by RTC/GPS), exposed via now(). +// +// Sensor state machine +// +// stopped ──start()──▶ starting ──first sample──▶ running ◀──sample──┐ +// │ │ │ +// │ exit / no data │ no sample │ +// ▼ ▼ for staleMs │ +// backoff ◀──── exit / stale too long ──────── stale +// │ +// └─ delay (1s,2s,4s … 30s) ─▶ starting +// +// Events: 'orientation', 'sensor-state', 'gps-state', 'gps' +import { EventEmitter } from 'node:events'; +import { spawn } from 'node:child_process'; +import readline from 'node:readline'; +import net from 'node:net'; + +const SENSOR_TRANSITIONS = { + stopped: ['starting'], + starting: ['running', 'backoff', 'stopped'], + running: ['stale', 'backoff', 'stopped'], + stale: ['running', 'backoff', 'stopped'], + backoff: ['starting', 'stopped'], +}; + +const isFiniteNum = (v) => typeof v === 'number' && Number.isFinite(v); + +function eulerToQuat(yaw, pitch, roll) { + const y = (yaw * Math.PI) / 360; + const p = (pitch * Math.PI) / 360; + const r = (roll * Math.PI) / 360; + const cy = Math.cos(y), sy = Math.sin(y); + const cp = Math.cos(p), sp = Math.sin(p); + const cr = Math.cos(r), sr = Math.sin(r); + return [ + sr * cp * cy - cr * sp * sy, + cr * sp * cy + sr * cp * sy, + cr * cp * sy - sr * sp * cy, + cr * cp * cy + sr * sp * sy, + ]; +} + + +export class TelemetryService extends EventEmitter { + #cfg; + #log; + + #sensor = { + state: 'stopped', + proc: null, + startedAt: 0, + lastSampleAt: 0, + runningSince: 0, + failures: 0, + restarts: 0, + lastError: null, + backoffTimer: null, + }; + #orientation = null; + #batteryTimer = null; + #batteryPolling = false; + #battery = { + state: 'unavailable', available: false, source: 'pisugar-server', socketPath: '/tmp/pisugar-server.sock', + voltageV: null, percent: null, percentEstimate: null, percentIsEstimate: false, + charging: null, powerPlugged: null, chargingAllowed: null, updatedAt: null, error: 'not polled yet', + }; + + #gps = { + socket: null, + connected: false, + retryTimer: null, + connectFailures: 0, + lastTpvAt: 0, + tpv: null, + sky: null, + lastGoodFix: null, + emittedState: 'disconnected', + }; + + #watchdog = null; + #stopping = true; + + constructor(cfg, { log }) { + super(); + this.#cfg = cfg; + this.#log = log; + } + + // ───────────────────────────── lifecycle ───────────────────────────── + + start() { + if (!this.#stopping) return; + this.#stopping = false; + this.#startSensor(); + this.#connectGps(); + this.#pollBattery().catch(() => {}); + if (this.#cfg.pisugar?.enabled !== false) { + this.#batteryTimer = setInterval(() => this.#pollBattery().catch(() => {}), this.#cfg.pisugar?.pollMs || 5000); + this.#batteryTimer.unref(); + } + this.#watchdog = setInterval(() => this.#tick(), 1000); + this.#watchdog.unref(); + } + + async stop() { + this.#stopping = true; + clearInterval(this.#watchdog); + clearInterval(this.#batteryTimer); + clearTimeout(this.#sensor.backoffTimer); + clearTimeout(this.#gps.retryTimer); + this.#transitionSensor('stopped', 'service stopped'); + + const proc = this.#sensor.proc; + this.#sensor.proc = null; + if (proc) { + await new Promise((resolve) => { + const t = setTimeout(() => proc.kill('SIGKILL'), 2000); + proc.once('close', () => { + clearTimeout(t); + resolve(); + }); + proc.kill('SIGTERM'); + }); + } + this.#gps.socket?.destroy(); + this.#gps.socket = null; + } + + // ───────────────────────────── public API ───────────────────────────── + + /** Current time. The OS clock is already synced to RTC/GPS. */ + now() { + return new Date(); + } + + /** + * Latest orientation, or null if the sensor is not delivering fresh data. + * @param {{maxAgeMs?: number}} [opts] + */ + getOrientation({ maxAgeMs = this.#cfg.staleMs } = {}) { + const o = this.#orientation; + if (!o) return null; + const ageMs = Date.now() - o.ts; + if (ageMs > maxAgeMs) return null; + return { yaw: o.yaw, pitch: o.pitch, roll: o.roll, quat: o.quat, ageMs, ts: o.ts }; + } + + /** Last good GPS fix (kept even if the fix is currently lost) or null if there has never been one. */ + getPosition() { + const f = this.#gps.lastGoodFix; + if (!f) return null; + const ageMs = Date.now() - f.at; + return { + lat: f.lat, + lon: f.lon, + altM: f.altM ?? 0, + mode: f.mode, + ageMs, + live: ageMs < this.#cfg.gpsStaleMs, + }; + } + + getSensorState() { + return this.#sensor.state; + } + + getGpsState() { + return this.#gpsStateNow(); + } + + getSnapshot() { + const now = Date.now(); + const s = this.#sensor; + const o = this.#orientation; + const g = this.#gps; + const pos = this.getPosition(); + return { + time: { iso: new Date(now).toISOString(), epochMs: now }, + sensor: { + state: s.state, + sampleAgeMs: s.lastSampleAt ? now - s.lastSampleAt : null, + restarts: s.restarts, + lastError: s.lastError, + }, + orientation: o + ? { yaw: o.yaw, pitch: o.pitch, roll: o.roll, quat: o.quat, ageMs: now - o.ts } + : null, + battery: { ...this.#battery }, + gps: { + state: this.#gpsStateNow(), + position: pos, + satellites: g.sky ? { used: g.sky.used, seen: g.sky.seen } : null, + dop: g.sky ? { hdop: g.sky.hdop, vdop: g.sky.vdop, pdop: g.sky.pdop } : null, + speedMps: g.tpv?.speed ?? null, + // GPS time minus system time. Should be a few ms if the OS sync is healthy. + clockSkewMs: g.tpv?.skewMs ?? null, + errorM: g.tpv ? { x: g.tpv.epx ?? null, y: g.tpv.epy ?? null, v: g.tpv.epv ?? null } : null, + }, + }; + } + + // ───────────────────────────── PiSugar battery ───────────────────────────── + + getBattery() { + return { ...this.#battery }; + } + + async #pisugarCommand(command) { + const path = this.#cfg.pisugar?.socketPath || '/tmp/pisugar-server.sock'; + return await new Promise((resolve, reject) => { + const socket = net.createConnection({ path }); + let output = ''; + let settled = false; + const finish = (err, value) => { + if (settled) return; + settled = true; + clearTimeout(timer); + socket.destroy(); + if (err) reject(err); + else resolve(value.trim()); + }; + const timer = setTimeout(() => finish(new Error(`PiSugar socket timed out for: ${command}`)), 1500); + socket.setEncoding('utf8'); + socket.on('connect', () => socket.write(`${command}\n`)); + socket.on('data', (chunk) => { + output += chunk; + const newline = output.indexOf('\n'); + if (newline >= 0) finish(null, output.slice(0, newline)); + }); + socket.on('error', (err) => finish(err)); + socket.on('end', () => finish(null, output)); + }); + } + + async #pollBattery() { + const cfg = this.#cfg.pisugar || {}; + if (cfg.enabled === false || this.#batteryPolling) return; + this.#batteryPolling = true; + + try { + const read = async (name) => { + const response = await this.#pisugarCommand(`get ${name}`); + const match = response.match(/:\s*(.+?)\s*$/); + if (!match) throw new Error(`Unexpected PiSugar response for get ${name}: ${response}`); + return match[1]; + }; + const [percentText, voltageText, pluggedText, allowChargingText] = await Promise.all([ + read('battery'), read('battery_v'), read('battery_power_plugged'), read('battery_allow_charging'), + ]); + const percent = Number(percentText); + const voltageV = Number(voltageText); + const powerPlugged = pluggedText.toLowerCase() === 'true'; + const chargingAllowed = allowChargingText.toLowerCase() === 'true'; + if (!Number.isFinite(percent) || !Number.isFinite(voltageV)) throw new Error('PiSugar returned invalid battery values'); + + this.#battery = { + state: 'ok', available: true, source: 'pisugar-server', + socketPath: cfg.socketPath || '/tmp/pisugar-server.sock', + voltageV: Math.round(voltageV * 1000) / 1000, + percent: Math.round(percent), percentEstimate: Math.round(percent), percentIsEstimate: false, + powerPlugged, chargingAllowed, charging: powerPlugged && chargingAllowed, + updatedAt: new Date().toISOString(), error: null, + }; + this.emit('battery', this.getBattery()); + } catch (err) { + const message = err.code === 'ENOENT' + ? `PiSugar socket unavailable (${cfg.socketPath || '/tmp/pisugar-server.sock'}); is pisugar-server running?` + : err.message; + const shouldLog = this.#battery.error !== message; + this.#battery = { + ...this.#battery, + state: this.#battery.updatedAt ? 'stale' : 'unavailable', + available: Boolean(this.#battery.updatedAt), + source: 'pisugar-server', socketPath: cfg.socketPath || '/tmp/pisugar-server.sock', error: message, + }; + if (shouldLog) this.#log.warn(`PiSugar battery read failed: ${message}`); + } finally { + this.#batteryPolling = false; + } + } + + // ───────────────────────────── sensor ───────────────────────────── + + #transitionSensor(next, reason) { + const s = this.#sensor; + if (s.state === next) return; + if (!SENSOR_TRANSITIONS[s.state]?.includes(next)) { + this.#log.debug(`ignored illegal sensor transition ${s.state} -> ${next}`); + return; + } + const prev = s.state; + s.state = next; + if (next === 'running') s.runningSince = Date.now(); + this.#log.info(`sensor ${prev} -> ${next}${reason ? ` (${reason})` : ''}`); + this.emit('sensor-state', { state: next, prev, reason }); + } + + #startSensor() { + if (this.#stopping) return; + const s = this.#sensor; + this.#transitionSensor('starting'); + s.startedAt = Date.now(); + s.lastSampleAt = 0; + s.runningSince = 0; + + let proc; + try { + proc = spawn(this.#cfg.python, [this.#cfg.script], { + stdio: ['ignore', 'pipe', 'pipe'], + env: { ...process.env, BNO_ADDR: String(this.#cfg.bnoAddress), BNO_HZ: String(this.#cfg.bnoHz) }, + }); + } catch (err) { + this.#sensorDied(null, `spawn failed: ${err.message}`); + return; + } + s.proc = proc; + + readline.createInterface({ input: proc.stdout }).on('line', (l) => this.#onSensorLine(l)); + readline.createInterface({ input: proc.stderr }).on('line', (l) => this.#onSensorStderr(l)); + proc.on('error', (err) => this.#sensorDied(proc, `process error: ${err.message}`)); + proc.on('exit', (code, signal) => this.#sensorDied(proc, `exited (code=${code}, signal=${signal})`)); + } + + #onSensorLine(line) { + let d; + try { + d = JSON.parse(line); + } catch { + this.#log.debug(`non-JSON from sensor: ${line.slice(0, 120)}`); + return; + } + if (![d.yaw, d.pitch, d.roll].every(isFiniteNum)) return; + const q = Array.isArray(d.quat) && d.quat.length === 4 && d.quat.every(isFiniteNum) + ? d.quat + : eulerToQuat(d.yaw, d.pitch, d.roll); + + const now = Date.now(); + this.#orientation = { yaw: d.yaw, pitch: d.pitch, roll: d.roll, quat: q, ts: now }; + this.#sensor.lastSampleAt = now; + + const st = this.#sensor.state; + if (st === 'starting' || st === 'stale') this.#transitionSensor('running', 'receiving samples'); + this.emit('orientation', this.#orientation); + } + + #onSensorStderr(line) { + let msg = line; + let level = 'warn'; + try { + const d = JSON.parse(line); + if (d.error) { + level = 'error'; + msg = d.error; + this.#sensor.lastError = String(d.error); + } else if (d.warning) { + msg = d.warning; + } + } catch { + /* plain traceback line */ + } + this.#log[level](`bno: ${msg}`); + } + + /** Called when the python process exits/errors. `proc` guards against double-handling. */ + #sensorDied(proc, reason) { + const s = this.#sensor; + if (proc && s.proc !== proc) return; // already handled + s.proc = null; + if (this.#stopping) return; + + s.lastError = reason; + // A process that ran healthily for a while resets the backoff. + if (s.runningSince && Date.now() - s.runningSince > 15000) s.failures = 0; + s.failures += 1; + s.restarts += 1; + + const delay = Math.min(30000, 1000 * 2 ** Math.min(s.failures - 1, 5)); + this.#transitionSensor('backoff', `${reason}; retry in ${delay / 1000}s`); + clearTimeout(s.backoffTimer); + s.backoffTimer = setTimeout(() => this.#startSensor(), delay); + } + + // ───────────────────────────── gpsd ───────────────────────────── + + #connectGps() { + if (this.#stopping) return; + const g = this.#gps; + const { gpsdHost: host, gpsdPort: port } = this.#cfg; + const sock = net.createConnection({ host, port }); + sock.setEncoding('utf8'); + sock.setKeepAlive(true, 10000); + g.socket = sock; + + let buf = ''; + sock.on('connect', () => { + g.connected = true; + g.connectFailures = 0; + this.#log.info(`gpsd connected (${host}:${port})`); + sock.write('?WATCH={"enable":true,"json":true}\n'); + this.#emitGpsStateIfChanged(); + }); + sock.on('data', (chunk) => { + buf += chunk; + let i; + while ((i = buf.indexOf('\n')) >= 0) { + const line = buf.slice(0, i).trim(); + buf = buf.slice(i + 1); + if (line) this.#onGpsLine(line); + } + if (buf.length > 1_000_000) buf = ''; + }); + sock.on('error', (err) => { + // Don't spam the dashboard if gpsd simply isn't running. + if (g.connectFailures === 0 || g.connectFailures % 20 === 0) { + this.#log.warn(`gpsd connection error: ${err.code || err.message}`); + } + }); + sock.on('close', () => { + if (g.socket === sock) g.socket = null; + const wasConnected = g.connected; + g.connected = false; + g.connectFailures += 1; + if (wasConnected) this.#log.warn('gpsd disconnected'); + this.#emitGpsStateIfChanged(); + if (this.#stopping) return; + clearTimeout(g.retryTimer); + g.retryTimer = setTimeout(() => this.#connectGps(), Math.min(10000, 2000 + g.connectFailures * 1000)); + }); + } + + #onGpsLine(line) { + let d; + try { + d = JSON.parse(line); + } catch { + return; + } + const g = this.#gps; + if (d.class === 'TPV') { + const now = Date.now(); + const tpv = { ...d, receivedAt: now }; + if (d.time) { + const t = Date.parse(d.time); + if (Number.isFinite(t)) tpv.skewMs = Math.round(t - now); + } + g.tpv = tpv; + g.lastTpvAt = now; + if (d.mode >= 2 && isFiniteNum(d.lat) && isFiniteNum(d.lon)) { + g.lastGoodFix = { + lat: d.lat, + lon: d.lon, + altM: [d.altMSL, d.altHAE, d.alt].find(isFiniteNum) ?? null, + mode: d.mode, + at: now, + }; + this.emit('gps', this.getPosition()); + } + this.#emitGpsStateIfChanged(); + } else if (d.class === 'SKY') { + const sats = Array.isArray(d.satellites) ? d.satellites : null; + g.sky = { + used: d.uSat ?? sats?.filter((s) => s.used).length ?? null, + seen: d.nSat ?? sats?.length ?? null, + hdop: d.hdop ?? null, + vdop: d.vdop ?? null, + pdop: d.pdop ?? null, + }; + } + } + + /** disconnected | no_gpsd_data | no_fix | fix_2d | fix_3d */ + #gpsStateNow() { + const g = this.#gps; + if (!g.connected) return 'disconnected'; + if (!g.tpv) return 'no_gpsd_data'; + if (Date.now() - g.lastTpvAt > this.#cfg.gpsStaleMs) return 'no_gpsd_data'; + if (g.tpv.mode === 3) return 'fix_3d'; + if (g.tpv.mode === 2) return 'fix_2d'; + return 'no_fix'; + } + + #emitGpsStateIfChanged() { + const now = this.#gpsStateNow(); + if (now === this.#gps.emittedState) return; + const prev = this.#gps.emittedState; + this.#gps.emittedState = now; + this.#log.info(`gps ${prev} -> ${now}`); + this.emit('gps-state', { state: now, prev }); + } + + // ───────────────────────────── watchdog ───────────────────────────── + + #tick() { + const now = Date.now(); + const s = this.#sensor; + const { staleMs, restartAfterMs, startTimeoutMs } = this.#cfg; + + if (s.state === 'running' && now - s.lastSampleAt > staleMs) { + this.#transitionSensor('stale', `no sample for ${now - s.lastSampleAt} ms`); + } else if (s.state === 'stale' && now - s.lastSampleAt > restartAfterMs) { + this.#log.warn('sensor stale too long; restarting python'); + s.proc?.kill('SIGKILL'); // 'exit' handler moves us to backoff + } else if (s.state === 'starting' && now - s.startedAt > startTimeoutMs) { + this.#log.warn('sensor produced no data after start; restarting python'); + s.proc?.kill('SIGKILL'); + } + + this.#emitGpsStateIfChanged(); // catches "TPV stopped arriving" + } +} +