saltjax 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
saltjax-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
saltjax-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,87 @@
1
+ Metadata-Version: 2.4
2
+ Name: saltjax
3
+ Version: 0.1.0
4
+ Summary: Fast batched SALT2 lightcurve fitting with JAX, reproducing sncosmo
5
+ Author-email: Mickael Rigault <m.rigault@ipnl.in2p3.fr>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/MickaelRigault/saltjax
8
+ Keywords: astronomy,astrophysics,supernovae,jax
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Scientific/Engineering :: Astronomy
13
+ Classifier: Topic :: Scientific/Engineering :: Physics
14
+ Requires-Python: >=3.10
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: numpy>=1.26
18
+ Requires-Dist: pandas
19
+ Requires-Dist: scipy
20
+ Requires-Dist: jax
21
+ Requires-Dist: sncosmo
22
+ Requires-Dist: extinction
23
+ Provides-Extra: docs
24
+ Requires-Dist: myst-nb; extra == "docs"
25
+ Requires-Dist: sphinx-book-theme; extra == "docs"
26
+ Requires-Dist: sphinx_copybutton; extra == "docs"
27
+ Requires-Dist: sphinx-design; extra == "docs"
28
+ Provides-Extra: tests
29
+ Requires-Dist: pytest; extra == "tests"
30
+ Requires-Dist: coverage; extra == "tests"
31
+ Requires-Dist: iminuit; extra == "tests"
32
+ Provides-Extra: progress
33
+ Requires-Dist: tqdm; extra == "progress"
34
+ Dynamic: license-file
35
+
36
+ # saltjax
37
+
38
+ Fast, batched SALT2 lightcurve fitting with [JAX](https://docs.jax.dev), reproducing
39
+ [sncosmo](https://sncosmo.readthedocs.io)'s `fit_lc`.
40
+
41
+ `saltjax` fits SALT2 to thousands of lightcurves at once. It uses the same model as sncosmo
42
+ (same interpolation kernel, model covariance and Milky Way dust), and gives the same
43
+ parameters and errors (to ~1e-2 sigma at worst) one to two orders of magnitude faster.
44
+
45
+ ## Install
46
+
47
+ ```bash
48
+ git clone https://github.com/MickaelRigault/saltjax.git
49
+ cd saltjax
50
+ pip install .
51
+ ```
52
+
53
+ ## Quick start
54
+
55
+ ```python
56
+ import saltjax
57
+
58
+ # data: lightcurves, indexed by (target, observation), with columns
59
+ # time (or mjd), band, flux, fluxerr, zp [, zpsys]
60
+ # targets: one row per target with z [, t0, x1, c, mwebv]
61
+ results = saltjax.fit_salt(data, targets, modelcov=True, progress_bar=True)
62
+ results[["t0", "x0", "x1", "c", "t0_err", "x0_err", "x1_err", "c_err"]]
63
+ ```
64
+
65
+ `saltjax` is used by [skysurvey](https://github.com/MickaelRigault/skysurvey) through
66
+ `skysurvey.lcfit.fit_salt_jax(dataset)`.
67
+
68
+ ## How it reproduces sncosmo
69
+
70
+ * **Interpolation.** sncosmo interpolates the SALT2 surfaces with a separable bicubic-convolution kernel. Band
71
+ integration is linear, so `saltjax` band-integrates the surfaces at the native phase nodes
72
+ and applies the *same* kernel in phase. This is exact.
73
+ * **Colour and dust.** The colour law and the Milky Way extinction (CCM89, observer frame) are written as an exact
74
+ band-mean factor times power series truncated below machine precision.
75
+ * **Redshift tables.** The band integrals are tabulated on a fine redshift grid. This is the only approximation:
76
+ relative flux differences are below 1e-6.
77
+ * **Model covariance.** `modelcov=True` follows `sncosmo.fit_lc`. The model covariance (a diagonal plus one block
78
+ per band) is inverted exactly with the Woodbury identity.
79
+ * **Errors.** Errors are `2 H^-1`, with `H` the exact Hessian of the chi2 (as Minuit HESSE).
80
+
81
+ ## Limitations
82
+
83
+ * SALT2 sources only (`sncosmo.SALT2Source`).
84
+ * The only effect supported is Milky Way CCM89 dust in the observer frame.
85
+ * AB magnitude system only.
86
+ * No parameter bounds.
87
+ * Fixed redshift.
@@ -0,0 +1,52 @@
1
+ # saltjax
2
+
3
+ Fast, batched SALT2 lightcurve fitting with [JAX](https://docs.jax.dev), reproducing
4
+ [sncosmo](https://sncosmo.readthedocs.io)'s `fit_lc`.
5
+
6
+ `saltjax` fits SALT2 to thousands of lightcurves at once. It uses the same model as sncosmo
7
+ (same interpolation kernel, model covariance and Milky Way dust), and gives the same
8
+ parameters and errors (to ~1e-2 sigma at worst) one to two orders of magnitude faster.
9
+
10
+ ## Install
11
+
12
+ ```bash
13
+ git clone https://github.com/MickaelRigault/saltjax.git
14
+ cd saltjax
15
+ pip install .
16
+ ```
17
+
18
+ ## Quick start
19
+
20
+ ```python
21
+ import saltjax
22
+
23
+ # data: lightcurves, indexed by (target, observation), with columns
24
+ # time (or mjd), band, flux, fluxerr, zp [, zpsys]
25
+ # targets: one row per target with z [, t0, x1, c, mwebv]
26
+ results = saltjax.fit_salt(data, targets, modelcov=True, progress_bar=True)
27
+ results[["t0", "x0", "x1", "c", "t0_err", "x0_err", "x1_err", "c_err"]]
28
+ ```
29
+
30
+ `saltjax` is used by [skysurvey](https://github.com/MickaelRigault/skysurvey) through
31
+ `skysurvey.lcfit.fit_salt_jax(dataset)`.
32
+
33
+ ## How it reproduces sncosmo
34
+
35
+ * **Interpolation.** sncosmo interpolates the SALT2 surfaces with a separable bicubic-convolution kernel. Band
36
+ integration is linear, so `saltjax` band-integrates the surfaces at the native phase nodes
37
+ and applies the *same* kernel in phase. This is exact.
38
+ * **Colour and dust.** The colour law and the Milky Way extinction (CCM89, observer frame) are written as an exact
39
+ band-mean factor times power series truncated below machine precision.
40
+ * **Redshift tables.** The band integrals are tabulated on a fine redshift grid. This is the only approximation:
41
+ relative flux differences are below 1e-6.
42
+ * **Model covariance.** `modelcov=True` follows `sncosmo.fit_lc`. The model covariance (a diagonal plus one block
43
+ per band) is inverted exactly with the Woodbury identity.
44
+ * **Errors.** Errors are `2 H^-1`, with `H` the exact Hessian of the chi2 (as Minuit HESSE).
45
+
46
+ ## Limitations
47
+
48
+ * SALT2 sources only (`sncosmo.SALT2Source`).
49
+ * The only effect supported is Milky Way CCM89 dust in the observer frame.
50
+ * AB magnitude system only.
51
+ * No parameter bounds.
52
+ * Fixed redshift.
@@ -0,0 +1,94 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.2"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "saltjax"
7
+ description = "Fast batched SALT2 lightcurve fitting with JAX, reproducing sncosmo"
8
+ authors = [
9
+ {name = "Mickael Rigault", email = "m.rigault@ipnl.in2p3.fr"},
10
+ ]
11
+ readme = "README.md"
12
+ requires-python = ">=3.10"
13
+ license = "Apache-2.0"
14
+ keywords = ["astronomy", "astrophysics", "supernovae", "jax"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Science/Research",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Scientific/Engineering :: Astronomy",
20
+ "Topic :: Scientific/Engineering :: Physics",
21
+ ]
22
+ dependencies = [
23
+ # basic
24
+ "numpy >=1.26",
25
+ "pandas",
26
+ "scipy",
27
+ # jax
28
+ "jax",
29
+ # Astro
30
+ "sncosmo",
31
+ "extinction",
32
+ ]
33
+ dynamic = ["version"]
34
+
35
+ [project.urls]
36
+ Homepage = "https://github.com/MickaelRigault/saltjax"
37
+
38
+ [project.optional-dependencies]
39
+ docs = [
40
+ "myst-nb",
41
+ "sphinx-book-theme",
42
+ "sphinx_copybutton",
43
+ "sphinx-design",
44
+ ]
45
+ tests = ["pytest", "coverage", "iminuit"]
46
+ progress = ["tqdm"]
47
+
48
+ [tool.setuptools]
49
+ include-package-data = true
50
+
51
+ [tool.setuptools.packages.find]
52
+ where = ["src"]
53
+
54
+ [tool.setuptools.dynamic]
55
+ version = {attr = "saltjax.__version__"}
56
+
57
+
58
+ # RUFF
59
+ [tool.ruff]
60
+ exclude = ["tests", "docs"]
61
+ include = ["*.py"]
62
+
63
+ [tool.ruff.lint]
64
+ select = [
65
+ "E", "F", # flake8
66
+ "NPY", # numpy
67
+ ]
68
+ ignore = [
69
+ "E501", # line-too-long
70
+ ]
71
+ unfixable = [
72
+ "F841", # Removes unused variables
73
+ ]
74
+
75
+ [tool.ruff.lint.isort]
76
+ known-first-party = ["saltjax"]
77
+
78
+ [tool.pytest.ini_options]
79
+ addopts = ["-ra", "--showlocals", "--strict-markers", "--strict-config"]
80
+ testpaths = ["tests"]
81
+
82
+ [tool.coverage.run]
83
+ source = ["saltjax"]
84
+ omit = ["tests/*"]
85
+ branch = true
86
+
87
+ [tool.coverage.report]
88
+ exclude_lines = [
89
+ "pragma: no cover",
90
+ "except ImportError",
91
+ "raise AssertionError",
92
+ "raise NotImplementedError",
93
+ "if __name__ == .__main__.:",
94
+ ]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,9 @@
1
+ """Fast batched SALT2 lightcurve fitting with JAX, reproducing sncosmo."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from .fit import fit_salt # noqa: F401, E402
6
+ from .tables import build_tables, get_tables, get_salt2_source # noqa: F401, E402
7
+ from .data import pack_lightcurves # noqa: F401, E402
8
+ from .model import get_model_functions # noqa: F401, E402
9
+ from .kernel import kernel_weights # noqa: F401, E402
@@ -0,0 +1,160 @@
1
+ """Pack lightcurves and per-target tables into padded arrays for the fit."""
2
+
3
+ import warnings
4
+
5
+ import numpy as np
6
+ import jax
7
+ import jax.numpy as jnp
8
+
9
+ from .kernel import kernel_weights
10
+
11
+ __all__ = ["pack_lightcurves"]
12
+
13
+ LC_KEYS = ("t", "flux", "err", "zpn", "band", "mask")
14
+ FIT_KEYS = ("K", "Ke", "CLb", "Tmw", "F", "Fe", "V", "Ve", "CD", "z") + LC_KEYS
15
+
16
+
17
+ def get_time_key(data, time_key=None):
18
+ """Get the time column of the lightcurves.
19
+
20
+ Parameters
21
+ ----------
22
+ data : pandas.DataFrame
23
+ Lightcurve data.
24
+
25
+ time_key : str or None, optional
26
+ Time column. If None, the first of 'time', 'mjd' or 'jd' found.
27
+ The default is None.
28
+
29
+ Returns
30
+ -------
31
+ str
32
+ Name of the time column.
33
+
34
+ Raises
35
+ ------
36
+ ValueError
37
+ If `time_key` is None and no time column is found.
38
+ """
39
+ if time_key is not None:
40
+ return time_key
41
+ time_key = next((k for k in ("time", "mjd", "jd") if k in data.columns), None)
42
+ if time_key is None:
43
+ raise ValueError("cannot parse the time column, provide time_key.")
44
+ return time_key
45
+
46
+
47
+ @jax.jit
48
+ def _interp_contract(K, idx, w, epow):
49
+ """Interpolate K in redshift and contract the dust series, per target."""
50
+ def one(i, ww, e):
51
+ return jnp.einsum("j,m,jbkcmp->bkcp", ww, e, K[i])
52
+ return jax.vmap(one)(idx, w, epow)
53
+
54
+
55
+ def pack_lightcurves(data, targets, tables, indexes=None, phase_range=(-10, 40),
56
+ mwebv_key="mwebv", time_key=None, pad_to=16):
57
+ """Pack the lightcurves and the per-target tables into padded arrays.
58
+
59
+ Parameters
60
+ ----------
61
+ data : pandas.DataFrame
62
+ Lightcurves, with a (target, observation) multi-index and columns
63
+ time (see `time_key`), 'band', 'flux', 'fluxerr', 'zp' and optionally
64
+ 'zpsys'.
65
+
66
+ targets : pandas.DataFrame
67
+ Targets, indexed as the first level of `data`, with a 'z' column, a
68
+ 't0' column if `phase_range` is given and a `mwebv_key` column for the
69
+ Milky Way extinction.
70
+
71
+ tables : dict
72
+ Output of :func:`saltjax.tables.build_tables`.
73
+
74
+ indexes : list or None, optional
75
+ Targets to pack. If None, all those of `targets`. The default is None.
76
+
77
+ phase_range : list or None, optional
78
+ Rest-frame phase range (relative to the targets' t0) of the data used.
79
+ The default is (-10, 40).
80
+
81
+ mwebv_key : str or None, optional
82
+ Column of `targets` with the Milky Way E(B-V). If None or absent, no
83
+ Milky Way extinction. The default is 'mwebv'.
84
+
85
+ time_key : str or None, optional
86
+ Time column of the lightcurves. If None, the first of 'time', 'mjd' or
87
+ 'jd' found. The default is None.
88
+
89
+ pad_to : int, optional
90
+ The number of points per lightcurve is padded to a multiple of
91
+ `pad_to`. The default is 16.
92
+
93
+ Returns
94
+ -------
95
+ dict
96
+ Arrays used by the fit (one row per target).
97
+
98
+ Raises
99
+ ------
100
+ NotImplementedError
101
+ If a magnitude system other than 'ab' is used.
102
+ """
103
+ indexes = list(targets.index if indexes is None else indexes)
104
+ truth = targets.loc[indexes]
105
+ z = truth["z"].to_numpy(float)
106
+ has_mw = mwebv_key is not None and mwebv_key in truth
107
+ ebv = truth[mwebv_key].to_numpy(float) if has_mw else np.zeros(len(z))
108
+ zg = tables["zgrid"]
109
+ idx, w = kernel_weights((z - zg[0]) / (zg[1] - zg[0]), len(zg))
110
+
111
+ def zi(table):
112
+ return np.einsum("sj,sj...->s...", w, table[idx])
113
+ epow = ebv[:, None] ** np.arange(tables["nm"])
114
+ with jax.enable_x64(True):
115
+ K, Ke = (np.asarray(_interp_contract(jnp.asarray(tables[key]), jnp.asarray(idx),
116
+ jnp.asarray(w), jnp.asarray(epow)))
117
+ for key in ("K", "Ke"))
118
+
119
+ data = data.loc[indexes]
120
+ time_key = get_time_key(data, time_key)
121
+ if "zpsys" in data.columns and not data["zpsys"].str.lower().eq("ab").all():
122
+ raise NotImplementedError("only the 'ab' magnitude system is supported")
123
+ lut = {k: j for j, k in enumerate(indexes)}
124
+ pos = np.fromiter((lut[v] for v in data.index.get_level_values(0)), int, len(data))
125
+ # as sncosmo.fit_lc: drop the points whose band is out of the model wavelength range
126
+ bandid = {b: j for j, b in enumerate(tables["bands"])}
127
+ bid = data["band"].map(bandid).to_numpy()
128
+ wmin, wmax = tables["wave_range"]
129
+ brange = tables["band_range"][bid]
130
+ covered = (brange[:, 0] >= wmin * (1 + z[pos])) & (brange[:, 1] <= wmax * (1 + z[pos]))
131
+ if not np.all(covered):
132
+ warnings.warn(f"{np.sum(~covered)} points dropped: band out of the model wavelength range "
133
+ f"({', '.join(sorted(data['band'][~covered].unique()))})")
134
+ data, pos = data[covered], pos[covered]
135
+ if phase_range is not None:
136
+ ph = (data[time_key].to_numpy() - truth["t0"].to_numpy(float)[pos]) / (1 + z[pos])
137
+ keep = (ph >= phase_range[0]) & (ph <= phase_range[1])
138
+ data, pos = data[keep], pos[keep]
139
+ order = np.argsort(pos, kind="stable")
140
+ ps = pos[order]
141
+ starts = np.r_[0, np.flatnonzero(np.diff(ps)) + 1]
142
+ slot = np.empty(len(ps), int)
143
+ slot[order] = np.arange(len(ps)) - np.repeat(starts, np.diff(np.r_[starts, len(ps)]))
144
+ nsn = len(indexes)
145
+ nobs = int(np.ceil((slot.max() + 1) / pad_to) * pad_to) if len(slot) else pad_to
146
+ out = {k: np.zeros((nsn, nobs)) for k in LC_KEYS}
147
+ out["t"][pos, slot] = data[time_key]
148
+ out["flux"][pos, slot] = data["flux"]
149
+ out["err"][pos, slot] = data["fluxerr"]
150
+ out["zpn"][pos, slot] = 10 ** (0.4 * data["zp"].to_numpy(float))
151
+ out["band"][pos, slot] = data["band"].map(bandid)
152
+ out["mask"][pos, slot] = 1.
153
+ out["err"][out["mask"] == 0] = 1.
154
+ out["band"] = out["band"].astype(int)
155
+ # exact band-mean dust factor
156
+ Tmw = 10 ** (-0.4 * ebv[:, None] * tables["Kb"][None, :])
157
+ return out | dict(K=K, Ke=Ke, CLb=zi(tables["CLb"]), Tmw=Tmw,
158
+ F=zi(tables["F"]), Fe=zi(tables["Fe"]),
159
+ V=zi(tables["V"]), Ve=zi(tables["Ve"]), CD=zi(tables["CD"]), z=z,
160
+ ebv=ebv, index=np.asarray(indexes))