-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathpycf3.py
1146 lines (930 loc) · 35.2 KB
/
pycf3.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2019, Juan B Cabral
# License: BSD-3-Clause
# Full Text: https://github.com/quatrope/pycf3/blob/master/LICENSE
# =============================================================================
# DOCS
# =============================================================================
"""Python client for several cosmic distance calculators.
Calculators:
- Cosmicflows-3 Distance-Velocity Calculator at distances
- Numerical Action Methods model
More information: http://edd.ifa.hawaii.edu/CF3calculator/
For citation check:
https://github.com/quatrope/pycf3/blob/master/README.rst
"""
__all__ = [
"AbstractClient",
"NAM",
"CF3",
"Result",
"NoCache",
"RetrySession",
"CFDeprecationWarning",
"MixedCoordinateSystemError",
]
__version__ = "2022.11"
# =============================================================================
# IMPORTS
# =============================================================================
import itertools as it
import json
import os
import typing as t
from collections import namedtuple
from collections.abc import MutableMapping
from enum import Enum
import attr
from custom_inherit import DocInheritMeta
from deprecated import deprecated
import diskcache as dcache
import numpy as np
import requests
from requests.packages.urllib3.util.retry import Retry
import tabulate
# =============================================================================
# CONSTANTS
# =============================================================================
class CoordinateSystem(Enum):
equatorial = "equatorial"
galactic = "galactic"
supergalactic = "supergalactic"
class Parameter(Enum):
distance = "distance"
velocity = "velocity"
ALPHA = {
CoordinateSystem.equatorial: "ra",
CoordinateSystem.galactic: "glon",
CoordinateSystem.supergalactic: "sgl",
}
ALPHA_TO_COORDINATE = {v: k for k, v in ALPHA.items()}
DELTA = {
CoordinateSystem.equatorial: "dec",
CoordinateSystem.galactic: "glat",
CoordinateSystem.supergalactic: "sgb",
}
DELTA_TO_COORDINATE = {v: k for k, v in DELTA.items()}
ALPHA_DELTA_TO_COORDINATE = dict(
it.chain(ALPHA_TO_COORDINATE.items(), DELTA_TO_COORDINATE.items())
)
PYCF3_DATA = os.path.expanduser(os.path.join("~", "pycf3_data"))
DEFAULT_CACHE_DIR = os.path.join(PYCF3_DATA, "_cache_")
RESULT_HTML_TEMPLATE = """
<div class="result-container" id="result-{{ id_result }}">
<div class="result-css">
<style>
.observed {
color: #dc3545! important;
}
.adjusted {
color: #28a745!important;
}
tablr.result-table, div.result-raw {
width: 100%;
}
table.result-table tr{
pointer-events: none;
background-color: inherit !important;
}
.result-container code{
color: #e83e8c;
background-color: inherit !important;
}
.result-container .hidden {
display: none;
}
div.result-raw {
background-color: #333 !important;
}
</style>
</div>
<div class="result-container container-fluid">
<table class="result-table">
<thead>
<th colspan=3>
Result - <small><code>{{ call_result }}</code></small>
</th>
</thead>
<tbody>
<tr>
<th rowspan=2 class="observed">Observed</th>
<td>Distance (Mpc)</td>
<td>
{{ result.observed_distance_ }}
</td>
</tr>
<tr>
<td>Velocity (Km/s)</td>
<td>
{{ result.observed_velocity_ }}
</td>
</tr>
{% if result.adjusted_distance_ or result.adjusted_velocity_ %}
<tr>
<th rowspan=2 class="adjusted">Adjusted</th>
<td>Distance (Mpc)</td>
<td>
{{ result.adjusted_distance_ }}
</td>
</tr>
<tr>
<td>Velocity (Km/s)</td>
<td>
{{ result.adjusted_velocity_ }}
</td>
</tr>
{% endif %}
</tbody>
</table>
<div class="">
<a onclick="return showRaw{{ id_result }}();" href="#">
Show/Hide Raw
</a>
<div class="result-raw">
<code id="result-code-{{ id_result }}" class="hidden">
{{ json_result }}
</code>
</div>
</div>
</div>
<div class="result-js">
<script>
function showRaw{{ id_result }}(){
var showed = document.getElementById(
"result-code-{{ id_result }}"
).classList.toggle("hidden");
return false;
}
</script>
</div>
</div>
"""
# =============================================================================
# EXCEPTIONS
# =============================================================================
class MixedCoordinateSystemError(ValueError):
"""Raised when the parameters are from different coordinates systems."""
class CFDeprecationWarning(DeprecationWarning):
"""Custom class to inform that some functionality is in desuse."""
# =============================================================================
# RETRY SESSION IMPLEMENTATION
# =============================================================================
class RetrySession(requests.Session):
r"""Session with retry.
Parameters
----------
retries: ``int`` (default: ``3``)
Total number of retries to allow.
It's a good idea to set this to some sensibly-high value to
account for unexpected edge cases and avoid infinite retry loops.
Set to ``0`` to fail on the first retry.
backoff_factor: ``float`` (default: ``0.3``)
A backoff factor to apply between attempts after the second try (most
errors are resolved immediately by a second try without a delay).
urllib3 will sleep for:
``{backoff factor} * (2 ** ({number of total retries} - 1))``
seconds. If the backoff_factor is ``0.1``, then ``sleep()`` will
sleep for ``[0.0s, 0.2s, 0.4s, ...]`` between retries. It will never be
longer than ``urllib3.Retry.BACKOFF_MAX``.
status_forcelist: iterable (default: ``500, 502, 504``)
A set of integer HTTP status codes that we should force a retry on. A
retry is initiated if the request method is in method_whitelist and the
response status code is in status_forcelist.
By default, this is ``500, 502, 504``.
"""
def __init__(
self,
retries=3,
backoff_factor=0.3,
status_forcelist=(500, 502, 504),
**session_options,
):
"""Create a new instance."""
super().__init__(**session_options)
retries = retries or 0
self.retry_ = Retry(
total=retries,
read=retries,
connect=retries,
backoff_factor=backoff_factor,
status_forcelist=status_forcelist,
)
self.adapter_ = requests.adapters.HTTPAdapter(max_retries=self.retry_)
self.mount("http://", self.adapter_)
self.mount("https://", self.adapter_)
self.total_backoff_ = float(backoff_factor) * (2 ** (retries - 1))
# =============================================================================
# NO CACHE CLASS
# =============================================================================
class NoCache(MutableMapping):
"""Implements a minimalist no-cache for disk-cache."""
def get(self, key, default=None, *args, **kwargs):
"""Return the ``default``."""
return default
def set(self, key, value, *args, **kwargs):
"""Return True."""
return True
def expire(self, now=None, retry=False):
"""Return 0."""
return 0
def __len__(self):
"""Return 0."""
return 0
def __enter__(self):
"""Enter the runtime context related to this object.
The with statement will bind this method’s return value to the
target(s) specified in the as clause of the statement, if any.
"""
return self
def __exit__(self, exc_type, exc_value, traceback):
"""Exit the runtime context related to this object.
The parameters describe the exception that caused the context to be
exited. If the context was exited without an exception, all three
arguments will be None.
"""
pass
def __delitem__(self, k):
"""Raise KeyError."""
raise KeyError(k)
def __getitem__(self, k):
"""Raise KeyError."""
raise KeyError(k)
def __iter__(self):
"""Return an empty iterator."""
return iter({})
def __setitem__(self, k, v):
"""Do nothing."""
pass
# =============================================================================
# RESPONSE OBJECT
# =============================================================================
CalculatedAt = namedtuple(
"CalculatedAt", ["ra", "dec", "glon", "glat", "sgl", "sgb"]
)
@attr.s(eq=False, order=False, frozen=True, repr=False)
class Result:
r"""Parsed result.
Parameters
----------
calculator : ``str``
The used calculator.
url : ``str``
The url of the calculator.
coordinate : ``Coordinate``
Coordinate system used to create this result.
alpha : ``int`` or ``float``
:math:`\alpha` value for the coordinate system.
delta : ``int`` or ``float``
:math:`\delta` value for the coordinate system.
distance : ``int``, ``float`` or ``None``
Distance used to calculate the velocity in Mpc.
velocity : ``int``, ``float`` or ``None``
Velocity used to calculate the distance in Km/s.
Attributes
----------
response_ : ``requests.Response``
Original response object create by the *requests* library.
More information: https://2.python-requests.org
observed_distance_: ``numpy.ndarray``
Observed distances.
observed_velocity_: ``float``
Observed velocity
adjusted_distance_: ``numpy.ndarray``
Cosmologically adjusted distances.
adjusted_velocity_: ``float``
Cosmologically adjusted velocity, :math:`V^c_{ls}`.
calculated_at_: ``pycf3.CalculatedAt``
Coordinates in all the three supported systems.
"""
calculator = attr.ib()
url = attr.ib(repr=False)
coordinate = attr.ib()
calculated_by = attr.ib()
alpha = attr.ib()
delta = attr.ib()
distance = attr.ib()
velocity = attr.ib()
response_ = attr.ib(repr=False)
observed_distance_ = attr.ib(init=False, repr=False)
observed_velocity_ = attr.ib(init=False, repr=False)
adjusted_distance_ = attr.ib(init=False, repr=False)
adjusted_velocity_ = attr.ib(init=False, repr=False)
calculated_at_ = attr.ib(init=False, repr=False)
# =========================================================================
# INTERNAL
# =========================================================================
def _get_call_result(self):
alpha_name, delta_name = ALPHA[self.coordinate], DELTA[self.coordinate]
value = (
self.distance
if self.calculated_by == Parameter.distance
else self.velocity
)
call_result = (
f"{self.calculator}("
f"{self.calculated_by.value}={value}, "
f"{alpha_name}={self.alpha}, "
f"{delta_name}={self.delta})"
)
return call_result
def __repr__(self):
"""x.__repr__() <==> repr(x)."""
# header
call_result = self._get_call_result()
header = f"Result - {call_result}"
# body
table = []
table.append(
[
"Observed\n\n",
"Distance (Mpc)\nVelocity (Km/s)",
f"{self.observed_distance_}\n{self.observed_velocity_}",
]
)
if self.adjusted_distance_ or self.adjusted_velocity_:
table.append(
[
"Adjusted\n\n",
"Distance (Mpc)\nVelocity (Km/s)",
f"{self.adjusted_distance_}\n{self.adjusted_velocity_}",
]
)
body = tabulate.tabulate(table, headers="", tablefmt="grid")
# merge and return
return f"{header}\n{body}"
def _repr_html_(self):
"""Create an HTML representation of the result.
Mostly used inside jupyter environment.
"""
import jinja2 # noqa
call_result = self._get_call_result()
id_result = str(id(self) + np.random.random()).replace(".", "rr")
params = {
"result": self,
"id_result": id_result,
"call_result": call_result,
"json_result": json.dumps(self.json_, indent=2),
}
return jinja2.Template(RESULT_HTML_TEMPLATE).render(**params)
@property
def json_(self):
"""Proxy to ``response_.json()``."""
return self.response_.json()
@observed_distance_.default
def _observed_distance_default(self):
if "observed" in self.json_:
return np.array(self.json_["observed"]["distance"])
return np.array(self.json_["distance"])
@observed_velocity_.default
def _observed_velocity_default(self):
if "observed" in self.json_:
return self.json_["observed"]["velocity"]
return self.json_["velocity"]
@adjusted_distance_.default
def _adjusted_distance_default(self):
try:
return np.array(self.json_["adjusted"]["distance"])
except KeyError:
return None
@adjusted_velocity_.default
def _adjusted_velocity_default(self):
try:
return self.json_["adjusted"]["velocity"]
except KeyError:
return None
@calculated_at_.default
def _calculated_at_default(self):
data = self.json_
return CalculatedAt(
ra=data["RA"],
dec=data["Dec"],
glon=data["Glon"],
glat=data["Glat"],
sgl=data["SGL"],
sgb=data["SGB"],
)
# =========================================================================
# DEPRECATED API
# =========================================================================
@property
@deprecated(
category=CFDeprecationWarning,
action="once",
reason="Use `calculated_by` instead",
version="2020.12",
)
def search_by(self):
"""Proxy to ``response.calculated_by``.
.. deprecated:: 2020.12
"Use `calculated_by` instead"
"""
return self.calculated_by
@property
@deprecated(
category=CFDeprecationWarning,
action="once",
reason="Use `calculated_at_` instead",
version="2020.12",
)
def search_at_(self):
"""Proxy to ``response.calculated_at_``.
.. deprecated:: 2020.12
"Use `calculated_at` instead"
"""
return self.calculated_at_
# =============================================================================
# ABSTRACT CLIENT
# =============================================================================
@attr.s(eq=False, order=False, frozen=True, repr=False)
class AbstractClient(metaclass=DocInheritMeta(style="numpy")):
"""Abstract base class for all clients.
Parameters
----------
session : ``pycf3.Session`` (default: ``None``)
The session to use to send the requests. By default a
``pyc3.RetrySession`` with 3 retry is created. More info:
https://2.python-requests.org,
https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html.
cache : ``diskcache.Cache``, ``diskcache.Fanout``,
``pycf3.NoCache`` or ``None`` (default: ``None``)
Any instance of ``diskcache.Cache``, ``diskcache.Fanout`` or
``None`` (Default). If it's ``None`` a ``diskcache.Cache`` istance
is created with the parameter ``directory = pycf3.DEFAULT_CACHE_DIR``.
More information: http://www.grantjenks.com/docs/diskcache
cache_expire : ``float`` or None (default=``None``)
Seconds until item expires (default ``None``, no expiry)
More information: http://www.grantjenks.com/docs/diskcache
"""
session: requests.Session = attr.ib(factory=RetrySession, repr=False)
cache: t.Union[dcache.Cache, dcache.FanoutCache] = attr.ib()
cache_expire: float = attr.ib(default=None, repr=False)
@cache.default
def _cache_default(self):
return dcache.Cache(directory=DEFAULT_CACHE_DIR)
def _determine_coordinate_system(self, ra, dec, glon, glat, sgl, sgb):
# first we put all the parameters in a single dictionary
params = {
"ra": ra,
"dec": dec,
"glon": glon,
"glat": glat,
"sgl": sgl,
"sgb": sgb,
}
# next we remove all keys with the default value `None`
params = {k: v for k, v in params.items() if v is not None}
# if we have 0 values no coordinate was given
if len(params) == 0:
raise ValueError(
"No coordinate was provided. "
"Please provide (ra, dec)', '(glon, glat)' or '(sgl, sgb)'."
)
# if we only have one we need to check wich one and inform about
# the mising companinon
if len(params) == 1:
pname = list(params.keys())[0]
coordinate_system, companion_dict = (
(ALPHA_TO_COORDINATE[pname], DELTA)
if pname in ALPHA_TO_COORDINATE
else (DELTA_TO_COORDINATE[pname], ALPHA)
)
companion = companion_dict[coordinate_system]
raise ValueError(f"No {companion} provided")
# if we have more than two parameter we have mixed coordinate system
if len(params) > 2:
raise MixedCoordinateSystemError(", ".join(params))
# now we need to detemine the coordinate system
coordinate_system_candidates = {
ALPHA_DELTA_TO_COORDINATE[p] for p in params.keys()
}
# if we have more than 1 candidate we mix coordinates again
if len(coordinate_system_candidates) > 1:
raise MixedCoordinateSystemError(", ".join(params))
# we have one coordinate system and we need to dermermine which
# is alpha and wich is delta
coordinate_system = coordinate_system_candidates.pop()
alpha_coordinate_name = ALPHA[coordinate_system]
delta_coordinate_name = DELTA[coordinate_system]
alpha = params[alpha_coordinate_name]
delta = params[delta_coordinate_name]
return coordinate_system, alpha, delta
def _search(
self,
coordinate_system,
alpha,
delta,
distance,
velocity,
**get_kwargs,
):
# The validations
if coordinate_system not in CoordinateSystem:
raise TypeError(
"coordinate_system must be a member of "
"pycf3.core.CoordinateSystem enum"
)
if not isinstance(alpha, (int, float)):
raise TypeError(f"{ALPHA[coordinate_system]} must be int or float")
if not isinstance(delta, (int, float)):
raise TypeError(f"{DELTA[coordinate_system]} must be int or float")
elif not (-90 <= delta <= 90):
raise ValueError(
f"{DELTA[coordinate_system]} must be >= -90 and <= 90"
)
if (distance, velocity) == (None, None):
raise ValueError(
"You must provide the distance or the velocity value"
)
elif distance is not None and velocity is not None:
raise ValueError(
"You cant provide velocity and distance at the same time"
)
if distance is not None:
if not isinstance(distance, (int, float)):
raise TypeError("'distance' must be int or float")
elif not (0 < distance <= self.MAX_DISTANCE):
raise ValueError(
f"'distance' must be > 0 and <= {self.MAX_DISTANCE}"
)
parameter, value = Parameter.distance, distance
elif velocity is not None:
if not isinstance(velocity, (int, float)):
raise TypeError("'velocity' must be int or float")
elif not (0 < velocity <= self.MAX_VELOCITY):
raise ValueError(
f"'velocity' must be > 0 and <= {self.MAX_VELOCITY}"
)
parameter, value = Parameter.velocity, velocity
payload = {
"coordinate": [float(alpha), float(delta)],
"system": coordinate_system.value,
"parameter": parameter.value,
"value": float(value),
}
# start the cache orchestration
base = (
self.CALCULATOR,
coordinate_system.value,
)
key = dcache.core.args_to_key(
base=base, args=(self.URL,), kwargs=payload, typed=False, ignore=[]
)
with self.cache as cache:
cache.expire()
response = cache.get(key, default=dcache.core.ENOVAL, retry=True)
if response == dcache.core.ENOVAL:
response = self.session.get(
self.URL, json=payload, **get_kwargs
)
response.raise_for_status()
cache.set(
key,
response,
expire=self.cache_expire,
tag="@".join(key[:2]),
retry=True,
)
result = Result(
calculator=self.CALCULATOR,
url=self.URL,
coordinate=coordinate_system,
calculated_by=parameter,
alpha=alpha,
delta=delta,
distance=distance,
velocity=velocity,
response_=response,
)
return result
# =========================================================================
# INTERNALS
# =========================================================================
def __repr__(self):
"""x.__repr__() <==> repr(x)."""
cls = type(self).__name__
calculator = f"calculator='{self.CALCULATOR}'"
cachedir = f"cache_dir='{getattr(self.cache, 'directory', '')}'"
expire = f"cache_expire={self.cache_expire}"
return f"{cls}({calculator}, {cachedir}, {expire})"
# =========================================================================
# API
# =========================================================================
def calculate_distance(
self,
velocity,
*,
ra=None,
dec=None,
glon=None,
glat=None,
sgl=None,
sgb=None,
**get_kwargs,
):
"""Calculate a distance based on the given velocity and location.
The mandatory parameters are ``velocity`` and a position
expressed in two components depending on the chosen coordinate system:
- ``ra`` and ``dec`` for an equatorial system.
- ``glon`` and ``glat`` for a galactic system.
- ``sgl`` and ``sgb`` for a supergalactic system.
Coordinates cannot be mixed between systems, and must be expressed in
J2000 as 360° decimal.
The returned distance(s) are expressed in Mpc, and potentially can
be more than one value.
Parameters
----------
velocity : ``int`` or ``float``
Model velocity in km/s.
ra : ``int`` or ``float`` (optional)
Right ascension. If you provide ``ra`` you need to provide also
``dec``.
dec : ``int`` or ``float`` (optional)
Declination. ``dec`` must be >= -90 and <= 90. If you provide
``dec`` you need to provide also ``ra``.
glon : ``int`` or ``float`` (optional)
Galactic longitude. If you provide ``glon`` you need to provide
also ``glat``.
glat: ``int`` or ``float`` (optional)
Galactic latitude. ``glat`` must be >= -90 and <= 90. If you
provide ``glat`` you need to provide also ``glon``.
sgl : ``int`` or ``float`` (optional)
Super-galactic longitude. If you provide ``sgl`` you need to
provide also ``sgb``.
sgb: ``int`` or ``float`` (optional)
Super-galactic latitude. ``sgb`` must be >= -90 and <= 90.
If you provide ``sgb`` you need to provide also ``sgl``.
get_kwargs:
Optional arguments that ``request.get`` takes.
Returns
-------
pycf3.Result :
Result object that automatically parses the entire model
returned by the remote calculator.
"""
coordinate_system, alpha, delta = self._determine_coordinate_system(
ra=ra, dec=dec, glon=glon, glat=glat, sgl=sgl, sgb=sgb
)
response = self._search(
coordinate_system=coordinate_system,
alpha=alpha,
delta=delta,
distance=None,
velocity=velocity,
**get_kwargs,
)
return response
def calculate_velocity(
self,
distance,
*,
ra=None,
dec=None,
glon=None,
glat=None,
sgl=None,
sgb=None,
**get_kwargs,
):
"""Calculate a velocity based on the given distance and location.
The mandatory parameters are ``distance`` and a position
expressed in two components depending on the chosen coordinate system:
- ``ra`` and ``dec`` for an equatorial system.
- ``glon`` and ``glat`` for a galactic system.
- ``sgl`` and ``sgb`` for a supergalactic system.
Coordinates cannot be mixed between systems, and must be expressed in
J2000 as 360° decimal.
The returned velocity are expressed in Km/s.
Parameters
----------
distance : ``int`` or ``float``
Distance(s) in Mpc.
ra : ``int`` or ``float`` (optional)
Right ascension. If you provide ``ra`` you need to provide also
``dec``.
dec : ``int`` or ``float`` (optional)
Declination. ``dec`` must be >= -90 and <= 90. If you provide
``dec`` you need to provide also ``ra``.
glon : ``int`` or ``float`` (optional)
Galactic longitude. If you provide ``glon`` you need to provide
also ``glat``.
glat: ``int`` or ``float`` (optional)
Galactic latitude. ``glat`` must be >= -90 and <= 90. If you
provide ``glat`` you need to provide also ``glon``.
sgl : ``int`` or ``float`` (optional)
Super-galactic longitude. If you provide ``sgl`` you need to
provide also ``sgb``.
sgb: ``int`` or ``float`` (optional)
Super-galactic latitude. ``sgb`` must be >= -90 and <= 90.
If you provide ``sgb`` you need to provide also ``sgl``.
get_kwargs:
Optional arguments that ``request.get`` takes.
Returns
-------
pycf3.Result :
Result object that automatically parses the entire model
returned by the remote calculator.
"""
coordinate_system, alpha, delta = self._determine_coordinate_system(
ra=ra, dec=dec, glon=glon, glat=glat, sgl=sgl, sgb=sgb
)
response = self._search(
coordinate_system=coordinate_system,
alpha=alpha,
delta=delta,
distance=distance,
velocity=None,
**get_kwargs,
)
return response
# =========================================================================
# OLD API
# =========================================================================
@deprecated(
category=CFDeprecationWarning,
action="once",
reason="Use `calculate_velocity` or `calculate_distance` instead",
version="2020.12",
)
def equatorial_search(
self,
ra=187.78917,
dec=13.33386,
distance=None,
velocity=None,
**get_kwargs,
):
"""Search by equatorial coordinates.
The coordinates are expressed in J2000 as 360° decimal.
.. deprecated:: 2020.12
"Use `calculate_velocity` or `calculate_distance` instead"
Parameters
----------
ra : ``int`` or ``float`` (default: ``187.78917``)
Right ascension.
dec : ``int`` or ``float`` (default: ``13.33386``)
Declination. dec must be >= -90 and <= 90
distance : ``int``, ``float`` or ``None`` (default: ``None``)
Distance(s) in Mpc.
velocity : ``int``, ``float`` or ``None`` (default: ``None``)
Velocity in km/s. The returned distance potentially can be more
than ine value.
get_kwargs:
Optional arguments that ``request.get`` takes.
Returns
-------
pycf3.Result :
Result object that automatically parses the entire model
returned by the remote calculator.
"""
response = self._search(
CoordinateSystem.equatorial,
alpha=ra,
delta=dec,
distance=distance,
velocity=velocity,
**get_kwargs,
)
return response
@deprecated(
category=CFDeprecationWarning,
action="once",
reason="Use `calculate_velocity` or `calculate_distance` instead",
version="2020.12",
)
def galactic_search(
self,
glon=282.96547,
glat=75.41360,
distance=None,
velocity=None,
**get_kwargs,
):
"""Search by galactic coordinates.
The coordinates are expressed in J2000 as 360° decimal.
.. deprecated:: 2020.12
"Use `calculate_velocity` or `calculate_distance` instead"
Parameters
----------
glon : ``int`` or ``float`` (default: ``282.96547``)
Galactic longitude.
glat: ``int`` or ``float`` (default: ``75.41360``)
Galactic latitude. dec must be >= -90 and <= 90
distance : ``int``, ``float`` or ``None`` (default: ``None``)
Distance(s) in Mpc.
velocity : ``int``, ``float`` or ``None`` (default: ``None``)
Velocity in km/s. The returned distance potentially can be more