mvgkde 0.1.0__py3-none-any.whl

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.
mvgkde/__init__.py ADDED
@@ -0,0 +1,10 @@
1
+ """MultiVariate Gaussian Kernel Density Estimator (mvgkde)."""
2
+
3
+ __all__: list[str] = [
4
+ "__version__",
5
+ "MultiVariateGaussianKDE",
6
+ "gaussian_kde",
7
+ ]
8
+
9
+ from ._core import MultiVariateGaussianKDE, gaussian_kde
10
+ from ._version import version as __version__
mvgkde/_core.py ADDED
@@ -0,0 +1,482 @@
1
+ """Gaussian Kernel Density Estimator."""
2
+
3
+ # NOTE: This file modifies code from JAX, which is licensed under the Apache
4
+ # License 2.0. Copyright 2018 Google LLC.
5
+
6
+ from collections.abc import Callable
7
+ from dataclasses import dataclass
8
+ from functools import partial
9
+ from typing import Annotated as Antd, Any, Literal, Never, TypeAlias, cast, final
10
+ from typing_extensions import Doc
11
+
12
+ import jax.numpy as jnp
13
+ import numpy as np
14
+ from jax import jit, lax, random, vmap
15
+ from jax._src.numpy.util import check_arraylike, promote_dtypes_inexact
16
+ from jax._src.prng import PRNGKeyArray
17
+ from jax.scipy import linalg, special
18
+ from jax.tree_util import register_pytree_node_class
19
+ from jaxtyping import Array, Float
20
+
21
+ Scalar: TypeAlias = Float[Array, ""]
22
+ Neff: TypeAlias = Float[Array, ""]
23
+ Dataset: TypeAlias = Float[Array, "F N"] | Float[Array, "N"]
24
+ Weights: TypeAlias = Float[Array, "N"]
25
+ Cov: TypeAlias = Float[Array, "F F"]
26
+
27
+ BWMethodOpts = (
28
+ Literal["scott", "silverman"] | Scalar | Callable[[Dataset, Weights], Scalar] | None
29
+ )
30
+
31
+
32
+ @final
33
+ @register_pytree_node_class
34
+ @dataclass(frozen=True, slots=True)
35
+ class MultiVariateGaussianKDE:
36
+ """MultiVariate Gaussian Kernel Density Estimator.
37
+
38
+ JAX implementation of `scipy.stats.gaussian_kde`.
39
+
40
+ Parameters
41
+ ----------
42
+ dataset: Array[float, (F, N)].
43
+ Data from which to estimate the distribution. If 1D, shape is (n_data,).
44
+ If 2D, shape is (n_dimensions, n_data).
45
+
46
+ bw_method : string, scalar, or callable.
47
+ Either "scott", "silverman", a scalar value, or a callable function
48
+ which takes ``self`` as a parameter.
49
+ covariance : Array[float, (F, F)], optional.
50
+ A covariance matrix to use for the kernel. If None, the covariance
51
+ is estimated from the data, using the "bw_method".
52
+
53
+ weights: Array[float, (N,)], optional.
54
+ Weights of the same shape as the dataset.
55
+
56
+ """
57
+
58
+ dataset: Antd[Dataset, Doc("Data for distribution estimation")]
59
+ weights: Antd[Weights, Doc("Weights for data points")]
60
+ neff: Antd[Neff, Doc("effective number of data points")]
61
+ covariance: Antd[Cov, Doc("Covariance matrix")]
62
+ inv_cov: Antd[Cov, Doc("Inverse covariance matrix")]
63
+
64
+ def __post_init__(self) -> None:
65
+ self._validate_dataset(self.dataset)
66
+ self._validate_weights(self.weights, self.dataset.shape[1])
67
+
68
+ @classmethod
69
+ def from_covariance(
70
+ cls,
71
+ dataset: Dataset,
72
+ /,
73
+ covariance: Cov,
74
+ *,
75
+ weights: Float[Array, "N"] | None = None,
76
+ ) -> "MultiVariateGaussianKDE":
77
+ # Dataset
78
+ dataset = jnp.atleast_2d(dataset)
79
+ cls._validate_dataset(dataset)
80
+
81
+ # Weights
82
+ n = dataset.shape[1]
83
+ if weights is not None:
84
+ dataset, weights = promote_dtypes_inexact(dataset, weights)
85
+ weights = jnp.atleast_1d(weights)
86
+ weights /= jnp.sum(weights)
87
+ else:
88
+ (dataset,) = promote_dtypes_inexact(dataset)
89
+ weights = jnp.full(n, 1.0 / n, dtype=dataset.dtype)
90
+
91
+ return cls(
92
+ dataset=dataset,
93
+ weights=weights,
94
+ neff=1 / jnp.sum(jnp.square(weights)),
95
+ covariance=covariance,
96
+ inv_cov=linalg.inv(covariance),
97
+ )
98
+
99
+ @classmethod
100
+ def from_bandwidth(
101
+ cls,
102
+ dataset: Dataset,
103
+ /,
104
+ *,
105
+ bw: BWMethodOpts = None,
106
+ weights: Float[Array, "N"] | None = None,
107
+ ) -> "MultiVariateGaussianKDE":
108
+ # Dataset
109
+ dataset = jnp.atleast_2d(dataset)
110
+ cls._validate_dataset(dataset)
111
+
112
+ # Weights
113
+ n = dataset.shape[1]
114
+ if weights is not None:
115
+ dataset, weights = promote_dtypes_inexact(dataset, weights)
116
+ weights = jnp.atleast_1d(weights)
117
+ weights /= jnp.sum(weights)
118
+ else:
119
+ (dataset,) = promote_dtypes_inexact(dataset)
120
+ weights = jnp.full(n, 1.0 / n, dtype=dataset.dtype)
121
+ cls._validate_weights(weights, n)
122
+
123
+ # Neff
124
+ neff = 1 / jnp.sum(jnp.square(weights))
125
+
126
+ # Covariance
127
+ cov, inv_cov = cls._parse_data_covariance(dataset, weights, neff, bw)
128
+
129
+ return cls(
130
+ dataset=dataset,
131
+ weights=weights,
132
+ neff=neff,
133
+ covariance=cov,
134
+ inv_cov=inv_cov,
135
+ )
136
+
137
+ # ====================================================================
138
+ # Pytree methods
139
+
140
+ def tree_flatten(self) -> tuple[tuple[Neff, Dataset, Weights, Cov, Cov], None]:
141
+ """Flatten a Gaussian KDE into a Pytree representation."""
142
+ return (
143
+ (self.dataset, self.weights, self.neff, self.covariance, self.inv_cov),
144
+ None,
145
+ )
146
+
147
+ @classmethod
148
+ def tree_unflatten(
149
+ cls,
150
+ aux_data: Any,
151
+ children: tuple[Neff, Dataset, Weights, Cov, Cov],
152
+ ) -> "MultiVariateGaussianKDE":
153
+ """Reconstruct a Gaussian KDE from its Pytree representation."""
154
+ del aux_data
155
+ kde = cls(
156
+ dataset=children[0],
157
+ weights=children[1],
158
+ neff=children[2],
159
+ covariance=children[3],
160
+ inv_cov=children[4],
161
+ )
162
+ return kde # noqa: RET504
163
+
164
+ # ====================================================================
165
+
166
+ @property
167
+ def d(self) -> int:
168
+ """Number of dimensions in the dataset."""
169
+ return cast(int, self.dataset.shape[0])
170
+
171
+ @property
172
+ def n(self) -> int:
173
+ """Number of data points in the dataset."""
174
+ return cast(int, self.dataset.shape[1])
175
+
176
+ # ====================================================================
177
+
178
+ def evaluate(self, points: Float[Array, "F data"]) -> Float[Array, "data"]:
179
+ """Evaluate the Gaussian KDE on the given points."""
180
+ check_arraylike("evaluate", points)
181
+ points = self._reshape_points(points)
182
+ result = _gaussian_kernel_eval(
183
+ self.dataset.T,
184
+ self.weights[:, None],
185
+ points.T,
186
+ self.inv_cov,
187
+ in_log=False,
188
+ )
189
+ return result[:, 0]
190
+
191
+ def __call__(self, points: Float[Array, "F data"]) -> Float[Array, "data"]:
192
+ """Evaluate the Gaussian KDE on the given points."""
193
+ return self.evaluate(points)
194
+
195
+ def pdf(
196
+ self,
197
+ x: Float[Array, "F"] | Float[Array, "F data"],
198
+ ) -> Float[Array, ""] | Float[Array, "data"]:
199
+ """Probability density function."""
200
+ return self.evaluate(x)
201
+
202
+ def logpdf(
203
+ self,
204
+ x: Float[Array, "F"] | Float[Array, "F data"],
205
+ ) -> Float[Array, ""] | Float[Array, "data"]:
206
+ """Log probability density function."""
207
+ check_arraylike("logpdf", x)
208
+ x = self._reshape_points(x)
209
+ result = _gaussian_kernel_eval(
210
+ self.dataset.T,
211
+ self.weights[:, None],
212
+ x.T,
213
+ self.inv_cov,
214
+ in_log=True,
215
+ )
216
+ return result[:, 0]
217
+
218
+ def resample(
219
+ self,
220
+ key: PRNGKeyArray,
221
+ shape: tuple[int, ...] = (),
222
+ ) -> Float[Array, "F {shape}"]:
223
+ """Randomly sample a dataset from the estimated pdf.
224
+
225
+ Parameters
226
+ ----------
227
+ key: PRNGKeyArray
228
+ a PRNG key used as the random key.
229
+ shape: tuple[int, ...], optional
230
+ A tuple of nonnegative integers specifying the result batch shape;
231
+ that is, the prefix of the result shape excluding the last axis.
232
+
233
+ Returns
234
+ -------
235
+ Array[float, (F, *shape)]
236
+ The resampled dataset as an array with shape `(d,) + shape`.
237
+
238
+ """
239
+ ind_key, eps_key = random.split(key)
240
+ ind = random.choice(ind_key, self.n, shape=shape, p=self.weights)
241
+ eps = random.multivariate_normal(
242
+ eps_key,
243
+ jnp.zeros(self.d, self.covariance.dtype),
244
+ self.covariance,
245
+ shape=shape,
246
+ dtype=self.dataset.dtype,
247
+ ).T
248
+ return self.dataset[:, ind] + eps
249
+
250
+ # ====================================================================
251
+ # Integration
252
+
253
+ def integrate_gaussian(
254
+ self,
255
+ mean: Float[Array, "F"],
256
+ cov: Float[Array, "F F"],
257
+ ) -> Float[Array, ""]:
258
+ """Integrate the distribution weighted by a Gaussian."""
259
+ mean = jnp.atleast_1d(jnp.squeeze(mean))
260
+
261
+ cov = jnp.atleast_2d(cov)
262
+
263
+ if mean.shape != (self.d,):
264
+ msg = f"mean does not have dimension {self.d}"
265
+ raise ValueError(msg)
266
+ if cov.shape != (self.d, self.d):
267
+ msg = f"covariance does not have dimension {self.d}"
268
+ raise ValueError(msg)
269
+
270
+ chol = linalg.cho_factor(self.covariance + cov)
271
+ norm = jnp.sqrt(2 * np.pi) ** self.d * jnp.prod(jnp.diag(chol[0]))
272
+ norm = 1.0 / norm
273
+ return _gaussian_kernel_convolve(chol, norm, self.dataset, self.weights, mean)
274
+
275
+ def integrate_box_1d(self, low: Scalar, high: Scalar) -> Float[Array, ""]:
276
+ """Integrate the distribution over the given limits."""
277
+ if self.d != 1:
278
+ msg = "integrate_box_1d() only handles 1D pdfs"
279
+ raise ValueError(msg)
280
+ if jnp.ndim(low) != 0 or jnp.ndim(high) != 0:
281
+ msg = "the limits of integration in integrate_box_1d must be scalars"
282
+ raise ValueError(msg)
283
+ sigma = jnp.squeeze(jnp.sqrt(self.covariance))
284
+ low = jnp.squeeze((low - self.dataset) / sigma)
285
+ high = jnp.squeeze((high - self.dataset) / sigma)
286
+ return jnp.sum(self.weights * (special.ndtr(high) - special.ndtr(low)))
287
+
288
+ def integrate_kde(self, other: "MultiVariateGaussianKDE") -> Float[Array, ""]:
289
+ """Integrate the product of two Gaussian KDE distributions."""
290
+ if other.d != self.d:
291
+ msg = "KDEs are not the same dimensionality"
292
+ raise ValueError(msg)
293
+
294
+ chol = linalg.cho_factor(self.covariance + other.covariance)
295
+ norm = jnp.sqrt(2 * np.pi) ** self.d * jnp.prod(jnp.diag(chol[0]))
296
+ norm = 1.0 / norm
297
+
298
+ sm, lg = (self, other) if self.n < other.n else (other, self)
299
+ result = vmap(
300
+ partial(_gaussian_kernel_convolve, chol, norm, lg.dataset, lg.weights),
301
+ in_axes=1,
302
+ )(sm.dataset)
303
+ return jnp.sum(result * sm.weights)
304
+
305
+ def integrate_box(
306
+ self,
307
+ low_bounds: Any,
308
+ high_bounds: Any,
309
+ maxpts: Any = None,
310
+ ) -> Never:
311
+ """This method is not implemented in the JAX interface.""" # noqa: D401, D404
312
+ del low_bounds, high_bounds, maxpts
313
+ msg = "only 1D box integrations are supported; use `integrate_box_1d`"
314
+ raise NotImplementedError(msg)
315
+
316
+ # ====================================================================
317
+
318
+ def set_bandwidth(self, bw_method: Any = None) -> Never:
319
+ """This method is not implemented in the JAX interface.""" # noqa: D401, D404
320
+ del bw_method
321
+ msg = "dynamically changing the bandwidth method is not supported"
322
+ raise NotImplementedError(msg)
323
+
324
+ # ====================================================================
325
+ # Parsing and Validation
326
+
327
+ @staticmethod
328
+ def _validate_dataset(dataset: Dataset) -> None:
329
+ if jnp.issubdtype(lax.dtype(dataset), jnp.complexfloating):
330
+ msg = "gaussian_kde does not support complex data"
331
+ raise NotImplementedError(msg)
332
+
333
+ if not dataset.size > 1:
334
+ msg = "`dataset` input should have multiple elements."
335
+ raise ValueError(msg)
336
+
337
+ @staticmethod
338
+ def _validate_weights(weights: Weights, n: int) -> None:
339
+ if weights.ndim != 1:
340
+ msg = "`weights` input should be one-dimensional."
341
+ raise ValueError(msg)
342
+
343
+ if len(weights) != n:
344
+ msg = "`weights` input should be of length n"
345
+ raise ValueError(msg)
346
+
347
+ @staticmethod
348
+ def _parse_data_covariance(
349
+ dataset: Dataset,
350
+ weights: Weights,
351
+ neff: Neff,
352
+ bw: BWMethodOpts,
353
+ ) -> tuple[Cov, Cov]:
354
+ d = dataset.shape[0]
355
+
356
+ # Bandwidth
357
+ # string options: scott / None, silverman
358
+ if bw == "scott" or bw is None:
359
+ factor = jnp.power(neff, -1.0 / (d + 4))
360
+ elif bw == "silverman":
361
+ factor = jnp.power(neff * (d + 2) / 4.0, -1.0 / (d + 4))
362
+ elif isinstance(bw, str):
363
+ msg = "`bw` str options are {'scott', 'silverman'}."
364
+ raise ValueError(msg)
365
+
366
+ # Callable
367
+ elif callable(bw):
368
+ factor = bw(dataset, weights)
369
+
370
+ # Array(-like) Options
371
+ elif jnp.isscalar(bw):
372
+ factor = bw
373
+ elif hasattr(bw, "shape"):
374
+ shape = bw.shape
375
+ if shape == (d,): # TODO: should this scale the off-diagonal?
376
+ factor = jnp.eye(d) * bw
377
+ elif shape == (d, d):
378
+ factor = bw
379
+ else:
380
+ msg = f"`bw` array shape should be ({d},) or ({d}, {d})."
381
+ raise ValueError(msg)
382
+
383
+ else:
384
+ msg = "`bw` should be 'scott', 'silverman', a scalar, or a callable."
385
+ raise ValueError(msg)
386
+
387
+ # Covariance
388
+ data_covariance = jnp.cov(dataset, rowvar=True, bias=False, aweights=weights)
389
+ covariance = jnp.atleast_2d(data_covariance) * factor**2
390
+ inv_cov = linalg.inv(covariance)
391
+
392
+ return covariance, inv_cov
393
+
394
+ # ====================================================================
395
+ # Helper methods
396
+
397
+ def _reshape_points(
398
+ self,
399
+ points: Float[Array, "F"] | Float[Array, "F data"],
400
+ ) -> Float[Array, "F data"]:
401
+ if jnp.issubdtype(lax.dtype(points), jnp.complexfloating):
402
+ msg = "gaussian_kde does not support complex coordinates"
403
+ raise NotImplementedError(msg)
404
+
405
+ points = jnp.atleast_2d(points)
406
+ d, m = points.shape
407
+ if d != self.d:
408
+ if d == 1 and m == self.d:
409
+ points = jnp.reshape(points, (self.d, 1))
410
+ else:
411
+ msg = f"points have dimension {d}, dataset has dimension {self.d}"
412
+ raise ValueError(msg)
413
+
414
+ return points
415
+
416
+
417
+ def gaussian_kde(
418
+ dataset: Dataset,
419
+ bw_method: BWMethodOpts = None,
420
+ weights: Weights | None = None,
421
+ ) -> MultiVariateGaussianKDE:
422
+ return MultiVariateGaussianKDE.from_bandwidth(
423
+ dataset,
424
+ bw=bw_method,
425
+ weights=weights,
426
+ )
427
+
428
+
429
+ # ====================================================================
430
+
431
+
432
+ def _gaussian_kernel_convolve(
433
+ chol: Array,
434
+ norm: Array,
435
+ target: Float[Array, "F N"],
436
+ weights: Weights,
437
+ mean: Float[Array, "F"],
438
+ ) -> Float[Array, "N"]:
439
+ diff = target - mean[:, None]
440
+ alpha = linalg.cho_solve(chol, diff)
441
+ arg = 0.5 * jnp.sum(diff * alpha, axis=0)
442
+ return norm * jnp.sum(jnp.exp(-arg) * weights)
443
+
444
+
445
+ @partial(jit, static_argnames=("in_log",))
446
+ def _gaussian_kernel_eval(
447
+ points: Float[Array, "data F"],
448
+ values: Float[Array, "N 1"],
449
+ xi: Float[Array, "data F"],
450
+ invcov: Cov,
451
+ *,
452
+ in_log: bool,
453
+ ) -> Float[Array, "data"]:
454
+ points, values, xi, invcov = promote_dtypes_inexact(points, values, xi, invcov)
455
+ d = points.shape[1]
456
+
457
+ if xi.shape[1] != d:
458
+ msg = "points and xi must have same trailing dim"
459
+ raise ValueError(msg)
460
+ if invcov.shape != (d, d):
461
+ msg = "precision matrix must match data dims"
462
+ raise ValueError(msg)
463
+
464
+ whitening = linalg.cholesky(invcov, lower=True)
465
+ points = jnp.dot(points, whitening)
466
+ xi = jnp.dot(xi, whitening)
467
+ log_norm = jnp.sum(jnp.log(jnp.diag(whitening))) - 0.5 * d * jnp.log(2 * np.pi)
468
+
469
+ def kernel(x_test: Array, x_train: Array, y_train: Array) -> Array:
470
+ arg = log_norm - 0.5 * jnp.sum(jnp.square(x_train - x_test))
471
+ if in_log:
472
+ return jnp.log(y_train) + arg
473
+ return y_train * jnp.exp(arg)
474
+
475
+ reduce = special.logsumexp if in_log else jnp.sum
476
+ reduced_kernel = lambda x: reduce( # noqa: E731
477
+ vmap(kernel, in_axes=(None, 0, 0))(x, points, values),
478
+ axis=0,
479
+ )
480
+ mapped_kernel = vmap(reduced_kernel)
481
+
482
+ return mapped_kernel(xi)
mvgkde/_version.py ADDED
@@ -0,0 +1,16 @@
1
+ # file generated by setuptools_scm
2
+ # don't change, don't track in version control
3
+ TYPE_CHECKING = False
4
+ if TYPE_CHECKING:
5
+ from typing import Tuple, Union
6
+ VERSION_TUPLE = Tuple[Union[int, str], ...]
7
+ else:
8
+ VERSION_TUPLE = object
9
+
10
+ version: str
11
+ __version__: str
12
+ __version_tuple__: VERSION_TUPLE
13
+ version_tuple: VERSION_TUPLE
14
+
15
+ __version__ = version = '0.1.0'
16
+ __version_tuple__ = version_tuple = (0, 1, 0)
mvgkde/_version.pyi ADDED
@@ -0,0 +1,2 @@
1
+ version: str
2
+ version_tuple: tuple[int, int, int] | tuple[int, int, int, str, str]
mvgkde/py.typed ADDED
File without changes
@@ -0,0 +1,376 @@
1
+ Metadata-Version: 2.3
2
+ Name: mvgkde
3
+ Version: 0.1.0
4
+ Summary: MultiVariate Gaussian Kernel Density Estimator
5
+ Project-URL: Homepage, https://github.com/nstarman/mvgkde
6
+ Project-URL: Bug Tracker, https://github.com/nstarman/mvgkde/issues
7
+ Project-URL: Changelog, https://github.com/nstarman/mvgkde/releases
8
+ Author-email: Nathaniel Starkman <nstarman@users.noreply.github.com>
9
+ License:
10
+ Apache License
11
+ Version 2.0, January 2004
12
+ http://www.apache.org/licenses/
13
+
14
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
15
+
16
+ 1. Definitions.
17
+
18
+ "License" shall mean the terms and conditions for use, reproduction,
19
+ and distribution as defined by Sections 1 through 9 of this document.
20
+
21
+ "Licensor" shall mean the copyright owner or entity authorized by
22
+ the copyright owner that is granting the License.
23
+
24
+ "Legal Entity" shall mean the union of the acting entity and all
25
+ other entities that control, are controlled by, or are under common
26
+ control with that entity. For the purposes of this definition,
27
+ "control" means (i) the power, direct or indirect, to cause the
28
+ direction or management of such entity, whether by contract or
29
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
30
+ outstanding shares, or (iii) beneficial ownership of such entity.
31
+
32
+ "You" (or "Your") shall mean an individual or Legal Entity
33
+ exercising permissions granted by this License.
34
+
35
+ "Source" form shall mean the preferred form for making modifications,
36
+ including but not limited to software source code, documentation
37
+ source, and configuration files.
38
+
39
+ "Object" form shall mean any form resulting from mechanical
40
+ transformation or translation of a Source form, including but
41
+ not limited to compiled object code, generated documentation,
42
+ and conversions to other media types.
43
+
44
+ "Work" shall mean the work of authorship, whether in Source or
45
+ Object form, made available under the License, as indicated by a
46
+ copyright notice that is included in or attached to the work
47
+ (an example is provided in the Appendix below).
48
+
49
+ "Derivative Works" shall mean any work, whether in Source or Object
50
+ form, that is based on (or derived from) the Work and for which the
51
+ editorial revisions, annotations, elaborations, or other modifications
52
+ represent, as a whole, an original work of authorship. For the purposes
53
+ of this License, Derivative Works shall not include works that remain
54
+ separable from, or merely link (or bind by name) to the interfaces of,
55
+ the Work and Derivative Works thereof.
56
+
57
+ "Contribution" shall mean any work of authorship, including
58
+ the original version of the Work and any modifications or additions
59
+ to that Work or Derivative Works thereof, that is intentionally
60
+ submitted to Licensor for inclusion in the Work by the copyright owner
61
+ or by an individual or Legal Entity authorized to submit on behalf of
62
+ the copyright owner. For the purposes of this definition, "submitted"
63
+ means any form of electronic, verbal, or written communication sent
64
+ to the Licensor or its representatives, including but not limited to
65
+ communication on electronic mailing lists, source code control systems,
66
+ and issue tracking systems that are managed by, or on behalf of, the
67
+ Licensor for the purpose of discussing and improving the Work, but
68
+ excluding communication that is conspicuously marked or otherwise
69
+ designated in writing by the copyright owner as "Not a Contribution."
70
+
71
+ "Contributor" shall mean Licensor and any individual or Legal Entity
72
+ on behalf of whom a Contribution has been received by Licensor and
73
+ subsequently incorporated within the Work.
74
+
75
+ 2. Grant of Copyright License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ copyright license to reproduce, prepare Derivative Works of,
79
+ publicly display, publicly perform, sublicense, and distribute the
80
+ Work and such Derivative Works in Source or Object form.
81
+
82
+ 3. Grant of Patent License. Subject to the terms and conditions of
83
+ this License, each Contributor hereby grants to You a perpetual,
84
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
85
+ (except as stated in this section) patent license to make, have made,
86
+ use, offer to sell, sell, import, and otherwise transfer the Work,
87
+ where such license applies only to those patent claims licensable
88
+ by such Contributor that are necessarily infringed by their
89
+ Contribution(s) alone or by combination of their Contribution(s)
90
+ with the Work to which such Contribution(s) was submitted. If You
91
+ institute patent litigation against any entity (including a
92
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
93
+ or a Contribution incorporated within the Work constitutes direct
94
+ or contributory patent infringement, then any patent licenses
95
+ granted to You under this License for that Work shall terminate
96
+ as of the date such litigation is filed.
97
+
98
+ 4. Redistribution. You may reproduce and distribute copies of the
99
+ Work or Derivative Works thereof in any medium, with or without
100
+ modifications, and in Source or Object form, provided that You
101
+ meet the following conditions:
102
+
103
+ (a) You must give any other recipients of the Work or
104
+ Derivative Works a copy of this License; and
105
+
106
+ (b) You must cause any modified files to carry prominent notices
107
+ stating that You changed the files; and
108
+
109
+ (c) You must retain, in the Source form of any Derivative Works
110
+ that You distribute, all copyright, patent, trademark, and
111
+ attribution notices from the Source form of the Work,
112
+ excluding those notices that do not pertain to any part of
113
+ the Derivative Works; and
114
+
115
+ (d) If the Work includes a "NOTICE" text file as part of its
116
+ distribution, then any Derivative Works that You distribute must
117
+ include a readable copy of the attribution notices contained
118
+ within such NOTICE file, excluding those notices that do not
119
+ pertain to any part of the Derivative Works, in at least one
120
+ of the following places: within a NOTICE text file distributed
121
+ as part of the Derivative Works; within the Source form or
122
+ documentation, if provided along with the Derivative Works; or,
123
+ within a display generated by the Derivative Works, if and
124
+ wherever such third-party notices normally appear. The contents
125
+ of the NOTICE file are for informational purposes only and
126
+ do not modify the License. You may add Your own attribution
127
+ notices within Derivative Works that You distribute, alongside
128
+ or as an addendum to the NOTICE text from the Work, provided
129
+ that such additional attribution notices cannot be construed
130
+ as modifying the License.
131
+
132
+ You may add Your own copyright statement to Your modifications and
133
+ may provide additional or different license terms and conditions
134
+ for use, reproduction, or distribution of Your modifications, or
135
+ for any such Derivative Works as a whole, provided Your use,
136
+ reproduction, and distribution of the Work otherwise complies with
137
+ the conditions stated in this License.
138
+
139
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
140
+ any Contribution intentionally submitted for inclusion in the Work
141
+ by You to the Licensor shall be under the terms and conditions of
142
+ this License, without any additional terms or conditions.
143
+ Notwithstanding the above, nothing herein shall supersede or modify
144
+ the terms of any separate license agreement you may have executed
145
+ with Licensor regarding such Contributions.
146
+
147
+ 6. Trademarks. This License does not grant permission to use the trade
148
+ names, trademarks, service marks, or product names of the Licensor,
149
+ except as required for reasonable and customary use in describing the
150
+ origin of the Work and reproducing the content of the NOTICE file.
151
+
152
+ 7. Disclaimer of Warranty. Unless required by applicable law or
153
+ agreed to in writing, Licensor provides the Work (and each
154
+ Contributor provides its Contributions) on an "AS IS" BASIS,
155
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
156
+ implied, including, without limitation, any warranties or conditions
157
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
158
+ PARTICULAR PURPOSE. You are solely responsible for determining the
159
+ appropriateness of using or redistributing the Work and assume any
160
+ risks associated with Your exercise of permissions under this License.
161
+
162
+ 8. Limitation of Liability. In no event and under no legal theory,
163
+ whether in tort (including negligence), contract, or otherwise,
164
+ unless required by applicable law (such as deliberate and grossly
165
+ negligent acts) or agreed to in writing, shall any Contributor be
166
+ liable to You for damages, including any direct, indirect, special,
167
+ incidental, or consequential damages of any character arising as a
168
+ result of this License or out of the use or inability to use the
169
+ Work (including but not limited to damages for loss of goodwill,
170
+ work stoppage, computer failure or malfunction, or any and all
171
+ other commercial damages or losses), even if such Contributor
172
+ has been advised of the possibility of such damages.
173
+
174
+ 9. Accepting Warranty or Additional Liability. While redistributing
175
+ the Work or Derivative Works thereof, You may choose to offer,
176
+ and charge a fee for, acceptance of support, warranty, indemnity,
177
+ or other liability obligations and/or rights consistent with this
178
+ License. However, in accepting such obligations, You may act only
179
+ on Your own behalf and on Your sole responsibility, not on behalf
180
+ of any other Contributor, and only if You agree to indemnify,
181
+ defend, and hold each Contributor harmless for any liability
182
+ incurred by, or claims asserted against, such Contributor by reason
183
+ of your accepting any such warranty or additional liability.
184
+
185
+ END OF TERMS AND CONDITIONS
186
+
187
+ APPENDIX: How to apply the Apache License to your work.
188
+
189
+ To apply the Apache License to your work, attach the following
190
+ boilerplate notice, with the fields enclosed by brackets "[]"
191
+ replaced with your own identifying information. (Don't include
192
+ the brackets!) The text should be enclosed in the appropriate
193
+ comment syntax for the file format. We also recommend that a
194
+ file or class name and description of purpose be included on the
195
+ same "printed page" as the copyright notice for easier
196
+ identification within third-party archives.
197
+
198
+ Copyright [yyyy] [name of copyright owner]
199
+
200
+ Licensed under the Apache License, Version 2.0 (the "License");
201
+ you may not use this file except in compliance with the License.
202
+ You may obtain a copy of the License at
203
+
204
+ http://www.apache.org/licenses/LICENSE-2.0
205
+
206
+ Unless required by applicable law or agreed to in writing, software
207
+ distributed under the License is distributed on an "AS IS" BASIS,
208
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
209
+ See the License for the specific language governing permissions and
210
+ limitations under the License.
211
+ License-File: LICENSE
212
+ License-File: NOTICE
213
+ Classifier: Development Status :: 3 - Alpha
214
+ Classifier: Intended Audience :: Developers
215
+ Classifier: Intended Audience :: Science/Research
216
+ Classifier: License :: OSI Approved :: Apache Software License
217
+ Classifier: Operating System :: OS Independent
218
+ Classifier: Programming Language :: Python
219
+ Classifier: Programming Language :: Python :: 3
220
+ Classifier: Programming Language :: Python :: 3 :: Only
221
+ Classifier: Programming Language :: Python :: 3.11
222
+ Classifier: Programming Language :: Python :: 3.12
223
+ Classifier: Programming Language :: Python :: 3.13
224
+ Classifier: Topic :: Scientific/Engineering
225
+ Classifier: Typing :: Typed
226
+ Requires-Python: >=3.11
227
+ Requires-Dist: jax>=0.4.35
228
+ Requires-Dist: jaxlib>=0.4.35
229
+ Requires-Dist: jaxtyping>=0.2.34
230
+ Requires-Dist: numpy>=2.1.2
231
+ Provides-Extra: dev
232
+ Requires-Dist: hypothesis>=6.115.4; extra == 'dev'
233
+ Requires-Dist: pytest-cov>=3; extra == 'dev'
234
+ Requires-Dist: pytest>=6; extra == 'dev'
235
+ Provides-Extra: test
236
+ Requires-Dist: hypothesis>=6.115.4; extra == 'test'
237
+ Requires-Dist: pytest-cov>=3; extra == 'test'
238
+ Requires-Dist: pytest>=6; extra == 'test'
239
+ Description-Content-Type: text/markdown
240
+
241
+ <h1 align='center'> <code>mvgkde</code> </h1>
242
+ <h3 align="center">MultiVariate Gaussian Kernel Density Estimator in JAX.</h3>
243
+
244
+ This is a micro-package, containing the single class `MultiVarGaussianKDE` (and
245
+ helper function `gaussian_kde`) to estimate the probability density function of
246
+ a multivariate dataset using a Gaussian kernel. This package modifies the
247
+ `jax.scipy.gaussian_kde` class (which is based on the `scipy.stats.gaussian_kde`
248
+ class), but allows for full control over the covariance matrix of the kernel,
249
+ even per-dimension bandwidths. See the Documentation below for more information.
250
+
251
+ ## Installation
252
+
253
+ [![PyPI version][pypi-version]][pypi-link]
254
+ [![PyPI platforms][pypi-platforms]][pypi-link]
255
+
256
+ ```bash
257
+ pip install mvgkde
258
+ ```
259
+
260
+ ## Documentation
261
+
262
+ [![Actions Status][actions-badge]][actions-link]
263
+
264
+ For these examples we will use the following imports:
265
+
266
+ ```python
267
+ import jax.numpy as jnp
268
+ import jax.random as jr
269
+ import matplotlib.pyplot as plt
270
+ import numpy as np
271
+
272
+ from mvgkde import MultiVariateGaussianKDE, gaussian_kde # This package
273
+ ```
274
+
275
+ And we will generate a dataset to work with:
276
+
277
+ ```python
278
+ key = jr.key(0)
279
+ dataset = jr.normal(key, (2, 1000))
280
+ ```
281
+
282
+ Lastly we will define a plotting function:
283
+
284
+ ```python
285
+ # Create a grid of points
286
+ (xmin, ymin) = dataset.min(axis=1)
287
+ (xmax, ymax) = dataset.max(axis=1)
288
+ X, Y = np.mgrid[xmin:xmax:100j, ymin:ymax:100j]
289
+ positions = np.vstack([X.ravel(), Y.ravel()])
290
+
291
+
292
+ def plot_kde(kde: MultiVariateGaussianKDE) -> plt.Figure:
293
+ # Evaluate the KDE on the grid
294
+ Z = np.reshape(kde(positions).T, X.shape)
295
+
296
+ # Plot the results
297
+ fig, ax = plt.subplots()
298
+ ax.imshow(np.rot90(Z), cmap=plt.cm.gist_earth_r, extent=[xmin, xmax, ymin, ymax])
299
+ ax.plot(dataset[0], dataset[1], "k.", markersize=2)
300
+ ax.set(
301
+ title="2D Kernel Density Estimation using JAX",
302
+ xlabel="X-axis",
303
+ xlim=[xmin, xmax],
304
+ ylabel="Y-axis",
305
+ ylim=[ymin, ymax],
306
+ )
307
+
308
+ return fig
309
+ ```
310
+
311
+ Here's an example that can be done with `jax.scipy.gaussian_kde`:
312
+
313
+ ```python
314
+ kde = gaussian_kde(dataset, bw="scott")
315
+
316
+ fig = plot_kde(kde)
317
+ plt.show()
318
+ ```
319
+
320
+ ![Scotts Rule](docs/bw_scott.png)
321
+
322
+ Here's an example with a per-dimension bandwidth. This is not possible with the
323
+ `jax.scipy.gaussian_kde`:
324
+
325
+ ```python
326
+ kde = gaussian_kde(dataset, bw=jnp.array([0.15, 1.3]))
327
+
328
+ fig = plot_kde(kde)
329
+ plt.show()
330
+ ```
331
+
332
+ ![Per-Dimension Bandwidth](docs/bw_perdim.png)
333
+
334
+ Lastly, here's an example with 2D bandwidth matrix:
335
+
336
+ ```python
337
+ bw = jnp.array([[0.15, 3], [3, 1.3]])
338
+ kde = gaussian_kde(dataset, bw=bw)
339
+
340
+ fig = plot_kde(kde)
341
+ plt.show()
342
+ ```
343
+
344
+ ![2D Bandwidth Matrix](docs/bw_matrix.png)
345
+
346
+ The previous examples are using the convenience function `gaussian_kde`. This
347
+ actually just calls the constructor method
348
+ `MultiVariateGaussianKDE.from_bandwidth`. This function allows for customixing
349
+ the bandwidth factor on the data-driven covariance matrix, but does not allow
350
+ for specifying the covariance matrix directly. To do that, you can call the
351
+ `MultiVariateGaussianKDE` constructor directly, or the `from_covariance`
352
+ constructor method. To illustrate the difference between modifying the bandwidth
353
+ and setting the full covariance matrix, consider the following example:
354
+
355
+ ```python
356
+ kde = MultiVariateGaussianKDE.from_covariance(
357
+ dataset,
358
+ jnp.array([[0.15, 0.1], [0.1, 1.3]]),
359
+ )
360
+
361
+ fig = plot_kde(kde)
362
+ plt.show()
363
+ ```
364
+
365
+ ![Covariance Matrix](docs/cov.png)
366
+
367
+ ## Acknowledgments
368
+
369
+ This package modifies code from [JAX](https://github.com/google/jax), which is
370
+ licensed under the Apache License 2.0.
371
+
372
+ [actions-badge]: https://github.com/nstarman/mvgkde/workflows/CI/badge.svg
373
+ [actions-link]: https://github.com/nstarman/mvgkde/actions
374
+ [pypi-link]: https://pypi.org/project/mvgkde/
375
+ [pypi-platforms]: https://img.shields.io/pypi/pyversions/mvgkde
376
+ [pypi-version]: https://img.shields.io/pypi/v/mvgkde
@@ -0,0 +1,10 @@
1
+ mvgkde/__init__.py,sha256=Qdf8oewKNVcus_UNjecOJ2j5nPAwbZjuFz_F3wy02Po,262
2
+ mvgkde/_core.py,sha256=qQ9NSaRqALe3p_j9xezLivXnHUrVdAXyxKKuDXInLXs,16073
3
+ mvgkde/_version.py,sha256=IMl2Pr_Sy4LVRKy_Sm4CdwUl1Gryous6ncL96EMYsnM,411
4
+ mvgkde/_version.pyi,sha256=o7uNL6MhuJoiqpEnriU7rBT6TmkJZA-i2qMoNz9YcgQ,82
5
+ mvgkde/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ mvgkde-0.1.0.dist-info/METADATA,sha256=F9fPMkhb3T3yNJrJdN7W1ONxGpOBuXD40FFVP1oJWb0,18319
7
+ mvgkde-0.1.0.dist-info/WHEEL,sha256=1yFddiXMmvYK7QYTqtRNtX66WJ0Mz8PYEiEUoOUUxRY,87
8
+ mvgkde-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
9
+ mvgkde-0.1.0.dist-info/licenses/NOTICE,sha256=vTXZ9TjDFTpITpvdV2_BFJiQmANJXirSnhR15hOdY-E,183
10
+ mvgkde-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.25.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,5 @@
1
+ This software modifies code from following third-party software:
2
+
3
+ - JAX (https://github.com/google/jax)
4
+ Copyright 2018 Google LLC.
5
+ Licensed under the Apache License, Version 2.0.