hc99 commited on
Commit
56d74b6
·
verified ·
1 Parent(s): 2c17839

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. testbed/astropy__astropy/.astropy-root +0 -0
  2. testbed/astropy__astropy/.gitattributes +3 -0
  3. testbed/astropy__astropy/.gitignore +70 -0
  4. testbed/astropy__astropy/.gitmodules +3 -0
  5. testbed/astropy__astropy/.mailmap +178 -0
  6. testbed/astropy__astropy/.readthedocs.yml +22 -0
  7. testbed/astropy__astropy/.travis.yml +216 -0
  8. testbed/astropy__astropy/CHANGES.rst +0 -0
  9. testbed/astropy__astropy/CITATION +112 -0
  10. testbed/astropy__astropy/CODE_OF_CONDUCT.md +1 -0
  11. testbed/astropy__astropy/CONTRIBUTING.md +177 -0
  12. testbed/astropy__astropy/GOVERNANCE.md +3 -0
  13. testbed/astropy__astropy/LICENSE.rst +26 -0
  14. testbed/astropy__astropy/MANIFEST.in +53 -0
  15. testbed/astropy__astropy/README.rst +90 -0
  16. testbed/astropy__astropy/ah_bootstrap.py +1010 -0
  17. testbed/astropy__astropy/appveyor.yml +38 -0
  18. testbed/astropy__astropy/astropy/CITATION +112 -0
  19. testbed/astropy__astropy/astropy/__init__.py +343 -0
  20. testbed/astropy__astropy/astropy/_erfa/__init__.py +3 -0
  21. testbed/astropy__astropy/astropy/_erfa/core.py.templ +313 -0
  22. testbed/astropy__astropy/astropy/_erfa/erfa_additions.h +21 -0
  23. testbed/astropy__astropy/astropy/_erfa/erfa_generator.py +740 -0
  24. testbed/astropy__astropy/astropy/_erfa/pav2pv.c +30 -0
  25. testbed/astropy__astropy/astropy/_erfa/pv2pav.c +30 -0
  26. testbed/astropy__astropy/astropy/_erfa/setup_package.py +108 -0
  27. testbed/astropy__astropy/astropy/_erfa/tests/__init__.py +1 -0
  28. testbed/astropy__astropy/astropy/_erfa/tests/test_erfa.py +240 -0
  29. testbed/astropy__astropy/astropy/_erfa/ufunc.c.templ +852 -0
  30. testbed/astropy__astropy/astropy/astropy.cfg +141 -0
  31. testbed/astropy__astropy/astropy/conftest.py +75 -0
  32. testbed/astropy__astropy/astropy/logger.py +568 -0
  33. testbed/astropy__astropy/astropy/setup_package.py +18 -0
  34. testbed/astropy__astropy/astropy/timeseries/__init__.py +12 -0
  35. testbed/astropy__astropy/astropy/timeseries/binned.py +334 -0
  36. testbed/astropy__astropy/astropy/timeseries/core.py +92 -0
  37. testbed/astropy__astropy/astropy/timeseries/downsample.py +137 -0
  38. testbed/astropy__astropy/astropy/timeseries/io/__init__.py +3 -0
  39. testbed/astropy__astropy/astropy/timeseries/io/kepler.py +93 -0
  40. testbed/astropy__astropy/astropy/timeseries/io/tests/__init__.py +1 -0
  41. testbed/astropy__astropy/astropy/timeseries/io/tests/test_kepler.py +88 -0
  42. testbed/astropy__astropy/astropy/timeseries/periodograms/__init__.py +3 -0
  43. testbed/astropy__astropy/astropy/timeseries/periodograms/base.py +56 -0
  44. testbed/astropy__astropy/astropy/timeseries/periodograms/bls/__init__.py +14 -0
  45. testbed/astropy__astropy/astropy/timeseries/periodograms/bls/_impl.pyx +96 -0
  46. testbed/astropy__astropy/astropy/timeseries/periodograms/bls/bls.c +224 -0
  47. testbed/astropy__astropy/astropy/timeseries/periodograms/bls/core.py +817 -0
  48. testbed/astropy__astropy/astropy/timeseries/periodograms/bls/methods.py +147 -0
  49. testbed/astropy__astropy/astropy/timeseries/periodograms/bls/setup_package.py +21 -0
  50. testbed/astropy__astropy/astropy/timeseries/periodograms/bls/tests/__init__.py +1 -0
testbed/astropy__astropy/.astropy-root ADDED
File without changes
testbed/astropy__astropy/.gitattributes ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ *.fits -text
2
+ astropy.0.3.windows.cfg eol=crlf
3
+ CHANGES.rst merge=union
testbed/astropy__astropy/.gitignore ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Compiled files
2
+ *.py[cod]
3
+ *.a
4
+ *.o
5
+ *.so
6
+ *.pyd
7
+ *.dll
8
+ __pycache__
9
+
10
+ # Ignore .c files by default to avoid including generated code. If you want to
11
+ # add a non-generated .c extension, use `git add -f filename.c`.
12
+ *.c
13
+
14
+ # Other generated files
15
+ MANIFEST
16
+ astropy/version.py
17
+ astropy/cython_version.py
18
+ astropy/wcs/include/wcsconfig.h
19
+ astropy/_erfa/core.py
20
+
21
+ # Sphinx
22
+ _build
23
+ _generated
24
+ docs/api
25
+ docs/generated
26
+ docs/visualization/ngc6976.jpeg
27
+ docs/visualization/ngc6976-default.jpeg
28
+
29
+ # Packages/installer info
30
+ *.egg
31
+ *.egg-info
32
+ dist
33
+ build
34
+ eggs
35
+ .eggs
36
+ parts
37
+ bin
38
+ var
39
+ sdist
40
+ develop-eggs
41
+ .installed.cfg
42
+ distribute-*.tar.gz
43
+ .venv
44
+ venv
45
+
46
+ # Other
47
+ .cache
48
+ .tox
49
+ .*.swp
50
+ .*.swo
51
+ *~
52
+ .project
53
+ .pydevproject
54
+ .settings
55
+ .coverage
56
+ cover
57
+ htmlcov
58
+
59
+ # Mac OSX
60
+ .DS_Store
61
+
62
+ # PyCharm
63
+ .idea
64
+
65
+ # Pytest
66
+ v
67
+ .pytest_cache
68
+
69
+ # VSCode
70
+ .vscode
testbed/astropy__astropy/.gitmodules ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [submodule "astropy_helpers"]
2
+ path = astropy_helpers
3
+ url = https://github.com/astropy/astropy-helpers.git
testbed/astropy__astropy/.mailmap ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Adam Ginsburg <keflavich@gmail.com>
2
+ Adam Ginsburg <keflavich@gmail.com> Adam Ginsburg <adam.g.ginsburg@gmail.com>
3
+ Adam Ginsburg <keflavich@gmail.com> Adam Ginsburg <keflavich@yahoo.com>
4
+ Adele Plunkett <aplunket@eso.org>
5
+ Alex Conley <alexander.conley@colorado.edu> Alexander Conley <alexander.conley@colorado.edu>
6
+ Alex Conley <alexander.conley@colorado.edu> Alexander Conley <alexanderconley@gmail.com>
7
+ Alex Hagen <mr.alex.hagen@gmail.com>
8
+ Asish Panda <asishrocks95@gmail.com>
9
+ Axel Donath <axel.donath@mpi-hd.mpg.de>
10
+ Bryce Nordgren <bnordgren@gmail.com>
11
+ Bogdan Nicula <bogdan@nicula.net>
12
+ Christopher Bonnett <c.bonnett@gmail.com>
13
+ Christoph Gohlke <cgohlke@uci.edu>
14
+ Curtis McCully <cmccully@lcogt.net>
15
+ Daniel Bell <stampsrule@gmail.com> Daniel <idaniel@me.com>
16
+ Daniel Bell <stampsrule@gmail.com> stampsrule <stampsrule@gmail.com>
17
+ Daniel Datsev <dan.datsev@gmail.com>
18
+ Daniel Datsev <dan.datsev@gmail.com> <fabled@vortex.(none)>
19
+ David Pérez-Suárez <dps.helio@gmail.com>
20
+ Demitri Muna <demitri.muna@gmail.com> <demitri@me.com>
21
+ Demitri Muna <demitri.muna@gmail.com> <beswiftly@gmail.com>
22
+ Dylan Gregersen <gregersen.dylan@gmail.com>
23
+ Emma Hogan <ehogan@gemini.edu>
24
+ Moataz Hisham <mtzhisham@gmail.com>
25
+ Erik M. Bray <erik.m.bray@gmail.com> <embray@stsci.edu>
26
+ Erik M. Bray <erik.m.bray@gmail.com> <erik.bray@lri.fr>
27
+ Erik M. Bray <erik.m.bray@gmail.com> Erik Bray <erik.m.bray@gmail.com>
28
+ Gerrit Schellenberger <gerrit@uni-bonn.de>
29
+ Gustavo Bragança <ga.braganca@gmail.com>
30
+ Hans Moritz Günther <moritz.guenther@gmx.de>
31
+ Hans Moritz Günther <moritz.guenther@gmx.de> hamogu <hgunther@mit.edu>
32
+ James Turner <jturner@gemini.edu>
33
+ Jeff Taylor <jeff.c.taylor@gmail.com>
34
+ Kacper Kowalik <xarthisius.kk@gmail.com> Kacper Kowalik <xarthisius@gentoo.org>
35
+ Kacper Kowalik <xarthisius.kk@gmail.com> Kacper Kowalik (Xarthisius) <xarthisius@gentoo.org>
36
+ Kacper Kowalik <xarthisius.kk@gmail.com> Kacper Kowalik (Xarthisius) <xarthisius.kk@gmail.com>
37
+ Karan Grover <karan@karan-HP-Pavilion-dm4-Notebook-PC.(none)>
38
+ Karl Vyhmeister <kvyh@users.noreply.github.com>
39
+ Kirill Tchernyshyov <ktchernyshyov@pha.jhu.edu>
40
+ Kelle Cruz <kellecruz@gmail.com>
41
+ Kevin Gullikson <kevin.gullikson@gmail.com>
42
+ Leonardo Ferreira <leonardo.ferreira.furg@gmail.com> [Leonardo Ferreira] <[leonardo.ferreira.furg@gmail.com]>
43
+ Lisa Walter <lisa@stsci.edu>
44
+ Marten van Kerkwijk <mhvk@astro.utoronto.ca> <mhvk@swan.astro.utoronto.ca>
45
+ Matt Davis <jiffyclub.programatic@gmail.com>
46
+ Nadia Dencheva <nadia.astropy@gmail.com> <nadia.dencheva@gmail.com>
47
+ Nadia Dencheva <nadia.astropy@gmail.com> <dencheva@itsd-osx13.local>
48
+ Neil Crighton <neilcrighton@gmail.com>
49
+ Perry Greenfield <perry@stsci.edu>
50
+ Pritish Chakraborty <chakrabortypritish@gmail.com>
51
+ Ryan Cooke <ryancooke86@gmail.com>
52
+ Shantanu Srivastava <shan_mbic@rediffmail.com>
53
+ Simon Conseil <contact@saimon.org> Simon Conseil <simon.conseil@univ-lyon1.fr>
54
+ Simon Conseil <contact@saimon.org> Simon <contact@saimon.org>
55
+ Simon Liedtke <liedtke.simon@googlemail.com>
56
+ Thomas Erben <terben@astro.uni-bonn.de> <thomas@astro.uni-bonn.de>
57
+ Thompson Le Blanc <leblanc@stsci.edu>
58
+ Thompson Le Blanc <leblanc@stsci.edu> astrocaribe <tlcommodore@gmail.com>
59
+ Tom Aldcroft <taldcroft@gmail.com> <aldcroft@dhcp-131-142-152-173.cfa.harvard.edu>
60
+ Zach Edwards <Zachary.Astro@Gmail.com>
61
+ Jonathan Foster <jonathan.bruce.foster@gmail.com>
62
+ David Kirkby <dkirkby@uci.edu>
63
+ Albert Y. Shih <ayshih@gmail.com>
64
+ Aleh Khvalko <algerdnazgul@gmail.com>
65
+ Elijah Bernstein-Cooper <e.bernsteincooper@gmail.com> <ezbc@astro.wisc.edu>
66
+ Lingyi Hu <hulingyi1995@yahoo.com.sg>
67
+ Francesco Montesano <franz.bergesund@gmail.com>
68
+ Daniel Lenz <dlenz.bonn@gmail.com>
69
+ Dan P. Cunningham <dan.p.cunningham@gmail.com>
70
+ Joseph Long <josephoenix@gmail.com> <me@joseph-long.com>
71
+ Brigitta Sipocz <bsipocz@gmail.com> <b.sipocz@gmail.com>
72
+ Rohit Patil <rohit4change@yahoo.in> QuanTakeuchi <rohit4change@yahoo.in>
73
+ Rohit Patil <rohit4change@yahoo.in> QuanTakeuchi <Quan@Aries.(none)>
74
+ Demitri Muna <demitri.muna@gmail.com> Demitri Muna <github@demitri.com>
75
+ Steve Crawford <crawfordsm@gmail.com> Steven Crawford <crawfordsm@gmail.com>
76
+ Steve Crawford <crawfordsm@gmail.com> <crawfodsm@gmail.com>
77
+ Anne Archibald <peridot.faceted@gmail.com> Anne Archibald <archibald@astron.nl>
78
+ Stuart Mumford <stuart@mumford.me.uk> Stuart Mumford <stuart@cadair.com>
79
+ Mihai Cara <mihail.cara@gmail.com> Mihai Cara <mcara@itsd-osx22.home>
80
+ Pey Lian Lim <lim@stsci.edu> P. L. Lim <lim@stsci.edu>
81
+ Pey Lian Lim <lim@stsci.edu> P. L. Lim <2090236+pllim@users.noreply.github.com>
82
+ Pey Lian Lim <lim@stsci.edu> Pey Lian Lim <2090236+pllim@users.noreply.github.com>
83
+ Jonathan Foster <jonathan.bruce.foster@gmail.com> Jonathan Foster <jonathan.b.foster@yale.edu>
84
+ Miguel de Val-Borro <miguel.deval@gmail.com> Miguel de Val-Borro <miguel@archlinux.net>
85
+ Eric Depagne <eric@depagne.org>
86
+ Pratik Patel <pratikpatel15133@gmail.com>
87
+ Mavani Bhautik <mavanibhautik@gmail.com>
88
+ Aniket Kulkarni <kaniket21@gmail.com>
89
+ Sara Ogaz <ogaz@stsci.edu>
90
+ Sourabh Cheedella <cheedella.sourabh@gmail.com>
91
+ Sudheesh Singanamalla <sudheesh1995@outlook.com>
92
+ Amit Kumar <dtu.amit@gmail.com>
93
+ Jake VanderPlas <jakevdp@gmail.com> Jake VanderPlas <jakevdp@uw.edu>
94
+ Matthew Craig <mattwcraig@gmail.com> Matt Craig <mattwcraig@gmail.com>
95
+ Sergio Pascual <sergio.pasra@gmail.com> Sergio Pascual <sergiopr@fis.ucm.es>
96
+ Laura Watkins <lauralwatkins@gmail.com> Laura L Watkins <lauralwatkins@gmail.com>
97
+ Axel Donath <axel.donath@mpi-hd.mpg.de> Axel Donath <donath@stud.uni-heidelberg.de>
98
+ Zé Vinicius <jvmirca@gmail.com> Ze Vinicius <jvmirca@gmail.com>
99
+ Ole Streicher <ole@aip.de> Ole Streicher <debian@liska.ath.cx>
100
+ Alex Rudy <alex.rudy@gmail.com> Alexander Rudy <alex.rudy@gmail.com>
101
+ Leo Singer <leo.singer@ligo.org> Leo Singer <leo.singer@nasa.gov>
102
+ Anthony Horton <anthony.horton@aao.gov.au>
103
+ Maneesh Yadav <maneesh.yadav@sri.com>
104
+ Esteban Pardo Sánchez <stbnps@users.noreply.github.com>
105
+ John Parejko <parejkoj@uw.edu> John K. Parejko <parejkoj@uw.edu> <parejkoj@gmail.com>
106
+ John Parejko <parejkoj@uw.edu> <parejkoj@gmail.com>
107
+ Pauline Barmby <pbarmby@uwo.ca> Pauline <pbarmby@uwo.ca>
108
+ Joseph Long <josephoenix@gmail.com> <jlong@stsci.edu>
109
+ Graham Kanarek <graykanarek@gmail.com>
110
+ Jurien Huisman <huisman@strw.leidenuniv.nl>
111
+ Aarya Patil <aaryapatil1996@gmail.com>
112
+ Aarya Patil <aaryapatil1996@gmail.com> <root@aaryas-MacBook-Pro.local>
113
+ Ritwick DSouza <ritwick.dsouza@outlook.com>
114
+ Jake VanderPlas <jakevdp@gmail.com>
115
+ Douglas Burke <dburke.gw@gmail.com>
116
+ Benjamin Alan Weaver <weaver@noao.edu> <benjamin.weaver@nyu.edu>
117
+ Benjamin Alan Weaver <weaver@noao.edu> <baweaver@lbl.gov>
118
+ Asra Nizami <anizami@macalester.edu> <anizami@itsd-summer18.stsci.edu>
119
+ Asra Nizami <anizami@macalester.edu> <anizami@itsd-summer18.local>
120
+ Michele Costa <thenocturnalastrostudent@gmail.com>
121
+ Luke G. Bouma <lgbouma@users.noreply.github.com>
122
+ VSN Reddy Janga <janga1997@gmail.com>
123
+ Giorgio Calderone <giorgio.calderone@gmail.com> <gcalderone@users.noreply.github.com>
124
+ Tyler Finethy <tylfin@gmail.com>
125
+ Sam Verstocken <sam.verstocken@gmail.com>
126
+ Mikhail Minin <mminin2010@gmail.com>
127
+ Matteo Bachetti <matteo@matteobachetti.it> <matteo.bachetti@irap.omp.eu>
128
+ Anirudh Katipally <akatipally@abiomed.com>
129
+ David Shupe <shupe@ipac.caltech.edu> <dave.shupe@gmail.com>
130
+ Adrian Price-Whelan <adrian.prw@gmail.com> <adrianmpw@gmail.com>
131
+ Derek Homeier <dhomeie@gwdg.de> <derek.homeier@ens-lyon.fr>
132
+ Brett Morris <brettmorris21@gmail.com> <bmmorris@uw.edu>
133
+ Daniel D'Avella <ddavella@stsci.edu> <drdavella@gmail.com>
134
+ Daniel D'Avella <ddavella@stsci.edu> Dan D'Avella <ddavella@stsci.edu>
135
+ Stuart Littlefair <s.littlefair@shef.ac.uk> StuartLittlefair <s.littlefair@shef.ac.uk>
136
+ Juan Luis Cano Rodríguez <juanlu001@gmail.com> Juan Luis Cano Rodríguez <juanlu@satellogic.com>
137
+ Juan Luis Cano Rodríguez <juanlu001@gmail.com> Juan Luis Cano Rodríguez <Juanlu001@users.noreply.github.com>
138
+ Joe Hunkeler <jhunk@stsci.edu> Joseph Hunkeler <jhunkeler@gmail.com>
139
+ Dan Foreman-Mackey <foreman.mackey@gmail.com> Dan F-M <danfm@nyu.edu>
140
+ Dan Foreman-Mackey <foreman.mackey@gmail.com> Dan F-M <foreman.mackey@gmail.com>
141
+ Johnny Greco <jgreco@astro.princeton.edu> Johnny <jgreco@astro.princeton.edu>
142
+ Zé Vinicius <jvmirca@gmail.com> mirca <jvmirca@gmail.com>
143
+ Michael Seifert <michaelseifert04@yahoo.de> --system <michaelseifert04@yahoo.de>
144
+ Michael Seifert <michaelseifert04@yahoo.de> MSeifert04 <michaelseifert04@yahoo.de>
145
+ Vishnunarayan K I <appukuttancr@gmail.com> vn-ki <appukuttancr@gmail.com>
146
+ Ritiek Malhotra <ritiekmalhotra123@gmail.com> ritiek <ritiekmalhotra123@gmail.com>
147
+ Rohan Rajpal <rohan17089@iiitd.ac.in> rohanrajpal <rohan17089@iiitd.ac.in>
148
+ Mangala Gowri Krishnamoorthy <mangalagb@gmail.com> mangalagb <mangalagb@gmail.com>
149
+ Hannes Breytenbach <hannes@saao.ac.za> astromancer <hannes@saao.ac.za>
150
+ Hannes Breytenbach <hannes@saao.ac.za> apodemus <hannes@saao.ac.za>
151
+ Christian Clauss <cclauss@bluewin.ch> cclauss <cclauss@bluewin.ch>
152
+ Eric Koch <koch.eric.w@gmail.com> e-koch <koch.eric.w@gmail.com>
153
+ Alexander Bakanov <bakanov.aleksandr@gmail.com> Aleksandr Bakanov <aleksandr_bakanov@epam.com>
154
+ Emily Deibert <emilydeibert@gmail.com> emilydeibert <emilydeibert@gmail.com>
155
+ Sanjeev Dubey <getsanjeevdubey@gmail.com> getsanjeev <getsanjeevdubey@gmail.com>
156
+ Humna Awan <humna.awan@rutgers.edu> Humna <humna.awan@rutgers.edu>
157
+ Daria Cara <daria.cara.2@gmail.com> unknown <daria.cara.2@gmail.com>
158
+ Jani Šumak <jani.sumak@gmail.com> dasdachs <jani.sumak@gmail.com>
159
+ Alexandre Beelen <alexandre.beelen@ias.u-psud.fr> alexandre beelen <alexandre.beelen@ias.u-psud.fr>
160
+ Steve Crawford <crawfordsm@gmail.com> Steven Crawford <scrawford@stsci.edu>
161
+ Steve Crawford <crawfordsm@gmail.com> crawfordsm <crawfordsm@gmail.com>
162
+ Mike Alexandersen <mikea@asiaa.sinica.edu.tw> Mike Alexandersen (on Vancouver) <mikea@asiaa.sinica.edu.tw>
163
+ Patricio Rojo <pato@das.uchile.cl> duckrojo <pato@oan.cl>
164
+ Ana Posses <anaposses@gmail.com> anaposses <anaposses@gmail.com>
165
+ Kyle Oman <koman@astro.rug.nl> K.A. Oman <koman@astro.rug.nl>
166
+ Vital Fernández <vital.fernandez@gmail.com> Delosari <lativmail@gmail.com>
167
+ Anany Shrey Jain <ananyashreyjain1998@gmail.com> ananyashreyjain <31594632+ananyashreyjain@users.noreply.github.com>
168
+ Joseph Schlitz <jrschlitz0725@gmail.com> SG004 <jrschlitz0725@gmail.com>
169
+ Benjamin Roulston <benjamin.roulston@protonmail.com> broulston <benjamin.roulston@protonmail.com>
170
+ Himanshu Pathak <hpathak336@gmail.com> himanshupathak21061998 <hpathak336@gmail.com>
171
+ Dan Taranu <dtaranu@astro.princeton.edu> taranu <dtaranu@astro.princeton.edu>
172
+ Yash Kumar <yash.kmr.99@gmail.com> yashkmr99 <yash.kmr.99@gmail.com>
173
+ Benjamin Winkel <bwinkel@mpifr.de> bwinkel <bwinkel78@gmail.com>
174
+ Javier Pascual Granado <javier@iaa.es> JaviPG <javier@iaa.es>
175
+ Javier Pascual Granado <javier@iaa.es> javier-iaa <javier@iaa.es>
176
+ Rohit Kapoor <algorithm059@gmail.com> algo-circle <algorithm059@gmail.com>
177
+ Jane Rigby <jane.rigby@gmail.com> janerigby <jane.rigby@gmail.com>
178
+ Lisa Martin <48742903+lisamartin72@users.noreply.github.com> lisamartin72 <48742903+lisamartin72@users.noreply.github.com>
testbed/astropy__astropy/.readthedocs.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: 2
2
+
3
+ build:
4
+ image: latest
5
+
6
+ # Install regular dependencies.
7
+ # Then, install special pinning for RTD.
8
+ python:
9
+ version: 3.6
10
+ install:
11
+ - method: pip
12
+ path: .
13
+ extra_requirements:
14
+ - docs
15
+ - all
16
+ - requirements: docs/rtd_requirements.txt
17
+
18
+ submodules:
19
+ include: all
20
+
21
+ # Don't build any extra formats
22
+ formats: []
testbed/astropy__astropy/.travis.yml ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # We set the language to c because python isn't supported on the MacOS X nodes
2
+ # on Travis. However, the language ends up being irrelevant anyway, since we
3
+ # install Python ourselves using conda.
4
+ language: c
5
+
6
+ compiler: gcc
7
+
8
+ # Cache can be cleared from the travis settings menu, see docs currently at
9
+ # https://docs.travis-ci.com/user/caching#Clearing-Caches
10
+ cache:
11
+ - ccache
12
+
13
+ os:
14
+ - linux
15
+
16
+ stage: Comprehensive tests
17
+
18
+ # Setting sudo to false opts in to Travis-CI container-based builds.
19
+ sudo: false
20
+
21
+ # The apt packages below are needed for sphinx builds, which can no longer
22
+ # be installed with sudo apt-get.
23
+ addons:
24
+ apt:
25
+ packages:
26
+ - graphviz
27
+ - language-pack-de
28
+
29
+ env:
30
+ global:
31
+ # Set defaults to avoid repeating in most cases
32
+ - PYTHON_VERSION=3.6
33
+ - NUMPY_VERSION=stable
34
+ - PYTEST_VERSION=3.10
35
+ - MAIN_CMD='python setup.py'
36
+ - CONDA_DEPENDENCIES='Cython jinja2'
37
+ - CONDA_ALL_DEPENDENCIES='Cython jinja2 scipy h5py matplotlib pyyaml pandas pytz html5lib beautifulsoup4 ipython mpmath bleach bottleneck'
38
+ - DEV_PIP_DEP='asdf>=2.3 Cython jinja2 scipy h5py matplotlib pyyaml scikit-image pandas pytz html5lib beautifulsoup4 ipython mpmath bleach bottleneck'
39
+ - ASDF_PIP_DEP='asdf>=2.3'
40
+ - SETUP_XVFB=True
41
+ - EVENT_TYPE='push pull_request'
42
+ - SETUP_CMD='test'
43
+ - INSTALL_WITH_PIP=False
44
+ - EXTRAS_INSTALL=""
45
+
46
+ # PEP8 errors/warnings:
47
+ # E101 - mix of tabs and spaces
48
+ # W191 - use of tabs
49
+ # W291 - trailing whitespace
50
+ # W292 - no newline at end of file
51
+ # W293 - trailing whitespace
52
+ # W391 - blank line at end of file
53
+ # E111 - 4 spaces per indentation level
54
+ # E112 - 4 spaces per indentation level
55
+ # E113 - 4 spaces per indentation level
56
+ # E502 - the backslash is redundant between brackets
57
+ # E722 - do not use bare except
58
+ # E901 - SyntaxError or IndentationError
59
+ # E902 - IOError
60
+ # E999: SyntaxError -- failed to compile a file into an Abstract Syntax Tree
61
+ # # F821: undefined name # Note: Removed for now because of heavy use of units.si
62
+ # F822: undefined name in __all__
63
+ # F823: local variable name referenced before assignment
64
+ - FLAKE8_OPT="--select=E101,W191,W291,W292,W293,W391,E111,E112,E113,E502,E722,E901,E902,E999,F822,F823"
65
+
66
+ stages:
67
+ # Do the style check and a single test job, don't proceed if it fails
68
+ - name: Initial tests
69
+ # Do the rest of the tests
70
+ - name: Comprehensive tests
71
+ - name: Cron tests
72
+ if: type = cron
73
+
74
+ matrix:
75
+
76
+ # Don't wait for allowed failures
77
+ fast_finish: true
78
+
79
+ include:
80
+ # Try MacOS X. Use a slightly old numpy version to help test against
81
+ # all supported numpy versions.
82
+ - os: osx
83
+ stage: Cron tests
84
+ env: SETUP_CMD='test --remote-data=astropy'
85
+ CONDA_DEPENDENCIES="$CONDA_ALL_DEPENDENCIES clang"
86
+ PIP_DEPENDENCIES="scikit-image jplephem $ASDF_PIP_DEP"
87
+ CCOMPILER=clang
88
+ EVENT_TYPE='cron'
89
+
90
+ # Try all python versions and Numpy versions. Since we can assume that
91
+ # the Numpy developers have taken care of testing Numpy with different
92
+ # versions of Python, we can vary Python and Numpy versions at the same
93
+ # time.
94
+ # Run this test using native pytest
95
+ - os: linux
96
+ env: PYTHON_VERSION=3.5 NUMPY_VERSION=1.13
97
+ INSTALL_CMD='python setup.py build_ext --inplace'
98
+ PIP_DEPENDENCIES='pytest-astropy'
99
+ TEST_CMD='pytest --open-files --doctest-rst'
100
+ PYTEST_VERSION=3.7
101
+ script:
102
+ - $INSTALL_CMD
103
+ - $TEST_CMD
104
+
105
+ # Now try with all optional dependencies. We also include the --readonly
106
+ # flag to make sure no files are being written to the temporary install
107
+ # location during testing. We also use this build to make sure that the
108
+ # dependencies get correctly installed with pip.
109
+ - os: linux
110
+ env: SETUP_CMD='test --remote-data=astropy --readonly'
111
+ LC_CTYPE=C.ascii LC_ALL=C
112
+ PYTEST_VERSION=4.4
113
+ PIP_DEPENDENCIES="" CONDA_DEPENDENCIES=""
114
+ INSTALL_WITH_PIP=True
115
+ EXTRAS_INSTALL="test,all"
116
+
117
+ - os: linux
118
+ stage: Initial tests
119
+ env: PYTHON_VERSION=3.7 CONDA_DEPENDENCIES=$CONDA_ALL_DEPENDENCIES
120
+ PIP_DEPENDENCIES="scikit-image $ASDF_PIP_DEP"
121
+ SETUP_CMD='test -a "--durations=50"'
122
+ compiler: clang
123
+
124
+ # Full tests with coverage checks.
125
+ - os: linux
126
+ env: SETUP_CMD='test --coverage --remote-data=astropy --readonly'
127
+ CONDA_DEPENDENCIES=$CONDA_ALL_DEPENDENCIES
128
+ PIP_DEPENDENCIES="scikit-image codecov objgraph jplephem bintrees sortedcontainers $ASDF_PIP_DEP"
129
+ LC_CTYPE=C.ascii LC_ALL=C
130
+ CFLAGS='--coverage -fno-inline-functions -O0'
131
+ MATPLOTLIB_VERSION=2.1
132
+ EVENT_TYPE='push pull_request cron'
133
+
134
+ # Try pre-release version of Numpy without optional dependencies
135
+ - os: linux
136
+ env: NUMPY_VERSION=prerelease
137
+ EVENT_TYPE='push pull_request cron'
138
+
139
+ # Do a PEP8/pyflakes test with flake8
140
+ - os: linux
141
+ stage: Initial tests
142
+ env: MAIN_CMD="flake8 astropy --count $FLAKE8_OPT" SETUP_CMD=''
143
+
144
+ # Try developer version of Numpy with optional dependencies and also
145
+ # run all remote tests. Since both cases will be potentially
146
+ # unstable, we combine them into a single unstable build that we can
147
+ # mark as an allowed failure below.
148
+ - os: linux
149
+ env: PYTHON_VERSION=3.7 NUMPY_VERSION=dev SETUP_CMD='test --remote-data'
150
+ CONDA_DEPENDENCIES=''
151
+ PIP_DEPENDENCIES=$DEV_PIP_DEP
152
+ MATPLOTLIB_VERSION=dev
153
+
154
+ # We check numpy-dev also in a job that only runs from cron, so that
155
+ # we can spot issues sooner. We do not use remote data here, since
156
+ # that gives too many false positives due to URL timeouts.
157
+ # We also install all dependencies via pip here so we pick up the latest
158
+ # releases.
159
+ - os: linux
160
+ stage: Cron tests
161
+ env: NUMPY_VERSION=dev MATPLOTLIB_VERSION=dev EVENT_TYPE='cron'
162
+ CONDA_DEPENDENCIES=''
163
+ PIP_DEPENDENCIES=$DEV_PIP_DEP
164
+
165
+ # Run documentation link check in a cron job.
166
+ # Was originally in CircleCI doc build but links are too flaky, so
167
+ # we moved it here instead.
168
+ - os: linux
169
+ stage: Cron tests
170
+ env: SETUP_CMD='build_docs -b linkcheck'
171
+ PIP_DEPENDENCIES="" CONDA_DEPENDENCIES=""
172
+ INSTALL_WITH_PIP=True
173
+ EXTRAS_INSTALL="docs,all"
174
+
175
+ allow_failures:
176
+ - os: linux
177
+ env: PYTHON_VERSION=3.7 NUMPY_VERSION=dev SETUP_CMD='test --remote-data'
178
+ CONDA_DEPENDENCIES=''
179
+ PIP_DEPENDENCIES=$DEV_PIP_DEP
180
+ MATPLOTLIB_VERSION=dev
181
+
182
+ before_install:
183
+
184
+ # We need to use CCOMPILER otherwise Travis overwrites CC if we define it
185
+ # in env: above.
186
+ - if [ ! -z $CCOMPILER ]; then
187
+ export CC=$CCOMPILER;
188
+ fi
189
+
190
+ # Check CC variable
191
+ - echo $CC
192
+
193
+ # Write configuration items to standard location to make sure they are
194
+ # ignored (the tests will fail if not)
195
+ - mkdir -p $HOME/.astropy/config/
196
+ - printf "unicode_output = True\nmax_width = 500" > $HOME/.astropy/config/astropy.cfg
197
+
198
+
199
+ install:
200
+ - git clone git://github.com/astropy/ci-helpers.git
201
+ - source ci-helpers/travis/setup_conda.sh
202
+ - if [[ $INSTALL_WITH_PIP == True ]]; then
203
+ if [ -z $EXTRAS_INSTALL ]; then
204
+ pip install -e .;
205
+ else
206
+ pip install -e .[$EXTRAS_INSTALL];
207
+ fi
208
+ fi
209
+
210
+ script:
211
+ - $MAIN_CMD $SETUP_CMD
212
+
213
+ after_success:
214
+ - if [[ $SETUP_CMD == *--coverage* ]]; then
215
+ codecov --gcov-glob "*cextern*";
216
+ fi
testbed/astropy__astropy/CHANGES.rst ADDED
The diff for this file is too large to render. See raw diff
 
testbed/astropy__astropy/CITATION ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ If you use Astropy for work/research presented in a publication (whether
2
+ directly, or as a dependency to another package), we recommend and encourage
3
+ the following acknowledgment:
4
+
5
+ This research made use of Astropy, a community-developed core Python package
6
+ for Astronomy (Astropy Collaboration, 2018).
7
+
8
+ where (Astropy Collaboration, 2018) is a citation to this paper:
9
+
10
+ http://adsabs.harvard.edu/abs/2018AJ....156..123T
11
+
12
+ An earlier paper is also available describing the status of the package at
13
+ the time of v0.2. If you have used Astropy for a long time, you are
14
+ encouraged to acknowledge both papers:
15
+
16
+ This research made use of Astropy, a community-developed core Python package
17
+ for Astronomy (Astropy Collaboration, 2013, 2018).
18
+
19
+ where (Astropy Collaboration, 2013) is a citation to this paper:
20
+
21
+ http://adsabs.harvard.edu/abs/2013A%26A...558A..33A
22
+
23
+ We encourage you to also include citations to the papers in the main text
24
+ wherever appropriate.
25
+
26
+
27
+ Recommended BibTeX entries for the above citations are:
28
+
29
+ @ARTICLE{2018AJ....156..123T,
30
+ author = {{The Astropy Collaboration} and {Price-Whelan}, A.~M. and {Sip{\H o}cz}, B.~M. and
31
+ {G{\"u}nther}, H.~M. and {Lim}, P.~L. and {Crawford}, S.~M. and
32
+ {Conseil}, S. and {Shupe}, D.~L. and {Craig}, M.~W. and {Dencheva}, N. and
33
+ {Ginsburg}, A. and {VanderPlas}, J.~T. and {Bradley}, L.~D. and
34
+ {P{\'e}rez-Su{\'a}rez}, D. and {de Val-Borro}, M. and {Paper Contributors}, (. and
35
+ {Aldcroft}, T.~L. and {Cruz}, K.~L. and {Robitaille}, T.~P. and
36
+ {Tollerud}, E.~J. and {Coordination Committee}, (. and {Ardelean}, C. and
37
+ {Babej}, T. and {Bach}, Y.~P. and {Bachetti}, M. and {Bakanov}, A.~V. and
38
+ {Bamford}, S.~P. and {Barentsen}, G. and {Barmby}, P. and {Baumbach}, A. and
39
+ {Berry}, K.~L. and {Biscani}, F. and {Boquien}, M. and {Bostroem}, K.~A. and
40
+ {Bouma}, L.~G. and {Brammer}, G.~B. and {Bray}, E.~M. and {Breytenbach}, H. and
41
+ {Buddelmeijer}, H. and {Burke}, D.~J. and {Calderone}, G. and
42
+ {Cano Rodr{\'{\i}}guez}, J.~L. and {Cara}, M. and {Cardoso}, J.~V.~M. and
43
+ {Cheedella}, S. and {Copin}, Y. and {Corrales}, L. and {Crichton}, D. and
44
+ {D{\rsquo}Avella}, D. and {Deil}, C. and {Depagne}, {\'E}. and
45
+ {Dietrich}, J.~P. and {Donath}, A. and {Droettboom}, M. and
46
+ {Earl}, N. and {Erben}, T. and {Fabbro}, S. and {Ferreira}, L.~A. and
47
+ {Finethy}, T. and {Fox}, R.~T. and {Garrison}, L.~H. and {Gibbons}, S.~L.~J. and
48
+ {Goldstein}, D.~A. and {Gommers}, R. and {Greco}, J.~P. and
49
+ {Greenfield}, P. and {Groener}, A.~M. and {Grollier}, F. and
50
+ {Hagen}, A. and {Hirst}, P. and {Homeier}, D. and {Horton}, A.~J. and
51
+ {Hosseinzadeh}, G. and {Hu}, L. and {Hunkeler}, J.~S. and {Ivezi{\'c}}, {\v Z}. and
52
+ {Jain}, A. and {Jenness}, T. and {Kanarek}, G. and {Kendrew}, S. and
53
+ {Kern}, N.~S. and {Kerzendorf}, W.~E. and {Khvalko}, A. and
54
+ {King}, J. and {Kirkby}, D. and {Kulkarni}, A.~M. and {Kumar}, A. and
55
+ {Lee}, A. and {Lenz}, D. and {Littlefair}, S.~P. and {Ma}, Z. and
56
+ {Macleod}, D.~M. and {Mastropietro}, M. and {McCully}, C. and
57
+ {Montagnac}, S. and {Morris}, B.~M. and {Mueller}, M. and {Mumford}, S.~J. and
58
+ {Muna}, D. and {Murphy}, N.~A. and {Nelson}, S. and {Nguyen}, G.~H. and
59
+ {Ninan}, J.~P. and {N{\"o}the}, M. and {Ogaz}, S. and {Oh}, S. and
60
+ {Parejko}, J.~K. and {Parley}, N. and {Pascual}, S. and {Patil}, R. and
61
+ {Patil}, A.~A. and {Plunkett}, A.~L. and {Prochaska}, J.~X. and
62
+ {Rastogi}, T. and {Reddy Janga}, V. and {Sabater}, J. and {Sakurikar}, P. and
63
+ {Seifert}, M. and {Sherbert}, L.~E. and {Sherwood-Taylor}, H. and
64
+ {Shih}, A.~Y. and {Sick}, J. and {Silbiger}, M.~T. and {Singanamalla}, S. and
65
+ {Singer}, L.~P. and {Sladen}, P.~H. and {Sooley}, K.~A. and
66
+ {Sornarajah}, S. and {Streicher}, O. and {Teuben}, P. and {Thomas}, S.~W. and
67
+ {Tremblay}, G.~R. and {Turner}, J.~E.~H. and {Terr{\'o}n}, V. and
68
+ {van Kerkwijk}, M.~H. and {de la Vega}, A. and {Watkins}, L.~L. and
69
+ {Weaver}, B.~A. and {Whitmore}, J.~B. and {Woillez}, J. and
70
+ {Zabalza}, V. and {Contributors}, (.},
71
+ title = "{The Astropy Project: Building an Open-science Project and Status of the v2.0 Core Package}",
72
+ journal = {\aj},
73
+ archivePrefix = "arXiv",
74
+ eprint = {1801.02634},
75
+ primaryClass = "astro-ph.IM",
76
+ keywords = {methods: data analysis, methods: miscellaneous, methods: statistical, reference systems },
77
+ year = 2018,
78
+ month = sep,
79
+ volume = 156,
80
+ eid = {123},
81
+ pages = {123},
82
+ doi = {10.3847/1538-3881/aabc4f},
83
+ adsurl = {http://adsabs.harvard.edu/abs/2018AJ....156..123T},
84
+ adsnote = {Provided by the SAO/NASA Astrophysics Data System}
85
+ }
86
+
87
+ @ARTICLE{2013A&A...558A..33A,
88
+ author = {{Astropy Collaboration} and {Robitaille}, T.~P. and {Tollerud}, E.~J. and
89
+ {Greenfield}, P. and {Droettboom}, M. and {Bray}, E. and {Aldcroft}, T. and
90
+ {Davis}, M. and {Ginsburg}, A. and {Price-Whelan}, A.~M. and
91
+ {Kerzendorf}, W.~E. and {Conley}, A. and {Crighton}, N. and
92
+ {Barbary}, K. and {Muna}, D. and {Ferguson}, H. and {Grollier}, F. and
93
+ {Parikh}, M.~M. and {Nair}, P.~H. and {Unther}, H.~M. and {Deil}, C. and
94
+ {Woillez}, J. and {Conseil}, S. and {Kramer}, R. and {Turner}, J.~E.~H. and
95
+ {Singer}, L. and {Fox}, R. and {Weaver}, B.~A. and {Zabalza}, V. and
96
+ {Edwards}, Z.~I. and {Azalee Bostroem}, K. and {Burke}, D.~J. and
97
+ {Casey}, A.~R. and {Crawford}, S.~M. and {Dencheva}, N. and
98
+ {Ely}, J. and {Jenness}, T. and {Labrie}, K. and {Lian Lim}, P. and
99
+ {Pierfederici}, F. and {Pontzen}, A. and {Ptak}, A. and {Refsdal}, B. and
100
+ {Servillat}, M. and {Streicher}, O.},
101
+ title = "{Astropy: A community Python package for astronomy}",
102
+ journal = {\aap},
103
+ keywords = {methods: data analysis, methods: miscellaneous, virtual observatory tools},
104
+ year = 2013,
105
+ month = oct,
106
+ volume = 558,
107
+ eid = {A33},
108
+ pages = {A33},
109
+ doi = {10.1051/0004-6361/201322068},
110
+ adsurl = {http://adsabs.harvard.edu/abs/2013A%26A...558A..33A},
111
+ adsnote = {Provided by the SAO/NASA Astrophysics Data System}
112
+ }
testbed/astropy__astropy/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1 @@
 
 
1
+ All Astropy community members are expected to abide by the [Astropy Project Code of Conduct](http://www.astropy.org/code_of_conduct.html).
testbed/astropy__astropy/CONTRIBUTING.md ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Contributing to Astropy
2
+ =======================
3
+
4
+ Reporting Issues
5
+ ----------------
6
+
7
+ When opening an issue to report a problem, please try to provide a minimal code
8
+ example that reproduces the issue along with details of the operating
9
+ system and the Python, NumPy, and `astropy` versions you are using.
10
+
11
+ Contributing Code
12
+ -----------------
13
+
14
+ So you are interested in contributing code to the Astropy Project? Excellent!
15
+ We love contributions! Astropy is open source, built on open source,
16
+ and we'd love to have you hang out in our community.
17
+
18
+ **Imposter syndrome disclaimer**: We want your help. No, really.
19
+
20
+ There may be a little voice inside your head that is telling you that you're not
21
+ ready to be an open source contributor; that your skills aren't nearly good
22
+ enough to contribute. What could you possibly offer a project like this one?
23
+
24
+ We assure you - the little voice in your head is wrong. If you can write code at
25
+ all, you can contribute code to open source. Contributing to open source
26
+ projects is a fantastic way to advance one's coding skills. Writing perfect code
27
+ isn't the measure of a good developer (that would disqualify all of us!); it's
28
+ trying to create something, making mistakes, and learning from those
29
+ mistakes. That's how we all improve, and we are happy to help others learn.
30
+
31
+ Being an open source contributor doesn't just mean writing code, either. You can
32
+ help out by writing documentation, tests, or even giving feedback about the
33
+ project (and yes - that includes giving feedback about the contribution
34
+ process). Some of these contributions may be the most valuable to the project as
35
+ a whole, because you're coming to the project with fresh eyes, so you can see
36
+ the errors and assumptions that seasoned contributors have glossed over.
37
+
38
+ Note: This disclaimer was originally written by
39
+ `Adrienne Lowe <https://github.com/adriennefriend>`_ for a
40
+ `PyCon talk <https://www.youtube.com/watch?v=6Uj746j9Heo>`_, and was adapted by
41
+ Astropy based on its use in the README file for the
42
+ `MetPy project <https://github.com/Unidata/MetPy>`_.
43
+
44
+ Most contributions to Astropy are done via pull requests from GitHub users'
45
+ forks of the [astropy repository](https://github.com/astropy/astropy). If you
46
+ are new to this style of development, you will want to read over our
47
+ [development workflow](http://docs.astropy.org/en/latest/development/workflow/development_workflow.html).
48
+
49
+ You may also/instead be interested in contributing to an
50
+ [astropy affiliated package](http://www.astropy.org/affiliated/).
51
+ Affiliated packages are astronomy-related software packages that are not a part
52
+ of the `astropy` core package, but build on it for more specialized applications
53
+ and follow the Astropy guidelines for reuse, interoperability, and interfacing.
54
+ Each affiliated package has its own developers/maintainers and its own specific
55
+ guidelines for contributions, so be sure to read their docs.
56
+
57
+ Once you open a pull request (which should be opened against the ``master``
58
+ branch, not against any of the other branches), please make sure to
59
+ include the following:
60
+
61
+ - **Code**: the code you are adding, which should follow
62
+ our [coding guidelines](http://docs.astropy.org/en/latest/development/codeguide.html) as much as possible.
63
+
64
+ - **Tests**: these are usually tests to ensure code that previously
65
+ failed now works (regression tests), or tests that cover as much as possible
66
+ of the new functionality to make sure it does not break in the future and
67
+ also returns consistent results on all platforms (since we run these tests on
68
+ many platforms/configurations). For more information about how to write
69
+ tests, see our [testing guidelines](http://docs.astropy.org/en/latest/development/testguide.html).
70
+
71
+ - **Documentation**: if you are adding new functionality, be sure to include a
72
+ description in the main documentation (in ``docs/``). Again, we have some
73
+ detailed [documentation guidelines](http://docs.astropy.org/en/latest/development/docguide.html) to help you out.
74
+
75
+ - **Performance improvements**: if you are making changes that impact `astropy`
76
+ performance, consider adding a performance benchmark in the
77
+ [astropy-benchmarks](https://github.com/astropy/astropy-benchmarks)
78
+ repository. You can find out more about how to do this
79
+ [in the README for that repository](https://github.com/astropy/astropy-benchmarks#contributing-a-benchmark).
80
+
81
+ - **Changelog entry**: whether you are fixing a bug or adding new
82
+ functionality, you should add an entry to the ``CHANGES.rst`` file that
83
+ includes the PR number. If you are opening a pull request you may not know
84
+ the PR number yet, but you can add it once the pull request is open. If you
85
+ are not sure where to put the changelog entry, wait until a maintainer
86
+ has reviewed your PR and assigned it to a milestone.
87
+
88
+ You do not need to include a changelog entry for fixes to bugs introduced in
89
+ the developer version and therefore are not present in the stable releases. In
90
+ general you do not need to include a changelog entry for minor documentation
91
+ or test updates. Only user-visible changes (new features/API changes, fixed
92
+ issues) need to be mentioned. If in doubt, ask the core maintainer reviewing
93
+ your changes.
94
+
95
+ Other Tips
96
+ ----------
97
+
98
+ - To prevent the automated tests from running, you can add ``[ci skip]`` to your
99
+ commit message. This is useful if your PR is a work in progress and you are
100
+ not yet ready for the tests to run. For example:
101
+
102
+ $ git commit -m "WIP widget [ci skip]"
103
+
104
+ - If you already made the commit without including this string, you can edit
105
+ your existing commit message by running:
106
+
107
+ $ git commit --amend
108
+
109
+ - To skip only the AppVeyor (Windows) CI builds you can use ``[skip appveyor]``,
110
+ and to skip testing on Travis CI use ``[skip travis]``.
111
+
112
+ - If your commit makes substantial changes to the documentation but no code
113
+ changes, then you can use ``[docs only]``, which will skip all but the
114
+ documentation building jobs on Travis.
115
+
116
+ - When contributing trivial documentation fixes (i.e. fixes to typos, spelling,
117
+ grammar) that don't contain any special markup and are not associated with
118
+ code changes, please include the string ``[docs only]`` in your commit
119
+ message.
120
+
121
+ $ git commit -m "Fixed typo [docs only]"
122
+
123
+ Checklist for Contributed Code
124
+ ------------------------------
125
+
126
+ A pull request for a new feature will be reviewed to see if it meets the
127
+ following requirements. For any pull request, an `astropy` maintainer can help
128
+ to make sure that the pull request meets the requirements for inclusion in the
129
+ package.
130
+
131
+ **Scientific Quality** (when applicable)
132
+ * Is the submission relevant to astronomy?
133
+ * Are references included to the origin source for the algorithm?
134
+ * Does the code perform as expected?
135
+ * Has the code been tested against previously existing implementations?
136
+
137
+ **Code Quality**
138
+ * Are the [coding guidelines](http://docs.astropy.org/en/latest/development/codeguide.html) followed?
139
+ * Is the code compatible with Python >=3.5?
140
+ * Are there dependencies other than the `astropy` core, the Python Standard
141
+ Library, and NumPy 1.10.0 or later?
142
+ * Is the package importable even if the C-extensions are not built?
143
+ * Are additional dependencies handled appropriately?
144
+ * Do functions that require additional dependencies raise an `ImportError`
145
+ if they are not present?
146
+
147
+ **Testing**
148
+ * Are the [testing guidelines](http://docs.astropy.org/en/latest/development/testguide.html) followed?
149
+ * Are the inputs to the functions sufficiently tested?
150
+ * Are there tests for any exceptions raised?
151
+ * Are there tests for the expected performance?
152
+ * Are the sources for the tests documented?
153
+ * Have tests that require an [optional dependency](http://docs.astropy.org/en/latest/development/testguide.html#tests-requiring-optional-dependencies)
154
+ been marked as such?
155
+ * Does ``python setup.py test`` run without failures?
156
+
157
+ **Documentation**
158
+ * Are the [documentation guidelines](http://docs.astropy.org/en/latest/development/docguide.html) followed?
159
+ * Is there a [docstring](http://docs.astropy.org/en/latest/development/docrules.html) in the function describing:
160
+ * What the code does?
161
+ * The format of the inputs of the function?
162
+ * The format of the outputs of the function?
163
+ * References to the original algorithms?
164
+ * Any exceptions which are raised?
165
+ * An example of running the code?
166
+ * Is there any information needed to be added to the docs to describe the
167
+ function?
168
+ * Does the documentation build without errors or warnings?
169
+
170
+ **License**
171
+ * Is the `astropy` license included at the top of the file?
172
+ * Are there any conflicts with this code and existing codes?
173
+
174
+ **Astropy requirements**
175
+ * Do all the Travis CI, AppVeyor, and CircleCI tests pass?
176
+ * If applicable, has an entry been added into the changelog?
177
+ * Can you check out the pull request and repeat the examples and tests?
testbed/astropy__astropy/GOVERNANCE.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Astropy Project Governance
2
+
3
+ Please visit our website to learn more about the [Astropy Team](http://www.astropy.org/team.html).
testbed/astropy__astropy/LICENSE.rst ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2011-2017, Astropy Developers
2
+
3
+ All rights reserved.
4
+
5
+ Redistribution and use in source and binary forms, with or without modification,
6
+ are permitted provided that the following conditions are met:
7
+
8
+ * Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+ * Redistributions in binary form must reproduce the above copyright notice, this
11
+ list of conditions and the following disclaimer in the documentation and/or
12
+ other materials provided with the distribution.
13
+ * Neither the name of the Astropy Team nor the names of its contributors may be
14
+ used to endorse or promote products derived from this software without
15
+ specific prior written permission.
16
+
17
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
18
+ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
20
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
21
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
22
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
24
+ ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
26
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
testbed/astropy__astropy/MANIFEST.in ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ include .astropy-root
2
+ include LICENSE.rst
3
+ include README.rst
4
+ include CHANGES.rst
5
+ include pip-requirements*
6
+ include CITATION
7
+ include astropy/CITATION
8
+
9
+ include ah_bootstrap.py
10
+ include setup.cfg
11
+ include astropy/tests/coveragerc
12
+ recursive-include astropy *.pyx *.c *.h *.map *.templ
13
+
14
+ include astropy/astropy.cfg
15
+
16
+ # We have to explicitly include the following modules, otherwise only the
17
+ # Python 2 versions are included when making a source distribution in Python
18
+ # 2, and similarly for Python 3:
19
+ include astropy/extern/configobj/*.py
20
+ recursive-include astropy/utils/compat *.py
21
+
22
+ recursive-include docs *
23
+ recursive-include examples *
24
+ recursive-include licenses *
25
+ recursive-include cextern *
26
+ recursive-include scripts *
27
+ recursive-include static *
28
+
29
+ prune docs/_build
30
+ prune build
31
+
32
+
33
+ # the next few stanzas are for astropy_helpers. It's derived from the
34
+ # astropy_helpers/MANIFEST.in, but requires additional includes for the actual
35
+ # package directory and egg-info.
36
+
37
+ include astropy_helpers/README.rst
38
+ include astropy_helpers/CHANGES.rst
39
+ include astropy_helpers/LICENSE.rst
40
+ recursive-include astropy_helpers/licenses *
41
+
42
+ include astropy_helpers/ah_bootstrap.py
43
+
44
+ recursive-include astropy_helpers/astropy_helpers *.py *.pyx *.c *.h *.rst
45
+ recursive-include astropy_helpers/astropy_helpers.egg-info *
46
+ # include the sphinx stuff with "*" because there are css/html/rst/etc.
47
+ recursive-include astropy_helpers/astropy_helpers/sphinx *
48
+
49
+ prune astropy_helpers/build
50
+ prune astropy_helpers/astropy_helpers/tests
51
+
52
+
53
+ global-exclude *.pyc *.o
testbed/astropy__astropy/README.rst ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ =======
2
+ Astropy
3
+ =======
4
+
5
+ |Travis Status| |AppVeyor Status| |CircleCI Status| |Coverage Status| |PyPI Status| |Documentation Status|
6
+
7
+ The Astropy Project (http://astropy.org/) is a community effort to develop a
8
+ single core package for Astronomy in Python and foster interoperability between
9
+ Python astronomy packages. This repository contains the core package which is
10
+ intended to contain much of the core functionality and some common tools needed
11
+ for performing astronomy and astrophysics with Python.
12
+
13
+ Releases are `registered on PyPI <http://pypi.python.org/pypi/astropy>`_,
14
+ and development is occurring at the
15
+ `project's GitHub page <http://github.com/astropy/astropy>`_.
16
+
17
+ For installation instructions, see the `online documentation <http://docs.astropy.org/>`_
18
+ or `docs/install.rst <docs/install.rst>`_ in this source distribution.
19
+
20
+ Contributing Code, Documentation, or Feedback
21
+ ---------------------------------------------
22
+
23
+ The Astropy Project is made both by and for its users, so we welcome and
24
+ encourage contributions of many kinds. Our goal is to keep this a positive,
25
+ inclusive, successful, and growing community by abiding with the
26
+ `Astropy Community Code of Conduct <http://www.astropy.org/about.html#codeofconduct>`_.
27
+
28
+ More detailed information on contributing to the project or submitting feedback
29
+ can be found on the `contributions <http://www.astropy.org/contribute.html>`_
30
+ page. A `summary of contribution guidelines <CONTRIBUTING.md>`_ can also be
31
+ used as a quick reference when you are ready to start writing or validating
32
+ code for submission.
33
+
34
+ Supporting the Project
35
+ ----------------------
36
+
37
+ |NumFOCUS| |Donate|
38
+
39
+ The Astropy Project is sponsored by NumFOCUS, a 501(c)(3) nonprofit in the
40
+ United States. You can donate to the project by using the link above, and this
41
+ donation will support our mission to promote sustainable, high-level code base
42
+ for the astronomy community, open code development, educational materials, and
43
+ reproducible scientific research.
44
+
45
+ License
46
+ -------
47
+
48
+ Astropy is licensed under a 3-clause BSD style license - see the
49
+ `LICENSE.rst <LICENSE.rst>`_ file.
50
+
51
+ Notes for Package Managers
52
+ --------------------------
53
+
54
+ For system packagers: Please install `astropy` with the command::
55
+
56
+ $ python setup.py --offline install
57
+
58
+ This will prevent the astropy_helpers bootstrap script from attempting to
59
+ reach out to PyPI.
60
+
61
+ .. |Travis Status| image:: https://travis-ci.org/astropy/astropy.svg
62
+ :target: https://travis-ci.org/astropy/astropy
63
+ :alt: Astropy's Travis CI Status
64
+
65
+ .. |CircleCI Status| image:: https://circleci.com/gh/astropy/astropy.svg?style=svg
66
+ :target: https://circleci.com/gh/astropy/astropy
67
+ :alt: Astropy's CircleCI Status
68
+
69
+ .. |AppVeyor Status| image:: https://ci.appveyor.com/api/projects/status/ym7lxajcs5qwm31e/branch/master?svg=true
70
+ :target: https://ci.appveyor.com/project/Astropy/astropy/branch/master
71
+ :alt: Astropy's Appveyor Status
72
+
73
+ .. |Coverage Status| image:: https://codecov.io/gh/astropy/astropy/branch/master/graph/badge.svg
74
+ :target: https://codecov.io/gh/astropy/astropy
75
+ :alt: Astropy's Coverage Status
76
+
77
+ .. |PyPI Status| image:: https://img.shields.io/pypi/v/astropy.svg
78
+ :target: https://pypi.python.org/pypi/astropy
79
+ :alt: Astropy's PyPI Status
80
+
81
+ .. |Documentation Status| image:: https://readthedocs.org/projects/astropy/badge/?version=stable
82
+ :target: http://docs.astropy.org/en/stable/?badge=stable
83
+ :alt: Documentation Status
84
+
85
+ .. |NumFOCUS| image:: https://img.shields.io/badge/powered%20by-NumFOCUS-orange.svg?style=flat&colorA=E1523D&colorB=007D8A
86
+ :target: http://numfocus.org
87
+ :alt: Powered by NumFOCUS
88
+
89
+ .. |Donate| image:: https://img.shields.io/badge/Donate-to%20Astropy-brightgreen.svg
90
+ :target: https://numfocus.salsalabs.org/donate-to-astropy/index.html
testbed/astropy__astropy/ah_bootstrap.py ADDED
@@ -0,0 +1,1010 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This bootstrap module contains code for ensuring that the astropy_helpers
3
+ package will be importable by the time the setup.py script runs. It also
4
+ includes some workarounds to ensure that a recent-enough version of setuptools
5
+ is being used for the installation.
6
+
7
+ This module should be the first thing imported in the setup.py of distributions
8
+ that make use of the utilities in astropy_helpers. If the distribution ships
9
+ with its own copy of astropy_helpers, this module will first attempt to import
10
+ from the shipped copy. However, it will also check PyPI to see if there are
11
+ any bug-fix releases on top of the current version that may be useful to get
12
+ past platform-specific bugs that have been fixed. When running setup.py, use
13
+ the ``--offline`` command-line option to disable the auto-upgrade checks.
14
+
15
+ When this module is imported or otherwise executed it automatically calls a
16
+ main function that attempts to read the project's setup.cfg file, which it
17
+ checks for a configuration section called ``[ah_bootstrap]`` the presences of
18
+ that section, and options therein, determine the next step taken: If it
19
+ contains an option called ``auto_use`` with a value of ``True``, it will
20
+ automatically call the main function of this module called
21
+ `use_astropy_helpers` (see that function's docstring for full details).
22
+ Otherwise no further action is taken and by default the system-installed version
23
+ of astropy-helpers will be used (however, ``ah_bootstrap.use_astropy_helpers``
24
+ may be called manually from within the setup.py script).
25
+
26
+ This behavior can also be controlled using the ``--auto-use`` and
27
+ ``--no-auto-use`` command-line flags. For clarity, an alias for
28
+ ``--no-auto-use`` is ``--use-system-astropy-helpers``, and we recommend using
29
+ the latter if needed.
30
+
31
+ Additional options in the ``[ah_boostrap]`` section of setup.cfg have the same
32
+ names as the arguments to `use_astropy_helpers`, and can be used to configure
33
+ the bootstrap script when ``auto_use = True``.
34
+
35
+ See https://github.com/astropy/astropy-helpers for more details, and for the
36
+ latest version of this module.
37
+ """
38
+
39
+ import contextlib
40
+ import errno
41
+ import io
42
+ import locale
43
+ import os
44
+ import re
45
+ import subprocess as sp
46
+ import sys
47
+
48
+ from distutils import log
49
+ from distutils.debug import DEBUG
50
+
51
+ from configparser import ConfigParser, RawConfigParser
52
+
53
+ import pkg_resources
54
+
55
+ from setuptools import Distribution
56
+ from setuptools.package_index import PackageIndex
57
+
58
+ # This is the minimum Python version required for astropy-helpers
59
+ __minimum_python_version__ = (3, 5)
60
+
61
+ # TODO: Maybe enable checking for a specific version of astropy_helpers?
62
+ DIST_NAME = 'astropy-helpers'
63
+ PACKAGE_NAME = 'astropy_helpers'
64
+ UPPER_VERSION_EXCLUSIVE = None
65
+
66
+ # Defaults for other options
67
+ DOWNLOAD_IF_NEEDED = True
68
+ INDEX_URL = 'https://pypi.python.org/simple'
69
+ USE_GIT = True
70
+ OFFLINE = False
71
+ AUTO_UPGRADE = True
72
+
73
+ # A list of all the configuration options and their required types
74
+ CFG_OPTIONS = [
75
+ ('auto_use', bool), ('path', str), ('download_if_needed', bool),
76
+ ('index_url', str), ('use_git', bool), ('offline', bool),
77
+ ('auto_upgrade', bool)
78
+ ]
79
+
80
+ # Start off by parsing the setup.cfg file
81
+
82
+ SETUP_CFG = ConfigParser()
83
+
84
+ if os.path.exists('setup.cfg'):
85
+
86
+ try:
87
+ SETUP_CFG.read('setup.cfg')
88
+ except Exception as e:
89
+ if DEBUG:
90
+ raise
91
+
92
+ log.error(
93
+ "Error reading setup.cfg: {0!r}\n{1} will not be "
94
+ "automatically bootstrapped and package installation may fail."
95
+ "\n{2}".format(e, PACKAGE_NAME, _err_help_msg))
96
+
97
+ # We used package_name in the package template for a while instead of name
98
+ if SETUP_CFG.has_option('metadata', 'name'):
99
+ parent_package = SETUP_CFG.get('metadata', 'name')
100
+ elif SETUP_CFG.has_option('metadata', 'package_name'):
101
+ parent_package = SETUP_CFG.get('metadata', 'package_name')
102
+ else:
103
+ parent_package = None
104
+
105
+ if SETUP_CFG.has_option('options', 'python_requires'):
106
+
107
+ python_requires = SETUP_CFG.get('options', 'python_requires')
108
+
109
+ # The python_requires key has a syntax that can be parsed by SpecifierSet
110
+ # in the packaging package. However, we don't want to have to depend on that
111
+ # package, so instead we can use setuptools (which bundles packaging). We
112
+ # have to add 'python' to parse it with Requirement.
113
+
114
+ from pkg_resources import Requirement
115
+ req = Requirement.parse('python' + python_requires)
116
+
117
+ # We want the Python version as a string, which we can get from the platform module
118
+ import platform
119
+ # strip off trailing '+' incase this is a dev install of python
120
+ python_version = platform.python_version().strip('+')
121
+ # allow pre-releases to count as 'new enough'
122
+ if not req.specifier.contains(python_version, True):
123
+ if parent_package is None:
124
+ message = "ERROR: Python {} is required by this package\n".format(req.specifier)
125
+ else:
126
+ message = "ERROR: Python {} is required by {}\n".format(req.specifier, parent_package)
127
+ sys.stderr.write(message)
128
+ sys.exit(1)
129
+
130
+ if sys.version_info < __minimum_python_version__:
131
+
132
+ if parent_package is None:
133
+ message = "ERROR: Python {} or later is required by astropy-helpers\n".format(
134
+ __minimum_python_version__)
135
+ else:
136
+ message = "ERROR: Python {} or later is required by astropy-helpers for {}\n".format(
137
+ __minimum_python_version__, parent_package)
138
+
139
+ sys.stderr.write(message)
140
+ sys.exit(1)
141
+
142
+ _str_types = (str, bytes)
143
+
144
+
145
+ # What follows are several import statements meant to deal with install-time
146
+ # issues with either missing or misbehaving pacakges (including making sure
147
+ # setuptools itself is installed):
148
+
149
+ # Check that setuptools 30.3 or later is present
150
+ from distutils.version import LooseVersion
151
+
152
+ try:
153
+ import setuptools
154
+ assert LooseVersion(setuptools.__version__) >= LooseVersion('30.3')
155
+ except (ImportError, AssertionError):
156
+ sys.stderr.write("ERROR: setuptools 30.3 or later is required by astropy-helpers\n")
157
+ sys.exit(1)
158
+
159
+ # typing as a dependency for 1.6.1+ Sphinx causes issues when imported after
160
+ # initializing submodule with ah_boostrap.py
161
+ # See discussion and references in
162
+ # https://github.com/astropy/astropy-helpers/issues/302
163
+
164
+ try:
165
+ import typing # noqa
166
+ except ImportError:
167
+ pass
168
+
169
+
170
+ # Note: The following import is required as a workaround to
171
+ # https://github.com/astropy/astropy-helpers/issues/89; if we don't import this
172
+ # module now, it will get cleaned up after `run_setup` is called, but that will
173
+ # later cause the TemporaryDirectory class defined in it to stop working when
174
+ # used later on by setuptools
175
+ try:
176
+ import setuptools.py31compat # noqa
177
+ except ImportError:
178
+ pass
179
+
180
+
181
+ # matplotlib can cause problems if it is imported from within a call of
182
+ # run_setup(), because in some circumstances it will try to write to the user's
183
+ # home directory, resulting in a SandboxViolation. See
184
+ # https://github.com/matplotlib/matplotlib/pull/4165
185
+ # Making sure matplotlib, if it is available, is imported early in the setup
186
+ # process can mitigate this (note importing matplotlib.pyplot has the same
187
+ # issue)
188
+ try:
189
+ import matplotlib
190
+ matplotlib.use('Agg')
191
+ import matplotlib.pyplot
192
+ except:
193
+ # Ignore if this fails for *any* reason*
194
+ pass
195
+
196
+
197
+ # End compatibility imports...
198
+
199
+
200
+ class _Bootstrapper(object):
201
+ """
202
+ Bootstrapper implementation. See ``use_astropy_helpers`` for parameter
203
+ documentation.
204
+ """
205
+
206
+ def __init__(self, path=None, index_url=None, use_git=None, offline=None,
207
+ download_if_needed=None, auto_upgrade=None):
208
+
209
+ if path is None:
210
+ path = PACKAGE_NAME
211
+
212
+ if not (isinstance(path, _str_types) or path is False):
213
+ raise TypeError('path must be a string or False')
214
+
215
+ if not isinstance(path, str):
216
+ fs_encoding = sys.getfilesystemencoding()
217
+ path = path.decode(fs_encoding) # path to unicode
218
+
219
+ self.path = path
220
+
221
+ # Set other option attributes, using defaults where necessary
222
+ self.index_url = index_url if index_url is not None else INDEX_URL
223
+ self.offline = offline if offline is not None else OFFLINE
224
+
225
+ # If offline=True, override download and auto-upgrade
226
+ if self.offline:
227
+ download_if_needed = False
228
+ auto_upgrade = False
229
+
230
+ self.download = (download_if_needed
231
+ if download_if_needed is not None
232
+ else DOWNLOAD_IF_NEEDED)
233
+ self.auto_upgrade = (auto_upgrade
234
+ if auto_upgrade is not None else AUTO_UPGRADE)
235
+
236
+ # If this is a release then the .git directory will not exist so we
237
+ # should not use git.
238
+ git_dir_exists = os.path.exists(os.path.join(os.path.dirname(__file__), '.git'))
239
+ if use_git is None and not git_dir_exists:
240
+ use_git = False
241
+
242
+ self.use_git = use_git if use_git is not None else USE_GIT
243
+ # Declared as False by default--later we check if astropy-helpers can be
244
+ # upgraded from PyPI, but only if not using a source distribution (as in
245
+ # the case of import from a git submodule)
246
+ self.is_submodule = False
247
+
248
+ @classmethod
249
+ def main(cls, argv=None):
250
+ if argv is None:
251
+ argv = sys.argv
252
+
253
+ config = cls.parse_config()
254
+ config.update(cls.parse_command_line(argv))
255
+
256
+ auto_use = config.pop('auto_use', False)
257
+ bootstrapper = cls(**config)
258
+
259
+ if auto_use:
260
+ # Run the bootstrapper, otherwise the setup.py is using the old
261
+ # use_astropy_helpers() interface, in which case it will run the
262
+ # bootstrapper manually after reconfiguring it.
263
+ bootstrapper.run()
264
+
265
+ return bootstrapper
266
+
267
+ @classmethod
268
+ def parse_config(cls):
269
+
270
+ if not SETUP_CFG.has_section('ah_bootstrap'):
271
+ return {}
272
+
273
+ config = {}
274
+
275
+ for option, type_ in CFG_OPTIONS:
276
+ if not SETUP_CFG.has_option('ah_bootstrap', option):
277
+ continue
278
+
279
+ if type_ is bool:
280
+ value = SETUP_CFG.getboolean('ah_bootstrap', option)
281
+ else:
282
+ value = SETUP_CFG.get('ah_bootstrap', option)
283
+
284
+ config[option] = value
285
+
286
+ return config
287
+
288
+ @classmethod
289
+ def parse_command_line(cls, argv=None):
290
+ if argv is None:
291
+ argv = sys.argv
292
+
293
+ config = {}
294
+
295
+ # For now we just pop recognized ah_bootstrap options out of the
296
+ # arg list. This is imperfect; in the unlikely case that a setup.py
297
+ # custom command or even custom Distribution class defines an argument
298
+ # of the same name then we will break that. However there's a catch22
299
+ # here that we can't just do full argument parsing right here, because
300
+ # we don't yet know *how* to parse all possible command-line arguments.
301
+ if '--no-git' in argv:
302
+ config['use_git'] = False
303
+ argv.remove('--no-git')
304
+
305
+ if '--offline' in argv:
306
+ config['offline'] = True
307
+ argv.remove('--offline')
308
+
309
+ if '--auto-use' in argv:
310
+ config['auto_use'] = True
311
+ argv.remove('--auto-use')
312
+
313
+ if '--no-auto-use' in argv:
314
+ config['auto_use'] = False
315
+ argv.remove('--no-auto-use')
316
+
317
+ if '--use-system-astropy-helpers' in argv:
318
+ config['auto_use'] = False
319
+ argv.remove('--use-system-astropy-helpers')
320
+
321
+ return config
322
+
323
+ def run(self):
324
+ strategies = ['local_directory', 'local_file', 'index']
325
+ dist = None
326
+
327
+ # First, remove any previously imported versions of astropy_helpers;
328
+ # this is necessary for nested installs where one package's installer
329
+ # is installing another package via setuptools.sandbox.run_setup, as in
330
+ # the case of setup_requires
331
+ for key in list(sys.modules):
332
+ try:
333
+ if key == PACKAGE_NAME or key.startswith(PACKAGE_NAME + '.'):
334
+ del sys.modules[key]
335
+ except AttributeError:
336
+ # Sometimes mysterious non-string things can turn up in
337
+ # sys.modules
338
+ continue
339
+
340
+ # Check to see if the path is a submodule
341
+ self.is_submodule = self._check_submodule()
342
+
343
+ for strategy in strategies:
344
+ method = getattr(self, 'get_{0}_dist'.format(strategy))
345
+ dist = method()
346
+ if dist is not None:
347
+ break
348
+ else:
349
+ raise _AHBootstrapSystemExit(
350
+ "No source found for the {0!r} package; {0} must be "
351
+ "available and importable as a prerequisite to building "
352
+ "or installing this package.".format(PACKAGE_NAME))
353
+
354
+ # This is a bit hacky, but if astropy_helpers was loaded from a
355
+ # directory/submodule its Distribution object gets a "precedence" of
356
+ # "DEVELOP_DIST". However, in other cases it gets a precedence of
357
+ # "EGG_DIST". However, when activing the distribution it will only be
358
+ # placed early on sys.path if it is treated as an EGG_DIST, so always
359
+ # do that
360
+ dist = dist.clone(precedence=pkg_resources.EGG_DIST)
361
+
362
+ # Otherwise we found a version of astropy-helpers, so we're done
363
+ # Just active the found distribution on sys.path--if we did a
364
+ # download this usually happens automatically but it doesn't hurt to
365
+ # do it again
366
+ # Note: Adding the dist to the global working set also activates it
367
+ # (makes it importable on sys.path) by default.
368
+
369
+ try:
370
+ pkg_resources.working_set.add(dist, replace=True)
371
+ except TypeError:
372
+ # Some (much) older versions of setuptools do not have the
373
+ # replace=True option here. These versions are old enough that all
374
+ # bets may be off anyways, but it's easy enough to work around just
375
+ # in case...
376
+ if dist.key in pkg_resources.working_set.by_key:
377
+ del pkg_resources.working_set.by_key[dist.key]
378
+ pkg_resources.working_set.add(dist)
379
+
380
+ @property
381
+ def config(self):
382
+ """
383
+ A `dict` containing the options this `_Bootstrapper` was configured
384
+ with.
385
+ """
386
+
387
+ return dict((optname, getattr(self, optname))
388
+ for optname, _ in CFG_OPTIONS if hasattr(self, optname))
389
+
390
+ def get_local_directory_dist(self):
391
+ """
392
+ Handle importing a vendored package from a subdirectory of the source
393
+ distribution.
394
+ """
395
+
396
+ if not os.path.isdir(self.path):
397
+ return
398
+
399
+ log.info('Attempting to import astropy_helpers from {0} {1!r}'.format(
400
+ 'submodule' if self.is_submodule else 'directory',
401
+ self.path))
402
+
403
+ dist = self._directory_import()
404
+
405
+ if dist is None:
406
+ log.warn(
407
+ 'The requested path {0!r} for importing {1} does not '
408
+ 'exist, or does not contain a copy of the {1} '
409
+ 'package.'.format(self.path, PACKAGE_NAME))
410
+ elif self.auto_upgrade and not self.is_submodule:
411
+ # A version of astropy-helpers was found on the available path, but
412
+ # check to see if a bugfix release is available on PyPI
413
+ upgrade = self._do_upgrade(dist)
414
+ if upgrade is not None:
415
+ dist = upgrade
416
+
417
+ return dist
418
+
419
+ def get_local_file_dist(self):
420
+ """
421
+ Handle importing from a source archive; this also uses setup_requires
422
+ but points easy_install directly to the source archive.
423
+ """
424
+
425
+ if not os.path.isfile(self.path):
426
+ return
427
+
428
+ log.info('Attempting to unpack and import astropy_helpers from '
429
+ '{0!r}'.format(self.path))
430
+
431
+ try:
432
+ dist = self._do_download(find_links=[self.path])
433
+ except Exception as e:
434
+ if DEBUG:
435
+ raise
436
+
437
+ log.warn(
438
+ 'Failed to import {0} from the specified archive {1!r}: '
439
+ '{2}'.format(PACKAGE_NAME, self.path, str(e)))
440
+ dist = None
441
+
442
+ if dist is not None and self.auto_upgrade:
443
+ # A version of astropy-helpers was found on the available path, but
444
+ # check to see if a bugfix release is available on PyPI
445
+ upgrade = self._do_upgrade(dist)
446
+ if upgrade is not None:
447
+ dist = upgrade
448
+
449
+ return dist
450
+
451
+ def get_index_dist(self):
452
+ if not self.download:
453
+ log.warn('Downloading {0!r} disabled.'.format(DIST_NAME))
454
+ return None
455
+
456
+ log.warn(
457
+ "Downloading {0!r}; run setup.py with the --offline option to "
458
+ "force offline installation.".format(DIST_NAME))
459
+
460
+ try:
461
+ dist = self._do_download()
462
+ except Exception as e:
463
+ if DEBUG:
464
+ raise
465
+ log.warn(
466
+ 'Failed to download and/or install {0!r} from {1!r}:\n'
467
+ '{2}'.format(DIST_NAME, self.index_url, str(e)))
468
+ dist = None
469
+
470
+ # No need to run auto-upgrade here since we've already presumably
471
+ # gotten the most up-to-date version from the package index
472
+ return dist
473
+
474
+ def _directory_import(self):
475
+ """
476
+ Import astropy_helpers from the given path, which will be added to
477
+ sys.path.
478
+
479
+ Must return True if the import succeeded, and False otherwise.
480
+ """
481
+
482
+ # Return True on success, False on failure but download is allowed, and
483
+ # otherwise raise SystemExit
484
+ path = os.path.abspath(self.path)
485
+
486
+ # Use an empty WorkingSet rather than the man
487
+ # pkg_resources.working_set, since on older versions of setuptools this
488
+ # will invoke a VersionConflict when trying to install an upgrade
489
+ ws = pkg_resources.WorkingSet([])
490
+ ws.add_entry(path)
491
+ dist = ws.by_key.get(DIST_NAME)
492
+
493
+ if dist is None:
494
+ # We didn't find an egg-info/dist-info in the given path, but if a
495
+ # setup.py exists we can generate it
496
+ setup_py = os.path.join(path, 'setup.py')
497
+ if os.path.isfile(setup_py):
498
+ # We use subprocess instead of run_setup from setuptools to
499
+ # avoid segmentation faults - see the following for more details:
500
+ # https://github.com/cython/cython/issues/2104
501
+ sp.check_output([sys.executable, 'setup.py', 'egg_info'], cwd=path)
502
+
503
+ for dist in pkg_resources.find_distributions(path, True):
504
+ # There should be only one...
505
+ return dist
506
+
507
+ return dist
508
+
509
+ def _do_download(self, version='', find_links=None):
510
+ if find_links:
511
+ allow_hosts = ''
512
+ index_url = None
513
+ else:
514
+ allow_hosts = None
515
+ index_url = self.index_url
516
+
517
+ # Annoyingly, setuptools will not handle other arguments to
518
+ # Distribution (such as options) before handling setup_requires, so it
519
+ # is not straightforward to programmatically augment the arguments which
520
+ # are passed to easy_install
521
+ class _Distribution(Distribution):
522
+ def get_option_dict(self, command_name):
523
+ opts = Distribution.get_option_dict(self, command_name)
524
+ if command_name == 'easy_install':
525
+ if find_links is not None:
526
+ opts['find_links'] = ('setup script', find_links)
527
+ if index_url is not None:
528
+ opts['index_url'] = ('setup script', index_url)
529
+ if allow_hosts is not None:
530
+ opts['allow_hosts'] = ('setup script', allow_hosts)
531
+ return opts
532
+
533
+ if version:
534
+ req = '{0}=={1}'.format(DIST_NAME, version)
535
+ else:
536
+ if UPPER_VERSION_EXCLUSIVE is None:
537
+ req = DIST_NAME
538
+ else:
539
+ req = '{0}<{1}'.format(DIST_NAME, UPPER_VERSION_EXCLUSIVE)
540
+
541
+ attrs = {'setup_requires': [req]}
542
+
543
+ # NOTE: we need to parse the config file (e.g. setup.cfg) to make sure
544
+ # it honours the options set in the [easy_install] section, and we need
545
+ # to explicitly fetch the requirement eggs as setup_requires does not
546
+ # get honored in recent versions of setuptools:
547
+ # https://github.com/pypa/setuptools/issues/1273
548
+
549
+ try:
550
+
551
+ context = _verbose if DEBUG else _silence
552
+ with context():
553
+ dist = _Distribution(attrs=attrs)
554
+ try:
555
+ dist.parse_config_files(ignore_option_errors=True)
556
+ dist.fetch_build_eggs(req)
557
+ except TypeError:
558
+ # On older versions of setuptools, ignore_option_errors
559
+ # doesn't exist, and the above two lines are not needed
560
+ # so we can just continue
561
+ pass
562
+
563
+ # If the setup_requires succeeded it will have added the new dist to
564
+ # the main working_set
565
+ return pkg_resources.working_set.by_key.get(DIST_NAME)
566
+ except Exception as e:
567
+ if DEBUG:
568
+ raise
569
+
570
+ msg = 'Error retrieving {0} from {1}:\n{2}'
571
+ if find_links:
572
+ source = find_links[0]
573
+ elif index_url != INDEX_URL:
574
+ source = index_url
575
+ else:
576
+ source = 'PyPI'
577
+
578
+ raise Exception(msg.format(DIST_NAME, source, repr(e)))
579
+
580
+ def _do_upgrade(self, dist):
581
+ # Build up a requirement for a higher bugfix release but a lower minor
582
+ # release (so API compatibility is guaranteed)
583
+ next_version = _next_version(dist.parsed_version)
584
+
585
+ req = pkg_resources.Requirement.parse(
586
+ '{0}>{1},<{2}'.format(DIST_NAME, dist.version, next_version))
587
+
588
+ package_index = PackageIndex(index_url=self.index_url)
589
+
590
+ upgrade = package_index.obtain(req)
591
+
592
+ if upgrade is not None:
593
+ return self._do_download(version=upgrade.version)
594
+
595
+ def _check_submodule(self):
596
+ """
597
+ Check if the given path is a git submodule.
598
+
599
+ See the docstrings for ``_check_submodule_using_git`` and
600
+ ``_check_submodule_no_git`` for further details.
601
+ """
602
+
603
+ if (self.path is None or
604
+ (os.path.exists(self.path) and not os.path.isdir(self.path))):
605
+ return False
606
+
607
+ if self.use_git:
608
+ return self._check_submodule_using_git()
609
+ else:
610
+ return self._check_submodule_no_git()
611
+
612
+ def _check_submodule_using_git(self):
613
+ """
614
+ Check if the given path is a git submodule. If so, attempt to initialize
615
+ and/or update the submodule if needed.
616
+
617
+ This function makes calls to the ``git`` command in subprocesses. The
618
+ ``_check_submodule_no_git`` option uses pure Python to check if the given
619
+ path looks like a git submodule, but it cannot perform updates.
620
+ """
621
+
622
+ cmd = ['git', 'submodule', 'status', '--', self.path]
623
+
624
+ try:
625
+ log.info('Running `{0}`; use the --no-git option to disable git '
626
+ 'commands'.format(' '.join(cmd)))
627
+ returncode, stdout, stderr = run_cmd(cmd)
628
+ except _CommandNotFound:
629
+ # The git command simply wasn't found; this is most likely the
630
+ # case on user systems that don't have git and are simply
631
+ # trying to install the package from PyPI or a source
632
+ # distribution. Silently ignore this case and simply don't try
633
+ # to use submodules
634
+ return False
635
+
636
+ stderr = stderr.strip()
637
+
638
+ if returncode != 0 and stderr:
639
+ # Unfortunately the return code alone cannot be relied on, as
640
+ # earlier versions of git returned 0 even if the requested submodule
641
+ # does not exist
642
+
643
+ # This is a warning that occurs in perl (from running git submodule)
644
+ # which only occurs with a malformatted locale setting which can
645
+ # happen sometimes on OSX. See again
646
+ # https://github.com/astropy/astropy/issues/2749
647
+ perl_warning = ('perl: warning: Falling back to the standard locale '
648
+ '("C").')
649
+ if not stderr.strip().endswith(perl_warning):
650
+ # Some other unknown error condition occurred
651
+ log.warn('git submodule command failed '
652
+ 'unexpectedly:\n{0}'.format(stderr))
653
+ return False
654
+
655
+ # Output of `git submodule status` is as follows:
656
+ #
657
+ # 1: Status indicator: '-' for submodule is uninitialized, '+' if
658
+ # submodule is initialized but is not at the commit currently indicated
659
+ # in .gitmodules (and thus needs to be updated), or 'U' if the
660
+ # submodule is in an unstable state (i.e. has merge conflicts)
661
+ #
662
+ # 2. SHA-1 hash of the current commit of the submodule (we don't really
663
+ # need this information but it's useful for checking that the output is
664
+ # correct)
665
+ #
666
+ # 3. The output of `git describe` for the submodule's current commit
667
+ # hash (this includes for example what branches the commit is on) but
668
+ # only if the submodule is initialized. We ignore this information for
669
+ # now
670
+ _git_submodule_status_re = re.compile(
671
+ r'^(?P<status>[+-U ])(?P<commit>[0-9a-f]{40}) '
672
+ r'(?P<submodule>\S+)( .*)?$')
673
+
674
+ # The stdout should only contain one line--the status of the
675
+ # requested submodule
676
+ m = _git_submodule_status_re.match(stdout)
677
+ if m:
678
+ # Yes, the path *is* a git submodule
679
+ self._update_submodule(m.group('submodule'), m.group('status'))
680
+ return True
681
+ else:
682
+ log.warn(
683
+ 'Unexpected output from `git submodule status`:\n{0}\n'
684
+ 'Will attempt import from {1!r} regardless.'.format(
685
+ stdout, self.path))
686
+ return False
687
+
688
+ def _check_submodule_no_git(self):
689
+ """
690
+ Like ``_check_submodule_using_git``, but simply parses the .gitmodules file
691
+ to determine if the supplied path is a git submodule, and does not exec any
692
+ subprocesses.
693
+
694
+ This can only determine if a path is a submodule--it does not perform
695
+ updates, etc. This function may need to be updated if the format of the
696
+ .gitmodules file is changed between git versions.
697
+ """
698
+
699
+ gitmodules_path = os.path.abspath('.gitmodules')
700
+
701
+ if not os.path.isfile(gitmodules_path):
702
+ return False
703
+
704
+ # This is a minimal reader for gitconfig-style files. It handles a few of
705
+ # the quirks that make gitconfig files incompatible with ConfigParser-style
706
+ # files, but does not support the full gitconfig syntax (just enough
707
+ # needed to read a .gitmodules file).
708
+ gitmodules_fileobj = io.StringIO()
709
+
710
+ # Must use io.open for cross-Python-compatible behavior wrt unicode
711
+ with io.open(gitmodules_path) as f:
712
+ for line in f:
713
+ # gitconfig files are more flexible with leading whitespace; just
714
+ # go ahead and remove it
715
+ line = line.lstrip()
716
+
717
+ # comments can start with either # or ;
718
+ if line and line[0] in (':', ';'):
719
+ continue
720
+
721
+ gitmodules_fileobj.write(line)
722
+
723
+ gitmodules_fileobj.seek(0)
724
+
725
+ cfg = RawConfigParser()
726
+
727
+ try:
728
+ cfg.readfp(gitmodules_fileobj)
729
+ except Exception as exc:
730
+ log.warn('Malformatted .gitmodules file: {0}\n'
731
+ '{1} cannot be assumed to be a git submodule.'.format(
732
+ exc, self.path))
733
+ return False
734
+
735
+ for section in cfg.sections():
736
+ if not cfg.has_option(section, 'path'):
737
+ continue
738
+
739
+ submodule_path = cfg.get(section, 'path').rstrip(os.sep)
740
+
741
+ if submodule_path == self.path.rstrip(os.sep):
742
+ return True
743
+
744
+ return False
745
+
746
+ def _update_submodule(self, submodule, status):
747
+ if status == ' ':
748
+ # The submodule is up to date; no action necessary
749
+ return
750
+ elif status == '-':
751
+ if self.offline:
752
+ raise _AHBootstrapSystemExit(
753
+ "Cannot initialize the {0} submodule in --offline mode; "
754
+ "this requires being able to clone the submodule from an "
755
+ "online repository.".format(submodule))
756
+ cmd = ['update', '--init']
757
+ action = 'Initializing'
758
+ elif status == '+':
759
+ cmd = ['update']
760
+ action = 'Updating'
761
+ if self.offline:
762
+ cmd.append('--no-fetch')
763
+ elif status == 'U':
764
+ raise _AHBootstrapSystemExit(
765
+ 'Error: Submodule {0} contains unresolved merge conflicts. '
766
+ 'Please complete or abandon any changes in the submodule so that '
767
+ 'it is in a usable state, then try again.'.format(submodule))
768
+ else:
769
+ log.warn('Unknown status {0!r} for git submodule {1!r}. Will '
770
+ 'attempt to use the submodule as-is, but try to ensure '
771
+ 'that the submodule is in a clean state and contains no '
772
+ 'conflicts or errors.\n{2}'.format(status, submodule,
773
+ _err_help_msg))
774
+ return
775
+
776
+ err_msg = None
777
+ cmd = ['git', 'submodule'] + cmd + ['--', submodule]
778
+ log.warn('{0} {1} submodule with: `{2}`'.format(
779
+ action, submodule, ' '.join(cmd)))
780
+
781
+ try:
782
+ log.info('Running `{0}`; use the --no-git option to disable git '
783
+ 'commands'.format(' '.join(cmd)))
784
+ returncode, stdout, stderr = run_cmd(cmd)
785
+ except OSError as e:
786
+ err_msg = str(e)
787
+ else:
788
+ if returncode != 0:
789
+ err_msg = stderr
790
+
791
+ if err_msg is not None:
792
+ log.warn('An unexpected error occurred updating the git submodule '
793
+ '{0!r}:\n{1}\n{2}'.format(submodule, err_msg,
794
+ _err_help_msg))
795
+
796
+ class _CommandNotFound(OSError):
797
+ """
798
+ An exception raised when a command run with run_cmd is not found on the
799
+ system.
800
+ """
801
+
802
+
803
+ def run_cmd(cmd):
804
+ """
805
+ Run a command in a subprocess, given as a list of command-line
806
+ arguments.
807
+
808
+ Returns a ``(returncode, stdout, stderr)`` tuple.
809
+ """
810
+
811
+ try:
812
+ p = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE)
813
+ # XXX: May block if either stdout or stderr fill their buffers;
814
+ # however for the commands this is currently used for that is
815
+ # unlikely (they should have very brief output)
816
+ stdout, stderr = p.communicate()
817
+ except OSError as e:
818
+ if DEBUG:
819
+ raise
820
+
821
+ if e.errno == errno.ENOENT:
822
+ msg = 'Command not found: `{0}`'.format(' '.join(cmd))
823
+ raise _CommandNotFound(msg, cmd)
824
+ else:
825
+ raise _AHBootstrapSystemExit(
826
+ 'An unexpected error occurred when running the '
827
+ '`{0}` command:\n{1}'.format(' '.join(cmd), str(e)))
828
+
829
+
830
+ # Can fail of the default locale is not configured properly. See
831
+ # https://github.com/astropy/astropy/issues/2749. For the purposes under
832
+ # consideration 'latin1' is an acceptable fallback.
833
+ try:
834
+ stdio_encoding = locale.getdefaultlocale()[1] or 'latin1'
835
+ except ValueError:
836
+ # Due to an OSX oddity locale.getdefaultlocale() can also crash
837
+ # depending on the user's locale/language settings. See:
838
+ # http://bugs.python.org/issue18378
839
+ stdio_encoding = 'latin1'
840
+
841
+ # Unlikely to fail at this point but even then let's be flexible
842
+ if not isinstance(stdout, str):
843
+ stdout = stdout.decode(stdio_encoding, 'replace')
844
+ if not isinstance(stderr, str):
845
+ stderr = stderr.decode(stdio_encoding, 'replace')
846
+
847
+ return (p.returncode, stdout, stderr)
848
+
849
+
850
+ def _next_version(version):
851
+ """
852
+ Given a parsed version from pkg_resources.parse_version, returns a new
853
+ version string with the next minor version.
854
+
855
+ Examples
856
+ ========
857
+ >>> _next_version(pkg_resources.parse_version('1.2.3'))
858
+ '1.3.0'
859
+ """
860
+
861
+ if hasattr(version, 'base_version'):
862
+ # New version parsing from setuptools >= 8.0
863
+ if version.base_version:
864
+ parts = version.base_version.split('.')
865
+ else:
866
+ parts = []
867
+ else:
868
+ parts = []
869
+ for part in version:
870
+ if part.startswith('*'):
871
+ break
872
+ parts.append(part)
873
+
874
+ parts = [int(p) for p in parts]
875
+
876
+ if len(parts) < 3:
877
+ parts += [0] * (3 - len(parts))
878
+
879
+ major, minor, micro = parts[:3]
880
+
881
+ return '{0}.{1}.{2}'.format(major, minor + 1, 0)
882
+
883
+
884
+ class _DummyFile(object):
885
+ """A noop writeable object."""
886
+
887
+ errors = '' # Required for Python 3.x
888
+ encoding = 'utf-8'
889
+
890
+ def write(self, s):
891
+ pass
892
+
893
+ def flush(self):
894
+ pass
895
+
896
+
897
+ @contextlib.contextmanager
898
+ def _verbose():
899
+ yield
900
+
901
+ @contextlib.contextmanager
902
+ def _silence():
903
+ """A context manager that silences sys.stdout and sys.stderr."""
904
+
905
+ old_stdout = sys.stdout
906
+ old_stderr = sys.stderr
907
+ sys.stdout = _DummyFile()
908
+ sys.stderr = _DummyFile()
909
+ exception_occurred = False
910
+ try:
911
+ yield
912
+ except:
913
+ exception_occurred = True
914
+ # Go ahead and clean up so that exception handling can work normally
915
+ sys.stdout = old_stdout
916
+ sys.stderr = old_stderr
917
+ raise
918
+
919
+ if not exception_occurred:
920
+ sys.stdout = old_stdout
921
+ sys.stderr = old_stderr
922
+
923
+
924
+ _err_help_msg = """
925
+ If the problem persists consider installing astropy_helpers manually using pip
926
+ (`pip install astropy_helpers`) or by manually downloading the source archive,
927
+ extracting it, and installing by running `python setup.py install` from the
928
+ root of the extracted source code.
929
+ """
930
+
931
+
932
+ class _AHBootstrapSystemExit(SystemExit):
933
+ def __init__(self, *args):
934
+ if not args:
935
+ msg = 'An unknown problem occurred bootstrapping astropy_helpers.'
936
+ else:
937
+ msg = args[0]
938
+
939
+ msg += '\n' + _err_help_msg
940
+
941
+ super(_AHBootstrapSystemExit, self).__init__(msg, *args[1:])
942
+
943
+
944
+ BOOTSTRAPPER = _Bootstrapper.main()
945
+
946
+
947
+ def use_astropy_helpers(**kwargs):
948
+ """
949
+ Ensure that the `astropy_helpers` module is available and is importable.
950
+ This supports automatic submodule initialization if astropy_helpers is
951
+ included in a project as a git submodule, or will download it from PyPI if
952
+ necessary.
953
+
954
+ Parameters
955
+ ----------
956
+
957
+ path : str or None, optional
958
+ A filesystem path relative to the root of the project's source code
959
+ that should be added to `sys.path` so that `astropy_helpers` can be
960
+ imported from that path.
961
+
962
+ If the path is a git submodule it will automatically be initialized
963
+ and/or updated.
964
+
965
+ The path may also be to a ``.tar.gz`` archive of the astropy_helpers
966
+ source distribution. In this case the archive is automatically
967
+ unpacked and made temporarily available on `sys.path` as a ``.egg``
968
+ archive.
969
+
970
+ If `None` skip straight to downloading.
971
+
972
+ download_if_needed : bool, optional
973
+ If the provided filesystem path is not found an attempt will be made to
974
+ download astropy_helpers from PyPI. It will then be made temporarily
975
+ available on `sys.path` as a ``.egg`` archive (using the
976
+ ``setup_requires`` feature of setuptools. If the ``--offline`` option
977
+ is given at the command line the value of this argument is overridden
978
+ to `False`.
979
+
980
+ index_url : str, optional
981
+ If provided, use a different URL for the Python package index than the
982
+ main PyPI server.
983
+
984
+ use_git : bool, optional
985
+ If `False` no git commands will be used--this effectively disables
986
+ support for git submodules. If the ``--no-git`` option is given at the
987
+ command line the value of this argument is overridden to `False`.
988
+
989
+ auto_upgrade : bool, optional
990
+ By default, when installing a package from a non-development source
991
+ distribution ah_boostrap will try to automatically check for patch
992
+ releases to astropy-helpers on PyPI and use the patched version over
993
+ any bundled versions. Setting this to `False` will disable that
994
+ functionality. If the ``--offline`` option is given at the command line
995
+ the value of this argument is overridden to `False`.
996
+
997
+ offline : bool, optional
998
+ If `False` disable all actions that require an internet connection,
999
+ including downloading packages from the package index and fetching
1000
+ updates to any git submodule. Defaults to `True`.
1001
+ """
1002
+
1003
+ global BOOTSTRAPPER
1004
+
1005
+ config = BOOTSTRAPPER.config
1006
+ config.update(**kwargs)
1007
+
1008
+ # Create a new bootstrapper with the updated configuration and run it
1009
+ BOOTSTRAPPER = _Bootstrapper(**config)
1010
+ BOOTSTRAPPER.run()
testbed/astropy__astropy/appveyor.yml ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AppVeyor.com is a Continuous Integration service to build and run tests under
2
+ # Windows
3
+
4
+ environment:
5
+
6
+ global:
7
+ PYTHON: "C:\\conda"
8
+ MINICONDA_VERSION: "latest"
9
+ CMD_IN_ENV: "cmd /E:ON /V:ON /C .\\ci-helpers\\appveyor\\windows_sdk.cmd"
10
+ PYTHON_ARCH: "64" # needs to be set for CMD_IN_ENV to succeed. If a mix
11
+ # of 32 bit and 64 bit builds are needed, move this
12
+ # to the matrix section.
13
+ CONDA_DEPENDENCIES: "Cython scipy h5py beautifulsoup4 html5lib jinja2 pyyaml matplotlib scikit-image pytz pandas"
14
+ PIP_DEPENDENCIES: "objgraph asdf"
15
+
16
+ matrix:
17
+ - PYTHON_VERSION: "3.7"
18
+ NUMPY_VERSION: "stable"
19
+
20
+ matrix:
21
+ fast_finish: true
22
+
23
+ platform:
24
+ -x64
25
+
26
+ os: Visual Studio 2017
27
+
28
+ install:
29
+ - "git clone git://github.com/astropy/ci-helpers.git"
30
+ - "powershell ci-helpers/appveyor/install-miniconda.ps1"
31
+ - "SET PATH=%PYTHON%;%PYTHON%\\Scripts;%PATH%"
32
+ - "activate test"
33
+
34
+ # Not a .NET project, we build Astropy in the install step instead
35
+ build: false
36
+
37
+ test_script:
38
+ - "%CMD_IN_ENV% python setup.py test --readonly"
testbed/astropy__astropy/astropy/CITATION ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ If you use Astropy for work/research presented in a publication (whether
2
+ directly, or as a dependency to another package), we recommend and encourage
3
+ the following acknowledgment:
4
+
5
+ This research made use of Astropy, a community-developed core Python package
6
+ for Astronomy (Astropy Collaboration, 2018).
7
+
8
+ where (Astropy Collaboration, 2018) is a citation to this paper:
9
+
10
+ http://adsabs.harvard.edu/abs/2018AJ....156..123T
11
+
12
+ An earlier paper is also available describing the status of the package at
13
+ the time of v0.2. If you have used Astropy for a long time, you are
14
+ encouraged to acknowledge both papers:
15
+
16
+ This research made use of Astropy, a community-developed core Python package
17
+ for Astronomy (Astropy Collaboration, 2013, 2018).
18
+
19
+ where (Astropy Collaboration, 2013) is a citation to this paper:
20
+
21
+ http://adsabs.harvard.edu/abs/2013A%26A...558A..33A
22
+
23
+ We encourage you to also include citations to the papers in the main text
24
+ wherever appropriate.
25
+
26
+
27
+ Recommended BibTeX entries for the above citations are:
28
+
29
+ @ARTICLE{2018AJ....156..123T,
30
+ author = {{The Astropy Collaboration} and {Price-Whelan}, A.~M. and {Sip{\H o}cz}, B.~M. and
31
+ {G{\"u}nther}, H.~M. and {Lim}, P.~L. and {Crawford}, S.~M. and
32
+ {Conseil}, S. and {Shupe}, D.~L. and {Craig}, M.~W. and {Dencheva}, N. and
33
+ {Ginsburg}, A. and {VanderPlas}, J.~T. and {Bradley}, L.~D. and
34
+ {P{\'e}rez-Su{\'a}rez}, D. and {de Val-Borro}, M. and {Paper Contributors}, (. and
35
+ {Aldcroft}, T.~L. and {Cruz}, K.~L. and {Robitaille}, T.~P. and
36
+ {Tollerud}, E.~J. and {Coordination Committee}, (. and {Ardelean}, C. and
37
+ {Babej}, T. and {Bach}, Y.~P. and {Bachetti}, M. and {Bakanov}, A.~V. and
38
+ {Bamford}, S.~P. and {Barentsen}, G. and {Barmby}, P. and {Baumbach}, A. and
39
+ {Berry}, K.~L. and {Biscani}, F. and {Boquien}, M. and {Bostroem}, K.~A. and
40
+ {Bouma}, L.~G. and {Brammer}, G.~B. and {Bray}, E.~M. and {Breytenbach}, H. and
41
+ {Buddelmeijer}, H. and {Burke}, D.~J. and {Calderone}, G. and
42
+ {Cano Rodr{\'{\i}}guez}, J.~L. and {Cara}, M. and {Cardoso}, J.~V.~M. and
43
+ {Cheedella}, S. and {Copin}, Y. and {Corrales}, L. and {Crichton}, D. and
44
+ {D{\rsquo}Avella}, D. and {Deil}, C. and {Depagne}, {\'E}. and
45
+ {Dietrich}, J.~P. and {Donath}, A. and {Droettboom}, M. and
46
+ {Earl}, N. and {Erben}, T. and {Fabbro}, S. and {Ferreira}, L.~A. and
47
+ {Finethy}, T. and {Fox}, R.~T. and {Garrison}, L.~H. and {Gibbons}, S.~L.~J. and
48
+ {Goldstein}, D.~A. and {Gommers}, R. and {Greco}, J.~P. and
49
+ {Greenfield}, P. and {Groener}, A.~M. and {Grollier}, F. and
50
+ {Hagen}, A. and {Hirst}, P. and {Homeier}, D. and {Horton}, A.~J. and
51
+ {Hosseinzadeh}, G. and {Hu}, L. and {Hunkeler}, J.~S. and {Ivezi{\'c}}, {\v Z}. and
52
+ {Jain}, A. and {Jenness}, T. and {Kanarek}, G. and {Kendrew}, S. and
53
+ {Kern}, N.~S. and {Kerzendorf}, W.~E. and {Khvalko}, A. and
54
+ {King}, J. and {Kirkby}, D. and {Kulkarni}, A.~M. and {Kumar}, A. and
55
+ {Lee}, A. and {Lenz}, D. and {Littlefair}, S.~P. and {Ma}, Z. and
56
+ {Macleod}, D.~M. and {Mastropietro}, M. and {McCully}, C. and
57
+ {Montagnac}, S. and {Morris}, B.~M. and {Mueller}, M. and {Mumford}, S.~J. and
58
+ {Muna}, D. and {Murphy}, N.~A. and {Nelson}, S. and {Nguyen}, G.~H. and
59
+ {Ninan}, J.~P. and {N{\"o}the}, M. and {Ogaz}, S. and {Oh}, S. and
60
+ {Parejko}, J.~K. and {Parley}, N. and {Pascual}, S. and {Patil}, R. and
61
+ {Patil}, A.~A. and {Plunkett}, A.~L. and {Prochaska}, J.~X. and
62
+ {Rastogi}, T. and {Reddy Janga}, V. and {Sabater}, J. and {Sakurikar}, P. and
63
+ {Seifert}, M. and {Sherbert}, L.~E. and {Sherwood-Taylor}, H. and
64
+ {Shih}, A.~Y. and {Sick}, J. and {Silbiger}, M.~T. and {Singanamalla}, S. and
65
+ {Singer}, L.~P. and {Sladen}, P.~H. and {Sooley}, K.~A. and
66
+ {Sornarajah}, S. and {Streicher}, O. and {Teuben}, P. and {Thomas}, S.~W. and
67
+ {Tremblay}, G.~R. and {Turner}, J.~E.~H. and {Terr{\'o}n}, V. and
68
+ {van Kerkwijk}, M.~H. and {de la Vega}, A. and {Watkins}, L.~L. and
69
+ {Weaver}, B.~A. and {Whitmore}, J.~B. and {Woillez}, J. and
70
+ {Zabalza}, V. and {Contributors}, (.},
71
+ title = "{The Astropy Project: Building an Open-science Project and Status of the v2.0 Core Package}",
72
+ journal = {\aj},
73
+ archivePrefix = "arXiv",
74
+ eprint = {1801.02634},
75
+ primaryClass = "astro-ph.IM",
76
+ keywords = {methods: data analysis, methods: miscellaneous, methods: statistical, reference systems },
77
+ year = 2018,
78
+ month = sep,
79
+ volume = 156,
80
+ eid = {123},
81
+ pages = {123},
82
+ doi = {10.3847/1538-3881/aabc4f},
83
+ adsurl = {http://adsabs.harvard.edu/abs/2018AJ....156..123T},
84
+ adsnote = {Provided by the SAO/NASA Astrophysics Data System}
85
+ }
86
+
87
+ @ARTICLE{2013A&A...558A..33A,
88
+ author = {{Astropy Collaboration} and {Robitaille}, T.~P. and {Tollerud}, E.~J. and
89
+ {Greenfield}, P. and {Droettboom}, M. and {Bray}, E. and {Aldcroft}, T. and
90
+ {Davis}, M. and {Ginsburg}, A. and {Price-Whelan}, A.~M. and
91
+ {Kerzendorf}, W.~E. and {Conley}, A. and {Crighton}, N. and
92
+ {Barbary}, K. and {Muna}, D. and {Ferguson}, H. and {Grollier}, F. and
93
+ {Parikh}, M.~M. and {Nair}, P.~H. and {Unther}, H.~M. and {Deil}, C. and
94
+ {Woillez}, J. and {Conseil}, S. and {Kramer}, R. and {Turner}, J.~E.~H. and
95
+ {Singer}, L. and {Fox}, R. and {Weaver}, B.~A. and {Zabalza}, V. and
96
+ {Edwards}, Z.~I. and {Azalee Bostroem}, K. and {Burke}, D.~J. and
97
+ {Casey}, A.~R. and {Crawford}, S.~M. and {Dencheva}, N. and
98
+ {Ely}, J. and {Jenness}, T. and {Labrie}, K. and {Lian Lim}, P. and
99
+ {Pierfederici}, F. and {Pontzen}, A. and {Ptak}, A. and {Refsdal}, B. and
100
+ {Servillat}, M. and {Streicher}, O.},
101
+ title = "{Astropy: A community Python package for astronomy}",
102
+ journal = {\aap},
103
+ keywords = {methods: data analysis, methods: miscellaneous, virtual observatory tools},
104
+ year = 2013,
105
+ month = oct,
106
+ volume = 558,
107
+ eid = {A33},
108
+ pages = {A33},
109
+ doi = {10.1051/0004-6361/201322068},
110
+ adsurl = {http://adsabs.harvard.edu/abs/2013A%26A...558A..33A},
111
+ adsnote = {Provided by the SAO/NASA Astrophysics Data System}
112
+ }
testbed/astropy__astropy/astropy/__init__.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+ """
3
+ Astropy is a package intended to contain core functionality and some
4
+ common tools needed for performing astronomy and astrophysics research with
5
+ Python. It also provides an index for other astronomy packages and tools for
6
+ managing them.
7
+ """
8
+
9
+ # Prior to Astropy 3.2, astropy was imported during setup.py commands. If we are
10
+ # in setup mode, then astropy-helpers defines an _ASTROPY_SETUP_ variable, which
11
+ # we used to use to conditionally import C extensions for example. However, the
12
+ # behavior of importing the package during the setup process is not good
13
+ # practice and we therefore now explicitly prevent the package from being
14
+ # imported in that case to prevent any regressions. We use _ASTROPY_CORE_SETUP_
15
+ # (defined in setup.py) rather than _ASTROPY_SETUP_ since the latter is also
16
+ # set up for affiliated packages, and those need to be able to import the
17
+ # (installed) core package during e.g. python setup.py test.
18
+ try:
19
+ _ASTROPY_CORE_SETUP_
20
+ except NameError:
21
+ pass
22
+ else:
23
+ raise RuntimeError("The astropy package cannot be imported during setup")
24
+
25
+ import sys
26
+ import os
27
+ from warnings import warn
28
+
29
+ __minimum_python_version__ = '3.5'
30
+ __minimum_numpy_version__ = '1.13.0'
31
+ # ASDF is an optional dependency, but this is the minimum version that is
32
+ # compatible with Astropy when it is installed.
33
+ __minimum_asdf_version__ = '2.3.0'
34
+
35
+
36
+ class UnsupportedPythonError(Exception):
37
+ pass
38
+
39
+
40
+ # This is the same check as the one at the top of setup.py
41
+ if sys.version_info < tuple((int(val) for val in __minimum_python_version__.split('.'))):
42
+ raise UnsupportedPythonError("Astropy does not support Python < {}".format(__minimum_python_version__))
43
+
44
+
45
+ def _is_astropy_source(path=None):
46
+ """
47
+ Returns whether the source for this module is directly in an astropy
48
+ source distribution or checkout.
49
+ """
50
+
51
+ # If this __init__.py file is in ./astropy/ then import is within a source
52
+ # dir .astropy-root is a file distributed with the source, but that should
53
+ # not installed
54
+ if path is None:
55
+ path = os.path.join(os.path.dirname(__file__), os.pardir)
56
+ elif os.path.isfile(path):
57
+ path = os.path.dirname(path)
58
+
59
+ source_dir = os.path.abspath(path)
60
+ return os.path.exists(os.path.join(source_dir, '.astropy-root'))
61
+
62
+
63
+ def _is_astropy_setup():
64
+ """
65
+ Returns whether we are currently being imported in the context of running
66
+ Astropy's setup.py.
67
+ """
68
+
69
+ main_mod = sys.modules.get('__main__')
70
+ if not main_mod:
71
+ return False
72
+
73
+ return (getattr(main_mod, '__file__', False) and
74
+ os.path.basename(main_mod.__file__).rstrip('co') == 'setup.py' and
75
+ _is_astropy_source(main_mod.__file__))
76
+
77
+ try:
78
+ from .version import version as __version__
79
+ except ImportError:
80
+ # TODO: Issue a warning using the logging framework
81
+ __version__ = ''
82
+ try:
83
+ from .version import githash as __githash__
84
+ except ImportError:
85
+ # TODO: Issue a warning using the logging framework
86
+ __githash__ = ''
87
+
88
+
89
+ # The location of the online documentation for astropy
90
+ # This location will normally point to the current released version of astropy
91
+ if 'dev' in __version__:
92
+ online_docs_root = 'http://docs.astropy.org/en/latest/'
93
+ else:
94
+ online_docs_root = 'http://docs.astropy.org/en/{0}/'.format(__version__)
95
+
96
+
97
+ def _check_numpy():
98
+ """
99
+ Check that Numpy is installed and it is of the minimum version we
100
+ require.
101
+ """
102
+ # Note: We could have used distutils.version for this comparison,
103
+ # but it seems like overkill to import distutils at runtime.
104
+ requirement_met = False
105
+
106
+ try:
107
+ import numpy
108
+ except ImportError:
109
+ pass
110
+ else:
111
+ from .utils import minversion
112
+ requirement_met = minversion(numpy, __minimum_numpy_version__)
113
+
114
+ if not requirement_met:
115
+ msg = ("Numpy version {0} or later must be installed to use "
116
+ "Astropy".format(__minimum_numpy_version__))
117
+ raise ImportError(msg)
118
+
119
+ return numpy
120
+
121
+
122
+ _check_numpy()
123
+
124
+
125
+ from . import config as _config
126
+
127
+
128
+ class Conf(_config.ConfigNamespace):
129
+ """
130
+ Configuration parameters for `astropy`.
131
+ """
132
+
133
+ unicode_output = _config.ConfigItem(
134
+ False,
135
+ 'When True, use Unicode characters when outputting values, and '
136
+ 'displaying widgets at the console.')
137
+ use_color = _config.ConfigItem(
138
+ sys.platform != 'win32',
139
+ 'When True, use ANSI color escape sequences when writing to the console.',
140
+ aliases=['astropy.utils.console.USE_COLOR', 'astropy.logger.USE_COLOR'])
141
+ max_lines = _config.ConfigItem(
142
+ None,
143
+ description='Maximum number of lines in the display of pretty-printed '
144
+ 'objects. If not provided, try to determine automatically from the '
145
+ 'terminal size. Negative numbers mean no limit.',
146
+ cfgtype='integer(default=None)',
147
+ aliases=['astropy.table.pprint.max_lines'])
148
+ max_width = _config.ConfigItem(
149
+ None,
150
+ description='Maximum number of characters per line in the display of '
151
+ 'pretty-printed objects. If not provided, try to determine '
152
+ 'automatically from the terminal size. Negative numbers mean no '
153
+ 'limit.',
154
+ cfgtype='integer(default=None)',
155
+ aliases=['astropy.table.pprint.max_width'])
156
+
157
+
158
+ conf = Conf()
159
+
160
+ # Create the test() function
161
+ from .tests.runner import TestRunner
162
+ test = TestRunner.make_test_runner_in(__path__[0])
163
+
164
+
165
+ # if we are *not* in setup mode, import the logger and possibly populate the
166
+ # configuration file with the defaults
167
+ def _initialize_astropy():
168
+ from . import config
169
+
170
+ def _rollback_import(message):
171
+ log.error(message)
172
+ # Now disable exception logging to avoid an annoying error in the
173
+ # exception logger before we raise the import error:
174
+ _teardown_log()
175
+
176
+ # Roll back any astropy sub-modules that have been imported thus
177
+ # far
178
+
179
+ for key in list(sys.modules):
180
+ if key.startswith('astropy.'):
181
+ del sys.modules[key]
182
+ raise ImportError('astropy')
183
+
184
+ try:
185
+ from .utils import _compiler
186
+ except ImportError:
187
+ if _is_astropy_source():
188
+ log.warning('You appear to be trying to import astropy from '
189
+ 'within a source checkout without building the '
190
+ 'extension modules first. Attempting to (re)build '
191
+ 'extension modules:')
192
+
193
+ try:
194
+ _rebuild_extensions()
195
+ except BaseException as exc:
196
+ _rollback_import(
197
+ 'An error occurred while attempting to rebuild the '
198
+ 'extension modules. Please try manually running '
199
+ '`./setup.py develop` or `./setup.py build_ext '
200
+ '--inplace` to see what the issue was. Extension '
201
+ 'modules must be successfully compiled and importable '
202
+ 'in order to import astropy.')
203
+ # Reraise the Exception only in case it wasn't an Exception,
204
+ # for example if a "SystemExit" or "KeyboardInterrupt" was
205
+ # invoked.
206
+ if not isinstance(exc, Exception):
207
+ raise
208
+
209
+ else:
210
+ # Outright broken installation; don't be nice.
211
+ raise
212
+
213
+ # add these here so we only need to cleanup the namespace at the end
214
+ config_dir = os.path.dirname(__file__)
215
+
216
+ try:
217
+ config.configuration.update_default_config(__package__, config_dir)
218
+ except config.configuration.ConfigurationDefaultMissingError as e:
219
+ wmsg = (e.args[0] + " Cannot install default profile. If you are "
220
+ "importing from source, this is expected.")
221
+ warn(config.configuration.ConfigurationDefaultMissingWarning(wmsg))
222
+
223
+
224
+ def _rebuild_extensions():
225
+ global __version__
226
+ global __githash__
227
+
228
+ import subprocess
229
+ import time
230
+
231
+ from .utils.console import Spinner
232
+
233
+ devnull = open(os.devnull, 'w')
234
+ old_cwd = os.getcwd()
235
+ os.chdir(os.path.join(os.path.dirname(__file__), os.pardir))
236
+ try:
237
+ sp = subprocess.Popen([sys.executable, 'setup.py', 'build_ext',
238
+ '--inplace'], stdout=devnull,
239
+ stderr=devnull)
240
+ with Spinner('Rebuilding extension modules') as spinner:
241
+ while sp.poll() is None:
242
+ next(spinner)
243
+ time.sleep(0.05)
244
+ finally:
245
+ os.chdir(old_cwd)
246
+ devnull.close()
247
+
248
+ if sp.returncode != 0:
249
+ raise OSError('Running setup.py build_ext --inplace failed '
250
+ 'with error code {0}: try rerunning this command '
251
+ 'manually to check what the error was.'.format(
252
+ sp.returncode))
253
+
254
+ # Try re-loading module-level globals from the astropy.version module,
255
+ # which may not have existed before this function ran
256
+ try:
257
+ from .version import version as __version__
258
+ except ImportError:
259
+ pass
260
+
261
+ try:
262
+ from .version import githash as __githash__
263
+ except ImportError:
264
+ pass
265
+
266
+
267
+ # Set the bibtex entry to the article referenced in CITATION.
268
+ def _get_bibtex():
269
+ citation_file = os.path.join(os.path.dirname(__file__), 'CITATION')
270
+
271
+ with open(citation_file, 'r') as citation:
272
+ refs = citation.read().split('@ARTICLE')[1:]
273
+ if len(refs) == 0: return ''
274
+ bibtexreference = "@ARTICLE{0}".format(refs[0])
275
+ return bibtexreference
276
+
277
+
278
+ __citation__ = __bibtex__ = _get_bibtex()
279
+
280
+ import logging
281
+
282
+ # Use the root logger as a dummy log before initilizing Astropy's logger
283
+ log = logging.getLogger()
284
+
285
+
286
+ from .logger import _init_log, _teardown_log
287
+
288
+ log = _init_log()
289
+
290
+ _initialize_astropy()
291
+
292
+ from .utils.misc import find_api_page
293
+
294
+
295
+ def online_help(query):
296
+ """
297
+ Search the online Astropy documentation for the given query.
298
+ Opens the results in the default web browser. Requires an active
299
+ Internet connection.
300
+
301
+ Parameters
302
+ ----------
303
+ query : str
304
+ The search query.
305
+ """
306
+ from urllib.parse import urlencode
307
+ import webbrowser
308
+
309
+ version = __version__
310
+ if 'dev' in version:
311
+ version = 'latest'
312
+ else:
313
+ version = 'v' + version
314
+
315
+ url = 'http://docs.astropy.org/en/{0}/search.html?{1}'.format(
316
+ version, urlencode({'q': query}))
317
+
318
+ webbrowser.open(url)
319
+
320
+
321
+ __dir_inc__ = ['__version__', '__githash__', '__minimum_numpy_version__',
322
+ '__bibtex__', 'test', 'log', 'find_api_page', 'online_help',
323
+ 'online_docs_root', 'conf']
324
+
325
+
326
+ from types import ModuleType as __module_type__
327
+ # Clean up top-level namespace--delete everything that isn't in __dir_inc__
328
+ # or is a magic attribute, and that isn't a submodule of this package
329
+ for varname in dir():
330
+ if not ((varname.startswith('__') and varname.endswith('__')) or
331
+ varname in __dir_inc__ or
332
+ (varname[0] != '_' and
333
+ isinstance(locals()[varname], __module_type__) and
334
+ locals()[varname].__name__.startswith(__name__ + '.'))):
335
+ # The last clause in the the above disjunction deserves explanation:
336
+ # When using relative imports like ``from .. import config``, the
337
+ # ``config`` variable is automatically created in the namespace of
338
+ # whatever module ``..`` resolves to (in this case astropy). This
339
+ # happens a few times just in the module setup above. This allows
340
+ # the cleanup to keep any public submodules of the astropy package
341
+ del locals()[varname]
342
+
343
+ del varname, __module_type__
testbed/astropy__astropy/astropy/_erfa/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+
3
+ from .core import *
testbed/astropy__astropy/astropy/_erfa/core.py.templ ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+
3
+ # "core.py" is auto-generated by erfa_generator.py from the template
4
+ # "core.py.templ". Do *not* edit "core.py" directly, instead edit
5
+ # "core.py.templ" and run erfa_generator.py from the source directory to
6
+ # update it.
7
+
8
+ """
9
+ Python wrappers for the ufunc wrappers of the ERFA library.
10
+
11
+ ..warning::
12
+ This is currently *not* part of the public Astropy API, and may change in
13
+ the future.
14
+
15
+ The key idea is that any function can be called with inputs that are arrays,
16
+ and the ufuncs will automatically vectorize and call the ERFA functions for
17
+ each item using broadcasting rules for numpy. So the return values are always
18
+ numpy arrays of some sort.
19
+
20
+ For ERFA functions that take/return vectors or matrices, the vector/matrix
21
+ dimension(s) are always the *last* dimension(s). For example, if you
22
+ want to give ten matrices (i.e., the ERFA input type is double[3][3]),
23
+ you would pass in a (10, 3, 3) numpy array. If the output of the ERFA
24
+ function is scalar, you'll get back a length-10 1D array.
25
+ (Note that the ufuncs take this into account using structured dtypes.)
26
+
27
+ Note that the ufunc part of these functions are implemented in a separate
28
+ module (compiled as ``ufunc``), derived from the ``ufunc.c`` file.
29
+ """
30
+
31
+ import warnings
32
+
33
+ import numpy
34
+
35
+ # we import these exceptions from astropy locations instead of defining them
36
+ # in this file because otherwise there are circular dependencies
37
+ from astropy.utils.exceptions import ErfaError, ErfaWarning
38
+ from astropy.utils.misc import check_broadcast
39
+
40
+ from . import ufunc
41
+ from .ufunc import (dt_eraASTROM, dt_eraLDBODY, dt_pv,
42
+ dt_sign, dt_type, dt_ymdf, dt_hmsf, dt_dmsf)
43
+
44
+ __all__ = ['ErfaError', 'ErfaWarning',
45
+ {{ funcs|map(attribute='pyname')|surround("'","'")|join(", ") }},
46
+ {{ constants|map(attribute='name')|surround("'","'")|join(", ") }},
47
+ # TODO: delete the functions below when they can get auto-generated
48
+ 'version', 'version_major', 'version_minor', 'version_micro', 'sofa_version',
49
+ 'dt_eraASTROM', 'dt_eraLDBODY', 'dt_pv', 'dt_ymdf', 'dt_hmsf', 'dt_dmsf']
50
+
51
+
52
+ # <---------------------------------Error-handling---------------------------->
53
+
54
+
55
+ STATUS_CODES = {} # populated below before each function that returns an int
56
+
57
+ # This is a hard-coded list of status codes that need to be remapped,
58
+ # such as to turn errors into warnings.
59
+ STATUS_CODES_REMAP = {
60
+ 'cal2jd': {-3: 3}
61
+ }
62
+
63
+
64
+ def check_errwarn(statcodes, func_name):
65
+ if not numpy.any(statcodes):
66
+ return
67
+ # Remap any errors into warnings in the STATUS_CODES_REMAP dict.
68
+ if func_name in STATUS_CODES_REMAP:
69
+ for before, after in STATUS_CODES_REMAP[func_name].items():
70
+ statcodes[statcodes == before] = after
71
+ STATUS_CODES[func_name][after] = STATUS_CODES[func_name][before]
72
+
73
+ if numpy.any(statcodes<0):
74
+ # errors present - only report the errors.
75
+ if statcodes.shape:
76
+ statcodes = statcodes[statcodes<0]
77
+
78
+ errcodes = numpy.unique(statcodes)
79
+
80
+ errcounts = dict([(e, numpy.sum(statcodes==e)) for e in errcodes])
81
+
82
+ elsemsg = STATUS_CODES[func_name].get('else', None)
83
+ if elsemsg is None:
84
+ errmsgs = dict([(e, STATUS_CODES[func_name].get(e, 'Return code ' + str(e))) for e in errcodes])
85
+ else:
86
+ errmsgs = dict([(e, STATUS_CODES[func_name].get(e, elsemsg)) for e in errcodes])
87
+
88
+ emsg = ', '.join(['{0} of "{1}"'.format(errcounts[e], errmsgs[e]) for e in errcodes])
89
+ raise ErfaError('ERFA function "' + func_name + '" yielded ' + emsg)
90
+
91
+ elif numpy.any(statcodes>0):
92
+ #only warnings present
93
+ if statcodes.shape:
94
+ statcodes = statcodes[statcodes>0]
95
+
96
+ warncodes = numpy.unique(statcodes)
97
+
98
+ warncounts = dict([(w, numpy.sum(statcodes==w)) for w in warncodes])
99
+
100
+ elsemsg = STATUS_CODES[func_name].get('else', None)
101
+ if elsemsg is None:
102
+ warnmsgs = dict([(w, STATUS_CODES[func_name].get(w, 'Return code ' + str(w))) for w in warncodes])
103
+ else:
104
+ warnmsgs = dict([(w, STATUS_CODES[func_name].get(w, elsemsg)) for w in warncodes])
105
+
106
+ wmsg = ', '.join(['{0} of "{1}"'.format(warncounts[w], warnmsgs[w]) for w in warncodes])
107
+ warnings.warn('ERFA function "' + func_name + '" yielded ' + wmsg, ErfaWarning)
108
+
109
+
110
+ # <------------------------structured dtype conversion------------------------>
111
+
112
+ {%- if NUMPY_LT_1_16 %}
113
+ # Note: the following are only necessary for NUMPY_LT_1_16. Once we support
114
+ # only numpy >=1.16, they can be removed, and the template code below should be
115
+ # adapted. Note that for >=1.16, these are not used, since the template parts
116
+ # that use it are never inserted (since `d3_fix_arg` is always empty).
117
+ class D3Fix(numpy.ndarray):
118
+ """NDarray subclass that can transfer itself into a Quantity.
119
+
120
+ For the rationale for this, see arrayify_inputs_and_create_d3_fix.
121
+ """
122
+ def __quantity_subclass__(self, unit):
123
+ return type(self), True
124
+
125
+ def __array_wrap__(self, obj, context):
126
+ return obj.view(numpy.ndarray)
127
+
128
+
129
+ def arrayify_inputs_and_create_d3_fix(inputs, core_dims, out_core_shape, out_dtype):
130
+ """Create an empty array of the right trailing shape.
131
+
132
+ Gufuncs currently do not allow one to pass in fixed dimensions, which
133
+ means that for functions with signatures like `()->(n)`, one has to pass in
134
+ an output argument for the gufunc to determine `n` (to be 3 for instance).
135
+
136
+ For those gufuncs, this functions creates the output array upfront,
137
+ with properly broadcast dimensions.
138
+
139
+ A problem that arises, though, is that if anything overrides the function
140
+ using ``__array_ufunc__``, it will fail because the output is of the wrong
141
+ class. To work around this for `~astropy.units.Quantity` at least, we
142
+ create the output with a special class (``D3Fix``), which has an
143
+ ``__array_wrap__`` that will turn it into a regular ndarray for normal
144
+ usage, and a ``__quantity_subclass__`` that allows it to be replaced by a
145
+ `~astropy.units.Quantity`.
146
+
147
+ Obviously, this is a hack, and only works easily for Quantity (which,
148
+ however, is the only class likely to use this private implementation). As
149
+ an alternative, one could create a regular empty ndarray and then remove
150
+ it in the C type resolver, so that a new one with the proper class is
151
+ created by the iterator. But that seemed even more fragile.
152
+
153
+ Parameters
154
+ ----------
155
+ inputs : array-like
156
+ Input arguments, used to determine the required broadcast shape.
157
+ core_dims: list of int
158
+ Number of core dimensions for the inputs; these are removed for
159
+ calculating the broadcast shape.
160
+ out_core_shape : tuple
161
+ Output core shape; the full shape will be the broadcast shape
162
+ determined from the inputs plus this core shape.
163
+ out_dtype : `~numpy.dtype`
164
+ Data type of the array.
165
+
166
+ Notes
167
+ -----
168
+ Once https://github.com/numpy/numpy/pull/11175 is in, this will no
169
+ longer be necessary for all but NUMPY_LT_1_16, since we'll be able to just
170
+ define the signature with explicit numerical dimensions.
171
+ """
172
+ shapes = []
173
+ arrays = []
174
+ for input, core_dim in zip(inputs, core_dims):
175
+ try:
176
+ shape = input.shape
177
+ except AttributeError:
178
+ input = numpy.asanyarray(input)
179
+ shape = input.shape
180
+ shapes.append(shape[:-core_dim] if core_dim else shape)
181
+ arrays.append(input)
182
+
183
+ broadcast_shape = check_broadcast(*shapes)
184
+ d3_fix = numpy.empty(broadcast_shape + out_core_shape, out_dtype).view(D3Fix)
185
+ return arrays, d3_fix
186
+ {%- endif %}
187
+
188
+
189
+ dt_bytes1 = numpy.dtype('S1')
190
+ dt_bytes12 = numpy.dtype('S12')
191
+
192
+ # <--------------------------Actual ERFA-wrapping code------------------------>
193
+
194
+ {% for constant in constants %}
195
+ {{ constant.name }} = {{ constant.value }}
196
+ """{{ constant.doc|join(' ') }}"""
197
+ {%- endfor %}
198
+
199
+
200
+ {% for func in funcs -%}
201
+ def {{ func.pyname }}({{ func.args_by_inout('in|inout')|map(attribute='name')|join(', ') }}):
202
+ """
203
+ Wrapper for ERFA function ``{{ func.name }}``.
204
+
205
+ Parameters
206
+ ----------
207
+ {%- for arg in func.args_by_inout('in|inout') %}
208
+ {{ arg.name }} : {{ arg.ctype }} array
209
+ {%- endfor %}
210
+
211
+ Returns
212
+ -------
213
+ {%- for arg in func.args_by_inout('inout|out|ret') %}
214
+ {{ arg.name }} : {{ arg.ctype }} array
215
+ {%- endfor %}
216
+
217
+ Notes
218
+ -----
219
+ The ERFA documentation is below.
220
+
221
+ {{ func.doc }}
222
+ """
223
+
224
+ {#-
225
+ # Call the ufunc. Note that we pass inout twice, once as input
226
+ # and once as output, so that changes are done in-place
227
+ #}
228
+ {%- if func.d3_fix_arg %}
229
+ {% if func.args_by_inout('in|inout') -%}
230
+ ({{ func.args_by_inout('in|inout')|map(attribute='name')|join(', ') }},)
231
+ {%- else -%}_{%- endif -%}, {{ func.d3_fix_arg.name
232
+ }} = arrayify_inputs_and_create_d3_fix(
233
+ [{{ func.args_by_inout('in|inout')|map(attribute='name')|list()|join(', ')
234
+ }}], core_dims=[{{
235
+ func.args_by_inout('in|inout')|map(attribute='ndim')|list()|join(', ')
236
+ }}], out_core_shape={{ func.d3_fix_arg.shape
237
+ }}, out_dtype=numpy.{{ func.d3_fix_arg.ctype }})
238
+ {%- endif %}
239
+ {{ func.python_call }}
240
+ {#-
241
+ # Check whether any warnings or errors occurred.
242
+ #}
243
+ {%- for arg in func.args_by_inout('stat') %}
244
+ check_errwarn({{ arg.name }}, '{{ func.pyname }}')
245
+ {%- endfor %}
246
+ {#-
247
+ # Any string outputs will be in structs; view them as their base type.
248
+ #}
249
+ {%- for arg in func.args_by_inout('out') -%}
250
+ {%- if 'char' in arg.ctype %}
251
+ {{ arg.name }} = {{ arg.name }}.view({{ arg.view_dtype }})
252
+ {%- endif %}
253
+ {%- endfor %}
254
+ {#-
255
+ # Return the output arguments (including the inplace ones)
256
+ #}
257
+ return {{ func.args_by_inout('inout|out|ret')|map(attribute='name')|join(', ') }}
258
+
259
+
260
+ {#
261
+ # Define the status codes that this function returns.
262
+ #}
263
+ {%- if func.args_by_inout('stat') -%}
264
+ {%- for stat in func.args_by_inout('stat') -%}
265
+ {%- if stat.doc_info.statuscodes -%}
266
+ STATUS_CODES['{{ func.pyname }}'] = {{ stat.doc_info.statuscodes|string }}
267
+ {% endif %}
268
+ {% endfor %}
269
+ {% endif -%}
270
+ {% endfor -%}
271
+
272
+
273
+ # TODO: delete the functions below when they can get auto-generated
274
+ # (current machinery doesn't support returning strings or non-status-codes)
275
+ def version():
276
+ """
277
+ Returns the package version
278
+ as defined in configure.ac
279
+ in string format
280
+ """
281
+ return "1.4.0"
282
+
283
+ def version_major():
284
+ """
285
+ Returns the package major version
286
+ as defined in configure.ac
287
+ as integer
288
+ """
289
+ return 1
290
+
291
+ def version_minor():
292
+ """
293
+ Returns the package minor version
294
+ as defined in configure.ac
295
+ as integer
296
+ """
297
+ return 4
298
+
299
+ def version_micro():
300
+ """
301
+ Returns the package micro version
302
+ as defined in configure.ac
303
+ as integer
304
+ """
305
+ return 0
306
+
307
+ def sofa_version():
308
+ """
309
+ Returns the corresponding SOFA version
310
+ as defined in configure.ac
311
+ in string format
312
+ """
313
+ return "20170420"
testbed/astropy__astropy/astropy/_erfa/erfa_additions.h ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #ifndef ERFAADDITIONSDEF
2
+ #define ERFAADDITIONSDEF
3
+
4
+ /*
5
+ ** - - - - - - - - - - - - - - - - -
6
+ ** e r f a _ a d d i t i o n s . h
7
+ ** - - - - - - - - - - - - - - - - -
8
+ **
9
+ ** A few extra routines which are particularly handy for constructing
10
+ ** pv vectors inside the coordinate transforms.
11
+ **
12
+ ** MHvK proposed these to Catherine Hohenkerk for inclusion in SOFA
13
+ ** on 2018-05-24, with the response suggesting this was reasonable and
14
+ ** might thus be done.
15
+ */
16
+
17
+ /* Extra/PVMergeExtract */
18
+ void eraPav2pv(double p[3], double v[3], double pv[2][3]);
19
+ void eraPv2pav(double pv[2][3], double p[3], double v[3]);
20
+
21
+ #endif
testbed/astropy__astropy/astropy/_erfa/erfa_generator.py ADDED
@@ -0,0 +1,740 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+ """
3
+ This module's main purpose is to act as a script to create new versions
4
+ of ufunc.c when ERFA is updated (or this generator is enhanced).
5
+
6
+ `Jinja2 <http://jinja.pocoo.org/>`_ must be installed for this
7
+ module/script to function.
8
+
9
+ Note that this does *not* currently automate the process of creating structs
10
+ or dtypes for those structs. They should be added manually in the template file.
11
+ """
12
+ # note that we do *not* use unicode_literals here, because that makes the
13
+ # generated code's strings have u'' in them on py 2.x
14
+
15
+ import re
16
+ import os.path
17
+ from collections import OrderedDict
18
+ from distutils.version import LooseVersion
19
+
20
+ import numpy
21
+
22
+ # Note: once we support only numpy >=1.16, all things related to "d3_fix"
23
+ # can be removed, here and in the templates (core.py.templ
24
+
25
+ # NOTE: we define this variable here instead of importing from astropy to
26
+ # ensure that running this script does not require importing astropy.
27
+ NUMPY_LT_1_16 = LooseVersion(numpy.__version__) < '1.16'
28
+
29
+
30
+ DEFAULT_ERFA_LOC = os.path.join(os.path.split(__file__)[0],
31
+ '../../cextern/erfa')
32
+ DEFAULT_TEMPLATE_LOC = os.path.split(__file__)[0]
33
+
34
+ NDIMS_REX = re.compile(re.escape("numpy.dtype([('fi0', '.*', <(.*)>)])").replace(r'\.\*', '.*').replace(r'\<', '(').replace(r'\>', ')'))
35
+
36
+
37
+ class FunctionDoc:
38
+
39
+ def __init__(self, doc):
40
+ self.doc = doc.replace("**", " ").replace("/*\n", "").replace("*/", "")
41
+ self.__input = None
42
+ self.__output = None
43
+ self.__ret_info = None
44
+
45
+ def _get_arg_doc_list(self, doc_lines):
46
+ """Parse input/output doc section lines, getting arguments from them.
47
+
48
+ Ensure all elements of eraASTROM and eraLDBODY are left out, as those
49
+ are not input or output arguments themselves. Also remove the nb
50
+ argument in from of eraLDBODY, as we infer nb from the python array.
51
+ """
52
+ doc_list = []
53
+ skip = []
54
+ for d in doc_lines:
55
+ arg_doc = ArgumentDoc(d)
56
+ if arg_doc.name is not None:
57
+ if skip:
58
+ if skip[0] == arg_doc.name:
59
+ skip.pop(0)
60
+ continue
61
+ else:
62
+ raise RuntimeError("We whould be skipping {} "
63
+ "but {} encountered."
64
+ .format(skip[0], arg_doc.name))
65
+
66
+ if arg_doc.type.startswith('eraLDBODY'):
67
+ # Special-case LDBODY: for those, the previous argument
68
+ # is always the number of bodies, but we don't need it
69
+ # as an input argument for the ufunc since we're going
70
+ # to determine this from the array itself. Also skip
71
+ # the description of its contents; those are not arguments.
72
+ doc_list.pop()
73
+ skip = ['bm', 'dl', 'pv']
74
+ elif arg_doc.type.startswith('eraASTROM'):
75
+ # Special-case ASTROM: need to skip the description
76
+ # of its contents; those are not arguments.
77
+ skip = ['pmt', 'eb', 'eh', 'em', 'v', 'bm1',
78
+ 'bpn', 'along', 'xpl', 'ypl', 'sphi',
79
+ 'cphi', 'diurab', 'eral', 'refa', 'refb']
80
+
81
+ doc_list.append(arg_doc)
82
+
83
+ return doc_list
84
+
85
+ @property
86
+ def input(self):
87
+ if self.__input is None:
88
+ self.__input = []
89
+ for regex in ("Given([^\n]*):\n(.+?) \n",
90
+ "Given and returned([^\n]*):\n(.+?) \n"):
91
+ result = re.search(regex, self.doc, re.DOTALL)
92
+ if result is not None:
93
+ doc_lines = result.group(2).split("\n")
94
+ self.__input += self._get_arg_doc_list(doc_lines)
95
+
96
+ return self.__input
97
+
98
+ @property
99
+ def output(self):
100
+ if self.__output is None:
101
+ self.__output = []
102
+ for regex in ("Given and returned([^\n]*):\n(.+?) \n",
103
+ "Returned([^\n]*):\n(.+?) \n"):
104
+ result = re.search(regex, self.doc, re.DOTALL)
105
+ if result is not None:
106
+ doc_lines = result.group(2).split("\n")
107
+ self.__output += self._get_arg_doc_list(doc_lines)
108
+
109
+ return self.__output
110
+
111
+ @property
112
+ def ret_info(self):
113
+ if self.__ret_info is None:
114
+ ret_info = []
115
+ result = re.search("Returned \\(function value\\)([^\n]*):\n(.+?) \n", self.doc, re.DOTALL)
116
+ if result is not None:
117
+ ret_info.append(ReturnDoc(result.group(2)))
118
+
119
+ if len(ret_info) == 0:
120
+ self.__ret_info = ''
121
+ elif len(ret_info) == 1:
122
+ self.__ret_info = ret_info[0]
123
+ else:
124
+ raise ValueError("Multiple C return sections found in this doc:\n" + self.doc)
125
+
126
+ return self.__ret_info
127
+
128
+ def __repr__(self):
129
+ return self.doc.replace(" \n", "\n")
130
+
131
+
132
+ class ArgumentDoc:
133
+
134
+ def __init__(self, doc):
135
+ match = re.search("^ +([^ ]+)[ ]+([^ ]+)[ ]+(.+)", doc)
136
+ if match is not None:
137
+ self.name = match.group(1)
138
+ self.type = match.group(2)
139
+ self.doc = match.group(3)
140
+ else:
141
+ self.name = None
142
+ self.type = None
143
+ self.doc = None
144
+
145
+ def __repr__(self):
146
+ return " {0:15} {1:15} {2}".format(self.name, self.type, self.doc)
147
+
148
+
149
+ class Variable:
150
+ """Properties shared by Argument and Return."""
151
+ @property
152
+ def npy_type(self):
153
+ """Predefined type used by numpy ufuncs to indicate a given ctype.
154
+
155
+ Eg., NPY_DOUBLE for double.
156
+ """
157
+ return "NPY_" + self.ctype.upper()
158
+
159
+ @property
160
+ def dtype(self):
161
+ """Name of dtype corresponding to the ctype.
162
+
163
+ Specifically,
164
+ double : dt_double
165
+ int : dt_int
166
+ double[3]: dt_vector
167
+ double[2][3] : dt_pv
168
+ double[2] : dt_pvdpv
169
+ double[3][3] : dt_matrix
170
+ int[4] : dt_ymdf | dt_hmsf | dt_dmsf, depding on name
171
+ eraASTROM: dt_eraASTROM
172
+ eraLDBODY: dt_eraLDBODY
173
+ char : dt_sign
174
+ char[] : dt_type
175
+
176
+ The corresponding dtypes are defined in ufunc.c, where they are
177
+ used for the loop definitions. In core.py, they are also used
178
+ to view-cast regular arrays to these structured dtypes.
179
+ """
180
+ if self.ctype == 'const char':
181
+ return 'dt_type'
182
+ elif self.ctype == 'char':
183
+ return 'dt_sign'
184
+ elif self.ctype == 'int' and self.shape == (4,):
185
+ return 'dt_' + self.name[1:]
186
+ elif self.ctype == 'double' and self.shape == (3,):
187
+ return 'dt_double'
188
+ elif self.ctype == 'double' and self.shape == (2, 3):
189
+ return 'dt_pv'
190
+ elif self.ctype == 'double' and self.shape == (2,):
191
+ return 'dt_pvdpv'
192
+ elif self.ctype == 'double' and self.shape == (3, 3):
193
+ return 'dt_double'
194
+ elif not self.shape:
195
+ return 'dt_' + self.ctype
196
+ else:
197
+ raise ValueError("ctype {} with shape {} not recognized."
198
+ .format(self.ctype, self.shape))
199
+
200
+ @property
201
+ def view_dtype(self):
202
+ """Name of dtype corresponding to the ctype for viewing back as array.
203
+
204
+ E.g., dt_double for double, dt_double33 for double[3][3].
205
+
206
+ The types are defined in core.py, where they are used for view-casts
207
+ of structured results as regular arrays.
208
+ """
209
+ if self.ctype == 'const char':
210
+ return 'dt_bytes12'
211
+ elif self.ctype == 'char':
212
+ return 'dt_bytes1'
213
+ else:
214
+ raise ValueError('Only char ctype should need view back!')
215
+
216
+ @property
217
+ def ndim(self):
218
+ return len(self.shape)
219
+
220
+ @property
221
+ def size(self):
222
+ size = 1
223
+ for s in self.shape:
224
+ size *= s
225
+ return size
226
+
227
+ @property
228
+ def cshape(self):
229
+ return ''.join(['[{0}]'.format(s) for s in self.shape])
230
+
231
+ @property
232
+ def signature_shape(self):
233
+ if self.ctype == 'eraLDBODY':
234
+ return '(n)'
235
+ elif self.ctype == 'double' and self.shape == (3,):
236
+ return '(d3)' if NUMPY_LT_1_16 else '(3)'
237
+ elif self.ctype == 'double' and self.shape == (3, 3):
238
+ return '(d3, d3)' if NUMPY_LT_1_16 else '(3, 3)'
239
+ else:
240
+ return '()'
241
+
242
+
243
+ class Argument(Variable):
244
+
245
+ def __init__(self, definition, doc):
246
+ self.definition = definition
247
+ self.doc = doc
248
+ self.__inout_state = None
249
+ self.ctype, ptr_name_arr = definition.strip().rsplit(" ", 1)
250
+ if "*" == ptr_name_arr[0]:
251
+ self.is_ptr = True
252
+ name_arr = ptr_name_arr[1:]
253
+ else:
254
+ self.is_ptr = False
255
+ name_arr = ptr_name_arr
256
+ if "[]" in ptr_name_arr:
257
+ self.is_ptr = True
258
+ name_arr = name_arr[:-2]
259
+ if "[" in name_arr:
260
+ self.name, arr = name_arr.split("[", 1)
261
+ self.shape = tuple([int(size) for size in arr[:-1].split("][")])
262
+ else:
263
+ self.name = name_arr
264
+ self.shape = ()
265
+
266
+ @property
267
+ def inout_state(self):
268
+ if self.__inout_state is None:
269
+ self.__inout_state = ''
270
+ for i in self.doc.input:
271
+ if self.name in i.name.split(','):
272
+ self.__inout_state = 'in'
273
+ for o in self.doc.output:
274
+ if self.name in o.name.split(','):
275
+ if self.__inout_state == 'in':
276
+ self.__inout_state = 'inout'
277
+ else:
278
+ self.__inout_state = 'out'
279
+ return self.__inout_state
280
+
281
+ @property
282
+ def name_for_call(self):
283
+ """How the argument should be used in the call to the ERFA function.
284
+
285
+ This takes care of ensuring that inputs are passed by value,
286
+ as well as adding back the number of bodies for any LDBODY argument.
287
+ The latter presumes that in the ufunc inner loops, that number is
288
+ called 'nb'.
289
+ """
290
+ if self.ctype == 'eraLDBODY':
291
+ assert self.name == 'b'
292
+ return 'nb, _' + self.name
293
+ elif self.is_ptr:
294
+ return '_'+self.name
295
+ else:
296
+ return '*_'+self.name
297
+
298
+ def __repr__(self):
299
+ return "Argument('{0}', name='{1}', ctype='{2}', inout_state='{3}')".format(self.definition, self.name, self.ctype, self.inout_state)
300
+
301
+
302
+ class ReturnDoc:
303
+
304
+ def __init__(self, doc):
305
+ self.doc = doc
306
+
307
+ self.infoline = doc.split('\n')[0].strip()
308
+ self.type = self.infoline.split()[0]
309
+ self.descr = self.infoline.split()[1]
310
+
311
+ if self.descr.startswith('status'):
312
+ self.statuscodes = statuscodes = {}
313
+
314
+ code = None
315
+ for line in doc[doc.index(':')+1:].split('\n'):
316
+ ls = line.strip()
317
+ if ls != '':
318
+ if ' = ' in ls:
319
+ code, msg = ls.split(' = ')
320
+ if code != 'else':
321
+ code = int(code)
322
+ statuscodes[code] = msg
323
+ elif code is not None:
324
+ statuscodes[code] += ls
325
+ else:
326
+ self.statuscodes = None
327
+
328
+ def __repr__(self):
329
+ return "Return value, type={0:15}, {1}, {2}".format(self.type, self.descr, self.doc)
330
+
331
+
332
+ class Return(Variable):
333
+
334
+ def __init__(self, ctype, doc):
335
+ self.name = 'c_retval'
336
+ self.inout_state = 'stat' if ctype == 'int' else 'ret'
337
+ self.ctype = ctype
338
+ self.shape = ()
339
+ self.doc = doc
340
+
341
+ def __repr__(self):
342
+ return "Return(name='{0}', ctype='{1}', inout_state='{2}')".format(self.name, self.ctype, self.inout_state)
343
+
344
+ @property
345
+ def doc_info(self):
346
+ return self.doc.ret_info
347
+
348
+
349
+ class Function:
350
+ """
351
+ A class representing a C function.
352
+
353
+ Parameters
354
+ ----------
355
+ name : str
356
+ The name of the function
357
+ source_path : str
358
+ Either a directory, which means look for the function in a
359
+ stand-alone file (like for the standard ERFA distribution), or a
360
+ file, which means look for the function in that file (as for the
361
+ astropy-packaged single-file erfa.c).
362
+ match_line : str, optional
363
+ If given, searching of the source file will skip until it finds
364
+ a line matching this string, and start from there.
365
+ """
366
+
367
+ def __init__(self, name, source_path, match_line=None):
368
+ self.name = name
369
+ self.pyname = name.split('era')[-1].lower()
370
+ self.filename = self.pyname+".c"
371
+ if os.path.isdir(source_path):
372
+ self.filepath = os.path.join(os.path.normpath(source_path), self.filename)
373
+ else:
374
+ self.filepath = source_path
375
+
376
+ with open(self.filepath) as f:
377
+ if match_line:
378
+ line = f.readline()
379
+ while line != '':
380
+ if line.startswith(match_line):
381
+ filecontents = '\n' + line + f.read()
382
+ break
383
+ line = f.readline()
384
+ else:
385
+ msg = ('Could not find the match_line "{0}" in '
386
+ 'the source file "{1}"')
387
+ raise ValueError(msg.format(match_line, self.filepath))
388
+ else:
389
+ filecontents = f.read()
390
+
391
+ pattern = r"\n([^\n]+{0} ?\([^)]+\)).+?(/\*.+?\*/)".format(name)
392
+ p = re.compile(pattern, flags=re.DOTALL | re.MULTILINE)
393
+
394
+ search = p.search(filecontents)
395
+ self.cfunc = " ".join(search.group(1).split())
396
+ self.doc = FunctionDoc(search.group(2))
397
+
398
+ self.args = []
399
+ for arg in re.search(r"\(([^)]+)\)", self.cfunc).group(1).split(', '):
400
+ self.args.append(Argument(arg, self.doc))
401
+ self.ret = re.search("^(.*){0}".format(name), self.cfunc).group(1).strip()
402
+ if self.ret != 'void':
403
+ self.args.append(Return(self.ret, self.doc))
404
+
405
+ def args_by_inout(self, inout_filter, prop=None, join=None):
406
+ """
407
+ Gives all of the arguments and/or returned values, depending on whether
408
+ they are inputs, outputs, etc.
409
+
410
+ The value for `inout_filter` should be a string containing anything
411
+ that arguments' `inout_state` attribute produces. Currently, that can be:
412
+
413
+ * "in" : input
414
+ * "out" : output
415
+ * "inout" : something that's could be input or output (e.g. a struct)
416
+ * "ret" : the return value of the C function
417
+ * "stat" : the return value of the C function if it is a status code
418
+
419
+ It can also be a "|"-separated string giving inout states to OR
420
+ together.
421
+ """
422
+ result = []
423
+ for arg in self.args:
424
+ if arg.inout_state in inout_filter.split('|'):
425
+ if prop is None:
426
+ result.append(arg)
427
+ else:
428
+ result.append(getattr(arg, prop))
429
+ if join is not None:
430
+ return join.join(result)
431
+ else:
432
+ return result
433
+
434
+ @property
435
+ def user_dtype(self):
436
+ """The non-standard dtype, if any, needed by this function's ufunc.
437
+
438
+ This would be any structured array for any input or output, but
439
+ we give preference to LDBODY, since that also decides that the ufunc
440
+ should be a generalized ufunc.
441
+ """
442
+ user_dtype = None
443
+ for arg in self.args_by_inout('in|inout|out'):
444
+ if arg.ctype == 'eraLDBODY':
445
+ return arg.dtype
446
+ elif user_dtype is None and arg.dtype not in ('dt_double',
447
+ 'dt_int'):
448
+ user_dtype = arg.dtype
449
+
450
+ return user_dtype
451
+
452
+ @property
453
+ def signature(self):
454
+ """Possible signature, if this function should be a gufunc."""
455
+ if all(arg.signature_shape == '()'
456
+ for arg in self.args_by_inout('in|inout|out')):
457
+ return None
458
+
459
+ return '->'.join(
460
+ [','.join([arg.signature_shape for arg in args])
461
+ for args in (self.args_by_inout('in|inout'),
462
+ self.args_by_inout('inout|out|ret|stat'))])
463
+
464
+ def _d3_fix_arg_and_index(self):
465
+ if not any('d3' in arg.signature_shape
466
+ for arg in self.args_by_inout('in|inout')):
467
+ for j, arg in enumerate(self.args_by_inout('out')):
468
+ if 'd3' in arg.signature_shape:
469
+ return j, arg
470
+
471
+ return None, None
472
+
473
+ @property
474
+ def d3_fix_op_index(self):
475
+ """Whether only output arguments have a d3 dimension."""
476
+ index = self._d3_fix_arg_and_index()[0]
477
+ if index is not None:
478
+ len_in = len(list(self.args_by_inout('in')))
479
+ len_inout = len(list(self.args_by_inout('inout')))
480
+ index += + len_in + 2 * len_inout
481
+ return index
482
+
483
+ @property
484
+ def d3_fix_arg(self):
485
+ """Whether only output arguments have a d3 dimension."""
486
+ return self._d3_fix_arg_and_index()[1]
487
+
488
+ @property
489
+ def python_call(self):
490
+ outnames = [arg.name for arg in self.args_by_inout('inout|out|stat|ret')]
491
+ argnames = [arg.name for arg in self.args_by_inout('in|inout')]
492
+ argnames += [arg.name for arg in self.args_by_inout('inout')]
493
+ d3fix_index = self._d3_fix_arg_and_index()[0]
494
+ if d3fix_index is not None:
495
+ argnames += ['None'] * d3fix_index + [self.d3_fix_arg.name]
496
+ return '{out} = {func}({args})'.format(out=', '.join(outnames),
497
+ func='ufunc.' + self.pyname,
498
+ args=', '.join(argnames))
499
+
500
+ def __repr__(self):
501
+ return "Function(name='{0}', pyname='{1}', filename='{2}', filepath='{3}')".format(self.name, self.pyname, self.filename, self.filepath)
502
+
503
+
504
+
505
+ class Constant:
506
+
507
+ def __init__(self, name, value, doc):
508
+ self.name = name.replace("ERFA_", "")
509
+ self.value = value.replace("ERFA_", "")
510
+ self.doc = doc
511
+
512
+
513
+ class ExtraFunction(Function):
514
+ """
515
+ An "extra" function - e.g. one not following the SOFA/ERFA standard format.
516
+
517
+ Parameters
518
+ ----------
519
+ cname : str
520
+ The name of the function in C
521
+ prototype : str
522
+ The prototype for the function (usually derived from the header)
523
+ pathfordoc : str
524
+ The path to a file that contains the prototype, with the documentation
525
+ as a multiline string *before* it.
526
+ """
527
+
528
+ def __init__(self, cname, prototype, pathfordoc):
529
+ self.name = cname
530
+ self.pyname = cname.split('era')[-1].lower()
531
+ self.filepath, self.filename = os.path.split(pathfordoc)
532
+
533
+ self.prototype = prototype.strip()
534
+ if prototype.endswith('{') or prototype.endswith(';'):
535
+ self.prototype = prototype[:-1].strip()
536
+
537
+ incomment = False
538
+ lastcomment = None
539
+ with open(pathfordoc, 'r') as f:
540
+ for l in f:
541
+ if incomment:
542
+ if l.lstrip().startswith('*/'):
543
+ incomment = False
544
+ lastcomment = ''.join(lastcomment)
545
+ else:
546
+ if l.startswith('**'):
547
+ l = l[2:]
548
+ lastcomment.append(l)
549
+ else:
550
+ if l.lstrip().startswith('/*'):
551
+ incomment = True
552
+ lastcomment = []
553
+ if l.startswith(self.prototype):
554
+ self.doc = lastcomment
555
+ break
556
+ else:
557
+ raise ValueError('Did not find prototype {} in file '
558
+ '{}'.format(self.prototype, pathfordoc))
559
+
560
+ self.args = []
561
+ argset = re.search(r"{0}\(([^)]+)?\)".format(self.name),
562
+ self.prototype).group(1)
563
+ if argset is not None:
564
+ for arg in argset.split(', '):
565
+ self.args.append(Argument(arg, self.doc))
566
+ self.ret = re.match("^(.*){0}".format(self.name),
567
+ self.prototype).group(1).strip()
568
+ if self.ret != 'void':
569
+ self.args.append(Return(self.ret, self.doc))
570
+
571
+ def __repr__(self):
572
+ r = super().__repr__()
573
+ if r.startswith('Function'):
574
+ r = 'Extra' + r
575
+ return r
576
+
577
+
578
+ def main(srcdir=DEFAULT_ERFA_LOC, outfn='core.py', ufuncfn='ufunc.c',
579
+ templateloc=DEFAULT_TEMPLATE_LOC, extra='erfa_additions.h',
580
+ verbose=True):
581
+ from jinja2 import Environment, FileSystemLoader
582
+
583
+ if verbose:
584
+ print_ = lambda *args, **kwargs: print(*args, **kwargs)
585
+ else:
586
+ print_ = lambda *args, **kwargs: None
587
+
588
+ # Prepare the jinja2 templating environment
589
+ env = Environment(loader=FileSystemLoader(templateloc))
590
+
591
+ def prefix(a_list, pre):
592
+ return [pre+'{0}'.format(an_element) for an_element in a_list]
593
+
594
+ def postfix(a_list, post):
595
+ return ['{0}'.format(an_element)+post for an_element in a_list]
596
+
597
+ def surround(a_list, pre, post):
598
+ return [pre+'{0}'.format(an_element)+post for an_element in a_list]
599
+ env.filters['prefix'] = prefix
600
+ env.filters['postfix'] = postfix
601
+ env.filters['surround'] = surround
602
+
603
+ erfa_c_in = env.get_template(ufuncfn + '.templ')
604
+ erfa_py_in = env.get_template(outfn + '.templ')
605
+
606
+ # Extract all the ERFA function names from erfa.h
607
+ if os.path.isdir(srcdir):
608
+ erfahfn = os.path.join(srcdir, 'erfa.h')
609
+ multifilserc = True
610
+ else:
611
+ erfahfn = os.path.join(os.path.split(srcdir)[0], 'erfa.h')
612
+ multifilserc = False
613
+
614
+ with open(erfahfn, "r") as f:
615
+ erfa_h = f.read()
616
+ print_("read erfa header")
617
+ if extra:
618
+ with open(os.path.join(templateloc or '.', extra), "r") as f:
619
+ erfa_h += f.read()
620
+ print_("read extra header")
621
+
622
+ funcs = OrderedDict()
623
+ section_subsection_functions = re.findall(
624
+ r'/\* (\w*)/(\w*) \*/\n(.*?)\n\n', erfa_h,
625
+ flags=re.DOTALL | re.MULTILINE)
626
+ for section, subsection, functions in section_subsection_functions:
627
+ print_("{0}.{1}".format(section, subsection))
628
+ # Right now, we compile everything, but one could be more selective.
629
+ # In particular, at the time of writing (2018-06-11), what was
630
+ # actually require for astropy was not quite everything, but:
631
+ # ((section == 'Extra')
632
+ # or (section == "Astronomy")
633
+ # or (subsection == "AngleOps")
634
+ # or (subsection == "SphericalCartesian")
635
+ # or (subsection == "MatrixVectorProducts")
636
+ # or (subsection == 'VectorOps'))
637
+ if True:
638
+
639
+ func_names = re.findall(r' (\w+)\(.*?\);', functions,
640
+ flags=re.DOTALL)
641
+ for name in func_names:
642
+ print_("{0}.{1}.{2}...".format(section, subsection, name))
643
+ if multifilserc:
644
+ # easy because it just looks in the file itself
645
+ cdir = (srcdir if section != 'Extra' else
646
+ templateloc or '.')
647
+ funcs[name] = Function(name, cdir)
648
+ else:
649
+ # Have to tell it to look for a declaration matching
650
+ # the start of the header declaration, otherwise it
651
+ # might find a *call* of the function instead of the
652
+ # definition
653
+ for line in functions.split(r'\n'):
654
+ if name in line:
655
+ # [:-1] is to remove trailing semicolon, and
656
+ # splitting on '(' is because the header and
657
+ # C files don't necessarily have to match
658
+ # argument names and line-breaking or
659
+ # whitespace
660
+ match_line = line[:-1].split('(')[0]
661
+ funcs[name] = Function(name, cdir, match_line)
662
+ break
663
+ else:
664
+ raise ValueError("A name for a C file wasn't "
665
+ "found in the string that "
666
+ "spawned it. This should be "
667
+ "impossible!")
668
+
669
+ funcs = funcs.values()
670
+
671
+ # Extract all the ERFA constants from erfam.h
672
+ erfamhfn = os.path.join(srcdir, 'erfam.h')
673
+ with open(erfamhfn, 'r') as f:
674
+ erfa_m_h = f.read()
675
+ constants = []
676
+ for chunk in erfa_m_h.split("\n\n"):
677
+ result = re.findall(r"#define (ERFA_\w+?) (.+?)$", chunk,
678
+ flags=re.DOTALL | re.MULTILINE)
679
+ if result:
680
+ doc = re.findall(r"/\* (.+?) \*/\n", chunk, flags=re.DOTALL)
681
+ for (name, value) in result:
682
+ constants.append(Constant(name, value, doc))
683
+
684
+ # TODO: re-enable this when const char* return values and
685
+ # non-status code integer rets are possible
686
+ # #Add in any "extra" functions from erfaextra.h
687
+ # erfaextrahfn = os.path.join(srcdir, 'erfaextra.h')
688
+ # with open(erfaextrahfn, 'r') as f:
689
+ # for l in f:
690
+ # ls = l.strip()
691
+ # match = re.match('.* (era.*)\(', ls)
692
+ # if match:
693
+ # print_("Extra: {0} ...".format(match.group(1)))
694
+ # funcs.append(ExtraFunction(match.group(1), ls, erfaextrahfn))
695
+
696
+ print_("Rendering template")
697
+ erfa_c = erfa_c_in.render(funcs=funcs, NUMPY_LT_1_16=NUMPY_LT_1_16)
698
+ erfa_py = erfa_py_in.render(funcs=funcs, constants=constants,
699
+ NUMPY_LT_1_16=NUMPY_LT_1_16)
700
+
701
+ if outfn is not None:
702
+ print_("Saving to", outfn, 'and', ufuncfn)
703
+ with open(os.path.join(templateloc, outfn), "w") as f:
704
+ f.write(erfa_py)
705
+ with open(os.path.join(templateloc, ufuncfn), "w") as f:
706
+ f.write(erfa_c)
707
+
708
+ print_("Done!")
709
+
710
+ return erfa_c, erfa_py, funcs
711
+
712
+
713
+ if __name__ == '__main__':
714
+ from argparse import ArgumentParser
715
+
716
+ ap = ArgumentParser()
717
+ ap.add_argument('srcdir', default=DEFAULT_ERFA_LOC, nargs='?',
718
+ help='Directory where the ERFA c and header files '
719
+ 'can be found or to a single erfa.c file '
720
+ '(which must be in the same directory as '
721
+ 'erfa.h). Defaults to the builtin astropy '
722
+ 'erfa: "{0}"'.format(DEFAULT_ERFA_LOC))
723
+ ap.add_argument('-o', '--output', default='core.py',
724
+ help='The output filename for the pure-python output.')
725
+ ap.add_argument('-u', '--ufunc', default='ufunc.c',
726
+ help='The output filename for the ufunc .c output')
727
+ ap.add_argument('-t', '--template-loc',
728
+ default=DEFAULT_TEMPLATE_LOC,
729
+ help='the location where the "core.py.templ" and '
730
+ '"ufunc.c.templ templates can be found.')
731
+ ap.add_argument('-x', '--extra',
732
+ default='erfa_additions.h',
733
+ help='header file for any extra files in the template '
734
+ 'location that should be included.')
735
+ ap.add_argument('-q', '--quiet', action='store_false', dest='verbose',
736
+ help='Suppress output normally printed to stdout.')
737
+
738
+ args = ap.parse_args()
739
+ main(args.srcdir, args.output, args.ufunc, args.template_loc,
740
+ args.extra)
testbed/astropy__astropy/astropy/_erfa/pav2pv.c ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "erfa.h"
2
+
3
+ void eraPav2pv(double p[3], double v[3], double pv[2][3])
4
+ /*
5
+ ** - - - - - - - - - -
6
+ ** e r a P a v 2 p v
7
+ ** - - - - - - - - - -
8
+ **
9
+ ** Extend a p-vector to a pv-vector by appending a zero velocity.
10
+ **
11
+ ** Given:
12
+ ** p double[3] p-vector
13
+ ** v double[3] v-vector
14
+ **
15
+ ** Returned:
16
+ ** pv double[2][3] pv-vector
17
+ **
18
+ ** Called:
19
+ ** eraCp copy p-vector
20
+ **
21
+ ** Copyright (C) 2013-2017, NumFOCUS Foundation.
22
+ ** Derived, with permission, from the SOFA library. See notes at end of file.
23
+ */
24
+ {
25
+ eraCp(p, pv[0]);
26
+ eraCp(v, pv[1]);
27
+
28
+ return;
29
+
30
+ }
testbed/astropy__astropy/astropy/_erfa/pv2pav.c ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "erfa.h"
2
+
3
+ void eraPv2pav(double pv[2][3], double p[3], double v[3])
4
+ /*
5
+ ** - - - - - - - - -
6
+ ** e r a P v 2 p a v
7
+ ** - - - - - - - - -
8
+ **
9
+ ** Extend a p-vector to a pv-vector by appending a zero velocity.
10
+ **
11
+ ** Given:
12
+ ** pv double[2][3] pv-vector
13
+ **
14
+ ** Returned:
15
+ ** p double[3] p-vector
16
+ ** v double[3] v-vector
17
+ **
18
+ ** Called:
19
+ ** eraCp copy p-vector
20
+ **
21
+ ** Copyright (C) 2013-2017, NumFOCUS Foundation.
22
+ ** Derived, with permission, from the SOFA library. See notes at end of file.
23
+ */
24
+ {
25
+ eraCp(pv[0], p);
26
+ eraCp(pv[1], v);
27
+
28
+ return;
29
+
30
+ }
testbed/astropy__astropy/astropy/_erfa/setup_package.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+
3
+ import os
4
+ import glob
5
+
6
+ from distutils import log
7
+ from distutils.extension import Extension
8
+
9
+ from astropy_helpers import setup_helpers
10
+ from astropy_helpers.utils import import_file
11
+ from astropy_helpers.version_helpers import get_pkg_version_module
12
+
13
+ ERFAPKGDIR = os.path.relpath(os.path.dirname(__file__))
14
+
15
+ ERFA_SRC = os.path.abspath(os.path.join(ERFAPKGDIR, '..', '..',
16
+ 'cextern', 'erfa'))
17
+
18
+ SRC_FILES = glob.glob(os.path.join(ERFA_SRC, '*'))
19
+ SRC_FILES += [os.path.join(ERFAPKGDIR, filename)
20
+ for filename in ['pav2pv.c', 'pv2pav.c', 'erfa_additions.h',
21
+ 'ufunc.c.templ', 'core.py.templ',
22
+ 'erfa_generator.py']]
23
+
24
+ GEN_FILES = [os.path.join(ERFAPKGDIR, 'core.py'),
25
+ os.path.join(ERFAPKGDIR, 'ufunc.c')]
26
+
27
+
28
+ def pre_build_py_hook(cmd_obj):
29
+ preprocess_source()
30
+
31
+
32
+ def pre_build_ext_hook(cmd_obj):
33
+ preprocess_source()
34
+
35
+
36
+ def pre_sdist_hook(cmd_obj):
37
+ preprocess_source()
38
+
39
+
40
+ def preprocess_source():
41
+ # Generating the ERFA wrappers should only be done if needed. This also
42
+ # ensures that it is not done for any release tarball since those will
43
+ # include core.py and ufunc.c.
44
+ if all(os.path.exists(filename) for filename in GEN_FILES):
45
+
46
+ # Determine modification times
47
+ erfa_mtime = max(os.path.getmtime(filename) for filename in SRC_FILES)
48
+ gen_mtime = min(os.path.getmtime(filename) for filename in GEN_FILES)
49
+
50
+ version = import_file(os.path.join(ERFAPKGDIR, '..', 'version.py'))
51
+
52
+ if gen_mtime > erfa_mtime:
53
+ # If generated source is recent enough, don't update
54
+ return
55
+ elif version.release:
56
+ # or, if we're on a release, issue a warning, but go ahead and use
57
+ # the wrappers anyway
58
+ log.warn('WARNING: The autogenerated wrappers in astropy._erfa '
59
+ 'seem to be older than the source templates used to '
60
+ 'create them. Because this is a release version we will '
61
+ 'use them anyway, but this might be a sign of some sort '
62
+ 'of version mismatch or other tampering. Or it might just '
63
+ 'mean you moved some files around or otherwise '
64
+ 'accidentally changed timestamps.')
65
+ return
66
+ # otherwise rebuild the autogenerated files
67
+
68
+ # If jinja2 isn't present, then print a warning and use existing files
69
+ try:
70
+ import jinja2 # pylint: disable=W0611
71
+ except ImportError:
72
+ log.warn("WARNING: jinja2 could not be imported, so the existing "
73
+ "ERFA core.py and ufunc.c files will be used")
74
+ return
75
+
76
+ gen = import_file(os.path.join(ERFAPKGDIR, 'erfa_generator.py'))
77
+
78
+ gen.main(verbose=False)
79
+
80
+
81
+ def get_extensions():
82
+ sources = [os.path.join(ERFAPKGDIR, fn)
83
+ for fn in ("ufunc.c", "pav2pv.c", "pv2pav.c")]
84
+ include_dirs = ['numpy']
85
+ libraries = []
86
+
87
+ if setup_helpers.use_system_library('erfa'):
88
+ libraries.append('erfa')
89
+ else:
90
+ # get all of the .c files in the cextern/erfa directory
91
+ erfafns = os.listdir(ERFA_SRC)
92
+ sources.extend(['cextern/erfa/' + fn
93
+ for fn in erfafns if fn.endswith('.c')])
94
+
95
+ include_dirs.append('cextern/erfa')
96
+
97
+ erfa_ext = Extension(
98
+ name="astropy._erfa.ufunc",
99
+ sources=sources,
100
+ include_dirs=include_dirs,
101
+ libraries=libraries,
102
+ language="c",)
103
+
104
+ return [erfa_ext]
105
+
106
+
107
+ def get_external_libraries():
108
+ return ['erfa']
testbed/astropy__astropy/astropy/_erfa/tests/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
testbed/astropy__astropy/astropy/_erfa/tests/test_erfa.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+
3
+ import numpy as np
4
+
5
+ from astropy._erfa import core as erfa
6
+ from astropy.tests.helper import catch_warnings
7
+
8
+
9
+ def test_erfa_wrapper():
10
+ """
11
+ Runs a set of tests that mostly make sure vectorization is
12
+ working as expected
13
+ """
14
+
15
+ jd = np.linspace(2456855.5, 2456855.5+1.0/24.0/60.0, 60*2+1)
16
+ ra = np.linspace(0.0, np.pi*2.0, 5)
17
+ dec = np.linspace(-np.pi/2.0, np.pi/2.0, 4)
18
+
19
+ aob, zob, hob, dob, rob, eo = erfa.atco13(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, jd, 0.0, 0.0, 0.0, np.pi/4.0, 0.0, 0.0, 0.0, 1014.0, 0.0, 0.0, 0.5)
20
+ assert aob.shape == (121,)
21
+
22
+ aob, zob, hob, dob, rob, eo = erfa.atco13(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, jd[0], 0.0, 0.0, 0.0, np.pi/4.0, 0.0, 0.0, 0.0, 1014.0, 0.0, 0.0, 0.5)
23
+ assert aob.shape == ()
24
+
25
+ aob, zob, hob, dob, rob, eo = erfa.atco13(ra[:, None, None], dec[None, :, None], 0.0, 0.0, 0.0, 0.0, jd[None, None, :], 0.0, 0.0, 0.0, np.pi/4.0, 0.0, 0.0, 0.0, 1014.0, 0.0, 0.0, 0.5)
26
+ (aob.shape) == (5, 4, 121)
27
+
28
+ iy, im, id, ihmsf = erfa.d2dtf("UTC", 3, jd, 0.0)
29
+ assert iy.shape == (121,)
30
+ assert ihmsf.shape == (121,)
31
+ assert ihmsf.dtype == erfa.dt_hmsf
32
+
33
+ iy, im, id, ihmsf = erfa.d2dtf("UTC", 3, jd[0], 0.0)
34
+ assert iy.shape == ()
35
+ assert ihmsf.shape == ()
36
+ assert ihmsf.dtype == erfa.dt_hmsf
37
+
38
+
39
+ def test_angle_ops():
40
+
41
+ sign, idmsf = erfa.a2af(6, -np.pi)
42
+ assert sign == b'-'
43
+ assert idmsf.item() == (180, 0, 0, 0)
44
+
45
+ sign, ihmsf = erfa.a2tf(6, np.pi)
46
+ assert sign == b'+'
47
+ assert ihmsf.item() == (12, 0, 0, 0)
48
+
49
+ rad = erfa.af2a('-', 180, 0, 0.0)
50
+ np.testing.assert_allclose(rad, -np.pi)
51
+
52
+ rad = erfa.tf2a('+', 12, 0, 0.0)
53
+ np.testing.assert_allclose(rad, np.pi)
54
+
55
+ rad = erfa.anp(3.*np.pi)
56
+ np.testing.assert_allclose(rad, np.pi)
57
+
58
+ rad = erfa.anpm(3.*np.pi)
59
+ np.testing.assert_allclose(rad, -np.pi)
60
+
61
+ sign, ihmsf = erfa.d2tf(1, -1.5)
62
+ assert sign == b'-'
63
+ assert ihmsf.item() == (36, 0, 0, 0)
64
+
65
+ days = erfa.tf2d('+', 3, 0, 0.0)
66
+ np.testing.assert_allclose(days, 0.125)
67
+
68
+
69
+ def test_spherical_cartesian():
70
+
71
+ theta, phi = erfa.c2s([0.0, np.sqrt(2.0), np.sqrt(2.0)])
72
+ np.testing.assert_allclose(theta, np.pi/2.0)
73
+ np.testing.assert_allclose(phi, np.pi/4.0)
74
+
75
+ theta, phi, r = erfa.p2s([0.0, np.sqrt(2.0), np.sqrt(2.0)])
76
+ np.testing.assert_allclose(theta, np.pi/2.0)
77
+ np.testing.assert_allclose(phi, np.pi/4.0)
78
+ np.testing.assert_allclose(r, 2.0)
79
+
80
+ pv = np.array(([0.0, np.sqrt(2.0), np.sqrt(2.0)], [1.0, 0.0, 0.0]),
81
+ dtype=erfa.dt_pv)
82
+ theta, phi, r, td, pd, rd = erfa.pv2s(pv)
83
+ np.testing.assert_allclose(theta, np.pi/2.0)
84
+ np.testing.assert_allclose(phi, np.pi/4.0)
85
+ np.testing.assert_allclose(r, 2.0)
86
+ np.testing.assert_allclose(td, -np.sqrt(2.0)/2.0)
87
+ np.testing.assert_allclose(pd, 0.0)
88
+ np.testing.assert_allclose(rd, 0.0)
89
+
90
+ c = erfa.s2c(np.pi/2.0, np.pi/4.0)
91
+ np.testing.assert_allclose(c, [0.0, np.sqrt(2.0)/2.0, np.sqrt(2.0)/2.0], atol=1e-14)
92
+
93
+ c = erfa.s2p(np.pi/2.0, np.pi/4.0, 1.0)
94
+ np.testing.assert_allclose(c, [0.0, np.sqrt(2.0)/2.0, np.sqrt(2.0)/2.0], atol=1e-14)
95
+
96
+ pv = erfa.s2pv(np.pi/2.0, np.pi/4.0, 2.0, np.sqrt(2.0)/2.0, 0.0, 0.0)
97
+ np.testing.assert_allclose(pv['p'], [0.0, np.sqrt(2.0), np.sqrt(2.0)], atol=1e-14)
98
+ np.testing.assert_allclose(pv['v'], [-1.0, 0.0, 0.0], atol=1e-14)
99
+
100
+
101
+ def test_errwarn_reporting():
102
+ """
103
+ Test that the ERFA error reporting mechanism works as it should
104
+ """
105
+
106
+ # no warning
107
+ erfa.dat(1990, 1, 1, 0.5)
108
+
109
+ # check warning is raised for a scalar
110
+ with catch_warnings() as w:
111
+ erfa.dat(100, 1, 1, 0.5)
112
+ assert len(w) == 1
113
+ assert w[0].category == erfa.ErfaWarning
114
+ assert '1 of "dubious year (Note 1)"' in str(w[0].message)
115
+
116
+ # and that the count is right for a vector.
117
+ with catch_warnings() as w:
118
+ erfa.dat([100, 200, 1990], 1, 1, 0.5)
119
+ assert len(w) == 1
120
+ assert w[0].category == erfa.ErfaWarning
121
+ assert '2 of "dubious year (Note 1)"' in str(w[0].message)
122
+
123
+ try:
124
+ erfa.dat(1990, [1, 34, 2], [1, 1, 43], 0.5)
125
+ except erfa.ErfaError as e:
126
+ if '1 of "bad day (Note 3)", 1 of "bad month"' not in e.args[0]:
127
+ assert False, 'Raised the correct type of error, but wrong message: ' + e.args[0]
128
+
129
+ try:
130
+ erfa.dat(200, [1, 34, 2], [1, 1, 43], 0.5)
131
+ except erfa.ErfaError as e:
132
+ if 'warning' in e.args[0]:
133
+ assert False, 'Raised the correct type of error, but there were warnings mixed in: ' + e.args[0]
134
+
135
+
136
+ def test_vector_inouts():
137
+ """
138
+ Tests that ERFA functions working with vectors are correctly consumed and spit out
139
+ """
140
+
141
+ # values are from test_erfa.c t_ab function
142
+ pnat = [-0.76321968546737951,
143
+ -0.60869453983060384,
144
+ -0.21676408580639883]
145
+ v = [2.1044018893653786e-5,
146
+ -8.9108923304429319e-5,
147
+ -3.8633714797716569e-5]
148
+ s = 0.99980921395708788
149
+ bm1 = 0.99999999506209258
150
+
151
+ expected = [-0.7631631094219556269,
152
+ -0.6087553082505590832,
153
+ -0.2167926269368471279]
154
+
155
+ res = erfa.ab(pnat, v, s, bm1)
156
+ assert res.shape == (3,)
157
+
158
+ np.testing.assert_allclose(res, expected)
159
+
160
+ res2 = erfa.ab([pnat]*4, v, s, bm1)
161
+ assert res2.shape == (4, 3)
162
+ np.testing.assert_allclose(res2, [expected]*4)
163
+
164
+ # here we stride an array and also do it Fortran-order to make sure
165
+ # it all still works correctly with non-contig arrays
166
+ pnata = np.array(pnat)
167
+ arrin = np.array([pnata, pnata/2, pnata/3, pnata/4, pnata/5]*4, order='F')
168
+ res3 = erfa.ab(arrin[::5], v, s, bm1)
169
+ assert res3.shape == (4, 3)
170
+ np.testing.assert_allclose(res3, [expected]*4)
171
+
172
+
173
+ def test_pv_in():
174
+ jd1 = 2456165.5
175
+ jd2 = 0.401182685
176
+
177
+ pv = np.empty((), dtype=erfa.dt_pv)
178
+ pv['p'] = [-6241497.16,
179
+ 401346.896,
180
+ -1251136.04]
181
+ pv['v'] = [-29.264597,
182
+ -455.021831,
183
+ 0.0266151194]
184
+
185
+ astrom = erfa.apcs13(jd1, jd2, pv)
186
+ assert astrom.shape == ()
187
+
188
+ # values from t_erfa_c
189
+ np.testing.assert_allclose(astrom['pmt'], 12.65133794027378508)
190
+ np.testing.assert_allclose(astrom['em'], 1.010428384373318379)
191
+ np.testing.assert_allclose(astrom['eb'], [0.9012691529023298391,
192
+ -.4173999812023068781,
193
+ -.1809906511146821008])
194
+ np.testing.assert_allclose(astrom['bpn'], np.eye(3))
195
+
196
+ # first make sure it *fails* if we mess with the input orders
197
+ pvbad = np.empty_like(pv)
198
+ pvbad['p'], pvbad['v'] = pv['v'], pv['p']
199
+ astrombad = erfa.apcs13(jd1, jd2, pvbad)
200
+ assert not np.allclose(astrombad['em'], 1.010428384373318379)
201
+
202
+ pvarr = np.array([pv]*3)
203
+ astrom2 = erfa.apcs13(jd1, jd2, pvarr)
204
+ assert astrom2.shape == (3,)
205
+ np.testing.assert_allclose(astrom2['em'], 1.010428384373318379)
206
+
207
+ # try striding of the input array to make non-contiguous
208
+ pvmatarr = np.array([pv]*9)[::3]
209
+ astrom3 = erfa.apcs13(jd1, jd2, pvmatarr)
210
+ assert astrom3.shape == (3,)
211
+ np.testing.assert_allclose(astrom3['em'], 1.010428384373318379)
212
+
213
+
214
+ def test_structs():
215
+ """
216
+ Checks producing and consuming of ERFA c structs
217
+ """
218
+
219
+ am, eo = erfa.apci13(2456165.5, [0.401182685, 1])
220
+ assert am.shape == (2, )
221
+ assert am.dtype == erfa.dt_eraASTROM
222
+ assert eo.shape == (2, )
223
+
224
+ # a few spotchecks from test_erfa.c
225
+ np.testing.assert_allclose(am[0]['pmt'], 12.65133794027378508)
226
+ np.testing.assert_allclose(am[0]['v'], [0.4289638897157027528e-4,
227
+ 0.8115034002544663526e-4,
228
+ 0.3517555122593144633e-4])
229
+
230
+ ri, di = erfa.atciqz(2.71, 0.174, am[0])
231
+ np.testing.assert_allclose(ri, 2.709994899247599271)
232
+ np.testing.assert_allclose(di, 0.1728740720983623469)
233
+
234
+
235
+ def test_float32_input():
236
+ # Regression test for gh-8615
237
+ xyz = np.array([[1, 0, 0], [0.9, 0.1, 0]])
238
+ out64 = erfa.p2s(xyz)
239
+ out32 = erfa.p2s(xyz.astype('f4'))
240
+ np.testing.assert_allclose(out32, out64, rtol=1.e-5)
testbed/astropy__astropy/astropy/_erfa/ufunc.c.templ ADDED
@@ -0,0 +1,852 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* -*- mode: c -*- */
2
+
3
+ /* Licensed under a 3-clause BSD style license - see LICENSE.rst */
4
+
5
+ /*
6
+ * "ufunc.c" is auto-generated by erfa_generator.py from the template
7
+ * "ufunc.c.templ". Do *not* edit "ufunc.c" directly, instead edit
8
+ * "ufunc.c.templ" and run ufunc_generator.py from the source directory
9
+ * to update it.
10
+ */
11
+
12
+ #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
13
+ #include "Python.h"
14
+ #include "numpy/arrayobject.h"
15
+ #include "numpy/ufuncobject.h"
16
+ #include "erfa.h"
17
+ #include "erfa_additions.h"
18
+
19
+ #define MODULE_DOCSTRING \
20
+ "Ufunc wrappers of the ERFA routines.\n\n" \
21
+ "These ufuncs vectorize the ERFA functions assuming structured dtypes\n" \
22
+ "for vector and matrix arguments. Status codes are vectors as well.\n" \
23
+ "Python wrappers are also provided, which convert between\n" \
24
+ "trailing dimensions and structured dtypes where necessary,\n" \
25
+ "and combine status codes."
26
+
27
+ static inline void copy_to_double3(char *ptr, npy_intp s, double d[3]) {
28
+ char *p = ptr;
29
+ int j;
30
+ for (j = 0; j < 3; j++, p += s) {
31
+ d[j] = *(double *)p;
32
+ }
33
+ }
34
+
35
+ static inline void copy_from_double3(char *ptr, npy_intp s, double d[3]) {
36
+ char *p = ptr;
37
+ int j;
38
+ for (j = 0; j < 3; j++, p += s) {
39
+ *(double *)p = d[j];
40
+ }
41
+ }
42
+
43
+ static inline void copy_to_double33(char *ptr, npy_intp s0, npy_intp s1,
44
+ double d[3][3]) {
45
+ char *p0 = ptr;
46
+ int j0, j1;
47
+ for (j0 = 0; j0 < 3; j0++, p0 += s0) {
48
+ char *p1 = p0;
49
+ for (j1 = 0; j1 < 3; j1++, p1 += s1) {
50
+ d[j0][j1] = *(double *)p1;
51
+ }
52
+ }
53
+ }
54
+
55
+ static inline void copy_from_double33(char *ptr, npy_intp s0, npy_intp s1,
56
+ double d[3][3]) {
57
+ char *p = ptr;
58
+ char *p0 = ptr;
59
+ int j0, j1;
60
+ for (j0 = 0; j0 < 3; j0++, p0 += s0) {
61
+ char *p1 = p0;
62
+ for (j1 = 0; j1 < 3; j1++, p1 += s1) {
63
+ *(double *)p = d[j0][j1];
64
+ }
65
+ }
66
+ }
67
+
68
+ /* eraLDBODY is never returned, so we do not need a copy_from */
69
+ static inline void copy_to_eraLDBODY(char *ptr, npy_intp s, npy_intp n,
70
+ eraLDBODY b[]) {
71
+ char *p = ptr;
72
+ npy_intp j;
73
+ for (j = 0; j < n; j++, p += s) {
74
+ b[j] = *(eraLDBODY *)p;
75
+ }
76
+ }
77
+
78
+ /*
79
+ * INNER LOOPS - iteratively call the erfa function for a chunk of data.
80
+ *
81
+ * For each argument:
82
+ * char *<name> is the pointer to the data in memory;
83
+ * npy_intp s_<name> is the number of bytes between successive elements;
84
+ * <ctype> *_<name> is a correctly cast pointer to the current element;
85
+ * (<ctype> _<name>, i.e., not a pointer, for status codes and return values)
86
+ *
87
+ * Notes:
88
+ * 1. Some erfa function change elements in-place; in the ufunc, these "inout"
89
+ * arguments are treated as separate: data is copied from the input to the
90
+ * output, and the output is changed in-place by the erfa function.
91
+ * To reproduce the in-place behaviour, the input to the ufunc can be passed
92
+ * in as output as well -- as is done in the python wrapper (the copy will
93
+ * be omitted for this case).
94
+ * 2. Any erfa function involving light deflection requires an struct
95
+ * eraLDBODY argument with a dimension that is user-defined. Those function
96
+ * are implemented as generalized ufuncs, with a signature in which the
97
+ * relevant variable is marked (i.e., '(),...,(n), (), ... -> (),...').
98
+ * In the inner loops, an appropriate copy is done if in the numpy array
99
+ * the n elements are not contiguous.
100
+ * 3. Similar copies are done for erfa functions that require vectors or
101
+ * matrices, if the corresponding axes in the input or output operands are
102
+ * not contiguous.
103
+ */
104
+
105
+ {%- macro inner_loop_steps_and_copy(arg, arg_name) %}
106
+ {%- for i in range(arg.ndim or 1) %}
107
+ npy_intp is_{{ arg_name }}{{ i }} = *steps++;
108
+ {%- endfor %}
109
+ {#- /* copy should be made if buffer not contiguous;
110
+ note: one can only have 1 or 2 dimensions */ #}
111
+ {%- if arg.ndim == 2 %}
112
+ int copy_{{ arg_name
113
+ }} = (is_{{ arg_name }}1 != sizeof({{ arg.ctype }}) &&
114
+ is_{{ arg_name }}0 != {{ arg.shape[1] }} * sizeof({{ arg.ctype }}));
115
+ {%- else %}
116
+ int copy_{{ arg_name }} = (is_{{ arg_name }}0 != sizeof({{ arg.ctype }}));
117
+ {%- endif %}
118
+ {%- endmacro %}
119
+
120
+ {%- for func in funcs %}
121
+
122
+ static void ufunc_loop_{{ func.pyname }}(
123
+ char **args, npy_intp *dimensions, npy_intp* steps, void* data)
124
+ {
125
+ {#- /* index and length of loop */ #}
126
+ npy_intp i_o;
127
+ npy_intp n_o = *dimensions++;
128
+ {#- /*
129
+ * Pointers to each argument, required step size
130
+ */ #}
131
+ {#- /* normal input arguments */ #}
132
+ {%- for arg in func.args_by_inout('in') %}
133
+ char *{{ arg.name }} = *args++;
134
+ npy_intp s_{{ arg.name }} = *steps++;
135
+ {%- endfor -%}
136
+ {#- /* for in part of in-place arguments, we need a different name */ #}
137
+ {%- for arg in func.args_by_inout('inout') %}
138
+ char *{{ arg.name }}_in = *args++;
139
+ npy_intp s_{{ arg.name }}_in = *steps++;
140
+ {%- endfor -%}
141
+ {#- /* out part of input, and output arguments, including status */ #}
142
+ {%- for arg in func.args_by_inout('inout|out|stat|ret') %}
143
+ char *{{ arg.name }} = *args++;
144
+ npy_intp s_{{ arg.name }} = *steps++;
145
+ {%- endfor -%}
146
+ {#- /*
147
+ * Cast pointers and possible contiguous buffers (for gufuncs)
148
+ */ #}
149
+ {%- for arg in func.args_by_inout('in|inout|out') %}
150
+ {%- if arg.signature_shape == '()' or arg.ctype == 'eraLDBODY' %}
151
+ {{ arg.ctype }} (*_{{ arg.name }}){{ arg.cshape }};
152
+ {%- else %}
153
+ double b_{{ arg.name }}{{ arg.cshape }};
154
+ {{ arg.ctype }} (*_{{ arg.name }}){{ arg.cshape }} = &b_{{ arg.name }};
155
+ {%- endif %}
156
+ {%- endfor %}
157
+ {#- /* variables to hold status and return values */ #}
158
+ {%- for arg in func.args_by_inout('stat|ret') %}
159
+ {{ arg.ctype }} _{{ arg.name }};
160
+ {%- endfor %}
161
+ {#- /*
162
+ * For GENERALIZED UFUNCS - inner loop steps, needs for copying.
163
+ */ #}
164
+ {%- if func.signature %}
165
+ {#- /* loop step sizes and whether copies are needed */ #}
166
+ {%- for arg in func.args_by_inout('in') %}
167
+ {#- /* only LDBODY has non-fixed dimension; it is always first */ #}
168
+ {%- if arg.ctype == 'eraLDBODY' %}
169
+ npy_intp nb = dimensions[0];
170
+ {%- endif %}
171
+ {%- if arg.signature_shape != '()' -%}
172
+ {{ inner_loop_steps_and_copy(arg, arg.name) }}
173
+ {%- endif %}
174
+ {%- endfor %}
175
+ {%- for arg in func.args_by_inout('inout') %}
176
+ {%- if arg.signature_shape != '()' -%}
177
+ {{ inner_loop_steps_and_copy(arg, arg.name + '_in') }}
178
+ {%- endif %}
179
+ {%- endfor %}
180
+ {%- for arg in func.args_by_inout('inout|out') %}
181
+ {%- if arg.signature_shape != '()' -%}
182
+ {{ inner_loop_steps_and_copy(arg, arg.name) }}
183
+ {%- endif %}
184
+ {%- endfor %}
185
+ {#- /* if needed, allocate memory for contiguous eraLDBODY copies */ #}
186
+ {%- if func.user_dtype == 'dt_eraLDBODY' %}
187
+ if (copy_b) {
188
+ _b = PyArray_malloc(nb * sizeof(eraLDBODY));
189
+ if (_b == NULL) {
190
+ PyErr_NoMemory();
191
+ return;
192
+ }
193
+ }
194
+ else { {#- /* just to keep compiler happy */ #}
195
+ _b = NULL;
196
+ }
197
+ {%- endif %}
198
+ {%- endif %} {#- /* end of GUFUNC inner loop definitions */ #}
199
+ {#- /*
200
+ * Actual inner loop, increasing all pointers by their steps
201
+ */ #}
202
+ for (i_o = 0; i_o < n_o;
203
+ i_o++ {%- for arg in func.args_by_inout('in|inout|out|stat|ret') -%}
204
+ , {{ arg.name }} += s_{{ arg.name }}
205
+ {%- endfor -%}
206
+ {%- for arg in func.args_by_inout('inout') -%}
207
+ , {{ arg.name }}_in += s_{{ arg.name }}_in
208
+ {%- endfor -%}) {
209
+ {%- if func.signature %}
210
+ {#- /*
211
+ * GENERALIZED UFUNC, prepare for call.
212
+ */ #}
213
+ {#- /* copy input arguments to buffer if needed */ #}
214
+ {%- for arg in func.args_by_inout('in') %}
215
+ {%- if arg.signature_shape != '()' %}
216
+ if (copy_{{ arg.name }}) {
217
+ copy_to_{{ arg.ctype }}{{ arg.shape|join('') }}({{ arg.name }}
218
+ {%- for i in range(arg.ndim or 1) -%}
219
+ , is_{{ arg.name }}{{ i }}
220
+ {%- endfor %}, {{ arg.name_for_call}});
221
+ }
222
+ else {
223
+ _{{ arg.name }} = (({{ arg.ctype }} (*){{ arg.cshape }}){{ arg.name }});
224
+ }
225
+ {%- else %}
226
+ _{{ arg.name }} = (({{ arg.ctype }} (*){{ arg.cshape }}){{ arg.name }});
227
+ {%- endif %}
228
+ {%- endfor %} {#- end of loop over 'in' #}
229
+ {#- /* for inout arguments, set up output first,
230
+ and then copy to it if needed */ #}
231
+ {%- for arg in func.args_by_inout('inout') %}
232
+ {%- if arg.signature_shape != '()' %}
233
+ if (!copy_{{ arg.name }}) {
234
+ _{{ arg.name }} = (({{ arg.ctype }} (*){{ arg.cshape }}){{ arg.name }});
235
+ }
236
+ if (copy_{{ arg.name }}_in || {{ arg.name }} != {{ arg.name }}_in) {
237
+ copy_to_{{ arg.ctype }}{{ arg.shape|join('') }}({{ arg.name }}_in
238
+ {%- for i in range(arg.ndim or 1) -%}
239
+ , is_{{ arg.name }}_in{{ i }}
240
+ {%- endfor %}, {{ arg.name_for_call}});
241
+ }
242
+ {%- else %}
243
+ _{{ arg.name }} = (({{ arg.ctype }} (*){{ arg.cshape }}){{ arg.name }});
244
+ if ({{ arg.name }}_in != {{ arg.name }}) {
245
+ memcpy({{ arg.name }}, {{ arg.name }}_in, {{ arg.size }}*sizeof({{ arg.ctype }}));
246
+ }
247
+ {%- endif %}
248
+ {%- endfor %} {#- end of loop over 'inout' #}
249
+ {#- /* set up gufunc outputs */ #}
250
+ {%- for arg in func.args_by_inout('out') %}
251
+ {%- if arg.signature_shape != '()' %}
252
+ if (!copy_{{ arg.name }}) {
253
+ _{{ arg.name }} = (({{ arg.ctype }} (*){{ arg.cshape }}){{ arg.name }});
254
+ }
255
+ {%- else %}
256
+ _{{ arg.name }} = (({{ arg.ctype }} (*){{ arg.cshape }}){{ arg.name }});
257
+ {%- endif %}
258
+ {%- endfor %} {#- end of loop over 'out' #}
259
+ {%- else %}
260
+ {#- /*
261
+ * NORMAL UFUNC, prepare for call
262
+ */ #}
263
+ {#- /* set up pointers to input/output arguments */ #}
264
+ {%- for arg in func.args_by_inout('in|inout|out') %}
265
+ _{{ arg.name }} = (({{ arg.ctype }} (*){{ arg.cshape }}){{ arg.name }});
266
+ {%- endfor %}
267
+ {#- /* copy from in to out for arugments changed in-place */ #}
268
+ {%- for arg in func.args_by_inout('inout') %}
269
+ if ({{ arg.name }}_in != {{ arg.name }}) {
270
+ memcpy({{ arg.name }}, {{ arg.name }}_in, {{ arg.size }}*sizeof({{ arg.ctype }}));
271
+ }
272
+ {%- endfor %}
273
+ {%- endif %} {#- end of gufunc/ufunc preparation #}
274
+ {#- /*
275
+ * call the actual erfa function
276
+ */ #}
277
+ {{ func.args_by_inout('ret|stat') |
278
+ map(attribute='name') |
279
+ surround('_', ' = ') |
280
+ join
281
+ }}{{ func.name
282
+ }}({{ func.args_by_inout('in|inout|out') |
283
+ map(attribute='name_for_call') |
284
+ join(', ') }});
285
+ {#- /* store any return values */ #}
286
+ {%- for arg in func.args_by_inout('ret|stat') %}
287
+ *(({{ arg.ctype }} *){{ arg.name }}) = _{{ arg.name }};
288
+ {%- endfor %}
289
+ {%- if func.signature %}
290
+ {#- /* for generalized ufunc, copy output from buffer if needed */ #}
291
+ {%- for arg in func.args_by_inout('inout|out') %}
292
+ {%- if arg.signature_shape != '()' %}
293
+ if (copy_{{ arg.name }}) {
294
+ copy_from_{{ arg.ctype }}{{ arg.shape|join('') }}({{ arg.name }}
295
+ {%- for i in range(arg.ndim or 1) -%}
296
+ , is_{{ arg.name }}{{ i }}
297
+ {%- endfor %}, {{ arg.name_for_call}});
298
+ }
299
+ {%- endif %}
300
+ {%- endfor %}
301
+ {%- endif %}
302
+ }
303
+ {%- if func.user_dtype == 'dt_eraLBODY' %}
304
+ if (copy_b) {
305
+ PyArray_free(_b);
306
+ }
307
+ {%- endif %}
308
+ }
309
+
310
+ {%- endfor %}
311
+
312
+ /*
313
+ * UFUNC LOOP MATCHING HELPERS
314
+ * All but ufunc_loop_matches are copies of code needed but not exported.
315
+ */
316
+
317
+ /*
318
+ * Adjusted version of ufunc_loop_matches from
319
+ * numpy/core/src/umath/ufunc_type_resolution.c.
320
+ * Here, we special-case the structured dtype check, only allowing
321
+ * casting of the same dtype or string. We also do not distinguish
322
+ * between input and output arguments for casting.
323
+ */
324
+ static int
325
+ ufunc_loop_matches(PyUFuncObject *self,
326
+ PyArrayObject **op,
327
+ NPY_CASTING casting,
328
+ int *types, PyArray_Descr **dtypes)
329
+ {
330
+ npy_intp i, nin = self->nin, nop = nin + self->nout;
331
+ /*
332
+ * Check if all the inputs can be cast to the types used by this function.
333
+ */
334
+ for (i = 0; i < nin; ++i) {
335
+ PyArray_Descr *op_descr = PyArray_DESCR(op[i]);
336
+ /*
337
+ * Check for NPY_VOID with an associated struct dtype.
338
+ */
339
+ if (types[i] == NPY_VOID && dtypes != NULL) {
340
+ int op_descr_type_num = op_descr->type_num;
341
+ int dtype_elsize = dtypes[i]->elsize;
342
+ /*
343
+ * MHvK: we do our own check on casting, since by default
344
+ * all items can cast to structured dtypes (see gh-11114),
345
+ * which is not OK. So, we only allow VOID->same VOID,
346
+ * and STRING -> VOID-of-STRING (which works well; we
347
+ * recognize VOID-of-STRING by the dtype element size;
348
+ * it would be rather costly to go look at dtype->fields).
349
+ */
350
+ if (op_descr_type_num == NPY_VOID) {
351
+ /* allow only the same structured to structured */
352
+ if (!PyArray_EquivTypes(op_descr, dtypes[i])) {
353
+ return 0;
354
+ }
355
+ }
356
+ else if (dtypes[i]->elsize == 1 || dtypes[i]->elsize == 12) {
357
+ /* string structured array; string argument is OK */
358
+ if (!((op_descr_type_num == NPY_STRING &&
359
+ op_descr->elsize <= dtype_elsize) ||
360
+ (op_descr_type_num == NPY_UNICODE &&
361
+ op_descr->elsize >> 2 <= dtype_elsize))) {
362
+ return 0;
363
+ }
364
+ }
365
+ else {
366
+ return 0;
367
+ }
368
+ }
369
+ else { /* non-void function argument */
370
+ PyArray_Descr *tmp = PyArray_DescrFromType(types[i]);
371
+ if (tmp == NULL) {
372
+ return -1;
373
+ }
374
+ if (!PyArray_CanCastTypeTo(op_descr, tmp, casting)) {
375
+ Py_DECREF(tmp);
376
+ return 0;
377
+ }
378
+ Py_DECREF(tmp);
379
+ }
380
+ }
381
+ /*
382
+ * All inputs were ok; now check casting back to the outputs.
383
+ * MHvK: Since no casting from structured to non-structured is
384
+ * possible, no changes needed here.
385
+ */
386
+ for (i = nin; i < nop; ++i) {
387
+ if (op[i] != NULL) {
388
+ PyArray_Descr *tmp = PyArray_DescrFromType(types[i]);
389
+ if (tmp == NULL) {
390
+ return -1;
391
+ }
392
+ if (!PyArray_CanCastTypeTo(tmp, PyArray_DESCR(op[i]),
393
+ casting)) {
394
+ Py_DECREF(tmp);
395
+ return 0;
396
+ }
397
+ Py_DECREF(tmp);
398
+ }
399
+ }
400
+ return 1;
401
+ }
402
+ /*
403
+ * Copy from numpy/core/src/umath/ufunc_type_resolution.c,
404
+ * since this translation function is not exported.
405
+ */
406
+ static const char *
407
+ npy_casting_to_string(NPY_CASTING casting)
408
+ {
409
+ switch (casting) {
410
+ case NPY_NO_CASTING:
411
+ return "'no'";
412
+ case NPY_EQUIV_CASTING:
413
+ return "'equiv'";
414
+ case NPY_SAFE_CASTING:
415
+ return "'safe'";
416
+ case NPY_SAME_KIND_CASTING:
417
+ return "'same_kind'";
418
+ case NPY_UNSAFE_CASTING:
419
+ return "'unsafe'";
420
+ default:
421
+ return "<unknown>";
422
+ }
423
+ }
424
+
425
+ /*
426
+ * Copy from numpy/core/src/umath/ufunc_type_resolution.c,
427
+ * since not exported.
428
+ */
429
+ static PyArray_Descr *
430
+ ensure_dtype_nbo(PyArray_Descr *type)
431
+ {
432
+ if (PyArray_ISNBO(type->byteorder)) {
433
+ Py_INCREF(type);
434
+ return type;
435
+ }
436
+ else {
437
+ return PyArray_DescrNewByteorder(type, NPY_NATIVE);
438
+ }
439
+ }
440
+
441
+ /*
442
+ * Copy from numpy/core/src/umath/ufunc_type_resolution.c,
443
+ * since not exported.
444
+ */
445
+ static int
446
+ set_ufunc_loop_data_types(PyUFuncObject *self, PyArrayObject **op,
447
+ PyArray_Descr **out_dtypes,
448
+ int *type_nums, PyArray_Descr **dtypes)
449
+ {
450
+ int i, nin = self->nin, nop = nin + self->nout;
451
+
452
+ /*
453
+ * Fill the dtypes array.
454
+ * For outputs,
455
+ * also search the inputs for a matching type_num to copy
456
+ * instead of creating a new one, similarly to preserve metadata.
457
+ **/
458
+ for (i = 0; i < nop; ++i) {
459
+ if (dtypes != NULL) {
460
+ out_dtypes[i] = dtypes[i];
461
+ Py_XINCREF(out_dtypes[i]);
462
+ /*
463
+ * Copy the dtype from 'op' if the type_num matches,
464
+ * to preserve metadata.
465
+ */
466
+ }
467
+ else if (op[i] != NULL &&
468
+ PyArray_DESCR(op[i])->type_num == type_nums[i]) {
469
+ out_dtypes[i] = ensure_dtype_nbo(PyArray_DESCR(op[i]));
470
+ }
471
+ /*
472
+ * For outputs, copy the dtype from op[0] if the type_num
473
+ * matches, similarly to preserve metdata.
474
+ */
475
+ else if (i >= nin && op[0] != NULL &&
476
+ PyArray_DESCR(op[0])->type_num == type_nums[i]) {
477
+ out_dtypes[i] = ensure_dtype_nbo(PyArray_DESCR(op[0]));
478
+ }
479
+ /* Otherwise create a plain descr from the type number */
480
+ else {
481
+ out_dtypes[i] = PyArray_DescrFromType(type_nums[i]);
482
+ }
483
+
484
+ if (out_dtypes[i] == NULL) {
485
+ goto fail;
486
+ }
487
+ }
488
+
489
+ return 0;
490
+
491
+ fail:
492
+ while (--i >= 0) {
493
+ Py_DECREF(out_dtypes[i]);
494
+ out_dtypes[i] = NULL;
495
+ }
496
+ return -1;
497
+ }
498
+
499
+ /*
500
+ * UFUNC TYPE RESOLVER
501
+ *
502
+ * We provide our own type resolver, since the default one,
503
+ * PyUFunc_DefaultTypeResolver from
504
+ * numpy/core/src/umath/ufunc_type_resolution.c, has problems:
505
+ * 1. It only looks for userloops if any of the operands have a user
506
+ * type, which does not work if the inputs are normal and no explicit
507
+ * output is given (see https://github.com/numpy/numpy/issues/11109).
508
+ * 2. It only allows "safe" casting of inputs, which annoyingly prevents
509
+ * passing in a python int for int32 input.
510
+ * The resolver below solves both, and speeds up the process by
511
+ * explicitly assuming that a ufunc has only one function built in,
512
+ * either a regular one or a userloop (for structured dtype).
513
+ *
514
+ * Combines code from linear_search_type_resolver and
515
+ * linear_search_userloop_type_resolver from
516
+ * numpy/core/src/umath/ufunc_type_resolution.c
517
+ */
518
+ static int ErfaUFuncTypeResolver(PyUFuncObject *ufunc,
519
+ NPY_CASTING casting,
520
+ PyArrayObject **operands,
521
+ PyObject *type_tup,
522
+ PyArray_Descr **out_dtypes)
523
+ {
524
+ int *types;
525
+ PyArray_Descr **dtypes;
526
+
527
+ if (ufunc->userloops) {
528
+ Py_ssize_t unused_pos = 0;
529
+ PyObject *userloop;
530
+ PyUFunc_Loop1d *funcdata;
531
+
532
+ if (ufunc->ntypes > 0 || PyDict_Size(ufunc->userloops) != 1) {
533
+ goto fail;
534
+ }
535
+ /* No iteration needed; only one entry in dict */
536
+ PyDict_Next(ufunc->userloops, &unused_pos, NULL, &userloop);
537
+ funcdata = (PyUFunc_Loop1d *)PyCapsule_GetPointer(userloop, NULL);
538
+ /* There should be only one function */
539
+ if (funcdata->next != NULL) {
540
+ goto fail;
541
+ }
542
+ types = funcdata->arg_types;
543
+ dtypes = funcdata->arg_dtypes;
544
+ }
545
+ else {
546
+ npy_intp j;
547
+ int types_array[NPY_MAXARGS];
548
+
549
+ if (ufunc->ntypes != 1) {
550
+ goto fail;
551
+ }
552
+ /* Copy the types into an int array for matching */
553
+ for (j = 0; j < ufunc->nargs; ++j) {
554
+ types_array[j] = ufunc->types[j];
555
+ }
556
+ types = types_array;
557
+ dtypes = NULL;
558
+ }
559
+ switch (ufunc_loop_matches(ufunc, operands, casting, types, dtypes)) {
560
+ case 1: /* Matching types */
561
+ return set_ufunc_loop_data_types(ufunc, operands, out_dtypes,
562
+ types, dtypes);
563
+ case -1: /* Error */
564
+ return -1;
565
+ }
566
+ /* No match */
567
+ PyErr_Format(PyExc_TypeError,
568
+ "ufunc '%s' not supported for the input types, and the "
569
+ "inputs could not be safely coerced to any supported "
570
+ "types according to the casting rule '%s'",
571
+ ufunc->name, npy_casting_to_string(casting));
572
+ return -1;
573
+
574
+ fail:
575
+ /* More than one loop or function */
576
+ PyErr_Format(PyExc_RuntimeError,
577
+ "Unexpected internal error: ufunc '%s' wraps an ERFA "
578
+ "function and should have only a single loop with a "
579
+ "single function, yet has more.",
580
+ ufunc->name);
581
+ return -1;
582
+ }
583
+
584
+ {%- if NUMPY_LT_1_16 %}
585
+ /*
586
+ * The following is only necessary for NUMPY_LT_1_16. Once we support
587
+ * only numpy >=1.16, it can be removed here and in the template part.
588
+ *
589
+ * For numpy <1.16, this works around the fact that gufuncs could not
590
+ * have fixed dimensions.
591
+ *
592
+ * Rather than just go for our type resolver, we check here whether
593
+ * any non-void input with core dimensions has dimension equal to 3. Here,
594
+ * we already know that all core dimensions are equal, so we have to check
595
+ * only one.
596
+ */
597
+ static int ErfaUFuncD3CheckTypeResolver(PyUFuncObject *ufunc,
598
+ NPY_CASTING casting,
599
+ PyArrayObject **operands,
600
+ PyObject *type_tup,
601
+ PyArray_Descr **out_dtypes)
602
+ {
603
+ int i;
604
+
605
+ for (i = 0; i < ufunc->nin; i++) {
606
+ if (ufunc->core_num_dims[i]) {
607
+ PyArrayObject *op = operands[i];
608
+ if (PyArray_DESCR(op)->type_num != NPY_VOID) {
609
+ /* last dimension is should always be 3 */
610
+ int last_dim = PyArray_DIMS(op)[PyArray_NDIM(op)-1];
611
+ if (last_dim != 3) {
612
+ PyErr_Format(PyExc_ValueError,
613
+ "%s: Input operand %d has a mismatch in its "
614
+ "core dimension %d, with gufunc signature %s "
615
+ "(size %zd is different from fixed size 3)",
616
+ ufunc->name, i, ufunc->core_num_dims[i] - 1,
617
+ ufunc->core_signature, last_dim);
618
+ return -1;
619
+ }
620
+ break;
621
+ }
622
+ }
623
+ }
624
+ if (i == ufunc->nin) {
625
+ PyErr_SetString(PyExc_RuntimeError,
626
+ "no relevant input found; should not happen!");
627
+ }
628
+ return ErfaUFuncTypeResolver(ufunc, casting, operands, type_tup,
629
+ out_dtypes);
630
+ }
631
+ {%- endif %}
632
+
633
+ /*
634
+ * UFUNC MODULE DEFINITIONS AND INITIALIZATION
635
+ */
636
+ static PyMethodDef ErfaUFuncMethods[] = {
637
+ {NULL, NULL, 0, NULL}
638
+ };
639
+
640
+ static struct PyModuleDef moduledef = {
641
+ PyModuleDef_HEAD_INIT,
642
+ "ufunc",
643
+ MODULE_DOCSTRING,
644
+ -1,
645
+ ErfaUFuncMethods,
646
+ NULL,
647
+ NULL,
648
+ NULL,
649
+ NULL
650
+ };
651
+
652
+ PyMODINIT_FUNC PyInit_ufunc(void)
653
+ {
654
+ /* module and its dict */
655
+ PyObject *m, *d;
656
+ /* structured dtypes and their definition */
657
+ PyObject *dtype_def;
658
+ PyArray_Descr *dt_double = NULL, *dt_int = NULL;
659
+ PyArray_Descr *dt_pv = NULL, *dt_pvdpv = NULL;
660
+ PyArray_Descr *dt_ymdf = NULL, *dt_hmsf = NULL, *dt_dmsf = NULL;
661
+ PyArray_Descr *dt_sign = NULL, *dt_type = NULL;
662
+ PyArray_Descr *dt_eraASTROM = NULL, *dt_eraLDBODY = NULL;
663
+ PyArray_Descr *dtypes[NPY_MAXARGS];
664
+ /* ufuncs and their definitions */
665
+ int status;
666
+ PyUFuncObject *ufunc;
667
+ static void *data[1] = {NULL};
668
+ {#- /* for non-structured functions, define there types and functions
669
+ as these do not get copied */ #}
670
+ {%- for func in funcs %}
671
+ {%- if not func.user_dtype %}
672
+ static char types_{{ func.pyname }}[{{ func.args_by_inout('in|inout|out|ret|stat')|count }}] = { {{ func.args_by_inout('in|inout|out|ret|stat')|map(attribute='npy_type')|join(', ') }} };
673
+ static PyUFuncGenericFunction funcs_{{ func.pyname }}[1] = { &ufunc_loop_{{ func.pyname }} };
674
+ {%- endif %}
675
+ {%- endfor %}
676
+
677
+ m = PyModule_Create(&moduledef);
678
+ if (m == NULL) {
679
+ return NULL;
680
+ }
681
+ d = PyModule_GetDict(m); /* borrowed ref. */
682
+ if (d == NULL) {
683
+ goto fail;
684
+ }
685
+
686
+ import_array();
687
+ import_umath();
688
+ /*
689
+ * Define the basic and structured types used in erfa so that
690
+ * we can use them for definitions of userloops below.
691
+ */
692
+ dt_double = PyArray_DescrFromType(NPY_DOUBLE);
693
+ dt_int = PyArray_DescrFromType(NPY_INT);
694
+ /* double[2][3] = pv */
695
+ dtype_def = Py_BuildValue("[(s, s), (s, s)]",
696
+ "p", "(3,)f8", "v", "(3,)f8");
697
+ PyArray_DescrAlignConverter(dtype_def, &dt_pv);
698
+ Py_DECREF(dtype_def);
699
+ /* double[2] = pvdpv */
700
+ dtype_def = Py_BuildValue("[(s, s), (s, s)]",
701
+ "pdp", "f8", "pdv", "f8");
702
+ PyArray_DescrAlignConverter(dtype_def, &dt_pvdpv);
703
+ Py_DECREF(dtype_def);
704
+ /* int[4] = ymdf, hmsf, dmsf */
705
+ dtype_def = Py_BuildValue("[(s, s), (s, s), (s, s), (s, s)]",
706
+ "y", "i4", "m", "i4", "d", "i4", "f", "i4");
707
+ PyArray_DescrAlignConverter(dtype_def, &dt_ymdf);
708
+ Py_DECREF(dtype_def);
709
+ dtype_def = Py_BuildValue("[(s, s), (s, s), (s, s), (s, s)]",
710
+ "h", "i4", "m", "i4", "s", "i4", "f", "i4");
711
+ PyArray_DescrAlignConverter(dtype_def, &dt_hmsf);
712
+ Py_DECREF(dtype_def);
713
+ dtype_def = Py_BuildValue("[(s, s), (s, s), (s, s), (s, s)]",
714
+ "h", "i4", "m", "i4", "s", "i4", "f", "i4");
715
+ PyArray_DescrAlignConverter(dtype_def, &dt_dmsf);
716
+ Py_DECREF(dtype_def);
717
+ /* char1 (have to use structured, otherwise it cannot be a user type) */
718
+ dtype_def = Py_BuildValue("[(s, s)]", "sign", "S1");
719
+ PyArray_DescrAlignConverter(dtype_def, &dt_sign);
720
+ Py_DECREF(dtype_def);
721
+ /* char12 */
722
+ dtype_def = Py_BuildValue("[(s, s)]", "type", "S12");
723
+ PyArray_DescrAlignConverter(dtype_def, &dt_type);
724
+ Py_DECREF(dtype_def);
725
+ /* eraLDBODY */
726
+ dtype_def = Py_BuildValue(
727
+ "[(s, s), (s, s), (s, s)]",
728
+ "bm", "f8", /* mass of the body (solar masses) */
729
+ "dl", "f8", /* deflection limiter (radians^2/2) */
730
+ "pv", "(2,3)f8" /* barycentric PV of the body (au, au/day) */
731
+ );
732
+ PyArray_DescrAlignConverter(dtype_def, &dt_eraLDBODY);
733
+ Py_DECREF(dtype_def);
734
+ /* eraASTROM */
735
+ dtype_def = Py_BuildValue(
736
+ "[(s, s), (s, s), (s, s), (s, s),"
737
+ " (s, s), (s, s), (s, s), (s, s),"
738
+ " (s, s), (s, s), (s, s), (s, s),"
739
+ " (s, s), (s, s), (s, s), (s, s), (s, s)]",
740
+ "pmt", "f8", /* PM time interval (SSB, Julian years) */
741
+ "eb", "(3,)f8", /* SSB to observer (vector, au) */
742
+ "eh", "(3,)f8", /* Sun to observer (unit vector) */
743
+ "em", "f8", /* distance from Sun to observer (au) */
744
+ "v", "(3,)f8", /* barycentric observer velocity (vector, c) */
745
+ "bm1", "f8", /* sqrt(1-|v|^2): reciprocal of Lorenz factor */
746
+ "bpn", "(3,3)f8", /* bias-precession-nutation matrix */
747
+ "along", "f8", /* longitude + s' + dERA(DUT) (radians) */
748
+ "phi", "f8", /* geodetic latitude (radians) */
749
+ "xpl", "f8", /* polar motion xp wrt local meridian (radians) */
750
+ "ypl", "f8", /* polar motion yp wrt local meridian (radians) */
751
+ "sphi", "f8", /* sine of geodetic latitude */
752
+ "cphi", "f8", /* cosine of geodetic latitude */
753
+ "diurab", "f8", /* magnitude of diurnal aberration vector */
754
+ "eral", "f8", /* "local" Earth rotation angle (radians) */
755
+ "refa", "f8", /* refraction constant A (radians) */
756
+ "refb", "f8" /* refraction constant B (radians) */
757
+ );
758
+ PyArray_DescrAlignConverter(dtype_def, &dt_eraASTROM);
759
+ Py_DECREF(dtype_def);
760
+ if (dt_double == NULL || dt_int == NULL ||
761
+ dt_pv == NULL || dt_pvdpv == NULL ||
762
+ dt_ymdf == NULL || dt_hmsf == NULL || dt_dmsf == NULL ||
763
+ dt_sign == NULL || dt_type == NULL ||
764
+ dt_eraLDBODY == NULL || dt_eraASTROM == NULL) {
765
+ goto fail;
766
+ }
767
+ /* Make the structured dtypes available in the module */
768
+ PyDict_SetItemString(d, "dt_pv", (PyObject *)dt_pv);
769
+ PyDict_SetItemString(d, "dt_pvdpv", (PyObject *)dt_pvdpv);
770
+ PyDict_SetItemString(d, "dt_ymdf", (PyObject *)dt_ymdf);
771
+ PyDict_SetItemString(d, "dt_hmsf", (PyObject *)dt_hmsf);
772
+ PyDict_SetItemString(d, "dt_dmsf", (PyObject *)dt_dmsf);
773
+ PyDict_SetItemString(d, "dt_sign", (PyObject *)dt_sign);
774
+ PyDict_SetItemString(d, "dt_type", (PyObject *)dt_type);
775
+ PyDict_SetItemString(d, "dt_eraLDBODY", (PyObject *)dt_eraLDBODY);
776
+ PyDict_SetItemString(d, "dt_eraASTROM", (PyObject *)dt_eraASTROM);
777
+ /*
778
+ * Define the ufuncs. For those without structured dtypes,
779
+ * the ufunc creation uses the static variables defined above;
780
+ * for those with structured dtypes, an empty ufunc is created,
781
+ * and then a userloop is added. For both, we set the type
782
+ * resolver to our own, and then add the ufunc to the module.
783
+ *
784
+ * Note that for the arguments, any inout arguments, i.e., those
785
+ * that are changed in-place in the ERFA function, are repeated,
786
+ * since we want the ufuncs not to do in-place changes (unless
787
+ * explicitly requested with ufunc(..., in,..., out=in))
788
+ */
789
+ {%- for func in funcs %}
790
+ {%- if not func.user_dtype %}
791
+ ufunc = (PyUFuncObject *)PyUFunc_FromFuncAndDataAndSignature(
792
+ funcs_{{ func.pyname }}, data, types_{{ func.pyname }},
793
+ 1, {{ func.args_by_inout('in|inout')|count }}, {{ func.args_by_inout('inout|out|ret|stat')|count }}, PyUFunc_None,
794
+ "{{ func.pyname }}",
795
+ "UFunc wrapper for {{ func.name }}",
796
+ 0, {% if func.signature -%} "{{ func.signature }}" {%- else -%} NULL {%- endif -%});
797
+ if (ufunc == NULL) {
798
+ goto fail;
799
+ }
800
+ {%- else %}
801
+ ufunc = (PyUFuncObject *)PyUFunc_FromFuncAndDataAndSignature(
802
+ NULL, NULL, NULL,
803
+ 0, {{ func.args_by_inout('in|inout')|count }}, {{ func.args_by_inout('inout|out|ret|stat')|count }}, PyUFunc_None,
804
+ "{{ func.pyname }}",
805
+ "UFunc wrapper for {{ func.name }}",
806
+ 0, {% if func.signature -%} "{{ func.signature }}" {%- else -%} NULL {%- endif -%});
807
+ if (ufunc == NULL) {
808
+ goto fail;
809
+ }
810
+ {%- for arg in func.args_by_inout('in|inout') %}
811
+ dtypes[{{ loop.index - 1 }}] = {{ arg.dtype }};
812
+ {%- endfor %}
813
+ {%- for arg in func.args_by_inout('inout|out|ret|stat') %}
814
+ dtypes[{{ loop.index - 1 + func.args_by_inout('in|inout')|count }}] = {{ arg.dtype }};
815
+ {%- endfor %}
816
+ status = PyUFunc_RegisterLoopForDescr(
817
+ ufunc, {{ func.user_dtype }},
818
+ ufunc_loop_{{ func.pyname }}, dtypes, NULL);
819
+ if(status != 0){
820
+ Py_DECREF(ufunc);
821
+ goto fail;
822
+ }
823
+ {%- endif %}
824
+ {%- if func.signature and 'd3' in func.signature and not func.d3_fix_arg %}
825
+ ufunc->type_resolver = &ErfaUFuncD3CheckTypeResolver;
826
+ {%- else %}
827
+ ufunc->type_resolver = &ErfaUFuncTypeResolver;
828
+ {%- endif %}
829
+ PyDict_SetItemString(d, "{{ func.pyname }}", (PyObject *)ufunc);
830
+ Py_DECREF(ufunc);
831
+ {%- endfor %}
832
+
833
+ goto decref;
834
+
835
+ fail:
836
+ Py_XDECREF(m);
837
+ m = NULL;
838
+
839
+ decref:
840
+ Py_XDECREF(dt_double);
841
+ Py_XDECREF(dt_int);
842
+ Py_XDECREF(dt_pv);
843
+ Py_XDECREF(dt_pvdpv);
844
+ Py_XDECREF(dt_ymdf);
845
+ Py_XDECREF(dt_hmsf);
846
+ Py_XDECREF(dt_dmsf);
847
+ Py_XDECREF(dt_sign);
848
+ Py_XDECREF(dt_type);
849
+ Py_XDECREF(dt_eraASTROM);
850
+ Py_XDECREF(dt_eraLDBODY);
851
+ return m;
852
+ }
testbed/astropy__astropy/astropy/astropy.cfg ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+
3
+ ### CONSOLE SETTINGS
4
+
5
+ ## Use Unicode characters when outputting values, and writing widgets to the
6
+ ## console.
7
+ # unicode_output = False
8
+
9
+ ## When True, use ANSI color escape sequences when writing to the console.
10
+ # use_color = True
11
+
12
+ ## Maximum number of lines for the pretty-printer. If not provided,
13
+ ## determine automatically from the size of the terminal. -1 means no
14
+ ## limit.
15
+ # max_lines =
16
+
17
+ ## Maximum number of characters-per-line for the pretty-printer. If
18
+ ## not provided, determine automatically from the size of the
19
+ ## terminal, if possible. -1 means no limit.
20
+ # max_width =
21
+
22
+
23
+ ### CORE DATA STRUCTURES AND TRANSFORMATIONS
24
+
25
+ [nddata]
26
+
27
+ ## Whether to issue a warning if NDData arithmetic is performed with
28
+ ## uncertainties and the uncertainties do not support the propagation of
29
+ ## correlated uncertainties.
30
+ # warn_unsupported_correlated = True
31
+
32
+ ## Whether to issue a warning when the `~astropy.nddata.NDData` unit
33
+ ## attribute is changed from a non-``None`` value to another value
34
+ ## that data values/uncertainties are not scaled with the unit change.
35
+ # warn_setting_unit_directly = True
36
+
37
+ [table]
38
+
39
+ ## The template that determines the name of a column if it cannot be
40
+ ## determined. Uses new-style (format method) string formatting
41
+ # auto_colname = col{0}
42
+
43
+ [table.jsviewer]
44
+
45
+ ## The URL to the jQuery library to use. If not provided, uses the
46
+ ## internal copy installed with astropy.
47
+ # jquery_url =
48
+
49
+ ## The URL to the jQuery datatables library to use. If not provided,
50
+ ## uses the internal copy installed with astropy.
51
+ # datatables_url =
52
+
53
+ ### ASTRONOMY COMPUTATIONS AND UTILITIES
54
+
55
+ [samp]
56
+
57
+ ## Whether to allow astropy.samp to use the internet, if available
58
+ # use_internet = True
59
+
60
+ ## How many times to retry communications when they fail
61
+ # n_retries = 10
62
+
63
+
64
+ ### INPUT/OUTPUT
65
+
66
+ [io.fits]
67
+
68
+ ## If True, enable support for record-valued keywords as described by FITS WCS
69
+ ## Paper IV. Otherwise they are treated as normal keywords.
70
+ # enable_record_valued_keyword_cards = True
71
+
72
+ ## If True, extension names (i.e. the EXTNAME keyword) should be treated as
73
+ ## case-sensitive.
74
+ # extension_name_case_sensitive = False
75
+
76
+ ## If True, automatically remove trailing whitespace for string values in
77
+ ## headers. Otherwise the values are returned verbatim, with all whitespace
78
+ ## intact.
79
+ # strip_header_whitespace = True
80
+
81
+ ## If True, use memory-mapped file access to read/write the data in FITS files.
82
+ ## This generally provides better performance, especially for large files, but
83
+ ## may affect performance in I/O-heavy applications.
84
+ # use_memmap = True
85
+
86
+ [io.votable]
87
+
88
+ ## When True, treat fixable violations of the VOTable spec as exceptions.
89
+ # pedantic = True
90
+
91
+
92
+ ### NUTS AND BOLTS OF ASTROPY
93
+
94
+
95
+ [logger]
96
+
97
+ ## Threshold for the logging messages. Logging messages that are less severe
98
+ ## than this level will be ignored. The levels are 'DEBUG', 'INFO', 'WARNING',
99
+ ## 'ERROR'
100
+ # log_level = INFO
101
+
102
+ ## Whether to log warnings.warn calls
103
+ # log_warnings = True
104
+
105
+ ## Whether to log exceptions before raising them
106
+ # log_exceptions = False
107
+
108
+ ## Whether to always log messages to a log file
109
+ # log_to_file = False
110
+
111
+ ## The file to log messages to. When '', it defaults to a file 'astropy.log' in
112
+ ## the astropy config directory.
113
+ # log_file_path = ""
114
+
115
+ ## Threshold for logging messages to log_file_path
116
+ # log_file_level = INFO
117
+
118
+ ## Format for log file entries
119
+ # log_file_format = "%(asctime)r, %(origin)r, %(levelname)r, %(message)r"
120
+
121
+ [utils.data]
122
+
123
+ ## URL for astropy remote data site.
124
+ # dataurl = http://data.astropy.org/
125
+
126
+ ## Time to wait for remote data query (in seconds).
127
+ # remote_timeout = 3.0
128
+
129
+ ## Block size for computing MD5 file hashes.
130
+ # hash_block_size = 65536
131
+
132
+ ## Number of bytes of remote data to download per step.
133
+ # download_block_size = 65536
134
+
135
+ ## Number of times to try to get the lock while accessing the data cache before
136
+ ## giving up.
137
+ # download_cache_lock_attempts = 5
138
+
139
+ ## If True, temporary download files created when the cache is inacessible will
140
+ ## be deleted at the end of the python session.
141
+ # delete_temporary_downloads_at_exit = True
testbed/astropy__astropy/astropy/conftest.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+ """
3
+ This file contains pytest configuration settings that are astropy-specific
4
+ (i.e. those that would not necessarily be shared by affiliated packages
5
+ making use of astropy's test runner).
6
+ """
7
+ import os
8
+ import builtins
9
+ import tempfile
10
+
11
+ from astropy.tests.plugins.display import PYTEST_HEADER_MODULES
12
+ from astropy.tests.helper import enable_deprecations_as_exceptions
13
+
14
+ try:
15
+ import matplotlib
16
+ except ImportError:
17
+ HAS_MATPLOTLIB = False
18
+ else:
19
+ HAS_MATPLOTLIB = True
20
+
21
+ enable_deprecations_as_exceptions(
22
+ include_astropy_deprecations=False,
23
+ # This is a workaround for the OpenSSL deprecation warning that comes from
24
+ # the `requests` module. It only appears when both asdf and sphinx are
25
+ # installed. This can be removed once pyopenssl 1.7.20+ is released.
26
+ modules_to_ignore_on_import=['requests'])
27
+
28
+ if HAS_MATPLOTLIB:
29
+ matplotlib.use('Agg')
30
+
31
+ matplotlibrc_cache = {}
32
+
33
+
34
+ def pytest_configure(config):
35
+ builtins._pytest_running = True
36
+ # do not assign to matplotlibrc_cache in function scope
37
+ if HAS_MATPLOTLIB:
38
+ matplotlibrc_cache.update(matplotlib.rcParams)
39
+ matplotlib.rcdefaults()
40
+
41
+ # Make sure we use temporary directories for the config and cache
42
+ # so that the tests are insensitive to local configuration. Note that this
43
+ # is also set in the test runner, but we need to also set it here for
44
+ # things to work properly in parallel mode
45
+
46
+ builtins._xdg_config_home_orig = os.environ.get('XDG_CONFIG_HOME')
47
+ builtins._xdg_cache_home_orig = os.environ.get('XDG_CACHE_HOME')
48
+
49
+ os.environ['XDG_CONFIG_HOME'] = tempfile.mkdtemp('astropy_config')
50
+ os.environ['XDG_CACHE_HOME'] = tempfile.mkdtemp('astropy_cache')
51
+
52
+ os.mkdir(os.path.join(os.environ['XDG_CONFIG_HOME'], 'astropy'))
53
+ os.mkdir(os.path.join(os.environ['XDG_CACHE_HOME'], 'astropy'))
54
+
55
+
56
+ def pytest_unconfigure(config):
57
+ builtins._pytest_running = False
58
+ # do not assign to matplotlibrc_cache in function scope
59
+ if HAS_MATPLOTLIB:
60
+ matplotlib.rcParams.update(matplotlibrc_cache)
61
+ matplotlibrc_cache.clear()
62
+
63
+ if builtins._xdg_config_home_orig is None:
64
+ os.environ.pop('XDG_CONFIG_HOME')
65
+ else:
66
+ os.environ['XDG_CONFIG_HOME'] = builtins._xdg_config_home_orig
67
+
68
+ if builtins._xdg_cache_home_orig is None:
69
+ os.environ.pop('XDG_CACHE_HOME')
70
+ else:
71
+ os.environ['XDG_CACHE_HOME'] = builtins._xdg_cache_home_orig
72
+
73
+
74
+ PYTEST_HEADER_MODULES['Cython'] = 'cython'
75
+ PYTEST_HEADER_MODULES['Scikit-image'] = 'skimage'
testbed/astropy__astropy/astropy/logger.py ADDED
@@ -0,0 +1,568 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+ """This module defines a logging class based on the built-in logging module"""
3
+
4
+ import inspect
5
+ import os
6
+ import sys
7
+ import logging
8
+ import warnings
9
+ from contextlib import contextmanager
10
+
11
+ from . import config as _config
12
+ from . import conf as _conf
13
+ from .utils import find_current_module
14
+ from .utils.exceptions import AstropyWarning, AstropyUserWarning
15
+
16
+ __all__ = ['Conf', 'conf', 'log', 'AstropyLogger', 'LoggingError']
17
+
18
+ # import the logging levels from logging so that one can do:
19
+ # log.setLevel(log.DEBUG), for example
20
+ logging_levels = ['NOTSET', 'DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL',
21
+ 'FATAL', ]
22
+ for level in logging_levels:
23
+ globals()[level] = getattr(logging, level)
24
+ __all__ += logging_levels
25
+
26
+
27
+ # Initialize by calling _init_log()
28
+ log = None
29
+
30
+
31
+ class LoggingError(Exception):
32
+ """
33
+ This exception is for various errors that occur in the astropy logger,
34
+ typically when activating or deactivating logger-related features.
35
+ """
36
+
37
+
38
+ class _AstLogIPYExc(Exception):
39
+ """
40
+ An exception that is used only as a placeholder to indicate to the
41
+ IPython exception-catching mechanism that the astropy
42
+ exception-capturing is activated. It should not actually be used as
43
+ an exception anywhere.
44
+ """
45
+
46
+
47
+ class Conf(_config.ConfigNamespace):
48
+ """
49
+ Configuration parameters for `astropy.logger`.
50
+ """
51
+ log_level = _config.ConfigItem(
52
+ 'INFO',
53
+ "Threshold for the logging messages. Logging "
54
+ "messages that are less severe than this level "
55
+ "will be ignored. The levels are ``'DEBUG'``, "
56
+ "``'INFO'``, ``'WARNING'``, ``'ERROR'``.")
57
+ log_warnings = _config.ConfigItem(
58
+ True,
59
+ "Whether to log `warnings.warn` calls.")
60
+ log_exceptions = _config.ConfigItem(
61
+ False,
62
+ "Whether to log exceptions before raising "
63
+ "them.")
64
+ log_to_file = _config.ConfigItem(
65
+ False,
66
+ "Whether to always log messages to a log "
67
+ "file.")
68
+ log_file_path = _config.ConfigItem(
69
+ '',
70
+ "The file to log messages to. When ``''``, "
71
+ "it defaults to a file ``'astropy.log'`` in "
72
+ "the astropy config directory.")
73
+ log_file_level = _config.ConfigItem(
74
+ 'INFO',
75
+ "Threshold for logging messages to "
76
+ "`log_file_path`.")
77
+ log_file_format = _config.ConfigItem(
78
+ "%(asctime)r, "
79
+ "%(origin)r, %(levelname)r, %(message)r",
80
+ "Format for log file entries.")
81
+
82
+
83
+ conf = Conf()
84
+
85
+
86
+ def _init_log():
87
+ """Initializes the Astropy log--in most circumstances this is called
88
+ automatically when importing astropy.
89
+ """
90
+
91
+ global log
92
+
93
+ orig_logger_cls = logging.getLoggerClass()
94
+ logging.setLoggerClass(AstropyLogger)
95
+ try:
96
+ log = logging.getLogger('astropy')
97
+ log._set_defaults()
98
+ finally:
99
+ logging.setLoggerClass(orig_logger_cls)
100
+
101
+ return log
102
+
103
+
104
+ def _teardown_log():
105
+ """Shut down exception and warning logging (if enabled) and clear all
106
+ Astropy loggers from the logging module's cache.
107
+
108
+ This involves poking some logging module internals, so much if it is 'at
109
+ your own risk' and is allowed to pass silently if any exceptions occur.
110
+ """
111
+
112
+ global log
113
+
114
+ if log.exception_logging_enabled():
115
+ log.disable_exception_logging()
116
+
117
+ if log.warnings_logging_enabled():
118
+ log.disable_warnings_logging()
119
+
120
+ del log
121
+
122
+ # Now for the fun stuff...
123
+ try:
124
+ logging._acquireLock()
125
+ try:
126
+ loggerDict = logging.Logger.manager.loggerDict
127
+ for key in loggerDict.keys():
128
+ if key == 'astropy' or key.startswith('astropy.'):
129
+ del loggerDict[key]
130
+ finally:
131
+ logging._releaseLock()
132
+ except Exception:
133
+ pass
134
+
135
+
136
+ Logger = logging.getLoggerClass()
137
+
138
+
139
+ class AstropyLogger(Logger):
140
+ '''
141
+ This class is used to set up the Astropy logging.
142
+
143
+ The main functionality added by this class over the built-in
144
+ logging.Logger class is the ability to keep track of the origin of the
145
+ messages, the ability to enable logging of warnings.warn calls and
146
+ exceptions, and the addition of colorized output and context managers to
147
+ easily capture messages to a file or list.
148
+ '''
149
+
150
+ def makeRecord(self, name, level, pathname, lineno, msg, args, exc_info,
151
+ func=None, extra=None, sinfo=None):
152
+ if extra is None:
153
+ extra = {}
154
+ if 'origin' not in extra:
155
+ current_module = find_current_module(1, finddiff=[True, 'logging'])
156
+ if current_module is not None:
157
+ extra['origin'] = current_module.__name__
158
+ else:
159
+ extra['origin'] = 'unknown'
160
+ return Logger.makeRecord(self, name, level, pathname, lineno, msg,
161
+ args, exc_info, func=func, extra=extra,
162
+ sinfo=sinfo)
163
+
164
+ _showwarning_orig = None
165
+
166
+ def _showwarning(self, *args, **kwargs):
167
+
168
+ # Bail out if we are not catching a warning from Astropy
169
+ if not isinstance(args[0], AstropyWarning):
170
+ return self._showwarning_orig(*args, **kwargs)
171
+
172
+ warning = args[0]
173
+ # Deliberately not using isinstance here: We want to display
174
+ # the class name only when it's not the default class,
175
+ # AstropyWarning. The name of subclasses of AstropyWarning should
176
+ # be displayed.
177
+ if type(warning) not in (AstropyWarning, AstropyUserWarning):
178
+ message = '{0}: {1}'.format(warning.__class__.__name__, args[0])
179
+ else:
180
+ message = str(args[0])
181
+
182
+ mod_path = args[2]
183
+ # Now that we have the module's path, we look through sys.modules to
184
+ # find the module object and thus the fully-package-specified module
185
+ # name. The module.__file__ is the original source file name.
186
+ mod_name = None
187
+ mod_path, ext = os.path.splitext(mod_path)
188
+ for name, mod in list(sys.modules.items()):
189
+ try:
190
+ # Believe it or not this can fail in some cases:
191
+ # https://github.com/astropy/astropy/issues/2671
192
+ path = os.path.splitext(getattr(mod, '__file__', ''))[0]
193
+ except Exception:
194
+ continue
195
+ if path == mod_path:
196
+ mod_name = mod.__name__
197
+ break
198
+
199
+ if mod_name is not None:
200
+ self.warning(message, extra={'origin': mod_name})
201
+ else:
202
+ self.warning(message)
203
+
204
+ def warnings_logging_enabled(self):
205
+ return self._showwarning_orig is not None
206
+
207
+ def enable_warnings_logging(self):
208
+ '''
209
+ Enable logging of warnings.warn() calls
210
+
211
+ Once called, any subsequent calls to ``warnings.warn()`` are
212
+ redirected to this logger and emitted with level ``WARN``. Note that
213
+ this replaces the output from ``warnings.warn``.
214
+
215
+ This can be disabled with ``disable_warnings_logging``.
216
+ '''
217
+ if self.warnings_logging_enabled():
218
+ raise LoggingError("Warnings logging has already been enabled")
219
+ self._showwarning_orig = warnings.showwarning
220
+ warnings.showwarning = self._showwarning
221
+
222
+ def disable_warnings_logging(self):
223
+ '''
224
+ Disable logging of warnings.warn() calls
225
+
226
+ Once called, any subsequent calls to ``warnings.warn()`` are no longer
227
+ redirected to this logger.
228
+
229
+ This can be re-enabled with ``enable_warnings_logging``.
230
+ '''
231
+ if not self.warnings_logging_enabled():
232
+ raise LoggingError("Warnings logging has not been enabled")
233
+ if warnings.showwarning != self._showwarning:
234
+ raise LoggingError("Cannot disable warnings logging: "
235
+ "warnings.showwarning was not set by this "
236
+ "logger, or has been overridden")
237
+ warnings.showwarning = self._showwarning_orig
238
+ self._showwarning_orig = None
239
+
240
+ _excepthook_orig = None
241
+
242
+ def _excepthook(self, etype, value, traceback):
243
+
244
+ if traceback is None:
245
+ mod = None
246
+ else:
247
+ tb = traceback
248
+ while tb.tb_next is not None:
249
+ tb = tb.tb_next
250
+ mod = inspect.getmodule(tb)
251
+
252
+ # include the the error type in the message.
253
+ if len(value.args) > 0:
254
+ message = '{0}: {1}'.format(etype.__name__, str(value))
255
+ else:
256
+ message = str(etype.__name__)
257
+
258
+ if mod is not None:
259
+ self.error(message, extra={'origin': mod.__name__})
260
+ else:
261
+ self.error(message)
262
+ self._excepthook_orig(etype, value, traceback)
263
+
264
+ def exception_logging_enabled(self):
265
+ '''
266
+ Determine if the exception-logging mechanism is enabled.
267
+
268
+ Returns
269
+ -------
270
+ exclog : bool
271
+ True if exception logging is on, False if not.
272
+ '''
273
+ try:
274
+ ip = get_ipython()
275
+ except NameError:
276
+ ip = None
277
+
278
+ if ip is None:
279
+ return self._excepthook_orig is not None
280
+ else:
281
+ return _AstLogIPYExc in ip.custom_exceptions
282
+
283
+ def enable_exception_logging(self):
284
+ '''
285
+ Enable logging of exceptions
286
+
287
+ Once called, any uncaught exceptions will be emitted with level
288
+ ``ERROR`` by this logger, before being raised.
289
+
290
+ This can be disabled with ``disable_exception_logging``.
291
+ '''
292
+ try:
293
+ ip = get_ipython()
294
+ except NameError:
295
+ ip = None
296
+
297
+ if self.exception_logging_enabled():
298
+ raise LoggingError("Exception logging has already been enabled")
299
+
300
+ if ip is None:
301
+ # standard python interpreter
302
+ self._excepthook_orig = sys.excepthook
303
+ sys.excepthook = self._excepthook
304
+ else:
305
+ # IPython has its own way of dealing with excepthook
306
+
307
+ # We need to locally define the function here, because IPython
308
+ # actually makes this a member function of their own class
309
+ def ipy_exc_handler(ipyshell, etype, evalue, tb, tb_offset=None):
310
+ # First use our excepthook
311
+ self._excepthook(etype, evalue, tb)
312
+
313
+ # Now also do IPython's traceback
314
+ ipyshell.showtraceback((etype, evalue, tb), tb_offset=tb_offset)
315
+
316
+ # now register the function with IPython
317
+ # note that we include _AstLogIPYExc so `disable_exception_logging`
318
+ # knows that it's disabling the right thing
319
+ ip.set_custom_exc((BaseException, _AstLogIPYExc), ipy_exc_handler)
320
+
321
+ # and set self._excepthook_orig to a no-op
322
+ self._excepthook_orig = lambda etype, evalue, tb: None
323
+
324
+ def disable_exception_logging(self):
325
+ '''
326
+ Disable logging of exceptions
327
+
328
+ Once called, any uncaught exceptions will no longer be emitted by this
329
+ logger.
330
+
331
+ This can be re-enabled with ``enable_exception_logging``.
332
+ '''
333
+ try:
334
+ ip = get_ipython()
335
+ except NameError:
336
+ ip = None
337
+
338
+ if not self.exception_logging_enabled():
339
+ raise LoggingError("Exception logging has not been enabled")
340
+
341
+ if ip is None:
342
+ # standard python interpreter
343
+ if sys.excepthook != self._excepthook:
344
+ raise LoggingError("Cannot disable exception logging: "
345
+ "sys.excepthook was not set by this logger, "
346
+ "or has been overridden")
347
+ sys.excepthook = self._excepthook_orig
348
+ self._excepthook_orig = None
349
+ else:
350
+ # IPython has its own way of dealing with exceptions
351
+ ip.set_custom_exc(tuple(), None)
352
+
353
+ def enable_color(self):
354
+ '''
355
+ Enable colorized output
356
+ '''
357
+ _conf.use_color = True
358
+
359
+ def disable_color(self):
360
+ '''
361
+ Disable colorized output
362
+ '''
363
+ _conf.use_color = False
364
+
365
+ @contextmanager
366
+ def log_to_file(self, filename, filter_level=None, filter_origin=None):
367
+ '''
368
+ Context manager to temporarily log messages to a file.
369
+
370
+ Parameters
371
+ ----------
372
+ filename : str
373
+ The file to log messages to.
374
+ filter_level : str
375
+ If set, any log messages less important than ``filter_level`` will
376
+ not be output to the file. Note that this is in addition to the
377
+ top-level filtering for the logger, so if the logger has level
378
+ 'INFO', then setting ``filter_level`` to ``INFO`` or ``DEBUG``
379
+ will have no effect, since these messages are already filtered
380
+ out.
381
+ filter_origin : str
382
+ If set, only log messages with an origin starting with
383
+ ``filter_origin`` will be output to the file.
384
+
385
+ Notes
386
+ -----
387
+
388
+ By default, the logger already outputs log messages to a file set in
389
+ the Astropy configuration file. Using this context manager does not
390
+ stop log messages from being output to that file, nor does it stop log
391
+ messages from being printed to standard output.
392
+
393
+ Examples
394
+ --------
395
+
396
+ The context manager is used as::
397
+
398
+ with logger.log_to_file('myfile.log'):
399
+ # your code here
400
+ '''
401
+
402
+ fh = logging.FileHandler(filename)
403
+ if filter_level is not None:
404
+ fh.setLevel(filter_level)
405
+ if filter_origin is not None:
406
+ fh.addFilter(FilterOrigin(filter_origin))
407
+ f = logging.Formatter(conf.log_file_format)
408
+ fh.setFormatter(f)
409
+ self.addHandler(fh)
410
+ yield
411
+ fh.close()
412
+ self.removeHandler(fh)
413
+
414
+ @contextmanager
415
+ def log_to_list(self, filter_level=None, filter_origin=None):
416
+ '''
417
+ Context manager to temporarily log messages to a list.
418
+
419
+ Parameters
420
+ ----------
421
+ filename : str
422
+ The file to log messages to.
423
+ filter_level : str
424
+ If set, any log messages less important than ``filter_level`` will
425
+ not be output to the file. Note that this is in addition to the
426
+ top-level filtering for the logger, so if the logger has level
427
+ 'INFO', then setting ``filter_level`` to ``INFO`` or ``DEBUG``
428
+ will have no effect, since these messages are already filtered
429
+ out.
430
+ filter_origin : str
431
+ If set, only log messages with an origin starting with
432
+ ``filter_origin`` will be output to the file.
433
+
434
+ Notes
435
+ -----
436
+
437
+ Using this context manager does not stop log messages from being
438
+ output to standard output.
439
+
440
+ Examples
441
+ --------
442
+
443
+ The context manager is used as::
444
+
445
+ with logger.log_to_list() as log_list:
446
+ # your code here
447
+ '''
448
+ lh = ListHandler()
449
+ if filter_level is not None:
450
+ lh.setLevel(filter_level)
451
+ if filter_origin is not None:
452
+ lh.addFilter(FilterOrigin(filter_origin))
453
+ self.addHandler(lh)
454
+ yield lh.log_list
455
+ self.removeHandler(lh)
456
+
457
+ def _set_defaults(self):
458
+ '''
459
+ Reset logger to its initial state
460
+ '''
461
+
462
+ # Reset any previously installed hooks
463
+ if self.warnings_logging_enabled():
464
+ self.disable_warnings_logging()
465
+ if self.exception_logging_enabled():
466
+ self.disable_exception_logging()
467
+
468
+ # Remove all previous handlers
469
+ for handler in self.handlers[:]:
470
+ self.removeHandler(handler)
471
+
472
+ # Set levels
473
+ self.setLevel(conf.log_level)
474
+
475
+ # Set up the stdout handler
476
+ sh = StreamHandler()
477
+ self.addHandler(sh)
478
+
479
+ # Set up the main log file handler if requested (but this might fail if
480
+ # configuration directory or log file is not writeable).
481
+ if conf.log_to_file:
482
+ log_file_path = conf.log_file_path
483
+
484
+ # "None" as a string because it comes from config
485
+ try:
486
+ _ASTROPY_TEST_
487
+ testing_mode = True
488
+ except NameError:
489
+ testing_mode = False
490
+
491
+ try:
492
+ if log_file_path == '' or testing_mode:
493
+ log_file_path = os.path.join(
494
+ _config.get_config_dir(), "astropy.log")
495
+ else:
496
+ log_file_path = os.path.expanduser(log_file_path)
497
+
498
+ fh = logging.FileHandler(log_file_path)
499
+ except OSError as e:
500
+ warnings.warn(
501
+ 'log file {0!r} could not be opened for writing: '
502
+ '{1}'.format(log_file_path, str(e)), RuntimeWarning)
503
+ else:
504
+ formatter = logging.Formatter(conf.log_file_format)
505
+ fh.setFormatter(formatter)
506
+ fh.setLevel(conf.log_file_level)
507
+ self.addHandler(fh)
508
+
509
+ if conf.log_warnings:
510
+ self.enable_warnings_logging()
511
+
512
+ if conf.log_exceptions:
513
+ self.enable_exception_logging()
514
+
515
+
516
+ class StreamHandler(logging.StreamHandler):
517
+ """
518
+ A specialized StreamHandler that logs INFO and DEBUG messages to
519
+ stdout, and all other messages to stderr. Also provides coloring
520
+ of the output, if enabled in the parent logger.
521
+ """
522
+
523
+ def emit(self, record):
524
+ '''
525
+ The formatter for stderr
526
+ '''
527
+ if record.levelno <= logging.INFO:
528
+ stream = sys.stdout
529
+ else:
530
+ stream = sys.stderr
531
+
532
+ if record.levelno < logging.DEBUG or not _conf.use_color:
533
+ print(record.levelname, end='', file=stream)
534
+ else:
535
+ # Import utils.console only if necessary and at the latest because
536
+ # the import takes a significant time [#4649]
537
+ from .utils.console import color_print
538
+ if record.levelno < logging.INFO:
539
+ color_print(record.levelname, 'magenta', end='', file=stream)
540
+ elif record.levelno < logging.WARN:
541
+ color_print(record.levelname, 'green', end='', file=stream)
542
+ elif record.levelno < logging.ERROR:
543
+ color_print(record.levelname, 'brown', end='', file=stream)
544
+ else:
545
+ color_print(record.levelname, 'red', end='', file=stream)
546
+ record.message = "{0} [{1:s}]".format(record.msg, record.origin)
547
+ print(": " + record.message, file=stream)
548
+
549
+
550
+ class FilterOrigin:
551
+ '''A filter for the record origin'''
552
+
553
+ def __init__(self, origin):
554
+ self.origin = origin
555
+
556
+ def filter(self, record):
557
+ return record.origin.startswith(self.origin)
558
+
559
+
560
+ class ListHandler(logging.Handler):
561
+ '''A handler that can be used to capture the records in a list'''
562
+
563
+ def __init__(self, filter_level=None, filter_origin=None):
564
+ logging.Handler.__init__(self)
565
+ self.log_list = []
566
+
567
+ def emit(self, record):
568
+ self.log_list.append(record)
testbed/astropy__astropy/astropy/setup_package.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+
3
+ import os
4
+ import glob
5
+
6
+
7
+ def get_package_data():
8
+
9
+ # Find all files in data/ sub-directories since this is a standard location
10
+ # for data files. We then need to adjust the paths to be relative to here
11
+ # (otherwise glob will be evaluated relative to setup.py)
12
+ data_files = glob.glob('**/data/**/*', recursive=True)
13
+ data_files = [os.path.relpath(x, os.path.dirname(__file__)) for x in data_files]
14
+
15
+ # Glob doesn't recognize hidden files
16
+ data_files.append('utils/tests/data/.hidden_file.txt')
17
+
18
+ return {'astropy': ['astropy.cfg', 'CITATION'] + data_files}
testbed/astropy__astropy/astropy/timeseries/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+
3
+ """
4
+ This subpackage contains classes and functions for work with time series.
5
+ """
6
+
7
+ from astropy.timeseries.core import * # noqa
8
+ from astropy.timeseries.sampled import * # noqa
9
+ from astropy.timeseries.binned import * # noqa
10
+ from astropy.timeseries import io # noqa
11
+ from astropy.timeseries.downsample import * # noqa
12
+ from astropy.timeseries.periodograms import * # noqa
testbed/astropy__astropy/astropy/timeseries/binned.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+
3
+ from copy import deepcopy
4
+
5
+ import numpy as np
6
+
7
+ from astropy.table import groups, Table, QTable
8
+ from astropy.time import Time, TimeDelta
9
+ from astropy import units as u
10
+ from astropy.units import Quantity
11
+ from astropy.utils.misc import InheritDocstrings
12
+
13
+ from astropy.timeseries.core import BaseTimeSeries, autocheck_required_columns
14
+
15
+ __all__ = ['BinnedTimeSeries']
16
+
17
+
18
+ @autocheck_required_columns
19
+ class BinnedTimeSeries(BaseTimeSeries, metaclass=InheritDocstrings):
20
+ """
21
+ A class to represent binned time series data in tabular form.
22
+
23
+ `~astropy.timeseries.BinnedTimeSeries` provides a class for representing
24
+ time series as a collection of values of different quantities measured in
25
+ time bins (for time series with values sampled at specific times, see the
26
+ `~astropy.timeseries.TimeSeries` class).
27
+ `~astropy.timeseries.BinnedTimeSeries` is a sub-class of `~astropy.table.QTable`
28
+ and thus provides all the standard table maniplation methods available to
29
+ tables, but it also provides additional conveniences for dealing with time
30
+ series, such as a flexible initializer for setting up the times, and
31
+ attributes to access the start/center/end time of bins.
32
+
33
+ See also: http://docs.astropy.org/en/stable/timeseries/
34
+
35
+ Parameters
36
+ ----------
37
+ data : numpy ndarray, dict, list, Table, or table-like object, optional
38
+ Data to initialize time series. This does not need to contain the times,
39
+ which can be provided separately, but if it does contain the times they
40
+ should be in columns called ``'time_bin_start'`` and ``'time_bin_size'``
41
+ to be automatically recognized.
42
+ time_bin_start : `~astropy.time.Time` or iterable
43
+ The times of the start of each bin - this can be either given
44
+ directly as a `~astropy.time.Time` array or as any iterable that
45
+ initializes the `~astropy.time.Time` class. If this is given, then
46
+ the remaining time-related arguments should not be used. This can also
47
+ be a scalar value if ``time_bin_size`` is provided.
48
+ time_bin_end : `~astropy.time.Time` or iterable
49
+ The times of the end of each bin - this can be either given directly as
50
+ a `~astropy.time.Time` array or as any value or iterable that
51
+ initializes the `~astropy.time.Time` class. If this is given, then the
52
+ remaining time-related arguments should not be used. This can only be
53
+ given if ``time_bin_start`` is an array of values. If ``time_bin_end``
54
+ is a scalar, time bins are assumed to be contiguous, such that the end
55
+ of each bin is the start of the next one, and ``time_bin_end`` gives the
56
+ end time for the last bin. If ``time_bin_end`` is an array, the time
57
+ bins do not need to be contiguous. If this argument is provided,
58
+ ``time_bin_size`` should not be provided.
59
+ time_bin_size : `~astropy.time.TimeDelta` or `~astropy.units.Quantity`
60
+ The size of the time bins, either as a scalar value (in which case all
61
+ time bins will be assumed to have the same duration) or as an array of
62
+ values (in which case each time bin can have a different duration).
63
+ If this argument is provided, ``time_bin_end`` should not be provided.
64
+ n_bins : int
65
+ The number of time bins for the series. This is only used if both
66
+ ``time_bin_start`` and ``time_bin_size`` are provided and are scalar
67
+ values.
68
+ **kwargs : dict, optional
69
+ Additional keyword arguments are passed to `~astropy.table.QTable`.
70
+ """
71
+
72
+ _required_columns = ['time_bin_start', 'time_bin_size']
73
+
74
+ def __init__(self, data=None, *, time_bin_start=None, time_bin_end=None,
75
+ time_bin_size=None, n_bins=None, **kwargs):
76
+
77
+ super().__init__(data=data, **kwargs)
78
+
79
+ # For some operations, an empty time series needs to be created, then
80
+ # columns added one by one. We should check that when columns are added
81
+ # manually, time is added first and is of the right type.
82
+ if (data is None and time_bin_start is None and time_bin_end is None and
83
+ time_bin_size is None and n_bins is None):
84
+ self._required_columns_relax = True
85
+ return
86
+
87
+ # First if time_bin_start and time_bin_end have been given in the table data, we
88
+ # should extract them and treat them as if they had been passed as
89
+ # keyword arguments.
90
+
91
+ if 'time_bin_start' in self.colnames:
92
+ if time_bin_start is None:
93
+ time_bin_start = self.columns['time_bin_start']
94
+ else:
95
+ raise TypeError("'time_bin_start' has been given both in the table "
96
+ "and as a keyword argument")
97
+
98
+ if 'time_bin_size' in self.colnames:
99
+ if time_bin_size is None:
100
+ time_bin_size = self.columns['time_bin_size']
101
+ else:
102
+ raise TypeError("'time_bin_size' has been given both in the table "
103
+ "and as a keyword argument")
104
+
105
+ if time_bin_start is None:
106
+ raise TypeError("'time_bin_start' has not been specified")
107
+
108
+ if time_bin_end is None and time_bin_size is None:
109
+ raise TypeError("Either 'time_bin_size' or 'time_bin_end' should be specified")
110
+
111
+ if not isinstance(time_bin_start, Time):
112
+ time_bin_start = Time(time_bin_start)
113
+
114
+ if time_bin_end is not None and not isinstance(time_bin_end, Time):
115
+ time_bin_end = Time(time_bin_end)
116
+
117
+ if time_bin_size is not None and not isinstance(time_bin_size, (Quantity, TimeDelta)):
118
+ raise TypeError("'time_bin_size' should be a Quantity or a TimeDelta")
119
+
120
+ if isinstance(time_bin_size, TimeDelta):
121
+ time_bin_size = time_bin_size.sec * u.s
122
+
123
+ if time_bin_start.isscalar:
124
+
125
+ # We interpret this as meaning that this is the start of the
126
+ # first bin and that the bins are contiguous. In this case,
127
+ # we require time_bin_size to be specified.
128
+
129
+ if time_bin_size is None:
130
+ raise TypeError("'time_bin_start' is scalar, so 'time_bin_size' is required")
131
+
132
+ if time_bin_size.isscalar:
133
+ if data is not None:
134
+ if n_bins is not None:
135
+ if n_bins != len(self):
136
+ raise TypeError("'n_bins' has been given and it is not the "
137
+ "same length as the input data.")
138
+ else:
139
+ n_bins = len(self)
140
+
141
+ time_bin_size = np.repeat(time_bin_size, n_bins)
142
+
143
+ time_delta = np.cumsum(time_bin_size)
144
+ time_bin_end = time_bin_start + time_delta
145
+
146
+ # Now shift the array so that the first entry is 0
147
+ time_delta = np.roll(time_delta, 1)
148
+ time_delta[0] = 0. * u.s
149
+
150
+ # Make time_bin_start into an array
151
+ time_bin_start = time_bin_start + time_delta
152
+
153
+ else:
154
+
155
+ if len(self.colnames) > 0 and len(time_bin_start) != len(self):
156
+ raise ValueError("Length of 'time_bin_start' ({0}) should match "
157
+ "table length ({1})".format(len(time_bin_start), len(self)))
158
+
159
+ if time_bin_end is not None:
160
+ if time_bin_end.isscalar:
161
+ times = time_bin_start.copy()
162
+ times[:-1] = times[1:]
163
+ times[-1] = time_bin_end
164
+ time_bin_end = times
165
+ time_bin_size = (time_bin_end - time_bin_start).sec * u.s
166
+
167
+ if time_bin_size.isscalar:
168
+ time_bin_size = np.repeat(time_bin_size, len(self))
169
+
170
+ with self._delay_required_column_checks():
171
+
172
+ if 'time_bin_start' in self.colnames:
173
+ self.remove_column('time_bin_start')
174
+
175
+ if 'time_bin_size' in self.colnames:
176
+ self.remove_column('time_bin_size')
177
+
178
+ self.add_column(time_bin_start, index=0, name='time_bin_start')
179
+ self.add_index('time_bin_start')
180
+ self.add_column(time_bin_size, index=1, name='time_bin_size')
181
+
182
+ @property
183
+ def time_bin_start(self):
184
+ """
185
+ The start times of all the time bins.
186
+ """
187
+ return self['time_bin_start']
188
+
189
+ @property
190
+ def time_bin_center(self):
191
+ """
192
+ The center times of all the time bins.
193
+ """
194
+ return self['time_bin_start'] + self['time_bin_size'] * 0.5
195
+
196
+ @property
197
+ def time_bin_end(self):
198
+ """
199
+ The end times of all the time bins.
200
+ """
201
+ return self['time_bin_start'] + self['time_bin_size']
202
+
203
+ @property
204
+ def time_bin_size(self):
205
+ """
206
+ The sizes of all the time bins.
207
+ """
208
+ return self['time_bin_size']
209
+
210
+ def __getitem__(self, item):
211
+ if self._is_list_or_tuple_of_str(item):
212
+ if 'time_bin_start' not in item or 'time_bin_size' not in item:
213
+ out = QTable([self[x] for x in item],
214
+ meta=deepcopy(self.meta),
215
+ copy_indices=self._copy_indices)
216
+ out._groups = groups.TableGroups(out, indices=self.groups._indices,
217
+ keys=self.groups._keys)
218
+ return out
219
+ return super().__getitem__(item)
220
+
221
+ @classmethod
222
+ def read(self, filename, time_bin_start_column=None, time_bin_end_column=None,
223
+ time_bin_size_column=None, time_bin_size_unit=None, time_format=None, time_scale=None,
224
+ format=None, *args, **kwargs):
225
+ """
226
+ Read and parse a file and returns a `astropy.timeseries.BinnedTimeSeries`.
227
+
228
+ This method uses the unified I/O infrastructure in Astropy which makes
229
+ it easy to define readers/writers for various classes
230
+ (http://docs.astropy.org/en/stable/io/unified.html). By default, this
231
+ method will try and use readers defined specifically for the
232
+ `astropy.timeseries.BinnedTimeSeries` class - however, it is also
233
+ possible to use the ``format`` keyword to specify formats defined for
234
+ the `astropy.table.Table` class - in this case, you will need to also
235
+ provide the column names for column containing the start times for the
236
+ bins, as well as other column names (see the Parameters section below
237
+ for details)::
238
+
239
+ >>> from astropy.timeseries.binned import BinnedTimeSeries
240
+ >>> ts = BinnedTimeSeries.read('binned.dat', format='ascii.ecsv',
241
+ ... time_bin_start_column='date_start',
242
+ ... time_bin_end_column='date_end') # doctest: +SKIP
243
+
244
+ Parameters
245
+ ----------
246
+ filename : str
247
+ File to parse.
248
+ format : str
249
+ File format specifier.
250
+ time_bin_start_column : str
251
+ The name of the column with the start time for each bin.
252
+ time_bin_end_column : str, optional
253
+ The name of the column with the end time for each bin. Either this
254
+ option or ``time_bin_size_column`` should be specified.
255
+ time_bin_size_column : str, optional
256
+ The name of the column with the size for each bin. Either this
257
+ option or ``time_bin_end_column`` should be specified.
258
+ time_bin_size_unit : `astropy.units.Unit`, optional
259
+ If ``time_bin_size_column`` is specified but does not have a unit
260
+ set in the table, you can specify the unit manually.
261
+ time_format : str, optional
262
+ The time format for the start and end columns.
263
+ time_scale : str, optional
264
+ The time scale for the start and end columns.
265
+ *args : tuple, optional
266
+ Positional arguments passed through to the data reader.
267
+ **kwargs : dict, optional
268
+ Keyword arguments passed through to the data reader.
269
+
270
+ Returns
271
+ -------
272
+ out : `astropy.timeseries.binned.BinnedTimeSeries`
273
+ BinnedTimeSeries corresponding to the file.
274
+
275
+ """
276
+
277
+ try:
278
+
279
+ # First we try the readers defined for the BinnedTimeSeries class
280
+ return super().read(filename, format=format, *args, **kwargs)
281
+
282
+ except TypeError:
283
+
284
+ # Otherwise we fall back to the default Table readers
285
+
286
+ if time_bin_start_column is None:
287
+ raise ValueError("``time_bin_start_column`` should be provided since the default Table readers are being used.")
288
+ if time_bin_end_column is None and time_bin_size_column is None:
289
+ raise ValueError("Either `time_bin_end_column` or `time_bin_size_column` should be provided.")
290
+ elif time_bin_end_column is not None and time_bin_size_column is not None:
291
+ raise ValueError("Cannot specify both `time_bin_end_column` and `time_bin_size_column`.")
292
+
293
+ table = Table.read(filename, format=format, *args, **kwargs)
294
+
295
+ if time_bin_start_column in table.colnames:
296
+ time_bin_start = Time(table.columns[time_bin_start_column],
297
+ scale=time_scale, format=time_format)
298
+ table.remove_column(time_bin_start_column)
299
+ else:
300
+ raise ValueError("Bin start time column '{}' not found in the input data.".format(time_bin_start_column))
301
+
302
+ if time_bin_end_column is not None:
303
+
304
+ if time_bin_end_column in table.colnames:
305
+ time_bin_end = Time(table.columns[time_bin_end_column],
306
+ scale=time_scale, format=time_format)
307
+ table.remove_column(time_bin_end_column)
308
+ else:
309
+ raise ValueError("Bin end time column '{}' not found in the input data.".format(time_bin_end_column))
310
+
311
+ time_bin_size = None
312
+
313
+ elif time_bin_size_column is not None:
314
+
315
+ if time_bin_size_column in table.colnames:
316
+ time_bin_size = table.columns[time_bin_size_column]
317
+ table.remove_column(time_bin_size_column)
318
+ else:
319
+ raise ValueError("Bin size column '{}' not found in the input data.".format(time_bin_size_column))
320
+
321
+ if time_bin_size.unit is None:
322
+ if time_bin_size_unit is None or not isinstance(time_bin_size_unit, u.UnitBase):
323
+ raise ValueError("The bin size unit should be specified as an astropy Unit using ``time_bin_size_unit``.")
324
+ time_bin_size = time_bin_size * time_bin_size_unit
325
+ else:
326
+ time_bin_size = u.Quantity(time_bin_size)
327
+
328
+ time_bin_end = None
329
+
330
+ return BinnedTimeSeries(data=table,
331
+ time_bin_start=time_bin_start,
332
+ time_bin_end=time_bin_end,
333
+ time_bin_size=time_bin_size,
334
+ n_bins=len(table))
testbed/astropy__astropy/astropy/timeseries/core.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+
3
+ from types import FunctionType
4
+ from contextlib import contextmanager
5
+ from functools import wraps
6
+
7
+ from astropy.table import QTable
8
+
9
+ __all__ = ['BaseTimeSeries', 'autocheck_required_columns']
10
+
11
+ COLUMN_RELATED_METHODS = ['add_column',
12
+ 'add_columns',
13
+ 'keep_columns',
14
+ 'remove_column',
15
+ 'remove_columns',
16
+ 'rename_column']
17
+
18
+
19
+ def autocheck_required_columns(cls):
20
+ """
21
+ This is a decorator that ensures that the table contains specific
22
+ methods indicated by the _required_columns attribute. The aim is to
23
+ decorate all methods that might affect the columns in the table and check
24
+ for consistency after the methods have been run.
25
+ """
26
+
27
+ def decorator_method(method):
28
+
29
+ @wraps(method)
30
+ def wrapper(self, *args, **kwargs):
31
+ result = method(self, *args, **kwargs)
32
+ self._check_required_columns()
33
+ return result
34
+
35
+ return wrapper
36
+
37
+ for name in COLUMN_RELATED_METHODS:
38
+ if (not hasattr(cls, name) or
39
+ not isinstance(getattr(cls, name), FunctionType)):
40
+ raise ValueError("{0} is not a valid method".format(name))
41
+ setattr(cls, name, decorator_method(getattr(cls, name)))
42
+
43
+ return cls
44
+
45
+
46
+ class BaseTimeSeries(QTable):
47
+
48
+ _required_columns = None
49
+ _required_columns_enabled = True
50
+
51
+ # If _required_column_relax is True, we don't require the columns to be
52
+ # present but we do require them to be the correct ones IF present. Note
53
+ # that this is a temporary state - as soon as the required columns
54
+ # are all present, we toggle this to False
55
+ _required_columns_relax = False
56
+
57
+ def _check_required_columns(self):
58
+
59
+ if not self._required_columns_enabled:
60
+ return
61
+
62
+ if self._required_columns is not None:
63
+
64
+ if self._required_columns_relax:
65
+ required_columns = self._required_columns[:len(self.colnames)]
66
+ else:
67
+ required_columns = self._required_columns
68
+
69
+ plural = 's' if len(required_columns) > 1 else ''
70
+
71
+ if not self._required_columns_relax and len(self.colnames) == 0:
72
+
73
+ raise ValueError("{0} object is invalid - expected '{1}' "
74
+ "as the first column{2} but time series has no columns"
75
+ .format(self.__class__.__name__, required_columns[0], plural))
76
+
77
+ elif self.colnames[:len(required_columns)] != required_columns:
78
+
79
+ raise ValueError("{0} object is invalid - expected '{1}' "
80
+ "as the first column{2} but found '{3}'"
81
+ .format(self.__class__.__name__, required_columns[0], plural, self.colnames[0]))
82
+
83
+ if (self._required_columns_relax
84
+ and self._required_columns == self.colnames[:len(self._required_columns)]):
85
+ self._required_columns_relax = False
86
+
87
+ @contextmanager
88
+ def _delay_required_column_checks(self):
89
+ self._required_columns_enabled = False
90
+ yield
91
+ self._required_columns_enabled = True
92
+ self._check_required_columns()
testbed/astropy__astropy/astropy/timeseries/downsample.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+
3
+ import warnings
4
+
5
+ import numpy as np
6
+ from astropy import units as u
7
+ from astropy.utils.exceptions import AstropyUserWarning
8
+
9
+ from astropy.timeseries.sampled import TimeSeries
10
+ from astropy.timeseries.binned import BinnedTimeSeries
11
+
12
+ __all__ = ['aggregate_downsample']
13
+
14
+
15
+ def reduceat(array, indices, function):
16
+ """
17
+ Manual reduceat functionality for cases where Numpy functions don't have a reduceat.
18
+ It will check if the input function has a reduceat and call that if it does.
19
+ """
20
+ if hasattr(function, 'reduceat'):
21
+ return np.array(function.reduceat(array, indices))
22
+ else:
23
+ result = []
24
+ for i in range(len(indices) - 1):
25
+ if indices[i+1] <= indices[i]+1:
26
+ result.append(function(array[indices[i]]))
27
+ else:
28
+ result.append(function(array[indices[i]:indices[i+1]]))
29
+ result.append(function(array[indices[-1]:]))
30
+ return np.array(result)
31
+
32
+
33
+ def aggregate_downsample(time_series, *, time_bin_size=None, time_bin_start=None,
34
+ n_bins=None, aggregate_func=None):
35
+ """
36
+ Downsample a time series by binning values into bins with a fixed size,
37
+ using a single function to combine the values in the bin.
38
+
39
+ Parameters
40
+ ----------
41
+ time_series : :class:`~astropy.timeseries.TimeSeries`
42
+ The time series to downsample.
43
+ time_bin_size : `~astropy.units.Quantity`
44
+ The time interval for the binned time series.
45
+ time_bin_start : `~astropy.time.Time`, optional
46
+ The start time for the binned time series. Defaults to the first
47
+ time in the sampled time series.
48
+ n_bins : int, optional
49
+ The number of bins to use. Defaults to the number needed to fit all
50
+ the original points.
51
+ aggregate_func : callable, optional
52
+ The function to use for combining points in the same bin. Defaults
53
+ to np.nanmean.
54
+
55
+ Returns
56
+ -------
57
+ binned_time_series : :class:`~astropy.timeseries.BinnedTimeSeries`
58
+ The downsampled time series.
59
+ """
60
+
61
+ if not isinstance(time_series, TimeSeries):
62
+ raise TypeError("time_series should be a TimeSeries")
63
+
64
+ if not isinstance(time_bin_size, u.Quantity):
65
+ raise TypeError("time_bin_size should be a astropy.unit quantity")
66
+
67
+ bin_size_sec = time_bin_size.to_value(u.s)
68
+
69
+ # Use the table sorted by time
70
+ sorted = time_series.iloc[:]
71
+
72
+ # Determine start time if needed
73
+ if time_bin_start is None:
74
+ time_bin_start = sorted.time[0]
75
+
76
+ # Find the relative time since the start time, in seconds
77
+ relative_time_sec = (sorted.time - time_bin_start).sec
78
+
79
+ # Determine the number of bins if needed
80
+ if n_bins is None:
81
+ n_bins = int(np.ceil(relative_time_sec[-1] / bin_size_sec))
82
+
83
+ if aggregate_func is None:
84
+ aggregate_func = np.nanmean
85
+
86
+ # Determine the bins
87
+ relative_bins_sec = np.cumsum(np.hstack([0, np.repeat(bin_size_sec, n_bins)]))
88
+ bins = time_bin_start + relative_bins_sec * u.s
89
+
90
+ # Find the subset of the table that is inside the bins
91
+ keep = ((relative_time_sec >= relative_bins_sec[0]) &
92
+ (relative_time_sec < relative_bins_sec[-1]))
93
+ subset = sorted[keep]
94
+
95
+ # Figure out which bin each row falls in - the -1 is because items
96
+ # falling in the first bins will have index 1 but we want that to be 0
97
+ indices = np.searchsorted(relative_bins_sec, relative_time_sec[keep]) - 1
98
+ # Add back the first time.
99
+ indices[relative_time_sec[keep] == relative_bins_sec[0]] = 0
100
+
101
+ # Create new binned time series
102
+ binned = BinnedTimeSeries(time_bin_start=bins[:-1], time_bin_end=bins[-1])
103
+
104
+ # Determine rows where values are defined
105
+ groups = np.hstack([0, np.nonzero(np.diff(indices))[0] + 1])
106
+
107
+ # Find unique indices to determine which rows in the final time series
108
+ # will not be empty.
109
+ unique_indices = np.unique(indices)
110
+
111
+ # Add back columns
112
+
113
+ for colname in subset.colnames:
114
+
115
+ if colname == 'time':
116
+ continue
117
+
118
+ values = subset[colname]
119
+
120
+ # FIXME: figure out how to avoid the following, if possible
121
+ if not isinstance(values, (np.ndarray, u.Quantity)):
122
+ warnings.warn("Skipping column {0} since it has a mix-in type", AstropyUserWarning)
123
+ continue
124
+
125
+ if isinstance(values, u.Quantity):
126
+ data = u.Quantity(np.repeat(np.nan, n_bins), unit=values.unit)
127
+ data[unique_indices] = u.Quantity(reduceat(values.value, groups, aggregate_func),
128
+ values.unit, copy=False)
129
+ else:
130
+ data = np.ma.zeros(n_bins, dtype=values.dtype)
131
+ data.mask = 1
132
+ data[unique_indices] = reduceat(values, groups, aggregate_func)
133
+ data.mask[unique_indices] = 0
134
+
135
+ binned[colname] = data
136
+
137
+ return binned
testbed/astropy__astropy/astropy/timeseries/io/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+
3
+ from .kepler import *
testbed/astropy__astropy/astropy/timeseries/io/kepler.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+ import warnings
3
+
4
+ import numpy as np
5
+
6
+ from astropy.io import registry, fits
7
+ from astropy.table import Table
8
+ from astropy.time import Time, TimeDelta
9
+
10
+ from astropy.timeseries.sampled import TimeSeries
11
+
12
+ __all__ = ["kepler_fits_reader"]
13
+
14
+
15
+ def kepler_fits_reader(filename):
16
+ """
17
+ This serves as the FITS reader for KEPLER or TESS files within
18
+ astropy-timeseries.
19
+
20
+ This function should generally not be called directly, and instead this
21
+ time series reader should be accessed with the
22
+ :meth:`~astropy.timeseries.TimeSeries.read` method::
23
+
24
+ >>> from astropy.timeseries import TimeSeries
25
+ >>> ts = TimeSeries.read('kplr33122.fits', format='kepler.fits') # doctest: +SKIP
26
+
27
+ Parameters
28
+ ----------
29
+ filename : `str` or `pathlib.Path`
30
+ File to load.
31
+
32
+ Returns
33
+ -------
34
+ ts : `~astropy.timeseries.TimeSeries`
35
+ Data converted into a TimeSeries.
36
+ """
37
+ hdulist = fits.open(filename)
38
+ # Get the lightcurve HDU
39
+ telescope = hdulist[0].header['telescop'].lower()
40
+
41
+ if telescope == 'tess':
42
+ hdu = hdulist['LIGHTCURVE']
43
+ elif telescope == 'kepler':
44
+ hdu = hdulist[1]
45
+ else:
46
+ raise NotImplementedError("{} is not implemented, only KEPLER or TESS are "
47
+ "supported through this reader".format(hdulist[0].header['telescop']))
48
+
49
+ if hdu.header['EXTVER'] > 1:
50
+ raise NotImplementedError("Support for {0} v{1} files not yet "
51
+ "implemented".format(hdu.header['TELESCOP'], hdu.header['EXTVER']))
52
+
53
+ # Check time scale
54
+ if hdu.header['TIMESYS'] != 'TDB':
55
+ raise NotImplementedError("Support for {0} time scale not yet "
56
+ "implemented in {1} reader".format(hdu.header['TIMESYS'], hdu.header['TELESCOP']))
57
+
58
+ tab = Table.read(hdu, format='fits')
59
+
60
+ # Some KEPLER files have a T column instead of TIME.
61
+ if "T" in tab.colnames:
62
+ tab.rename_column("T", "TIME")
63
+
64
+ for colname in tab.colnames:
65
+ # Fix units
66
+ if tab[colname].unit == 'e-/s':
67
+ tab[colname].unit = 'electron/s'
68
+ if tab[colname].unit == 'pixels':
69
+ tab[colname].unit = 'pixel'
70
+
71
+ # Rename columns to lowercase
72
+ tab.rename_column(colname, colname.lower())
73
+
74
+ # Filter out NaN rows
75
+ nans = np.isnan(tab['time'].data)
76
+ if np.any(nans):
77
+ warnings.warn('Ignoring {0} rows with NaN times'.format(np.sum(nans)))
78
+ tab = tab[~nans]
79
+
80
+ # Time column is dependent on source and we correct it here
81
+ reference_date = Time(hdu.header['BJDREFI'], hdu.header['BJDREFF'],
82
+ scale=hdu.header['TIMESYS'].lower(), format='jd')
83
+ time = reference_date + TimeDelta(tab['time'].data)
84
+ time.format = 'isot'
85
+
86
+ # Remove original time column
87
+ tab.remove_column('time')
88
+
89
+ return TimeSeries(time=time, data=tab)
90
+
91
+
92
+ registry.register_reader('kepler.fits', TimeSeries, kepler_fits_reader)
93
+ registry.register_reader('tess.fits', TimeSeries, kepler_fits_reader)
testbed/astropy__astropy/astropy/timeseries/io/tests/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
testbed/astropy__astropy/astropy/timeseries/io/tests/test_kepler.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+
3
+ from unittest import mock
4
+
5
+ import pytest
6
+
7
+ from astropy.io.fits import HDUList, Header, PrimaryHDU, BinTableHDU
8
+ from astropy.utils.data import get_pkg_data_filename
9
+
10
+ from astropy.timeseries.io.kepler import kepler_fits_reader
11
+
12
+
13
+ def fake_header(extver, version, timesys, telescop):
14
+ return Header({"SIMPLE": "T",
15
+ "BITPIX": 8,
16
+ "NAXIS": 0,
17
+ "EXTVER": extver,
18
+ "VERSION": version,
19
+ 'TIMESYS': "{}".format(timesys),
20
+ "TELESCOP": "{}".format(telescop)})
21
+
22
+
23
+ def fake_hdulist(extver=1, version=2, timesys="TDB", telescop="KEPLER"):
24
+ new_header = fake_header(extver, version, timesys, telescop)
25
+ return [HDUList(hdus=[PrimaryHDU(header=new_header),
26
+ BinTableHDU(header=new_header, name="LIGHTCURVE")])]
27
+
28
+
29
+ @mock.patch("astropy.io.fits.open", side_effect=fake_hdulist(telescop="MadeUp"))
30
+ def test_raise_telescop_wrong(mock_file):
31
+ with pytest.raises(NotImplementedError) as exc:
32
+ kepler_fits_reader(None)
33
+ assert exc.value.args[0] == ("MadeUp is not implemented, only KEPLER or TESS are "
34
+ "supported through this reader")
35
+
36
+
37
+ @mock.patch("astropy.io.fits.open", side_effect=fake_hdulist(extver=2))
38
+ def test_raise_extversion_kepler(mock_file):
39
+ with pytest.raises(NotImplementedError) as exc:
40
+ kepler_fits_reader(None)
41
+ assert exc.value.args[0] == ("Support for KEPLER v2 files not yet "
42
+ "implemented")
43
+
44
+
45
+ @mock.patch("astropy.io.fits.open", side_effect=fake_hdulist(extver=2, telescop="TESS"))
46
+ def test_raise_extversion_tess(mock_file):
47
+ with pytest.raises(NotImplementedError) as exc:
48
+ kepler_fits_reader(None)
49
+ assert exc.value.args[0] == ("Support for TESS v2 files not yet "
50
+ "implemented")
51
+
52
+
53
+ @mock.patch("astropy.io.fits.open", side_effect=fake_hdulist(timesys="TCB"))
54
+ def test_raise_timesys_kepler(mock_file):
55
+ with pytest.raises(NotImplementedError) as exc:
56
+ kepler_fits_reader(None)
57
+ assert exc.value.args[0] == ("Support for TCB time scale not yet "
58
+ "implemented in KEPLER reader")
59
+
60
+
61
+ @mock.patch("astropy.io.fits.open", side_effect=fake_hdulist(timesys="TCB", telescop="TESS"))
62
+ def test_raise_timesys_tess(mock_file):
63
+ with pytest.raises(NotImplementedError) as exc:
64
+ kepler_fits_reader(None)
65
+ assert exc.value.args[0] == ("Support for TCB time scale not yet "
66
+ "implemented in TESS reader")
67
+
68
+
69
+ @pytest.mark.remote_data(source='astropy')
70
+ def test_kepler_astropy():
71
+ filename = get_pkg_data_filename('timeseries/kplr010666592-2009131110544_slc.fits')
72
+ timeseries = kepler_fits_reader(filename)
73
+ assert timeseries["time"].format == 'isot'
74
+ assert timeseries["time"].scale == 'tdb'
75
+ assert timeseries["sap_flux"].unit.to_string() == 'electron / s'
76
+ assert len(timeseries) == 14280
77
+ assert len(timeseries.columns) == 20
78
+
79
+
80
+ @pytest.mark.remote_data(source='astropy')
81
+ def test_tess_astropy():
82
+ filename = get_pkg_data_filename('timeseries/hlsp_tess-data-alerts_tess_phot_00025155310-s01_tess_v1_lc.fits')
83
+ timeseries = kepler_fits_reader(filename)
84
+ assert timeseries["time"].format == 'isot'
85
+ assert timeseries["time"].scale == 'tdb'
86
+ assert timeseries["sap_flux"].unit.to_string() == 'electron / s'
87
+ assert len(timeseries) == 19261
88
+ assert len(timeseries.columns) == 20
testbed/astropy__astropy/astropy/timeseries/periodograms/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from astropy.timeseries.periodograms.base import * # noqa
2
+ from astropy.timeseries.periodograms.lombscargle import * # noqa
3
+ from astropy.timeseries.periodograms.bls import * # noqa
testbed/astropy__astropy/astropy/timeseries/periodograms/base.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ import numpy as np
3
+ from astropy.timeseries import TimeSeries, BinnedTimeSeries
4
+
5
+ __all__ = ['BasePeriodogram']
6
+
7
+
8
+ class BasePeriodogram:
9
+
10
+ @abc.abstractmethod
11
+ def __init__(self, t, y, dy=None):
12
+ pass
13
+
14
+ @classmethod
15
+ def from_timeseries(cls, timeseries, signal_column_name=None, uncertainty=None, **kwargs):
16
+ """
17
+ Initialize a periodogram from a time series object.
18
+
19
+ If a binned time series is passed, the time at the center of the bins is
20
+ used. Also note that this method automatically gets rid of NaN/undefined
21
+ values when initalizing the periodogram.
22
+
23
+ Parameters
24
+ ----------
25
+ signal_column_name : str
26
+ The name of the column containing the signal values to use.
27
+ uncertainty : str or float or `~astropy.units.Quantity`, optional
28
+ The name of the column containing the errors on the signal, or the
29
+ value to use for the error, if a scalar.
30
+ **kwargs
31
+ Additional keyword arguments are passed to the initializer for this
32
+ periodogram class.
33
+ """
34
+
35
+ if signal_column_name is None:
36
+ raise ValueError('signal_column_name should be set to a valid column name')
37
+
38
+ y = timeseries[signal_column_name]
39
+ keep = ~np.isnan(y)
40
+
41
+ if isinstance(uncertainty, str):
42
+ dy = timeseries[uncertainty]
43
+ keep &= ~np.isnan(dy)
44
+ dy = dy[keep]
45
+ else:
46
+ dy = uncertainty
47
+
48
+ if isinstance(timeseries, TimeSeries):
49
+ time = timeseries.time
50
+ elif isinstance(timeseries, BinnedTimeSeries):
51
+ time = timeseries.time_bin_center
52
+ else:
53
+ raise TypeError('Input time series should be an instance of '
54
+ 'TimeSeries or BinnedTimeSeries')
55
+
56
+ return cls(time[keep], y[keep], dy=dy, **kwargs)
testbed/astropy__astropy/astropy/timeseries/periodograms/bls/__init__.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+
3
+ """
4
+ Box Least Squares
5
+ =================
6
+
7
+ AstroPy-compatible reference implementation of the transit periorogram used
8
+ to discover transiting exoplanets.
9
+
10
+ """
11
+
12
+ __all__ = ["BoxLeastSquares", "BoxLeastSquaresResults"]
13
+
14
+ from .core import BoxLeastSquares, BoxLeastSquaresResults
testbed/astropy__astropy/astropy/timeseries/periodograms/bls/_impl.pyx ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+ #cython: language_level=3
3
+
4
+ import numpy as np
5
+ cimport numpy as np
6
+
7
+ cimport cython
8
+
9
+ from libc.math cimport sqrt
10
+ from libc.stdlib cimport malloc, free
11
+
12
+ DTYPE = np.float64
13
+ ctypedef np.float64_t DTYPE_t
14
+
15
+ IDTYPE = np.int64
16
+ ctypedef np.int64_t IDTYPE_t
17
+
18
+ cdef extern int run_bls (
19
+ int N, # Length of the time array
20
+ double* t, # The list of timestamps
21
+ double* y, # The y measured at ``t``
22
+ double* ivar, # The inverse variance of the y array
23
+
24
+ int n_periods, #
25
+ double* periods, # The period to test in units of ``t``
26
+
27
+ int n_durations, # Length of the durations array
28
+ double* durations, # The durations to test in units of ``bin_duration``
29
+ int oversample, # The number of ``bin_duration`` bins in the maximum duration
30
+
31
+ int obj_flag, # A flag indicating the periodogram type
32
+ # 0 - depth signal-to-noise
33
+ # 1 - log likelihood
34
+
35
+ # Outputs
36
+ double* best_objective, # The value of the periodogram at maximum
37
+ double* best_depth, # The estimated depth at maximum
38
+ double* best_depth_std, # The uncertainty on ``best_depth``
39
+ double* best_duration, # The best fitting duration in units of ``t``
40
+ double* best_phase, # The phase of the mid-transit time in units of
41
+ # ``t``
42
+ double* best_depth_snr, # The signal-to-noise ratio of the depth estimate
43
+ double* best_log_like # The log likelihood at maximum
44
+ ) nogil
45
+
46
+
47
+ @cython.cdivision(True)
48
+ @cython.boundscheck(False)
49
+ @cython.wraparound(False)
50
+ def bls_impl(
51
+ np.ndarray[DTYPE_t, mode='c'] t_array,
52
+ np.ndarray[DTYPE_t, mode='c'] y_array,
53
+ np.ndarray[DTYPE_t, mode='c'] ivar_array,
54
+ np.ndarray[DTYPE_t, mode='c'] period_array,
55
+ np.ndarray[DTYPE_t, mode='c'] duration_array,
56
+ int oversample,
57
+ int obj_flag
58
+ ):
59
+
60
+ cdef np.ndarray[DTYPE_t, mode='c'] out_objective = np.empty_like(period_array, dtype=DTYPE)
61
+ cdef np.ndarray[DTYPE_t, mode='c'] out_depth = np.empty_like(period_array, dtype=DTYPE)
62
+ cdef np.ndarray[DTYPE_t, mode='c'] out_depth_err = np.empty_like(period_array, dtype=DTYPE)
63
+ cdef np.ndarray[DTYPE_t, mode='c'] out_duration = np.empty_like(period_array, dtype=DTYPE)
64
+ cdef np.ndarray[DTYPE_t, mode='c'] out_phase = np.empty_like(period_array, dtype=DTYPE)
65
+ cdef np.ndarray[DTYPE_t, mode='c'] out_depth_snr = np.empty_like(period_array, dtype=DTYPE)
66
+ cdef np.ndarray[DTYPE_t, mode='c'] out_log_like = np.empty_like(period_array, dtype=DTYPE)
67
+ cdef int flag, N = len(t_array), n_periods = len(period_array), n_durations = len(duration_array)
68
+
69
+ with nogil:
70
+ flag = run_bls(
71
+ N,
72
+ <double*>t_array.data,
73
+ <double*>y_array.data,
74
+ <double*>ivar_array.data,
75
+ n_periods,
76
+ <double*>period_array.data,
77
+ n_durations,
78
+ <double*>duration_array.data,
79
+ oversample,
80
+ obj_flag,
81
+ <double*>out_objective.data,
82
+ <double*>out_depth.data,
83
+ <double*>out_depth_err.data,
84
+ <double*>out_duration.data,
85
+ <double*>out_phase.data,
86
+ <double*>out_depth_snr.data,
87
+ <double*>out_log_like.data
88
+ )
89
+
90
+ if flag < 0:
91
+ raise MemoryError()
92
+ if flag > 0:
93
+ raise ValueError("Invalid inputs for period and/or duration")
94
+
95
+ return (out_objective, out_depth, out_depth_err, out_duration, out_phase,
96
+ out_depth_snr, out_log_like)
testbed/astropy__astropy/astropy/timeseries/periodograms/bls/bls.c ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Licensed under a 3-clause BSD style license - see LICENSE.rst */
2
+
3
+ #include <math.h>
4
+ #include <float.h>
5
+ #include <stdlib.h>
6
+
7
+ #if defined(_OPENMP)
8
+ #include <omp.h>
9
+ #endif
10
+
11
+ #ifndef INFINITY
12
+ #define INFINITY (1.0 / 0.0)
13
+ #endif
14
+
15
+ void compute_objective(
16
+ double y_in,
17
+ double y_out,
18
+ double ivar_in,
19
+ double ivar_out,
20
+ int obj_flag,
21
+ double* objective,
22
+ double* log_likelihood,
23
+ double* depth,
24
+ double* depth_err,
25
+ double* depth_snr
26
+ ) {
27
+ if (obj_flag) {
28
+ double arg = y_out - y_in;
29
+ *log_likelihood = 0.5*ivar_in*arg*arg;
30
+ *objective = *log_likelihood;
31
+ } else {
32
+ *depth = y_out - y_in;
33
+ *depth_err = sqrt(1.0 / ivar_in + 1.0 / ivar_out);
34
+ *depth_snr = *depth / *depth_err;
35
+ *objective = *depth_snr;
36
+ }
37
+ }
38
+
39
+ inline double wrap_into (double x, double period)
40
+ {
41
+ return x - period * floor(x / period);
42
+ }
43
+
44
+ int run_bls (
45
+ // Inputs
46
+ int N, // Length of the time array
47
+ double* t, // The list of timestamps
48
+ double* y, // The y measured at ``t``
49
+ double* ivar, // The inverse variance of the y array
50
+
51
+ int n_periods,
52
+ double* periods, // The period to test in units of ``t``
53
+
54
+ int n_durations, // Length of the durations array
55
+ double* durations, // The durations to test in units of ``bin_duration``
56
+ int oversample, // The number of ``bin_duration`` bins in the maximum duration
57
+
58
+ int obj_flag, // A flag indicating the periodogram type
59
+ // 0 - depth signal-to-noise
60
+ // 1 - log likelihood
61
+
62
+ // Outputs
63
+ double* best_objective, // The value of the periodogram at maximum
64
+ double* best_depth, // The estimated depth at maximum
65
+ double* best_depth_err, // The uncertainty on ``best_depth``
66
+ double* best_duration, // The best fitting duration in units of ``t``
67
+ double* best_phase, // The phase of the mid-transit time in units of
68
+ // ``t``
69
+ double* best_depth_snr, // The signal-to-noise ratio of the depth estimate
70
+ double* best_log_like // The log likelihood at maximum
71
+ ) {
72
+ // Start by finding the period and duration ranges
73
+ double max_period = periods[0], min_period = periods[0];
74
+ int k;
75
+ for (k = 1; k < n_periods; ++k) {
76
+ if (periods[k] < min_period) min_period = periods[k];
77
+ if (periods[k] > max_period) max_period = periods[k];
78
+ }
79
+ if (min_period < DBL_EPSILON) return 1;
80
+ double min_duration = durations[0], max_duration = durations[0];
81
+ for (k = 1; k < n_durations; ++k) {
82
+ if (durations[k] < min_duration) min_duration = durations[k];
83
+ if (durations[k] > max_duration) max_duration = durations[k];
84
+ }
85
+ if ((max_duration > min_period) || (min_duration < DBL_EPSILON)) return 2;
86
+
87
+ // Compute the durations in terms of bin_duration
88
+ double bin_duration = min_duration / ((double)oversample);
89
+ int max_n_bins = (int)(ceil(max_period / bin_duration)) + oversample;
90
+
91
+ int nthreads, blocksize = max_n_bins+1;
92
+ #pragma omp parallel
93
+ {
94
+ #if defined(_OPENMP)
95
+ nthreads = omp_get_num_threads();
96
+ #else
97
+ nthreads = 1;
98
+ #endif
99
+ }
100
+
101
+ // Allocate the work arrays
102
+ double* mean_y_0 = (double*)malloc(nthreads*blocksize*sizeof(double));
103
+ if (mean_y_0 == NULL) {
104
+ return -2;
105
+ }
106
+ double* mean_ivar_0 = (double*)malloc(nthreads*blocksize*sizeof(double));
107
+ if (mean_ivar_0 == NULL) {
108
+ free(mean_y_0);
109
+ return -3;
110
+ }
111
+
112
+ // Pre-accumulate some factors.
113
+ double min_t = INFINITY;
114
+ double sum_y = 0.0, sum_ivar = 0.0;
115
+ int i;
116
+ #pragma omp parallel for reduction(+:sum_y), reduction(+:sum_ivar)
117
+ for (i = 0; i < N; ++i) {
118
+ min_t = fmin(min_t, t[i]);
119
+ sum_y += y[i] * ivar[i];
120
+ sum_ivar += ivar[i];
121
+ }
122
+
123
+ // Loop over periods and do the search
124
+ int p;
125
+ #pragma omp parallel for
126
+ for (p = 0; p < n_periods; ++p) {
127
+ #if defined(_OPENMP)
128
+ int ithread = omp_get_thread_num();
129
+ #else
130
+ int ithread = 0;
131
+ #endif
132
+ int block = blocksize * ithread;
133
+ double period = periods[p];
134
+ int n_bins = (int)(ceil(period / bin_duration)) + oversample;
135
+
136
+ double* mean_y = mean_y_0 + block;
137
+ double* mean_ivar = mean_ivar_0 + block;
138
+
139
+ // This first pass bins the data into a fine-grain grid in phase from zero
140
+ // to period and computes the weighted sum and inverse variance for each
141
+ // bin.
142
+ int n, ind;
143
+ for (n = 0; n < n_bins+1; ++n) {
144
+ mean_y[n] = 0.0;
145
+ mean_ivar[n] = 0.0;
146
+ }
147
+ for (n = 0; n < N; ++n) {
148
+ int ind = (int)(wrap_into(t[n] - min_t, period) / bin_duration) + 1;
149
+ mean_y[ind] += y[n] * ivar[n];
150
+ mean_ivar[ind] += ivar[n];
151
+ }
152
+
153
+ // To simplify calculations below, we wrap the binned values around and pad
154
+ // the end of the array with the first ``oversample`` samples.
155
+ for (n = 1, ind = n_bins - oversample; n <= oversample; ++n, ++ind) {
156
+ mean_y[ind] = mean_y[n];
157
+ mean_ivar[ind] = mean_ivar[n];
158
+ }
159
+
160
+ // To compute the estimates of the in-transit flux, we need the sum of
161
+ // mean_y and mean_ivar over a given set of transit points. To get this
162
+ // fast, we can compute the cumulative sum and then use differences between
163
+ // points separated by ``duration`` bins. Here we convert the mean arrays
164
+ // to cumulative sums.
165
+ for (n = 1; n <= n_bins; ++n) {
166
+ mean_y[n] += mean_y[n-1];
167
+ mean_ivar[n] += mean_ivar[n-1];
168
+ }
169
+
170
+ // Then we loop over phases (in steps of n_bin) and durations and find the
171
+ // best fit value. By looping over durations here, we get to reuse a lot of
172
+ // the computations that we did above.
173
+ double objective, log_like, depth, depth_err, depth_snr;
174
+ best_objective[p] = -INFINITY;
175
+ int k;
176
+ for (k = 0; k < n_durations; ++k) {
177
+ int dur = (int)(round(durations[k] / bin_duration));
178
+ int n_max = n_bins-dur;
179
+ for (n = 0; n <= n_max; ++n) {
180
+ // Estimate the in-transit and out-of-transit flux
181
+ double y_in = mean_y[n+dur] - mean_y[n];
182
+ double ivar_in = mean_ivar[n+dur] - mean_ivar[n];
183
+ double y_out = sum_y - y_in;
184
+ double ivar_out = sum_ivar - ivar_in;
185
+
186
+ // Skip this model if there are no points in transit
187
+ if ((ivar_in < DBL_EPSILON) || (ivar_out < DBL_EPSILON)) {
188
+ continue;
189
+ }
190
+
191
+ // Normalize to compute the actual value of the flux
192
+ y_in /= ivar_in;
193
+ y_out /= ivar_out;
194
+
195
+ // Either compute the log likelihood or the signal-to-noise
196
+ // ratio
197
+ compute_objective(y_in, y_out, ivar_in, ivar_out, obj_flag,
198
+ &objective, &log_like, &depth, &depth_err, &depth_snr);
199
+
200
+ // If this is the best result seen so far, keep it
201
+ if (y_out >= y_in && objective > best_objective[p]) {
202
+ best_objective[p] = objective;
203
+
204
+ // Compute the other parameters
205
+ compute_objective(y_in, y_out, ivar_in, ivar_out, (obj_flag == 0),
206
+ &objective, &log_like, &depth, &depth_err, &depth_snr);
207
+
208
+ best_depth[p] = depth;
209
+ best_depth_err[p] = depth_err;
210
+ best_depth_snr[p] = depth_snr;
211
+ best_log_like[p] = log_like;
212
+ best_duration[p] = dur * bin_duration;
213
+ best_phase[p] = fmod(n*bin_duration + 0.5*best_duration[p] + min_t, period);
214
+ }
215
+ }
216
+ }
217
+ }
218
+
219
+ // Clean up
220
+ free(mean_y_0);
221
+ free(mean_ivar_0);
222
+
223
+ return 0;
224
+ }
testbed/astropy__astropy/astropy/timeseries/periodograms/bls/core.py ADDED
@@ -0,0 +1,817 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
3
+
4
+ __all__ = ["BoxLeastSquares", "BoxLeastSquaresResults"]
5
+
6
+ import numpy as np
7
+
8
+ from astropy import units
9
+ from astropy.time import Time, TimeDelta
10
+ from astropy.timeseries.periodograms.lombscargle.core import has_units, strip_units
11
+ from astropy import units as u
12
+ from . import methods
13
+ from astropy.timeseries.periodograms.base import BasePeriodogram
14
+
15
+
16
+ def validate_unit_consistency(reference_object, input_object):
17
+ if has_units(reference_object):
18
+ input_object = units.Quantity(input_object, unit=reference_object.unit)
19
+ else:
20
+ if has_units(input_object):
21
+ input_object = units.Quantity(input_object, unit=units.one)
22
+ input_object = input_object.value
23
+ return input_object
24
+
25
+
26
+ class BoxLeastSquares(BasePeriodogram):
27
+ """Compute the box least squares periodogram
28
+
29
+ This method is a commonly used tool for discovering transiting exoplanets
30
+ or eclipsing binaries in photometric time series datasets. This
31
+ implementation is based on the "box least squares (BLS)" method described
32
+ in [1]_ and [2]_.
33
+
34
+ Parameters
35
+ ----------
36
+ t : array-like, `~astropy.units.Quantity`, `~astropy.time.Time`, or `~astropy.time.TimeDelta`
37
+ Sequence of observation times.
38
+ y : array-like or `~astropy.units.Quantity`
39
+ Sequence of observations associated with times ``t``.
40
+ dy : float, array-like or `~astropy.units.Quantity`, optional
41
+ Error or sequence of observational errors associated with times ``t``.
42
+
43
+ Examples
44
+ --------
45
+ Generate noisy data with a transit:
46
+
47
+ >>> rand = np.random.RandomState(42)
48
+ >>> t = rand.uniform(0, 10, 500)
49
+ >>> y = np.ones_like(t)
50
+ >>> y[np.abs((t + 1.0)%2.0-1)<0.08] = 1.0 - 0.1
51
+ >>> y += 0.01 * rand.randn(len(t))
52
+
53
+ Compute the transit periodogram on a heuristically determined period grid
54
+ and find the period with maximum power:
55
+
56
+ >>> model = BoxLeastSquares(t, y)
57
+ >>> results = model.autopower(0.16)
58
+ >>> results.period[np.argmax(results.power)] # doctest: +FLOAT_CMP
59
+ 1.9923406038842544
60
+
61
+ Compute the periodogram on a user-specified period grid:
62
+
63
+ >>> periods = np.linspace(1.9, 2.1, 5)
64
+ >>> results = model.power(periods, 0.16)
65
+ >>> results.power # doctest: +FLOAT_CMP
66
+ array([0.01421067, 0.02842475, 0.10867671, 0.05117755, 0.01783253])
67
+
68
+ If the inputs are AstroPy Quantities with units, the units will be
69
+ validated and the outputs will also be Quantities with appropriate units:
70
+
71
+ >>> from astropy import units as u
72
+ >>> t = t * u.day
73
+ >>> y = y * u.dimensionless_unscaled
74
+ >>> model = BoxLeastSquares(t, y)
75
+ >>> results = model.autopower(0.16 * u.day)
76
+ >>> results.period.unit
77
+ Unit("d")
78
+ >>> results.power.unit
79
+ Unit(dimensionless)
80
+
81
+ References
82
+ ----------
83
+ .. [1] Kovacs, Zucker, & Mazeh (2002), A&A, 391, 369
84
+ (arXiv:astro-ph/0206099)
85
+ .. [2] Hartman & Bakos (2016), Astronomy & Computing, 17, 1
86
+ (arXiv:1605.06811)
87
+
88
+ """
89
+
90
+ def __init__(self, t, y, dy=None):
91
+
92
+ # If t is a TimeDelta, convert it to a quantity. The units we convert
93
+ # to don't really matter since the user gets a Quantity back at the end
94
+ # so can convert to any units they like.
95
+ if isinstance(t, TimeDelta):
96
+ t = t.to('day')
97
+
98
+ # We want to expose self.t as being the times the user passed in, but
99
+ # if the times are absolute, we need to convert them to relative times
100
+ # internally, so we use self._trel and self._tstart for this.
101
+
102
+ self.t = t
103
+
104
+ if isinstance(self.t, Time):
105
+ self._tstart = self.t[0]
106
+ trel = (self.t - self._tstart).to(u.day)
107
+ else:
108
+ self._tstart = None
109
+ trel = self.t
110
+
111
+ self._trel, self.y, self.dy = self._validate_inputs(trel, y, dy)
112
+
113
+ def autoperiod(self, duration,
114
+ minimum_period=None, maximum_period=None,
115
+ minimum_n_transit=3, frequency_factor=1.0):
116
+ """Determine a suitable grid of periods
117
+
118
+ This method uses a set of heuristics to select a conservative period
119
+ grid that is uniform in frequency. This grid might be too fine for
120
+ some user's needs depending on the precision requirements or the
121
+ sampling of the data. The grid can be made coarser by increasing
122
+ ``frequency_factor``.
123
+
124
+ Parameters
125
+ ----------
126
+ duration : float, array-like or `~astropy.units.Quantity`
127
+ The set of durations that will be considered.
128
+ minimum_period, maximum_period : float or `~astropy.units.Quantity`, optional
129
+ The minimum/maximum periods to search. If not provided, these will
130
+ be computed as described in the notes below.
131
+ minimum_n_transits : int, optional
132
+ If ``maximum_period`` is not provided, this is used to compute the
133
+ maximum period to search by asserting that any systems with at
134
+ least ``minimum_n_transits`` will be within the range of searched
135
+ periods. Note that this is not the same as requiring that
136
+ ``minimum_n_transits`` be required for detection. The default
137
+ value is ``3``.
138
+ frequency_factor : float, optional
139
+ A factor to control the frequency spacing as described in the
140
+ notes below. The default value is ``1.0``.
141
+
142
+ Returns
143
+ -------
144
+ period : array-like or `~astropy.units.Quantity`
145
+ The set of periods computed using these heuristics with the same
146
+ units as ``t``.
147
+
148
+ Notes
149
+ -----
150
+ The default minimum period is chosen to be twice the maximum duration
151
+ because there won't be much sensitivity to periods shorter than that.
152
+
153
+ The default maximum period is computed as
154
+
155
+ .. code-block:: python
156
+
157
+ maximum_period = (max(t) - min(t)) / minimum_n_transits
158
+
159
+ ensuring that any systems with at least ``minimum_n_transits`` are
160
+ within the range of searched periods.
161
+
162
+ The frequency spacing is given by
163
+
164
+ .. code-block:: python
165
+
166
+ df = frequency_factor * min(duration) / (max(t) - min(t))**2
167
+
168
+ so the grid can be made finer by decreasing ``frequency_factor`` or
169
+ coarser by increasing ``frequency_factor``.
170
+
171
+ """
172
+
173
+ duration = self._validate_duration(duration)
174
+ baseline = strip_units((self._trel.max() - self._trel.min()))
175
+ min_duration = strip_units(np.min(duration))
176
+
177
+ # Estimate the required frequency spacing
178
+ # Because of the sparsity of a transit, this must be much finer than
179
+ # the frequency resolution for a sinusoidal fit. For a sinusoidal fit,
180
+ # df would be 1/baseline (see LombScargle), but here this should be
181
+ # scaled proportionally to the duration in units of baseline.
182
+ df = frequency_factor * min_duration / baseline**2
183
+
184
+ # If a minimum period is not provided, choose one that is twice the
185
+ # maximum duration because we won't be sensitive to any periods
186
+ # shorter than that.
187
+ if minimum_period is None:
188
+ minimum_period = 2.0 * strip_units(np.max(duration))
189
+ else:
190
+ minimum_period = validate_unit_consistency(self._trel, minimum_period)
191
+ minimum_period = strip_units(minimum_period)
192
+
193
+ # If no maximum period is provided, choose one by requiring that
194
+ # all signals with at least minimum_n_transit should be detectable.
195
+ if maximum_period is None:
196
+ if minimum_n_transit <= 1:
197
+ raise ValueError("minimum_n_transit must be greater than 1")
198
+ maximum_period = baseline / (minimum_n_transit-1)
199
+ else:
200
+ maximum_period = validate_unit_consistency(self._trel, maximum_period)
201
+ maximum_period = strip_units(maximum_period)
202
+
203
+ if maximum_period < minimum_period:
204
+ minimum_period, maximum_period = maximum_period, minimum_period
205
+ if minimum_period <= 0.0:
206
+ raise ValueError("minimum_period must be positive")
207
+
208
+ # Convert bounds to frequency
209
+ minimum_frequency = 1.0/strip_units(maximum_period)
210
+ maximum_frequency = 1.0/strip_units(minimum_period)
211
+
212
+ # Compute the number of frequencies and the frequency grid
213
+ nf = 1 + int(np.round((maximum_frequency - minimum_frequency)/df))
214
+ return 1.0/(maximum_frequency-df*np.arange(nf)) * self._t_unit()
215
+
216
+ def autopower(self, duration, objective=None, method=None, oversample=10,
217
+ minimum_n_transit=3, minimum_period=None,
218
+ maximum_period=None, frequency_factor=1.0):
219
+ """Compute the periodogram at set of heuristically determined periods
220
+
221
+ This method calls :func:`BoxLeastSquares.autoperiod` to determine
222
+ the period grid and then :func:`BoxLeastSquares.power` to compute
223
+ the periodogram. See those methods for documentation of the arguments.
224
+
225
+ """
226
+ period = self.autoperiod(duration,
227
+ minimum_n_transit=minimum_n_transit,
228
+ minimum_period=minimum_period,
229
+ maximum_period=maximum_period,
230
+ frequency_factor=frequency_factor)
231
+ return self.power(period, duration, objective=objective, method=method,
232
+ oversample=oversample)
233
+
234
+ def power(self, period, duration, objective=None, method=None,
235
+ oversample=10):
236
+ """Compute the periodogram for a set of periods
237
+
238
+ Parameters
239
+ ----------
240
+ period : array-like or `~astropy.units.Quantity`
241
+ The periods where the power should be computed
242
+ duration : float, array-like or `~astropy.units.Quantity`
243
+ The set of durations to test
244
+ objective : {'likelihood', 'snr'}, optional
245
+ The scalar that should be optimized to find the best fit phase,
246
+ duration, and depth. This can be either ``'likelihood'`` (default)
247
+ to optimize the log-likelihood of the model, or ``'snr'`` to
248
+ optimize the signal-to-noise with which the transit depth is
249
+ measured.
250
+ method : {'fast', 'slow'}, optional
251
+ The computational method used to compute the periodogram. This is
252
+ mainly included for the purposes of testing and most users will
253
+ want to use the optimized ``'fast'`` method (default) that is
254
+ implemented in Cython. ``'slow'`` is a brute-force method that is
255
+ used to test the results of the ``'fast'`` method.
256
+ oversample : int, optional
257
+ The number of bins per duration that should be used. This sets the
258
+ time resolution of the phase fit with larger values of
259
+ ``oversample`` yielding a finer grid and higher computational cost.
260
+
261
+ Returns
262
+ -------
263
+ results : BoxLeastSquaresResults
264
+ The periodogram results as a :class:`BoxLeastSquaresResults`
265
+ object.
266
+
267
+ Raises
268
+ ------
269
+ ValueError
270
+ If ``oversample`` is not an integer greater than 0 or if
271
+ ``objective`` or ``method`` are not valid.
272
+
273
+ """
274
+ period, duration = self._validate_period_and_duration(period, duration)
275
+
276
+ # Check for absurdities in the ``oversample`` choice
277
+ try:
278
+ oversample = int(oversample)
279
+ except TypeError:
280
+ raise ValueError("oversample must be an int, got {0}"
281
+ .format(oversample))
282
+ if oversample < 1:
283
+ raise ValueError("oversample must be greater than or equal to 1")
284
+
285
+ # Select the periodogram objective
286
+ if objective is None:
287
+ objective = "likelihood"
288
+ allowed_objectives = ["snr", "likelihood"]
289
+ if objective not in allowed_objectives:
290
+ raise ValueError(("Unrecognized method '{0}'\n"
291
+ "allowed methods are: {1}")
292
+ .format(objective, allowed_objectives))
293
+ use_likelihood = (objective == "likelihood")
294
+
295
+ # Select the computational method
296
+ if method is None:
297
+ method = "fast"
298
+ allowed_methods = ["fast", "slow"]
299
+ if method not in allowed_methods:
300
+ raise ValueError(("Unrecognized method '{0}'\n"
301
+ "allowed methods are: {1}")
302
+ .format(method, allowed_methods))
303
+
304
+ # Format and check the input arrays
305
+ t = np.ascontiguousarray(strip_units(self._trel), dtype=np.float64)
306
+ y = np.ascontiguousarray(strip_units(self.y), dtype=np.float64)
307
+ if self.dy is None:
308
+ ivar = np.ones_like(y)
309
+ else:
310
+ ivar = 1.0 / np.ascontiguousarray(strip_units(self.dy),
311
+ dtype=np.float64)**2
312
+
313
+ # Make sure that the period and duration arrays are C-order
314
+ period_fmt = np.ascontiguousarray(strip_units(period),
315
+ dtype=np.float64)
316
+ duration = np.ascontiguousarray(strip_units(duration),
317
+ dtype=np.float64)
318
+
319
+ # Select the correct implementation for the chosen method
320
+ if method == "fast":
321
+ bls = methods.bls_fast
322
+ else:
323
+ bls = methods.bls_slow
324
+
325
+ # Run the implementation
326
+ results = bls(
327
+ t, y - np.median(y), ivar, period_fmt, duration,
328
+ oversample, use_likelihood)
329
+
330
+ return self._format_results(objective, period, results)
331
+
332
+ def _as_relative_time(self, name, times):
333
+ """
334
+ Convert the provided times (if absolute) to relative times using the
335
+ current _tstart value. If the times provided are relative, they are
336
+ returned without conversion (though we still do some checks).
337
+ """
338
+
339
+ if isinstance(times, TimeDelta):
340
+ times = times.to('day')
341
+
342
+ if self._tstart is None:
343
+ if isinstance(times, Time):
344
+ raise TypeError('{0} was provided as an absolute time but '
345
+ 'the BoxLeastSquares class was initialized '
346
+ 'with relative times.'.format(name))
347
+ else:
348
+ if isinstance(times, Time):
349
+ times = (times - self._tstart).to(u.day)
350
+ else:
351
+ raise TypeError('{0} was provided as a relative time but '
352
+ 'the BoxLeastSquares class was initialized '
353
+ 'with absolute times.'.format(name))
354
+
355
+ times = validate_unit_consistency(self._trel, times)
356
+
357
+ return times
358
+
359
+ def _as_absolute_time_if_needed(self, name, times):
360
+ """
361
+ Convert the provided times to absolute times using the current _tstart
362
+ value, if needed.
363
+ """
364
+ if self._tstart is not None:
365
+ # Some time formats/scales can't represent dates/times too far
366
+ # off from the present, so we need to mask values offset by
367
+ # more than 100,000 yr (the periodogram algorithm can return
368
+ # transit times of e.g 1e300 for some periods).
369
+ reset = np.abs(times.to_value(u.year)) > 100000
370
+ times[reset] = 0
371
+ times = self._tstart + times
372
+ times[reset] = np.nan
373
+ return times
374
+
375
+ def model(self, t_model, period, duration, transit_time):
376
+ """Compute the transit model at the given period, duration, and phase
377
+
378
+ Parameters
379
+ ----------
380
+ t_model : array-like or `~astropy.units.Quantity` or `~astropy.time.Time`
381
+ Times at which to compute the model.
382
+ period : float or `~astropy.units.Quantity`
383
+ The period of the transits.
384
+ duration : float or `~astropy.units.Quantity`
385
+ The duration of the transit.
386
+ transit_time : float or `~astropy.units.Quantity` or `~astropy.time.Time`
387
+ The mid-transit time of a reference transit.
388
+
389
+ Returns
390
+ -------
391
+ y_model : array-like or `~astropy.units.Quantity`
392
+ The model evaluated at the times ``t_model`` with units of ``y``.
393
+
394
+ """
395
+
396
+ period, duration = self._validate_period_and_duration(period, duration)
397
+
398
+ transit_time = self._as_relative_time('transit_time', transit_time)
399
+ t_model = strip_units(self._as_relative_time('t_model', t_model))
400
+
401
+ period = float(strip_units(period))
402
+ duration = float(strip_units(duration))
403
+ transit_time = float(strip_units(transit_time))
404
+
405
+ t = np.ascontiguousarray(strip_units(self._trel), dtype=np.float64)
406
+ y = np.ascontiguousarray(strip_units(self.y), dtype=np.float64)
407
+ if self.dy is None:
408
+ ivar = np.ones_like(y)
409
+ else:
410
+ ivar = 1.0 / np.ascontiguousarray(strip_units(self.dy),
411
+ dtype=np.float64)**2
412
+
413
+ # Compute the depth
414
+ hp = 0.5*period
415
+ m_in = np.abs((t-transit_time+hp) % period - hp) < 0.5*duration
416
+ m_out = ~m_in
417
+ y_in = np.sum(y[m_in] * ivar[m_in]) / np.sum(ivar[m_in])
418
+ y_out = np.sum(y[m_out] * ivar[m_out]) / np.sum(ivar[m_out])
419
+
420
+ # Evaluate the model
421
+ y_model = y_out + np.zeros_like(t_model)
422
+ m_model = np.abs((t_model-transit_time+hp) % period-hp) < 0.5*duration
423
+ y_model[m_model] = y_in
424
+
425
+ return y_model * self._y_unit()
426
+
427
+ def compute_stats(self, period, duration, transit_time):
428
+ """Compute descriptive statistics for a given transit model
429
+
430
+ These statistics are commonly used for vetting of transit candidates.
431
+
432
+ Parameters
433
+ ----------
434
+ period : float or `~astropy.units.Quantity`
435
+ The period of the transits.
436
+ duration : float or `~astropy.units.Quantity`
437
+ The duration of the transit.
438
+ transit_time : float or `~astropy.units.Quantity` or `~astropy.time.Time`
439
+ The mid-transit time of a reference transit.
440
+
441
+ Returns
442
+ -------
443
+ stats : dict
444
+ A dictionary containing several descriptive statistics:
445
+
446
+ - ``depth``: The depth and uncertainty (as a tuple with two
447
+ values) on the depth for the fiducial model.
448
+ - ``depth_odd``: The depth and uncertainty on the depth for a
449
+ model where the period is twice the fiducial period.
450
+ - ``depth_even``: The depth and uncertainty on the depth for a
451
+ model where the period is twice the fiducial period and the
452
+ phase is offset by one orbital period.
453
+ - ``depth_half``: The depth and uncertainty for a model with a
454
+ period of half the fiducial period.
455
+ - ``depth_phased``: The depth and uncertainty for a model with the
456
+ fiducial period and the phase offset by half a period.
457
+ - ``harmonic_amplitude``: The amplitude of the best fit sinusoidal
458
+ model.
459
+ - ``harmonic_delta_log_likelihood``: The difference in log
460
+ likelihood between a sinusoidal model and the transit model.
461
+ If ``harmonic_delta_log_likelihood`` is greater than zero, the
462
+ sinusoidal model is preferred.
463
+ - ``transit_times``: The mid-transit time for each transit in the
464
+ baseline.
465
+ - ``per_transit_count``: An array with a count of the number of
466
+ data points in each unique transit included in the baseline.
467
+ - ``per_transit_log_likelihood``: An array with the value of the
468
+ log likelihood for each unique transit included in the
469
+ baseline.
470
+
471
+ """
472
+
473
+ period, duration = self._validate_period_and_duration(period, duration)
474
+ transit_time = self._as_relative_time('transit_time', transit_time)
475
+
476
+ period = float(strip_units(period))
477
+ duration = float(strip_units(duration))
478
+ transit_time = float(strip_units(transit_time))
479
+
480
+ t = np.ascontiguousarray(strip_units(self._trel), dtype=np.float64)
481
+ y = np.ascontiguousarray(strip_units(self.y), dtype=np.float64)
482
+ if self.dy is None:
483
+ ivar = np.ones_like(y)
484
+ else:
485
+ ivar = 1.0 / np.ascontiguousarray(strip_units(self.dy),
486
+ dtype=np.float64)**2
487
+
488
+ # This a helper function that will compute the depth for several
489
+ # different hypothesized transit models with different parameters
490
+ def _compute_depth(m, y_out=None, var_out=None):
491
+ if np.any(m) and (var_out is None or np.isfinite(var_out)):
492
+ var_m = 1.0 / np.sum(ivar[m])
493
+ y_m = np.sum(y[m] * ivar[m]) * var_m
494
+ if y_out is None:
495
+ return y_m, var_m
496
+ return y_out - y_m, np.sqrt(var_m + var_out)
497
+ return 0.0, np.inf
498
+
499
+ # Compute the depth of the fiducial model and the two models at twice
500
+ # the period
501
+ hp = 0.5*period
502
+ m_in = np.abs((t-transit_time+hp) % period - hp) < 0.5*duration
503
+ m_out = ~m_in
504
+ m_odd = np.abs((t-transit_time) % (2*period) - period) \
505
+ < 0.5*duration
506
+ m_even = np.abs((t-transit_time+period) % (2*period) - period) \
507
+ < 0.5*duration
508
+
509
+ y_out, var_out = _compute_depth(m_out)
510
+ depth = _compute_depth(m_in, y_out, var_out)
511
+ depth_odd = _compute_depth(m_odd, y_out, var_out)
512
+ depth_even = _compute_depth(m_even, y_out, var_out)
513
+ y_in = y_out - depth[0]
514
+
515
+ # Compute the depth of the model at a phase of 0.5*period
516
+ m_phase = np.abs((t-transit_time) % period - hp) < 0.5*duration
517
+ depth_phase = _compute_depth(m_phase,
518
+ *_compute_depth((~m_phase) & m_out))
519
+
520
+ # Compute the depth of a model with a period of 0.5*period
521
+ m_half = np.abs((t-transit_time+0.25*period) % (0.5*period)
522
+ - 0.25*period) < 0.5*duration
523
+ depth_half = _compute_depth(m_half, *_compute_depth(~m_half))
524
+
525
+ # Compute the number of points in each transit
526
+ transit_id = np.round((t[m_in]-transit_time) / period).astype(int)
527
+ transit_times = period * np.arange(transit_id.min(),
528
+ transit_id.max()+1) + transit_time
529
+ unique_ids, unique_counts = np.unique(transit_id,
530
+ return_counts=True)
531
+ unique_ids -= np.min(transit_id)
532
+ transit_id -= np.min(transit_id)
533
+ counts = np.zeros(np.max(transit_id) + 1, dtype=int)
534
+ counts[unique_ids] = unique_counts
535
+
536
+ # Compute the per-transit log likelihood
537
+ ll = -0.5 * ivar[m_in] * ((y[m_in] - y_in)**2 - (y[m_in] - y_out)**2)
538
+ lls = np.zeros(len(counts))
539
+ for i in unique_ids:
540
+ lls[i] = np.sum(ll[transit_id == i])
541
+ full_ll = -0.5*np.sum(ivar[m_in] * (y[m_in] - y_in)**2)
542
+ full_ll -= 0.5*np.sum(ivar[m_out] * (y[m_out] - y_out)**2)
543
+
544
+ # Compute the log likelihood of a sine model
545
+ A = np.vstack((
546
+ np.sin(2*np.pi*t/period), np.cos(2*np.pi*t/period),
547
+ np.ones_like(t)
548
+ )).T
549
+ w = np.linalg.solve(np.dot(A.T, A * ivar[:, None]),
550
+ np.dot(A.T, y * ivar))
551
+ mod = np.dot(A, w)
552
+ sin_ll = -0.5*np.sum((y-mod)**2*ivar)
553
+
554
+ # Format the results
555
+ y_unit = self._y_unit()
556
+ ll_unit = 1
557
+ if self.dy is None:
558
+ ll_unit = y_unit * y_unit
559
+ return dict(
560
+ transit_times=self._as_absolute_time_if_needed('transit_times', transit_times * self._t_unit()),
561
+ per_transit_count=counts,
562
+ per_transit_log_likelihood=lls * ll_unit,
563
+ depth=(depth[0] * y_unit, depth[1] * y_unit),
564
+ depth_phased=(depth_phase[0] * y_unit, depth_phase[1] * y_unit),
565
+ depth_half=(depth_half[0] * y_unit, depth_half[1] * y_unit),
566
+ depth_odd=(depth_odd[0] * y_unit, depth_odd[1] * y_unit),
567
+ depth_even=(depth_even[0] * y_unit, depth_even[1] * y_unit),
568
+ harmonic_amplitude=np.sqrt(np.sum(w[:2]**2)) * y_unit,
569
+ harmonic_delta_log_likelihood=(sin_ll - full_ll) * ll_unit,
570
+ )
571
+
572
+ def transit_mask(self, t, period, duration, transit_time):
573
+ """Compute which data points are in transit for a given parameter set
574
+
575
+ Parameters
576
+ ----------
577
+ t_model : array-like or `~astropy.units.Quantity`
578
+ Times where the mask should be evaluated.
579
+ period : float or `~astropy.units.Quantity`
580
+ The period of the transits.
581
+ duration : float or `~astropy.units.Quantity`
582
+ The duration of the transit.
583
+ transit_time : float or `~astropy.units.Quantity` or `~astropy.time.Time`
584
+ The mid-transit time of a reference transit.
585
+
586
+ Returns
587
+ -------
588
+ transit_mask : array-like
589
+ A boolean array where ``True`` indicates and in transit point and
590
+ ``False`` indicates and out-of-transit point.
591
+
592
+ """
593
+
594
+ period, duration = self._validate_period_and_duration(period, duration)
595
+ transit_time = self._as_relative_time('transit_time', transit_time)
596
+ t = strip_units(self._as_relative_time('t', t))
597
+
598
+ period = float(strip_units(period))
599
+ duration = float(strip_units(duration))
600
+ transit_time = float(strip_units(transit_time))
601
+
602
+ hp = 0.5*period
603
+ return np.abs((t-transit_time+hp) % period - hp) < 0.5*duration
604
+
605
+ def _validate_inputs(self, t, y, dy):
606
+ """Private method used to check the consistency of the inputs
607
+
608
+ Parameters
609
+ ----------
610
+ t : array-like, `~astropy.units.Quantity`, `~astropy.time.Time`, or `~astropy.time.TimeDelta`
611
+ Sequence of observation times.
612
+ y : array-like or `~astropy.units.Quantity`
613
+ Sequence of observations associated with times t.
614
+ dy : float, array-like or `~astropy.units.Quantity`
615
+ Error or sequence of observational errors associated with times t.
616
+
617
+ Returns
618
+ -------
619
+ t, y, dy : array-like or `~astropy.units.Quantity` or `~astropy.time.Time`
620
+ The inputs with consistent shapes and units.
621
+ Raises
622
+ ------
623
+ ValueError
624
+ If the dimensions are incompatible or if the units of dy cannot be
625
+ converted to the units of y.
626
+
627
+ """
628
+
629
+ # Validate shapes of inputs
630
+ if dy is None:
631
+ t, y = np.broadcast_arrays(t, y, subok=True)
632
+ else:
633
+ t, y, dy = np.broadcast_arrays(t, y, dy, subok=True)
634
+ if t.ndim != 1:
635
+ raise ValueError("Inputs (t, y, dy) must be 1-dimensional")
636
+
637
+ # validate units of inputs if any is a Quantity
638
+ if dy is not None:
639
+ dy = validate_unit_consistency(y, dy)
640
+
641
+ return t, y, dy
642
+
643
+ def _validate_duration(self, duration):
644
+ """Private method used to check a set of test durations
645
+
646
+ Parameters
647
+ ----------
648
+ duration : float, array-like or `~astropy.units.Quantity`
649
+ The set of durations that will be considered.
650
+
651
+ Returns
652
+ -------
653
+ duration : array-like or `~astropy.units.Quantity`
654
+ The input reformatted with the correct shape and units.
655
+
656
+ Raises
657
+ ------
658
+ ValueError
659
+ If the units of duration cannot be converted to the units of t.
660
+
661
+ """
662
+ duration = np.atleast_1d(np.abs(duration))
663
+ if duration.ndim != 1 or duration.size == 0:
664
+ raise ValueError("duration must be 1-dimensional")
665
+ return validate_unit_consistency(self._trel, duration)
666
+
667
+ def _validate_period_and_duration(self, period, duration):
668
+ """Private method used to check a set of periods and durations
669
+
670
+ Parameters
671
+ ----------
672
+ period : float, array-like or `~astropy.units.Quantity`
673
+ The set of test periods.
674
+ duration : float, array-like or `~astropy.units.Quantity`
675
+ The set of durations that will be considered.
676
+
677
+ Returns
678
+ -------
679
+ period, duration : array-like or `~astropy.units.Quantity`
680
+ The inputs reformatted with the correct shapes and units.
681
+
682
+ Raises
683
+ ------
684
+ ValueError
685
+ If the units of period or duration cannot be converted to the
686
+ units of t.
687
+
688
+ """
689
+ duration = self._validate_duration(duration)
690
+ period = np.atleast_1d(np.abs(period))
691
+ if period.ndim != 1 or period.size == 0:
692
+ raise ValueError("period must be 1-dimensional")
693
+ period = validate_unit_consistency(self._trel, period)
694
+
695
+ if not np.min(period) > np.max(duration):
696
+ raise ValueError("The maximum transit duration must be shorter "
697
+ "than the minimum period")
698
+
699
+ return period, duration
700
+
701
+ def _format_results(self, objective, period, results):
702
+ """A private method used to wrap and add units to the periodogram
703
+
704
+ Parameters
705
+ ----------
706
+ objective : string
707
+ The name of the objective used in the optimization.
708
+ period : array-like or `~astropy.units.Quantity`
709
+ The set of trial periods.
710
+ results : tuple
711
+ The output of one of the periodogram implementations.
712
+
713
+ """
714
+ (power, depth, depth_err, duration, transit_time, depth_snr,
715
+ log_likelihood) = results
716
+
717
+ if has_units(self._trel):
718
+ transit_time = units.Quantity(transit_time, unit=self._trel.unit)
719
+ transit_time = self._as_absolute_time_if_needed('transit_time', transit_time)
720
+ duration = units.Quantity(duration, unit=self._trel.unit)
721
+
722
+ if has_units(self.y):
723
+ depth = units.Quantity(depth, unit=self.y.unit)
724
+ depth_err = units.Quantity(depth_err, unit=self.y.unit)
725
+
726
+ depth_snr = units.Quantity(depth_snr, unit=units.one)
727
+
728
+ if self.dy is None:
729
+ if objective == "likelihood":
730
+ power = units.Quantity(power, unit=self.y.unit**2)
731
+ else:
732
+ power = units.Quantity(power, unit=units.one)
733
+ log_likelihood = units.Quantity(log_likelihood,
734
+ unit=self.y.unit**2)
735
+ else:
736
+ power = units.Quantity(power, unit=units.one)
737
+ log_likelihood = units.Quantity(log_likelihood, unit=units.one)
738
+
739
+ return BoxLeastSquaresResults(
740
+ objective, period, power, depth, depth_err, duration, transit_time,
741
+ depth_snr, log_likelihood)
742
+
743
+ def _t_unit(self):
744
+ if has_units(self._trel):
745
+ return self._trel.unit
746
+ else:
747
+ return 1
748
+
749
+ def _y_unit(self):
750
+ if has_units(self.y):
751
+ return self.y.unit
752
+ else:
753
+ return 1
754
+
755
+
756
+ class BoxLeastSquaresResults(dict):
757
+ """The results of a BoxLeastSquares search
758
+
759
+ Attributes
760
+ ----------
761
+ objective : string
762
+ The scalar used to optimize to find the best fit phase, duration, and
763
+ depth. See :func:`BoxLeastSquares.power` for more information.
764
+ period : array-like or `~astropy.units.Quantity`
765
+ The set of test periods.
766
+ power : array-like or `~astropy.units.Quantity`
767
+ The periodogram evaluated at the periods in ``period``. If
768
+ ``objective`` is:
769
+
770
+ * ``'likelihood'``: the values of ``power`` are the
771
+ log likelihood maximized over phase, depth, and duration, or
772
+ * ``'snr'``: the values of ``power`` are the signal-to-noise with
773
+ which the depth is measured maximized over phase, depth, and
774
+ duration.
775
+
776
+ depth : array-like or `~astropy.units.Quantity`
777
+ The estimated depth of the maximum power model at each period.
778
+ depth_err : array-like or `~astropy.units.Quantity`
779
+ The 1-sigma uncertainty on ``depth``.
780
+ duration : array-like or `~astropy.units.Quantity`
781
+ The maximum power duration at each period.
782
+ transit_time : array-like or `~astropy.units.Quantity` or `~astropy.time.Time`
783
+ The maximum power phase of the transit in units of time. This
784
+ indicates the mid-transit time and it will always be in the range
785
+ (0, period).
786
+ depth_snr : array-like or `~astropy.units.Quantity`
787
+ The signal-to-noise with which the depth is measured at maximum power.
788
+ log_likelihood : array-like or `~astropy.units.Quantity`
789
+ The log likelihood of the maximum power model.
790
+
791
+ """
792
+ def __init__(self, *args):
793
+ super().__init__(zip(
794
+ ("objective", "period", "power", "depth", "depth_err",
795
+ "duration", "transit_time", "depth_snr", "log_likelihood"),
796
+ args
797
+ ))
798
+
799
+ def __getattr__(self, name):
800
+ try:
801
+ return self[name]
802
+ except KeyError:
803
+ raise AttributeError(name)
804
+
805
+ __setattr__ = dict.__setitem__
806
+ __delattr__ = dict.__delitem__
807
+
808
+ def __repr__(self):
809
+ if self.keys():
810
+ m = max(map(len, list(self.keys()))) + 1
811
+ return '\n'.join([k.rjust(m) + ': ' + repr(v)
812
+ for k, v in sorted(self.items())])
813
+ else:
814
+ return self.__class__.__name__ + "()"
815
+
816
+ def __dir__(self):
817
+ return list(self.keys())
testbed/astropy__astropy/astropy/timeseries/periodograms/bls/methods.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
3
+
4
+ __all__ = ["bls_fast", "bls_slow"]
5
+
6
+ import numpy as np
7
+ from functools import partial
8
+
9
+ from ._impl import bls_impl
10
+
11
+
12
+ def bls_slow(t, y, ivar, period, duration, oversample, use_likelihood):
13
+ """Compute the periodogram using a brute force reference method
14
+
15
+ t : array-like
16
+ Sequence of observation times.
17
+ y : array-like
18
+ Sequence of observations associated with times t.
19
+ ivar : array-like
20
+ The inverse variance of ``y``.
21
+ period : array-like
22
+ The trial periods where the periodogram should be computed.
23
+ duration : array-like
24
+ The durations that should be tested.
25
+ oversample :
26
+ The resolution of the phase grid in units of durations.
27
+ use_likeliood : bool
28
+ If true, maximize the log likelihood over phase, duration, and depth.
29
+
30
+ Returns
31
+ -------
32
+ power : array-like
33
+ The periodogram evaluated at the periods in ``period``.
34
+ depth : array-like
35
+ The estimated depth of the maximum power model at each period.
36
+ depth_err : array-like
37
+ The 1-sigma uncertainty on ``depth``.
38
+ duration : array-like
39
+ The maximum power duration at each period.
40
+ transit_time : array-like
41
+ The maximum power phase of the transit in units of time. This
42
+ indicates the mid-transit time and it will always be in the range
43
+ (0, period).
44
+ depth_snr : array-like
45
+ The signal-to-noise with which the depth is measured at maximum power.
46
+ log_likelihood : array-like
47
+ The log likelihood of the maximum power model.
48
+
49
+ """
50
+ f = partial(_bls_slow_one, t, y, ivar, duration,
51
+ oversample, use_likelihood)
52
+ return _apply(f, period)
53
+
54
+
55
+ def bls_fast(t, y, ivar, period, duration, oversample, use_likelihood):
56
+ """Compute the periodogram using an optimized Cython implementation
57
+
58
+ t : array-like
59
+ Sequence of observation times.
60
+ y : array-like
61
+ Sequence of observations associated with times t.
62
+ ivar : array-like
63
+ The inverse variance of ``y``.
64
+ period : array-like
65
+ The trial periods where the periodogram should be computed.
66
+ duration : array-like
67
+ The durations that should be tested.
68
+ oversample :
69
+ The resolution of the phase grid in units of durations.
70
+ use_likeliood : bool
71
+ If true, maximize the log likelihood over phase, duration, and depth.
72
+
73
+ Returns
74
+ -------
75
+ power : array-like
76
+ The periodogram evaluated at the periods in ``period``.
77
+ depth : array-like
78
+ The estimated depth of the maximum power model at each period.
79
+ depth_err : array-like
80
+ The 1-sigma uncertainty on ``depth``.
81
+ duration : array-like
82
+ The maximum power duration at each period.
83
+ transit_time : array-like
84
+ The maximum power phase of the transit in units of time. This
85
+ indicates the mid-transit time and it will always be in the range
86
+ (0, period).
87
+ depth_snr : array-like
88
+ The signal-to-noise with which the depth is measured at maximum power.
89
+ log_likelihood : array-like
90
+ The log likelihood of the maximum power model.
91
+
92
+ """
93
+ return bls_impl(
94
+ t, y, ivar, period, duration, oversample, use_likelihood
95
+ )
96
+
97
+
98
+ def _bls_slow_one(t, y, ivar, duration, oversample, use_likelihood, period):
99
+ """A private function to compute the brute force periodogram result"""
100
+ best = (-np.inf, None)
101
+ hp = 0.5*period
102
+ min_t = np.min(t)
103
+ for dur in duration:
104
+
105
+ # Compute the phase grid (this is set by the duration and oversample).
106
+ d_phase = dur / oversample
107
+ phase = np.arange(0, period+d_phase, d_phase)
108
+
109
+ for t0 in phase:
110
+ # Figure out which data points are in and out of transit.
111
+ m_in = np.abs((t-min_t-t0+hp) % period - hp) < 0.5*dur
112
+ m_out = ~m_in
113
+
114
+ # Compute the estimates of the in and out-of-transit flux.
115
+ ivar_in = np.sum(ivar[m_in])
116
+ ivar_out = np.sum(ivar[m_out])
117
+ y_in = np.sum(y[m_in] * ivar[m_in]) / ivar_in
118
+ y_out = np.sum(y[m_out] * ivar[m_out]) / ivar_out
119
+
120
+ # Use this to compute the best fit depth and uncertainty.
121
+ depth = y_out - y_in
122
+ depth_err = np.sqrt(1.0 / ivar_in + 1.0 / ivar_out)
123
+ snr = depth / depth_err
124
+
125
+ # Compute the log likelihood of this model.
126
+ loglike = -0.5*np.sum((y_in - y[m_in])**2 * ivar[m_in])
127
+ loglike += 0.5*np.sum((y_out - y[m_in])**2 * ivar[m_in])
128
+
129
+ # Choose which objective should be used for the optimization.
130
+ if use_likelihood:
131
+ objective = loglike
132
+ else:
133
+ objective = snr
134
+
135
+ # If this model is better than any before, keep it.
136
+ if depth > 0 and objective > best[0]:
137
+ best = (
138
+ objective,
139
+ (objective, depth, depth_err, dur, (t0+min_t) % period,
140
+ snr, loglike)
141
+ )
142
+
143
+ return best[1]
144
+
145
+
146
+ def _apply(f, period):
147
+ return tuple(map(np.array, zip(*map(f, period))))
testbed/astropy__astropy/astropy/timeseries/periodograms/bls/setup_package.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst
2
+
3
+ import os
4
+ from os.path import join
5
+
6
+ from distutils.core import Extension
7
+
8
+
9
+ BLS_ROOT = os.path.relpath(os.path.dirname(__file__))
10
+
11
+
12
+ def get_extensions():
13
+ ext = Extension(
14
+ "astropy.timeseries.periodograms.bls._impl",
15
+ sources=[
16
+ join(BLS_ROOT, "bls.c"),
17
+ join(BLS_ROOT, "_impl.pyx"),
18
+ ],
19
+ include_dirs=["numpy"],
20
+ )
21
+ return [ext]
testbed/astropy__astropy/astropy/timeseries/periodograms/bls/tests/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Licensed under a 3-clause BSD style license - see LICENSE.rst