diff --git a/.gitattributes b/.gitattributes index b9be204283f1f3527985feb873c12f2ac212299a..8bd76f413b32d999a8ec45f65490f1bce3e676df 100644 --- a/.gitattributes +++ b/.gitattributes @@ -777,3 +777,39 @@ shared/package-files/a9/a9d8cb904b2e9c8e9050b9a5c6fbaa23ed1787b4d05f11652e384045 shared/package-files/a9/a9e6b812a5a9ffe44a8962c3fd10fa53679fbc5952bd02abf02c55d7d73c4aad/blob filter=lfs diff=lfs merge=lfs -text shared/package-files/aa/aa4b82cca13d02f1f088c9e02e13af5151df9af92fe788b9fe2a36ce9dc808cd/blob filter=lfs diff=lfs merge=lfs -text shared/package-files/ab/ab1175f9ef7ed52106ce1127b7da91bfc3d91782c0a2fec2f8189f661e3679db/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/ab/ab2f91050f5a4ea97e09dce3855f7e6c2d1e6b1153dbb2adab14d0f089137260/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/ab/ab656e5e6759a61c81d95347eaa4a70cc59262878f291b267e08ba5b4f675f7d/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/ab/ab7c6a6fe1688a764fa48f8e18e5ebb9f150f19e8df09877d52646e5418bc246/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/ab/ab9388f413a20efd0857000f57c3921c5c7d7ebe07fc832f03f350f150423d4d/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/ab/abac8a45936f393a2c856af7434382b18276337c969a082c82a4f94ca716139e/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/ab/abd0feb59c961d9d9330d5bbe09dbc9e7b35347a8c7b2f2554813839ad590be3/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/ac/ac1eac9fced06aa971538f9436cbaa30e803cf37da881af3cddecdfdfced81cb/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/ac/ac5bd929d122652da56b9a23666429b5a52ff6a57f7620873abff4f78604ae0e/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/ac/ac8785903ed669a9962b7a837efb02bffeea43e9552e5b047b39505b7a583d60/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/ac/acc7bc91df0cedee35d24e5191cb48965806822fbfc4aea4da559f7435ab1841/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/ac/accac55bb262559affdbdb37a7028ff71c2679b3a74fd41e14d5d8208004e47e/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/ad/ad148328c5565076b4e985a41cc8498b7d82dda5a524c98b0934b9808d9cf80e/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/ad/adc4278e12e6f397b91bd3d77aa36a90c0fa73ffa7c36d4d663e27aa0d1907cb/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/ad/adc88690bcc3b1bfde01a3375879a78677c72e5cc331566627f47343313881a9/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/ad/addb6c696bc426f5a12deb1646a9c3b3286da178ef396a4a452744db3ea8c8fc/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/ae/ae10677466af541293ad126deba26286d35619dcb31639f00c7dc18dad5b4a13/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/ae/ae304da2366a5c08ae8148953dd1db095d39587c5c3d1d1d6438bfba175ce7c4/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/ae/ae31aa6f3c2b75e1eeb8294fec685c08941f11cf93a6e914ebb20ff43ae927c0/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/af/af2aaf48e18405dda1f392cbb0aa8cb8fe017e69d679caa9d9047d9aca0d0b3b/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/af/af90703e8c7aaddc43931e06e3ad03e5f160af9ec09c3855b3f5915b6c6f50cc/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/af/afab6df9a91b20a43fa0519d98436d2451711a585357caf7605a6228fac4bdc2/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/af/aff1358de79d3105038dfe6075853ad73ac9d0ec332f749e1b595e91fb85c13c/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/b0/b04b8c9d3fbcc1eb8a9db3b595659d5ed1b032e45060b8d2655405f220a8c933/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/b0/b05c67a1ceb3ca6f5caec89575ecad39725261fcd722f304fce8cdd2fa278999/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/b0/b0dcb85c17e1f35a460118de33ee035ed288899f2a982f9ec6d5a9c96525fd40/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/b1/b14af618690aeac35a23470fb0f8e1c3fca9f45f8d824a69d35eec4c6f1dca75/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/b1/b184b89e3c1075f22f6b71575b6fc20d4972b3cfd3b23322ca6fd596dcaef167/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/b1/b193cd7a47da341642e077b719c85e4c42efaed460527531a53a4621c9c41428/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/b1/b1cde583d76b3acaf6928648846f24d12e243799fd33870dcb8ba821a42e2db2/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/b1/b1d9c359af694c5c58042042b76dcda012f3873541ea895c03da24edda9a9847/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/b2/b20f2181780cdd883655488ce174a61425881ff8a2c2d3b2ebf40433fda72926/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/b2/b21bae3804b4066b4d1e50f4876126c01d69e72486689a726c4122476b774e33/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/b2/b22029d6f530c68a9737fb5394e779ffd3c221b6e53900aa84ea65429bdd18f1/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/b2/b2337523b68fbff0cbbed588b0a2e3e95057230f7ce0a4814ab3482738a85546/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/b2/b23879d49e9b2b7dd3c7ff153fa050dab48499715b971a6ff3708840d891d188/blob filter=lfs diff=lfs merge=lfs -text +shared/package-files/b2/b2db8e0e933034f7fe13e2cc7cc35ad58e265af8ae222af3add973045443d8f4/blob filter=lfs diff=lfs merge=lfs -text diff --git a/shared/package-files/ab/ab29fb90fe5bd78332c2da8e50be42f8d3af8dfdaa2b83ec5c6a42bea9a8fb81/blob b/shared/package-files/ab/ab29fb90fe5bd78332c2da8e50be42f8d3af8dfdaa2b83ec5c6a42bea9a8fb81/blob new file mode 100644 index 0000000000000000000000000000000000000000..13dc82d779f953fbea54323785bdcadc3e24dfd8 --- /dev/null +++ b/shared/package-files/ab/ab29fb90fe5bd78332c2da8e50be42f8d3af8dfdaa2b83ec5c6a42bea9a8fb81/blob @@ -0,0 +1,14 @@ +import numpy as np + +from pandas.core.dtypes.cast import dict_compat + +from pandas import Timestamp + + +def test_dict_compat(): + data_datetime64 = {np.datetime64("1990-03-15"): 1, np.datetime64("2015-03-15"): 2} + data_unchanged = {1: 2, 3: 4, 5: 6} + expected = {Timestamp("1990-3-15"): 1, Timestamp("2015-03-15"): 2} + assert dict_compat(data_datetime64) == expected + assert dict_compat(expected) == expected + assert dict_compat(data_unchanged) == data_unchanged diff --git a/shared/package-files/ab/ab2d0f9637b9209bafb020637a32728430a310075c0cb2bfd9a81571ec7c67a5/blob b/shared/package-files/ab/ab2d0f9637b9209bafb020637a32728430a310075c0cb2bfd9a81571ec7c67a5/blob new file mode 100644 index 0000000000000000000000000000000000000000..75bf729258f9daef77370b6df1a57940f90fc23f --- /dev/null +++ b/shared/package-files/ab/ab2d0f9637b9209bafb020637a32728430a310075c0cb2bfd9a81571ec7c67a5/blob @@ -0,0 +1 @@ +markupsafe diff --git a/shared/package-files/ab/ab2f91050f5a4ea97e09dce3855f7e6c2d1e6b1153dbb2adab14d0f089137260/blob b/shared/package-files/ab/ab2f91050f5a4ea97e09dce3855f7e6c2d1e6b1153dbb2adab14d0f089137260/blob new file mode 100644 index 0000000000000000000000000000000000000000..1951fb49e77e129f5c1827bcb8db32804aff9b59 --- /dev/null +++ b/shared/package-files/ab/ab2f91050f5a4ea97e09dce3855f7e6c2d1e6b1153dbb2adab14d0f089137260/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab2f91050f5a4ea97e09dce3855f7e6c2d1e6b1153dbb2adab14d0f089137260 +size 24879987 diff --git a/shared/package-files/ab/ab31b0b56d7242624b62e8303f0ea97af46656dc5820e3fe5228ab2e22e11ed8/blob b/shared/package-files/ab/ab31b0b56d7242624b62e8303f0ea97af46656dc5820e3fe5228ab2e22e11ed8/blob new file mode 100644 index 0000000000000000000000000000000000000000..107e03622fe12d7350d18521319b57803940ce59 --- /dev/null +++ b/shared/package-files/ab/ab31b0b56d7242624b62e8303f0ea97af46656dc5820e3fe5228ab2e22e11ed8/blob @@ -0,0 +1,30 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_print(str s) -> () +inline void _print(c10::string_view s) { + return at::_ops::_print::call(s); +} + +} diff --git a/shared/package-files/ab/ab33bc51cb9f5ab60c758444206dc7d2bbad93ddb61bede0b82e33349a161652/blob b/shared/package-files/ab/ab33bc51cb9f5ab60c758444206dc7d2bbad93ddb61bede0b82e33349a161652/blob new file mode 100644 index 0000000000000000000000000000000000000000..a53bcea61248bf0c74654c658cb4abc8044a1f33 --- /dev/null +++ b/shared/package-files/ab/ab33bc51cb9f5ab60c758444206dc7d2bbad93ddb61bede0b82e33349a161652/blob @@ -0,0 +1,92 @@ +from typing import Any, Optional + +class BaseCache: + default_timeout: float + def __init__(self, default_timeout: float = ...): ... + def get(self, key): ... + def delete(self, key): ... + def get_many(self, *keys): ... + def get_dict(self, *keys): ... + def set(self, key, value, timeout: Optional[float] = ...): ... + def add(self, key, value, timeout: Optional[float] = ...): ... + def set_many(self, mapping, timeout: Optional[float] = ...): ... + def delete_many(self, *keys): ... + def has(self, key): ... + def clear(self): ... + def inc(self, key, delta=...): ... + def dec(self, key, delta=...): ... + +class NullCache(BaseCache): ... + +class SimpleCache(BaseCache): + clear: Any + def __init__(self, threshold: int = ..., default_timeout: float = ...): ... + def get(self, key): ... + def set(self, key, value, timeout: Optional[float] = ...): ... + def add(self, key, value, timeout: Optional[float] = ...): ... + def delete(self, key): ... + def has(self, key): ... + +class MemcachedCache(BaseCache): + key_prefix: Any + def __init__(self, servers: Optional[Any] = ..., default_timeout: float = ..., key_prefix: Optional[Any] = ...): ... + def get(self, key): ... + def get_dict(self, *keys): ... + def add(self, key, value, timeout: Optional[float] = ...): ... + def set(self, key, value, timeout: Optional[float] = ...): ... + def get_many(self, *keys): ... + def set_many(self, mapping, timeout: Optional[float] = ...): ... + def delete(self, key): ... + def delete_many(self, *keys): ... + def has(self, key): ... + def clear(self): ... + def inc(self, key, delta=...): ... + def dec(self, key, delta=...): ... + def import_preferred_memcache_lib(self, servers): ... + +GAEMemcachedCache: Any + +class RedisCache(BaseCache): + key_prefix: Any + def __init__( + self, + host: str = ..., + port: int = ..., + password: Optional[Any] = ..., + db: int = ..., + default_timeout: float = ..., + key_prefix: Optional[Any] = ..., + **kwargs, + ): ... + def dump_object(self, value): ... + def load_object(self, value): ... + def get(self, key): ... + def get_many(self, *keys): ... + def set(self, key, value, timeout: Optional[float] = ...): ... + def add(self, key, value, timeout: Optional[float] = ...): ... + def set_many(self, mapping, timeout: Optional[float] = ...): ... + def delete(self, key): ... + def delete_many(self, *keys): ... + def has(self, key): ... + def clear(self): ... + def inc(self, key, delta=...): ... + def dec(self, key, delta=...): ... + +class FileSystemCache(BaseCache): + def __init__(self, cache_dir, threshold: int = ..., default_timeout: float = ..., mode: int = ...): ... + def clear(self): ... + def get(self, key): ... + def add(self, key, value, timeout: Optional[float] = ...): ... + def set(self, key, value, timeout: Optional[float] = ...): ... + def delete(self, key): ... + def has(self, key): ... + +class UWSGICache(BaseCache): + cache: Any + def __init__(self, default_timeout: float = ..., cache: str = ...): ... + def get(self, key): ... + def delete(self, key): ... + def set(self, key, value, timeout: Optional[float] = ...): ... + def add(self, key, value, timeout: Optional[float] = ...): ... + def clear(self): ... + def has(self, key): ... diff --git a/shared/package-files/ab/ab34cb487f0fbc0918d5fafa410daf57e2b013f33cdf0757ba0b6925a3ff01b3/blob b/shared/package-files/ab/ab34cb487f0fbc0918d5fafa410daf57e2b013f33cdf0757ba0b6925a3ff01b3/blob new file mode 100644 index 0000000000000000000000000000000000000000..59930f455b0a288e958f8ae4564b02b49b8e2f9f --- /dev/null +++ b/shared/package-files/ab/ab34cb487f0fbc0918d5fafa410daf57e2b013f33cdf0757ba0b6925a3ff01b3/blob @@ -0,0 +1,13 @@ +"""Verify certificates using native system trust stores""" + +import sys as _sys + +if _sys.version_info < (3, 10): + raise ImportError("truststore requires Python 3.10 or later") + +from ._api import SSLContext, extract_from_ssl, inject_into_ssl # noqa: E402 + +del _api, _sys # type: ignore[name-defined] # noqa: F821 + +__all__ = ["SSLContext", "inject_into_ssl", "extract_from_ssl"] +__version__ = "0.8.0" diff --git a/shared/package-files/ab/ab370113df1c83c4f1e623c902f4383dd7f6c9ce91dabfb8c86252d7f0c421e6/blob b/shared/package-files/ab/ab370113df1c83c4f1e623c902f4383dd7f6c9ce91dabfb8c86252d7f0c421e6/blob new file mode 100644 index 0000000000000000000000000000000000000000..5b80e19d896b746ccc4318bb2f8ce250c7892e66 --- /dev/null +++ b/shared/package-files/ab/ab370113df1c83c4f1e623c902f4383dd7f6c9ce91dabfb8c86252d7f0c421e6/blob @@ -0,0 +1,35 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include +#include + +#include "arrow/util/visibility.h" + +namespace arrow { +namespace util { + +ARROW_EXPORT +std::string base64_encode(std::string_view s); + +ARROW_EXPORT +std::string base64_decode(std::string_view s); + +} // namespace util +} // namespace arrow diff --git a/shared/package-files/ab/ab371cec1a3839605762ccb229d0c9c1d4d1b2d32a075673d0688662d9dd0671/blob b/shared/package-files/ab/ab371cec1a3839605762ccb229d0c9c1d4d1b2d32a075673d0688662d9dd0671/blob new file mode 100644 index 0000000000000000000000000000000000000000..562b0b2c53d8684fcb2b0417bad36877d92af53e Binary files /dev/null and b/shared/package-files/ab/ab371cec1a3839605762ccb229d0c9c1d4d1b2d32a075673d0688662d9dd0671/blob differ diff --git a/shared/package-files/ab/ab39c873e7fe1837175fd4cd11e75998528d80dae755cb78e74bfae94c99a183/blob b/shared/package-files/ab/ab39c873e7fe1837175fd4cd11e75998528d80dae755cb78e74bfae94c99a183/blob new file mode 100644 index 0000000000000000000000000000000000000000..0dbb2d20f7617129a8a28810ce0fd55741f85005 Binary files /dev/null and b/shared/package-files/ab/ab39c873e7fe1837175fd4cd11e75998528d80dae755cb78e74bfae94c99a183/blob differ diff --git a/shared/package-files/ab/ab3b9a3943b225f4cffa590cdef6419d5aac1a2623ca96eb01348cff1ee61029/model_config.json b/shared/package-files/ab/ab3b9a3943b225f4cffa590cdef6419d5aac1a2623ca96eb01348cff1ee61029/model_config.json new file mode 100644 index 0000000000000000000000000000000000000000..6016a7180610242fa62ec08d133505f354abcfe4 --- /dev/null +++ b/shared/package-files/ab/ab3b9a3943b225f4cffa590cdef6419d5aac1a2623ca96eb01348cff1ee61029/model_config.json @@ -0,0 +1,103 @@ +{ + "fingerprint": "Morgan4096-radius2", + "inference_workers": 4, + "mass_coefficient": 0.05, + "mass_parameters": { + "all": { + "offset": 0.0017379104733558116, + "scale": 0.22784726949100334 + }, + "[M+H]+": { + "offset": 0.0026598596314496036, + "scale": 0.15197921970275186 + }, + "[M+H]+|CE_known": { + "offset": -7.5456039222815375e-06, + "scale": 0.1 + }, + "[M+H]+ Orbitrap|CE_known": { + "offset": -0.0012137828913790357, + "scale": 0.1 + }, + "[M+H]+|CE_missing": { + "offset": 0.34631438891746547, + "scale": 1.2049855792590873 + }, + "[M+H]+ QTOF|CE_missing": { + "offset": 0.31476867963403604, + "scale": 1.1661727787433172 + }, + "[M+H]+ |CE_missing": { + "offset": -0.07318393565829291, + "scale": 0.9669946819840058 + }, + "[M+H]+ Orbitrap|CE_missing": { + "offset": 0.4053671391343552, + "scale": 1.2247049028286892 + }, + "[M+Na]+": { + "offset": -0.18138664899886367, + "scale": 2.7908660677201578 + }, + "[M+Na]+|CE_known": { + "offset": -0.01708129304095346, + "scale": 0.1 + }, + "[M+Na]+ Orbitrap|CE_known": { + "offset": -0.010102936926932657, + "scale": 0.1 + }, + "[M+Na]+|CE_missing": { + "offset": -0.32485984366270015, + "scale": 3.2315997762307016 + }, + "[M+Na]+ |CE_missing": { + "offset": -0.0487177506227377, + "scale": 0.5698143697858935 + }, + "[M+Na]+ Orbitrap|CE_missing": { + "offset": -0.438501156388837, + "scale": 4.0867859774060795 + }, + "[M+Na]+ QTOF|CE_missing": { + "offset": 0.005669038371233242, + "scale": 0.551818998766307 + }, + "[M+Na]+ QTOF|CE_known": { + "offset": -0.09100474226353564, + "scale": 0.6701640150891102 + }, + "[M+H]+ QTOF|CE_known": { + "offset": 6.490960030784106e-05, + "scale": 0.1 + } + }, + "ion_masses": { + "[M+H]+": 1.007276466621, + "[M+Na]+": 22.989220702091 + }, + "mass_conditioning": "energy_presence", + "method": "equal-weight-peak-ensemble", + "score": "cosine_idf_cauchy_mass", + "ensemble_rule": "mean_probabilities", + "members": [ + { + "width": 384, + "depth": 4, + "dropout": 0.1, + "feature_version": "peak-transformer-fine-mass-defect-v1", + "max_peaks": 64, + "fingerprint": "Morgan4096-radius2", + "score": "cosine_sigmoid" + }, + { + "width": 384, + "depth": 4, + "dropout": 0.1, + "feature_version": "peak-transformer-fine-mass-defect-v1", + "max_peaks": 10, + "fingerprint": "Morgan4096-radius2", + "score": "cosine_sigmoid" + } + ] +} \ No newline at end of file diff --git a/shared/package-files/ab/ab3d06b221fb6fab018eb20d80fd8b3004746a4e8c93300333f1086dadba26c1/blob b/shared/package-files/ab/ab3d06b221fb6fab018eb20d80fd8b3004746a4e8c93300333f1086dadba26c1/blob new file mode 100644 index 0000000000000000000000000000000000000000..e9036a46cb1f80e39f741ad7e3160cecc4615935 --- /dev/null +++ b/shared/package-files/ab/ab3d06b221fb6fab018eb20d80fd8b3004746a4e8c93300333f1086dadba26c1/blob @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor fft_irfft(const at::Tensor & self, c10::optional n=c10::nullopt, int64_t dim=-1, c10::optional norm=c10::nullopt); +TORCH_API at::Tensor fft_irfft_symint(const at::Tensor & self, c10::optional n=c10::nullopt, int64_t dim=-1, c10::optional norm=c10::nullopt); +TORCH_API at::Tensor & fft_irfft_out(at::Tensor & out, const at::Tensor & self, c10::optional n=c10::nullopt, int64_t dim=-1, c10::optional norm=c10::nullopt); +TORCH_API at::Tensor & fft_irfft_outf(const at::Tensor & self, c10::optional n, int64_t dim, c10::optional norm, at::Tensor & out); +TORCH_API at::Tensor & fft_irfft_symint_out(at::Tensor & out, const at::Tensor & self, c10::optional n=c10::nullopt, int64_t dim=-1, c10::optional norm=c10::nullopt); +TORCH_API at::Tensor & fft_irfft_symint_outf(const at::Tensor & self, c10::optional n, int64_t dim, c10::optional norm, at::Tensor & out); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/shared/package-files/ab/ab3d3254c6f895611e3930cbfc35b3e6ee5ac261883ca02cb991495e0c0724d5/blob b/shared/package-files/ab/ab3d3254c6f895611e3930cbfc35b3e6ee5ac261883ca02cb991495e0c0724d5/blob new file mode 100644 index 0000000000000000000000000000000000000000..1e198697fa042b7cc8bcba9e9e770f5c8106dad6 --- /dev/null +++ b/shared/package-files/ab/ab3d3254c6f895611e3930cbfc35b3e6ee5ac261883ca02cb991495e0c0724d5/blob @@ -0,0 +1,1431 @@ +r""" +Elliptic functions historically comprise the elliptic integrals +and their inverses, and originate from the problem of computing the +arc length of an ellipse. From a more modern point of view, +an elliptic function is defined as a doubly periodic function, i.e. +a function which satisfies + +.. math :: + + f(z + 2 \omega_1) = f(z + 2 \omega_2) = f(z) + +for some half-periods `\omega_1, \omega_2` with +`\mathrm{Im}[\omega_1 / \omega_2] > 0`. The canonical elliptic +functions are the Jacobi elliptic functions. More broadly, this section +includes quasi-doubly periodic functions (such as the Jacobi theta +functions) and other functions useful in the study of elliptic functions. + +Many different conventions for the arguments of +elliptic functions are in use. It is even standard to use +different parameterizations for different functions in the same +text or software (and mpmath is no exception). +The usual parameters are the elliptic nome `q`, which usually +must satisfy `|q| < 1`; the elliptic parameter `m` (an arbitrary +complex number); the elliptic modulus `k` (an arbitrary complex +number); and the half-period ratio `\tau`, which usually must +satisfy `\mathrm{Im}[\tau] > 0`. +These quantities can be expressed in terms of each other +using the following relations: + +.. math :: + + m = k^2 + +.. math :: + + \tau = i \frac{K(1-m)}{K(m)} + +.. math :: + + q = e^{i \pi \tau} + +.. math :: + + k = \frac{\vartheta_2^2(q)}{\vartheta_3^2(q)} + +In addition, an alternative definition is used for the nome in +number theory, which we here denote by q-bar: + +.. math :: + + \bar{q} = q^2 = e^{2 i \pi \tau} + +For convenience, mpmath provides functions to convert +between the various parameters (:func:`~mpmath.qfrom`, :func:`~mpmath.mfrom`, +:func:`~mpmath.kfrom`, :func:`~mpmath.taufrom`, :func:`~mpmath.qbarfrom`). + +**References** + +1. [AbramowitzStegun]_ + +2. [WhittakerWatson]_ + +""" + +from .functions import defun, defun_wrapped + +@defun_wrapped +def eta(ctx, tau): + r""" + Returns the Dedekind eta function of tau in the upper half-plane. + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> eta(1j); gamma(0.25) / (2*pi**0.75) + (0.7682254223260566590025942 + 0.0j) + 0.7682254223260566590025942 + >>> tau = sqrt(2) + sqrt(5)*1j + >>> eta(-1/tau); sqrt(-1j*tau) * eta(tau) + (0.9022859908439376463573294 + 0.07985093673948098408048575j) + (0.9022859908439376463573295 + 0.07985093673948098408048575j) + >>> eta(tau+1); exp(pi*1j/12) * eta(tau) + (0.4493066139717553786223114 + 0.3290014793877986663915939j) + (0.4493066139717553786223114 + 0.3290014793877986663915939j) + >>> f = lambda z: diff(eta, z) / eta(z) + >>> chop(36*diff(f,tau)**2 - 24*diff(f,tau,2)*f(tau) + diff(f,tau,3)) + 0.0 + + """ + if ctx.im(tau) <= 0.0: + raise ValueError("eta is only defined in the upper half-plane") + q = ctx.expjpi(tau/12) + return q * ctx.qp(q**24) + +def nome(ctx, m): + m = ctx.convert(m) + if not m: + return m + if m == ctx.one: + return m + if ctx.isnan(m): + return m + if ctx.isinf(m): + if m == ctx.ninf: + return type(m)(-1) + else: + return ctx.mpc(-1) + a = ctx.ellipk(ctx.one-m) + b = ctx.ellipk(m) + v = ctx.exp(-ctx.pi*a/b) + if not ctx._im(m) and ctx._re(m) < 1: + if ctx._is_real_type(m): + return v.real + else: + return v.real + 0j + elif m == 2: + v = ctx.mpc(0, v.imag) + return v + +@defun_wrapped +def qfrom(ctx, q=None, m=None, k=None, tau=None, qbar=None): + r""" + Returns the elliptic nome `q`, given any of `q, m, k, \tau, \bar{q}`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> qfrom(q=0.25) + 0.25 + >>> qfrom(m=mfrom(q=0.25)) + 0.25 + >>> qfrom(k=kfrom(q=0.25)) + 0.25 + >>> qfrom(tau=taufrom(q=0.25)) + (0.25 + 0.0j) + >>> qfrom(qbar=qbarfrom(q=0.25)) + 0.25 + + """ + if q is not None: + return ctx.convert(q) + if m is not None: + return nome(ctx, m) + if k is not None: + return nome(ctx, ctx.convert(k)**2) + if tau is not None: + return ctx.expjpi(tau) + if qbar is not None: + return ctx.sqrt(qbar) + +@defun_wrapped +def qbarfrom(ctx, q=None, m=None, k=None, tau=None, qbar=None): + r""" + Returns the number-theoretic nome `\bar q`, given any of + `q, m, k, \tau, \bar{q}`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> qbarfrom(qbar=0.25) + 0.25 + >>> qbarfrom(q=qfrom(qbar=0.25)) + 0.25 + >>> qbarfrom(m=extraprec(20)(mfrom)(qbar=0.25)) # ill-conditioned + 0.25 + >>> qbarfrom(k=extraprec(20)(kfrom)(qbar=0.25)) # ill-conditioned + 0.25 + >>> qbarfrom(tau=taufrom(qbar=0.25)) + (0.25 + 0.0j) + + """ + if qbar is not None: + return ctx.convert(qbar) + if q is not None: + return ctx.convert(q) ** 2 + if m is not None: + return nome(ctx, m) ** 2 + if k is not None: + return nome(ctx, ctx.convert(k)**2) ** 2 + if tau is not None: + return ctx.expjpi(2*tau) + +@defun_wrapped +def taufrom(ctx, q=None, m=None, k=None, tau=None, qbar=None): + r""" + Returns the elliptic half-period ratio `\tau`, given any of + `q, m, k, \tau, \bar{q}`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> taufrom(tau=0.5j) + (0.0 + 0.5j) + >>> taufrom(q=qfrom(tau=0.5j)) + (0.0 + 0.5j) + >>> taufrom(m=mfrom(tau=0.5j)) + (0.0 + 0.5j) + >>> taufrom(k=kfrom(tau=0.5j)) + (0.0 + 0.5j) + >>> taufrom(qbar=qbarfrom(tau=0.5j)) + (0.0 + 0.5j) + + """ + if tau is not None: + return ctx.convert(tau) + if m is not None: + m = ctx.convert(m) + return ctx.j*ctx.ellipk(1-m)/ctx.ellipk(m) + if k is not None: + k = ctx.convert(k) + return ctx.j*ctx.ellipk(1-k**2)/ctx.ellipk(k**2) + if q is not None: + return ctx.log(q) / (ctx.pi*ctx.j) + if qbar is not None: + qbar = ctx.convert(qbar) + return ctx.log(qbar) / (2*ctx.pi*ctx.j) + +@defun_wrapped +def kfrom(ctx, q=None, m=None, k=None, tau=None, qbar=None): + r""" + Returns the elliptic modulus `k`, given any of + `q, m, k, \tau, \bar{q}`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> kfrom(k=0.25) + 0.25 + >>> kfrom(m=mfrom(k=0.25)) + 0.25 + >>> kfrom(q=qfrom(k=0.25)) + 0.25 + >>> kfrom(tau=taufrom(k=0.25)) + (0.25 + 0.0j) + >>> kfrom(qbar=qbarfrom(k=0.25)) + 0.25 + + As `q \to 1` and `q \to -1`, `k` rapidly approaches + `1` and `i \infty` respectively:: + + >>> kfrom(q=0.75) + 0.9999999999999899166471767 + >>> kfrom(q=-0.75) + (0.0 + 7041781.096692038332790615j) + >>> kfrom(q=1) + 1 + >>> kfrom(q=-1) + (0.0 + +infj) + """ + if k is not None: + return ctx.convert(k) + if m is not None: + return ctx.sqrt(m) + if tau is not None: + q = ctx.expjpi(tau) + if qbar is not None: + q = ctx.sqrt(qbar) + if q == 1: + return q + if q == -1: + return ctx.mpc(0,'inf') + return (ctx.jtheta(2,0,q)/ctx.jtheta(3,0,q))**2 + +@defun_wrapped +def mfrom(ctx, q=None, m=None, k=None, tau=None, qbar=None): + r""" + Returns the elliptic parameter `m`, given any of + `q, m, k, \tau, \bar{q}`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> mfrom(m=0.25) + 0.25 + >>> mfrom(q=qfrom(m=0.25)) + 0.25 + >>> mfrom(k=kfrom(m=0.25)) + 0.25 + >>> mfrom(tau=taufrom(m=0.25)) + (0.25 + 0.0j) + >>> mfrom(qbar=qbarfrom(m=0.25)) + 0.25 + + As `q \to 1` and `q \to -1`, `m` rapidly approaches + `1` and `-\infty` respectively:: + + >>> mfrom(q=0.75) + 0.9999999999999798332943533 + >>> mfrom(q=-0.75) + -49586681013729.32611558353 + >>> mfrom(q=1) + 1.0 + >>> mfrom(q=-1) + -inf + + The inverse nome as a function of `q` has an integer + Taylor series expansion:: + + >>> taylor(lambda q: mfrom(q), 0, 7) + [0.0, 16.0, -128.0, 704.0, -3072.0, 11488.0, -38400.0, 117632.0] + + """ + if m is not None: + return m + if k is not None: + return k**2 + if tau is not None: + q = ctx.expjpi(tau) + if qbar is not None: + q = ctx.sqrt(qbar) + if q == 1: + return ctx.convert(q) + if q == -1: + return q*ctx.inf + v = (ctx.jtheta(2,0,q)/ctx.jtheta(3,0,q))**4 + if ctx._is_real_type(q) and q < 0: + v = v.real + return v + +jacobi_spec = { + 'sn' : ([3],[2],[1],[4], 'sin', 'tanh'), + 'cn' : ([4],[2],[2],[4], 'cos', 'sech'), + 'dn' : ([4],[3],[3],[4], '1', 'sech'), + 'ns' : ([2],[3],[4],[1], 'csc', 'coth'), + 'nc' : ([2],[4],[4],[2], 'sec', 'cosh'), + 'nd' : ([3],[4],[4],[3], '1', 'cosh'), + 'sc' : ([3],[4],[1],[2], 'tan', 'sinh'), + 'sd' : ([3,3],[2,4],[1],[3], 'sin', 'sinh'), + 'cd' : ([3],[2],[2],[3], 'cos', '1'), + 'cs' : ([4],[3],[2],[1], 'cot', 'csch'), + 'dc' : ([2],[3],[3],[2], 'sec', '1'), + 'ds' : ([2,4],[3,3],[3],[1], 'csc', 'csch'), + 'cc' : None, + 'ss' : None, + 'nn' : None, + 'dd' : None +} + +@defun +def ellipfun(ctx, kind, u=None, m=None, q=None, k=None, tau=None): + try: + S = jacobi_spec[kind] + except KeyError: + raise ValueError("First argument must be a two-character string " + "containing 's', 'c', 'd' or 'n', e.g.: 'sn'") + if u is None: + def f(*args, **kwargs): + return ctx.ellipfun(kind, *args, **kwargs) + f.__name__ = kind + return f + prec = ctx.prec + try: + ctx.prec += 10 + u = ctx.convert(u) + q = ctx.qfrom(m=m, q=q, k=k, tau=tau) + if S is None: + v = ctx.one + 0*q*u + elif q == ctx.zero: + if S[4] == '1': v = ctx.one + else: v = getattr(ctx, S[4])(u) + v += 0*q*u + elif q == ctx.one: + if S[5] == '1': v = ctx.one + else: v = getattr(ctx, S[5])(u) + v += 0*q*u + else: + t = u / ctx.jtheta(3, 0, q)**2 + v = ctx.one + for a in S[0]: v *= ctx.jtheta(a, 0, q) + for b in S[1]: v /= ctx.jtheta(b, 0, q) + for c in S[2]: v *= ctx.jtheta(c, t, q) + for d in S[3]: v /= ctx.jtheta(d, t, q) + finally: + ctx.prec = prec + return +v + +@defun_wrapped +def kleinj(ctx, tau=None, **kwargs): + r""" + Evaluates the Klein j-invariant, which is a modular function defined for + `\tau` in the upper half-plane as + + .. math :: + + J(\tau) = \frac{g_2^3(\tau)}{g_2^3(\tau) - 27 g_3^2(\tau)} + + where `g_2` and `g_3` are the modular invariants of the Weierstrass + elliptic function, + + .. math :: + + g_2(\tau) = 60 \sum_{(m,n) \in \mathbb{Z}^2 \setminus (0,0)} (m \tau+n)^{-4} + + g_3(\tau) = 140 \sum_{(m,n) \in \mathbb{Z}^2 \setminus (0,0)} (m \tau+n)^{-6}. + + An alternative, common notation is that of the j-function + `j(\tau) = 1728 J(\tau)`. + + **Plots** + + .. literalinclude :: /plots/kleinj.py + .. image :: /plots/kleinj.png + .. literalinclude :: /plots/kleinj2.py + .. image :: /plots/kleinj2.png + + **Examples** + + Verifying the functional equation `J(\tau) = J(\tau+1) = J(-\tau^{-1})`:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> tau = 0.625+0.75*j + >>> tau = 0.625+0.75*j + >>> kleinj(tau) + (-0.1507492166511182267125242 + 0.07595948379084571927228948j) + >>> kleinj(tau+1) + (-0.1507492166511182267125242 + 0.07595948379084571927228948j) + >>> kleinj(-1/tau) + (-0.1507492166511182267125242 + 0.07595948379084571927228946j) + + The j-function has a famous Laurent series expansion in terms of the nome + `\bar{q}`, `j(\tau) = \bar{q}^{-1} + 744 + 196884\bar{q} + \ldots`:: + + >>> mp.dps = 15 + >>> taylor(lambda q: 1728*q*kleinj(qbar=q), 0, 5, singular=True) + [1.0, 744.0, 196884.0, 21493760.0, 864299970.0, 20245856256.0] + + The j-function admits exact evaluation at special algebraic points + related to the Heegner numbers 1, 2, 3, 7, 11, 19, 43, 67, 163:: + + >>> @extraprec(10) + ... def h(n): + ... v = (1+sqrt(n)*j) + ... if n > 2: + ... v *= 0.5 + ... return v + ... + >>> mp.dps = 25 + >>> for n in [1,2,3,7,11,19,43,67,163]: + ... n, chop(1728*kleinj(h(n))) + ... + (1, 1728.0) + (2, 8000.0) + (3, 0.0) + (7, -3375.0) + (11, -32768.0) + (19, -884736.0) + (43, -884736000.0) + (67, -147197952000.0) + (163, -262537412640768000.0) + + Also at other special points, the j-function assumes explicit + algebraic values, e.g.:: + + >>> chop(1728*kleinj(j*sqrt(5))) + 1264538.909475140509320227 + >>> identify(cbrt(_)) # note: not simplified + '((100+sqrt(13520))/2)' + >>> (50+26*sqrt(5))**3 + 1264538.909475140509320227 + + """ + q = ctx.qfrom(tau=tau, **kwargs) + t2 = ctx.jtheta(2,0,q) + t3 = ctx.jtheta(3,0,q) + t4 = ctx.jtheta(4,0,q) + P = (t2**8 + t3**8 + t4**8)**3 + Q = 54*(t2*t3*t4)**8 + return P/Q + + +def RF_calc(ctx, x, y, z, r): + if y == z: return RC_calc(ctx, x, y, r) + if x == z: return RC_calc(ctx, y, x, r) + if x == y: return RC_calc(ctx, z, x, r) + if not (ctx.isnormal(x) and ctx.isnormal(y) and ctx.isnormal(z)): + if ctx.isnan(x) or ctx.isnan(y) or ctx.isnan(z): + return x*y*z + if ctx.isinf(x) or ctx.isinf(y) or ctx.isinf(z): + return ctx.zero + xm,ym,zm = x,y,z + A0 = Am = (x+y+z)/3 + Q = ctx.root(3*r, -6) * max(abs(A0-x),abs(A0-y),abs(A0-z)) + g = ctx.mpf(0.25) + pow4 = ctx.one + while 1: + xs = ctx.sqrt(xm) + ys = ctx.sqrt(ym) + zs = ctx.sqrt(zm) + lm = xs*ys + xs*zs + ys*zs + Am1 = (Am+lm)*g + xm, ym, zm = (xm+lm)*g, (ym+lm)*g, (zm+lm)*g + if pow4 * Q < abs(Am): + break + Am = Am1 + pow4 *= g + t = pow4/Am + X = (A0-x)*t + Y = (A0-y)*t + Z = -X-Y + E2 = X*Y-Z**2 + E3 = X*Y*Z + return ctx.power(Am,-0.5) * (9240-924*E2+385*E2**2+660*E3-630*E2*E3)/9240 + +def RC_calc(ctx, x, y, r, pv=True): + if not (ctx.isnormal(x) and ctx.isnormal(y)): + if ctx.isinf(x) or ctx.isinf(y): + return 1/(x*y) + if y == 0: + return ctx.inf + if x == 0: + return ctx.pi / ctx.sqrt(y) / 2 + raise ValueError + # Cauchy principal value + if pv and ctx._im(y) == 0 and ctx._re(y) < 0: + return ctx.sqrt(x/(x-y)) * RC_calc(ctx, x-y, -y, r) + if x == y: + return 1/ctx.sqrt(x) + extraprec = 2*max(0,-ctx.mag(x-y)+ctx.mag(x)) + ctx.prec += extraprec + if ctx._is_real_type(x) and ctx._is_real_type(y): + x = ctx._re(x) + y = ctx._re(y) + a = ctx.sqrt(x/y) + if x < y: + b = ctx.sqrt(y-x) + v = ctx.acos(a)/b + else: + b = ctx.sqrt(x-y) + v = ctx.acosh(a)/b + else: + sx = ctx.sqrt(x) + sy = ctx.sqrt(y) + v = ctx.acos(sx/sy)/(ctx.sqrt((1-x/y))*sy) + ctx.prec -= extraprec + return v + +def RJ_calc(ctx, x, y, z, p, r, integration): + """ + With integration == 0, computes RJ only using Carlson's algorithm + (may be wrong for some values). + With integration == 1, uses an initial integration to make sure + Carlson's algorithm is correct. + With integration == 2, uses only integration. + """ + if not (ctx.isnormal(x) and ctx.isnormal(y) and \ + ctx.isnormal(z) and ctx.isnormal(p)): + if ctx.isnan(x) or ctx.isnan(y) or ctx.isnan(z) or ctx.isnan(p): + return x*y*z + if ctx.isinf(x) or ctx.isinf(y) or ctx.isinf(z) or ctx.isinf(p): + return ctx.zero + if not p: + return ctx.inf + if (not x) + (not y) + (not z) > 1: + return ctx.inf + # Check conditions and fall back on integration for argument + # reduction if needed. The following conditions might be needlessly + # restrictive. + initial_integral = ctx.zero + if integration >= 1: + ok = (x.real >= 0 and y.real >= 0 and z.real >= 0 and p.real > 0) + if not ok: + if x == p or y == p or z == p: + ok = True + if not ok: + if p.imag != 0 or p.real >= 0: + if (x.imag == 0 and x.real >= 0 and ctx.conj(y) == z): + ok = True + if (y.imag == 0 and y.real >= 0 and ctx.conj(x) == z): + ok = True + if (z.imag == 0 and z.real >= 0 and ctx.conj(x) == y): + ok = True + if not ok or (integration == 2): + N = ctx.ceil(-min(x.real, y.real, z.real, p.real)) + 1 + # Integrate around any singularities + if all((t.imag >= 0 or t.real > 0) for t in [x, y, z, p]): + margin = ctx.j + elif all((t.imag < 0 or t.real > 0) for t in [x, y, z, p]): + margin = -ctx.j + else: + margin = 1 + # Go through the upper half-plane, but low enough that any + # parameter starting in the lower plane doesn't cross the + # branch cut + for t in [x, y, z, p]: + if t.imag >= 0 or t.real > 0: + continue + margin = min(margin, abs(t.imag) * 0.5) + margin *= ctx.j + N += margin + F = lambda t: 1/(ctx.sqrt(t+x)*ctx.sqrt(t+y)*ctx.sqrt(t+z)*(t+p)) + if integration == 2: + return 1.5 * ctx.quadsubdiv(F, [0, N, ctx.inf]) + initial_integral = 1.5 * ctx.quadsubdiv(F, [0, N]) + x += N; y += N; z += N; p += N + xm,ym,zm,pm = x,y,z,p + A0 = Am = (x + y + z + 2*p)/5 + delta = (p-x)*(p-y)*(p-z) + Q = ctx.root(0.25*r, -6) * max(abs(A0-x),abs(A0-y),abs(A0-z),abs(A0-p)) + g = ctx.mpf(0.25) + pow4 = ctx.one + S = 0 + while 1: + sx = ctx.sqrt(xm) + sy = ctx.sqrt(ym) + sz = ctx.sqrt(zm) + sp = ctx.sqrt(pm) + lm = sx*sy + sx*sz + sy*sz + Am1 = (Am+lm)*g + xm = (xm+lm)*g; ym = (ym+lm)*g; zm = (zm+lm)*g; pm = (pm+lm)*g + dm = (sp+sx) * (sp+sy) * (sp+sz) + em = delta * pow4**3 / dm**2 + if pow4 * Q < abs(Am): + break + T = RC_calc(ctx, ctx.one, ctx.one+em, r) * pow4 / dm + S += T + pow4 *= g + Am = Am1 + t = pow4 / Am + X = (A0-x)*t + Y = (A0-y)*t + Z = (A0-z)*t + P = (-X-Y-Z)/2 + E2 = X*Y + X*Z + Y*Z - 3*P**2 + E3 = X*Y*Z + 2*E2*P + 4*P**3 + E4 = (2*X*Y*Z + E2*P + 3*P**3)*P + E5 = X*Y*Z*P**2 + P = 24024 - 5148*E2 + 2457*E2**2 + 4004*E3 - 4158*E2*E3 - 3276*E4 + 2772*E5 + Q = 24024 + v1 = pow4 * ctx.power(Am, -1.5) * P/Q + v2 = 6*S + return initial_integral + v1 + v2 + +@defun +def elliprf(ctx, x, y, z): + r""" + Evaluates the Carlson symmetric elliptic integral of the first kind + + .. math :: + + R_F(x,y,z) = \frac{1}{2} + \int_0^{\infty} \frac{dt}{\sqrt{(t+x)(t+y)(t+z)}} + + which is defined for `x,y,z \notin (-\infty,0)`, and with + at most one of `x,y,z` being zero. + + For real `x,y,z \ge 0`, the principal square root is taken in the integrand. + For complex `x,y,z`, the principal square root is taken as `t \to \infty` + and as `t \to 0` non-principal branches are chosen as necessary so as to + make the integrand continuous. + + **Examples** + + Some basic values and limits:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> elliprf(0,1,1); pi/2 + 1.570796326794896619231322 + 1.570796326794896619231322 + >>> elliprf(0,1,inf) + 0.0 + >>> elliprf(1,1,1) + 1.0 + >>> elliprf(2,2,2)**2 + 0.5 + >>> elliprf(1,0,0); elliprf(0,0,1); elliprf(0,1,0); elliprf(0,0,0) + +inf + +inf + +inf + +inf + + Representing complete elliptic integrals in terms of `R_F`:: + + >>> m = mpf(0.75) + >>> ellipk(m); elliprf(0,1-m,1) + 2.156515647499643235438675 + 2.156515647499643235438675 + >>> ellipe(m); elliprf(0,1-m,1)-m*elliprd(0,1-m,1)/3 + 1.211056027568459524803563 + 1.211056027568459524803563 + + Some symmetries and argument transformations:: + + >>> x,y,z = 2,3,4 + >>> elliprf(x,y,z); elliprf(y,x,z); elliprf(z,y,x) + 0.5840828416771517066928492 + 0.5840828416771517066928492 + 0.5840828416771517066928492 + >>> k = mpf(100000) + >>> elliprf(k*x,k*y,k*z); k**(-0.5) * elliprf(x,y,z) + 0.001847032121923321253219284 + 0.001847032121923321253219284 + >>> l = sqrt(x*y) + sqrt(y*z) + sqrt(z*x) + >>> elliprf(x,y,z); 2*elliprf(x+l,y+l,z+l) + 0.5840828416771517066928492 + 0.5840828416771517066928492 + >>> elliprf((x+l)/4,(y+l)/4,(z+l)/4) + 0.5840828416771517066928492 + + Comparing with numerical integration:: + + >>> x,y,z = 2,3,4 + >>> elliprf(x,y,z) + 0.5840828416771517066928492 + >>> f = lambda t: 0.5*((t+x)*(t+y)*(t+z))**(-0.5) + >>> q = extradps(25)(quad) + >>> q(f, [0,inf]) + 0.5840828416771517066928492 + + With the following arguments, the square root in the integrand becomes + discontinuous at `t = 1/2` if the principal branch is used. To obtain + the right value, `-\sqrt{r}` must be taken instead of `\sqrt{r}` + on `t \in (0, 1/2)`:: + + >>> x,y,z = j-1,j,0 + >>> elliprf(x,y,z) + (0.7961258658423391329305694 - 1.213856669836495986430094j) + >>> -q(f, [0,0.5]) + q(f, [0.5,inf]) + (0.7961258658423391329305694 - 1.213856669836495986430094j) + + The so-called *first lemniscate constant*, a transcendental number:: + + >>> elliprf(0,1,2) + 1.31102877714605990523242 + >>> extradps(25)(quad)(lambda t: 1/sqrt(1-t**4), [0,1]) + 1.31102877714605990523242 + >>> gamma('1/4')**2/(4*sqrt(2*pi)) + 1.31102877714605990523242 + + **References** + + 1. [Carlson]_ + 2. [DLMF]_ Chapter 19. Elliptic Integrals + + """ + x = ctx.convert(x) + y = ctx.convert(y) + z = ctx.convert(z) + prec = ctx.prec + try: + ctx.prec += 20 + tol = ctx.eps * 2**10 + v = RF_calc(ctx, x, y, z, tol) + finally: + ctx.prec = prec + return +v + +@defun +def elliprc(ctx, x, y, pv=True): + r""" + Evaluates the degenerate Carlson symmetric elliptic integral + of the first kind + + .. math :: + + R_C(x,y) = R_F(x,y,y) = + \frac{1}{2} \int_0^{\infty} \frac{dt}{(t+y) \sqrt{(t+x)}}. + + If `y \in (-\infty,0)`, either a value defined by continuity, + or with *pv=True* the Cauchy principal value, can be computed. + + If `x \ge 0, y > 0`, the value can be expressed in terms of + elementary functions as + + .. math :: + + R_C(x,y) = + \begin{cases} + \dfrac{1}{\sqrt{y-x}} + \cos^{-1}\left(\sqrt{\dfrac{x}{y}}\right), & x < y \\ + \dfrac{1}{\sqrt{y}}, & x = y \\ + \dfrac{1}{\sqrt{x-y}} + \cosh^{-1}\left(\sqrt{\dfrac{x}{y}}\right), & x > y \\ + \end{cases}. + + **Examples** + + Some special values and limits:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> elliprc(1,2)*4; elliprc(0,1)*2; +pi + 3.141592653589793238462643 + 3.141592653589793238462643 + 3.141592653589793238462643 + >>> elliprc(1,0) + +inf + >>> elliprc(5,5)**2 + 0.2 + >>> elliprc(1,inf); elliprc(inf,1); elliprc(inf,inf) + 0.0 + 0.0 + 0.0 + + Comparing with the elementary closed-form solution:: + + >>> elliprc('1/3', '1/5'); sqrt(7.5)*acosh(sqrt('5/3')) + 2.041630778983498390751238 + 2.041630778983498390751238 + >>> elliprc('1/5', '1/3'); sqrt(7.5)*acos(sqrt('3/5')) + 1.875180765206547065111085 + 1.875180765206547065111085 + + Comparing with numerical integration:: + + >>> q = extradps(25)(quad) + >>> elliprc(2, -3, pv=True) + 0.3333969101113672670749334 + >>> elliprc(2, -3, pv=False) + (0.3333969101113672670749334 + 0.7024814731040726393156375j) + >>> 0.5*q(lambda t: 1/(sqrt(t+2)*(t-3)), [0,3-j,6,inf]) + (0.3333969101113672670749334 + 0.7024814731040726393156375j) + + """ + x = ctx.convert(x) + y = ctx.convert(y) + prec = ctx.prec + try: + ctx.prec += 20 + tol = ctx.eps * 2**10 + v = RC_calc(ctx, x, y, tol, pv) + finally: + ctx.prec = prec + return +v + +@defun +def elliprj(ctx, x, y, z, p, integration=1): + r""" + Evaluates the Carlson symmetric elliptic integral of the third kind + + .. math :: + + R_J(x,y,z,p) = \frac{3}{2} + \int_0^{\infty} \frac{dt}{(t+p)\sqrt{(t+x)(t+y)(t+z)}}. + + Like :func:`~mpmath.elliprf`, the branch of the square root in the integrand + is defined so as to be continuous along the path of integration for + complex values of the arguments. + + **Examples** + + Some values and limits:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> elliprj(1,1,1,1) + 1.0 + >>> elliprj(2,2,2,2); 1/(2*sqrt(2)) + 0.3535533905932737622004222 + 0.3535533905932737622004222 + >>> elliprj(0,1,2,2) + 1.067937989667395702268688 + >>> 3*(2*gamma('5/4')**2-pi**2/gamma('1/4')**2)/(sqrt(2*pi)) + 1.067937989667395702268688 + >>> elliprj(0,1,1,2); 3*pi*(2-sqrt(2))/4 + 1.380226776765915172432054 + 1.380226776765915172432054 + >>> elliprj(1,3,2,0); elliprj(0,1,1,0); elliprj(0,0,0,0) + +inf + +inf + +inf + >>> elliprj(1,inf,1,0); elliprj(1,1,1,inf) + 0.0 + 0.0 + >>> chop(elliprj(1+j, 1-j, 1, 1)) + 0.8505007163686739432927844 + + Scale transformation:: + + >>> x,y,z,p = 2,3,4,5 + >>> k = mpf(100000) + >>> elliprj(k*x,k*y,k*z,k*p); k**(-1.5)*elliprj(x,y,z,p) + 4.521291677592745527851168e-9 + 4.521291677592745527851168e-9 + + Comparing with numerical integration:: + + >>> elliprj(1,2,3,4) + 0.2398480997495677621758617 + >>> f = lambda t: 1/((t+4)*sqrt((t+1)*(t+2)*(t+3))) + >>> 1.5*quad(f, [0,inf]) + 0.2398480997495677621758617 + >>> elliprj(1,2+1j,3,4-2j) + (0.216888906014633498739952 + 0.04081912627366673332369512j) + >>> f = lambda t: 1/((t+4-2j)*sqrt((t+1)*(t+2+1j)*(t+3))) + >>> 1.5*quad(f, [0,inf]) + (0.216888906014633498739952 + 0.04081912627366673332369511j) + + """ + x = ctx.convert(x) + y = ctx.convert(y) + z = ctx.convert(z) + p = ctx.convert(p) + prec = ctx.prec + try: + ctx.prec += 20 + tol = ctx.eps * 2**10 + v = RJ_calc(ctx, x, y, z, p, tol, integration) + finally: + ctx.prec = prec + return +v + +@defun +def elliprd(ctx, x, y, z): + r""" + Evaluates the degenerate Carlson symmetric elliptic integral + of the third kind or Carlson elliptic integral of the + second kind `R_D(x,y,z) = R_J(x,y,z,z)`. + + See :func:`~mpmath.elliprj` for additional information. + + **Examples** + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> elliprd(1,2,3) + 0.2904602810289906442326534 + >>> elliprj(1,2,3,3) + 0.2904602810289906442326534 + + The so-called *second lemniscate constant*, a transcendental number:: + + >>> elliprd(0,2,1)/3 + 0.5990701173677961037199612 + >>> extradps(25)(quad)(lambda t: t**2/sqrt(1-t**4), [0,1]) + 0.5990701173677961037199612 + >>> gamma('3/4')**2/sqrt(2*pi) + 0.5990701173677961037199612 + + """ + return ctx.elliprj(x,y,z,z) + +@defun +def elliprg(ctx, x, y, z): + r""" + Evaluates the Carlson completely symmetric elliptic integral + of the second kind + + .. math :: + + R_G(x,y,z) = \frac{1}{4} \int_0^{\infty} + \frac{t}{\sqrt{(t+x)(t+y)(t+z)}} + \left( \frac{x}{t+x} + \frac{y}{t+y} + \frac{z}{t+z}\right) dt. + + **Examples** + + Evaluation for real and complex arguments:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> elliprg(0,1,1)*4; +pi + 3.141592653589793238462643 + 3.141592653589793238462643 + >>> elliprg(0,0.5,1) + 0.6753219405238377512600874 + >>> chop(elliprg(1+j, 1-j, 2)) + 1.172431327676416604532822 + + A double integral that can be evaluated in terms of `R_G`:: + + >>> x,y,z = 2,3,4 + >>> def f(t,u): + ... st = fp.sin(t); ct = fp.cos(t) + ... su = fp.sin(u); cu = fp.cos(u) + ... return (x*(st*cu)**2 + y*(st*su)**2 + z*ct**2)**0.5 * st + ... + >>> nprint(mpf(fp.quad(f, [0,fp.pi], [0,2*fp.pi])/(4*fp.pi)), 13) + 1.725503028069 + >>> nprint(elliprg(x,y,z), 13) + 1.725503028069 + + """ + x = ctx.convert(x) + y = ctx.convert(y) + z = ctx.convert(z) + zeros = (not x) + (not y) + (not z) + if zeros == 3: + return (x+y+z)*0 + if zeros == 2: + if x: return 0.5*ctx.sqrt(x) + if y: return 0.5*ctx.sqrt(y) + return 0.5*ctx.sqrt(z) + if zeros == 1: + if not z: + x, z = z, x + def terms(): + T1 = 0.5*z*ctx.elliprf(x,y,z) + T2 = -0.5*(x-z)*(y-z)*ctx.elliprd(x,y,z)/3 + T3 = 0.5*ctx.sqrt(x)*ctx.sqrt(y)/ctx.sqrt(z) + return T1,T2,T3 + return ctx.sum_accurately(terms) + + +@defun_wrapped +def ellipf(ctx, phi, m): + r""" + Evaluates the Legendre incomplete elliptic integral of the first kind + + .. math :: + + F(\phi,m) = \int_0^{\phi} \frac{dt}{\sqrt{1-m \sin^2 t}} + + or equivalently + + .. math :: + + F(\phi,m) = \int_0^{\sin \phi} + \frac{dt}{\left(\sqrt{1-t^2}\right)\left(\sqrt{1-mt^2}\right)}. + + The function reduces to a complete elliptic integral of the first kind + (see :func:`~mpmath.ellipk`) when `\phi = \frac{\pi}{2}`; that is, + + .. math :: + + F\left(\frac{\pi}{2}, m\right) = K(m). + + In the defining integral, it is assumed that the principal branch + of the square root is taken and that the path of integration avoids + crossing any branch cuts. Outside `-\pi/2 \le \Re(\phi) \le \pi/2`, + the function extends quasi-periodically as + + .. math :: + + F(\phi + n \pi, m) = 2 n K(m) + F(\phi,m), n \in \mathbb{Z}. + + **Plots** + + .. literalinclude :: /plots/ellipf.py + .. image :: /plots/ellipf.png + + **Examples** + + Basic values and limits:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> ellipf(0,1) + 0.0 + >>> ellipf(0,0) + 0.0 + >>> ellipf(1,0); ellipf(2+3j,0) + 1.0 + (2.0 + 3.0j) + >>> ellipf(1,1); log(sec(1)+tan(1)) + 1.226191170883517070813061 + 1.226191170883517070813061 + >>> ellipf(pi/2, -0.5); ellipk(-0.5) + 1.415737208425956198892166 + 1.415737208425956198892166 + >>> ellipf(pi/2+eps, 1); ellipf(-pi/2-eps, 1) + +inf + +inf + >>> ellipf(1.5, 1) + 3.340677542798311003320813 + + Comparing with numerical integration:: + + >>> z,m = 0.5, 1.25 + >>> ellipf(z,m) + 0.5287219202206327872978255 + >>> quad(lambda t: (1-m*sin(t)**2)**(-0.5), [0,z]) + 0.5287219202206327872978255 + + The arguments may be complex numbers:: + + >>> ellipf(3j, 0.5) + (0.0 + 1.713602407841590234804143j) + >>> ellipf(3+4j, 5-6j) + (1.269131241950351323305741 - 0.3561052815014558335412538j) + >>> z,m = 2+3j, 1.25 + >>> k = 1011 + >>> ellipf(z+pi*k,m); ellipf(z,m) + 2*k*ellipk(m) + (4086.184383622179764082821 - 3003.003538923749396546871j) + (4086.184383622179764082821 - 3003.003538923749396546871j) + + For `|\Re(z)| < \pi/2`, the function can be expressed as a + hypergeometric series of two variables + (see :func:`~mpmath.appellf1`):: + + >>> z,m = 0.5, 0.25 + >>> ellipf(z,m) + 0.5050887275786480788831083 + >>> sin(z)*appellf1(0.5,0.5,0.5,1.5,sin(z)**2,m*sin(z)**2) + 0.5050887275786480788831083 + + """ + z = phi + if not (ctx.isnormal(z) and ctx.isnormal(m)): + if m == 0: + return z + m + if z == 0: + return z * m + if m == ctx.inf or m == ctx.ninf: return z/m + raise ValueError + x = z.real + ctx.prec += max(0, ctx.mag(x)) + pi = +ctx.pi + away = abs(x) > pi/2 + if m == 1: + if away: + return ctx.inf + if away: + d = ctx.nint(x/pi) + z = z-pi*d + P = 2*d*ctx.ellipk(m) + else: + P = 0 + c, s = ctx.cos_sin(z) + return s * ctx.elliprf(c**2, 1-m*s**2, 1) + P + +@defun_wrapped +def ellipe(ctx, *args): + r""" + Called with a single argument `m`, evaluates the Legendre complete + elliptic integral of the second kind, `E(m)`, defined by + + .. math :: E(m) = \int_0^{\pi/2} \sqrt{1-m \sin^2 t} \, dt \,=\, + \frac{\pi}{2} + \,_2F_1\left(\frac{1}{2}, -\frac{1}{2}, 1, m\right). + + Called with two arguments `\phi, m`, evaluates the incomplete elliptic + integral of the second kind + + .. math :: + + E(\phi,m) = \int_0^{\phi} \sqrt{1-m \sin^2 t} \, dt = + \int_0^{\sin z} + \frac{\sqrt{1-mt^2}}{\sqrt{1-t^2}} \, dt. + + The incomplete integral reduces to a complete integral when + `\phi = \frac{\pi}{2}`; that is, + + .. math :: + + E\left(\frac{\pi}{2}, m\right) = E(m). + + In the defining integral, it is assumed that the principal branch + of the square root is taken and that the path of integration avoids + crossing any branch cuts. Outside `-\pi/2 \le \Re(z) \le \pi/2`, + the function extends quasi-periodically as + + .. math :: + + E(\phi + n \pi, m) = 2 n E(m) + E(\phi,m), n \in \mathbb{Z}. + + **Plots** + + .. literalinclude :: /plots/ellipe.py + .. image :: /plots/ellipe.png + + **Examples for the complete integral** + + Basic values and limits:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> ellipe(0) + 1.570796326794896619231322 + >>> ellipe(1) + 1.0 + >>> ellipe(-1) + 1.910098894513856008952381 + >>> ellipe(2) + (0.5990701173677961037199612 + 0.5990701173677961037199612j) + >>> ellipe(inf) + (0.0 + +infj) + >>> ellipe(-inf) + +inf + + Verifying the defining integral and hypergeometric + representation:: + + >>> ellipe(0.5) + 1.350643881047675502520175 + >>> quad(lambda t: sqrt(1-0.5*sin(t)**2), [0, pi/2]) + 1.350643881047675502520175 + >>> pi/2*hyp2f1(0.5,-0.5,1,0.5) + 1.350643881047675502520175 + + Evaluation is supported for arbitrary complex `m`:: + + >>> ellipe(0.5+0.25j) + (1.360868682163129682716687 - 0.1238733442561786843557315j) + >>> ellipe(3+4j) + (1.499553520933346954333612 - 1.577879007912758274533309j) + + A definite integral:: + + >>> quad(ellipe, [0,1]) + 1.333333333333333333333333 + + **Examples for the incomplete integral** + + Basic values and limits:: + + >>> ellipe(0,1) + 0.0 + >>> ellipe(0,0) + 0.0 + >>> ellipe(1,0) + 1.0 + >>> ellipe(2+3j,0) + (2.0 + 3.0j) + >>> ellipe(1,1); sin(1) + 0.8414709848078965066525023 + 0.8414709848078965066525023 + >>> ellipe(pi/2, -0.5); ellipe(-0.5) + 1.751771275694817862026502 + 1.751771275694817862026502 + >>> ellipe(pi/2, 1); ellipe(-pi/2, 1) + 1.0 + -1.0 + >>> ellipe(1.5, 1) + 0.9974949866040544309417234 + + Comparing with numerical integration:: + + >>> z,m = 0.5, 1.25 + >>> ellipe(z,m) + 0.4740152182652628394264449 + >>> quad(lambda t: sqrt(1-m*sin(t)**2), [0,z]) + 0.4740152182652628394264449 + + The arguments may be complex numbers:: + + >>> ellipe(3j, 0.5) + (0.0 + 7.551991234890371873502105j) + >>> ellipe(3+4j, 5-6j) + (24.15299022574220502424466 + 75.2503670480325997418156j) + >>> k = 35 + >>> z,m = 2+3j, 1.25 + >>> ellipe(z+pi*k,m); ellipe(z,m) + 2*k*ellipe(m) + (48.30138799412005235090766 + 17.47255216721987688224357j) + (48.30138799412005235090766 + 17.47255216721987688224357j) + + For `|\Re(z)| < \pi/2`, the function can be expressed as a + hypergeometric series of two variables + (see :func:`~mpmath.appellf1`):: + + >>> z,m = 0.5, 0.25 + >>> ellipe(z,m) + 0.4950017030164151928870375 + >>> sin(z)*appellf1(0.5,0.5,-0.5,1.5,sin(z)**2,m*sin(z)**2) + 0.4950017030164151928870376 + + """ + if len(args) == 1: + return ctx._ellipe(args[0]) + else: + phi, m = args + z = phi + if not (ctx.isnormal(z) and ctx.isnormal(m)): + if m == 0: + return z + m + if z == 0: + return z * m + if m == ctx.inf or m == ctx.ninf: + return ctx.inf + raise ValueError + x = z.real + ctx.prec += max(0, ctx.mag(x)) + pi = +ctx.pi + away = abs(x) > pi/2 + if away: + d = ctx.nint(x/pi) + z = z-pi*d + P = 2*d*ctx.ellipe(m) + else: + P = 0 + def terms(): + c, s = ctx.cos_sin(z) + x = c**2 + y = 1-m*s**2 + RF = ctx.elliprf(x, y, 1) + RD = ctx.elliprd(x, y, 1) + return s*RF, -m*s**3*RD/3 + return ctx.sum_accurately(terms) + P + +@defun_wrapped +def ellippi(ctx, *args): + r""" + Called with three arguments `n, \phi, m`, evaluates the Legendre + incomplete elliptic integral of the third kind + + .. math :: + + \Pi(n; \phi, m) = \int_0^{\phi} + \frac{dt}{(1-n \sin^2 t) \sqrt{1-m \sin^2 t}} = + \int_0^{\sin \phi} + \frac{dt}{(1-nt^2) \sqrt{1-t^2} \sqrt{1-mt^2}}. + + Called with two arguments `n, m`, evaluates the complete + elliptic integral of the third kind + `\Pi(n,m) = \Pi(n; \frac{\pi}{2},m)`. + + In the defining integral, it is assumed that the principal branch + of the square root is taken and that the path of integration avoids + crossing any branch cuts. Outside `-\pi/2 \le \Re(\phi) \le \pi/2`, + the function extends quasi-periodically as + + .. math :: + + \Pi(n,\phi+k\pi,m) = 2k\Pi(n,m) + \Pi(n,\phi,m), k \in \mathbb{Z}. + + **Plots** + + .. literalinclude :: /plots/ellippi.py + .. image :: /plots/ellippi.png + + **Examples for the complete integral** + + Some basic values and limits:: + + >>> from mpmath import * + >>> mp.dps = 25; mp.pretty = True + >>> ellippi(0,-5); ellipk(-5) + 0.9555039270640439337379334 + 0.9555039270640439337379334 + >>> ellippi(inf,2) + 0.0 + >>> ellippi(2,inf) + 0.0 + >>> abs(ellippi(1,5)) + +inf + >>> abs(ellippi(0.25,1)) + +inf + + Evaluation in terms of simpler functions:: + + >>> ellippi(0.25,0.25); ellipe(0.25)/(1-0.25) + 1.956616279119236207279727 + 1.956616279119236207279727 + >>> ellippi(3,0); pi/(2*sqrt(-2)) + (0.0 - 1.11072073453959156175397j) + (0.0 - 1.11072073453959156175397j) + >>> ellippi(-3,0); pi/(2*sqrt(4)) + 0.7853981633974483096156609 + 0.7853981633974483096156609 + + **Examples for the incomplete integral** + + Basic values and limits:: + + >>> ellippi(0.25,-0.5); ellippi(0.25,pi/2,-0.5) + 1.622944760954741603710555 + 1.622944760954741603710555 + >>> ellippi(1,0,1) + 0.0 + >>> ellippi(inf,0,1) + 0.0 + >>> ellippi(0,0.25,0.5); ellipf(0.25,0.5) + 0.2513040086544925794134591 + 0.2513040086544925794134591 + >>> ellippi(1,1,1); (log(sec(1)+tan(1))+sec(1)*tan(1))/2 + 2.054332933256248668692452 + 2.054332933256248668692452 + >>> ellippi(0.25, 53*pi/2, 0.75); 53*ellippi(0.25,0.75) + 135.240868757890840755058 + 135.240868757890840755058 + >>> ellippi(0.5,pi/4,0.5); 2*ellipe(pi/4,0.5)-1/sqrt(3) + 0.9190227391656969903987269 + 0.9190227391656969903987269 + + Complex arguments are supported:: + + >>> ellippi(0.5, 5+6j-2*pi, -7-8j) + (-0.3612856620076747660410167 + 0.5217735339984807829755815j) + + Some degenerate cases:: + + >>> ellippi(1,1) + +inf + >>> ellippi(1,0) + +inf + >>> ellippi(1,2,0) + +inf + >>> ellippi(1,2,1) + +inf + >>> ellippi(1,0,1) + 0.0 + + """ + if len(args) == 2: + n, m = args + complete = True + z = phi = ctx.pi/2 + else: + n, phi, m = args + complete = False + z = phi + if not (ctx.isnormal(n) and ctx.isnormal(z) and ctx.isnormal(m)): + if ctx.isnan(n) or ctx.isnan(z) or ctx.isnan(m): + raise ValueError + if complete: + if m == 0: + if n == 1: + return ctx.inf + return ctx.pi/(2*ctx.sqrt(1-n)) + if n == 0: return ctx.ellipk(m) + if ctx.isinf(n) or ctx.isinf(m): return ctx.zero + else: + if z == 0: return z + if ctx.isinf(n): return ctx.zero + if ctx.isinf(m): return ctx.zero + if ctx.isinf(n) or ctx.isinf(z) or ctx.isinf(m): + raise ValueError + if complete: + if m == 1: + if n == 1: + return ctx.inf + return -ctx.inf/ctx.sign(n-1) + away = False + else: + x = z.real + ctx.prec += max(0, ctx.mag(x)) + pi = +ctx.pi + away = abs(x) > pi/2 + if away: + d = ctx.nint(x/pi) + z = z-pi*d + P = 2*d*ctx.ellippi(n,m) + if ctx.isinf(P): + return ctx.inf + else: + P = 0 + def terms(): + if complete: + c, s = ctx.zero, ctx.one + else: + c, s = ctx.cos_sin(z) + x = c**2 + y = 1-m*s**2 + RF = ctx.elliprf(x, y, 1) + RJ = ctx.elliprj(x, y, 1, 1-n*s**2) + return s*RF, n*s**3*RJ/3 + return ctx.sum_accurately(terms) + P diff --git a/shared/package-files/ab/ab3f08d9f8e6a7cf2f05beaac6af33cce76ce7b8eeb5500095ed4cb58dc6e6ac/blob b/shared/package-files/ab/ab3f08d9f8e6a7cf2f05beaac6af33cce76ce7b8eeb5500095ed4cb58dc6e6ac/blob new file mode 100644 index 0000000000000000000000000000000000000000..58145b2c779cc38113c1916dec01f5fe8a75ef2e --- /dev/null +++ b/shared/package-files/ab/ab3f08d9f8e6a7cf2f05beaac6af33cce76ce7b8eeb5500095ed4cb58dc6e6ac/blob @@ -0,0 +1,223 @@ +#include +#include +#include +#include +#include +#include + +namespace c10 { + +namespace detail { + +struct IncrementRAII final { + public: + explicit IncrementRAII(std::atomic* counter) : _counter(counter) { + _counter->fetch_add(1); + } + + ~IncrementRAII() { + _counter->fetch_sub(1); + } + + private: + std::atomic* _counter; + + C10_DISABLE_COPY_AND_ASSIGN(IncrementRAII); +}; + +} // namespace detail + +// LeftRight wait-free readers synchronization primitive +// https://hal.archives-ouvertes.fr/hal-01207881/document +// +// LeftRight is quite easy to use (it can make an arbitrary +// data structure permit wait-free reads), but it has some +// particular performance characteristics you should be aware +// of if you're deciding to use it: +// +// - Reads still incur an atomic write (this is how LeftRight +// keeps track of how long it needs to keep around the old +// data structure) +// +// - Writes get executed twice, to keep both the left and right +// versions up to date. So if your write is expensive or +// nondeterministic, this is also an inappropriate structure +// +// LeftRight is used fairly rarely in PyTorch's codebase. If you +// are still not sure if you need it or not, consult your local +// C++ expert. +// +template +class LeftRight final { + public: + template + explicit LeftRight(const Args&... args) + : _counters{{{0}, {0}}}, + _foregroundCounterIndex(0), + _foregroundDataIndex(0), + _data{{T{args...}, T{args...}}}, + _writeMutex() {} + + // Copying and moving would not be threadsafe. + // Needs more thought and careful design to make that work. + LeftRight(const LeftRight&) = delete; + LeftRight(LeftRight&&) noexcept = delete; + LeftRight& operator=(const LeftRight&) = delete; + LeftRight& operator=(LeftRight&&) noexcept = delete; + + ~LeftRight() { + // wait until any potentially running writers are finished + { std::unique_lock lock(_writeMutex); } + + // wait until any potentially running readers are finished + while (_counters[0].load() != 0 || _counters[1].load() != 0) { + std::this_thread::yield(); + } + } + + template + auto read(F&& readFunc) const { + detail::IncrementRAII _increment_counter( + &_counters[_foregroundCounterIndex.load()]); + + return std::forward(readFunc)(_data[_foregroundDataIndex.load()]); + } + + // Throwing an exception in writeFunc is ok but causes the state to be either + // the old or the new state, depending on if the first or the second call to + // writeFunc threw. + template + auto write(F&& writeFunc) { + std::unique_lock lock(_writeMutex); + + return _write(std::forward(writeFunc)); + } + + private: + template + auto _write(const F& writeFunc) { + /* + * Assume, A is in background and B in foreground. In simplified terms, we + * want to do the following: + * 1. Write to A (old background) + * 2. Switch A/B + * 3. Write to B (new background) + * + * More detailed algorithm (explanations on why this is important are below + * in code): + * 1. Write to A + * 2. Switch A/B data pointers + * 3. Wait until A counter is zero + * 4. Switch A/B counters + * 5. Wait until B counter is zero + * 6. Write to B + */ + + auto localDataIndex = _foregroundDataIndex.load(); + + // 1. Write to A + _callWriteFuncOnBackgroundInstance(writeFunc, localDataIndex); + + // 2. Switch A/B data pointers + localDataIndex = localDataIndex ^ 1; + _foregroundDataIndex = localDataIndex; + + /* + * 3. Wait until A counter is zero + * + * In the previous write run, A was foreground and B was background. + * There was a time after switching _foregroundDataIndex (B to foreground) + * and before switching _foregroundCounterIndex, in which new readers could + * have read B but incremented A's counter. + * + * In this current run, we just switched _foregroundDataIndex (A back to + * foreground), but before writing to the new background B, we have to make + * sure A's counter was zero briefly, so all these old readers are gone. + */ + auto localCounterIndex = _foregroundCounterIndex.load(); + _waitForBackgroundCounterToBeZero(localCounterIndex); + + /* + * 4. Switch A/B counters + * + * Now that we know all readers on B are really gone, we can switch the + * counters and have new readers increment A's counter again, which is the + * correct counter since they're reading A. + */ + localCounterIndex = localCounterIndex ^ 1; + _foregroundCounterIndex = localCounterIndex; + + /* + * 5. Wait until B counter is zero + * + * This waits for all the readers on B that came in while both data and + * counter for B was in foreground, i.e. normal readers that happened + * outside of that brief gap between switching data and counter. + */ + _waitForBackgroundCounterToBeZero(localCounterIndex); + + // 6. Write to B + return _callWriteFuncOnBackgroundInstance(writeFunc, localDataIndex); + } + + template + auto _callWriteFuncOnBackgroundInstance( + const F& writeFunc, + uint8_t localDataIndex) { + try { + return writeFunc(_data[localDataIndex ^ 1]); + } catch (...) { + // recover invariant by copying from the foreground instance + _data[localDataIndex ^ 1] = _data[localDataIndex]; + // rethrow + throw; + } + } + + void _waitForBackgroundCounterToBeZero(uint8_t counterIndex) { + while (_counters[counterIndex ^ 1].load() != 0) { + std::this_thread::yield(); + } + } + + mutable std::array, 2> _counters; + std::atomic _foregroundCounterIndex; + std::atomic _foregroundDataIndex; + std::array _data; + std::mutex _writeMutex; +}; + +// RWSafeLeftRightWrapper is API compatible with LeftRight and uses a +// read-write lock to protect T (data). +template +class RWSafeLeftRightWrapper final { + public: + template + explicit RWSafeLeftRightWrapper(const Args&... args) : data_{args...} {} + + // RWSafeLeftRightWrapper is not copyable or moveable since LeftRight + // is not copyable or moveable. + RWSafeLeftRightWrapper(const RWSafeLeftRightWrapper&) = delete; + RWSafeLeftRightWrapper(RWSafeLeftRightWrapper&&) noexcept = delete; + RWSafeLeftRightWrapper& operator=(const RWSafeLeftRightWrapper&) = delete; + RWSafeLeftRightWrapper& operator=(RWSafeLeftRightWrapper&&) noexcept = delete; + + template + // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward) + auto read(F&& readFunc) const { + return data_.withLock( + [&readFunc](T const& data) { return std::forward(readFunc)(data); }); + } + + template + // NOLINTNEXTLINE(cppcoreguidelines-missing-std-forward) + auto write(F&& writeFunc) { + return data_.withLock( + [&writeFunc](T& data) { return std::forward(writeFunc)(data); }); + } + + private: + c10::Synchronized data_; +}; + +} // namespace c10 diff --git a/shared/package-files/ab/ab417fe03d04b9cecfbfaebaf029e50688ab8d7f83aba38435eab9142ab76b30/blob b/shared/package-files/ab/ab417fe03d04b9cecfbfaebaf029e50688ab8d7f83aba38435eab9142ab76b30/blob new file mode 100644 index 0000000000000000000000000000000000000000..f4c91304a1b1a83c24bfbfd108dc234aaa3615bc --- /dev/null +++ b/shared/package-files/ab/ab417fe03d04b9cecfbfaebaf029e50688ab8d7f83aba38435eab9142ab76b30/blob @@ -0,0 +1,26 @@ +from typing import Any, Dict, List, Set + +import torch + +# This module is defined in torch/csrc/distributed/autograd/init.cpp + +class DistAutogradContext: + def _context_id(self) -> int: ... + def _recv_functions(self) -> Dict[int, Any]: ... + def _send_functions(self) -> Dict[int, Any]: ... + def _known_worker_ids(self) -> Set[int]: ... + +def _new_context() -> DistAutogradContext: ... +def _release_context(context_id: int) -> None: ... +def _get_max_id() -> int: ... +def _is_valid_context(worker_id: int) -> bool: ... +def _retrieve_context(context_id: int) -> DistAutogradContext: ... +def _current_context() -> DistAutogradContext: ... +def _init(worker_id: int) -> None: ... +def _get_debug_info() -> Dict[str, str]: ... +def backward( + context_id: int, + roots: List[torch.Tensor], + retain_graph=False, +) -> None: ... +def get_gradients(context_id: int) -> Dict[torch.Tensor, torch.Tensor]: ... diff --git a/shared/package-files/ab/ab4227e437234e0e8ba80418f90d7f5a7986efee0c84606a20c0eb4aecaccfc6/blob b/shared/package-files/ab/ab4227e437234e0e8ba80418f90d7f5a7986efee0c84606a20c0eb4aecaccfc6/blob new file mode 100644 index 0000000000000000000000000000000000000000..3188cfb9b0067de39927346cf6cb6fac011504c1 --- /dev/null +++ b/shared/package-files/ab/ab4227e437234e0e8ba80418f90d7f5a7986efee0c84606a20c0eb4aecaccfc6/blob @@ -0,0 +1,29 @@ +import signal +import sys +from numba import njit +import numpy as np + + +def sigterm_handler(signum, frame): + raise RuntimeError("Caught SIGTERM") + + +@njit(parallel=True) +def busy_func_inner(a, b): + c = a + b * np.sqrt(a) + np.sqrt(b) + d = np.sqrt(a + b * np.sqrt(a) + np.sqrt(b)) + return c + d + + +def busy_func(a, b, q=None): + sys.stdout.flush() + sys.stderr.flush() + signal.signal(signal.SIGTERM, sigterm_handler) + try: + z = busy_func_inner(a, b) + sys.stdout.flush() + sys.stderr.flush() + return z + except Exception as e: + if q is not None: + q.put(e) diff --git a/shared/package-files/ab/ab439ca41391e16cdc42a2b16f7bbe3222f1bc12dc3caea1fde39225454ea2c8/blob b/shared/package-files/ab/ab439ca41391e16cdc42a2b16f7bbe3222f1bc12dc3caea1fde39225454ea2c8/blob new file mode 100644 index 0000000000000000000000000000000000000000..66e0294010330612e511eaaefd18bdfcc62c165c --- /dev/null +++ b/shared/package-files/ab/ab439ca41391e16cdc42a2b16f7bbe3222f1bc12dc3caea1fde39225454ea2c8/blob @@ -0,0 +1,2421 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +# cython: profile=False +# distutils: language = c++ + +from collections.abc import Sequence +from textwrap import indent +import warnings + +from cython.operator cimport dereference as deref +from pyarrow.includes.common cimport * +from pyarrow.includes.libarrow cimport * +from pyarrow.includes.libarrow_python cimport * +from pyarrow.lib cimport (_Weakrefable, Buffer, Schema, + check_status, + MemoryPool, maybe_unbox_memory_pool, + Table, KeyValueMetadata, + pyarrow_wrap_chunked_array, + pyarrow_wrap_schema, + pyarrow_unwrap_data_type, + pyarrow_unwrap_metadata, + pyarrow_unwrap_schema, + pyarrow_wrap_table, + pyarrow_wrap_batch, + pyarrow_wrap_scalar, + NativeFile, get_reader, get_writer, + string_to_timeunit) + +from pyarrow.lib import (ArrowException, NativeFile, BufferOutputStream, + ListType, LargeListType, + _stringify_path, + tobytes, frombytes, is_threading_enabled) + +cimport cpython as cp + +_DEFAULT_ROW_GROUP_SIZE = 1024*1024 +_MAX_ROW_GROUP_SIZE = 64*1024*1024 + + +cdef Type _unwrap_list_type(obj) except *: + if obj is ListType: + return _Type_LIST + elif obj is LargeListType: + return _Type_LARGE_LIST + else: + raise TypeError(f"Unexpected list_type: {obj!r}") + + +cdef class Statistics(_Weakrefable): + """Statistics for a single column in a single row group.""" + + def __init__(self): + raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly") + + def __cinit__(self): + pass + + def __repr__(self): + return f"""{object.__repr__(self)} + has_min_max: {self.has_min_max} + min: {self.min} + max: {self.max} + null_count: {self.null_count} + distinct_count: {self.distinct_count} + num_values: {self.num_values} + physical_type: {self.physical_type} + logical_type: {self.logical_type} + converted_type (legacy): {self.converted_type}""" + + def to_dict(self): + """ + Get dictionary representation of statistics. + + Returns + ------- + dict + Dictionary with a key for each attribute of this class. + """ + d = dict( + has_min_max=self.has_min_max, + min=self.min, + max=self.max, + null_count=self.null_count, + distinct_count=self.distinct_count, + num_values=self.num_values, + physical_type=self.physical_type + ) + return d + + def __eq__(self, other): + try: + return self.equals(other) + except TypeError: + return NotImplemented + + def equals(self, Statistics other): + """ + Return whether the two column statistics objects are equal. + + Parameters + ---------- + other : Statistics + Statistics to compare against. + + Returns + ------- + are_equal : bool + """ + return self.statistics.get().Equals(deref(other.statistics.get())) + + @property + def has_min_max(self): + """Whether min and max are present (bool).""" + return self.statistics.get().HasMinMax() + + @property + def has_null_count(self): + """Whether null count is present (bool).""" + return self.statistics.get().HasNullCount() + + @property + def has_distinct_count(self): + """Whether distinct count is preset (bool).""" + return self.statistics.get().HasDistinctCount() + + @property + def min_raw(self): + """Min value as physical type (bool, int, float, or bytes).""" + if self.has_min_max: + return _cast_statistic_raw_min(self.statistics.get()) + else: + return None + + @property + def max_raw(self): + """Max value as physical type (bool, int, float, or bytes).""" + if self.has_min_max: + return _cast_statistic_raw_max(self.statistics.get()) + else: + return None + + @property + def min(self): + """ + Min value as logical type. + + Returned as the Python equivalent of logical type, such as datetime.date + for dates and decimal.Decimal for decimals. + """ + if self.has_min_max: + min_scalar, _ = _cast_statistics(self.statistics.get()) + return min_scalar.as_py() + else: + return None + + @property + def max(self): + """ + Max value as logical type. + + Returned as the Python equivalent of logical type, such as datetime.date + for dates and decimal.Decimal for decimals. + """ + if self.has_min_max: + _, max_scalar = _cast_statistics(self.statistics.get()) + return max_scalar.as_py() + else: + return None + + @property + def null_count(self): + """Number of null values in chunk (int).""" + if self.has_null_count: + return self.statistics.get().null_count() + else: + return None + + @property + def distinct_count(self): + """Distinct number of values in chunk (int).""" + if self.has_distinct_count: + return self.statistics.get().distinct_count() + else: + return None + + @property + def num_values(self): + """Number of non-null values (int).""" + return self.statistics.get().num_values() + + @property + def physical_type(self): + """Physical type of column (str).""" + raw_physical_type = self.statistics.get().physical_type() + return physical_type_name_from_enum(raw_physical_type) + + @property + def logical_type(self): + """Logical type of column (:class:`ParquetLogicalType`).""" + return wrap_logical_type(self.statistics.get().descr().logical_type()) + + @property + def converted_type(self): + """Legacy converted type (str or None).""" + raw_converted_type = self.statistics.get().descr().converted_type() + return converted_type_name_from_enum(raw_converted_type) + + +cdef class ParquetLogicalType(_Weakrefable): + """Logical type of parquet type.""" + + def __init__(self): + raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly") + + cdef: + shared_ptr[const CParquetLogicalType] type + + def __cinit__(self): + pass + + cdef init(self, const shared_ptr[const CParquetLogicalType]& type): + self.type = type + + def __repr__(self): + return f"{object.__repr__(self)}\n {self}" + + def __str__(self): + return frombytes(self.type.get().ToString(), safe=True) + + def to_json(self): + """ + Get a JSON string containing type and type parameters. + + Returns + ------- + json : str + JSON representation of type, with at least a field called 'Type' + which contains the type name. If the type is parameterized, such + as a decimal with scale and precision, will contain those as fields + as well. + """ + return frombytes(self.type.get().ToJSON()) + + @property + def type(self): + """Name of the logical type (str).""" + return logical_type_name_from_enum(self.type.get().type()) + + +cdef wrap_logical_type(const shared_ptr[const CParquetLogicalType]& type): + cdef ParquetLogicalType out = ParquetLogicalType.__new__(ParquetLogicalType) + out.init(type) + return out + + +cdef _cast_statistic_raw_min(CStatistics* statistics): + cdef ParquetType physical_type = statistics.physical_type() + cdef uint32_t type_length = statistics.descr().type_length() + if physical_type == ParquetType_BOOLEAN: + return ( statistics).min() + elif physical_type == ParquetType_INT32: + return ( statistics).min() + elif physical_type == ParquetType_INT64: + return ( statistics).min() + elif physical_type == ParquetType_FLOAT: + return ( statistics).min() + elif physical_type == ParquetType_DOUBLE: + return ( statistics).min() + elif physical_type == ParquetType_BYTE_ARRAY: + return _box_byte_array(( statistics).min()) + elif physical_type == ParquetType_FIXED_LEN_BYTE_ARRAY: + return _box_flba(( statistics).min(), type_length) + + +cdef _cast_statistic_raw_max(CStatistics* statistics): + cdef ParquetType physical_type = statistics.physical_type() + cdef uint32_t type_length = statistics.descr().type_length() + if physical_type == ParquetType_BOOLEAN: + return ( statistics).max() + elif physical_type == ParquetType_INT32: + return ( statistics).max() + elif physical_type == ParquetType_INT64: + return ( statistics).max() + elif physical_type == ParquetType_FLOAT: + return ( statistics).max() + elif physical_type == ParquetType_DOUBLE: + return ( statistics).max() + elif physical_type == ParquetType_BYTE_ARRAY: + return _box_byte_array(( statistics).max()) + elif physical_type == ParquetType_FIXED_LEN_BYTE_ARRAY: + return _box_flba(( statistics).max(), type_length) + + +cdef _cast_statistics(CStatistics* statistics): + cdef: + shared_ptr[CScalar] c_min + shared_ptr[CScalar] c_max + check_status(StatisticsAsScalars(statistics[0], &c_min, &c_max)) + return (pyarrow_wrap_scalar(c_min), pyarrow_wrap_scalar(c_max)) + + +cdef _box_byte_array(ParquetByteArray val): + return cp.PyBytes_FromStringAndSize( val.ptr, val.len) + + +cdef _box_flba(ParquetFLBA val, uint32_t len): + return cp.PyBytes_FromStringAndSize( val.ptr, len) + + +cdef class GeoStatistics(_Weakrefable): + """Statistics for columns with geospatial data types (experimental) + + These statistics provide a bounding box and list of geometry types for + geospatial columns (GEOMETRY or GEOGRAPHY). All components may be None + if a file does not provide information about a particular component. + """ + + def __init__(self): + raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly") + + def __cinit__(self): + pass + + def __repr__(self): + return f"""{object.__repr__(self)} + geospatial_types: {self.geospatial_types} + xmin: {self.xmin}, xmax: {self.xmax} + ymin: {self.ymin}, ymax: {self.ymax} + zmin: {self.zmin}, zmax: {self.zmax} + mmin: {self.mmin}, mmax: {self.mmax}""" + + def to_dict(self): + """Dictionary summary of these statistics""" + out = { + "geospatial_types": self.geospatial_types, + "xmin": self.xmin, + "xmax": self.xmax, + "ymin": self.ymin, + "ymax": self.ymax, + "zmin": self.zmin, + "zmax": self.zmax, + "mmin": self.mmin, + "mmax": self.mmax + } + + return out + + @property + def geospatial_types(self): + """Unique geometry types + + Contains an integer code for each geometry type code encountered in the + geometries represented by these statistics. The geometry type codes are + ISO WKB geometry type codes returned in sorted order without duplicates. + + This property may be None if geospatial types are not available. + """ + cdef optional[vector[int32_t]] maybe_geometry_types = \ + self.statistics.get().geometry_types() + if not maybe_geometry_types.has_value(): + return None + + return list(maybe_geometry_types.value()) + + @property + def xmin(self): + """Minimum X value or None if not available + + Note that Parquet permits "wraparound" bounds in the X direction only + to more compactly represent bounds for geometries with components on + both sides of the antimeridian. This case is denoted by xmin > xmax. + """ + return self.statistics.get().lower_bound()[0] if self._x_valid() else None + + @property + def xmax(self): + """Maximum X value or None if not available + + Note that Parquet permits "wraparound" bounds in the X direction only + (see xmin). + """ + return self.statistics.get().upper_bound()[0] if self._x_valid() else None + + @property + def ymin(self): + """Minimum Y value or None if not available""" + return self.statistics.get().lower_bound()[1] if self._y_valid() else None + + @property + def ymax(self): + """Maximum Y value or None if not available""" + return self.statistics.get().upper_bound()[1] if self._y_valid() else None + + @property + def zmin(self): + """Minimum Z value or None if not available""" + return self.statistics.get().lower_bound()[2] if self._z_valid() else None + + @property + def zmax(self): + """Maximum Z value or None if not available""" + return self.statistics.get().upper_bound()[2] if self._z_valid() else None + + @property + def mmin(self): + """Minimum M value or None if not available""" + return self.statistics.get().lower_bound()[3] if self._m_valid() else None + + @property + def mmax(self): + """Maximum M value or None if not available""" + return self.statistics.get().upper_bound()[3] if self._m_valid() else None + + # Helpers to calculate the availability of a given dimension. For statistics + # read from a file, dimension_empty should always be false because there is + # no way to represent an empty range in Thrift; however, we check to be safe. + def _x_valid(self): + return self.statistics.get().dimension_valid()[0] \ + and not self.statistics.get().dimension_empty()[0] + + def _y_valid(self): + return self.statistics.get().dimension_valid()[1] \ + and not self.statistics.get().dimension_empty()[1] + + def _z_valid(self): + return self.statistics.get().dimension_valid()[2] \ + and not self.statistics.get().dimension_empty()[2] + + def _m_valid(self): + return self.statistics.get().dimension_valid()[3] \ + and not self.statistics.get().dimension_empty()[3] + + +cdef class ColumnChunkMetaData(_Weakrefable): + """Column metadata for a single row group.""" + + def __init__(self): + raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly") + + def __cinit__(self): + pass + + def __repr__(self): + statistics = indent(repr(self.statistics), 4 * ' ') + geo_statistics = indent(repr(self.geo_statistics), 4 * ' ') + return f"""{object.__repr__(self)} + file_offset: {self.file_offset} + file_path: {self.file_path} + physical_type: {self.physical_type} + num_values: {self.num_values} + path_in_schema: {self.path_in_schema} + is_stats_set: {self.is_stats_set} + statistics: +{statistics} + geo_statistics: +{geo_statistics} + compression: {self.compression} + encodings: {self.encodings} + has_dictionary_page: {self.has_dictionary_page} + dictionary_page_offset: {self.dictionary_page_offset} + data_page_offset: {self.data_page_offset} + total_compressed_size: {self.total_compressed_size} + total_uncompressed_size: {self.total_uncompressed_size}""" + + def to_dict(self): + """ + Get dictionary representation of the column chunk metadata. + + Returns + ------- + dict + Dictionary with a key for each attribute of this class. + """ + statistics = self.statistics.to_dict() if self.is_stats_set else None + if self.is_geo_stats_set: + geo_statistics = self.geo_statistics.to_dict() + else: + geo_statistics = None + + d = dict( + file_offset=self.file_offset, + file_path=self.file_path, + physical_type=self.physical_type, + num_values=self.num_values, + path_in_schema=self.path_in_schema, + is_stats_set=self.is_stats_set, + statistics=statistics, + geo_statistics=geo_statistics, + compression=self.compression, + encodings=self.encodings, + has_dictionary_page=self.has_dictionary_page, + dictionary_page_offset=self.dictionary_page_offset, + data_page_offset=self.data_page_offset, + total_compressed_size=self.total_compressed_size, + total_uncompressed_size=self.total_uncompressed_size + ) + return d + + def __eq__(self, other): + try: + return self.equals(other) + except TypeError: + return NotImplemented + + def equals(self, ColumnChunkMetaData other): + """ + Return whether the two column chunk metadata objects are equal. + + Parameters + ---------- + other : ColumnChunkMetaData + Metadata to compare against. + + Returns + ------- + are_equal : bool + """ + return self.metadata.Equals(deref(other.metadata)) + + @property + def file_offset(self): + """Offset into file where column chunk is located (int).""" + return self.metadata.file_offset() + + @property + def file_path(self): + """Optional file path if set (str or None).""" + return frombytes(self.metadata.file_path()) + + @property + def physical_type(self): + """Physical type of column (str).""" + return physical_type_name_from_enum(self.metadata.type()) + + @property + def num_values(self): + """Total number of values (int).""" + return self.metadata.num_values() + + @property + def path_in_schema(self): + """Nested path to field, separated by periods (str).""" + path = self.metadata.path_in_schema().get().ToDotString() + return frombytes(path) + + @property + def is_stats_set(self): + """Whether or not statistics are present in metadata (bool).""" + return self.metadata.is_stats_set() + + @property + def statistics(self): + """Statistics for column chunk (:class:`Statistics`).""" + if not self.metadata.is_stats_set(): + return None + cdef Statistics statistics = Statistics.__new__(Statistics) + statistics.init(self.metadata.statistics(), self) + return statistics + + @property + def is_geo_stats_set(self): + """Whether or not geometry statistics are present in metadata (bool).""" + return self.metadata.is_geo_stats_set() + + @property + def geo_statistics(self): + """Statistics for column chunk (:class:`GeoStatistics`).""" + c_geo_statistics = self.metadata.geo_statistics() + if not c_geo_statistics or not c_geo_statistics.get().is_valid(): + return None + cdef GeoStatistics geo_statistics = GeoStatistics.__new__(GeoStatistics) + geo_statistics.init(c_geo_statistics, self) + return geo_statistics + + @property + def compression(self): + """ + Type of compression used for column (str). + + One of 'UNCOMPRESSED', 'SNAPPY', 'GZIP', 'LZO', 'BROTLI', 'LZ4', 'ZSTD', + or 'UNKNOWN'. + """ + return compression_name_from_enum(self.metadata.compression()) + + @property + def encodings(self): + """ + Encodings used for column (tuple of str). + + One of 'PLAIN', 'BIT_PACKED', 'RLE', 'BYTE_STREAM_SPLIT', 'DELTA_BINARY_PACKED', + 'DELTA_LENGTH_BYTE_ARRAY', 'DELTA_BYTE_ARRAY'. + """ + return tuple(map(encoding_name_from_enum, self.metadata.encodings())) + + @property + def has_dictionary_page(self): + """Whether there is dictionary data present in the column chunk (bool).""" + return bool(self.metadata.has_dictionary_page()) + + @property + def dictionary_page_offset(self): + """Offset of dictionary page relative to beginning of the file (int).""" + if self.has_dictionary_page: + return self.metadata.dictionary_page_offset() + else: + return None + + @property + def data_page_offset(self): + """Offset of data page relative to beginning of the file (int).""" + return self.metadata.data_page_offset() + + @property + def has_index_page(self): + """Not yet supported.""" + raise NotImplementedError('not supported in parquet-cpp') + + @property + def index_page_offset(self): + """Not yet supported.""" + raise NotImplementedError("parquet-cpp doesn't return valid values") + + @property + def total_compressed_size(self): + """Compressed size in bytes (int).""" + return self.metadata.total_compressed_size() + + @property + def total_uncompressed_size(self): + """Uncompressed size in bytes (int).""" + return self.metadata.total_uncompressed_size() + + @property + def has_offset_index(self): + """Whether the column chunk has an offset index""" + return self.metadata.GetOffsetIndexLocation().has_value() + + @property + def has_column_index(self): + """Whether the column chunk has a column index""" + return self.metadata.GetColumnIndexLocation().has_value() + + @property + def metadata(self): + """Additional metadata as key value pairs (dict[bytes, bytes]).""" + cdef: + unordered_map[c_string, c_string] metadata + const CKeyValueMetadata* underlying_metadata + underlying_metadata = self.metadata.key_value_metadata().get() + if underlying_metadata != NULL: + underlying_metadata.ToUnorderedMap(&metadata) + return metadata + else: + return None + + +cdef class SortingColumn: + """ + Sorting specification for a single column. + + Returned by :meth:`RowGroupMetaData.sorting_columns` and used in + :class:`ParquetWriter` to specify the sort order of the data. + + Parameters + ---------- + column_index : int + Index of column that data is sorted by. + descending : bool, default False + Whether column is sorted in descending order. + nulls_first : bool, default False + Whether null values appear before valid values. + + Notes + ----- + + Column indices are zero-based, refer only to leaf fields, and are in + depth-first order. This may make the column indices for nested schemas + different from what you expect. In most cases, it will be easier to + specify the sort order using column names instead of column indices + and converting using the ``from_ordering`` method. + + Examples + -------- + + In other APIs, sort order is specified by names, such as: + + >>> sort_order = [('id', 'ascending'), ('timestamp', 'descending')] + + For Parquet, the column index must be used instead: + + >>> import pyarrow.parquet as pq + >>> [pq.SortingColumn(0), pq.SortingColumn(1, descending=True)] + [SortingColumn(column_index=0, descending=False, nulls_first=False), SortingColumn(column_index=1, descending=True, nulls_first=False)] + + Convert the sort_order into the list of sorting columns with + ``from_ordering`` (note that the schema must be provided as well): + + >>> import pyarrow as pa + >>> schema = pa.schema([('id', pa.int64()), ('timestamp', pa.timestamp('ms'))]) + >>> sorting_columns = pq.SortingColumn.from_ordering(schema, sort_order) + >>> sorting_columns + (SortingColumn(column_index=0, descending=False, nulls_first=False), SortingColumn(column_index=1, descending=True, nulls_first=False)) + + Convert back to the sort order with ``to_ordering``: + + >>> pq.SortingColumn.to_ordering(schema, sorting_columns) + ((('id', 'ascending'), ('timestamp', 'descending')), 'at_end') + + See Also + -------- + RowGroupMetaData.sorting_columns + """ + cdef int column_index + cdef c_bool descending + cdef c_bool nulls_first + + def __init__(self, int column_index, c_bool descending=False, c_bool nulls_first=False): + self.column_index = column_index + self.descending = descending + self.nulls_first = nulls_first + + @classmethod + def from_ordering(cls, Schema schema, sort_keys, null_placement='at_end'): + """ + Create a tuple of SortingColumn objects from the same arguments as + :class:`pyarrow.compute.SortOptions`. + + Parameters + ---------- + schema : Schema + Schema of the input data. + sort_keys : Sequence of (name, order) tuples + Names of field/column keys (str) to sort the input on, + along with the order each field/column is sorted in. + Accepted values for `order` are "ascending", "descending". + null_placement : {'at_start', 'at_end'}, default 'at_end' + Where null values should appear in the sort order. + + Returns + ------- + sorting_columns : tuple of SortingColumn + """ + if null_placement == 'at_start': + nulls_first = True + elif null_placement == 'at_end': + nulls_first = False + else: + raise ValueError('null_placement must be "at_start" or "at_end"') + + col_map = _name_to_index_map(schema) + + sorting_columns = [] + + for sort_key in sort_keys: + if isinstance(sort_key, str): + name = sort_key + descending = False + elif (isinstance(sort_key, tuple) and len(sort_key) == 2 and + isinstance(sort_key[0], str) and + isinstance(sort_key[1], str)): + name, descending = sort_key + if descending == "descending": + descending = True + elif descending == "ascending": + descending = False + else: + raise ValueError(f"Invalid sort key direction: {descending}") + else: + raise ValueError(f"Invalid sort key: {sort_key}") + + try: + column_index = col_map[name] + except KeyError: + raise ValueError( + f"Sort key name '{name}' not found in schema:\n{schema}") + + sorting_columns.append( + cls(column_index, descending=descending, nulls_first=nulls_first) + ) + + return tuple(sorting_columns) + + @staticmethod + def to_ordering(Schema schema, sorting_columns): + """ + Convert a tuple of SortingColumn objects to the same format as + :class:`pyarrow.compute.SortOptions`. + + Parameters + ---------- + schema : Schema + Schema of the input data. + sorting_columns : tuple of SortingColumn + Columns to sort the input on. + + Returns + ------- + sort_keys : tuple of (name, order) tuples + null_placement : {'at_start', 'at_end'} + """ + col_map = {i: name for name, i in _name_to_index_map(schema).items()} + + sort_keys = [] + nulls_first = None + + for sorting_column in sorting_columns: + name = col_map[sorting_column.column_index] + if sorting_column.descending: + order = "descending" + else: + order = "ascending" + sort_keys.append((name, order)) + if nulls_first is None: + nulls_first = sorting_column.nulls_first + elif nulls_first != sorting_column.nulls_first: + raise ValueError("Sorting columns have inconsistent null placement") + + if nulls_first: + null_placement = "at_start" + else: + null_placement = "at_end" + + return tuple(sort_keys), null_placement + + def __repr__(self): + return f"{self.__class__.__name__}(column_index={self.column_index}, " \ + f"descending={self.descending}, nulls_first={self.nulls_first})" + + def __eq__(self, SortingColumn other): + return (self.column_index == other.column_index and + self.descending == other.descending and + self.nulls_first == other.nulls_first) + + def __hash__(self): + return hash((self.column_index, self.descending, self.nulls_first)) + + @property + def column_index(self): + """"Index of column data is sorted by (int).""" + return self.column_index + + @property + def descending(self): + """Whether column is sorted in descending order (bool).""" + return self.descending + + @property + def nulls_first(self): + """Whether null values appear before valid values (bool).""" + return self.nulls_first + + def to_dict(self): + """ + Get dictionary representation of the SortingColumn. + + Returns + ------- + dict + Dictionary with a key for each attribute of this class. + """ + d = dict( + column_index=self.column_index, + descending=self.descending, + nulls_first=self.nulls_first + ) + return d + + +cdef class RowGroupMetaData(_Weakrefable): + """Metadata for a single row group.""" + + def __init__(self): + raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly") + + def __cinit__(self): + pass + + def __reduce__(self): + return RowGroupMetaData, (self.parent, self.index) + + def __eq__(self, other): + try: + return self.equals(other) + except TypeError: + return NotImplemented + + def equals(self, RowGroupMetaData other): + """ + Return whether the two row group metadata objects are equal. + + Parameters + ---------- + other : RowGroupMetaData + Metadata to compare against. + + Returns + ------- + are_equal : bool + """ + return self.metadata.Equals(deref(other.metadata)) + + def column(self, int i): + """ + Get column metadata at given index. + + Parameters + ---------- + i : int + Index of column to get metadata for. + + Returns + ------- + ColumnChunkMetaData + Metadata for column within this chunk. + """ + if i < 0 or i >= self.num_columns: + raise IndexError(f'{i} out of bounds') + cdef ColumnChunkMetaData chunk = ColumnChunkMetaData.__new__(ColumnChunkMetaData) + chunk.init(self, i) + return chunk + + def __repr__(self): + return f"""{object.__repr__(self)} + num_columns: {self.num_columns} + num_rows: {self.num_rows} + total_byte_size: {self.total_byte_size} + sorting_columns: {self.sorting_columns}""" + + def to_dict(self): + """ + Get dictionary representation of the row group metadata. + + Returns + ------- + dict + Dictionary with a key for each attribute of this class. + """ + columns = [] + d = dict( + num_columns=self.num_columns, + num_rows=self.num_rows, + total_byte_size=self.total_byte_size, + columns=columns, + sorting_columns=[col.to_dict() for col in self.sorting_columns] + ) + for i in range(self.num_columns): + columns.append(self.column(i).to_dict()) + return d + + @property + def num_columns(self): + """Number of columns in this row group (int).""" + return self.metadata.num_columns() + + @property + def num_rows(self): + """Number of rows in this row group (int).""" + return self.metadata.num_rows() + + @property + def total_byte_size(self): + """Total byte size of all the uncompressed column data in this row group (int).""" + return self.metadata.total_byte_size() + + @property + def sorting_columns(self): + """Columns the row group is sorted by (tuple of :class:`SortingColumn`)).""" + out = [] + cdef vector[CSortingColumn] sorting_columns = self.metadata.sorting_columns() + for sorting_col in sorting_columns: + out.append(SortingColumn( + sorting_col.column_idx, + sorting_col.descending, + sorting_col.nulls_first + )) + return tuple(out) + + +def _reconstruct_filemetadata(Buffer serialized): + cdef: + FileMetaData metadata = FileMetaData.__new__(FileMetaData) + CBuffer *buffer = serialized.buffer.get() + uint32_t metadata_len = buffer.size() + + metadata.init(CFileMetaData_Make(buffer.data(), &metadata_len)) + + return metadata + + +cdef class FileMetaData(_Weakrefable): + """Parquet metadata for a single file.""" + + def __init__(self): + raise TypeError(f"Do not call {self.__class__.__name__}'s constructor directly") + + def __cinit__(self): + pass + + def __reduce__(self): + cdef: + NativeFile sink = BufferOutputStream() + COutputStream* c_sink = sink.get_output_stream().get() + with nogil: + self._metadata.WriteTo(c_sink) + + cdef Buffer buffer = sink.getvalue() + return _reconstruct_filemetadata, (buffer,) + + def __hash__(self): + return hash((self.schema, + self.num_rows, + self.num_row_groups, + self.format_version, + self.serialized_size)) + + def __repr__(self): + return f"""{object.__repr__(self)} + created_by: {self.created_by} + num_columns: {self.num_columns} + num_rows: {self.num_rows} + num_row_groups: {self.num_row_groups} + format_version: {self.format_version} + serialized_size: {self.serialized_size}""" + + def to_dict(self): + """ + Get dictionary representation of the file metadata. + + Returns + ------- + dict + Dictionary with a key for each attribute of this class. + """ + row_groups = [] + d = dict( + created_by=self.created_by, + num_columns=self.num_columns, + num_rows=self.num_rows, + num_row_groups=self.num_row_groups, + row_groups=row_groups, + format_version=self.format_version, + serialized_size=self.serialized_size + ) + for i in range(self.num_row_groups): + row_groups.append(self.row_group(i).to_dict()) + return d + + def __eq__(self, other): + try: + return self.equals(other) + except TypeError: + return NotImplemented + + def equals(self, FileMetaData other not None): + """ + Return whether the two file metadata objects are equal. + + Parameters + ---------- + other : FileMetaData + Metadata to compare against. + + Returns + ------- + are_equal : bool + """ + return self._metadata.Equals(deref(other._metadata)) + + @property + def schema(self): + """Schema of the file (:class:`ParquetSchema`).""" + if self._schema is None: + self._schema = ParquetSchema(self) + return self._schema + + @property + def serialized_size(self): + """Size of the original thrift encoded metadata footer (int).""" + return self._metadata.size() + + @property + def num_columns(self): + """Number of columns in file (int).""" + return self._metadata.num_columns() + + @property + def num_rows(self): + """Total number of rows in file (int).""" + return self._metadata.num_rows() + + @property + def num_row_groups(self): + """Number of row groups in file (int).""" + return self._metadata.num_row_groups() + + @property + def format_version(self): + """ + Parquet format version used in file (str, such as '1.0', '2.4'). + + If version is missing or unparsable, will default to assuming '2.6'. + """ + cdef ParquetVersion version = self._metadata.version() + if version == ParquetVersion_V1: + return '1.0' + elif version == ParquetVersion_V2_4: + return '2.4' + elif version == ParquetVersion_V2_6: + return '2.6' + else: + warnings.warn(f'Unrecognized file version, assuming 2.6: {version}') + return '2.6' + + @property + def created_by(self): + """ + String describing source of the parquet file (str). + + This typically includes library name and version number. For example, Arrow 7.0's + writer returns 'parquet-cpp-arrow version 7.0.0'. + """ + return frombytes(self._metadata.created_by()) + + @property + def metadata(self): + """Additional metadata as key value pairs (dict[bytes, bytes]).""" + cdef: + unordered_map[c_string, c_string] metadata + const CKeyValueMetadata* underlying_metadata + underlying_metadata = self._metadata.key_value_metadata().get() + if underlying_metadata != NULL: + underlying_metadata.ToUnorderedMap(&metadata) + return metadata + else: + return None + + def row_group(self, int i): + """ + Get metadata for row group at index i. + + Parameters + ---------- + i : int + Row group index to get. + + Returns + ------- + row_group_metadata : RowGroupMetaData + """ + cdef RowGroupMetaData row_group = RowGroupMetaData.__new__(RowGroupMetaData) + row_group.init(self, i) + return row_group + + def set_file_path(self, path): + """ + Set ColumnChunk file paths to the given value. + + This method modifies the ``file_path`` field of each ColumnChunk + in the FileMetaData to be a particular value. + + Parameters + ---------- + path : str + The file path to set on all ColumnChunks. + """ + cdef: + c_string c_path = tobytes(path) + self._metadata.set_file_path(c_path) + + def append_row_groups(self, FileMetaData other): + """ + Append row groups from other FileMetaData object. + + Parameters + ---------- + other : FileMetaData + Other metadata to append row groups from. + """ + cdef shared_ptr[CFileMetaData] c_metadata + + c_metadata = other.sp_metadata + self._metadata.AppendRowGroups(deref(c_metadata)) + + def write_metadata_file(self, where): + """ + Write the metadata to a metadata-only Parquet file. + + Parameters + ---------- + where : path or file-like object + Where to write the metadata. Should be a writable path on + the local filesystem, or a writable file-like object. + """ + cdef: + shared_ptr[COutputStream] sink + c_string c_where + + try: + where = _stringify_path(where) + except TypeError: + get_writer(where, &sink) + else: + c_where = tobytes(where) + with nogil: + sink = GetResultValue(FileOutputStream.Open(c_where)) + + with nogil: + check_status( + WriteMetaDataFile(deref(self._metadata), sink.get())) + + +cdef class ParquetSchema(_Weakrefable): + """A Parquet schema.""" + + def __cinit__(self, FileMetaData container): + self.parent = container + self.schema = container._metadata.schema() + + def __repr__(self): + return f"{object.__repr__(self)}\n{frombytes(self.schema.ToString(), safe=True)}" + + def __reduce__(self): + return ParquetSchema, (self.parent,) + + def __len__(self): + return self.schema.num_columns() + + def __getitem__(self, i): + return self.column(i) + + def __hash__(self): + return hash(self.schema.ToString()) + + @property + def names(self): + """Name of each field (list of str).""" + return [self[i].name for i in range(len(self))] + + def to_arrow_schema(self): + """ + Convert Parquet schema to effective Arrow schema. + + Returns + ------- + schema : Schema + """ + cdef shared_ptr[CSchema] sp_arrow_schema + + with nogil: + check_status(FromParquetSchema( + self.schema, default_arrow_reader_properties(), + self.parent._metadata.key_value_metadata(), + &sp_arrow_schema)) + + return pyarrow_wrap_schema(sp_arrow_schema) + + def __eq__(self, other): + try: + return self.equals(other) + except TypeError: + return NotImplemented + + def equals(self, ParquetSchema other): + """ + Return whether the two schemas are equal. + + Parameters + ---------- + other : ParquetSchema + Schema to compare against. + + Returns + ------- + are_equal : bool + """ + return self.schema.Equals(deref(other.schema)) + + def column(self, i): + """ + Return the schema for a single column. + + Parameters + ---------- + i : int + Index of column in schema. + + Returns + ------- + column_schema : ColumnSchema + """ + if i < 0 or i >= len(self): + raise IndexError(f'{i} out of bounds') + + return ColumnSchema(self, i) + + +cdef class ColumnSchema(_Weakrefable): + """Schema for a single column.""" + cdef: + int index + ParquetSchema parent + const ColumnDescriptor* descr + + def __cinit__(self, ParquetSchema schema, int index): + self.parent = schema + self.index = index # for pickling support + self.descr = schema.schema.Column(index) + + def __eq__(self, other): + try: + return self.equals(other) + except TypeError: + return NotImplemented + + def __reduce__(self): + return ColumnSchema, (self.parent, self.index) + + def equals(self, ColumnSchema other): + """ + Return whether the two column schemas are equal. + + Parameters + ---------- + other : ColumnSchema + Schema to compare against. + + Returns + ------- + are_equal : bool + """ + return self.descr.Equals(deref(other.descr)) + + def __repr__(self): + physical_type = self.physical_type + converted_type = self.converted_type + if converted_type == 'DECIMAL': + converted_type = f'DECIMAL({self.precision}, {self.scale})' + elif physical_type == 'FIXED_LEN_BYTE_ARRAY': + converted_type = f'FIXED_LEN_BYTE_ARRAY(length={self.length})' + + return f""" + name: {self.name} + path: {self.path} + max_definition_level: {self.max_definition_level} + max_repetition_level: {self.max_repetition_level} + physical_type: {physical_type} + logical_type: {self.logical_type} + converted_type (legacy): {converted_type}""" + + @property + def name(self): + """Name of field (str).""" + return frombytes(self.descr.name()) + + @property + def path(self): + """Nested path to field, separated by periods (str).""" + return frombytes(self.descr.path().get().ToDotString()) + + @property + def max_definition_level(self): + """Maximum definition level (int).""" + return self.descr.max_definition_level() + + @property + def max_repetition_level(self): + """Maximum repetition level (int).""" + return self.descr.max_repetition_level() + + @property + def physical_type(self): + """Name of physical type (str).""" + return physical_type_name_from_enum(self.descr.physical_type()) + + @property + def logical_type(self): + """Logical type of column (:class:`ParquetLogicalType`).""" + return wrap_logical_type(self.descr.logical_type()) + + @property + def converted_type(self): + """Legacy converted type (str or None).""" + return converted_type_name_from_enum(self.descr.converted_type()) + + # FIXED_LEN_BYTE_ARRAY attribute + @property + def length(self): + """Array length if fixed length byte array type, None otherwise (int or None).""" + return self.descr.type_length() + + # Decimal attributes + @property + def precision(self): + """Precision if decimal type, None otherwise (int or None).""" + return self.descr.type_precision() + + @property + def scale(self): + """Scale if decimal type, None otherwise (int or None).""" + return self.descr.type_scale() + + +cdef physical_type_name_from_enum(ParquetType type_): + return { + ParquetType_BOOLEAN: 'BOOLEAN', + ParquetType_INT32: 'INT32', + ParquetType_INT64: 'INT64', + ParquetType_INT96: 'INT96', + ParquetType_FLOAT: 'FLOAT', + ParquetType_DOUBLE: 'DOUBLE', + ParquetType_BYTE_ARRAY: 'BYTE_ARRAY', + ParquetType_FIXED_LEN_BYTE_ARRAY: 'FIXED_LEN_BYTE_ARRAY', + }.get(type_, 'UNKNOWN') + + +cdef logical_type_name_from_enum(ParquetLogicalTypeId type_): + return { + ParquetLogicalType_UNDEFINED: 'UNDEFINED', + ParquetLogicalType_STRING: 'STRING', + ParquetLogicalType_MAP: 'MAP', + ParquetLogicalType_LIST: 'LIST', + ParquetLogicalType_ENUM: 'ENUM', + ParquetLogicalType_DECIMAL: 'DECIMAL', + ParquetLogicalType_DATE: 'DATE', + ParquetLogicalType_TIME: 'TIME', + ParquetLogicalType_TIMESTAMP: 'TIMESTAMP', + ParquetLogicalType_INT: 'INT', + ParquetLogicalType_FLOAT16: 'FLOAT16', + ParquetLogicalType_JSON: 'JSON', + ParquetLogicalType_BSON: 'BSON', + ParquetLogicalType_UUID: 'UUID', + ParquetLogicalType_NONE: 'NONE', + }.get(type_, 'UNKNOWN') + + +cdef converted_type_name_from_enum(ParquetConvertedType type_): + return { + ParquetConvertedType_NONE: 'NONE', + ParquetConvertedType_UTF8: 'UTF8', + ParquetConvertedType_MAP: 'MAP', + ParquetConvertedType_MAP_KEY_VALUE: 'MAP_KEY_VALUE', + ParquetConvertedType_LIST: 'LIST', + ParquetConvertedType_ENUM: 'ENUM', + ParquetConvertedType_DECIMAL: 'DECIMAL', + ParquetConvertedType_DATE: 'DATE', + ParquetConvertedType_TIME_MILLIS: 'TIME_MILLIS', + ParquetConvertedType_TIME_MICROS: 'TIME_MICROS', + ParquetConvertedType_TIMESTAMP_MILLIS: 'TIMESTAMP_MILLIS', + ParquetConvertedType_TIMESTAMP_MICROS: 'TIMESTAMP_MICROS', + ParquetConvertedType_UINT_8: 'UINT_8', + ParquetConvertedType_UINT_16: 'UINT_16', + ParquetConvertedType_UINT_32: 'UINT_32', + ParquetConvertedType_UINT_64: 'UINT_64', + ParquetConvertedType_INT_8: 'INT_8', + ParquetConvertedType_INT_16: 'INT_16', + ParquetConvertedType_INT_32: 'INT_32', + ParquetConvertedType_INT_64: 'INT_64', + ParquetConvertedType_JSON: 'JSON', + ParquetConvertedType_BSON: 'BSON', + ParquetConvertedType_INTERVAL: 'INTERVAL', + }.get(type_, 'UNKNOWN') + + +cdef encoding_name_from_enum(ParquetEncoding encoding_): + return { + ParquetEncoding_PLAIN: 'PLAIN', + ParquetEncoding_PLAIN_DICTIONARY: 'PLAIN_DICTIONARY', + ParquetEncoding_RLE: 'RLE', + ParquetEncoding_BIT_PACKED: 'BIT_PACKED', + ParquetEncoding_DELTA_BINARY_PACKED: 'DELTA_BINARY_PACKED', + ParquetEncoding_DELTA_LENGTH_BYTE_ARRAY: 'DELTA_LENGTH_BYTE_ARRAY', + ParquetEncoding_DELTA_BYTE_ARRAY: 'DELTA_BYTE_ARRAY', + ParquetEncoding_RLE_DICTIONARY: 'RLE_DICTIONARY', + ParquetEncoding_BYTE_STREAM_SPLIT: 'BYTE_STREAM_SPLIT', + }.get(encoding_, 'UNKNOWN') + + +cdef encoding_enum_from_name(str encoding_name): + enc = { + 'PLAIN': ParquetEncoding_PLAIN, + 'BIT_PACKED': ParquetEncoding_BIT_PACKED, + 'RLE': ParquetEncoding_RLE, + 'BYTE_STREAM_SPLIT': ParquetEncoding_BYTE_STREAM_SPLIT, + 'DELTA_BINARY_PACKED': ParquetEncoding_DELTA_BINARY_PACKED, + 'DELTA_LENGTH_BYTE_ARRAY': ParquetEncoding_DELTA_LENGTH_BYTE_ARRAY, + 'DELTA_BYTE_ARRAY': ParquetEncoding_DELTA_BYTE_ARRAY, + 'RLE_DICTIONARY': 'dict', + 'PLAIN_DICTIONARY': 'dict', + }.get(encoding_name, None) + if enc is None: + raise ValueError(f"Unsupported column encoding: {encoding_name!r}") + elif enc == 'dict': + raise ValueError(f"{encoding_name!r} is already used by default.") + else: + return enc + + +cdef compression_name_from_enum(ParquetCompression compression_): + return { + ParquetCompression_UNCOMPRESSED: 'UNCOMPRESSED', + ParquetCompression_SNAPPY: 'SNAPPY', + ParquetCompression_GZIP: 'GZIP', + ParquetCompression_LZO: 'LZO', + ParquetCompression_BROTLI: 'BROTLI', + ParquetCompression_LZ4: 'LZ4', + ParquetCompression_ZSTD: 'ZSTD', + }.get(compression_, 'UNKNOWN') + + +cdef int check_compression_name(name) except -1: + if name.upper() not in {'NONE', 'SNAPPY', 'GZIP', 'LZO', 'BROTLI', 'LZ4', + 'ZSTD'}: + raise ArrowException("Unsupported compression: " + name) + return 0 + + +cdef ParquetCompression compression_from_name(name): + name = name.upper() + if name == 'SNAPPY': + return ParquetCompression_SNAPPY + elif name == 'GZIP': + return ParquetCompression_GZIP + elif name == 'LZO': + return ParquetCompression_LZO + elif name == 'BROTLI': + return ParquetCompression_BROTLI + elif name == 'LZ4': + return ParquetCompression_LZ4 + elif name == 'ZSTD': + return ParquetCompression_ZSTD + else: + return ParquetCompression_UNCOMPRESSED + + +cdef class ParquetReader(_Weakrefable): + cdef: + object source + CMemoryPool* pool + UniquePtrNoGIL[FileReader] reader + FileMetaData _metadata + shared_ptr[CRandomAccessFile] rd_handle + + cdef public: + _column_idx_map + + def __cinit__(self, MemoryPool memory_pool=None): + self.pool = maybe_unbox_memory_pool(memory_pool) + self._metadata = None + + def open(self, object source not None, *, bint use_memory_map=False, + read_dictionary=None, binary_type=None, list_type=None, + FileMetaData metadata=None, + int buffer_size=0, bint pre_buffer=False, + coerce_int96_timestamp_unit=None, + FileDecryptionProperties decryption_properties=None, + thrift_string_size_limit=None, + thrift_container_size_limit=None, + page_checksum_verification=False, + arrow_extensions_enabled=False): + """ + Open a parquet file for reading. + + Parameters + ---------- + source : str, pathlib.Path, pyarrow.NativeFile, or file-like object + use_memory_map : bool, default False + read_dictionary : iterable[int or str], optional + binary_type : pyarrow.DataType, optional + list_type : subclass of pyarrow.DataType, optional + metadata : FileMetaData, optional + buffer_size : int, default 0 + pre_buffer : bool, default False + coerce_int96_timestamp_unit : str, optional + decryption_properties : FileDecryptionProperties, optional + thrift_string_size_limit : int, optional + thrift_container_size_limit : int, optional + page_checksum_verification : bool, default False + arrow_extensions_enabled : bool, default False + """ + cdef: + shared_ptr[CFileMetaData] c_metadata + CReaderProperties properties = default_reader_properties() + ArrowReaderProperties arrow_props = ( + default_arrow_reader_properties()) + FileReaderBuilder builder + + if pre_buffer and not is_threading_enabled(): + pre_buffer = False + + if metadata is not None: + c_metadata = metadata.sp_metadata + + if buffer_size > 0: + properties.enable_buffered_stream() + properties.set_buffer_size(buffer_size) + elif buffer_size == 0: + properties.disable_buffered_stream() + else: + raise ValueError('Buffer size must be larger than zero') + + if thrift_string_size_limit is not None: + if thrift_string_size_limit <= 0: + raise ValueError("thrift_string_size_limit " + "must be larger than zero") + properties.set_thrift_string_size_limit(thrift_string_size_limit) + if thrift_container_size_limit is not None: + if thrift_container_size_limit <= 0: + raise ValueError("thrift_container_size_limit " + "must be larger than zero") + properties.set_thrift_container_size_limit( + thrift_container_size_limit) + + if decryption_properties is not None: + properties.file_decryption_properties( + decryption_properties.unwrap()) + + arrow_props.set_pre_buffer(pre_buffer) + + properties.set_page_checksum_verification(page_checksum_verification) + + if binary_type is not None: + c_binary_type = pyarrow_unwrap_data_type(binary_type) + arrow_props.set_binary_type(c_binary_type.get().id()) + + if list_type is not None: + arrow_props.set_list_type(_unwrap_list_type(list_type)) + + if coerce_int96_timestamp_unit is None: + # use the default defined in default_arrow_reader_properties() + pass + else: + arrow_props.set_coerce_int96_timestamp_unit( + string_to_timeunit(coerce_int96_timestamp_unit)) + + arrow_props.set_arrow_extensions_enabled(arrow_extensions_enabled) + + self.source = source + get_reader(source, use_memory_map, &self.rd_handle) + + with nogil: + check_status(builder.Open(self.rd_handle, properties, c_metadata)) + + # Set up metadata + with nogil: + c_metadata = builder.raw_reader().metadata() + cdef FileMetaData result = FileMetaData.__new__(FileMetaData) + self._metadata = result + result.init(c_metadata) + + if read_dictionary is not None: + self._set_read_dictionary(read_dictionary, &arrow_props) + + with nogil: + check_status(builder.memory_pool(self.pool) + .properties(arrow_props) + .Build(&self.reader)) + + cdef _set_read_dictionary(self, read_dictionary, + ArrowReaderProperties* props): + for column in read_dictionary: + if not isinstance(column, int): + column = self.column_name_idx(column) + props.set_read_dictionary(column, True) + + @property + def column_paths(self): + cdef: + FileMetaData container = self.metadata + const CFileMetaData* metadata = container._metadata + vector[c_string] path + int i = 0 + + paths = [] + for i in range(0, metadata.num_columns()): + path = (metadata.schema().Column(i) + .path().get().ToDotVector()) + paths.append([frombytes(x) for x in path]) + + return paths + + @property + def metadata(self): + return self._metadata + + @property + def schema_arrow(self): + cdef shared_ptr[CSchema] out + with nogil: + check_status(self.reader.get().GetSchema(&out)) + return pyarrow_wrap_schema(out) + + @property + def num_row_groups(self): + return self.reader.get().num_row_groups() + + def set_use_threads(self, bint use_threads): + """ + Parameters + ---------- + use_threads : bool + """ + if is_threading_enabled(): + self.reader.get().set_use_threads(use_threads) + else: + self.reader.get().set_use_threads(False) + + def set_batch_size(self, int64_t batch_size): + """ + Parameters + ---------- + batch_size : int64 + """ + self.reader.get().set_batch_size(batch_size) + + def iter_batches(self, int64_t batch_size, row_groups, column_indices=None, + bint use_threads=True): + """ + Parameters + ---------- + batch_size : int64 + row_groups : list[int] + column_indices : list[int], optional + use_threads : bool, default True + + Yields + ------ + next : RecordBatch + """ + cdef: + vector[int] c_row_groups + vector[int] c_column_indices + shared_ptr[CRecordBatch] record_batch + UniquePtrNoGIL[CRecordBatchReader] recordbatchreader + + self.set_batch_size(batch_size) + + if use_threads: + self.set_use_threads(use_threads) + + for row_group in row_groups: + c_row_groups.push_back(row_group) + + if column_indices is not None: + for index in column_indices: + c_column_indices.push_back(index) + with nogil: + recordbatchreader = GetResultValue( + self.reader.get().GetRecordBatchReader( + c_row_groups, c_column_indices + ) + ) + else: + with nogil: + recordbatchreader = GetResultValue( + self.reader.get().GetRecordBatchReader( + c_row_groups + ) + ) + + while True: + with nogil: + check_status( + recordbatchreader.get().ReadNext(&record_batch) + ) + if record_batch.get() == NULL: + break + + yield pyarrow_wrap_batch(record_batch) + + def read_row_group(self, int i, column_indices=None, + bint use_threads=True): + """ + Parameters + ---------- + i : int + column_indices : list[int], optional + use_threads : bool, default True + + Returns + ------- + table : pyarrow.Table + """ + return self.read_row_groups([i], column_indices, use_threads) + + def read_row_groups(self, row_groups not None, column_indices=None, + bint use_threads=True): + """ + Parameters + ---------- + row_groups : list[int] + column_indices : list[int], optional + use_threads : bool, default True + + Returns + ------- + table : pyarrow.Table + """ + cdef: + shared_ptr[CTable] ctable + vector[int] c_row_groups + vector[int] c_column_indices + + self.set_use_threads(use_threads) + + for row_group in row_groups: + c_row_groups.push_back(row_group) + + if column_indices is not None: + for index in column_indices: + c_column_indices.push_back(index) + + with nogil: + check_status(self.reader.get() + .ReadRowGroups(c_row_groups, c_column_indices, + &ctable)) + else: + # Read all columns + with nogil: + check_status(self.reader.get() + .ReadRowGroups(c_row_groups, &ctable)) + return pyarrow_wrap_table(ctable) + + def read_all(self, column_indices=None, bint use_threads=True): + """ + Parameters + ---------- + column_indices : list[int], optional + use_threads : bool, default True + + Returns + ------- + table : pyarrow.Table + """ + cdef: + shared_ptr[CTable] ctable + vector[int] c_column_indices + + self.set_use_threads(use_threads) + + if column_indices is not None: + for index in column_indices: + c_column_indices.push_back(index) + + with nogil: + check_status(self.reader.get() + .ReadTable(c_column_indices, &ctable)) + else: + # Read all columns + with nogil: + check_status(self.reader.get() + .ReadTable(&ctable)) + return pyarrow_wrap_table(ctable) + + def scan_contents(self, column_indices=None, batch_size=65536): + """ + Parameters + ---------- + column_indices : list[int], optional + batch_size : int32, default 65536 + + Returns + ------- + num_rows : int64 + """ + cdef: + vector[int] c_column_indices + int32_t c_batch_size + int64_t c_num_rows + + if column_indices is not None: + for index in column_indices: + c_column_indices.push_back(index) + + c_batch_size = batch_size + + with nogil: + check_status(self.reader.get() + .ScanContents(c_column_indices, c_batch_size, + &c_num_rows)) + + return c_num_rows + + def column_name_idx(self, column_name): + """ + Find the index of a column by its name. + + Parameters + ---------- + column_name : str + Name of the column; separation of nesting levels is done via ".". + + Returns + ------- + column_idx : int + Integer index of the column in the schema. + """ + cdef: + FileMetaData container = self.metadata + const CFileMetaData* metadata = container._metadata + int i = 0 + + if self._column_idx_map is None: + self._column_idx_map = {} + for i in range(0, metadata.num_columns()): + col_bytes = tobytes(metadata.schema().Column(i) + .path().get().ToDotString()) + self._column_idx_map[col_bytes] = i + + return self._column_idx_map[tobytes(column_name)] + + def read_column(self, int column_index): + """ + Read the column at the specified index. + + Parameters + ---------- + column_index : int + Index of the column. + + Returns + ------- + column : pyarrow.ChunkedArray + """ + cdef shared_ptr[CChunkedArray] out + with nogil: + check_status(self.reader.get() + .ReadColumn(column_index, &out)) + return pyarrow_wrap_chunked_array(out) + + def close(self): + if not self.closed: + with nogil: + check_status(self.rd_handle.get().Close()) + + @property + def closed(self): + if self.rd_handle == NULL: + return True + with nogil: + closed = self.rd_handle.get().closed() + return closed + + +cdef CSortingColumn _convert_sorting_column(SortingColumn sorting_column): + cdef CSortingColumn c_sorting_column + + c_sorting_column.column_idx = sorting_column.column_index + c_sorting_column.descending = sorting_column.descending + c_sorting_column.nulls_first = sorting_column.nulls_first + + return c_sorting_column + + +cdef vector[CSortingColumn] _convert_sorting_columns(sorting_columns) except *: + if not (isinstance(sorting_columns, Sequence) + and all(isinstance(col, SortingColumn) for col in sorting_columns)): + raise ValueError( + "'sorting_columns' must be a list of `SortingColumn`") + + cdef vector[CSortingColumn] c_sorting_columns = [_convert_sorting_column(col) + for col in sorting_columns] + + return c_sorting_columns + + +cdef shared_ptr[WriterProperties] _create_writer_properties( + use_dictionary=None, + compression=None, + version=None, + write_statistics=None, + data_page_size=None, + max_rows_per_page=None, + compression_level=None, + use_byte_stream_split=False, + column_encoding=None, + data_page_version=None, + FileEncryptionProperties encryption_properties=None, + write_batch_size=None, + dictionary_pagesize_limit=None, + write_page_index=False, + write_page_checksum=False, + sorting_columns=None, + store_decimal_as_integer=False, + use_content_defined_chunking=False) except *: + + """General writer properties""" + cdef: + shared_ptr[WriterProperties] properties + WriterProperties.Builder props + CdcOptions cdc_options + + # data_page_version + + if data_page_version is not None: + if data_page_version == "1.0": + props.data_page_version(ParquetDataPageVersion_V1) + elif data_page_version == "2.0": + props.data_page_version(ParquetDataPageVersion_V2) + else: + raise ValueError( + f"Unsupported Parquet data page version: {data_page_version}") + + # version + + if version is not None: + if version == "1.0": + props.version(ParquetVersion_V1) + elif version == "2.4": + props.version(ParquetVersion_V2_4) + elif version == "2.6": + props.version(ParquetVersion_V2_6) + else: + raise ValueError(f"Unsupported Parquet format version: {version}") + + # compression + + if isinstance(compression, basestring): + check_compression_name(compression) + props.compression(compression_from_name(compression)) + elif compression is not None: + for column, codec in compression.iteritems(): + check_compression_name(codec) + props.compression(tobytes(column), compression_from_name(codec)) + + if isinstance(compression_level, int): + props.compression_level(compression_level) + elif compression_level is not None: + for column, level in compression_level.iteritems(): + props.compression_level(tobytes(column), level) + + # use_dictionary + + if isinstance(use_dictionary, bool): + if use_dictionary: + props.enable_dictionary() + if column_encoding is not None: + raise ValueError( + "To use 'column_encoding' set 'use_dictionary' to False") + else: + props.disable_dictionary() + elif use_dictionary is not None: + # Deactivate dictionary encoding by default + props.disable_dictionary() + for column in use_dictionary: + props.enable_dictionary(tobytes(column)) + if (column_encoding is not None and + column_encoding.get(column) is not None): + raise ValueError( + "To use 'column_encoding' set 'use_dictionary' to False") + + # write_statistics + + if isinstance(write_statistics, bool): + if write_statistics: + props.enable_statistics() + else: + props.disable_statistics() + elif write_statistics is not None: + # Deactivate statistics by default and enable for specified columns + props.disable_statistics() + for column in write_statistics: + props.enable_statistics(tobytes(column)) + + # sorting_columns + + if sorting_columns is not None: + props.set_sorting_columns(_convert_sorting_columns(sorting_columns)) + + # use_byte_stream_split + + if isinstance(use_byte_stream_split, bool): + if use_byte_stream_split: + if column_encoding is not None: + raise ValueError( + "'use_byte_stream_split' cannot be passed" + "together with 'column_encoding'") + else: + props.encoding(ParquetEncoding_BYTE_STREAM_SPLIT) + elif use_byte_stream_split is not None: + for column in use_byte_stream_split: + if column_encoding is None: + column_encoding = {column: 'BYTE_STREAM_SPLIT'} + elif column_encoding.get(column, None) is None: + column_encoding[column] = 'BYTE_STREAM_SPLIT' + else: + raise ValueError( + "'use_byte_stream_split' cannot be passed" + "together with 'column_encoding'") + + # store_decimal_as_integer + + if isinstance(store_decimal_as_integer, bool): + if store_decimal_as_integer: + props.enable_store_decimal_as_integer() + else: + props.disable_store_decimal_as_integer() + else: + raise TypeError("'store_decimal_as_integer' must be a boolean") + + # column_encoding + # encoding map - encode individual columns + + if column_encoding is not None: + if isinstance(column_encoding, dict): + for column, _encoding in column_encoding.items(): + props.encoding(tobytes(column), + encoding_enum_from_name(_encoding)) + elif isinstance(column_encoding, str): + props.encoding(encoding_enum_from_name(column_encoding)) + else: + raise TypeError( + "'column_encoding' should be a dictionary or a string") + + # size limits + if data_page_size is not None: + props.data_pagesize(data_page_size) + + if max_rows_per_page is not None: + props.max_rows_per_page(max_rows_per_page) + + if write_batch_size is not None: + props.write_batch_size(write_batch_size) + + if dictionary_pagesize_limit is not None: + props.dictionary_pagesize_limit(dictionary_pagesize_limit) + + # content defined chunking + + if use_content_defined_chunking is True: + props.enable_content_defined_chunking() + elif use_content_defined_chunking is False: + props.disable_content_defined_chunking() + elif isinstance(use_content_defined_chunking, dict): + defined_keys = use_content_defined_chunking.keys() + mandatory_keys = {"min_chunk_size", "max_chunk_size"} + allowed_keys = {"min_chunk_size", "max_chunk_size", "norm_level"} + unknown_keys = defined_keys - allowed_keys + missing_keys = mandatory_keys - defined_keys + if unknown_keys: + raise ValueError( + f"Unknown options in 'use_content_defined_chunking': {unknown_keys}") + if missing_keys: + raise ValueError( + f"Missing options in 'use_content_defined_chunking': {missing_keys}") + cdc_options.min_chunk_size = use_content_defined_chunking["min_chunk_size"] + cdc_options.max_chunk_size = use_content_defined_chunking["max_chunk_size"] + cdc_options.norm_level = use_content_defined_chunking.get("norm_level", 0) + props.enable_content_defined_chunking() + props.content_defined_chunking_options(cdc_options) + else: + raise TypeError( + "'use_content_defined_chunking' should be either boolean or a dictionary") + + # encryption + + if encryption_properties is not None: + props.encryption( + (encryption_properties).unwrap()) + + # For backwards compatibility reasons we cap the maximum row group size + # at 64Mi rows. This could be changed in the future, though it would be + # a breaking change. + # + # The user can always specify a smaller row group size (and the default + # is smaller) when calling write_table. If the call to write_table uses + # a size larger than this then it will be latched to this value. + props.max_row_group_length(_MAX_ROW_GROUP_SIZE) + + # checksum + + if write_page_checksum: + props.enable_page_checksum() + else: + props.disable_page_checksum() + + # page index + + if write_page_index: + props.enable_write_page_index() + else: + props.disable_write_page_index() + + properties = props.build() + + return properties + + +cdef shared_ptr[ArrowWriterProperties] _create_arrow_writer_properties( + use_deprecated_int96_timestamps=False, + coerce_timestamps=None, + allow_truncated_timestamps=False, + writer_engine_version=None, + use_compliant_nested_type=True, + store_schema=True, + write_time_adjusted_to_utc=False) except *: + """Arrow writer properties""" + cdef: + shared_ptr[ArrowWriterProperties] arrow_properties + ArrowWriterProperties.Builder arrow_props + + # Store the original Arrow schema so things like dictionary types can + # be automatically reconstructed + if store_schema: + arrow_props.store_schema() + + # int96 support + + if use_deprecated_int96_timestamps: + arrow_props.enable_deprecated_int96_timestamps() + else: + arrow_props.disable_deprecated_int96_timestamps() + + # coerce_timestamps + + if coerce_timestamps == 'ms': + arrow_props.coerce_timestamps(TimeUnit_MILLI) + elif coerce_timestamps == 'us': + arrow_props.coerce_timestamps(TimeUnit_MICRO) + elif coerce_timestamps is not None: + raise ValueError(f'Invalid value for coerce_timestamps: {coerce_timestamps}') + + # allow_truncated_timestamps + + if allow_truncated_timestamps: + arrow_props.allow_truncated_timestamps() + else: + arrow_props.disallow_truncated_timestamps() + + # use_compliant_nested_type + + if use_compliant_nested_type: + arrow_props.enable_compliant_nested_types() + else: + arrow_props.disable_compliant_nested_types() + + # writer_engine_version + + if writer_engine_version == "V1": + warnings.warn("V1 parquet writer engine is a no-op. Use V2.") + arrow_props.set_engine_version(ArrowWriterEngineVersion.V1) + elif writer_engine_version != "V2": + raise ValueError(f"Unsupported Writer Engine Version: {writer_engine_version}") + + arrow_props.set_time_adjusted_to_utc(write_time_adjusted_to_utc) + + arrow_properties = arrow_props.build() + + return arrow_properties + +cdef _name_to_index_map(Schema arrow_schema): + cdef: + shared_ptr[CSchema] sp_arrow_schema + shared_ptr[SchemaDescriptor] sp_parquet_schema + shared_ptr[WriterProperties] props = _create_writer_properties() + shared_ptr[ArrowWriterProperties] arrow_props = _create_arrow_writer_properties( + use_deprecated_int96_timestamps=False, + coerce_timestamps=None, + allow_truncated_timestamps=False, + writer_engine_version="V2" + ) + + sp_arrow_schema = pyarrow_unwrap_schema(arrow_schema) + + with nogil: + check_status(ToParquetSchema( + sp_arrow_schema.get(), deref(props.get()), deref(arrow_props.get()), &sp_parquet_schema)) + + out = dict() + + cdef SchemaDescriptor* parquet_schema = sp_parquet_schema.get() + + for i in range(parquet_schema.num_columns()): + name = frombytes(parquet_schema.Column(i).path().get().ToDotString()) + out[name] = i + + return out + + +cdef class ParquetWriter(_Weakrefable): + cdef: + unique_ptr[FileWriter] writer + shared_ptr[COutputStream] sink + bint own_sink + + def __cinit__(self, where, Schema schema not None, use_dictionary=None, + compression=None, version=None, + write_statistics=None, + MemoryPool memory_pool=None, + use_deprecated_int96_timestamps=False, + coerce_timestamps=None, + data_page_size=None, + max_rows_per_page=None, + allow_truncated_timestamps=False, + compression_level=None, + use_byte_stream_split=False, + column_encoding=None, + writer_engine_version=None, + data_page_version=None, + use_compliant_nested_type=True, + encryption_properties=None, + write_batch_size=None, + dictionary_pagesize_limit=None, + store_schema=True, + write_page_index=False, + write_page_checksum=False, + sorting_columns=None, + store_decimal_as_integer=False, + use_content_defined_chunking=False, + write_time_adjusted_to_utc=False): + cdef: + shared_ptr[WriterProperties] properties + shared_ptr[ArrowWriterProperties] arrow_properties + c_string c_where + CMemoryPool* pool + + try: + where = _stringify_path(where) + except TypeError: + get_writer(where, &self.sink) + self.own_sink = False + else: + c_where = tobytes(where) + with nogil: + self.sink = GetResultValue(FileOutputStream.Open(c_where)) + self.own_sink = True + + properties = _create_writer_properties( + use_dictionary=use_dictionary, + compression=compression, + version=version, + write_statistics=write_statistics, + data_page_size=data_page_size, + max_rows_per_page=max_rows_per_page, + compression_level=compression_level, + use_byte_stream_split=use_byte_stream_split, + column_encoding=column_encoding, + data_page_version=data_page_version, + encryption_properties=encryption_properties, + write_batch_size=write_batch_size, + dictionary_pagesize_limit=dictionary_pagesize_limit, + write_page_index=write_page_index, + write_page_checksum=write_page_checksum, + sorting_columns=sorting_columns, + store_decimal_as_integer=store_decimal_as_integer, + use_content_defined_chunking=use_content_defined_chunking + ) + arrow_properties = _create_arrow_writer_properties( + use_deprecated_int96_timestamps=use_deprecated_int96_timestamps, + coerce_timestamps=coerce_timestamps, + allow_truncated_timestamps=allow_truncated_timestamps, + writer_engine_version=writer_engine_version, + use_compliant_nested_type=use_compliant_nested_type, + store_schema=store_schema, + write_time_adjusted_to_utc=write_time_adjusted_to_utc, + ) + + pool = maybe_unbox_memory_pool(memory_pool) + with nogil: + self.writer = move(GetResultValue( + FileWriter.Open(deref(schema.schema), pool, + self.sink, properties, arrow_properties))) + + def close(self): + with nogil: + check_status(self.writer.get().Close()) + if self.own_sink: + check_status(self.sink.get().Close()) + + def write_table(self, Table table, row_group_size=None): + cdef: + CTable* ctable = table.table + int64_t c_row_group_size + + if row_group_size is None or row_group_size == -1: + c_row_group_size = min(ctable.num_rows(), _DEFAULT_ROW_GROUP_SIZE) + elif row_group_size == 0: + raise ValueError('Row group size cannot be 0') + else: + c_row_group_size = row_group_size + + with nogil: + check_status(self.writer.get() + .WriteTable(deref(ctable), c_row_group_size)) + + def add_key_value_metadata(self, key_value_metadata): + cdef: + shared_ptr[const CKeyValueMetadata] c_metadata + + c_metadata = pyarrow_unwrap_metadata(KeyValueMetadata(key_value_metadata)) + with nogil: + check_status(self.writer.get() + .AddKeyValueMetadata(c_metadata)) + + @property + def metadata(self): + cdef: + shared_ptr[CFileMetaData] metadata + FileMetaData result + with nogil: + metadata = self.writer.get().metadata() + if metadata: + result = FileMetaData.__new__(FileMetaData) + result.init(metadata) + return result + raise RuntimeError( + 'file metadata is only available after writer close') diff --git a/shared/package-files/ab/ab448355bce6538ebff267fadd46a8e69604e0c832ae147dbe7f78409a904aff/blob b/shared/package-files/ab/ab448355bce6538ebff267fadd46a8e69604e0c832ae147dbe7f78409a904aff/blob new file mode 100644 index 0000000000000000000000000000000000000000..9a0cb09077ffa35e32d23326bd63b52f60f1ba74 --- /dev/null +++ b/shared/package-files/ab/ab448355bce6538ebff267fadd46a8e69604e0c832ae147dbe7f78409a904aff/blob @@ -0,0 +1,220 @@ +""" +Known facts in assumptions module. + +This module defines the facts between unary predicates in ``get_known_facts()``, +and supports functions to generate the contents in +``sympy.assumptions.ask_generated`` file. +""" + +from sympy.assumptions.ask import Q +from sympy.assumptions.assume import AppliedPredicate +from sympy.core.cache import cacheit +from sympy.core.symbol import Symbol +from sympy.logic.boolalg import (to_cnf, And, Not, Implies, Equivalent, + Exclusive,) +from sympy.logic.inference import satisfiable + + +@cacheit +def get_composite_predicates(): + # To reduce the complexity of sat solver, these predicates are + # transformed into the combination of primitive predicates. + return { + Q.real : Q.negative | Q.zero | Q.positive, + Q.integer : Q.even | Q.odd, + Q.nonpositive : Q.negative | Q.zero, + Q.nonzero : Q.negative | Q.positive, + Q.nonnegative : Q.zero | Q.positive, + Q.extended_real : Q.negative_infinite | Q.negative | Q.zero | Q.positive | Q.positive_infinite, + Q.extended_positive: Q.positive | Q.positive_infinite, + Q.extended_negative: Q.negative | Q.negative_infinite, + Q.extended_nonzero: Q.negative_infinite | Q.negative | Q.positive | Q.positive_infinite, + Q.extended_nonpositive: Q.negative_infinite | Q.negative | Q.zero, + Q.extended_nonnegative: Q.zero | Q.positive | Q.positive_infinite, + Q.complex : Q.algebraic | Q.transcendental + } + + +@cacheit +def get_known_facts(x=None): + """ + Facts between unary predicates. + + Parameters + ========== + + x : Symbol, optional + Placeholder symbol for unary facts. Default is ``Symbol('x')``. + + Returns + ======= + + fact : Known facts in conjugated normal form. + + """ + if x is None: + x = Symbol('x') + + fact = And( + # primitive predicates for extended real exclude each other. + Exclusive(Q.negative_infinite(x), Q.negative(x), Q.zero(x), + Q.positive(x), Q.positive_infinite(x)), + + # build complex plane + Exclusive(Q.real(x), Q.imaginary(x)), + Implies(Q.real(x) | Q.imaginary(x), Q.complex(x)), + + # other subsets of complex + Exclusive(Q.transcendental(x), Q.algebraic(x)), + Equivalent(Q.real(x), Q.rational(x) | Q.irrational(x)), + Exclusive(Q.irrational(x), Q.rational(x)), + Implies(Q.rational(x), Q.algebraic(x)), + + # integers + Exclusive(Q.even(x), Q.odd(x)), + Implies(Q.integer(x), Q.rational(x)), + Implies(Q.zero(x), Q.even(x)), + Exclusive(Q.composite(x), Q.prime(x)), + Implies(Q.composite(x) | Q.prime(x), Q.integer(x) & Q.positive(x)), + Implies(Q.even(x) & Q.positive(x) & ~Q.prime(x), Q.composite(x)), + + # hermitian and antihermitian + Implies(Q.real(x), Q.hermitian(x)), + Implies(Q.imaginary(x), Q.antihermitian(x)), + Implies(Q.zero(x), Q.hermitian(x) | Q.antihermitian(x)), + + # define finity and infinity, and build extended real line + Exclusive(Q.infinite(x), Q.finite(x)), + Implies(Q.complex(x), Q.finite(x)), + Implies(Q.negative_infinite(x) | Q.positive_infinite(x), Q.infinite(x)), + + # commutativity + Implies(Q.finite(x) | Q.infinite(x), Q.commutative(x)), + + # matrices + Implies(Q.orthogonal(x), Q.positive_definite(x)), + Implies(Q.orthogonal(x), Q.unitary(x)), + Implies(Q.unitary(x) & Q.real_elements(x), Q.orthogonal(x)), + Implies(Q.unitary(x), Q.normal(x)), + Implies(Q.unitary(x), Q.invertible(x)), + Implies(Q.normal(x), Q.square(x)), + Implies(Q.diagonal(x), Q.normal(x)), + Implies(Q.positive_definite(x), Q.invertible(x)), + Implies(Q.diagonal(x), Q.upper_triangular(x)), + Implies(Q.diagonal(x), Q.lower_triangular(x)), + Implies(Q.lower_triangular(x), Q.triangular(x)), + Implies(Q.upper_triangular(x), Q.triangular(x)), + Implies(Q.triangular(x), Q.upper_triangular(x) | Q.lower_triangular(x)), + Implies(Q.upper_triangular(x) & Q.lower_triangular(x), Q.diagonal(x)), + Implies(Q.diagonal(x), Q.symmetric(x)), + Implies(Q.unit_triangular(x), Q.triangular(x)), + Implies(Q.invertible(x), Q.fullrank(x)), + Implies(Q.invertible(x), Q.square(x)), + Implies(Q.symmetric(x), Q.square(x)), + Implies(Q.fullrank(x) & Q.square(x), Q.invertible(x)), + Equivalent(Q.invertible(x), ~Q.singular(x)), + Implies(Q.integer_elements(x), Q.real_elements(x)), + Implies(Q.real_elements(x), Q.complex_elements(x)), + ) + return fact + + +def generate_known_facts_dict(keys, fact): + """ + Computes and returns a dictionary which contains the relations between + unary predicates. + + Each key is a predicate, and item is two groups of predicates. + First group contains the predicates which are implied by the key, and + second group contains the predicates which are rejected by the key. + + All predicates in *keys* and *fact* must be unary and have same placeholder + symbol. + + Parameters + ========== + + keys : list of AppliedPredicate instances. + + fact : Fact between predicates in conjugated normal form. + + Examples + ======== + + >>> from sympy import Q, And, Implies + >>> from sympy.assumptions.facts import generate_known_facts_dict + >>> from sympy.abc import x + >>> keys = [Q.even(x), Q.odd(x), Q.zero(x)] + >>> fact = And(Implies(Q.even(x), ~Q.odd(x)), + ... Implies(Q.zero(x), Q.even(x))) + >>> generate_known_facts_dict(keys, fact) + {Q.even: ({Q.even}, {Q.odd}), + Q.odd: ({Q.odd}, {Q.even, Q.zero}), + Q.zero: ({Q.even, Q.zero}, {Q.odd})} + """ + fact_cnf = to_cnf(fact) + mapping = single_fact_lookup(keys, fact_cnf) + + ret = {} + for key, value in mapping.items(): + implied = set() + rejected = set() + for expr in value: + if isinstance(expr, AppliedPredicate): + implied.add(expr.function) + elif isinstance(expr, Not): + pred = expr.args[0] + rejected.add(pred.function) + ret[key.function] = (implied, rejected) + return ret + + +@cacheit +def get_known_facts_keys(): + """ + Return every unary predicates registered to ``Q``. + + This function is used to generate the keys for + ``generate_known_facts_dict``. + + """ + exclude = set() + for pred in [Q.eq, Q.ne, Q.gt, Q.lt, Q.ge, Q.le]: + # exclude polyadic predicates + exclude.add(pred) + + result = [] + for attr in Q.__class__.__dict__: + if attr.startswith('__'): + continue + pred = getattr(Q, attr) + if pred in exclude: + continue + result.append(pred) + return result + + +def single_fact_lookup(known_facts_keys, known_facts_cnf): + # Return the dictionary for quick lookup of single fact + mapping = {} + for key in known_facts_keys: + mapping[key] = {key} + for other_key in known_facts_keys: + if other_key != key: + if ask_full_inference(other_key, key, known_facts_cnf): + mapping[key].add(other_key) + if ask_full_inference(~other_key, key, known_facts_cnf): + mapping[key].add(~other_key) + return mapping + + +def ask_full_inference(proposition, assumptions, known_facts_cnf): + """ + Method for inferring properties about objects. + + """ + if not satisfiable(And(known_facts_cnf, assumptions, proposition)): + return False + if not satisfiable(And(known_facts_cnf, assumptions, Not(proposition))): + return True + return None diff --git a/shared/package-files/ab/ab49726ba95b3ade0752e8de7edbd368aca9ac02ad53fc1f7fdc6ae2de917513/blob b/shared/package-files/ab/ab49726ba95b3ade0752e8de7edbd368aca9ac02ad53fc1f7fdc6ae2de917513/blob new file mode 100644 index 0000000000000000000000000000000000000000..172213fb0c171312f78d2088f17d69dacc96c1eb --- /dev/null +++ b/shared/package-files/ab/ab49726ba95b3ade0752e8de7edbd368aca9ac02ad53fc1f7fdc6ae2de917513/blob @@ -0,0 +1,54 @@ +from typing import Iterator, Tuple, Union +from .api import ShardedOptimizer + +import torch.nn as nn + +from torch.distributed._shard.sharded_tensor import ( + ShardedTensor +) + +def named_params_with_sharded_tensor( + module: nn.Module, + prefix: str = '', + recurse: bool = True, +) -> Iterator[Tuple[str, Union[nn.Parameter, ShardedTensor]]]: + + r"""Returns an iterator over module parameters (together with the + ShardedTensor parameters), yielding both the name of the parameter + as well as the parameter itself. This is typically passed to a + :class:torch.distributed._shard.sharded_optim.ShardedOptimizer + + Args: + prefix (str): prefix to prepend to all parameter names. + recurse (bool): if True, then yields parameters of this module + and all submodules. Otherwise, yields only parameters that + are direct members of this module. + + Yields: + (str, Union[Tensor, ShardedTensor]): Tuple containing + the name and parameter (or ShardedTensor parameter) + + Example:: + + >>> # xdoctest: +SKIP + >>> model = torch.nn.Linear(*linear_size) + >>> shard_parameter(model, "weight", spec) + >>> for name, param in named_params_with_sharded_tensor(model): + >>> if name in ['weight']: + >>> print(param.size()) + + """ + modules = module.named_modules(prefix=prefix) if recurse else [(prefix, module)] + + memo = set() + for mod_prefix, mod in modules: + # find all sharded tensor params + for name, val in vars(mod).items(): + if isinstance(val, ShardedTensor) and val not in memo: + memo.add(val) + name = mod_prefix + ('.' if mod_prefix else '') + name + yield name, val + + # find all nn.Parameters + for name, val in module.named_parameters(): + yield name, val diff --git a/shared/package-files/ab/ab4aa14c3d499d41f5c5930d56d69fd453de2bd55fde554e854ca6b0cc7714fd/blob b/shared/package-files/ab/ab4aa14c3d499d41f5c5930d56d69fd453de2bd55fde554e854ca6b0cc7714fd/blob new file mode 100644 index 0000000000000000000000000000000000000000..c7d49edece6f04feb87c7fc3442814ece5b45b08 --- /dev/null +++ b/shared/package-files/ab/ab4aa14c3d499d41f5c5930d56d69fd453de2bd55fde554e854ca6b0cc7714fd/blob @@ -0,0 +1,40 @@ +""" +Utilities imported from ipython_genutils +""" + +import re +import textwrap +from textwrap import dedent +from textwrap import indent as _indent +from typing import List + + +def indent(val): + res = _indent(val, " ") + return res + + +def wrap_paragraphs(text: str, ncols: int = 80) -> List[str]: + """Wrap multiple paragraphs to fit a specified width. + + This is equivalent to textwrap.wrap, but with support for multiple + paragraphs, as separated by empty lines. + + Returns + ------- + + list of complete paragraphs, wrapped to fill `ncols` columns. + """ + paragraph_re = re.compile(r"\n(\s*\n)+", re.MULTILINE) + text = dedent(text).strip() + paragraphs = paragraph_re.split(text)[::2] # every other entry is space + out_ps = [] + indent_re = re.compile(r"\n\s+", re.MULTILINE) + for p in paragraphs: + # presume indentation that survives dedent is meaningful formatting, + # so don't fill unless text is flush. + if indent_re.search(p) is None: + # wrap paragraph + p = textwrap.fill(p, ncols) + out_ps.append(p) + return out_ps diff --git a/shared/package-files/ab/ab4c2456e1557560999802b513b581427ca6f0f3e3dd01d0e244956ec4a9e3d9/blob b/shared/package-files/ab/ab4c2456e1557560999802b513b581427ca6f0f3e3dd01d0e244956ec4a9e3d9/blob new file mode 100644 index 0000000000000000000000000000000000000000..2b92fd940a35bfe6b1e44c0f300224bdd3661b1f --- /dev/null +++ b/shared/package-files/ab/ab4c2456e1557560999802b513b581427ca6f0f3e3dd01d0e244956ec4a9e3d9/blob @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API ::std::tuple _embedding_bag_forward_only(const at::Tensor & weight, const at::Tensor & indices, const at::Tensor & offsets, bool scale_grad_by_freq=false, int64_t mode=0, bool sparse=false, const c10::optional & per_sample_weights={}, bool include_last_offset=false, int64_t padding_idx=-1); + +} // namespace cpu +} // namespace at diff --git a/shared/package-files/ab/ab50bb896a6f743ca611464dcb326f64bb0bb60c12918b428b1304f9f632203c/blob b/shared/package-files/ab/ab50bb896a6f743ca611464dcb326f64bb0bb60c12918b428b1304f9f632203c/blob new file mode 100644 index 0000000000000000000000000000000000000000..8e294544bfdce13633ecff762ff42861aa12719f --- /dev/null +++ b/shared/package-files/ab/ab50bb896a6f743ca611464dcb326f64bb0bb60c12918b428b1304f9f632203c/blob @@ -0,0 +1,5 @@ +""" +Module to implement predicate classes. + +Class of every predicate registered to ``Q`` is defined here. +""" diff --git a/shared/package-files/ab/ab5117f4081cab5c6cb575d6c8dc1b24220b3e596b9d3b5206d6dbf8869b00da/blob b/shared/package-files/ab/ab5117f4081cab5c6cb575d6c8dc1b24220b3e596b9d3b5206d6dbf8869b00da/blob new file mode 100644 index 0000000000000000000000000000000000000000..931cd86e77d984cc3b69aca0516b7c3489320825 --- /dev/null +++ b/shared/package-files/ab/ab5117f4081cab5c6cb575d6c8dc1b24220b3e596b9d3b5206d6dbf8869b00da/blob @@ -0,0 +1,560 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace at { + +class Tensor; + +enum class TORCH_API Float32MatmulPrecision { HIGHEST, HIGH, MEDIUM }; + +class TORCH_API Context { + public: + Context(); + + const Generator& defaultGenerator(Device device) { + c10::DeviceType device_type = device.type(); + initCUDAIfNeeded(device_type); + initHIPIfNeeded(device_type); + if (device_type == at::kCPU) { + return at::detail::getDefaultCPUGenerator(); + } else if (device_type == at::kCUDA) { + return at::detail::getCUDAHooks().getDefaultCUDAGenerator(device.index()); + } else if (device_type == at::kMPS) { + return at::detail::getMPSHooks().getDefaultMPSGenerator(); + } else if (device_type == at::kXPU) { + return at::detail::getXPUHooks().getDefaultXPUGenerator(device.index()); + } else if (device_type == at::kIPU) { + return at::detail::getIPUHooks().getDefaultIPUGenerator(device.index()); + } else if (device_type == at::kPrivateUse1) { + return at::GetPrivateUse1HooksInterface()->getDefaultGenerator( + device.index()); + } else { + AT_ERROR(c10::DeviceTypeName(device_type), " device type not enabled."); + } + } + const AcceleratorHooksInterface& getAcceleratorHooksInterface( + c10::optional opt_device_type = c10::nullopt) { + c10::DeviceType device_type = opt_device_type.has_value() + ? opt_device_type.value() + : at::getAccelerator(true).value(); + if (device_type == at::kCUDA) { + return at::detail::getCUDAHooks(); + } else if (device_type == at::kMPS) { + return at::detail::getMPSHooks(); + } else if (device_type == at::kPrivateUse1) { + return at::detail::getPrivateUse1Hooks(); + } else { + AT_ERROR( + c10::DeviceTypeName(device_type), " device type not an accelerator."); + } + } + Device getDeviceFromPtr(void* data, c10::DeviceType device_type) { + initCUDAIfNeeded(device_type); + initHIPIfNeeded(device_type); + initXPUIfNeeded(device_type); + if (device_type == at::kCPU) { + return c10::DeviceType::CPU; + } else if (device_type == at::kCUDA) { + return at::detail::getCUDAHooks().getDeviceFromPtr(data); + } else if (device_type == at::kXPU) { + return at::detail::getXPUHooks().getDeviceFromPtr(data); + } else if (device_type == at::kPrivateUse1) { + return at::GetPrivateUse1HooksInterface()->getDeviceFromPtr(data); + } else { + AT_ERROR(c10::DeviceTypeName(device_type), " device type not enabled."); + } + } + static bool isPinnedPtr(const void* data) { + return detail::getCUDAHooks().isPinnedPtr(data); + } + static bool hasOpenMP(); + static bool hasMKL(); + static bool hasLAPACK(); + static bool hasMKLDNN(); + static bool hasMAGMA() { + return detail::getCUDAHooks().hasMAGMA(); + } + static bool hasCUDA() { + return detail::getCUDAHooks().hasCUDA(); + } + static bool hasMTIA() { + return detail::getMTIAHooks().hasMTIA(); + } + static bool hasCUDART() { + return detail::getCUDAHooks().hasCUDART(); + } + static long versionCUDART() { + return detail::getCUDAHooks().versionCUDART(); + } + static bool hasCuDNN() { + return detail::getCUDAHooks().hasCuDNN(); + } + static long versionCuDNN() { + return detail::getCUDAHooks().versionCuDNN(); + } + static bool hasCuSOLVER() { + return detail::getCUDAHooks().hasCuSOLVER(); + } + static bool hasHIP() { + return detail::getHIPHooks().hasHIP(); + } + static bool hasMPS() { + return detail::getMPSHooks().hasMPS(); + } + static bool hasIPU() { + return c10::impl::hasDeviceGuardImpl(c10::DeviceType::IPU); + } + static bool hasXLA() { + return c10::impl::hasDeviceGuardImpl(c10::DeviceType::XLA); + } + static bool hasXPU() { + return detail::getXPUHooks().hasXPU(); + } + static bool hasLazy() { + return c10::impl::hasDeviceGuardImpl(c10::DeviceType::Lazy); + } + static bool hasORT() { + return c10::impl::hasDeviceGuardImpl(c10::DeviceType::ORT); + } + // defined in header so that getNonVariableType has ability to inline + // call_once check. getNonVariableType is called fairly frequently + void lazyInitCUDA() { + c10::call_once(thc_init, [&] { detail::getCUDAHooks().initCUDA(); }); + } + void lazyInitHIP() { + c10::call_once(thh_init, [&] { detail::getHIPHooks().initHIP(); }); + } + void lazyInitXPU() { + c10::call_once(thx_init, [&] { detail::getXPUHooks().initXPU(); }); + } + void lazyInitPrivateUse1() { + c10::call_once(thp_init, [&] { + if (isPrivateUse1HooksRegistered()) { + at::GetPrivateUse1HooksInterface()->initPrivateUse1(); + } + }); + } + static const at::cuda::NVRTC& getNVRTC() { + return detail::getCUDAHooks().nvrtc(); + } + + static bool setFlushDenormal(bool on); + + // NB: This method is *purely* whether or not a user requested + // that CuDNN was enabled, it doesn't actually say anything about + // whether or not CuDNN is actually usable. Use cudnn_is_acceptable + // to test this instead + bool userEnabledCuDNN() const; + void setUserEnabledCuDNN(bool e); + bool userEnabledMkldnn() const; + void setUserEnabledMkldnn(bool e); + bool benchmarkCuDNN() const; + void setBenchmarkCuDNN(bool); + int benchmarkLimitCuDNN() const; + void setBenchmarkLimitCuDNN(int); + bool deterministicCuDNN() const; + void setDeterministicCuDNN(bool); + bool userEnabledNNPACK() const; + void setUserEnabledNNPACK(bool e); + + // Note [Disabling Fused SDP Kernels] + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // Flash and Memory Efficient SDP kernels are enabled by default. + // However, they can be disabled by setting + // at::globalContext().setUserEnabledFlashSDP(false) flag. + // This is useful for debugging purposes. For example, if you want to + // compare the performance of the flash SDP kernels with the unfused + // kernel, you can disable the flash SDP kernels. By disabling + // the math SDP kernel, you can force your code to use flash kernels. + // The math SDP kernel can be disabled by setting + // at::globalContext().setUserEnabledMathSDP(false) flag. + void setSDPUseFlash(bool); + bool userEnabledFlashSDP() const; + + void setSDPUseMemEfficient(bool); + bool userEnabledMemEfficientSDP() const; + + void setSDPUseMath(bool); + bool userEnabledMathSDP() const; + + void setSDPUseCuDNN(bool); + bool userEnabledCuDNNSDP() const; + + at::LinalgBackend linalgPreferredBackend() const; + void setLinalgPreferredBackend(at::LinalgBackend); + + // Note [Enabling Deterministic Operations] + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // Operations in PyTorch that normally act nondeterministically, but have an + // alternate deterministic implementation, should satisfy the following + // requirements: + // + // * Include this comment: "See Note [Enabling Deterministic Operations]" + // + // * Check the value of `at::globalContext().deterministicAlgorithms()` to + // toggle + // between nondeterministic and deterministic implementations. + // + // * Have an entry in the list of PyTorch operations that toggle between + // nondeterministic + // and deterministic implementations, in the docstring of + // `use_deterministic_algorithms()` in torch/__init__.py + // + // `example_func()` below shows an example of toggling between + // nondeterministic and deterministic implementations: + // + // void example_func() { + // // See Note [Enabling Deterministic Operations] + // if (at::globalContext().deterministicAlgorithms()) { + // example_func_deterministic(); + // } else { + // example_func_nondeterministic(); + // } + // } + + bool deterministicAlgorithms() const; + bool deterministicAlgorithmsWarnOnly() const; + void setDeterministicAlgorithms(bool, bool); + bool deterministicFillUninitializedMemory() const; + void setDeterministicFillUninitializedMemory(bool); + + // Note [Writing Nondeterministic Operations] + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + // Operations in PyTorch that act nondeterministically and do not have an + // alternate deterministic implementation should satisfy the following + // requirements: + // + // * Include this comment: "See Note [Writing Nondeterministic Operations]" + // + // * Include a comment explaining why the operation is nondeterministic. + // + // * Throw an error when `Context::deterministicAlgorithms()` is true. Most + // of the time, this should be accomplished by calling + // `at::globalContext().alertNotDeterminstic()`. However, if the + // nondeterministic behavior is caused by the CuBLAS workspace + // configuration in CUDA >= 10.2, + // `at::globalContext().alertCuBLASConfigNotDeterministic()` should be + // called instead (in this case, a comment explaining why the operation is + // nondeterministic is not necessary). See below for details on these + // methods. + // + // * Have an entry in the list of nondeterministic PyTorch operations in the + // docstring of `use_deterministic_algorithms()` in torch/__init__.py + // + // * Have a test function in `test/test_torch.py` whose name begins with + // `test_nondeterministic_alert_`. Alternatively, if CuBLAS workspace + // configuration is the reason for nondeterminism, the operation should be + // included in the `test_cublas_config_nondeterministic_alert` test. Any new + // tests should ideally follow a pattern similar to the existing ones. + // + // `example_func()` below shows an example of the comments and error-throwing + // code for a nondeterministic operation: + // + // void example_func() { + // // See Note [Writing Nondeterministic Operations] + // // Nondeterministic because + // at::globalContext().alertNondeterministic("example_func"); + // ... + // } + + // Throws an error if `Context::deterministicAlgorithms()` is true + static void alertNotDeterministic(c10::string_view const& caller); + + // Throws an error if `Context::deterministicAlgorithms()` is true, CUDA + // >= 10.2, and CUBLAS_WORKSPACE_CONFIG is not set to either ":16:8" or + // ":4096:8". For more details: + // https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility + void alertCuBLASConfigNotDeterministic() const; + + void setFloat32MatmulPrecision(const std::string& s); + bool allowTF32CuDNN() const; + void setAllowTF32CuDNN(bool); + bool allowTF32CuBLAS() const; + void setAllowTF32CuBLAS(bool); + Float32MatmulPrecision float32MatmulPrecision() const; + void setFloat32MatmulPrecision(Float32MatmulPrecision p); + bool allowFP16ReductionCuBLAS() const; + void setAllowFP16ReductionCuBLAS(bool); + bool allowBF16ReductionCuBLAS() const; + void setAllowBF16ReductionCuBLAS(bool); + at::QEngine qEngine() const; + void setQEngine(at::QEngine e); + static const std::vector& supportedQEngines(); + static bool isXNNPACKAvailable(); + void setCheckSparseTensorInvariants(bool e); + bool checkSparseTensorInvariants() const; + // This method is used to release the original weight after pre-packing. + // It should be called once before loading/running the model. + // NB: By default it is set to true for mobile builds. + void setReleaseWeightsWhenPrepacking(bool e); + bool releaseWeightsWhenPrepacking() const; + + void setDisplayVmapFallbackWarnings(bool enabled); + bool areVmapFallbackWarningsEnabled() const; + + void setDefaultMobileCPUAllocator(); + void unsetDefaultMobileCPUAllocator(); + bool allowFP16ReductionCPU() const; + void setAllowFP16ReductionCPU(bool); + + private: + void initCUDAIfNeeded(c10::DeviceType p) { + if (p == c10::DeviceType::CUDA) { + lazyInitCUDA(); + } + } + void initHIPIfNeeded(c10::DeviceType p) { + if (p == c10::DeviceType::HIP) { + lazyInitHIP(); + } + } + void initXPUIfNeeded(c10::DeviceType p) { + if (p == c10::DeviceType::XPU) { + lazyInitXPU(); + } + } + static bool checkCuBLASConfigDeterministic(); + c10::once_flag thc_init; + c10::once_flag thh_init; + c10::once_flag thx_init; + c10::once_flag thp_init; + bool enabled_cudnn = true; + bool deterministic_cudnn = false; + bool _deterministic_algorithms = false; + bool _deterministic_algorithms_warn_only = false; + bool _deterministic_fill_uninitialized_memory = true; + bool enabled_flashSDP = true; + bool enabled_mem_efficientSDP = true; + bool enabled_mathSDP = true; + bool enabled_cudnnSDP = false; +#ifdef USE_ROCM + bool benchmark_cudnn = true; +#else + bool benchmark_cudnn = false; +#endif + Float32MatmulPrecision float32_matmul_precision = + c10::utils::check_env("TORCH_ALLOW_TF32_CUBLAS_OVERRIDE") == true + ? at::Float32MatmulPrecision::HIGH + : at::Float32MatmulPrecision::HIGHEST; + int benchmark_limit_cudnn = 10; + bool allow_tf32_cudnn = true; + bool allow_fp16_reduction_cublas = true; + bool allow_bf16_reduction_cublas = true; + bool enabled_mkldnn = true; + bool enabled_nnpack = true; + at::LinalgBackend linalg_preferred_backend = + c10::utils::check_env("TORCH_LINALG_PREFER_CUSOLVER") == true + ? at::LinalgBackend::Cusolver + : at::LinalgBackend::Default; +#ifdef C10_MOBILE + bool release_original_weights = true; +#else + bool release_original_weights = false; +#endif + bool display_vmap_fallback_warnings_ = false; + c10::optional quantized_engine = c10::nullopt; + bool enable_sparse_tensor_invariant_checks = false; + bool allow_fp16_reduction_cpu = false; + + Allocator* prev_allocator_ptr_{nullptr}; +}; + +TORCH_API Context& globalContext(); + +static inline void init() { + globalContext(); +} + +TORCH_API Allocator* getCPUAllocator(); + +static inline DeprecatedTypeProperties& getDeprecatedTypeProperties( + Backend p, + ScalarType s) { + return globalDeprecatedTypePropertiesRegistry().getDeprecatedTypeProperties( + p, s); +} + +static inline DeprecatedTypeProperties& CPU(ScalarType s) { + return globalDeprecatedTypePropertiesRegistry().getDeprecatedTypeProperties( + Backend::CPU, s); +} + +static inline DeprecatedTypeProperties& CUDA(ScalarType s) { + return globalDeprecatedTypePropertiesRegistry().getDeprecatedTypeProperties( + Backend::CUDA, s); +} + +static inline DeprecatedTypeProperties& HIP(ScalarType s) { + return globalDeprecatedTypePropertiesRegistry().getDeprecatedTypeProperties( + Backend::HIP, s); +} + +static inline DeprecatedTypeProperties& MPS(ScalarType s) { + return globalDeprecatedTypePropertiesRegistry().getDeprecatedTypeProperties( + Backend::MPS, s); +} + +static inline bool hasCUDA() { + return globalContext().hasCUDA(); +} + +static inline bool hasMTIA() { + return globalContext().hasMTIA(); +} + +static inline bool hasHIP() { + return globalContext().hasHIP(); +} + +static inline bool hasIPU() { + return globalContext().hasIPU(); +} + +static inline bool hasXLA() { + return globalContext().hasXLA(); +} + +static inline bool hasMPS() { + return globalContext().hasMPS(); +} + +static inline bool hasORT() { + return globalContext().hasORT(); +} + +static inline bool hasXPU() { + return globalContext().hasXPU(); +} + +// Despite its name, this function returns the number of *CUDA* GPUs. +static inline size_t getNumGPUs() { + // WARNING: DO NOT ADD LOGIC TO HANDLE OTHER DEVICE TYPES TO THIS + // FUNCTION. If you are interested in interrogating the number of + // devices for a specific device type, add that function to the + // relevant library (e.g., similar to at::cuda::device_count()) + if (hasCUDA() && hasHIP()) { + throw std::runtime_error( + "Enabling both CUDA and HIP in ATen is not supported, as HIP masquerades " + "to be CUDA (e.g., when you say CUDA, on a HIP build of ATen, this actually " + "means HIP. Rebuild PyTorch with one or the other disabled."); + } else if (hasCUDA()) { + return detail::getCUDAHooks().getNumGPUs(); + } else if (hasHIP()) { + return detail::getHIPHooks().getNumGPUs(); + } else { + return 0; + } +} + +static inline bool hasOpenMP() { + return globalContext().hasOpenMP(); +} + +static inline bool hasMKL() { + return globalContext().hasMKL(); +} + +static inline bool hasLAPACK() { + return globalContext().hasLAPACK(); +} + +static inline bool hasMAGMA() { + return globalContext().hasMAGMA(); +} + +static inline bool hasMKLDNN() { + return globalContext().hasMKLDNN(); +} + +static inline void manual_seed(uint64_t seed) { + auto gen = globalContext().defaultGenerator(c10::DeviceType::CPU); + { + // See Note [Acquire lock when using random generators] + std::lock_guard lock(gen.mutex()); + gen.set_current_seed(seed); + } + // NB: Sometimes we build with CUDA, but we don't have any GPUs + // available. In that case, we must not seed CUDA; it will fail! + const auto cuda_num_gpus = detail::getCUDAHooks().getNumGPUs(); + if (hasCUDA() && cuda_num_gpus > 0) { + for (const auto i : c10::irange(cuda_num_gpus)) { + auto cuda_gen = globalContext().defaultGenerator( + Device(at::kCUDA, static_cast(i))); + { + // See Note [Acquire lock when using random generators] + std::lock_guard lock(cuda_gen.mutex()); + cuda_gen.set_current_seed(seed); + } + } + } + + const auto xpu_num_gpus = detail::getXPUHooks().getNumGPUs(); + if (hasXPU() && xpu_num_gpus) { + for (const auto i : c10::irange(xpu_num_gpus)) { + auto xpu_gen = globalContext().defaultGenerator( + Device(at::kXPU, static_cast(i))); + { + // See Note [Acquire lock when using random generators] + std::lock_guard lock(xpu_gen.mutex()); + xpu_gen.set_current_seed(seed); + } + } + } + + if (hasMPS()) { + auto mps_gen = globalContext().defaultGenerator(c10::DeviceType::MPS); + // See Note [Acquire lock when using random generators] + std::lock_guard lock(mps_gen.mutex()); + mps_gen.set_current_seed(seed); + } +} + +// When the global flag `allow_tf32` is set to true, cuBLAS handles are +// automatically configured to use math mode CUBLAS_TF32_TENSOR_OP_MATH. +// For some operators, such as addmv, TF32 offers no performance improvement +// but causes precision loss. To help this case, this class implements +// a RAII guard that can be used to quickly disable TF32 within its scope. +// +// Usage: +// NoTF32Guard disable_tf32; +struct TORCH_API NoTF32Guard { + NoTF32Guard(); + ~NoTF32Guard(); + static bool should_disable_tf32(); + + private: + bool changed = false; +}; + +struct TORCH_API ROCmBackwardPassGuard { + ROCmBackwardPassGuard(); + ~ROCmBackwardPassGuard(); + static bool is_backward_pass(); +}; + +} // namespace at diff --git a/shared/package-files/ab/ab52198b90afc94a7f3cdcdb438fd72eba00576e15128bc1133d93929c1427d7/blob b/shared/package-files/ab/ab52198b90afc94a7f3cdcdb438fd72eba00576e15128bc1133d93929c1427d7/blob new file mode 100644 index 0000000000000000000000000000000000000000..764a4440ee4973dd6506c3c5d467e5c5a260e428 --- /dev/null +++ b/shared/package-files/ab/ab52198b90afc94a7f3cdcdb438fd72eba00576e15128bc1133d93929c1427d7/blob @@ -0,0 +1,35 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. + +#pragma once + +#include + +#include "arrow/util/visibility.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// A less featureful implementation of strptime() for platforms lacking +// a standard implementation (e.g. Windows). +ARROW_EXPORT char* arrow_strptime(const char* __restrict, const char* __restrict, + struct tm* __restrict); + +#ifdef __cplusplus +} // extern "C" +#endif diff --git a/shared/package-files/ab/ab52403333cd797da62e4ffe8f9e67511f994cda73f3597610189343d8b76ed9/blob b/shared/package-files/ab/ab52403333cd797da62e4ffe8f9e67511f994cda73f3597610189343d8b76ed9/blob new file mode 100644 index 0000000000000000000000000000000000000000..ce13f819850165905c013490f5a14d45db0f0ccd --- /dev/null +++ b/shared/package-files/ab/ab52403333cd797da62e4ffe8f9e67511f994cda73f3597610189343d8b76ed9/blob @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor & as_strided_scatter_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & src, at::IntArrayRef size, at::IntArrayRef stride, c10::optional storage_offset=c10::nullopt); +TORCH_API at::Tensor & as_strided_scatter_outf(const at::Tensor & self, const at::Tensor & src, at::IntArrayRef size, at::IntArrayRef stride, c10::optional storage_offset, at::Tensor & out); +TORCH_API at::Tensor & as_strided_scatter_symint_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & src, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional storage_offset=c10::nullopt); +TORCH_API at::Tensor & as_strided_scatter_symint_outf(const at::Tensor & self, const at::Tensor & src, c10::SymIntArrayRef size, c10::SymIntArrayRef stride, c10::optional storage_offset, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/shared/package-files/ab/ab529cbf71f881a411eaca3f3fbedea299e85869b6ebdc71b8233f2cf2c2222d/blob b/shared/package-files/ab/ab529cbf71f881a411eaca3f3fbedea299e85869b6ebdc71b8233f2cf2c2222d/blob new file mode 100644 index 0000000000000000000000000000000000000000..e8260164202e648385618ff32bd9f3a1e5f21617 --- /dev/null +++ b/shared/package-files/ab/ab529cbf71f881a411eaca3f3fbedea299e85869b6ebdc71b8233f2cf2c2222d/blob @@ -0,0 +1,1797 @@ +"""Multi-layer Perceptron""" + +# Authors: The scikit-learn developers +# SPDX-License-Identifier: BSD-3-Clause + +import warnings +from abc import ABC, abstractmethod +from itertools import chain, pairwise +from numbers import Integral, Real + +import numpy as np +import scipy.optimize + +from ..base import ( + BaseEstimator, + ClassifierMixin, + RegressorMixin, + _fit_context, + is_classifier, +) +from ..exceptions import ConvergenceWarning +from ..metrics import accuracy_score, r2_score +from ..model_selection import train_test_split +from ..preprocessing import LabelBinarizer +from ..utils import ( + _safe_indexing, + check_random_state, + column_or_1d, + gen_batches, + shuffle, +) +from ..utils._param_validation import Interval, Options, StrOptions +from ..utils.extmath import safe_sparse_dot +from ..utils.fixes import _get_additional_lbfgs_options_dict +from ..utils.metaestimators import available_if +from ..utils.multiclass import ( + _check_partial_fit_first_call, + type_of_target, + unique_labels, +) +from ..utils.optimize import _check_optimize_result +from ..utils.validation import _check_sample_weight, check_is_fitted, validate_data +from ._base import ACTIVATIONS, DERIVATIVES, LOSS_FUNCTIONS +from ._stochastic_optimizers import AdamOptimizer, SGDOptimizer + +_STOCHASTIC_SOLVERS = ["sgd", "adam"] + + +def _pack(coefs_, intercepts_): + """Pack the parameters into a single vector.""" + return np.hstack([l.ravel() for l in coefs_ + intercepts_]) + + +class BaseMultilayerPerceptron(BaseEstimator, ABC): + """Base class for MLP classification and regression. + + Warning: This class should not be used directly. + Use derived classes instead. + + .. versionadded:: 0.18 + """ + + _parameter_constraints: dict = { + "hidden_layer_sizes": [ + "array-like", + Interval(Integral, 1, None, closed="left"), + ], + "activation": [StrOptions({"identity", "logistic", "tanh", "relu"})], + "solver": [StrOptions({"lbfgs", "sgd", "adam"})], + "alpha": [Interval(Real, 0, None, closed="left")], + "batch_size": [ + StrOptions({"auto"}), + Interval(Integral, 1, None, closed="left"), + ], + "learning_rate": [StrOptions({"constant", "invscaling", "adaptive"})], + "learning_rate_init": [Interval(Real, 0, None, closed="neither")], + "power_t": [Interval(Real, 0, None, closed="left")], + "max_iter": [Interval(Integral, 1, None, closed="left")], + "shuffle": ["boolean"], + "random_state": ["random_state"], + "tol": [Interval(Real, 0, None, closed="left")], + "verbose": ["verbose"], + "warm_start": ["boolean"], + "momentum": [Interval(Real, 0, 1, closed="both")], + "nesterovs_momentum": ["boolean"], + "early_stopping": ["boolean"], + "validation_fraction": [Interval(Real, 0, 1, closed="left")], + "beta_1": [Interval(Real, 0, 1, closed="left")], + "beta_2": [Interval(Real, 0, 1, closed="left")], + "epsilon": [Interval(Real, 0, None, closed="neither")], + "n_iter_no_change": [ + Interval(Integral, 1, None, closed="left"), + Options(Real, {np.inf}), + ], + "max_fun": [Interval(Integral, 1, None, closed="left")], + } + + @abstractmethod + def __init__( + self, + hidden_layer_sizes, + activation, + solver, + alpha, + batch_size, + learning_rate, + learning_rate_init, + power_t, + max_iter, + loss, + shuffle, + random_state, + tol, + verbose, + warm_start, + momentum, + nesterovs_momentum, + early_stopping, + validation_fraction, + beta_1, + beta_2, + epsilon, + n_iter_no_change, + max_fun, + ): + self.activation = activation + self.solver = solver + self.alpha = alpha + self.batch_size = batch_size + self.learning_rate = learning_rate + self.learning_rate_init = learning_rate_init + self.power_t = power_t + self.max_iter = max_iter + self.loss = loss + self.hidden_layer_sizes = hidden_layer_sizes + self.shuffle = shuffle + self.random_state = random_state + self.tol = tol + self.verbose = verbose + self.warm_start = warm_start + self.momentum = momentum + self.nesterovs_momentum = nesterovs_momentum + self.early_stopping = early_stopping + self.validation_fraction = validation_fraction + self.beta_1 = beta_1 + self.beta_2 = beta_2 + self.epsilon = epsilon + self.n_iter_no_change = n_iter_no_change + self.max_fun = max_fun + + def _unpack(self, packed_parameters): + """Extract the coefficients and intercepts from packed_parameters.""" + for i in range(self.n_layers_ - 1): + start, end, shape = self._coef_indptr[i] + self.coefs_[i] = np.reshape(packed_parameters[start:end], shape) + + start, end = self._intercept_indptr[i] + self.intercepts_[i] = packed_parameters[start:end] + + def _forward_pass(self, activations): + """Perform a forward pass on the network by computing the values + of the neurons in the hidden layers and the output layer. + + Parameters + ---------- + activations : list, length = n_layers - 1 + The ith element of the list holds the values of the ith layer. + """ + hidden_activation = ACTIVATIONS[self.activation] + # Iterate over the hidden layers + for i in range(self.n_layers_ - 1): + activations[i + 1] = safe_sparse_dot(activations[i], self.coefs_[i]) + activations[i + 1] += self.intercepts_[i] + + # For the hidden layers + if (i + 1) != (self.n_layers_ - 1): + hidden_activation(activations[i + 1]) + + # For the last layer + output_activation = ACTIVATIONS[self.out_activation_] + output_activation(activations[i + 1]) + + return activations + + def _forward_pass_fast(self, X, check_input=True): + """Predict using the trained model + + This is the same as _forward_pass but does not record the activations + of all layers and only returns the last layer's activation. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input data. + + check_input : bool, default=True + Perform input data validation or not. + + Returns + ------- + y_pred : ndarray of shape (n_samples,) or (n_samples, n_outputs) + The decision function of the samples for each class in the model. + """ + if check_input: + X = validate_data(self, X, accept_sparse=["csr", "csc"], reset=False) + + # Initialize first layer + activation = X + + # Forward propagate + hidden_activation = ACTIVATIONS[self.activation] + for i in range(self.n_layers_ - 1): + activation = safe_sparse_dot(activation, self.coefs_[i]) + activation += self.intercepts_[i] + if i != self.n_layers_ - 2: + hidden_activation(activation) + output_activation = ACTIVATIONS[self.out_activation_] + output_activation(activation) + + return activation + + def _compute_loss_grad( + self, layer, sw_sum, activations, deltas, coef_grads, intercept_grads + ): + """Compute the gradient of loss with respect to coefs and intercept for + specified layer. + + This function does backpropagation for the specified one layer. + """ + coef_grads[layer] = safe_sparse_dot(activations[layer].T, deltas[layer]) + coef_grads[layer] += self.alpha * self.coefs_[layer] + coef_grads[layer] /= sw_sum + + intercept_grads[layer] = np.sum(deltas[layer], axis=0) / sw_sum + + def _loss_grad_lbfgs( + self, + packed_coef_inter, + X, + y, + sample_weight, + activations, + deltas, + coef_grads, + intercept_grads, + ): + """Compute the MLP loss function and its corresponding derivatives + with respect to the different parameters given in the initialization. + + Returned gradients are packed in a single vector so it can be used + in lbfgs + + Parameters + ---------- + packed_coef_inter : ndarray + A vector comprising the flattened coefficients and intercepts. + + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input data. + + y : ndarray of shape (n_samples,) + The target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + activations : list, length = n_layers - 1 + The ith element of the list holds the values of the ith layer. + + deltas : list, length = n_layers - 1 + The ith element of the list holds the difference between the + activations of the i + 1 layer and the backpropagated error. + More specifically, deltas are gradients of loss with respect to z + in each layer, where z = wx + b is the value of a particular layer + before passing through the activation function + + coef_grads : list, length = n_layers - 1 + The ith element contains the amount of change used to update the + coefficient parameters of the ith layer in an iteration. + + intercept_grads : list, length = n_layers - 1 + The ith element contains the amount of change used to update the + intercept parameters of the ith layer in an iteration. + + Returns + ------- + loss : float + grad : array-like, shape (number of nodes of all layers,) + """ + self._unpack(packed_coef_inter) + loss, coef_grads, intercept_grads = self._backprop( + X, y, sample_weight, activations, deltas, coef_grads, intercept_grads + ) + grad = _pack(coef_grads, intercept_grads) + return loss, grad + + def _backprop( + self, X, y, sample_weight, activations, deltas, coef_grads, intercept_grads + ): + """Compute the MLP loss function and its corresponding derivatives + with respect to each parameter: weights and bias vectors. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input data. + + y : ndarray of shape (n_samples,) + The target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + activations : list, length = n_layers - 1 + The ith element of the list holds the values of the ith layer. + + deltas : list, length = n_layers - 1 + The ith element of the list holds the difference between the + activations of the i + 1 layer and the backpropagated error. + More specifically, deltas are gradients of loss with respect to z + in each layer, where z = wx + b is the value of a particular layer + before passing through the activation function + + coef_grads : list, length = n_layers - 1 + The ith element contains the amount of change used to update the + coefficient parameters of the ith layer in an iteration. + + intercept_grads : list, length = n_layers - 1 + The ith element contains the amount of change used to update the + intercept parameters of the ith layer in an iteration. + + Returns + ------- + loss : float + coef_grads : list, length = n_layers - 1 + intercept_grads : list, length = n_layers - 1 + """ + n_samples = X.shape[0] + + # Forward propagate + activations = self._forward_pass(activations) + + # Get loss + loss_func_name = self.loss + if loss_func_name == "log_loss" and self.out_activation_ == "logistic": + loss_func_name = "binary_log_loss" + loss = LOSS_FUNCTIONS[loss_func_name](y, activations[-1], sample_weight) + # Add L2 regularization term to loss + values = 0 + for s in self.coefs_: + s = s.ravel() + values += np.dot(s, s) + if sample_weight is None: + sw_sum = n_samples + else: + sw_sum = sample_weight.sum() + loss += (0.5 * self.alpha) * values / sw_sum + + # Backward propagate + last = self.n_layers_ - 2 + + # The calculation of delta[last] is as follows: + # delta[last] = d/dz loss(y, act(z)) = act(z) - y + # with z=x@w + b being the output of the last layer before passing through the + # output activation, act(z) = activations[-1]. + # The simple formula for delta[last] here works with following (canonical + # loss-link) combinations of output activation and loss function: + # sigmoid and binary cross entropy, softmax and categorical cross + # entropy, and identity with squared loss + deltas[last] = activations[-1] - y + if sample_weight is not None: + deltas[last] *= sample_weight.reshape(-1, 1) + + # Compute gradient for the last layer + self._compute_loss_grad( + last, sw_sum, activations, deltas, coef_grads, intercept_grads + ) + + inplace_derivative = DERIVATIVES[self.activation] + # Iterate over the hidden layers + for i in range(last, 0, -1): + deltas[i - 1] = safe_sparse_dot(deltas[i], self.coefs_[i].T) + inplace_derivative(activations[i], deltas[i - 1]) + + self._compute_loss_grad( + i - 1, sw_sum, activations, deltas, coef_grads, intercept_grads + ) + + return loss, coef_grads, intercept_grads + + def _initialize(self, y, layer_units, dtype): + # set all attributes, allocate weights etc. for first call + # Initialize parameters + self.n_iter_ = 0 + self.t_ = 0 + self.n_outputs_ = y.shape[1] + + # Compute the number of layers + self.n_layers_ = len(layer_units) + + # Output for regression + if not is_classifier(self): + if self.loss == "poisson": + self.out_activation_ = "exp" + else: + # loss = "squared_error" + self.out_activation_ = "identity" + # Output for multi class + elif self._label_binarizer.y_type_ == "multiclass": + self.out_activation_ = "softmax" + # Output for binary class and multi-label + else: + self.out_activation_ = "logistic" + + # Initialize coefficient and intercept layers + self.coefs_ = [] + self.intercepts_ = [] + + for i in range(self.n_layers_ - 1): + coef_init, intercept_init = self._init_coef( + layer_units[i], layer_units[i + 1], dtype + ) + self.coefs_.append(coef_init) + self.intercepts_.append(intercept_init) + + self._best_coefs = [c.copy() for c in self.coefs_] + self._best_intercepts = [i.copy() for i in self.intercepts_] + + if self.solver in _STOCHASTIC_SOLVERS: + self.loss_curve_ = [] + self._no_improvement_count = 0 + if self.early_stopping: + self.validation_scores_ = [] + self.best_validation_score_ = -np.inf + self.best_loss_ = None + else: + self.best_loss_ = np.inf + self.validation_scores_ = None + self.best_validation_score_ = None + + def _init_coef(self, fan_in, fan_out, dtype): + # Use the initialization method recommended by + # Glorot et al. + factor = 6.0 + if self.activation == "logistic": + factor = 2.0 + init_bound = np.sqrt(factor / (fan_in + fan_out)) + + # Generate weights and bias: + coef_init = self._random_state.uniform( + -init_bound, init_bound, (fan_in, fan_out) + ) + intercept_init = self._random_state.uniform(-init_bound, init_bound, fan_out) + coef_init = coef_init.astype(dtype, copy=False) + intercept_init = intercept_init.astype(dtype, copy=False) + return coef_init, intercept_init + + def _fit(self, X, y, sample_weight=None, incremental=False): + # Make sure self.hidden_layer_sizes is a list + hidden_layer_sizes = self.hidden_layer_sizes + if not hasattr(hidden_layer_sizes, "__iter__"): + hidden_layer_sizes = [hidden_layer_sizes] + hidden_layer_sizes = list(hidden_layer_sizes) + + if np.any(np.array(hidden_layer_sizes) <= 0): + raise ValueError( + "hidden_layer_sizes must be > 0, got %s." % hidden_layer_sizes + ) + first_pass = not hasattr(self, "coefs_") or ( + not self.warm_start and not incremental + ) + + X, y = self._validate_input(X, y, incremental, reset=first_pass) + n_samples, n_features = X.shape + if sample_weight is not None: + sample_weight = _check_sample_weight(sample_weight, X) + + # Ensure y is 2D + if y.ndim == 1: + y = y.reshape((-1, 1)) + + self.n_outputs_ = y.shape[1] + + layer_units = [n_features] + hidden_layer_sizes + [self.n_outputs_] + + # check random state + self._random_state = check_random_state(self.random_state) + + if first_pass: + # First time training the model + self._initialize(y, layer_units, X.dtype) + + # Initialize lists + activations = [X] + [None] * (len(layer_units) - 1) + deltas = [None] * (len(activations) - 1) + + coef_grads = [ + np.empty((n_fan_in_, n_fan_out_), dtype=X.dtype) + for n_fan_in_, n_fan_out_ in pairwise(layer_units) + ] + + intercept_grads = [ + np.empty(n_fan_out_, dtype=X.dtype) for n_fan_out_ in layer_units[1:] + ] + + # Run the Stochastic optimization solver + if self.solver in _STOCHASTIC_SOLVERS: + self._fit_stochastic( + X, + y, + sample_weight, + activations, + deltas, + coef_grads, + intercept_grads, + layer_units, + incremental, + ) + + # Run the LBFGS solver + elif self.solver == "lbfgs": + self._fit_lbfgs( + X, + y, + sample_weight, + activations, + deltas, + coef_grads, + intercept_grads, + layer_units, + ) + + # validate parameter weights + weights = chain(self.coefs_, self.intercepts_) + if not all(np.isfinite(w).all() for w in weights): + raise ValueError( + "Solver produced non-finite parameter weights. The input data may" + " contain large values and need to be preprocessed." + ) + + return self + + def _fit_lbfgs( + self, + X, + y, + sample_weight, + activations, + deltas, + coef_grads, + intercept_grads, + layer_units, + ): + # Store meta information for the parameters + self._coef_indptr = [] + self._intercept_indptr = [] + start = 0 + + # Save sizes and indices of coefficients for faster unpacking + for i in range(self.n_layers_ - 1): + n_fan_in, n_fan_out = layer_units[i], layer_units[i + 1] + + end = start + (n_fan_in * n_fan_out) + self._coef_indptr.append((start, end, (n_fan_in, n_fan_out))) + start = end + + # Save sizes and indices of intercepts for faster unpacking + for i in range(self.n_layers_ - 1): + end = start + layer_units[i + 1] + self._intercept_indptr.append((start, end)) + start = end + + # Run LBFGS + packed_coef_inter = _pack(self.coefs_, self.intercepts_) + + if self.verbose is True or self.verbose >= 1: + iprint = 1 + else: + iprint = -1 + + opt_res = scipy.optimize.minimize( + self._loss_grad_lbfgs, + packed_coef_inter, + method="L-BFGS-B", + jac=True, + options={ + "maxfun": self.max_fun, + "maxiter": self.max_iter, + "gtol": self.tol, + **_get_additional_lbfgs_options_dict("iprint", iprint), + }, + args=( + X, + y, + sample_weight, + activations, + deltas, + coef_grads, + intercept_grads, + ), + ) + self.n_iter_ = _check_optimize_result("lbfgs", opt_res, self.max_iter) + self.loss_ = opt_res.fun + self._unpack(opt_res.x) + + def _fit_stochastic( + self, + X, + y, + sample_weight, + activations, + deltas, + coef_grads, + intercept_grads, + layer_units, + incremental, + ): + params = self.coefs_ + self.intercepts_ + if not incremental or not hasattr(self, "_optimizer"): + if self.solver == "sgd": + self._optimizer = SGDOptimizer( + params, + self.learning_rate_init, + self.learning_rate, + self.momentum, + self.nesterovs_momentum, + self.power_t, + ) + elif self.solver == "adam": + self._optimizer = AdamOptimizer( + params, + self.learning_rate_init, + self.beta_1, + self.beta_2, + self.epsilon, + ) + + # early_stopping in partial_fit doesn't make sense + if self.early_stopping and incremental: + raise ValueError("partial_fit does not support early_stopping=True") + early_stopping = self.early_stopping + if early_stopping: + # don't stratify in multilabel classification + should_stratify = is_classifier(self) and self.n_outputs_ == 1 + stratify = y if should_stratify else None + if sample_weight is None: + X_train, X_val, y_train, y_val = train_test_split( + X, + y, + random_state=self._random_state, + test_size=self.validation_fraction, + stratify=stratify, + ) + sample_weight_train = sample_weight_val = None + else: + # TODO: incorporate sample_weight in sampling here. + ( + X_train, + X_val, + y_train, + y_val, + sample_weight_train, + sample_weight_val, + ) = train_test_split( + X, + y, + sample_weight, + random_state=self._random_state, + test_size=self.validation_fraction, + stratify=stratify, + ) + if X_val.shape[0] < 2: + raise ValueError( + "The validation set is too small. Increase 'validation_fraction' " + "or the size of your dataset." + ) + + if is_classifier(self): + y_val = self._label_binarizer.inverse_transform(y_val) + else: + X_train, y_train, sample_weight_train = X, y, sample_weight + X_val = y_val = sample_weight_val = None + + n_samples = X_train.shape[0] + sample_idx = np.arange(n_samples, dtype=int) + + if self.batch_size == "auto": + batch_size = min(200, n_samples) + else: + if self.batch_size > n_samples: + warnings.warn( + "Got `batch_size` less than 1 or larger than " + "sample size. It is going to be clipped" + ) + batch_size = np.clip(self.batch_size, 1, n_samples) + + try: + self.n_iter_ = 0 + for it in range(self.max_iter): + if self.shuffle: + # Only shuffle the sample indices instead of X and y to + # reduce the memory footprint. These indices will be used + # to slice the X and y. + sample_idx = shuffle(sample_idx, random_state=self._random_state) + + accumulated_loss = 0.0 + for batch_slice in gen_batches(n_samples, batch_size): + if self.shuffle: + batch_idx = sample_idx[batch_slice] + X_batch = _safe_indexing(X_train, batch_idx) + else: + batch_idx = batch_slice + X_batch = X_train[batch_idx] + y_batch = y_train[batch_idx] + if sample_weight is None: + sample_weight_batch = None + else: + sample_weight_batch = sample_weight_train[batch_idx] + + activations[0] = X_batch + batch_loss, coef_grads, intercept_grads = self._backprop( + X_batch, + y_batch, + sample_weight_batch, + activations, + deltas, + coef_grads, + intercept_grads, + ) + accumulated_loss += batch_loss * ( + batch_slice.stop - batch_slice.start + ) + + # update weights + grads = coef_grads + intercept_grads + self._optimizer.update_params(params, grads) + + self.n_iter_ += 1 + self.loss_ = accumulated_loss / X_train.shape[0] + + self.t_ += n_samples + self.loss_curve_.append(self.loss_) + if self.verbose: + print("Iteration %d, loss = %.8f" % (self.n_iter_, self.loss_)) + + # update no_improvement_count based on training loss or + # validation score according to early_stopping + self._update_no_improvement_count( + early_stopping, X_val, y_val, sample_weight_val + ) + + # for learning rate that needs to be updated at iteration end + self._optimizer.iteration_ends(self.t_) + + if self._no_improvement_count > self.n_iter_no_change: + # not better than last `n_iter_no_change` iterations by tol + # stop or decrease learning rate + if early_stopping: + msg = ( + "Validation score did not improve more than " + "tol=%f for %d consecutive epochs." + % (self.tol, self.n_iter_no_change) + ) + else: + msg = ( + "Training loss did not improve more than tol=%f" + " for %d consecutive epochs." + % (self.tol, self.n_iter_no_change) + ) + + is_stopping = self._optimizer.trigger_stopping(msg, self.verbose) + if is_stopping: + break + else: + self._no_improvement_count = 0 + + if incremental: + break + + if self.n_iter_ == self.max_iter: + warnings.warn( + "Stochastic Optimizer: Maximum iterations (%d) " + "reached and the optimization hasn't converged yet." + % self.max_iter, + ConvergenceWarning, + ) + except KeyboardInterrupt: + warnings.warn("Training interrupted by user.") + + if early_stopping: + # restore best weights + self.coefs_ = self._best_coefs + self.intercepts_ = self._best_intercepts + + def _update_no_improvement_count(self, early_stopping, X, y, sample_weight): + if early_stopping: + # compute validation score (can be NaN), use that for stopping + val_score = self._score(X, y, sample_weight=sample_weight) + + self.validation_scores_.append(val_score) + + if self.verbose: + print("Validation score: %f" % self.validation_scores_[-1]) + # update best parameters + # use validation_scores_, not loss_curve_ + # let's hope no-one overloads .score with mse + last_valid_score = self.validation_scores_[-1] + + if last_valid_score < (self.best_validation_score_ + self.tol): + self._no_improvement_count += 1 + else: + self._no_improvement_count = 0 + + if last_valid_score > self.best_validation_score_: + self.best_validation_score_ = last_valid_score + self._best_coefs = [c.copy() for c in self.coefs_] + self._best_intercepts = [i.copy() for i in self.intercepts_] + else: + if self.loss_curve_[-1] > self.best_loss_ - self.tol: + self._no_improvement_count += 1 + else: + self._no_improvement_count = 0 + if self.loss_curve_[-1] < self.best_loss_: + self.best_loss_ = self.loss_curve_[-1] + + @_fit_context(prefer_skip_nested_validation=True) + def fit(self, X, y, sample_weight=None): + """Fit the model to data matrix X and target(s) y. + + Parameters + ---------- + X : ndarray or sparse matrix of shape (n_samples, n_features) + The input data. + + y : ndarray of shape (n_samples,) or (n_samples, n_outputs) + The target values (class labels in classification, real numbers in + regression). + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + .. versionadded:: 1.7 + + Returns + ------- + self : object + Returns a trained MLP model. + """ + return self._fit(X, y, sample_weight=sample_weight, incremental=False) + + def _check_solver(self): + if self.solver not in _STOCHASTIC_SOLVERS: + raise AttributeError( + "partial_fit is only available for stochastic" + " optimizers. %s is not stochastic." % self.solver + ) + return True + + def _score_with_function(self, X, y, sample_weight, score_function): + """Private score method without input validation.""" + # Input validation would remove feature names, so we disable it + y_pred = self._predict(X, check_input=False) + + if np.isnan(y_pred).any() or np.isinf(y_pred).any(): + return np.nan + + return score_function(y, y_pred, sample_weight=sample_weight) + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.input_tags.sparse = True + return tags + + +class MLPClassifier(ClassifierMixin, BaseMultilayerPerceptron): + """Multi-layer Perceptron classifier. + + This model optimizes the log-loss function using LBFGS or stochastic + gradient descent. + + .. versionadded:: 0.18 + + Parameters + ---------- + hidden_layer_sizes : array-like of shape(n_layers - 2,), default=(100,) + The ith element represents the number of neurons in the ith + hidden layer. + + activation : {'identity', 'logistic', 'tanh', 'relu'}, default='relu' + Activation function for the hidden layer. + + - 'identity', no-op activation, useful to implement linear bottleneck, + returns f(x) = x + + - 'logistic', the logistic sigmoid function, + returns f(x) = 1 / (1 + exp(-x)). + + - 'tanh', the hyperbolic tan function, + returns f(x) = tanh(x). + + - 'relu', the rectified linear unit function, + returns f(x) = max(0, x) + + solver : {'lbfgs', 'sgd', 'adam'}, default='adam' + The solver for weight optimization. + + - 'lbfgs' is an optimizer in the family of quasi-Newton methods. + + - 'sgd' refers to stochastic gradient descent. + + - 'adam' refers to a stochastic gradient-based optimizer proposed + by Kingma, Diederik, and Jimmy Ba + + For a comparison between Adam optimizer and SGD, see + :ref:`sphx_glr_auto_examples_neural_networks_plot_mlp_training_curves.py`. + + Note: The default solver 'adam' works pretty well on relatively + large datasets (with thousands of training samples or more) in terms of + both training time and validation score. + For small datasets, however, 'lbfgs' can converge faster and perform + better. + + alpha : float, default=0.0001 + Strength of the L2 regularization term. The L2 regularization term + is divided by the sample size when added to the loss. + + For an example usage and visualization of varying regularization, see + :ref:`sphx_glr_auto_examples_neural_networks_plot_mlp_alpha.py`. + + batch_size : int, default='auto' + Size of minibatches for stochastic optimizers. + If the solver is 'lbfgs', the classifier will not use minibatch. + When set to "auto", `batch_size=min(200, n_samples)`. + + learning_rate : {'constant', 'invscaling', 'adaptive'}, default='constant' + Learning rate schedule for weight updates. + + - 'constant' is a constant learning rate given by + 'learning_rate_init'. + + - 'invscaling' gradually decreases the learning rate at each + time step 't' using an inverse scaling exponent of 'power_t'. + effective_learning_rate = learning_rate_init / pow(t, power_t) + + - 'adaptive' keeps the learning rate constant to + 'learning_rate_init' as long as training loss keeps decreasing. + Each time two consecutive epochs fail to decrease training loss by at + least tol, or fail to increase validation score by at least tol if + 'early_stopping' is on, the current learning rate is divided by 5. + + Only used when ``solver='sgd'``. + + learning_rate_init : float, default=0.001 + The initial learning rate used. It controls the step-size + in updating the weights. Only used when solver='sgd' or 'adam'. + + power_t : float, default=0.5 + The exponent for inverse scaling learning rate. + It is used in updating effective learning rate when the learning_rate + is set to 'invscaling'. Only used when solver='sgd'. + + max_iter : int, default=200 + Maximum number of iterations. The solver iterates until convergence + (determined by 'tol') or this number of iterations. For stochastic + solvers ('sgd', 'adam'), note that this determines the number of epochs + (how many times each data point will be used), not the number of + gradient steps. + + shuffle : bool, default=True + Whether to shuffle samples in each iteration. Only used when + solver='sgd' or 'adam'. + + random_state : int, RandomState instance, default=None + Determines random number generation for weights and bias + initialization, train-test split if early stopping is used, and batch + sampling when solver='sgd' or 'adam'. + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary `. + + tol : float, default=1e-4 + Tolerance for the optimization. When the loss or score is not improving + by at least ``tol`` for ``n_iter_no_change`` consecutive iterations, + unless ``learning_rate`` is set to 'adaptive', convergence is + considered to be reached and training stops. + + verbose : bool, default=False + Whether to print progress messages to stdout. + + warm_start : bool, default=False + When set to True, reuse the solution of the previous + call to fit as initialization, otherwise, just erase the + previous solution. See :term:`the Glossary `. + + momentum : float, default=0.9 + Momentum for gradient descent update. Should be between 0 and 1. Only + used when solver='sgd'. + + nesterovs_momentum : bool, default=True + Whether to use Nesterov's momentum. Only used when solver='sgd' and + momentum > 0. + + early_stopping : bool, default=False + Whether to use early stopping to terminate training when validation + score is not improving. If set to true, it will automatically set + aside 10% of training data as validation and terminate training when + validation score is not improving by at least ``tol`` for + ``n_iter_no_change`` consecutive epochs. The split is stratified, + except in a multilabel setting. + If early stopping is False, then the training stops when the training + loss does not improve by more than tol for n_iter_no_change consecutive + passes over the training set. + Only effective when solver='sgd' or 'adam'. + + validation_fraction : float, default=0.1 + The proportion of training data to set aside as validation set for + early stopping. Must be between 0 and 1. + Only used if early_stopping is True. + + beta_1 : float, default=0.9 + Exponential decay rate for estimates of first moment vector in adam, + should be in [0, 1). Only used when solver='adam'. + + beta_2 : float, default=0.999 + Exponential decay rate for estimates of second moment vector in adam, + should be in [0, 1). Only used when solver='adam'. + + epsilon : float, default=1e-8 + Value for numerical stability in adam. Only used when solver='adam'. + + n_iter_no_change : int, default=10 + Maximum number of epochs to not meet ``tol`` improvement. + Only effective when solver='sgd' or 'adam'. + + .. versionadded:: 0.20 + + max_fun : int, default=15000 + Only used when solver='lbfgs'. Maximum number of loss function calls. + The solver iterates until convergence (determined by 'tol'), number + of iterations reaches max_iter, or this number of loss function calls. + Note that number of loss function calls will be greater than or equal + to the number of iterations for the `MLPClassifier`. + + .. versionadded:: 0.22 + + Attributes + ---------- + classes_ : ndarray or list of ndarray of shape (n_classes,) + Class labels for each output. + + loss_ : float + The current loss computed with the loss function. + + best_loss_ : float or None + The minimum loss reached by the solver throughout fitting. + If `early_stopping=True`, this attribute is set to `None`. Refer to + the `best_validation_score_` fitted attribute instead. + + loss_curve_ : list of shape (`n_iter_`,) + The ith element in the list represents the loss at the ith iteration. + + validation_scores_ : list of shape (`n_iter_`,) or None + The score at each iteration on a held-out validation set. The score + reported is the accuracy score. Only available if `early_stopping=True`, + otherwise the attribute is set to `None`. + + best_validation_score_ : float or None + The best validation score (i.e. accuracy score) that triggered the + early stopping. Only available if `early_stopping=True`, otherwise the + attribute is set to `None`. + + t_ : int + The number of training samples seen by the solver during fitting. + + coefs_ : list of shape (n_layers - 1,) + The ith element in the list represents the weight matrix corresponding + to layer i. + + intercepts_ : list of shape (n_layers - 1,) + The ith element in the list represents the bias vector corresponding to + layer i + 1. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_iter_ : int + The number of iterations the solver has run. + + n_layers_ : int + Number of layers. + + n_outputs_ : int + Number of outputs. + + out_activation_ : str + Name of the output activation function. + + See Also + -------- + MLPRegressor : Multi-layer Perceptron regressor. + BernoulliRBM : Bernoulli Restricted Boltzmann Machine (RBM). + + Notes + ----- + MLPClassifier trains iteratively since at each time step + the partial derivatives of the loss function with respect to the model + parameters are computed to update the parameters. + + It can also have a regularization term added to the loss function + that shrinks model parameters to prevent overfitting. + + This implementation works with data represented as dense numpy arrays or + sparse scipy arrays of floating point values. + + References + ---------- + Hinton, Geoffrey E. "Connectionist learning procedures." + Artificial intelligence 40.1 (1989): 185-234. + + Glorot, Xavier, and Yoshua Bengio. + "Understanding the difficulty of training deep feedforward neural networks." + International Conference on Artificial Intelligence and Statistics. 2010. + + :arxiv:`He, Kaiming, et al (2015). "Delving deep into rectifiers: + Surpassing human-level performance on imagenet classification." <1502.01852>` + + :arxiv:`Kingma, Diederik, and Jimmy Ba (2014) + "Adam: A method for stochastic optimization." <1412.6980>` + + Examples + -------- + >>> from sklearn.neural_network import MLPClassifier + >>> from sklearn.datasets import make_classification + >>> from sklearn.model_selection import train_test_split + >>> X, y = make_classification(n_samples=100, random_state=1) + >>> X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, + ... random_state=1) + >>> clf = MLPClassifier(random_state=1, max_iter=300).fit(X_train, y_train) + >>> clf.predict_proba(X_test[:1]) + array([[0.0383, 0.961]]) + >>> clf.predict(X_test[:5, :]) + array([1, 0, 1, 0, 1]) + >>> clf.score(X_test, y_test) + 0.8... + """ + + def __init__( + self, + hidden_layer_sizes=(100,), + activation="relu", + *, + solver="adam", + alpha=0.0001, + batch_size="auto", + learning_rate="constant", + learning_rate_init=0.001, + power_t=0.5, + max_iter=200, + shuffle=True, + random_state=None, + tol=1e-4, + verbose=False, + warm_start=False, + momentum=0.9, + nesterovs_momentum=True, + early_stopping=False, + validation_fraction=0.1, + beta_1=0.9, + beta_2=0.999, + epsilon=1e-8, + n_iter_no_change=10, + max_fun=15000, + ): + super().__init__( + hidden_layer_sizes=hidden_layer_sizes, + activation=activation, + solver=solver, + alpha=alpha, + batch_size=batch_size, + learning_rate=learning_rate, + learning_rate_init=learning_rate_init, + power_t=power_t, + max_iter=max_iter, + loss="log_loss", + shuffle=shuffle, + random_state=random_state, + tol=tol, + verbose=verbose, + warm_start=warm_start, + momentum=momentum, + nesterovs_momentum=nesterovs_momentum, + early_stopping=early_stopping, + validation_fraction=validation_fraction, + beta_1=beta_1, + beta_2=beta_2, + epsilon=epsilon, + n_iter_no_change=n_iter_no_change, + max_fun=max_fun, + ) + + def _validate_input(self, X, y, incremental, reset): + X, y = validate_data( + self, + X, + y, + accept_sparse=["csr", "csc"], + multi_output=True, + dtype=(np.float64, np.float32), + reset=reset, + ) + if y.ndim == 2 and y.shape[1] == 1: + y = column_or_1d(y, warn=True) + + # Matrix of actions to be taken under the possible combinations: + # The case that incremental == True and classes_ not defined is + # already checked by _check_partial_fit_first_call that is called + # in _partial_fit below. + # The cases are already grouped into the respective if blocks below. + # + # incremental warm_start classes_ def action + # 0 0 0 define classes_ + # 0 1 0 define classes_ + # 0 0 1 redefine classes_ + # + # 0 1 1 check compat warm_start + # 1 1 1 check compat warm_start + # + # 1 0 1 check compat last fit + # + # Note the reliance on short-circuiting here, so that the second + # or part implies that classes_ is defined. + if (not hasattr(self, "classes_")) or (not self.warm_start and not incremental): + self._label_binarizer = LabelBinarizer() + self._label_binarizer.fit(y) + self.classes_ = self._label_binarizer.classes_ + else: + classes = unique_labels(y) + if self.warm_start: + if set(classes) != set(self.classes_): + raise ValueError( + "warm_start can only be used where `y` has the same " + "classes as in the previous call to fit. Previously " + f"got {self.classes_}, `y` has {classes}" + ) + elif len(np.setdiff1d(classes, self.classes_, assume_unique=True)): + raise ValueError( + "`y` has classes not in `self.classes_`. " + f"`self.classes_` has {self.classes_}. 'y' has {classes}." + ) + + # This downcast to bool is to prevent upcasting when working with + # float32 data + y = self._label_binarizer.transform(y).astype(bool) + return X, y + + def predict(self, X): + """Predict using the multi-layer perceptron classifier. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input data. + + Returns + ------- + y : ndarray, shape (n_samples,) or (n_samples, n_classes) + The predicted classes. + """ + check_is_fitted(self) + return self._predict(X) + + def _predict(self, X, check_input=True): + """Private predict method with optional input validation""" + y_pred = self._forward_pass_fast(X, check_input=check_input) + + if self.n_outputs_ == 1: + y_pred = y_pred.ravel() + + return self._label_binarizer.inverse_transform(y_pred) + + def _score(self, X, y, sample_weight=None): + return super()._score_with_function( + X, y, sample_weight=sample_weight, score_function=accuracy_score + ) + + @available_if(lambda est: est._check_solver()) + @_fit_context(prefer_skip_nested_validation=True) + def partial_fit(self, X, y, sample_weight=None, classes=None): + """Update the model with a single iteration over the given data. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input data. + + y : array-like of shape (n_samples,) + The target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + .. versionadded:: 1.7 + + classes : array of shape (n_classes,), default=None + Classes across all calls to partial_fit. + Can be obtained via `np.unique(y_all)`, where y_all is the + target vector of the entire dataset. + This argument is required for the first call to partial_fit + and can be omitted in the subsequent calls. + Note that y doesn't need to contain all labels in `classes`. + + Returns + ------- + self : object + Trained MLP model. + """ + if _check_partial_fit_first_call(self, classes): + self._label_binarizer = LabelBinarizer() + if type_of_target(y).startswith("multilabel"): + self._label_binarizer.fit(y) + else: + self._label_binarizer.fit(classes) + + return self._fit(X, y, sample_weight=sample_weight, incremental=True) + + def predict_log_proba(self, X): + """Return the log of probability estimates. + + Parameters + ---------- + X : ndarray of shape (n_samples, n_features) + The input data. + + Returns + ------- + log_y_prob : ndarray of shape (n_samples, n_classes) + The predicted log-probability of the sample for each class + in the model, where classes are ordered as they are in + `self.classes_`. Equivalent to `log(predict_proba(X))`. + """ + y_prob = self.predict_proba(X) + return np.log(y_prob, out=y_prob) + + def predict_proba(self, X): + """Probability estimates. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input data. + + Returns + ------- + y_prob : ndarray of shape (n_samples, n_classes) + The predicted probability of the sample for each class in the + model, where classes are ordered as they are in `self.classes_`. + """ + check_is_fitted(self) + y_pred = self._forward_pass_fast(X) + + if self.n_outputs_ == 1: + y_pred = y_pred.ravel() + + if y_pred.ndim == 1: + return np.vstack([1 - y_pred, y_pred]).T + else: + return y_pred + + def __sklearn_tags__(self): + tags = super().__sklearn_tags__() + tags.classifier_tags.multi_label = True + return tags + + +class MLPRegressor(RegressorMixin, BaseMultilayerPerceptron): + """Multi-layer Perceptron regressor. + + This model optimizes the squared error using LBFGS or stochastic gradient + descent. + + .. versionadded:: 0.18 + + Parameters + ---------- + loss : {'squared_error', 'poisson'}, default='squared_error' + The loss function to use when training the weights. Note that the + "squared error" and "poisson" losses actually implement + "half squares error" and "half poisson deviance" to simplify the + computation of the gradient. Furthermore, the "poisson" loss internally uses + a log-link (exponential as the output activation function) and requires + ``y >= 0``. + + .. versionchanged:: 1.7 + Added parameter `loss` and option 'poisson'. + + hidden_layer_sizes : array-like of shape(n_layers - 2,), default=(100,) + The ith element represents the number of neurons in the ith + hidden layer. + + activation : {'identity', 'logistic', 'tanh', 'relu'}, default='relu' + Activation function for the hidden layer. + + - 'identity', no-op activation, useful to implement linear bottleneck, + returns f(x) = x + + - 'logistic', the logistic sigmoid function, + returns f(x) = 1 / (1 + exp(-x)). + + - 'tanh', the hyperbolic tan function, + returns f(x) = tanh(x). + + - 'relu', the rectified linear unit function, + returns f(x) = max(0, x) + + solver : {'lbfgs', 'sgd', 'adam'}, default='adam' + The solver for weight optimization. + + - 'lbfgs' is an optimizer in the family of quasi-Newton methods. + + - 'sgd' refers to stochastic gradient descent. + + - 'adam' refers to a stochastic gradient-based optimizer proposed by + Kingma, Diederik, and Jimmy Ba + + For a comparison between Adam optimizer and SGD, see + :ref:`sphx_glr_auto_examples_neural_networks_plot_mlp_training_curves.py`. + + Note: The default solver 'adam' works pretty well on relatively + large datasets (with thousands of training samples or more) in terms of + both training time and validation score. + For small datasets, however, 'lbfgs' can converge faster and perform + better. + + alpha : float, default=0.0001 + Strength of the L2 regularization term. The L2 regularization term + is divided by the sample size when added to the loss. + + batch_size : int, default='auto' + Size of minibatches for stochastic optimizers. + If the solver is 'lbfgs', the regressor will not use minibatch. + When set to "auto", `batch_size=min(200, n_samples)`. + + learning_rate : {'constant', 'invscaling', 'adaptive'}, default='constant' + Learning rate schedule for weight updates. + + - 'constant' is a constant learning rate given by + 'learning_rate_init'. + + - 'invscaling' gradually decreases the learning rate ``learning_rate_`` + at each time step 't' using an inverse scaling exponent of 'power_t'. + effective_learning_rate = learning_rate_init / pow(t, power_t) + + - 'adaptive' keeps the learning rate constant to + 'learning_rate_init' as long as training loss keeps decreasing. + Each time two consecutive epochs fail to decrease training loss by at + least tol, or fail to increase validation score by at least tol if + 'early_stopping' is on, the current learning rate is divided by 5. + + Only used when solver='sgd'. + + learning_rate_init : float, default=0.001 + The initial learning rate used. It controls the step-size + in updating the weights. Only used when solver='sgd' or 'adam'. + + power_t : float, default=0.5 + The exponent for inverse scaling learning rate. + It is used in updating effective learning rate when the learning_rate + is set to 'invscaling'. Only used when solver='sgd'. + + max_iter : int, default=200 + Maximum number of iterations. The solver iterates until convergence + (determined by 'tol') or this number of iterations. For stochastic + solvers ('sgd', 'adam'), note that this determines the number of epochs + (how many times each data point will be used), not the number of + gradient steps. + + shuffle : bool, default=True + Whether to shuffle samples in each iteration. Only used when + solver='sgd' or 'adam'. + + random_state : int, RandomState instance, default=None + Determines random number generation for weights and bias + initialization, train-test split if early stopping is used, and batch + sampling when solver='sgd' or 'adam'. + Pass an int for reproducible results across multiple function calls. + See :term:`Glossary `. + + tol : float, default=1e-4 + Tolerance for the optimization. When the loss or score is not improving + by at least ``tol`` for ``n_iter_no_change`` consecutive iterations, + unless ``learning_rate`` is set to 'adaptive', convergence is + considered to be reached and training stops. + + verbose : bool, default=False + Whether to print progress messages to stdout. + + warm_start : bool, default=False + When set to True, reuse the solution of the previous + call to fit as initialization, otherwise, just erase the + previous solution. See :term:`the Glossary `. + + momentum : float, default=0.9 + Momentum for gradient descent update. Should be between 0 and 1. Only + used when solver='sgd'. + + nesterovs_momentum : bool, default=True + Whether to use Nesterov's momentum. Only used when solver='sgd' and + momentum > 0. + + early_stopping : bool, default=False + Whether to use early stopping to terminate training when validation + score is not improving. If set to True, it will automatically set + aside ``validation_fraction`` of training data as validation and + terminate training when validation score is not improving by at + least ``tol`` for ``n_iter_no_change`` consecutive epochs. + Only effective when solver='sgd' or 'adam'. + + validation_fraction : float, default=0.1 + The proportion of training data to set aside as validation set for + early stopping. Must be between 0 and 1. + Only used if early_stopping is True. + + beta_1 : float, default=0.9 + Exponential decay rate for estimates of first moment vector in adam, + should be in [0, 1). Only used when solver='adam'. + + beta_2 : float, default=0.999 + Exponential decay rate for estimates of second moment vector in adam, + should be in [0, 1). Only used when solver='adam'. + + epsilon : float, default=1e-8 + Value for numerical stability in adam. Only used when solver='adam'. + + n_iter_no_change : int, default=10 + Maximum number of epochs to not meet ``tol`` improvement. + Only effective when solver='sgd' or 'adam'. + + .. versionadded:: 0.20 + + max_fun : int, default=15000 + Only used when solver='lbfgs'. Maximum number of function calls. + The solver iterates until convergence (determined by ``tol``), number + of iterations reaches max_iter, or this number of function calls. + Note that number of function calls will be greater than or equal to + the number of iterations for the MLPRegressor. + + .. versionadded:: 0.22 + + Attributes + ---------- + loss_ : float + The current loss computed with the loss function. + + best_loss_ : float + The minimum loss reached by the solver throughout fitting. + If `early_stopping=True`, this attribute is set to `None`. Refer to + the `best_validation_score_` fitted attribute instead. + Only accessible when solver='sgd' or 'adam'. + + loss_curve_ : list of shape (`n_iter_`,) + Loss value evaluated at the end of each training step. + The ith element in the list represents the loss at the ith iteration. + Only accessible when solver='sgd' or 'adam'. + + validation_scores_ : list of shape (`n_iter_`,) or None + The score at each iteration on a held-out validation set. The score + reported is the R2 score. Only available if `early_stopping=True`, + otherwise the attribute is set to `None`. + Only accessible when solver='sgd' or 'adam'. + + best_validation_score_ : float or None + The best validation score (i.e. R2 score) that triggered the + early stopping. Only available if `early_stopping=True`, otherwise the + attribute is set to `None`. + Only accessible when solver='sgd' or 'adam'. + + t_ : int + The number of training samples seen by the solver during fitting. + Mathematically equals `n_iters * X.shape[0]`, it means + `time_step` and it is used by optimizer's learning rate scheduler. + + coefs_ : list of shape (n_layers - 1,) + The ith element in the list represents the weight matrix corresponding + to layer i. + + intercepts_ : list of shape (n_layers - 1,) + The ith element in the list represents the bias vector corresponding to + layer i + 1. + + n_features_in_ : int + Number of features seen during :term:`fit`. + + .. versionadded:: 0.24 + + feature_names_in_ : ndarray of shape (`n_features_in_`,) + Names of features seen during :term:`fit`. Defined only when `X` + has feature names that are all strings. + + .. versionadded:: 1.0 + + n_iter_ : int + The number of iterations the solver has run. + + n_layers_ : int + Number of layers. + + n_outputs_ : int + Number of outputs. + + out_activation_ : str + Name of the output activation function. + + See Also + -------- + BernoulliRBM : Bernoulli Restricted Boltzmann Machine (RBM). + MLPClassifier : Multi-layer Perceptron classifier. + sklearn.linear_model.SGDRegressor : Linear model fitted by minimizing + a regularized empirical loss with SGD. + + Notes + ----- + MLPRegressor trains iteratively since at each time step + the partial derivatives of the loss function with respect to the model + parameters are computed to update the parameters. + + It can also have a regularization term added to the loss function + that shrinks model parameters to prevent overfitting. + + This implementation works with data represented as dense and sparse numpy + arrays of floating point values. + + References + ---------- + Hinton, Geoffrey E. "Connectionist learning procedures." + Artificial intelligence 40.1 (1989): 185-234. + + Glorot, Xavier, and Yoshua Bengio. + "Understanding the difficulty of training deep feedforward neural networks." + International Conference on Artificial Intelligence and Statistics. 2010. + + :arxiv:`He, Kaiming, et al (2015). "Delving deep into rectifiers: + Surpassing human-level performance on imagenet classification." <1502.01852>` + + :arxiv:`Kingma, Diederik, and Jimmy Ba (2014) + "Adam: A method for stochastic optimization." <1412.6980>` + + Examples + -------- + >>> from sklearn.neural_network import MLPRegressor + >>> from sklearn.datasets import make_regression + >>> from sklearn.model_selection import train_test_split + >>> X, y = make_regression(n_samples=200, n_features=20, random_state=1) + >>> X_train, X_test, y_train, y_test = train_test_split(X, y, + ... random_state=1) + >>> regr = MLPRegressor(random_state=1, max_iter=2000, tol=0.1) + >>> regr.fit(X_train, y_train) + MLPRegressor(max_iter=2000, random_state=1, tol=0.1) + >>> regr.predict(X_test[:2]) + array([ 28.98, -291]) + >>> regr.score(X_test, y_test) + 0.98 + """ + + _parameter_constraints: dict = { + **BaseMultilayerPerceptron._parameter_constraints, + "loss": [StrOptions({"squared_error", "poisson"})], + } + + def __init__( + self, + loss="squared_error", + hidden_layer_sizes=(100,), + activation="relu", + *, + solver="adam", + alpha=0.0001, + batch_size="auto", + learning_rate="constant", + learning_rate_init=0.001, + power_t=0.5, + max_iter=200, + shuffle=True, + random_state=None, + tol=1e-4, + verbose=False, + warm_start=False, + momentum=0.9, + nesterovs_momentum=True, + early_stopping=False, + validation_fraction=0.1, + beta_1=0.9, + beta_2=0.999, + epsilon=1e-8, + n_iter_no_change=10, + max_fun=15000, + ): + super().__init__( + hidden_layer_sizes=hidden_layer_sizes, + activation=activation, + solver=solver, + alpha=alpha, + batch_size=batch_size, + learning_rate=learning_rate, + learning_rate_init=learning_rate_init, + power_t=power_t, + max_iter=max_iter, + loss=loss, + shuffle=shuffle, + random_state=random_state, + tol=tol, + verbose=verbose, + warm_start=warm_start, + momentum=momentum, + nesterovs_momentum=nesterovs_momentum, + early_stopping=early_stopping, + validation_fraction=validation_fraction, + beta_1=beta_1, + beta_2=beta_2, + epsilon=epsilon, + n_iter_no_change=n_iter_no_change, + max_fun=max_fun, + ) + + def predict(self, X): + """Predict using the multi-layer perceptron model. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input data. + + Returns + ------- + y : ndarray of shape (n_samples, n_outputs) + The predicted values. + """ + check_is_fitted(self) + return self._predict(X) + + def _predict(self, X, check_input=True): + """Private predict method with optional input validation""" + y_pred = self._forward_pass_fast(X, check_input=check_input) + if y_pred.shape[1] == 1: + return y_pred.ravel() + return y_pred + + def _score(self, X, y, sample_weight=None): + return super()._score_with_function( + X, y, sample_weight=sample_weight, score_function=r2_score + ) + + def _validate_input(self, X, y, incremental, reset): + X, y = validate_data( + self, + X, + y, + accept_sparse=["csr", "csc"], + multi_output=True, + y_numeric=True, + dtype=(np.float64, np.float32), + reset=reset, + ) + if y.ndim == 2 and y.shape[1] == 1: + y = column_or_1d(y, warn=True) + return X, y + + @available_if(lambda est: est._check_solver) + @_fit_context(prefer_skip_nested_validation=True) + def partial_fit(self, X, y, sample_weight=None): + """Update the model with a single iteration over the given data. + + Parameters + ---------- + X : {array-like, sparse matrix} of shape (n_samples, n_features) + The input data. + + y : ndarray of shape (n_samples,) + The target values. + + sample_weight : array-like of shape (n_samples,), default=None + Sample weights. + + .. versionadded:: 1.6 + + Returns + ------- + self : object + Trained MLP model. + """ + return self._fit(X, y, sample_weight=sample_weight, incremental=True) diff --git a/shared/package-files/ab/ab55b88bd16e51e688c76440eeae061b30d18772afe67bd65dcf9cd491c02291/blob b/shared/package-files/ab/ab55b88bd16e51e688c76440eeae061b30d18772afe67bd65dcf9cd491c02291/blob new file mode 100644 index 0000000000000000000000000000000000000000..cd7b2a92c0ad018a7d376b6fcde29134ea3838ce --- /dev/null +++ b/shared/package-files/ab/ab55b88bd16e51e688c76440eeae061b30d18772afe67bd65dcf9cd491c02291/blob @@ -0,0 +1,369 @@ +""" +Test functions for models.tools +""" + +from statsmodels.compat.pandas import assert_frame_equal, assert_series_equal +from statsmodels.compat.python import lrange + +import itertools +import string + +import numpy as np +from numpy.testing import ( + assert_almost_equal, + assert_array_equal, + assert_equal, + assert_string_equal, +) +import pandas as pd +import pytest + +from statsmodels.datasets import longley +from statsmodels.tools import tools +from statsmodels.tools.tools import pinv_extended + + +@pytest.fixture(scope="module") +def string_var(): + string_var = [ + string.ascii_lowercase[0:5], + string.ascii_lowercase[5:10], + string.ascii_lowercase[10:15], + string.ascii_lowercase[15:20], + string.ascii_lowercase[20:25], + ] + string_var *= 5 + string_var = np.asarray(sorted(string_var)) + series = pd.Series(string_var, name="string_var") + return series + + +class TestTools: + def test_add_constant_list(self): + x = lrange(1, 5) + x = tools.add_constant(x) + y = np.asarray([[1, 1, 1, 1], [1, 2, 3, 4.0]]).T + assert_equal(x, y) + + def test_add_constant_1d(self): + x = np.arange(1, 5) + x = tools.add_constant(x) + y = np.asarray([[1, 1, 1, 1], [1, 2, 3, 4.0]]).T + assert_equal(x, y) + + def test_add_constant_has_constant1d(self): + x = np.ones(5) + x = tools.add_constant(x, has_constant="skip") + assert_equal(x, np.ones((5, 1))) + + with pytest.raises(ValueError): + tools.add_constant(x, has_constant="raise") + + assert_equal(tools.add_constant(x, has_constant="add"), np.ones((5, 2))) + + def test_add_constant_has_constant2d(self): + x = np.asarray([[1, 1, 1, 1], [1, 2, 3, 4.0]]).T + y = tools.add_constant(x, has_constant="skip") + assert_equal(x, y) + + with pytest.raises(ValueError): + tools.add_constant(x, has_constant="raise") + + assert_equal( + tools.add_constant(x, has_constant="add"), + np.column_stack((np.ones(4), x)), + ) + + def test_add_constant_series(self): + s = pd.Series([1.0, 2.0, 3.0]) + output = tools.add_constant(s) + expected = pd.Series([1.0, 1.0, 1.0], name="const") + assert_series_equal(expected, output["const"]) + + def test_add_constant_dataframe(self): + df = pd.DataFrame([[1.0, "a", 4], [2.0, "bc", 9], [3.0, "def", 16]]) + output = tools.add_constant(df) + expected = pd.Series([1.0, 1.0, 1.0], name="const") + assert_series_equal(expected, output["const"]) + dfc = df.copy() + dfc.insert(0, "const", np.ones(3)) + assert_frame_equal(dfc, output) + + def test_add_constant_zeros(self): + a = np.zeros(100) + output = tools.add_constant(a) + assert_equal(output[:, 0], np.ones(100)) + + s = pd.Series([0.0, 0.0, 0.0]) + output = tools.add_constant(s) + expected = pd.Series([1.0, 1.0, 1.0], name="const") + assert_series_equal(expected, output["const"]) + + df = pd.DataFrame([[0.0, "a", 4], [0.0, "bc", 9], [0.0, "def", 16]]) + output = tools.add_constant(df) + dfc = df.copy() + dfc.insert(0, "const", np.ones(3)) + assert_frame_equal(dfc, output) + + df = pd.DataFrame([[1.0, "a", 0], [0.0, "bc", 0], [0.0, "def", 0]]) + output = tools.add_constant(df) + dfc = df.copy() + dfc.insert(0, "const", np.ones(3)) + assert_frame_equal(dfc, output) + + def test_drop_missing(self): + _y = np.array([[1.0, 2.0, np.nan], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]) + # axis=1 looks for missing values across the columns of each row, so + # the row holding the nan is dropped + assert_almost_equal( + tools.drop_missing(_y, axis=1), + np.array([[4.0, 5.0, 6.0], [7.0, 8.0, 9.0]]), + ) + # axis=0 looks across the rows of each column, so the column holding + # the nan is dropped instead + assert_almost_equal( + tools.drop_missing(_y, axis=0), + np.array([[1.0, 2.0], [4.0, 5.0], [7.0, 8.0]]), + ) + + def test_drop_missing_x(self): + _y = np.array([[1.0, 2.0], [3.0, np.nan], [5.0, 6.0]]) + _x = np.array([[1.0, np.nan], [1.0, 1.0], [1.0, 1.0]]) + y, x = tools.drop_missing(_y, _x, axis=0) + assert_almost_equal(y, np.array([[1.0], [3.0], [5.0]])) + assert_almost_equal(x, np.array([[1.0], [1.0], [1.0]])) + + # axis=1 with two variables: a row is dropped if either _y or _x + # is missing anywhere in that row + _y = np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]]) + _x = np.array([[1.0, 1.0], [1.0, np.nan], [1.0, 1.0]]) + y, x = tools.drop_missing(_y, _x, axis=1) + assert_almost_equal(y, np.array([[1.0, 2.0], [5.0, 6.0]])) + assert_almost_equal(x, np.array([[1.0, 1.0], [1.0, 1.0]])) + + def test_recipr(self): + X = np.array([[2, 1], [-1, 0]]) + Y = tools.recipr(X) + assert_almost_equal(Y, np.array([[0.5, 1], [0, 0]])) + + def test_recipr0(self): + X = np.array([[2, 1], [-4, 0]]) + Y = tools.recipr0(X) + assert_almost_equal(Y, np.array([[0.5, 1], [-0.25, 0]])) + + def test_extendedpinv(self): + rs = np.random.RandomState(4783891) + X = rs.standard_normal((40, 10)) + np_inv = np.linalg.pinv(X) + np_sing_vals = np.linalg.svd(X, 0, 0) + sm_inv, sing_vals = pinv_extended(X) + assert_almost_equal(np_inv, sm_inv) + assert_almost_equal(np_sing_vals, sing_vals) + + def test_extendedpinv_singular(self): + rs = np.random.RandomState(4783893) + X = rs.standard_normal((40, 10)) + X[:, 5] = X[:, 1] + X[:, 3] + np_inv = np.linalg.pinv(X) + np_sing_vals = np.linalg.svd(X, 0, 0) + sm_inv, sing_vals = pinv_extended(X) + assert_almost_equal(np_inv, sm_inv) + assert_almost_equal(np_sing_vals, sing_vals) + + def test_fullrank(self): + import warnings + + rs = np.random.RandomState(4783895) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + X = rs.standard_normal((40, 10)) + X[:, 0] = X[:, 1] + X[:, 2] + + Y = tools.fullrank(X) + assert_equal(Y.shape, (40, 9)) + + X[:, 5] = X[:, 3] + X[:, 4] + Y = tools.fullrank(X) + assert_equal(Y.shape, (40, 8)) + warnings.simplefilter("ignore") + + +def test_estimable(): + rng = np.random.RandomState(20120713) + N, P = (40, 10) + X = rng.normal(size=(N, P)) + C = rng.normal(size=(1, P)) + isestimable = tools.isestimable + assert isestimable(C, X) + assert isestimable(np.eye(P), X) + for row in np.eye(P): + assert isestimable(row, X) + X = np.ones((40, 2)) + assert isestimable([1, 1], X) + assert not isestimable([1, 0], X) + assert not isestimable([0, 1], X) + assert not isestimable(np.eye(2), X) + halfX = rng.normal(size=(N, 5)) + X = np.hstack([halfX, halfX]) + assert not isestimable(np.hstack([np.eye(5), np.zeros((5, 5))]), X) + assert not isestimable(np.hstack([np.zeros((5, 5)), np.eye(5)]), X) + assert isestimable(np.hstack([np.eye(5), np.eye(5)]), X) + # Test array_like for design + XL = X.tolist() + assert isestimable(np.hstack([np.eye(5), np.eye(5)]), XL) + # Test ValueError for incorrect number of columns + X = rng.normal(size=(N, 5)) + for n in range(1, 4): + with pytest.raises(ValueError): + isestimable(np.ones((n,)), X) + with pytest.raises(ValueError): + isestimable(np.eye(4), X) + + +@pytest.mark.parametrize("method", ["ip", "qr", "svd"]) +def test_matrix_rank_column_order(method): + # the rank of a matrix is a property of its column space, so it does not + # depend on the order the columns are given in. The regressor here is + # measured on a much larger scale than the intercept, which is the case + # that separates a tolerance taken from the leading diagonal element of + # the R matrix from one taken from the largest. + x = 1e3 * np.arange(1.0, 41.0) / 7.0 + exog = np.column_stack((np.ones(40), x, 2.0 * x)) + + for cols in itertools.permutations(range(exog.shape[1])): + rank = tools.matrix_rank(exog[:, list(cols)], method=method) + assert_equal(rank, 2, err_msg=f"column order {cols}") + + +def test_pandas_const_series(): + dta = longley.load_pandas() + series = dta.exog["GNP"] + series = tools.add_constant(series, prepend=False) + assert_string_equal("const", series.columns[1]) + assert_equal(series.var(axis=0).iloc[1], 0) + + +def test_pandas_const_series_prepend(): + dta = longley.load_pandas() + series = dta.exog["GNP"] + series = tools.add_constant(series, prepend=True) + assert_string_equal("const", series.columns[0]) + assert_equal(series.var(axis=0).iloc[0], 0) + + +def test_pandas_const_df(): + dta = longley.load_pandas().exog + dta = tools.add_constant(dta, prepend=False) + assert_string_equal("const", dta.columns[-1]) + assert_equal(dta.var(axis=0).iloc[-1], 0) + + +def test_pandas_const_df_prepend(): + dta = longley.load_pandas().exog + # regression test for #1025 + dta["UNEMP"] /= dta["UNEMP"].std() + dta = tools.add_constant(dta, prepend=True) + assert_string_equal("const", dta.columns[0]) + assert_equal(dta.var(axis=0).iloc[0], 0) + + +class TestNanDot: + @classmethod + def setup_class(cls): + nan = np.nan + cls.mx_1 = np.array([[nan, 1.0], [2.0, 3.0]]) + cls.mx_2 = np.array([[nan, nan], [2.0, 3.0]]) + cls.mx_3 = np.array([[0.0, 0.0], [0.0, 0.0]]) + cls.mx_4 = np.array([[1.0, 0.0], [1.0, 0.0]]) + cls.mx_5 = np.array([[0.0, 1.0], [0.0, 1.0]]) + cls.mx_6 = np.array([[1.0, 2.0], [3.0, 4.0]]) + + def test_11(self): + test_res = tools.nan_dot(self.mx_1, self.mx_1) + expected_res = np.array([[np.nan, np.nan], [np.nan, 11.0]]) + assert_array_equal(test_res, expected_res) + + def test_12(self): + nan = np.nan + test_res = tools.nan_dot(self.mx_1, self.mx_2) + expected_res = np.array([[nan, nan], [nan, nan]]) + assert_array_equal(test_res, expected_res) + + def test_13(self): + test_res = tools.nan_dot(self.mx_1, self.mx_3) + expected_res = np.array([[0.0, 0.0], [0.0, 0.0]]) + assert_array_equal(test_res, expected_res) + + def test_14(self): + nan = np.nan + test_res = tools.nan_dot(self.mx_1, self.mx_4) + expected_res = np.array([[nan, 0.0], [5.0, 0.0]]) + assert_array_equal(test_res, expected_res) + + def test_41(self): + nan = np.nan + test_res = tools.nan_dot(self.mx_4, self.mx_1) + expected_res = np.array([[nan, 1.0], [nan, 1.0]]) + assert_array_equal(test_res, expected_res) + + def test_23(self): + test_res = tools.nan_dot(self.mx_2, self.mx_3) + expected_res = np.array([[0.0, 0.0], [0.0, 0.0]]) + assert_array_equal(test_res, expected_res) + + def test_32(self): + test_res = tools.nan_dot(self.mx_3, self.mx_2) + expected_res = np.array([[0.0, 0.0], [0.0, 0.0]]) + assert_array_equal(test_res, expected_res) + + def test_24(self): + nan = np.nan + test_res = tools.nan_dot(self.mx_2, self.mx_4) + expected_res = np.array([[nan, 0.0], [5.0, 0.0]]) + assert_array_equal(test_res, expected_res) + + def test_25(self): + nan = np.nan + test_res = tools.nan_dot(self.mx_2, self.mx_5) + expected_res = np.array([[0.0, nan], [0.0, 5.0]]) + assert_array_equal(test_res, expected_res) + + def test_66(self): + test_res = tools.nan_dot(self.mx_6, self.mx_6) + expected_res = np.array([[7.0, 10.0], [15.0, 22.0]]) + assert_array_equal(test_res, expected_res) + + +class TestEnsure2d: + @classmethod + def setup_class(cls): + x = np.arange(400.0).reshape((100, 4)) + cls.df = pd.DataFrame(x, columns=["a", "b", "c", "d"]) + cls.series = cls.df.iloc[:, 0] + cls.ndarray = x + + def test_enfore_numpy(self): + results = tools._ensure_2d(self.df, True) + assert_array_equal(results[0], self.ndarray) + assert_array_equal(results[1], self.df.columns) + results = tools._ensure_2d(self.series, True) + assert_array_equal(results[0], self.ndarray[:, [0]]) + assert_array_equal(results[1], self.df.columns[0]) + + def test_pandas(self): + results = tools._ensure_2d(self.df, False) + assert_frame_equal(results[0], self.df) + assert_array_equal(results[1], self.df.columns) + + results = tools._ensure_2d(self.series, False) + assert_frame_equal(results[0], self.df.iloc[:, [0]]) + assert_equal(results[1], self.df.columns[0]) + + def test_numpy(self): + results = tools._ensure_2d(self.ndarray) + assert_array_equal(results[0], self.ndarray) + assert_equal(results[1], None) + + results = tools._ensure_2d(self.ndarray[:, 0]) + assert_array_equal(results[0], self.ndarray[:, [0]]) + assert_equal(results[1], None) diff --git a/shared/package-files/ab/ab56282cd247bfeeefd81cf577f5d21d20d08e22600777ce62a9033a1c7ee57d/blob b/shared/package-files/ab/ab56282cd247bfeeefd81cf577f5d21d20d08e22600777ce62a9033a1c7ee57d/blob new file mode 100644 index 0000000000000000000000000000000000000000..119f769c944035dfe3e4147f75923e5ed2314276 Binary files /dev/null and b/shared/package-files/ab/ab56282cd247bfeeefd81cf577f5d21d20d08e22600777ce62a9033a1c7ee57d/blob differ diff --git a/shared/package-files/ab/ab56b130b5df29e4871924951fb08229d5857ed0a2b27cfd5d3f7f84dda43aef/blob b/shared/package-files/ab/ab56b130b5df29e4871924951fb08229d5857ed0a2b27cfd5d3f7f84dda43aef/blob new file mode 100644 index 0000000000000000000000000000000000000000..6eb548130c5cf2cfc2f9bc972db8ab7e44bd0059 --- /dev/null +++ b/shared/package-files/ab/ab56b130b5df29e4871924951fb08229d5857ed0a2b27cfd5d3f7f84dda43aef/blob @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor max_pool2d(const at::Tensor & self, at::IntArrayRef kernel_size, at::IntArrayRef stride={}, at::IntArrayRef padding=0, at::IntArrayRef dilation=1, bool ceil_mode=false); +} // namespace native +} // namespace at diff --git a/shared/package-files/ab/ab5ede532a8e10ad8b25829760b089ab2963faf99a086daf48d32db6aad04d19/blob b/shared/package-files/ab/ab5ede532a8e10ad8b25829760b089ab2963faf99a086daf48d32db6aad04d19/blob new file mode 100644 index 0000000000000000000000000000000000000000..a3bf7f29b6f14debfbd0f8ccb45f1ea338009ef7 Binary files /dev/null and b/shared/package-files/ab/ab5ede532a8e10ad8b25829760b089ab2963faf99a086daf48d32db6aad04d19/blob differ diff --git a/shared/package-files/ab/ab5f25a53347e316db071ba8d939c0ac6007b26a168b35e3cbff28e65e1fa81e/blob b/shared/package-files/ab/ab5f25a53347e316db071ba8d939c0ac6007b26a168b35e3cbff28e65e1fa81e/blob new file mode 100644 index 0000000000000000000000000000000000000000..a8090d36b5e897339127029d683ead751e7f4915 --- /dev/null +++ b/shared/package-files/ab/ab5f25a53347e316db071ba8d939c0ac6007b26a168b35e3cbff28e65e1fa81e/blob @@ -0,0 +1,319 @@ +Metadata-Version: 2.1 +Name: platformdirs +Version: 3.10.0 +Summary: A small Python package for determining appropriate platform-specific dirs, e.g. a "user data dir". +Project-URL: Documentation, https://platformdirs.readthedocs.io +Project-URL: Homepage, https://github.com/platformdirs/platformdirs +Project-URL: Source, https://github.com/platformdirs/platformdirs +Project-URL: Tracker, https://github.com/platformdirs/platformdirs/issues +Maintainer-email: Bernát Gábor , Julian Berman , Ofek Lev , Ronny Pfannschmidt +License-Expression: MIT +License-File: LICENSE +Keywords: appdirs,application,cache,directory,log,user +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.7 +Requires-Dist: typing-extensions>=4.7.1; python_version < '3.8' +Provides-Extra: docs +Requires-Dist: furo>=2023.7.26; extra == 'docs' +Requires-Dist: proselint>=0.13; extra == 'docs' +Requires-Dist: sphinx-autodoc-typehints>=1.24; extra == 'docs' +Requires-Dist: sphinx>=7.1.1; extra == 'docs' +Provides-Extra: test +Requires-Dist: appdirs==1.4.4; extra == 'test' +Requires-Dist: covdefaults>=2.3; extra == 'test' +Requires-Dist: pytest-cov>=4.1; extra == 'test' +Requires-Dist: pytest-mock>=3.11.1; extra == 'test' +Requires-Dist: pytest>=7.4; extra == 'test' +Description-Content-Type: text/x-rst + +The problem +=========== + +.. image:: https://github.com/platformdirs/platformdirs/workflows/Test/badge.svg + :target: https://github.com/platformdirs/platformdirs/actions?query=workflow%3ATest + +When writing desktop application, finding the right location to store user data +and configuration varies per platform. Even for single-platform apps, there +may by plenty of nuances in figuring out the right location. + +For example, if running on macOS, you should use:: + + ~/Library/Application Support/ + +If on Windows (at least English Win) that should be:: + + C:\Documents and Settings\\Application Data\Local Settings\\ + +or possibly:: + + C:\Documents and Settings\\Application Data\\ + +for `roaming profiles `_ but that is another story. + +On Linux (and other Unices), according to the `XDG Basedir Spec`_, it should be:: + + ~/.local/share/ + +.. _XDG Basedir Spec: https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html + +``platformdirs`` to the rescue +============================== + +This kind of thing is what the ``platformdirs`` package is for. +``platformdirs`` will help you choose an appropriate: + +- user data dir (``user_data_dir``) +- user config dir (``user_config_dir``) +- user cache dir (``user_cache_dir``) +- site data dir (``site_data_dir``) +- site config dir (``site_config_dir``) +- user log dir (``user_log_dir``) +- user documents dir (``user_documents_dir``) +- user downloads dir (``user_downloads_dir``) +- user pictures dir (``user_pictures_dir``) +- user videos dir (``user_videos_dir``) +- user music dir (``user_music_dir``) +- user desktop dir (``user_desktop_dir``) +- user runtime dir (``user_runtime_dir``) + +And also: + +- Is slightly opinionated on the directory names used. Look for "OPINION" in + documentation and code for when an opinion is being applied. + +Example output +============== + +On macOS: + +.. code-block:: pycon + + >>> from platformdirs import * + >>> appname = "SuperApp" + >>> appauthor = "Acme" + >>> user_data_dir(appname, appauthor) + '/Users/trentm/Library/Application Support/SuperApp' + >>> site_data_dir(appname, appauthor) + '/Library/Application Support/SuperApp' + >>> user_cache_dir(appname, appauthor) + '/Users/trentm/Library/Caches/SuperApp' + >>> user_log_dir(appname, appauthor) + '/Users/trentm/Library/Logs/SuperApp' + >>> user_documents_dir() + '/Users/trentm/Documents' + >>> user_downloads_dir() + '/Users/trentm/Downloads' + >>> user_pictures_dir() + '/Users/trentm/Pictures' + >>> user_videos_dir() + '/Users/trentm/Movies' + >>> user_music_dir() + '/Users/trentm/Music' + >>> user_desktop_dir() + '/Users/trentm/Desktop' + >>> user_runtime_dir(appname, appauthor) + '/Users/trentm/Library/Caches/TemporaryItems/SuperApp' + +On Windows: + +.. code-block:: pycon + + >>> from platformdirs import * + >>> appname = "SuperApp" + >>> appauthor = "Acme" + >>> user_data_dir(appname, appauthor) + 'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp' + >>> user_data_dir(appname, appauthor, roaming=True) + 'C:\\Users\\trentm\\AppData\\Roaming\\Acme\\SuperApp' + >>> user_cache_dir(appname, appauthor) + 'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp\\Cache' + >>> user_log_dir(appname, appauthor) + 'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp\\Logs' + >>> user_documents_dir() + 'C:\\Users\\trentm\\Documents' + >>> user_downloads_dir() + 'C:\\Users\\trentm\\Downloads' + >>> user_pictures_dir() + 'C:\\Users\\trentm\\Pictures' + >>> user_videos_dir() + 'C:\\Users\\trentm\\Videos' + >>> user_music_dir() + 'C:\\Users\\trentm\\Music' + >>> user_desktop_dir() + 'C:\\Users\\trentm\\Desktop' + >>> user_runtime_dir(appname, appauthor) + 'C:\\Users\\trentm\\AppData\\Local\\Temp\\Acme\\SuperApp' + +On Linux: + +.. code-block:: pycon + + >>> from platformdirs import * + >>> appname = "SuperApp" + >>> appauthor = "Acme" + >>> user_data_dir(appname, appauthor) + '/home/trentm/.local/share/SuperApp' + >>> site_data_dir(appname, appauthor) + '/usr/local/share/SuperApp' + >>> site_data_dir(appname, appauthor, multipath=True) + '/usr/local/share/SuperApp:/usr/share/SuperApp' + >>> user_cache_dir(appname, appauthor) + '/home/trentm/.cache/SuperApp' + >>> user_log_dir(appname, appauthor) + '/home/trentm/.cache/SuperApp/log' + >>> user_config_dir(appname) + '/home/trentm/.config/SuperApp' + >>> user_documents_dir() + '/home/trentm/Documents' + >>> user_downloads_dir() + '/home/trentm/Downloads' + >>> user_pictures_dir() + '/home/trentm/Pictures' + >>> user_videos_dir() + '/home/trentm/Videos' + >>> user_music_dir() + '/home/trentm/Music' + >>> user_desktop_dir() + '/home/trentm/Desktop' + >>> user_runtime_dir(appname, appauthor) + '/run/user/{os.getuid()}/SuperApp' + >>> site_config_dir(appname) + '/etc/xdg/SuperApp' + >>> os.environ["XDG_CONFIG_DIRS"] = "/etc:/usr/local/etc" + >>> site_config_dir(appname, multipath=True) + '/etc/SuperApp:/usr/local/etc/SuperApp' + +On Android:: + + >>> from platformdirs import * + >>> appname = "SuperApp" + >>> appauthor = "Acme" + >>> user_data_dir(appname, appauthor) + '/data/data/com.myApp/files/SuperApp' + >>> user_cache_dir(appname, appauthor) + '/data/data/com.myApp/cache/SuperApp' + >>> user_log_dir(appname, appauthor) + '/data/data/com.myApp/cache/SuperApp/log' + >>> user_config_dir(appname) + '/data/data/com.myApp/shared_prefs/SuperApp' + >>> user_documents_dir() + '/storage/emulated/0/Documents' + >>> user_downloads_dir() + '/storage/emulated/0/Downloads' + >>> user_pictures_dir() + '/storage/emulated/0/Pictures' + >>> user_videos_dir() + '/storage/emulated/0/DCIM/Camera' + >>> user_music_dir() + '/storage/emulated/0/Music' + >>> user_desktop_dir() + '/storage/emulated/0/Desktop' + >>> user_runtime_dir(appname, appauthor) + '/data/data/com.myApp/cache/SuperApp/tmp' + +Note: Some android apps like Termux and Pydroid are used as shells. These +apps are used by the end user to emulate Linux environment. Presence of +``SHELL`` environment variable is used by Platformdirs to differentiate +between general android apps and android apps used as shells. Shell android +apps also support ``XDG_*`` environment variables. + + +``PlatformDirs`` for convenience +================================ + +.. code-block:: pycon + + >>> from platformdirs import PlatformDirs + >>> dirs = PlatformDirs("SuperApp", "Acme") + >>> dirs.user_data_dir + '/Users/trentm/Library/Application Support/SuperApp' + >>> dirs.site_data_dir + '/Library/Application Support/SuperApp' + >>> dirs.user_cache_dir + '/Users/trentm/Library/Caches/SuperApp' + >>> dirs.user_log_dir + '/Users/trentm/Library/Logs/SuperApp' + >>> dirs.user_documents_dir + '/Users/trentm/Documents' + >>> dirs.user_downloads_dir + '/Users/trentm/Downloads' + >>> dirs.user_pictures_dir + '/Users/trentm/Pictures' + >>> dirs.user_videos_dir + '/Users/trentm/Movies' + >>> dirs.user_music_dir + '/Users/trentm/Music' + >>> dirs.user_desktop_dir + '/Users/trentm/Desktop' + >>> dirs.user_runtime_dir + '/Users/trentm/Library/Caches/TemporaryItems/SuperApp' + +Per-version isolation +===================== + +If you have multiple versions of your app in use that you want to be +able to run side-by-side, then you may want version-isolation for these +dirs:: + + >>> from platformdirs import PlatformDirs + >>> dirs = PlatformDirs("SuperApp", "Acme", version="1.0") + >>> dirs.user_data_dir + '/Users/trentm/Library/Application Support/SuperApp/1.0' + >>> dirs.site_data_dir + '/Library/Application Support/SuperApp/1.0' + >>> dirs.user_cache_dir + '/Users/trentm/Library/Caches/SuperApp/1.0' + >>> dirs.user_log_dir + '/Users/trentm/Library/Logs/SuperApp/1.0' + >>> dirs.user_documents_dir + '/Users/trentm/Documents' + >>> dirs.user_downloads_dir + '/Users/trentm/Downloads' + >>> dirs.user_pictures_dir + '/Users/trentm/Pictures' + >>> dirs.user_videos_dir + '/Users/trentm/Movies' + >>> dirs.user_music_dir + '/Users/trentm/Music' + >>> dirs.user_desktop_dir + '/Users/trentm/Desktop' + >>> dirs.user_runtime_dir + '/Users/trentm/Library/Caches/TemporaryItems/SuperApp/1.0' + +Be wary of using this for configuration files though; you'll need to handle +migrating configuration files manually. + +Why this Fork? +============== + +This repository is a friendly fork of the wonderful work started by +`ActiveState `_ who created +``appdirs``, this package's ancestor. + +Maintaining an open source project is no easy task, particularly +from within an organization, and the Python community is indebted +to ``appdirs`` (and to Trent Mick and Jeff Rouse in particular) for +creating an incredibly useful simple module, as evidenced by the wide +number of users it has attracted over the years. + +Nonetheless, given the number of long-standing open issues +and pull requests, and no clear path towards `ensuring +that maintenance of the package would continue or grow +`_, this fork was +created. + +Contributions are most welcome. diff --git a/shared/package-files/ab/ab62247474c5955df8aab42590e2f5049ae8b06fb86b5d2fc410dcc9047f8878/blob b/shared/package-files/ab/ab62247474c5955df8aab42590e2f5049ae8b06fb86b5d2fc410dcc9047f8878/blob new file mode 100644 index 0000000000000000000000000000000000000000..8689550157b66bb8280db0056ece315d014b6209 --- /dev/null +++ b/shared/package-files/ab/ab62247474c5955df8aab42590e2f5049ae8b06fb86b5d2fc410dcc9047f8878/blob @@ -0,0 +1,65 @@ +#ifndef NUMBA_NRT_EXTERNAL_H_ +#define NUMBA_NRT_EXTERNAL_H_ + +#include + +typedef struct MemInfo NRT_MemInfo; + +typedef void NRT_managed_dtor(void *data); + +typedef void *(*NRT_external_malloc_func)(size_t size, void *opaque_data); +typedef void *(*NRT_external_realloc_func)(void *ptr, size_t new_size, void *opaque_data); +typedef void (*NRT_external_free_func)(void *ptr, void *opaque_data); + +struct ExternalMemAllocator { + NRT_external_malloc_func malloc; + NRT_external_realloc_func realloc; + NRT_external_free_func free; + void *opaque_data; +}; + +typedef struct ExternalMemAllocator NRT_ExternalAllocator; + +typedef struct { + /* Methods to create MemInfos. + + MemInfos are like smart pointers for objects that are managed by the Numba. + */ + + /* Allocate memory + + *nbytes* is the number of bytes to be allocated + + Returning a new reference. + */ + NRT_MemInfo* (*allocate)(size_t nbytes); + /* Allocates memory using an external allocator but still using Numba's MemInfo. + * + * NOTE: An externally provided allocator must behave the same way as C99 + * stdlib.h's "malloc" function with respect to return value + * (including the behaviour that occurs when requesting an allocation + * of size 0 bytes). + */ + NRT_MemInfo* (*allocate_external)(size_t nbytes, NRT_ExternalAllocator *allocator); + + /* Convert externally allocated memory into a MemInfo. + + *data* is the memory pointer + *dtor* is the deallocator of the memory + */ + NRT_MemInfo* (*manage_memory)(void *data, NRT_managed_dtor dtor); + + /* Acquire a reference */ + void (*acquire)(NRT_MemInfo* mi); + + /* Release a reference */ + void (*release)(NRT_MemInfo* mi); + + /* Get MemInfo data pointer */ + void* (*get_data)(NRT_MemInfo* mi); + +} NRT_api_functions; + + + +#endif /* NUMBA_NRT_EXTERNAL_H_ */ diff --git a/shared/package-files/ab/ab6258127aa652aefcacef27a3d857419ddf73746ec4fad109ca6c2ebba8bc38/blob b/shared/package-files/ab/ab6258127aa652aefcacef27a3d857419ddf73746ec4fad109ca6c2ebba8bc38/blob new file mode 100644 index 0000000000000000000000000000000000000000..f36fd2915be8c8d14138493c34dfd5733a2a1e6d --- /dev/null +++ b/shared/package-files/ab/ab6258127aa652aefcacef27a3d857419ddf73746ec4fad109ca6c2ebba8bc38/blob @@ -0,0 +1,48 @@ +""" +Various made-up tests to hit different branches of the code in specfun.c +""" + +import numpy as np +from numpy.testing import assert_allclose +from scipy import special + + +def test_cva2_cv0_branches(): + res, resp = special.mathieu_cem([40, 129], [13, 14], [30, 45]) + assert_allclose(res, np.array([-0.3741211, 0.74441928])) + assert_allclose(resp, np.array([-37.02872758, -86.13549877])) + + res, resp = special.mathieu_sem([40, 129], [13, 14], [30, 45]) + assert_allclose(res, np.array([0.92955551, 0.66771207])) + assert_allclose(resp, np.array([-14.91073448, 96.02954185])) + + +def test_chgm_branches(): + res = special.eval_genlaguerre(-3.2, 3, 2.5) + assert_allclose(res, -0.7077721935779854) + + +def test_hygfz_branches(): + """(z == 1.0) && (c-a-b > 0.0)""" + res = special.hyp2f1(1.5, 2.5, 4.5, 1.+0.j) + assert_allclose(res, 10.30835089459151+0j) + """(cabs(z+1) < eps) && (fabs(c-a+b - 1.0) < eps)""" + res = special.hyp2f1(5+5e-16, 2, 2, -1.0 + 5e-16j) + assert_allclose(res, 0.031249999999999986+3.9062499999999994e-17j) + + +def test_pro_rad1(): + # https://github.com/scipy/scipy/issues/21058 + # Reference values taken from WolframAlpha + # SpheroidalS1(1, 1, 30, 1.1) + # SpheroidalS1Prime(1, 1, 30, 1.1) + res = special.pro_rad1(1, 1, 30, 1.1) + assert_allclose(res, (0.009657872296166435, 3.253369651472877), rtol=2e-5) + +def test_pro_rad2(): + # https://github.com/scipy/scipy/issues/21461 + # Reference values taken from WolframAlpha + # SpheroidalS2(0, 0, 3, 1.02) + # SpheroidalS2Prime(0, 0, 3, 1.02) + res = special.pro_rad2(0, 0, 3, 1.02) + assert_allclose(res, (-0.35089596858528077, 13.652764213480872), rtol=10e-10) diff --git a/shared/package-files/ab/ab656e5e6759a61c81d95347eaa4a70cc59262878f291b267e08ba5b4f675f7d/blob b/shared/package-files/ab/ab656e5e6759a61c81d95347eaa4a70cc59262878f291b267e08ba5b4f675f7d/blob new file mode 100644 index 0000000000000000000000000000000000000000..6983f6b119e46698ae9539925f9b9128044e0c65 --- /dev/null +++ b/shared/package-files/ab/ab656e5e6759a61c81d95347eaa4a70cc59262878f291b267e08ba5b4f675f7d/blob @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab656e5e6759a61c81d95347eaa4a70cc59262878f291b267e08ba5b4f675f7d +size 670240 diff --git a/shared/package-files/ab/ab66eadd51f995801fcc342cf4fe5c1342aabe3717af7580a881db52b30d63dc/blob b/shared/package-files/ab/ab66eadd51f995801fcc342cf4fe5c1342aabe3717af7580a881db52b30d63dc/blob new file mode 100644 index 0000000000000000000000000000000000000000..823fd6932344ec608fb35654d799eef5bf716d9e --- /dev/null +++ b/shared/package-files/ab/ab66eadd51f995801fcc342cf4fe5c1342aabe3717af7580a881db52b30d63dc/blob @@ -0,0 +1,1377 @@ +# menu.tcl -- +# +# This file defines the default bindings for Tk menus and menubuttons. +# It also implements keyboard traversal of menus and implements a few +# other utility procedures related to menus. +# +# Copyright (c) 1992-1994 The Regents of the University of California. +# Copyright (c) 1994-1997 Sun Microsystems, Inc. +# Copyright (c) 1998-1999 Scriptics Corporation. +# Copyright (c) 2007 Daniel A. Steffen +# +# See the file "license.terms" for information on usage and redistribution +# of this file, and for a DISCLAIMER OF ALL WARRANTIES. +# + +#------------------------------------------------------------------------- +# Elements of tk::Priv that are used in this file: +# +# cursor - Saves the -cursor option for the posted menubutton. +# focus - Saves the focus during a menu selection operation. +# Focus gets restored here when the menu is unposted. +# grabGlobal - Used in conjunction with tk::Priv(oldGrab): if +# tk::Priv(oldGrab) is non-empty, then tk::Priv(grabGlobal) +# contains either an empty string or "-global" to +# indicate whether the old grab was a local one or +# a global one. +# inMenubutton - The name of the menubutton widget containing +# the mouse, or an empty string if the mouse is +# not over any menubutton. +# menuBar - The name of the menubar that is the root +# of the cascade hierarchy which is currently +# posted. This is null when there is no menu currently +# being pulled down from a menu bar. +# oldGrab - Window that had the grab before a menu was posted. +# Used to restore the grab state after the menu +# is unposted. Empty string means there was no +# grab previously set. +# popup - If a menu has been popped up via tk_popup, this +# gives the name of the menu. Otherwise this +# value is empty. +# postedMb - Name of the menubutton whose menu is currently +# posted, or an empty string if nothing is posted +# A grab is set on this widget. +# relief - Used to save the original relief of the current +# menubutton. +# window - When the mouse is over a menu, this holds the +# name of the menu; it's cleared when the mouse +# leaves the menu. +# tearoff - Whether the last menu posted was a tearoff or not. +# This is true always for unix, for tearoffs for Mac +# and Windows. +# activeMenu - This is the last active menu for use +# with the <> virtual event. +# activeItem - This is the last active menu item for +# use with the <> virtual event. +#------------------------------------------------------------------------- + +#------------------------------------------------------------------------- +# Overall note: +# This file is tricky because there are five different ways that menus +# can be used: +# +# 1. As a pulldown from a menubutton. In this style, the variable +# tk::Priv(postedMb) identifies the posted menubutton. +# 2. As a torn-off menu copied from some other menu. In this style +# tk::Priv(postedMb) is empty, and menu's type is "tearoff". +# 3. As an option menu, triggered from an option menubutton. In this +# style tk::Priv(postedMb) identifies the posted menubutton. +# 4. As a popup menu. In this style tk::Priv(postedMb) is empty and +# the top-level menu's type is "normal". +# 5. As a pulldown from a menubar. The variable tk::Priv(menubar) has +# the owning menubar, and the menu itself is of type "normal". +# +# The various binding procedures use the state described above to +# distinguish the various cases and take different actions in each +# case. +#------------------------------------------------------------------------- + +#------------------------------------------------------------------------- +# The code below creates the default class bindings for menus +# and menubuttons. +#------------------------------------------------------------------------- + +bind Menubutton {} +bind Menubutton { + tk::MbEnter %W +} +bind Menubutton { + tk::MbLeave %W +} +bind Menubutton <1> { + if {$tk::Priv(inMenubutton) ne ""} { + tk::MbPost $tk::Priv(inMenubutton) %X %Y + } +} +bind Menubutton { + tk::MbMotion %W up %X %Y +} +bind Menubutton { + tk::MbMotion %W down %X %Y +} +bind Menubutton { + tk::MbButtonUp %W +} +bind Menubutton { + tk::MbPost %W + tk::MenuFirstEntry [%W cget -menu] +} +bind Menubutton <> { + tk::MbPost %W + tk::MenuFirstEntry [%W cget -menu] +} + +# Must set focus when mouse enters a menu, in order to allow +# mixed-mode processing using both the mouse and the keyboard. +# Don't set the focus if the event comes from a grab release, +# though: such an event can happen after as part of unposting +# a cascaded chain of menus, after the focus has already been +# restored to wherever it was before menu selection started. + +bind Menu {} + +bind Menu { + set tk::Priv(window) %W + if {[%W cget -type] eq "tearoff"} { + if {"%m" ne "NotifyUngrab"} { + if {[tk windowingsystem] eq "x11"} { + tk_menuSetFocus %W + } + } + } + tk::MenuMotion %W %x %y %s +} + +bind Menu { + tk::MenuLeave %W %X %Y %s +} +bind Menu { + tk::MenuMotion %W %x %y %s +} +bind Menu