1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
//! Coordinate transformations between different astronomical reference frames.
//!
//! This module provides transformations between equatorial (RA/Dec) and horizontal
//! (Alt/Az) coordinate systems. All functions properly handle error cases and validate
//! input coordinates.
//!
//! # Coordinate Systems
//!
//! - **Equatorial**: Fixed relative to the stars
//! - Right Ascension (RA): 0° to 360° measured eastward along celestial equator
//! - Declination (Dec): -90° to +90° measured from celestial equator
//!
//! - **Horizontal**: Fixed relative to observer on Earth
//! - Altitude: -90° to +90° above horizon
//! - Azimuth: 0° to 360° clockwise from north
//!
//! # Error Handling
//!
//! All functions validate their inputs and return `Result<T>` types. Common errors:
//! - `AstroError::InvalidCoordinate` for out-of-range RA or Dec values
use crateLocation;
use crate;
use cratejulian_date;
use ;
use PI;
use *;
/// Sanitize coordinate transformation results to prevent NaN/Infinity propagation
/// Sanitize RA/Dec transformation results
/// Converts equatorial coordinates (RA/DEC) to horizontal coordinates (Altitude/Azimuth)
/// for a given UTC time and observer location.
///
/// This uses the standard Meeus spherical trigonometry formulation:
/// - Computes **hour angle (HA)** from local **apparent sidereal time**
/// - Computes **altitude** and **azimuth** from HA, declination, and latitude
///
/// This method matches apparent sidereal time behavior (e.g. Astropy's `"apparent"` mode)
/// and is accurate to within arcseconds over multiple centuries.
///
/// # Arguments
///
/// - `ra_deg`: Right Ascension in degrees (0° to 360°)
/// - `dec_deg`: Declination in degrees (−90° to +90°)
/// - `datetime`: UTC datetime of observation
/// - `observer`: [Location](`Location`) containing lat/lon/alt
///
/// # Returns
///
/// A tuple `(altitude_deg, azimuth_deg)` in degrees:
/// - `altitude_deg`: Elevation above horizon (−90° to +90°)
/// - `azimuth_deg`: Degrees clockwise from true north (0° = North, 90° = East, etc.)
///
/// # Errors
///
/// Returns `Err(AstroError::InvalidCoordinate)` if:
/// - `ra_deg` is outside [0, 360)
/// - `dec_deg` is outside [-90, 90]
///
/// # Formulae
///
/// ```text
/// HA = LST - RA
/// Alt = arcsin(sin(Dec)·sin(Lat) + cos(Dec)·cos(Lat)·cos(HA))
/// Az = arccos((sin(Dec) - sin(Alt)·sin(Lat)) / (cos(Alt)·cos(Lat)))
/// ```
///
/// If `HA > 0` (object is west of the meridian), Azimuth is flipped:
/// ```text
/// Az = 360° − Az
/// ```
///
/// # Example
///
/// ```
/// use chrono::{Utc, TimeZone};
/// use astro_math::{Location, ra_dec_to_alt_az};
///
/// let dt = Utc.with_ymd_and_hms(2025, 4, 21, 19, 5, 6).unwrap();
/// let loc = Location {
/// latitude_deg: 39.0005,
/// longitude_deg: -92.3009,
/// altitude_m: 0.0,
/// };
///
/// // Vega (α Lyrae): RA = 279.2347°, Dec = +38.7837°
/// let (alt, az) = ra_dec_to_alt_az(279.2347, 38.7837, dt, &loc).unwrap();
///
/// // These will match Stellarium/Astropy to within ~0.1°
/// assert!(alt > 0.0 && alt < 10.0);
/// assert!(az > 300.0 && az < 360.0);
/// ```
///
/// # Error Example
///
/// ```
/// # use chrono::{Utc, TimeZone};
/// # use astro_math::{Location, ra_dec_to_alt_az, error::AstroError};
/// # let dt = Utc::now();
/// # let loc = Location { latitude_deg: 40.0, longitude_deg: -74.0, altitude_m: 0.0 };
/// // Invalid RA (must be < 360)
/// match ra_dec_to_alt_az(400.0, 45.0, dt, &loc) {
/// Err(AstroError::InvalidCoordinate { coord_type, value, .. }) => {
/// assert_eq!(coord_type, "RA");
/// assert_eq!(value, 400.0);
/// }
/// _ => panic!("Expected error"),
/// }
/// ```
/// Converts ICRS equatorial coordinates to horizontal coordinates using ERFA.
///
/// This provides the most accurate transformation using the IAU 2000/2006 models,
/// matching professional astronomy software like astropy.
///
/// # Arguments
///
/// - `ra_icrs`: ICRS right ascension in degrees (0° to 360°)
/// - `dec_icrs`: ICRS declination in degrees (-90° to +90°)
/// - `datetime`: UTC datetime of observation
/// - `observer`: Observer location
/// - `pressure_hpa`: Atmospheric pressure in hPa (default ~1013.25)
/// - `temperature_c`: Temperature in Celsius (default ~15°C)
/// - `humidity`: Relative humidity 0-1 (default 0.5)
///
/// # Returns
///
/// A tuple `(altitude_deg, azimuth_deg)` in degrees
///
/// # Note
///
/// This function includes:
/// - Frame bias and precession-nutation (IAU 2006)
/// - Earth rotation and polar motion
/// - Annual and diurnal aberration
/// - Atmospheric refraction (if pressure > 0)
/// Parallel batch conversion of equatorial coordinates to horizontal coordinates using ERFA.
///
/// This function processes multiple coordinate pairs in parallel using Rayon for maximum performance.
/// It's optimized for processing large datasets (thousands to millions of coordinates).
///
/// # Arguments
///
/// - `ra_dec_pairs`: Slice of (RA, Dec) coordinate pairs in degrees
/// - `datetime`: UTC datetime of observation
/// - `observer`: Observer location
/// - `pressure_hpa`: Atmospheric pressure in hPa (default 0 = no refraction, matching AstroPy)
/// - `temperature_c`: Temperature in Celsius (default 0°C)
/// - `humidity`: Relative humidity 0-1 (default 0.0)
///
/// # Returns
///
/// A vector of `(altitude_deg, azimuth_deg)` tuples in the same order as input
///
/// # Performance
///
/// This function uses Rayon for parallel processing and can achieve:
/// - Single-threaded: ~1000-5000 coords/sec (depending on hardware)
/// - Multi-threaded: Scales with CPU cores (e.g., 8-core = ~8x faster)
///
/// # Example
///
/// ```
/// use chrono::{Utc, TimeZone};
/// use astro_math::{Location, ra_dec_to_alt_az_batch_parallel};
///
/// let coords = vec![(0.0, 0.0), (90.0, 45.0), (180.0, -30.0)];
/// let dt = Utc.with_ymd_and_hms(2024, 1, 1, 0, 0, 0).unwrap();
/// let loc = Location {
/// latitude_deg: 40.0,
/// longitude_deg: -74.0,
/// altitude_m: 0.0,
/// };
///
/// let results = ra_dec_to_alt_az_batch_parallel(&coords, dt, &loc, None, None, None).unwrap();
/// assert_eq!(results.len(), 3);
/// ```
/// Converts horizontal coordinates (Altitude/Azimuth) to equatorial coordinates (RA/DEC)
/// for a given UTC time and observer location.
///
/// This is the inverse transformation of `ra_dec_to_alt_az`. It uses spherical trigonometry
/// to convert from the horizontal coordinate system (fixed to the observer) back to the
/// equatorial coordinate system (fixed relative to the stars).
///
/// The mathematical formulation follows standard astronomical practice:
/// 1. Convert altitude and azimuth to hour angle and declination
/// 2. Convert hour angle to right ascension using local sidereal time
///
/// # Arguments
///
/// - `altitude_deg`: Elevation above horizon in degrees (−90° to +90°)
/// - `azimuth_deg`: Degrees clockwise from true north (0° to 360°)
/// - `datetime`: UTC datetime of observation
/// - `observer`: [Location](`Location`) containing lat/lon/alt
///
/// # Returns
///
/// A tuple `(ra_deg, dec_deg)` in degrees:
/// - `ra_deg`: Right Ascension (0° to 360°)
/// - `dec_deg`: Declination (−90° to +90°)
///
/// # Errors
///
/// Returns `Err(AstroError::InvalidCoordinate)` if:
/// - `altitude_deg` is outside [-90, 90]
/// - `azimuth_deg` is outside [0, 360)
///
/// # Formulae
///
/// The spherical trigonometry formulae are:
/// ```text
/// sin(Dec) = sin(Alt)·sin(Lat) + cos(Alt)·cos(Lat)·cos(Az)
/// cos(HA) = (sin(Alt) - sin(Dec)·sin(Lat)) / (cos(Dec)·cos(Lat))
/// RA = LST - HA
/// ```
///
/// Where:
/// - Alt = altitude, Az = azimuth, Lat = observer latitude
/// - HA = hour angle, LST = local sidereal time
/// - Dec = declination, RA = right ascension
///
/// Special handling for quadrant ambiguity:
/// - Hour angle sign is determined from `sin(HA) = -sin(Az)·cos(Alt) / cos(Dec)`
/// - RA is normalized to [0, 360) range
///
/// # Example
///
/// ```
/// use chrono::{Utc, TimeZone};
/// use astro_math::{Location, alt_az_to_ra_dec};
///
/// let dt = Utc.with_ymd_and_hms(2025, 4, 21, 19, 5, 6).unwrap();
/// let loc = Location {
/// latitude_deg: 39.0005,
/// longitude_deg: -92.3009,
/// altitude_m: 0.0,
/// };
///
/// // Convert known alt/az back to RA/Dec
/// let (ra, dec) = alt_az_to_ra_dec(45.0, 120.0, dt, &loc).unwrap();
///
/// // Result should be valid equatorial coordinates
/// assert!(ra >= 0.0 && ra < 360.0);
/// assert!(dec >= -90.0 && dec <= 90.0);
/// ```
///
/// # Round-trip Example
///
/// ```
/// use chrono::{Utc, TimeZone};
/// use astro_math::{Location, ra_dec_to_alt_az, alt_az_to_ra_dec};
///
/// let dt = Utc.with_ymd_and_hms(2024, 6, 21, 12, 0, 0).unwrap();
/// let loc = Location {
/// latitude_deg: 40.0,
/// longitude_deg: -74.0,
/// altitude_m: 0.0,
/// };
///
/// // Start with known RA/Dec
/// let original_ra = 279.23473479; // Vega
/// let original_dec = 38.78368896;
///
/// // Convert to alt/az and back
/// let (alt, az) = ra_dec_to_alt_az(original_ra, original_dec, dt, &loc).unwrap();
/// let (ra, dec) = alt_az_to_ra_dec(alt, az, dt, &loc).unwrap();
///
/// // Should recover original coordinates (within numerical precision)
/// assert!((ra - original_ra).abs() < 1e-6);
/// assert!((dec - original_dec).abs() < 1e-6);
/// ```
// Note: ERFA does not provide a direct single-function inverse transformation
// from observed coordinates (alt/az) to ICRS coordinates. The Atio13 function
// transforms from CIRS to observed, not the reverse. For highest accuracy
// inverse transformations, multiple ERFA steps would be needed, but for
// practical astronomical applications, the basic alt_az_to_ra_dec function
// provides excellent accuracy (sub-arcsecond round-trip precision).