-
Notifications
You must be signed in to change notification settings - Fork 0
/
angles.py
2094 lines (1698 loc) · 60.5 KB
/
angles.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding:utf-8 -*-
"""Classes for representing angles, and positions on a unit sphere.
This module provides three classes for representing angles: `Angle`,
`AlphaAngle` and `DeltaAngle`, and one class for representing a point
on a unit sphere, `AngularPosition`.
`Angle` is for representing generic angles. `AlphaAngle` is for
representing longitudinal angles such as geographic longitude, right
ascension and others. `DeltaAngle` is for representing latitudinal
angles such as geographic latitude, declination and others.
An angle object can be initialized with value in various units, it can
normalize its value into an appropriate range. The value can be
retrieved in various units, using appropriately named attributes.
Sexagesimal representation of an angle can be obtained through
appropriate attributes of the angle object. The number of decimal
places in the final part of a sexagesimal representation, and whether
rounding or truncation is used to produce these many decimal places,
can be customized.
An angle object can provide string representation of itself. The
delimiters used in the string representation can be customized. The
string representation is based on the sexagesimal value and hence it
also reflects the precision and truncation settings.
The `AngularPosition` class can be used for representing points on a
sphere. It uses an `AlphaAngle` instance for storing the longitudinal
angle, and a `DeltaAngle` instance for storing the latitudinal angle.
It can calcuate the separation and bearing, also called position angle,
to another point on the sphere. The results for separation and
bearing agree with those from the SLALIB (pyslalib) library (see the
function `_test_with_slalib()`).
The separation and bearing calculations do not use spherical
trignometry. They involve Cartesian vectors, and objects of the class
`CartesianVector` are used for these calculations.
Almost all the methods of the classes call functions for performing
calculations. If needed these functions can be used directly.
Functions include those for converting angles between different units,
parsing sexagesimal strings, creating string representations of angles,
converting angles between various units, normalizing angles into a
given range, finding separation and bearing bewteen two points and
others. Normalization of angles can be performed in two different
ways. One method normalizes angles in the manner that longitudinal
angles are normalized i.e., [0, 360.0) or [0, 2π) or [0, 24.0). The
other method normalizes angles in the manner that latitudinal angles
are normalized i.e., [-90, 90] or [-π/2, π/2].
See docstrings of classes and functions for documentation and examples.
:author: Prasanth Nair
:contact: prasanthhn@gmail.com
:license: BSD (http://www.opensource.org/licenses/bsd-license.php)
"""
import warnings
import math
import re
__version__ = "1.1"
def r2d(r):
"""Convert radians into degrees."""
return math.degrees(r)
def d2r(d):
"""Convert degrees into radians."""
return math.radians(d)
def h2d(h):
"""Convert hours into degrees."""
return h * 15.0
def d2h(d):
"""Convert degrees into hours."""
return d * (24.0 / 360.0)
def arcs2d(arcs):
"""Convert arcseconds into degrees."""
return arcs / 3600.0
def d2arcs(d):
"""Convert degrees into arcseconds."""
return d * 3600.0
def h2r(h):
"""Convert hours into radians."""
return d2r(h2d(h))
def r2h(r):
"""Convert radians into hours."""
return d2h(r2d(r))
def arcs2r(arcs):
"""Convert arcseconds into radians."""
return d2r(arcs2d(arcs))
def r2arcs(r):
"""Convert radians into arcseconds."""
return d2arcs(r2d(r))
def arcs2h(arcs):
"""Convert arcseconds into hours."""
return d2h(arcs2d(arcs))
def h2arcs(h):
"""Convert hours into arcseconds."""
return d2arcs(h2d(h))
def normalize(num, lower=0, upper=360, b=False):
"""Normalize number to range [lower, upper) or [lower, upper].
Parameters
----------
num : float
The number to be normalized.
lower : int
Lower limit of range. Default is 0.
upper : int
Upper limit of range. Default is 360.
b : bool
Type of normalization. Default is False. See notes.
Returns
-------
n : float
A number in the range [lower, upper) or [lower, upper].
Raises
------
ValueError
If lower >= upper.
Notes
-----
If the keyword `b == False`, then the normalization is done in the
following way. Consider the numbers to be arranged in a circle,
with the lower and upper ends sitting on top of each other. Moving
past one limit, takes the number into the beginning of the other
end. For example, if range is [0 - 360), then 361 becomes 1 and 360
becomes 0. Negative numbers move from higher to lower numbers. So,
-1 normalized to [0 - 360) becomes 359.
If the keyword `b == True`, then the given number is considered to
"bounce" between the two limits. So, -91 normalized to [-90, 90],
becomes -89, instead of 89. In this case the range is [lower,
upper]. This code is based on the function `fmt_delta` of `TPM`.
Range must be symmetric about 0 or lower == 0.
Examples
--------
>>> normalize(-270,-180,180)
90.0
>>> import math
>>> math.degrees(normalize(-2*math.pi,-math.pi,math.pi))
0.0
>>> normalize(-180, -180, 180)
-180.0
>>> normalize(180, -180, 180)
-180.0
>>> normalize(180, -180, 180, b=True)
180.0
>>> normalize(181,-180,180)
-179.0
>>> normalize(181, -180, 180, b=True)
179.0
>>> normalize(-180,0,360)
180.0
>>> normalize(36,0,24)
12.0
>>> normalize(368.5,-180,180)
8.5
>>> normalize(-100, -90, 90)
80.0
>>> normalize(-100, -90, 90, b=True)
-80.0
>>> normalize(100, -90, 90, b=True)
80.0
>>> normalize(181, -90, 90, b=True)
-1.0
>>> normalize(270, -90, 90, b=True)
-90.0
>>> normalize(271, -90, 90, b=True)
-89.0
"""
from math import floor, ceil
# abs(num + upper) and abs(num - lower) are needed, instead of
# abs(num), since the lower and upper limits need not be 0. We need
# to add half size of the range, so that the final result is lower +
# <value> or upper - <value>, respectively.
res = num
if not b:
if lower >= upper:
raise ValueError("Invalid lower and upper limits: (%s, %s)" %
(lower, upper))
res = num
if num > upper or num == lower:
num = lower + abs(num + upper) % (abs(lower) + abs(upper))
if num < lower or num == upper:
num = upper - abs(num - lower) % (abs(lower) + abs(upper))
res = lower if num == upper else num
else:
total_length = abs(lower) + abs(upper)
if num < -total_length:
num += ceil(num / (-2 * total_length)) * 2 * total_length
if num > total_length:
num -= floor(num / (2 * total_length)) * 2 * total_length
if num > upper:
num = total_length - num
if num < lower:
num = -total_length - num
res = num
res *= 1.0 # Make all numbers float, to be consistent
return res
def d2d(d):
"""Normalize angle in degree to [0, 360)."""
return normalize(d, 0, 360)
def h2h(h):
"""Normalize angle in hours to [0, 24.0)."""
return normalize(h, 0, 24)
def r2r(r):
"""Normalize angle in radians to [0, 2π)."""
return normalize(r, 0, 2 * math.pi)
def deci2sexa(deci, pre=3, trunc=False, lower=None, upper=None,
b=False, upper_trim=False):
"""Returns the sexagesimal representation of a decimal number.
Parameters
----------
deci : float
Decimal number to be converted into sexagesimal. If `lower` and
`upper` are given then the number is normalized to the given
range before converting to sexagesimal.
pre : int
The last part of the sexagesimal number is rounded to these
many decimal places. This can be negative. Default is 3.
trunc : bool
If True then the last part of the sexagesimal number is
truncated and not rounded to `pre` decimal places. Default is
False.
lower : int
Lower bound of range to which number is to be normalized.
upper : int
Upper bound of range to which number is to be normalized.
b : bool
Affects type of normalization. See docstring for `normalize`.
upper_trim : bool
If `lower` and `upper` are given and this is True, then if the
first part of the sexagesimal number is equal to `upper`, it is
replaced with `lower`. This converts numbers such as "24 00
00.000" to "00 00 00.000". Default value is False.
Returns
-------
s : 4 element tuple; (int, int, int, float)
A tuple of sign and the three parts of the sexagesimal
number. Sign is 1 for positive and -1 for negative values. The
sign applies to the whole angle and not to any single part,
i.e., all parts are positive and the sign multiplies the
angle. The first and second parts of the sexagesimal number are
integers and the last part is a float.
Notes
-----
The given decimal number `deci` is converted into a sexagesimal
number. The last part of the sexagesimal number is rounded to `pre`
number of decimal points. If `trunc == True` then instead of
rounding, the last part is truncated.
If `lower` and `upper` are given then the number is normalized to
the given range before converting into sexagesimal format. The `b`
argument determines the type of normalization. See docstring of the
`normalize` function for details.
If `upper_trim` is True then, if after convertion to sexagesimal
the first part is equal to `upper`, it is replaced with `lower`.
This is useful in cases where numbers such as "24 00 00.00" needs
to be converted into "00 00 00.00"
The returned sign, first element of tuple, applies to the whole
number and not just to a single part.
Examples
--------
>>> deci2sexa(-11.2345678)
(-1, 11, 14, 4.444)
>>> deci2sexa(-11.2345678, pre=5)
(-1, 11, 14, 4.44408)
>>> deci2sexa(-11.2345678, pre=4)
(-1, 11, 14, 4.4441)
>>> deci2sexa(-11.2345678, pre=4, trunc=True)
(-1, 11, 14, 4.444)
>>> deci2sexa(-11.2345678, pre=1)
(-1, 11, 14, 4.4)
>>> deci2sexa(-11.2345678, pre=0)
(-1, 11, 14, 4.0)
>>> deci2sexa(-11.2345678, pre=-1)
(-1, 11, 14, 0.0)
>>> x = 23+59/60.0+59.99999/3600.0
To 3 decimal places, this number is 24 or 0 hours.
>>> deci2sexa(x, pre=3, lower=0, upper=24, upper_trim=True)
(1, 0, 0, 0.0)
>>> deci2sexa(x, pre=3, lower=0, upper=24, upper_trim=False)
(1, 24, 0, 0.0)
To 5 decimal places, we get back the full value.
>>> deci2sexa(x, pre=5, lower=0, upper=24, upper_trim=True)
(1, 23, 59, 59.99999)
"""
if lower != None and upper != None:
deci = normalize(deci, lower=lower, upper=upper, b=b)
sign = 1
if deci < 0:
deci = abs(deci)
sign = -1
hd, f1 = divmod(deci, 1)
mm, f2 = divmod(f1 * 60.0, 1)
sf = f2 * 60.0
# Find the seconds part to required precision.
fp = 10 ** pre
if trunc:
ss, _ = divmod(sf * fp, 1)
else:
ss = round(sf * fp, 0)
ss = int(ss)
# If ss is 60 to given precision then update mm, and if necessary
# hd.
if ss == 60 * fp:
mm += 1
ss = 0
if mm == 60:
hd += 1
mm = 0
hd = int(hd)
mm = int(mm)
if lower != None and upper != None and upper_trim:
# For example 24h0m0s => 0h0m0s.
if hd == upper:
hd = lower
if hd == 0 and mm == 0 and ss == 0:
sign = 1
ss /= float(fp)
# hd and mm parts are integer values but of type float
return (sign, hd, mm, ss)
def sexa2deci(sign, hd, mm, ss, todeg=False):
"""Combine sexagesimal components into a decimal number.
Parameters
----------
sign : int
Sign of the number: 1 for +ve, -1 for negative.
hd : float
The hour or degree like part.
mm : float
The minute or arc-minute like part.
ss : float
The second or arc-second like part.
todeg : bool
If True then convert to degrees, assuming that the input value
is in hours. Default is False.
Returns
-------
d : float
The decimal equivalent of the sexagesimal number.
Raises
------
ValueError
This exception is raised if `sign` is not -1 or 1.
Notes
-----
The angle returned is::
sign * (hd + mm / 60.0 + ss / 3600.0)
In sexagesimal notation the sign applies to the whole quantity and
not to each part separately. So the `sign` is asked separately, and
applied to the whole quantity.
If the sexagesimal quantity is in hours, then we frequently want to
convert it into degrees. If the `todeg == True` then the given
value is assumed to be in hours, and the returned value will be in
degrees.
Examples
--------
>>> d = sexa2deci(1,12,0,0.0)
>>> d
12.0
>>> d = sexa2deci(1,12,0,0.0,todeg=True)
>>> d
180.0
>>> x = sexa2deci(1,9,12.456,0.0)
>>> assert round(x,4) == 9.2076
>>> x = sexa2deci(1,11,30,27.0)
>>> assert round(x, 4) == 11.5075
"""
divisors = [1.0, 60.0, 3600.0]
d = 0.0
# sexages[0] is sign.
if sign not in (-1, 1):
raise ValueError("Sign has to be -1 or 1.")
sexages = [sign, hd, mm, ss]
for i, divis in zip(sexages[1:], divisors):
d += i / divis
# Add proper sign.
d *= sexages[0]
if todeg:
d = h2d(d)
return d
def fmt_angle(val, s1=" ", s2=" ", s3=" ", pre=3, trunc=False,
lower=None, upper=None, b=False, upper_trim=False):
"""Return sexagesimal string of given angle in degrees or hours.
Parameters
----------
val : float
The angle (in degrees or hours) that is to be converted into a
sexagesimal string.
s1 : str
Character to be used between the first and second parts of the
the sexagesimal representation.
s2 : str
Character to be used between the second and third parts of the
the sexagesimal representation.
s3 : str
Character to be used after the third part of the sexagesimal
representation.
pre : int
The final part of the sexagesimal number is rounded to these
many decimal places. This can be negative.
trunc : bool
If True then the third part of the sexagesimal number is
truncated to `pre` decimal places, instead of rounding.
lower, upper : float
If `lower` and `upper` are given then the given value is
normalized into the this range before converting to sexagesimal
string.
b : bool
This affect how the normalization is performed. See notes. This
works exactly like that for the function `normalize()`.
upper_trim : bool
If `lower` and `upper` are given, then if the first part of the
sexagesimal number equals `upper`, it is replaced with
`lower`. For examples, "12 00 00" gets turned into "00 00
00".
See also
--------
normalize
deci2sexa
Examples
--------
>>> fmt_angle(12.348978659, pre=4, trunc=True)
'+12 20 56.3231 '
>>> fmt_angle(12.348978659, pre=5)
'+12 20 56.32317 '
>>> fmt_angle(12.348978659, s1='HH ', s2='MM ', s3='SS', pre=5)
'+12HH 20MM 56.32317SS'
>>> x = 23+59/60.0+59.99999/3600.0
>>> fmt_angle(x)
'+24 00 00.000 '
>>> fmt_angle(x, lower=0, upper=24, upper_trim=True)
'+00 00 00.000 '
>>> fmt_angle(x, pre=5)
'+23 59 59.99999 '
>>> fmt_angle(-x, lower=0, upper=24, upper_trim=True)
'+00 00 00.000 '
>>> fmt_angle(-x)
'-24 00 00.000 '
"""
# Don't normalize if range not given. 0 is valid.
if lower == None or upper == None:
n = val
else:
n = normalize(val, lower=lower, upper=upper, b=b)
x = deci2sexa(n, pre=pre, trunc=trunc, lower=lower, upper=upper,
upper_trim=upper_trim)
p = "{3:0" + "{0}.{1}".format(pre + 3, pre) + "f}" + s3
p = "{0}{1:02d}" + s1 + "{2:02d}" + s2 + p
return p.format("-" if x[0] < 0 else "+", *x[1:])
def phmsdms(hmsdms):
"""Parse a string containing a sexageismal number.
This can handle several types of delimiters and will process
reasonably valid strings. See examples.
Parameters
----------
hmsdms : str
String containing a sexagesimal number.
Returns
-------
d : dict
parts : a 3 element list of floats
The three parts of the sexagesimal number that were
identified.
vals : 3 element list of floats
The numerical values of the three parts of the sexagesimal
number.
sign : int
Sign of the sexagesimal number; 1 for positive and -1 for
negative.
units : {"degrees", "hours"}
The units of the sexagesimal number. This is infered from
the characters present in the string. If it a pure number
then units is "degrees".
Examples
--------
>>> phmsdms("12")
{'parts': [12.0, None, None],
'sign': 1,
'units': 'degrees',
'vals': [12.0, 0.0, 0.0]}
>>> phmsdms("12h")
{'parts': [12.0, None, None],
'sign': 1,
'units': 'hours',
'vals': [12.0, 0.0, 0.0]}
>>> phmsdms("12d13m14.56")
{'parts': [12.0, 13.0, 14.56],
'sign': 1,
'units': 'degrees',
'vals': [12.0, 13.0, 14.56]}
>>> phmsdms("12d13m14.56")
{'parts': [12.0, 13.0, 14.56],
'sign': 1,
'units': 'degrees',
'vals': [12.0, 13.0, 14.56]}
>>> phmsdms("12d14.56ss")
{'parts': [12.0, None, 14.56],
'sign': 1,
'units': 'degrees',
'vals': [12.0, 0.0, 14.56]}
>>> phmsdms("14.56ss")
{'parts': [None, None, 14.56],
'sign': 1,
'units': 'degrees',
'vals': [0.0, 0.0, 14.56]}
>>> phmsdms("12h13m12.4s")
{'parts': [12.0, 13.0, 12.4],
'sign': 1,
'units': 'hours',
'vals': [12.0, 13.0, 12.4]}
>>> phmsdms("12:13:12.4s")
{'parts': [12.0, 13.0, 12.4],
'sign': 1,
'units': 'degrees',
'vals': [12.0, 13.0, 12.4]}
But `phmsdms("12:13mm:12.4s")` will not work.
"""
units = None
sign = None
# Floating point regex:
# http://www.regular-expressions.info/floatingpoint.html
#
# pattern1: find a decimal number (int or float) and any
# characters following it upto the next decimal number. [^0-9\-+]*
# => keep gathering elements until we get to a digit, a - or a
# +. These three indicates the possible start of the next number.
pattern1 = re.compile(r"([-+]?[0-9]*\.?[0-9]+[^0-9\-+]*)")
# pattern2: find decimal number (int or float) in string.
pattern2 = re.compile(r"([-+]?[0-9]*\.?[0-9]+)")
hmsdms = hmsdms.lower()
hdlist = pattern1.findall(hmsdms)
parts = [None, None, None]
def _fill_right_not_none():
# Find the pos. where parts is not None. Next value must
# be inserted to the right of this. If this is 2 then we have
# already filled seconds part, raise exception. If this is 1
# then fill 2. If this is 0 fill 1. If none of these then fill
# 0.
rp = reversed(parts)
for i, j in enumerate(rp):
if j is not None:
break
if i == 0:
# Seconds part already filled.
raise ValueError("Invalid string.")
elif i == 1:
parts[2] = v
elif i == 2:
# Either parts[0] is None so fill it, or it is filled
# and hence fill parts[1].
if parts[0] is None:
parts[0] = v
else:
parts[1] = v
for valun in hdlist:
try:
# See if this is pure number.
v = float(valun)
# Sexagesimal part cannot be determined. So guess it by
# seeing which all parts have already been identified.
_fill_right_not_none()
except ValueError:
# Not a pure number. Infer sexagesimal part from the
# suffix.
if "hh" in valun or "h" in valun:
m = pattern2.search(valun)
parts[0] = float(valun[m.start():m.end()])
units = "hours"
if "dd" in valun or "d" in valun:
m = pattern2.search(valun)
parts[0] = float(valun[m.start():m.end()])
units = "degrees"
if "mm" in valun or "m" in valun:
m = pattern2.search(valun)
parts[1] = float(valun[m.start():m.end()])
if "ss" in valun or "s" in valun:
m = pattern2.search(valun)
parts[2] = float(valun[m.start():m.end()])
if "'" in valun:
m = pattern2.search(valun)
parts[1] = float(valun[m.start():m.end()])
if '"' in valun:
m = pattern2.search(valun)
parts[2] = float(valun[m.start():m.end()])
if ":" in valun:
# Sexagesimal part cannot be determined. So guess it by
# seeing which all parts have already been identified.
v = valun.replace(":", "")
v = float(v)
_fill_right_not_none()
if not units:
units = "degrees"
# Find sign. Only the first identified part can have a -ve sign.
for i in parts:
if i and i < 0.0:
if sign is None:
sign = -1
else:
raise ValueError("Only one number can be negative.")
if sign is None: # None of these are negative.
sign = 1
vals = [abs(i) if i is not None else 0.0 for i in parts]
return dict(sign=sign, units=units, vals=vals, parts=parts)
def pposition(hd, details=False):
"""Parse string into angular position.
A string containing 2 or 6 numbers is parsed, and the numbers are
converted into decimal numbers. In the former case the numbers are
assumed to be floats. In the latter case, the numbers are assumed
to be sexagesimal.
Parameters
----------
hd: str
String containing 2 or 6 numbers. The numbers can be spearated
with character or characters other than ".", "-", "+".
The string must contain either 2 or 6 numbers.
details: bool
The detailed result from parsing the string is returned. See
"Returns" section below.
Default is False.
Returns
-------
x: (float, float) or dict
A tuple containing decimal equivalents of the parsed numbers. If
the string contains 6 numbers then they are assumed be
sexagesimal components.
If ``details`` is True then a dictionary with the following keys
is returned:
x: float
The first number.
y: float
The second number
numvals: int
Number of items parsed; 2 or 6.
raw_x: dict
The result returned by ``phmsdms`` for the first number.
raw_y: dict
The result returned by ``phmsdms`` for the second number.
It is up to the user to interpret the units of the numbers
returned.
Raises
------
ValueError:
The exception is raised if the string cannot be interpreted as a
sequence of 2 or 6 numbers.
Examples
--------
The position of M100 reported by SIMBAD is
"12 22 54.899 +15 49 20.57". This can be easily parsed in the
following manner.
>>> from angles import pposition
>>> ra, de = pposition("12 22 54.899 +15 49 20.57")
>>> ra
12.381916388888889
>>> de
15.822380555555556
"""
# Split at any character other than a digit, ".", "-", and "+".
p = re.split(r"[^\d\-+.]*", hd)
if len(p) not in [2, 6]:
raise ValueError("Input must contain either 2 or 6 numbers.")
# Two floating point numbers if string has 2 numbers.
if len(p) == 2:
x, y = float(p[0]), float(p[1])
if details:
numvals = 2
raw_x = p[0]
raw_y = p[1]
# Two sexagesimal numbers if string has 6 numbers.
elif len(p) == 6:
x_p = phmsdms(" ".join(p[:3]))
x = sexa2deci(x_p['sign'], *x_p['vals'])
y_p = phmsdms(" ".join(p[3:]))
y = sexa2deci(y_p['sign'], *y_p['vals'])
if details:
raw_x = x_p
raw_y = y_p
numvals = 6
if details:
result = dict(x=x, y=y, numvals=numvals, raw_x=raw_x,
raw_y=raw_y)
else:
result = x, y
return result
def sep(a1, b1, a2, b2):
"""Angular spearation between two points on a unit sphere.
This will be an angle between [0, π] radians.
Parameters
----------
a1, b1 : float
Longitude-like and latitude-like angles defining the first
point. Both are in radians.
a2, b2 : float
Longitude-like and latitude-like angles defining the second
point. Both are in radians.
Notes
-----
The great cicle angular separation of the second point from the
first is returned as an angle in radians. the return value is
always in the range [0, π].
Results agree with those from SLALIB routine sla_dsep. See
_test_with_slalib().
Examples
--------
>>> r2d(sep(0, 0, 0, d2r(90.0)))
90.0
>>> r2d(sep(0, d2r(45.0), 0, d2r(90.0)))
45.00000000000001
>>> r2d(sep(0, d2r(-45.0), 0, d2r(90.0)))
135.0
>>> r2d(sep(0, d2r(-90.0), 0, d2r(90.0)))
180.0
>>> r2d(sep(d2r(45.0), d2r(-90.0), d2r(45.0), d2r(90.0)))
180.0
>>> r2d(sep(0, 0, d2r(90.0), 0))
90.0
>>> r2d(sep(0, d2r(45.0), d2r(90.0), d2r(45.0)))
60.00000000000001
>>> import math
>>> 90.0 * math.cos(d2r(45.0)) # Distance along latitude circle.
63.63961030678928
"""
# Tolerance to decide if the calculated separation is zero.
tol = 1e-15
v = CartesianVector()
v.from_s(1.0, a1, b1)
v2 = CartesianVector()
v2.from_s(1.0, a2, b2)
d = v.dot(v2)
c = v.cross(v2).mod
res = math.atan2(c, d)
if abs(res) < tol:
return 0.0
else:
return res
def bear(a1, b1, a2, b2):
"""Find bearing/position angle between two points on a unit sphere.
Parameters
----------
a1, b1 : float
Longitude-like and latitude-like angles defining the first
point. Both are in radians.
a2, b2 : float
Longitude-like and latitude-like angles defining the second
point. Both are in radians.
Notes
-----
Position angle of the second point with respect to the first
is returned in radians. Position angle is calculated clockwise
and counter-clockwise from the direction towards the North
pole. It is between [0 and π] if the second point is in the
eastern hemisphere w.r.t the first, and between (0, -π) if
the second point is in the western hemisphere w.r.t the first.
.. warning::
If the first point is at the pole then bearing is undefined and
0 is returned.
Results agree with those from SLALIB rountine sla_dbear. See
_test_with_slalib().
Examples
--------
>>> angles.bear(0, 0, 0, -angles.d2r(90.0))
3.141592653589793
>>> angles.bear(0, -angles.d2r(90.0), 0, 0)
0.0
>>> angles.bear(0, -angles.d2r(45.0), 0, 0)
0.0
>>> angles.bear(0, -angles.d2r(89.678), 0, 0)
0.0
>>> r2d(bear(angles.d2r(45.0), angles.d2r(45.0),
angles.d2r(60.0), angles.d2r(45.0)))
84.68152816060062
>>> r2d(bear(angles.d2r(45.0), angles.d2r(45.0),
angles.d2r(46.0), angles.d2r(45.0)))
89.64644212193384
>>> r2d(bear(angles.d2r(45.0), angles.d2r(45.0),
angles.d2r(44.0), angles.d2r(45.0)))
-89.64644212193421
"""
# Find perpendicular to the plane containing the base and
# z-axis. Then find the perpendicular to the plane containing
# the base and the target. The angle between these two is the
# position angle or bearing of the target w.r.t the base. Check
# sign of the z component of the latter vector to determine
# quadrant: 1st and 2nd quadrants are +ve while 3rd and 4th are
# negative.
#
# Tolerance to decide if first is on the pole and also to decide if
# the calculated bearing is zero.
tol = 1e-15
v1 = CartesianVector()
v1.from_s(1.0, a1, b1)
v2 = CartesianVector()
v2.from_s(1.0, a2, b2)
# Z-axis
v0 = CartesianVector()
v0.from_s(r=1.0, alpha=0.0, delta=d2r(90.0))
if abs(v1.cross(v0).mod) < tol:
# The first point is on the pole. Bearing is undefined.
warnings.warn(
"First point is on the pole. Bearing undefined.")
return 0.0
# Vector perpendicular to great circle containing two points.
v12 = v1.cross(v2)
# Vector perpendicular to great circle containing base and
# Z-axis.
v10 = v1.cross(v0)
# Find angle between these two vectors.
dot = v12.dot(v10)
cross = v12.cross(v10).mod
x = math.atan2(cross, dot)
# If z is negative then we are in the 3rd or 4th quadrant.
if v12.z < 0:
x = -x
if abs(x) < tol:
return 0.0
else:
return x
class Angle(object):
"""A class for representing angles, including string formatting.
This is the basic Angle object. The angle is initialized to the
given value. Default is 0 radians. This class will accept any
reasonably well formatted sexagesimal string representation, in
addition to numerical values.
The value of the angle in different units are available as
attributes. The angle object can be converted to a sexagesimal