ZTWHHH commited on
Commit
5df5d4e
·
verified ·
1 Parent(s): c1208c9

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. parrot/lib/python3.10/site-packages/numpy/linalg/__pycache__/_linalg.cpython-310.pyc +3 -0
  3. parrot/lib/python3.10/site-packages/scipy/io/_netcdf.py +1095 -0
  4. parrot/lib/python3.10/site-packages/scipy/io/harwell_boeing.py +17 -0
  5. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/__init__.cpython-310.pyc +0 -0
  6. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_axis_nan_policy.cpython-310.pyc +0 -0
  7. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_binomtest.cpython-310.pyc +0 -0
  8. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_bws_test.cpython-310.pyc +0 -0
  9. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_censored_data.cpython-310.pyc +0 -0
  10. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_common.cpython-310.pyc +0 -0
  11. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_constants.cpython-310.pyc +0 -0
  12. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_covariance.cpython-310.pyc +0 -0
  13. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_crosstab.cpython-310.pyc +0 -0
  14. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_discrete_distns.cpython-310.pyc +0 -0
  15. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_fit.cpython-310.pyc +0 -0
  16. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_hypotests.cpython-310.pyc +0 -0
  17. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_kde.cpython-310.pyc +0 -0
  18. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_mannwhitneyu.cpython-310.pyc +0 -0
  19. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_mgc.cpython-310.pyc +0 -0
  20. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_mstats_extras.cpython-310.pyc +0 -0
  21. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_odds_ratio.cpython-310.pyc +0 -0
  22. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_page_trend_test.cpython-310.pyc +0 -0
  23. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_qmc.cpython-310.pyc +0 -0
  24. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_qmvnt.cpython-310.pyc +0 -0
  25. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_relative_risk.cpython-310.pyc +0 -0
  26. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_resampling.cpython-310.pyc +0 -0
  27. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_rvs_sampling.cpython-310.pyc +0 -0
  28. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_sensitivity_analysis.cpython-310.pyc +0 -0
  29. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_stats_mstats_common.cpython-310.pyc +0 -0
  30. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_survival.cpython-310.pyc +0 -0
  31. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_tukeylambda_stats.cpython-310.pyc +0 -0
  32. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_variation.cpython-310.pyc +0 -0
  33. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_warnings_errors.cpython-310.pyc +0 -0
  34. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_wilcoxon.cpython-310.pyc +0 -0
  35. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/biasedurn.cpython-310.pyc +0 -0
  36. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/contingency.cpython-310.pyc +0 -0
  37. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/distributions.cpython-310.pyc +0 -0
  38. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/morestats.cpython-310.pyc +0 -0
  39. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/mstats.cpython-310.pyc +0 -0
  40. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/mstats_extras.cpython-310.pyc +0 -0
  41. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/mvn.cpython-310.pyc +0 -0
  42. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/qmc.cpython-310.pyc +0 -0
  43. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/sampling.cpython-310.pyc +0 -0
  44. parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/stats.cpython-310.pyc +0 -0
  45. parrot/lib/python3.10/site-packages/scipy/stats/_levy_stable/__init__.py +1224 -0
  46. parrot/lib/python3.10/site-packages/scipy/stats/_levy_stable/__pycache__/__init__.cpython-310.pyc +0 -0
  47. parrot/lib/python3.10/site-packages/scipy/stats/_levy_stable/levyst.cpython-310-x86_64-linux-gnu.so +0 -0
  48. parrot/lib/python3.10/site-packages/scipy/stats/_rcont/__init__.py +4 -0
  49. parrot/lib/python3.10/site-packages/scipy/stats/_rcont/__pycache__/__init__.cpython-310.pyc +0 -0
  50. parrot/lib/python3.10/site-packages/scipy/stats/_unuran/__init__.py +0 -0
.gitattributes CHANGED
@@ -1448,3 +1448,4 @@ parrot/lib/python3.10/site-packages/numpy/_core/tests/__pycache__/test_regressio
1448
  vllm/lib/python3.10/site-packages/wandb/bin/wandb-core filter=lfs diff=lfs merge=lfs -text
1449
  vllm/lib/python3.10/site-packages/ray/_raylet.so filter=lfs diff=lfs merge=lfs -text
1450
  vllm/lib/python3.10/site-packages/mpmath/__pycache__/function_docs.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
 
 
1448
  vllm/lib/python3.10/site-packages/wandb/bin/wandb-core filter=lfs diff=lfs merge=lfs -text
1449
  vllm/lib/python3.10/site-packages/ray/_raylet.so filter=lfs diff=lfs merge=lfs -text
1450
  vllm/lib/python3.10/site-packages/mpmath/__pycache__/function_docs.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
1451
+ parrot/lib/python3.10/site-packages/numpy/linalg/__pycache__/_linalg.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
parrot/lib/python3.10/site-packages/numpy/linalg/__pycache__/_linalg.cpython-310.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:55865e5f8f27b015bf19923c757d9da1d11eaa115a927e844fe01ddd0214fe2c
3
+ size 107917
parrot/lib/python3.10/site-packages/scipy/io/_netcdf.py ADDED
@@ -0,0 +1,1095 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ NetCDF reader/writer module.
3
+
4
+ This module is used to read and create NetCDF files. NetCDF files are
5
+ accessed through the `netcdf_file` object. Data written to and from NetCDF
6
+ files are contained in `netcdf_variable` objects. Attributes are given
7
+ as member variables of the `netcdf_file` and `netcdf_variable` objects.
8
+
9
+ This module implements the Scientific.IO.NetCDF API to read and create
10
+ NetCDF files. The same API is also used in the PyNIO and pynetcdf
11
+ modules, allowing these modules to be used interchangeably when working
12
+ with NetCDF files.
13
+
14
+ Only NetCDF3 is supported here; for NetCDF4 see
15
+ `netCDF4-python <http://unidata.github.io/netcdf4-python/>`__,
16
+ which has a similar API.
17
+
18
+ """
19
+
20
+ # TODO:
21
+ # * properly implement ``_FillValue``.
22
+ # * fix character variables.
23
+ # * implement PAGESIZE for Python 2.6?
24
+
25
+ # The Scientific.IO.NetCDF API allows attributes to be added directly to
26
+ # instances of ``netcdf_file`` and ``netcdf_variable``. To differentiate
27
+ # between user-set attributes and instance attributes, user-set attributes
28
+ # are automatically stored in the ``_attributes`` attribute by overloading
29
+ #``__setattr__``. This is the reason why the code sometimes uses
30
+ #``obj.__dict__['key'] = value``, instead of simply ``obj.key = value``;
31
+ # otherwise the key would be inserted into userspace attributes.
32
+
33
+
34
+ __all__ = ['netcdf_file', 'netcdf_variable']
35
+
36
+
37
+ import warnings
38
+ import weakref
39
+ from operator import mul
40
+ from platform import python_implementation
41
+
42
+ import mmap as mm
43
+
44
+ import numpy as np
45
+ from numpy import frombuffer, dtype, empty, array, asarray
46
+ from numpy import little_endian as LITTLE_ENDIAN
47
+ from functools import reduce
48
+
49
+
50
+ IS_PYPY = python_implementation() == 'PyPy'
51
+
52
+ ABSENT = b'\x00\x00\x00\x00\x00\x00\x00\x00'
53
+ ZERO = b'\x00\x00\x00\x00'
54
+ NC_BYTE = b'\x00\x00\x00\x01'
55
+ NC_CHAR = b'\x00\x00\x00\x02'
56
+ NC_SHORT = b'\x00\x00\x00\x03'
57
+ NC_INT = b'\x00\x00\x00\x04'
58
+ NC_FLOAT = b'\x00\x00\x00\x05'
59
+ NC_DOUBLE = b'\x00\x00\x00\x06'
60
+ NC_DIMENSION = b'\x00\x00\x00\n'
61
+ NC_VARIABLE = b'\x00\x00\x00\x0b'
62
+ NC_ATTRIBUTE = b'\x00\x00\x00\x0c'
63
+ FILL_BYTE = b'\x81'
64
+ FILL_CHAR = b'\x00'
65
+ FILL_SHORT = b'\x80\x01'
66
+ FILL_INT = b'\x80\x00\x00\x01'
67
+ FILL_FLOAT = b'\x7C\xF0\x00\x00'
68
+ FILL_DOUBLE = b'\x47\x9E\x00\x00\x00\x00\x00\x00'
69
+
70
+ TYPEMAP = {NC_BYTE: ('b', 1),
71
+ NC_CHAR: ('c', 1),
72
+ NC_SHORT: ('h', 2),
73
+ NC_INT: ('i', 4),
74
+ NC_FLOAT: ('f', 4),
75
+ NC_DOUBLE: ('d', 8)}
76
+
77
+ FILLMAP = {NC_BYTE: FILL_BYTE,
78
+ NC_CHAR: FILL_CHAR,
79
+ NC_SHORT: FILL_SHORT,
80
+ NC_INT: FILL_INT,
81
+ NC_FLOAT: FILL_FLOAT,
82
+ NC_DOUBLE: FILL_DOUBLE}
83
+
84
+ REVERSE = {('b', 1): NC_BYTE,
85
+ ('B', 1): NC_CHAR,
86
+ ('c', 1): NC_CHAR,
87
+ ('h', 2): NC_SHORT,
88
+ ('i', 4): NC_INT,
89
+ ('f', 4): NC_FLOAT,
90
+ ('d', 8): NC_DOUBLE,
91
+
92
+ # these come from asarray(1).dtype.char and asarray('foo').dtype.char,
93
+ # used when getting the types from generic attributes.
94
+ ('l', 4): NC_INT,
95
+ ('S', 1): NC_CHAR}
96
+
97
+
98
+ class netcdf_file:
99
+ """
100
+ A file object for NetCDF data.
101
+
102
+ A `netcdf_file` object has two standard attributes: `dimensions` and
103
+ `variables`. The values of both are dictionaries, mapping dimension
104
+ names to their associated lengths and variable names to variables,
105
+ respectively. Application programs should never modify these
106
+ dictionaries.
107
+
108
+ All other attributes correspond to global attributes defined in the
109
+ NetCDF file. Global file attributes are created by assigning to an
110
+ attribute of the `netcdf_file` object.
111
+
112
+ Parameters
113
+ ----------
114
+ filename : string or file-like
115
+ string -> filename
116
+ mode : {'r', 'w', 'a'}, optional
117
+ read-write-append mode, default is 'r'
118
+ mmap : None or bool, optional
119
+ Whether to mmap `filename` when reading. Default is True
120
+ when `filename` is a file name, False when `filename` is a
121
+ file-like object. Note that when mmap is in use, data arrays
122
+ returned refer directly to the mmapped data on disk, and the
123
+ file cannot be closed as long as references to it exist.
124
+ version : {1, 2}, optional
125
+ version of netcdf to read / write, where 1 means *Classic
126
+ format* and 2 means *64-bit offset format*. Default is 1. See
127
+ `here <https://docs.unidata.ucar.edu/nug/current/netcdf_introduction.html#select_format>`__
128
+ for more info.
129
+ maskandscale : bool, optional
130
+ Whether to automatically scale and/or mask data based on attributes.
131
+ Default is False.
132
+
133
+ Notes
134
+ -----
135
+ The major advantage of this module over other modules is that it doesn't
136
+ require the code to be linked to the NetCDF libraries. This module is
137
+ derived from `pupynere <https://bitbucket.org/robertodealmeida/pupynere/>`_.
138
+
139
+ NetCDF files are a self-describing binary data format. The file contains
140
+ metadata that describes the dimensions and variables in the file. More
141
+ details about NetCDF files can be found `here
142
+ <https://www.unidata.ucar.edu/software/netcdf/guide_toc.html>`__. There
143
+ are three main sections to a NetCDF data structure:
144
+
145
+ 1. Dimensions
146
+ 2. Variables
147
+ 3. Attributes
148
+
149
+ The dimensions section records the name and length of each dimension used
150
+ by the variables. The variables would then indicate which dimensions it
151
+ uses and any attributes such as data units, along with containing the data
152
+ values for the variable. It is good practice to include a
153
+ variable that is the same name as a dimension to provide the values for
154
+ that axes. Lastly, the attributes section would contain additional
155
+ information such as the name of the file creator or the instrument used to
156
+ collect the data.
157
+
158
+ When writing data to a NetCDF file, there is often the need to indicate the
159
+ 'record dimension'. A record dimension is the unbounded dimension for a
160
+ variable. For example, a temperature variable may have dimensions of
161
+ latitude, longitude and time. If one wants to add more temperature data to
162
+ the NetCDF file as time progresses, then the temperature variable should
163
+ have the time dimension flagged as the record dimension.
164
+
165
+ In addition, the NetCDF file header contains the position of the data in
166
+ the file, so access can be done in an efficient manner without loading
167
+ unnecessary data into memory. It uses the ``mmap`` module to create
168
+ Numpy arrays mapped to the data on disk, for the same purpose.
169
+
170
+ Note that when `netcdf_file` is used to open a file with mmap=True
171
+ (default for read-only), arrays returned by it refer to data
172
+ directly on the disk. The file should not be closed, and cannot be cleanly
173
+ closed when asked, if such arrays are alive. You may want to copy data arrays
174
+ obtained from mmapped Netcdf file if they are to be processed after the file
175
+ is closed, see the example below.
176
+
177
+ Examples
178
+ --------
179
+ To create a NetCDF file:
180
+
181
+ >>> from scipy.io import netcdf_file
182
+ >>> import numpy as np
183
+ >>> f = netcdf_file('simple.nc', 'w')
184
+ >>> f.history = 'Created for a test'
185
+ >>> f.createDimension('time', 10)
186
+ >>> time = f.createVariable('time', 'i', ('time',))
187
+ >>> time[:] = np.arange(10)
188
+ >>> time.units = 'days since 2008-01-01'
189
+ >>> f.close()
190
+
191
+ Note the assignment of ``arange(10)`` to ``time[:]``. Exposing the slice
192
+ of the time variable allows for the data to be set in the object, rather
193
+ than letting ``arange(10)`` overwrite the ``time`` variable.
194
+
195
+ To read the NetCDF file we just created:
196
+
197
+ >>> from scipy.io import netcdf_file
198
+ >>> f = netcdf_file('simple.nc', 'r')
199
+ >>> print(f.history)
200
+ b'Created for a test'
201
+ >>> time = f.variables['time']
202
+ >>> print(time.units)
203
+ b'days since 2008-01-01'
204
+ >>> print(time.shape)
205
+ (10,)
206
+ >>> print(time[-1])
207
+ 9
208
+
209
+ NetCDF files, when opened read-only, return arrays that refer
210
+ directly to memory-mapped data on disk:
211
+
212
+ >>> data = time[:]
213
+
214
+ If the data is to be processed after the file is closed, it needs
215
+ to be copied to main memory:
216
+
217
+ >>> data = time[:].copy()
218
+ >>> del time
219
+ >>> f.close()
220
+ >>> data.mean()
221
+ 4.5
222
+
223
+ A NetCDF file can also be used as context manager:
224
+
225
+ >>> from scipy.io import netcdf_file
226
+ >>> with netcdf_file('simple.nc', 'r') as f:
227
+ ... print(f.history)
228
+ b'Created for a test'
229
+
230
+ """
231
+ def __init__(self, filename, mode='r', mmap=None, version=1,
232
+ maskandscale=False):
233
+ """Initialize netcdf_file from fileobj (str or file-like)."""
234
+ if mode not in 'rwa':
235
+ raise ValueError("Mode must be either 'r', 'w' or 'a'.")
236
+
237
+ if hasattr(filename, 'seek'): # file-like
238
+ self.fp = filename
239
+ self.filename = 'None'
240
+ if mmap is None:
241
+ mmap = False
242
+ elif mmap and not hasattr(filename, 'fileno'):
243
+ raise ValueError('Cannot use file object for mmap')
244
+ else: # maybe it's a string
245
+ self.filename = filename
246
+ omode = 'r+' if mode == 'a' else mode
247
+ self.fp = open(self.filename, '%sb' % omode)
248
+ if mmap is None:
249
+ # Mmapped files on PyPy cannot be usually closed
250
+ # before the GC runs, so it's better to use mmap=False
251
+ # as the default.
252
+ mmap = (not IS_PYPY)
253
+
254
+ if mode != 'r':
255
+ # Cannot read write-only files
256
+ mmap = False
257
+
258
+ self.use_mmap = mmap
259
+ self.mode = mode
260
+ self.version_byte = version
261
+ self.maskandscale = maskandscale
262
+
263
+ self.dimensions = {}
264
+ self.variables = {}
265
+
266
+ self._dims = []
267
+ self._recs = 0
268
+ self._recsize = 0
269
+
270
+ self._mm = None
271
+ self._mm_buf = None
272
+ if self.use_mmap:
273
+ self._mm = mm.mmap(self.fp.fileno(), 0, access=mm.ACCESS_READ)
274
+ self._mm_buf = np.frombuffer(self._mm, dtype=np.int8)
275
+
276
+ self._attributes = {}
277
+
278
+ if mode in 'ra':
279
+ self._read()
280
+
281
+ def __setattr__(self, attr, value):
282
+ # Store user defined attributes in a separate dict,
283
+ # so we can save them to file later.
284
+ try:
285
+ self._attributes[attr] = value
286
+ except AttributeError:
287
+ pass
288
+ self.__dict__[attr] = value
289
+
290
+ def close(self):
291
+ """Closes the NetCDF file."""
292
+ if hasattr(self, 'fp') and not self.fp.closed:
293
+ try:
294
+ self.flush()
295
+ finally:
296
+ self.variables = {}
297
+ if self._mm_buf is not None:
298
+ ref = weakref.ref(self._mm_buf)
299
+ self._mm_buf = None
300
+ if ref() is None:
301
+ # self._mm_buf is gc'd, and we can close the mmap
302
+ self._mm.close()
303
+ else:
304
+ # we cannot close self._mm, since self._mm_buf is
305
+ # alive and there may still be arrays referring to it
306
+ warnings.warn(
307
+ "Cannot close a netcdf_file opened with mmap=True, when "
308
+ "netcdf_variables or arrays referring to its data still "
309
+ "exist. All data arrays obtained from such files refer "
310
+ "directly to data on disk, and must be copied before the "
311
+ "file can be cleanly closed. "
312
+ "(See netcdf_file docstring for more information on mmap.)",
313
+ category=RuntimeWarning, stacklevel=2,
314
+ )
315
+ self._mm = None
316
+ self.fp.close()
317
+ __del__ = close
318
+
319
+ def __enter__(self):
320
+ return self
321
+
322
+ def __exit__(self, type, value, traceback):
323
+ self.close()
324
+
325
+ def createDimension(self, name, length):
326
+ """
327
+ Adds a dimension to the Dimension section of the NetCDF data structure.
328
+
329
+ Note that this function merely adds a new dimension that the variables can
330
+ reference. The values for the dimension, if desired, should be added as
331
+ a variable using `createVariable`, referring to this dimension.
332
+
333
+ Parameters
334
+ ----------
335
+ name : str
336
+ Name of the dimension (Eg, 'lat' or 'time').
337
+ length : int
338
+ Length of the dimension.
339
+
340
+ See Also
341
+ --------
342
+ createVariable
343
+
344
+ """
345
+ if length is None and self._dims:
346
+ raise ValueError("Only first dimension may be unlimited!")
347
+
348
+ self.dimensions[name] = length
349
+ self._dims.append(name)
350
+
351
+ def createVariable(self, name, type, dimensions):
352
+ """
353
+ Create an empty variable for the `netcdf_file` object, specifying its data
354
+ type and the dimensions it uses.
355
+
356
+ Parameters
357
+ ----------
358
+ name : str
359
+ Name of the new variable.
360
+ type : dtype or str
361
+ Data type of the variable.
362
+ dimensions : sequence of str
363
+ List of the dimension names used by the variable, in the desired order.
364
+
365
+ Returns
366
+ -------
367
+ variable : netcdf_variable
368
+ The newly created ``netcdf_variable`` object.
369
+ This object has also been added to the `netcdf_file` object as well.
370
+
371
+ See Also
372
+ --------
373
+ createDimension
374
+
375
+ Notes
376
+ -----
377
+ Any dimensions to be used by the variable should already exist in the
378
+ NetCDF data structure or should be created by `createDimension` prior to
379
+ creating the NetCDF variable.
380
+
381
+ """
382
+ shape = tuple([self.dimensions[dim] for dim in dimensions])
383
+ shape_ = tuple([dim or 0 for dim in shape]) # replace None with 0 for NumPy
384
+
385
+ type = dtype(type)
386
+ typecode, size = type.char, type.itemsize
387
+ if (typecode, size) not in REVERSE:
388
+ raise ValueError("NetCDF 3 does not support type %s" % type)
389
+
390
+ # convert to big endian always for NetCDF 3
391
+ data = empty(shape_, dtype=type.newbyteorder("B"))
392
+ self.variables[name] = netcdf_variable(
393
+ data, typecode, size, shape, dimensions,
394
+ maskandscale=self.maskandscale)
395
+ return self.variables[name]
396
+
397
+ def flush(self):
398
+ """
399
+ Perform a sync-to-disk flush if the `netcdf_file` object is in write mode.
400
+
401
+ See Also
402
+ --------
403
+ sync : Identical function
404
+
405
+ """
406
+ if hasattr(self, 'mode') and self.mode in 'wa':
407
+ self._write()
408
+ sync = flush
409
+
410
+ def _write(self):
411
+ self.fp.seek(0)
412
+ self.fp.write(b'CDF')
413
+ self.fp.write(array(self.version_byte, '>b').tobytes())
414
+
415
+ # Write headers and data.
416
+ self._write_numrecs()
417
+ self._write_dim_array()
418
+ self._write_gatt_array()
419
+ self._write_var_array()
420
+
421
+ def _write_numrecs(self):
422
+ # Get highest record count from all record variables.
423
+ for var in self.variables.values():
424
+ if var.isrec and len(var.data) > self._recs:
425
+ self.__dict__['_recs'] = len(var.data)
426
+ self._pack_int(self._recs)
427
+
428
+ def _write_dim_array(self):
429
+ if self.dimensions:
430
+ self.fp.write(NC_DIMENSION)
431
+ self._pack_int(len(self.dimensions))
432
+ for name in self._dims:
433
+ self._pack_string(name)
434
+ length = self.dimensions[name]
435
+ self._pack_int(length or 0) # replace None with 0 for record dimension
436
+ else:
437
+ self.fp.write(ABSENT)
438
+
439
+ def _write_gatt_array(self):
440
+ self._write_att_array(self._attributes)
441
+
442
+ def _write_att_array(self, attributes):
443
+ if attributes:
444
+ self.fp.write(NC_ATTRIBUTE)
445
+ self._pack_int(len(attributes))
446
+ for name, values in attributes.items():
447
+ self._pack_string(name)
448
+ self._write_att_values(values)
449
+ else:
450
+ self.fp.write(ABSENT)
451
+
452
+ def _write_var_array(self):
453
+ if self.variables:
454
+ self.fp.write(NC_VARIABLE)
455
+ self._pack_int(len(self.variables))
456
+
457
+ # Sort variable names non-recs first, then recs.
458
+ def sortkey(n):
459
+ v = self.variables[n]
460
+ if v.isrec:
461
+ return (-1,)
462
+ return v._shape
463
+ variables = sorted(self.variables, key=sortkey, reverse=True)
464
+
465
+ # Set the metadata for all variables.
466
+ for name in variables:
467
+ self._write_var_metadata(name)
468
+ # Now that we have the metadata, we know the vsize of
469
+ # each record variable, so we can calculate recsize.
470
+ self.__dict__['_recsize'] = sum([
471
+ var._vsize for var in self.variables.values()
472
+ if var.isrec])
473
+ # Set the data for all variables.
474
+ for name in variables:
475
+ self._write_var_data(name)
476
+ else:
477
+ self.fp.write(ABSENT)
478
+
479
+ def _write_var_metadata(self, name):
480
+ var = self.variables[name]
481
+
482
+ self._pack_string(name)
483
+ self._pack_int(len(var.dimensions))
484
+ for dimname in var.dimensions:
485
+ dimid = self._dims.index(dimname)
486
+ self._pack_int(dimid)
487
+
488
+ self._write_att_array(var._attributes)
489
+
490
+ nc_type = REVERSE[var.typecode(), var.itemsize()]
491
+ self.fp.write(nc_type)
492
+
493
+ if not var.isrec:
494
+ vsize = var.data.size * var.data.itemsize
495
+ vsize += -vsize % 4
496
+ else: # record variable
497
+ try:
498
+ vsize = var.data[0].size * var.data.itemsize
499
+ except IndexError:
500
+ vsize = 0
501
+ rec_vars = len([v for v in self.variables.values()
502
+ if v.isrec])
503
+ if rec_vars > 1:
504
+ vsize += -vsize % 4
505
+ self.variables[name].__dict__['_vsize'] = vsize
506
+ self._pack_int(vsize)
507
+
508
+ # Pack a bogus begin, and set the real value later.
509
+ self.variables[name].__dict__['_begin'] = self.fp.tell()
510
+ self._pack_begin(0)
511
+
512
+ def _write_var_data(self, name):
513
+ var = self.variables[name]
514
+
515
+ # Set begin in file header.
516
+ the_beguine = self.fp.tell()
517
+ self.fp.seek(var._begin)
518
+ self._pack_begin(the_beguine)
519
+ self.fp.seek(the_beguine)
520
+
521
+ # Write data.
522
+ if not var.isrec:
523
+ self.fp.write(var.data.tobytes())
524
+ count = var.data.size * var.data.itemsize
525
+ self._write_var_padding(var, var._vsize - count)
526
+ else: # record variable
527
+ # Handle rec vars with shape[0] < nrecs.
528
+ if self._recs > len(var.data):
529
+ shape = (self._recs,) + var.data.shape[1:]
530
+ # Resize in-place does not always work since
531
+ # the array might not be single-segment
532
+ try:
533
+ var.data.resize(shape)
534
+ except ValueError:
535
+ dtype = var.data.dtype
536
+ var.__dict__['data'] = np.resize(var.data, shape).astype(dtype)
537
+
538
+ pos0 = pos = self.fp.tell()
539
+ for rec in var.data:
540
+ # Apparently scalars cannot be converted to big endian. If we
541
+ # try to convert a ``=i4`` scalar to, say, '>i4' the dtype
542
+ # will remain as ``=i4``.
543
+ if not rec.shape and (rec.dtype.byteorder == '<' or
544
+ (rec.dtype.byteorder == '=' and LITTLE_ENDIAN)):
545
+ rec = rec.byteswap()
546
+ self.fp.write(rec.tobytes())
547
+ # Padding
548
+ count = rec.size * rec.itemsize
549
+ self._write_var_padding(var, var._vsize - count)
550
+ pos += self._recsize
551
+ self.fp.seek(pos)
552
+ self.fp.seek(pos0 + var._vsize)
553
+
554
+ def _write_var_padding(self, var, size):
555
+ encoded_fill_value = var._get_encoded_fill_value()
556
+ num_fills = size // len(encoded_fill_value)
557
+ self.fp.write(encoded_fill_value * num_fills)
558
+
559
+ def _write_att_values(self, values):
560
+ if hasattr(values, 'dtype'):
561
+ nc_type = REVERSE[values.dtype.char, values.dtype.itemsize]
562
+ else:
563
+ types = [(int, NC_INT), (float, NC_FLOAT), (str, NC_CHAR)]
564
+
565
+ # bytes index into scalars in py3k. Check for "string" types
566
+ if isinstance(values, (str, bytes)):
567
+ sample = values
568
+ else:
569
+ try:
570
+ sample = values[0] # subscriptable?
571
+ except TypeError:
572
+ sample = values # scalar
573
+
574
+ for class_, nc_type in types:
575
+ if isinstance(sample, class_):
576
+ break
577
+
578
+ typecode, size = TYPEMAP[nc_type]
579
+ dtype_ = '>%s' % typecode
580
+ # asarray() dies with bytes and '>c' in py3k. Change to 'S'
581
+ dtype_ = 'S' if dtype_ == '>c' else dtype_
582
+
583
+ values = asarray(values, dtype=dtype_)
584
+
585
+ self.fp.write(nc_type)
586
+
587
+ if values.dtype.char == 'S':
588
+ nelems = values.itemsize
589
+ else:
590
+ nelems = values.size
591
+ self._pack_int(nelems)
592
+
593
+ if not values.shape and (values.dtype.byteorder == '<' or
594
+ (values.dtype.byteorder == '=' and LITTLE_ENDIAN)):
595
+ values = values.byteswap()
596
+ self.fp.write(values.tobytes())
597
+ count = values.size * values.itemsize
598
+ self.fp.write(b'\x00' * (-count % 4)) # pad
599
+
600
+ def _read(self):
601
+ # Check magic bytes and version
602
+ magic = self.fp.read(3)
603
+ if not magic == b'CDF':
604
+ raise TypeError("Error: %s is not a valid NetCDF 3 file" %
605
+ self.filename)
606
+ self.__dict__['version_byte'] = frombuffer(self.fp.read(1), '>b')[0]
607
+
608
+ # Read file headers and set data.
609
+ self._read_numrecs()
610
+ self._read_dim_array()
611
+ self._read_gatt_array()
612
+ self._read_var_array()
613
+
614
+ def _read_numrecs(self):
615
+ self.__dict__['_recs'] = self._unpack_int()
616
+
617
+ def _read_dim_array(self):
618
+ header = self.fp.read(4)
619
+ if header not in [ZERO, NC_DIMENSION]:
620
+ raise ValueError("Unexpected header.")
621
+ count = self._unpack_int()
622
+
623
+ for dim in range(count):
624
+ name = self._unpack_string().decode('latin1')
625
+ length = self._unpack_int() or None # None for record dimension
626
+ self.dimensions[name] = length
627
+ self._dims.append(name) # preserve order
628
+
629
+ def _read_gatt_array(self):
630
+ for k, v in self._read_att_array().items():
631
+ self.__setattr__(k, v)
632
+
633
+ def _read_att_array(self):
634
+ header = self.fp.read(4)
635
+ if header not in [ZERO, NC_ATTRIBUTE]:
636
+ raise ValueError("Unexpected header.")
637
+ count = self._unpack_int()
638
+
639
+ attributes = {}
640
+ for attr in range(count):
641
+ name = self._unpack_string().decode('latin1')
642
+ attributes[name] = self._read_att_values()
643
+ return attributes
644
+
645
+ def _read_var_array(self):
646
+ header = self.fp.read(4)
647
+ if header not in [ZERO, NC_VARIABLE]:
648
+ raise ValueError("Unexpected header.")
649
+
650
+ begin = 0
651
+ dtypes = {'names': [], 'formats': []}
652
+ rec_vars = []
653
+ count = self._unpack_int()
654
+ for var in range(count):
655
+ (name, dimensions, shape, attributes,
656
+ typecode, size, dtype_, begin_, vsize) = self._read_var()
657
+ # https://www.unidata.ucar.edu/software/netcdf/guide_toc.html
658
+ # Note that vsize is the product of the dimension lengths
659
+ # (omitting the record dimension) and the number of bytes
660
+ # per value (determined from the type), increased to the
661
+ # next multiple of 4, for each variable. If a record
662
+ # variable, this is the amount of space per record. The
663
+ # netCDF "record size" is calculated as the sum of the
664
+ # vsize's of all the record variables.
665
+ #
666
+ # The vsize field is actually redundant, because its value
667
+ # may be computed from other information in the header. The
668
+ # 32-bit vsize field is not large enough to contain the size
669
+ # of variables that require more than 2^32 - 4 bytes, so
670
+ # 2^32 - 1 is used in the vsize field for such variables.
671
+ if shape and shape[0] is None: # record variable
672
+ rec_vars.append(name)
673
+ # The netCDF "record size" is calculated as the sum of
674
+ # the vsize's of all the record variables.
675
+ self.__dict__['_recsize'] += vsize
676
+ if begin == 0:
677
+ begin = begin_
678
+ dtypes['names'].append(name)
679
+ dtypes['formats'].append(str(shape[1:]) + dtype_)
680
+
681
+ # Handle padding with a virtual variable.
682
+ if typecode in 'bch':
683
+ actual_size = reduce(mul, (1,) + shape[1:]) * size
684
+ padding = -actual_size % 4
685
+ if padding:
686
+ dtypes['names'].append('_padding_%d' % var)
687
+ dtypes['formats'].append('(%d,)>b' % padding)
688
+
689
+ # Data will be set later.
690
+ data = None
691
+ else: # not a record variable
692
+ # Calculate size to avoid problems with vsize (above)
693
+ a_size = reduce(mul, shape, 1) * size
694
+ if self.use_mmap:
695
+ data = self._mm_buf[begin_:begin_+a_size].view(dtype=dtype_)
696
+ data.shape = shape
697
+ else:
698
+ pos = self.fp.tell()
699
+ self.fp.seek(begin_)
700
+ data = frombuffer(self.fp.read(a_size), dtype=dtype_
701
+ ).copy()
702
+ data.shape = shape
703
+ self.fp.seek(pos)
704
+
705
+ # Add variable.
706
+ self.variables[name] = netcdf_variable(
707
+ data, typecode, size, shape, dimensions, attributes,
708
+ maskandscale=self.maskandscale)
709
+
710
+ if rec_vars:
711
+ # Remove padding when only one record variable.
712
+ if len(rec_vars) == 1:
713
+ dtypes['names'] = dtypes['names'][:1]
714
+ dtypes['formats'] = dtypes['formats'][:1]
715
+
716
+ # Build rec array.
717
+ if self.use_mmap:
718
+ buf = self._mm_buf[begin:begin+self._recs*self._recsize]
719
+ rec_array = buf.view(dtype=dtypes)
720
+ rec_array.shape = (self._recs,)
721
+ else:
722
+ pos = self.fp.tell()
723
+ self.fp.seek(begin)
724
+ rec_array = frombuffer(self.fp.read(self._recs*self._recsize),
725
+ dtype=dtypes).copy()
726
+ rec_array.shape = (self._recs,)
727
+ self.fp.seek(pos)
728
+
729
+ for var in rec_vars:
730
+ self.variables[var].__dict__['data'] = rec_array[var]
731
+
732
+ def _read_var(self):
733
+ name = self._unpack_string().decode('latin1')
734
+ dimensions = []
735
+ shape = []
736
+ dims = self._unpack_int()
737
+
738
+ for i in range(dims):
739
+ dimid = self._unpack_int()
740
+ dimname = self._dims[dimid]
741
+ dimensions.append(dimname)
742
+ dim = self.dimensions[dimname]
743
+ shape.append(dim)
744
+ dimensions = tuple(dimensions)
745
+ shape = tuple(shape)
746
+
747
+ attributes = self._read_att_array()
748
+ nc_type = self.fp.read(4)
749
+ vsize = self._unpack_int()
750
+ begin = [self._unpack_int, self._unpack_int64][self.version_byte-1]()
751
+
752
+ typecode, size = TYPEMAP[nc_type]
753
+ dtype_ = '>%s' % typecode
754
+
755
+ return name, dimensions, shape, attributes, typecode, size, dtype_, begin, vsize
756
+
757
+ def _read_att_values(self):
758
+ nc_type = self.fp.read(4)
759
+ n = self._unpack_int()
760
+
761
+ typecode, size = TYPEMAP[nc_type]
762
+
763
+ count = n*size
764
+ values = self.fp.read(int(count))
765
+ self.fp.read(-count % 4) # read padding
766
+
767
+ if typecode != 'c':
768
+ values = frombuffer(values, dtype='>%s' % typecode).copy()
769
+ if values.shape == (1,):
770
+ values = values[0]
771
+ else:
772
+ values = values.rstrip(b'\x00')
773
+ return values
774
+
775
+ def _pack_begin(self, begin):
776
+ if self.version_byte == 1:
777
+ self._pack_int(begin)
778
+ elif self.version_byte == 2:
779
+ self._pack_int64(begin)
780
+
781
+ def _pack_int(self, value):
782
+ self.fp.write(array(value, '>i').tobytes())
783
+ _pack_int32 = _pack_int
784
+
785
+ def _unpack_int(self):
786
+ return int(frombuffer(self.fp.read(4), '>i')[0])
787
+ _unpack_int32 = _unpack_int
788
+
789
+ def _pack_int64(self, value):
790
+ self.fp.write(array(value, '>q').tobytes())
791
+
792
+ def _unpack_int64(self):
793
+ return frombuffer(self.fp.read(8), '>q')[0]
794
+
795
+ def _pack_string(self, s):
796
+ count = len(s)
797
+ self._pack_int(count)
798
+ self.fp.write(s.encode('latin1'))
799
+ self.fp.write(b'\x00' * (-count % 4)) # pad
800
+
801
+ def _unpack_string(self):
802
+ count = self._unpack_int()
803
+ s = self.fp.read(count).rstrip(b'\x00')
804
+ self.fp.read(-count % 4) # read padding
805
+ return s
806
+
807
+
808
+ class netcdf_variable:
809
+ """
810
+ A data object for netcdf files.
811
+
812
+ `netcdf_variable` objects are constructed by calling the method
813
+ `netcdf_file.createVariable` on the `netcdf_file` object. `netcdf_variable`
814
+ objects behave much like array objects defined in numpy, except that their
815
+ data resides in a file. Data is read by indexing and written by assigning
816
+ to an indexed subset; the entire array can be accessed by the index ``[:]``
817
+ or (for scalars) by using the methods `getValue` and `assignValue`.
818
+ `netcdf_variable` objects also have attribute `shape` with the same meaning
819
+ as for arrays, but the shape cannot be modified. There is another read-only
820
+ attribute `dimensions`, whose value is the tuple of dimension names.
821
+
822
+ All other attributes correspond to variable attributes defined in
823
+ the NetCDF file. Variable attributes are created by assigning to an
824
+ attribute of the `netcdf_variable` object.
825
+
826
+ Parameters
827
+ ----------
828
+ data : array_like
829
+ The data array that holds the values for the variable.
830
+ Typically, this is initialized as empty, but with the proper shape.
831
+ typecode : dtype character code
832
+ Desired data-type for the data array.
833
+ size : int
834
+ Desired element size for the data array.
835
+ shape : sequence of ints
836
+ The shape of the array. This should match the lengths of the
837
+ variable's dimensions.
838
+ dimensions : sequence of strings
839
+ The names of the dimensions used by the variable. Must be in the
840
+ same order of the dimension lengths given by `shape`.
841
+ attributes : dict, optional
842
+ Attribute values (any type) keyed by string names. These attributes
843
+ become attributes for the netcdf_variable object.
844
+ maskandscale : bool, optional
845
+ Whether to automatically scale and/or mask data based on attributes.
846
+ Default is False.
847
+
848
+
849
+ Attributes
850
+ ----------
851
+ dimensions : list of str
852
+ List of names of dimensions used by the variable object.
853
+ isrec, shape
854
+ Properties
855
+
856
+ See also
857
+ --------
858
+ isrec, shape
859
+
860
+ """
861
+ def __init__(self, data, typecode, size, shape, dimensions,
862
+ attributes=None,
863
+ maskandscale=False):
864
+ self.data = data
865
+ self._typecode = typecode
866
+ self._size = size
867
+ self._shape = shape
868
+ self.dimensions = dimensions
869
+ self.maskandscale = maskandscale
870
+
871
+ self._attributes = attributes or {}
872
+ for k, v in self._attributes.items():
873
+ self.__dict__[k] = v
874
+
875
+ def __setattr__(self, attr, value):
876
+ # Store user defined attributes in a separate dict,
877
+ # so we can save them to file later.
878
+ try:
879
+ self._attributes[attr] = value
880
+ except AttributeError:
881
+ pass
882
+ self.__dict__[attr] = value
883
+
884
+ def isrec(self):
885
+ """Returns whether the variable has a record dimension or not.
886
+
887
+ A record dimension is a dimension along which additional data could be
888
+ easily appended in the netcdf data structure without much rewriting of
889
+ the data file. This attribute is a read-only property of the
890
+ `netcdf_variable`.
891
+
892
+ """
893
+ return bool(self.data.shape) and not self._shape[0]
894
+ isrec = property(isrec)
895
+
896
+ def shape(self):
897
+ """Returns the shape tuple of the data variable.
898
+
899
+ This is a read-only attribute and can not be modified in the
900
+ same manner of other numpy arrays.
901
+ """
902
+ return self.data.shape
903
+ shape = property(shape)
904
+
905
+ def getValue(self):
906
+ """
907
+ Retrieve a scalar value from a `netcdf_variable` of length one.
908
+
909
+ Raises
910
+ ------
911
+ ValueError
912
+ If the netcdf variable is an array of length greater than one,
913
+ this exception will be raised.
914
+
915
+ """
916
+ return self.data.item()
917
+
918
+ def assignValue(self, value):
919
+ """
920
+ Assign a scalar value to a `netcdf_variable` of length one.
921
+
922
+ Parameters
923
+ ----------
924
+ value : scalar
925
+ Scalar value (of compatible type) to assign to a length-one netcdf
926
+ variable. This value will be written to file.
927
+
928
+ Raises
929
+ ------
930
+ ValueError
931
+ If the input is not a scalar, or if the destination is not a length-one
932
+ netcdf variable.
933
+
934
+ """
935
+ if not self.data.flags.writeable:
936
+ # Work-around for a bug in NumPy. Calling itemset() on a read-only
937
+ # memory-mapped array causes a seg. fault.
938
+ # See NumPy ticket #1622, and SciPy ticket #1202.
939
+ # This check for `writeable` can be removed when the oldest version
940
+ # of NumPy still supported by scipy contains the fix for #1622.
941
+ raise RuntimeError("variable is not writeable")
942
+
943
+ self.data[:] = value
944
+
945
+ def typecode(self):
946
+ """
947
+ Return the typecode of the variable.
948
+
949
+ Returns
950
+ -------
951
+ typecode : char
952
+ The character typecode of the variable (e.g., 'i' for int).
953
+
954
+ """
955
+ return self._typecode
956
+
957
+ def itemsize(self):
958
+ """
959
+ Return the itemsize of the variable.
960
+
961
+ Returns
962
+ -------
963
+ itemsize : int
964
+ The element size of the variable (e.g., 8 for float64).
965
+
966
+ """
967
+ return self._size
968
+
969
+ def __getitem__(self, index):
970
+ if not self.maskandscale:
971
+ return self.data[index]
972
+
973
+ data = self.data[index].copy()
974
+ missing_value = self._get_missing_value()
975
+ data = self._apply_missing_value(data, missing_value)
976
+ scale_factor = self._attributes.get('scale_factor')
977
+ add_offset = self._attributes.get('add_offset')
978
+ if add_offset is not None or scale_factor is not None:
979
+ data = data.astype(np.float64)
980
+ if scale_factor is not None:
981
+ data = data * scale_factor
982
+ if add_offset is not None:
983
+ data += add_offset
984
+
985
+ return data
986
+
987
+ def __setitem__(self, index, data):
988
+ if self.maskandscale:
989
+ missing_value = (
990
+ self._get_missing_value() or
991
+ getattr(data, 'fill_value', 999999))
992
+ self._attributes.setdefault('missing_value', missing_value)
993
+ self._attributes.setdefault('_FillValue', missing_value)
994
+ data = ((data - self._attributes.get('add_offset', 0.0)) /
995
+ self._attributes.get('scale_factor', 1.0))
996
+ data = np.ma.asarray(data).filled(missing_value)
997
+ if self._typecode not in 'fd' and data.dtype.kind == 'f':
998
+ data = np.round(data)
999
+
1000
+ # Expand data for record vars?
1001
+ if self.isrec:
1002
+ if isinstance(index, tuple):
1003
+ rec_index = index[0]
1004
+ else:
1005
+ rec_index = index
1006
+ if isinstance(rec_index, slice):
1007
+ recs = (rec_index.start or 0) + len(data)
1008
+ else:
1009
+ recs = rec_index + 1
1010
+ if recs > len(self.data):
1011
+ shape = (recs,) + self._shape[1:]
1012
+ # Resize in-place does not always work since
1013
+ # the array might not be single-segment
1014
+ try:
1015
+ self.data.resize(shape)
1016
+ except ValueError:
1017
+ dtype = self.data.dtype
1018
+ self.__dict__['data'] = np.resize(self.data, shape).astype(dtype)
1019
+ self.data[index] = data
1020
+
1021
+ def _default_encoded_fill_value(self):
1022
+ """
1023
+ The default encoded fill-value for this Variable's data type.
1024
+ """
1025
+ nc_type = REVERSE[self.typecode(), self.itemsize()]
1026
+ return FILLMAP[nc_type]
1027
+
1028
+ def _get_encoded_fill_value(self):
1029
+ """
1030
+ Returns the encoded fill value for this variable as bytes.
1031
+
1032
+ This is taken from either the _FillValue attribute, or the default fill
1033
+ value for this variable's data type.
1034
+ """
1035
+ if '_FillValue' in self._attributes:
1036
+ fill_value = np.array(self._attributes['_FillValue'],
1037
+ dtype=self.data.dtype).tobytes()
1038
+ if len(fill_value) == self.itemsize():
1039
+ return fill_value
1040
+ else:
1041
+ return self._default_encoded_fill_value()
1042
+ else:
1043
+ return self._default_encoded_fill_value()
1044
+
1045
+ def _get_missing_value(self):
1046
+ """
1047
+ Returns the value denoting "no data" for this variable.
1048
+
1049
+ If this variable does not have a missing/fill value, returns None.
1050
+
1051
+ If both _FillValue and missing_value are given, give precedence to
1052
+ _FillValue. The netCDF standard gives special meaning to _FillValue;
1053
+ missing_value is just used for compatibility with old datasets.
1054
+ """
1055
+
1056
+ if '_FillValue' in self._attributes:
1057
+ missing_value = self._attributes['_FillValue']
1058
+ elif 'missing_value' in self._attributes:
1059
+ missing_value = self._attributes['missing_value']
1060
+ else:
1061
+ missing_value = None
1062
+
1063
+ return missing_value
1064
+
1065
+ @staticmethod
1066
+ def _apply_missing_value(data, missing_value):
1067
+ """
1068
+ Applies the given missing value to the data array.
1069
+
1070
+ Returns a numpy.ma array, with any value equal to missing_value masked
1071
+ out (unless missing_value is None, in which case the original array is
1072
+ returned).
1073
+ """
1074
+
1075
+ if missing_value is None:
1076
+ newdata = data
1077
+ else:
1078
+ try:
1079
+ missing_value_isnan = np.isnan(missing_value)
1080
+ except (TypeError, NotImplementedError):
1081
+ # some data types (e.g., characters) cannot be tested for NaN
1082
+ missing_value_isnan = False
1083
+
1084
+ if missing_value_isnan:
1085
+ mymask = np.isnan(data)
1086
+ else:
1087
+ mymask = (data == missing_value)
1088
+
1089
+ newdata = np.ma.masked_where(mymask, data)
1090
+
1091
+ return newdata
1092
+
1093
+
1094
+ NetCDFFile = netcdf_file
1095
+ NetCDFVariable = netcdf_variable
parrot/lib/python3.10/site-packages/scipy/io/harwell_boeing.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.io` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+ __all__ = ["hb_read", "hb_write"] # noqa: F822
8
+
9
+
10
+ def __dir__():
11
+ return __all__
12
+
13
+
14
+ def __getattr__(name):
15
+ return _sub_module_deprecation(sub_package="io", module="harwell_boeing",
16
+ private_modules=["_harwell_boeing"], all=__all__,
17
+ attribute=name)
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (18.7 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_axis_nan_policy.cpython-310.pyc ADDED
Binary file (21.1 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_binomtest.cpython-310.pyc ADDED
Binary file (11.4 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_bws_test.cpython-310.pyc ADDED
Binary file (6.69 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_censored_data.cpython-310.pyc ADDED
Binary file (17.2 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_common.cpython-310.pyc ADDED
Binary file (310 Bytes). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_constants.cpython-310.pyc ADDED
Binary file (515 Bytes). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_covariance.cpython-310.pyc ADDED
Binary file (23.2 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_crosstab.cpython-310.pyc ADDED
Binary file (7.32 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_discrete_distns.cpython-310.pyc ADDED
Binary file (62.6 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_fit.cpython-310.pyc ADDED
Binary file (52.4 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_hypotests.cpython-310.pyc ADDED
Binary file (69.4 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_kde.cpython-310.pyc ADDED
Binary file (21.8 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_mannwhitneyu.cpython-310.pyc ADDED
Binary file (16.8 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_mgc.cpython-310.pyc ADDED
Binary file (18.3 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_mstats_extras.cpython-310.pyc ADDED
Binary file (15.4 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_odds_ratio.cpython-310.pyc ADDED
Binary file (15.8 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_page_trend_test.cpython-310.pyc ADDED
Binary file (17.7 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_qmc.cpython-310.pyc ADDED
Binary file (88.9 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_qmvnt.cpython-310.pyc ADDED
Binary file (13.5 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_relative_risk.cpython-310.pyc ADDED
Binary file (8.31 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_resampling.cpython-310.pyc ADDED
Binary file (85.8 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_rvs_sampling.cpython-310.pyc ADDED
Binary file (2.37 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_sensitivity_analysis.cpython-310.pyc ADDED
Binary file (23.7 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_stats_mstats_common.cpython-310.pyc ADDED
Binary file (10.7 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_survival.cpython-310.pyc ADDED
Binary file (22.8 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_tukeylambda_stats.cpython-310.pyc ADDED
Binary file (3.09 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_variation.cpython-310.pyc ADDED
Binary file (4.59 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_warnings_errors.cpython-310.pyc ADDED
Binary file (1.71 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/_wilcoxon.cpython-310.pyc ADDED
Binary file (7.05 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/biasedurn.cpython-310.pyc ADDED
Binary file (624 Bytes). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/contingency.cpython-310.pyc ADDED
Binary file (15.1 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/distributions.cpython-310.pyc ADDED
Binary file (569 Bytes). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/morestats.cpython-310.pyc ADDED
Binary file (947 Bytes). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/mstats.cpython-310.pyc ADDED
Binary file (2.44 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/mstats_extras.cpython-310.pyc ADDED
Binary file (752 Bytes). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/mvn.cpython-310.pyc ADDED
Binary file (606 Bytes). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/qmc.cpython-310.pyc ADDED
Binary file (11.9 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/sampling.cpython-310.pyc ADDED
Binary file (1.96 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/__pycache__/stats.cpython-310.pyc ADDED
Binary file (1.35 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/_levy_stable/__init__.py ADDED
@@ -0,0 +1,1224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #
2
+
3
+ import warnings
4
+ from functools import partial
5
+
6
+ import numpy as np
7
+
8
+ from scipy import optimize
9
+ from scipy import integrate
10
+ from scipy.integrate._quadrature import _builtincoeffs
11
+ from scipy import interpolate
12
+ from scipy.interpolate import RectBivariateSpline
13
+ import scipy.special as sc
14
+ from scipy._lib._util import _lazywhere
15
+ from .._distn_infrastructure import rv_continuous, _ShapeInfo
16
+ from .._continuous_distns import uniform, expon, _norm_pdf, _norm_cdf
17
+ from .levyst import Nolan
18
+ from scipy._lib.doccer import inherit_docstring_from
19
+
20
+
21
+ __all__ = ["levy_stable", "levy_stable_gen", "pdf_from_cf_with_fft"]
22
+
23
+ # Stable distributions are known for various parameterisations
24
+ # some being advantageous for numerical considerations and others
25
+ # useful due to their location/scale awareness.
26
+ #
27
+ # Here we follow [NO] convention (see the references in the docstring
28
+ # for levy_stable_gen below).
29
+ #
30
+ # S0 / Z0 / x0 (aka Zoleterav's M)
31
+ # S1 / Z1 / x1
32
+ #
33
+ # Where S* denotes parameterisation, Z* denotes standardized
34
+ # version where gamma = 1, delta = 0 and x* denotes variable.
35
+ #
36
+ # Scipy's original Stable was a random variate generator. It
37
+ # uses S1 and unfortunately is not a location/scale aware.
38
+
39
+
40
+ # default numerical integration tolerance
41
+ # used for epsrel in piecewise and both epsrel and epsabs in dni
42
+ # (epsabs needed in dni since weighted quad requires epsabs > 0)
43
+ _QUAD_EPS = 1.2e-14
44
+
45
+
46
+ def _Phi_Z0(alpha, t):
47
+ return (
48
+ -np.tan(np.pi * alpha / 2) * (np.abs(t) ** (1 - alpha) - 1)
49
+ if alpha != 1
50
+ else -2.0 * np.log(np.abs(t)) / np.pi
51
+ )
52
+
53
+
54
+ def _Phi_Z1(alpha, t):
55
+ return (
56
+ np.tan(np.pi * alpha / 2)
57
+ if alpha != 1
58
+ else -2.0 * np.log(np.abs(t)) / np.pi
59
+ )
60
+
61
+
62
+ def _cf(Phi, t, alpha, beta):
63
+ """Characteristic function."""
64
+ return np.exp(
65
+ -(np.abs(t) ** alpha) * (1 - 1j * beta * np.sign(t) * Phi(alpha, t))
66
+ )
67
+
68
+
69
+ _cf_Z0 = partial(_cf, _Phi_Z0)
70
+ _cf_Z1 = partial(_cf, _Phi_Z1)
71
+
72
+
73
+ def _pdf_single_value_cf_integrate(Phi, x, alpha, beta, **kwds):
74
+ """To improve DNI accuracy convert characteristic function in to real
75
+ valued integral using Euler's formula, then exploit cosine symmetry to
76
+ change limits to [0, inf). Finally use cosine addition formula to split
77
+ into two parts that can be handled by weighted quad pack.
78
+ """
79
+ quad_eps = kwds.get("quad_eps", _QUAD_EPS)
80
+
81
+ def integrand1(t):
82
+ if t == 0:
83
+ return 0
84
+ return np.exp(-(t ** alpha)) * (
85
+ np.cos(beta * (t ** alpha) * Phi(alpha, t))
86
+ )
87
+
88
+ def integrand2(t):
89
+ if t == 0:
90
+ return 0
91
+ return np.exp(-(t ** alpha)) * (
92
+ np.sin(beta * (t ** alpha) * Phi(alpha, t))
93
+ )
94
+
95
+ with np.errstate(invalid="ignore"):
96
+ int1, *ret1 = integrate.quad(
97
+ integrand1,
98
+ 0,
99
+ np.inf,
100
+ weight="cos",
101
+ wvar=x,
102
+ limit=1000,
103
+ epsabs=quad_eps,
104
+ epsrel=quad_eps,
105
+ full_output=1,
106
+ )
107
+
108
+ int2, *ret2 = integrate.quad(
109
+ integrand2,
110
+ 0,
111
+ np.inf,
112
+ weight="sin",
113
+ wvar=x,
114
+ limit=1000,
115
+ epsabs=quad_eps,
116
+ epsrel=quad_eps,
117
+ full_output=1,
118
+ )
119
+
120
+ return (int1 + int2) / np.pi
121
+
122
+
123
+ _pdf_single_value_cf_integrate_Z0 = partial(
124
+ _pdf_single_value_cf_integrate, _Phi_Z0
125
+ )
126
+ _pdf_single_value_cf_integrate_Z1 = partial(
127
+ _pdf_single_value_cf_integrate, _Phi_Z1
128
+ )
129
+
130
+
131
+ def _nolan_round_x_near_zeta(x0, alpha, zeta, x_tol_near_zeta):
132
+ """Round x close to zeta for Nolan's method in [NO]."""
133
+ # "8. When |x0-beta*tan(pi*alpha/2)| is small, the
134
+ # computations of the density and cumulative have numerical problems.
135
+ # The program works around this by setting
136
+ # z = beta*tan(pi*alpha/2) when
137
+ # |z-beta*tan(pi*alpha/2)| < tol(5)*alpha**(1/alpha).
138
+ # (The bound on the right is ad hoc, to get reasonable behavior
139
+ # when alpha is small)."
140
+ # where tol(5) = 0.5e-2 by default.
141
+ #
142
+ # We seem to have partially addressed this through re-expression of
143
+ # g(theta) here, but it still needs to be used in some extreme cases.
144
+ # Perhaps tol(5) = 0.5e-2 could be reduced for our implementation.
145
+ if np.abs(x0 - zeta) < x_tol_near_zeta * alpha ** (1 / alpha):
146
+ x0 = zeta
147
+ return x0
148
+
149
+
150
+ def _nolan_round_difficult_input(
151
+ x0, alpha, beta, zeta, x_tol_near_zeta, alpha_tol_near_one
152
+ ):
153
+ """Round difficult input values for Nolan's method in [NO]."""
154
+
155
+ # following Nolan's STABLE,
156
+ # "1. When 0 < |alpha-1| < 0.005, the program has numerical problems
157
+ # evaluating the pdf and cdf. The current version of the program sets
158
+ # alpha=1 in these cases. This approximation is not bad in the S0
159
+ # parameterization."
160
+ if np.abs(alpha - 1) < alpha_tol_near_one:
161
+ alpha = 1.0
162
+
163
+ # "2. When alpha=1 and |beta| < 0.005, the program has numerical
164
+ # problems. The current version sets beta=0."
165
+ # We seem to have addressed this through re-expression of g(theta) here
166
+
167
+ x0 = _nolan_round_x_near_zeta(x0, alpha, zeta, x_tol_near_zeta)
168
+ return x0, alpha, beta
169
+
170
+
171
+ def _pdf_single_value_piecewise_Z1(x, alpha, beta, **kwds):
172
+ # convert from Nolan's S_1 (aka S) to S_0 (aka Zolaterev M)
173
+ # parameterization
174
+
175
+ zeta = -beta * np.tan(np.pi * alpha / 2.0)
176
+ x0 = x + zeta if alpha != 1 else x
177
+
178
+ return _pdf_single_value_piecewise_Z0(x0, alpha, beta, **kwds)
179
+
180
+
181
+ def _pdf_single_value_piecewise_Z0(x0, alpha, beta, **kwds):
182
+
183
+ quad_eps = kwds.get("quad_eps", _QUAD_EPS)
184
+ x_tol_near_zeta = kwds.get("piecewise_x_tol_near_zeta", 0.005)
185
+ alpha_tol_near_one = kwds.get("piecewise_alpha_tol_near_one", 0.005)
186
+
187
+ zeta = -beta * np.tan(np.pi * alpha / 2.0)
188
+ x0, alpha, beta = _nolan_round_difficult_input(
189
+ x0, alpha, beta, zeta, x_tol_near_zeta, alpha_tol_near_one
190
+ )
191
+
192
+ # some other known distribution pdfs / analytical cases
193
+ # TODO: add more where possible with test coverage,
194
+ # eg https://en.wikipedia.org/wiki/Stable_distribution#Other_analytic_cases
195
+ if alpha == 2.0:
196
+ # normal
197
+ return _norm_pdf(x0 / np.sqrt(2)) / np.sqrt(2)
198
+ elif alpha == 0.5 and beta == 1.0:
199
+ # levy
200
+ # since S(1/2, 1, gamma, delta; <x>) ==
201
+ # S(1/2, 1, gamma, gamma + delta; <x0>).
202
+ _x = x0 + 1
203
+ if _x <= 0:
204
+ return 0
205
+
206
+ return 1 / np.sqrt(2 * np.pi * _x) / _x * np.exp(-1 / (2 * _x))
207
+ elif alpha == 0.5 and beta == 0.0 and x0 != 0:
208
+ # analytical solution [HO]
209
+ S, C = sc.fresnel([1 / np.sqrt(2 * np.pi * np.abs(x0))])
210
+ arg = 1 / (4 * np.abs(x0))
211
+ return (
212
+ np.sin(arg) * (0.5 - S[0]) + np.cos(arg) * (0.5 - C[0])
213
+ ) / np.sqrt(2 * np.pi * np.abs(x0) ** 3)
214
+ elif alpha == 1.0 and beta == 0.0:
215
+ # cauchy
216
+ return 1 / (1 + x0 ** 2) / np.pi
217
+
218
+ return _pdf_single_value_piecewise_post_rounding_Z0(
219
+ x0, alpha, beta, quad_eps, x_tol_near_zeta
220
+ )
221
+
222
+
223
+ def _pdf_single_value_piecewise_post_rounding_Z0(x0, alpha, beta, quad_eps,
224
+ x_tol_near_zeta):
225
+ """Calculate pdf using Nolan's methods as detailed in [NO]."""
226
+
227
+ _nolan = Nolan(alpha, beta, x0)
228
+ zeta = _nolan.zeta
229
+ xi = _nolan.xi
230
+ c2 = _nolan.c2
231
+ g = _nolan.g
232
+
233
+ # round x0 to zeta again if needed. zeta was recomputed and may have
234
+ # changed due to floating point differences.
235
+ # See https://github.com/scipy/scipy/pull/18133
236
+ x0 = _nolan_round_x_near_zeta(x0, alpha, zeta, x_tol_near_zeta)
237
+ # handle Nolan's initial case logic
238
+ if x0 == zeta:
239
+ return (
240
+ sc.gamma(1 + 1 / alpha)
241
+ * np.cos(xi)
242
+ / np.pi
243
+ / ((1 + zeta ** 2) ** (1 / alpha / 2))
244
+ )
245
+ elif x0 < zeta:
246
+ return _pdf_single_value_piecewise_post_rounding_Z0(
247
+ -x0, alpha, -beta, quad_eps, x_tol_near_zeta
248
+ )
249
+
250
+ # following Nolan, we may now assume
251
+ # x0 > zeta when alpha != 1
252
+ # beta != 0 when alpha == 1
253
+
254
+ # spare calculating integral on null set
255
+ # use isclose as macos has fp differences
256
+ if np.isclose(-xi, np.pi / 2, rtol=1e-014, atol=1e-014):
257
+ return 0.0
258
+
259
+ def integrand(theta):
260
+ # limit any numerical issues leading to g_1 < 0 near theta limits
261
+ g_1 = g(theta)
262
+ if not np.isfinite(g_1) or g_1 < 0:
263
+ g_1 = 0
264
+ return g_1 * np.exp(-g_1)
265
+
266
+ with np.errstate(all="ignore"):
267
+ peak = optimize.bisect(
268
+ lambda t: g(t) - 1, -xi, np.pi / 2, xtol=quad_eps
269
+ )
270
+
271
+ # this integrand can be very peaked, so we need to force
272
+ # QUADPACK to evaluate the function inside its support
273
+ #
274
+
275
+ # lastly, we add additional samples at
276
+ # ~exp(-100), ~exp(-10), ~exp(-5), ~exp(-1)
277
+ # to improve QUADPACK's detection of rapidly descending tail behavior
278
+ # (this choice is fairly ad hoc)
279
+ tail_points = [
280
+ optimize.bisect(lambda t: g(t) - exp_height, -xi, np.pi / 2)
281
+ for exp_height in [100, 10, 5]
282
+ # exp_height = 1 is handled by peak
283
+ ]
284
+ intg_points = [0, peak] + tail_points
285
+ intg, *ret = integrate.quad(
286
+ integrand,
287
+ -xi,
288
+ np.pi / 2,
289
+ points=intg_points,
290
+ limit=100,
291
+ epsrel=quad_eps,
292
+ epsabs=0,
293
+ full_output=1,
294
+ )
295
+
296
+ return c2 * intg
297
+
298
+
299
+ def _cdf_single_value_piecewise_Z1(x, alpha, beta, **kwds):
300
+ # convert from Nolan's S_1 (aka S) to S_0 (aka Zolaterev M)
301
+ # parameterization
302
+
303
+ zeta = -beta * np.tan(np.pi * alpha / 2.0)
304
+ x0 = x + zeta if alpha != 1 else x
305
+
306
+ return _cdf_single_value_piecewise_Z0(x0, alpha, beta, **kwds)
307
+
308
+
309
+ def _cdf_single_value_piecewise_Z0(x0, alpha, beta, **kwds):
310
+
311
+ quad_eps = kwds.get("quad_eps", _QUAD_EPS)
312
+ x_tol_near_zeta = kwds.get("piecewise_x_tol_near_zeta", 0.005)
313
+ alpha_tol_near_one = kwds.get("piecewise_alpha_tol_near_one", 0.005)
314
+
315
+ zeta = -beta * np.tan(np.pi * alpha / 2.0)
316
+ x0, alpha, beta = _nolan_round_difficult_input(
317
+ x0, alpha, beta, zeta, x_tol_near_zeta, alpha_tol_near_one
318
+ )
319
+
320
+ # some other known distribution cdfs / analytical cases
321
+ # TODO: add more where possible with test coverage,
322
+ # eg https://en.wikipedia.org/wiki/Stable_distribution#Other_analytic_cases
323
+ if alpha == 2.0:
324
+ # normal
325
+ return _norm_cdf(x0 / np.sqrt(2))
326
+ elif alpha == 0.5 and beta == 1.0:
327
+ # levy
328
+ # since S(1/2, 1, gamma, delta; <x>) ==
329
+ # S(1/2, 1, gamma, gamma + delta; <x0>).
330
+ _x = x0 + 1
331
+ if _x <= 0:
332
+ return 0
333
+
334
+ return sc.erfc(np.sqrt(0.5 / _x))
335
+ elif alpha == 1.0 and beta == 0.0:
336
+ # cauchy
337
+ return 0.5 + np.arctan(x0) / np.pi
338
+
339
+ return _cdf_single_value_piecewise_post_rounding_Z0(
340
+ x0, alpha, beta, quad_eps, x_tol_near_zeta
341
+ )
342
+
343
+
344
+ def _cdf_single_value_piecewise_post_rounding_Z0(x0, alpha, beta, quad_eps,
345
+ x_tol_near_zeta):
346
+ """Calculate cdf using Nolan's methods as detailed in [NO]."""
347
+ _nolan = Nolan(alpha, beta, x0)
348
+ zeta = _nolan.zeta
349
+ xi = _nolan.xi
350
+ c1 = _nolan.c1
351
+ # c2 = _nolan.c2
352
+ c3 = _nolan.c3
353
+ g = _nolan.g
354
+ # round x0 to zeta again if needed. zeta was recomputed and may have
355
+ # changed due to floating point differences.
356
+ # See https://github.com/scipy/scipy/pull/18133
357
+ x0 = _nolan_round_x_near_zeta(x0, alpha, zeta, x_tol_near_zeta)
358
+ # handle Nolan's initial case logic
359
+ if (alpha == 1 and beta < 0) or x0 < zeta:
360
+ # NOTE: Nolan's paper has a typo here!
361
+ # He states F(x) = 1 - F(x, alpha, -beta), but this is clearly
362
+ # incorrect since F(-infty) would be 1.0 in this case
363
+ # Indeed, the alpha != 1, x0 < zeta case is correct here.
364
+ return 1 - _cdf_single_value_piecewise_post_rounding_Z0(
365
+ -x0, alpha, -beta, quad_eps, x_tol_near_zeta
366
+ )
367
+ elif x0 == zeta:
368
+ return 0.5 - xi / np.pi
369
+
370
+ # following Nolan, we may now assume
371
+ # x0 > zeta when alpha != 1
372
+ # beta > 0 when alpha == 1
373
+
374
+ # spare calculating integral on null set
375
+ # use isclose as macos has fp differences
376
+ if np.isclose(-xi, np.pi / 2, rtol=1e-014, atol=1e-014):
377
+ return c1
378
+
379
+ def integrand(theta):
380
+ g_1 = g(theta)
381
+ return np.exp(-g_1)
382
+
383
+ with np.errstate(all="ignore"):
384
+ # shrink supports where required
385
+ left_support = -xi
386
+ right_support = np.pi / 2
387
+ if alpha > 1:
388
+ # integrand(t) monotonic 0 to 1
389
+ if integrand(-xi) != 0.0:
390
+ res = optimize.minimize(
391
+ integrand,
392
+ (-xi,),
393
+ method="L-BFGS-B",
394
+ bounds=[(-xi, np.pi / 2)],
395
+ )
396
+ left_support = res.x[0]
397
+ else:
398
+ # integrand(t) monotonic 1 to 0
399
+ if integrand(np.pi / 2) != 0.0:
400
+ res = optimize.minimize(
401
+ integrand,
402
+ (np.pi / 2,),
403
+ method="L-BFGS-B",
404
+ bounds=[(-xi, np.pi / 2)],
405
+ )
406
+ right_support = res.x[0]
407
+
408
+ intg, *ret = integrate.quad(
409
+ integrand,
410
+ left_support,
411
+ right_support,
412
+ points=[left_support, right_support],
413
+ limit=100,
414
+ epsrel=quad_eps,
415
+ epsabs=0,
416
+ full_output=1,
417
+ )
418
+
419
+ return c1 + c3 * intg
420
+
421
+
422
+ def _rvs_Z1(alpha, beta, size=None, random_state=None):
423
+ """Simulate random variables using Nolan's methods as detailed in [NO].
424
+ """
425
+
426
+ def alpha1func(alpha, beta, TH, aTH, bTH, cosTH, tanTH, W):
427
+ return (
428
+ 2
429
+ / np.pi
430
+ * (
431
+ (np.pi / 2 + bTH) * tanTH
432
+ - beta * np.log((np.pi / 2 * W * cosTH) / (np.pi / 2 + bTH))
433
+ )
434
+ )
435
+
436
+ def beta0func(alpha, beta, TH, aTH, bTH, cosTH, tanTH, W):
437
+ return (
438
+ W
439
+ / (cosTH / np.tan(aTH) + np.sin(TH))
440
+ * ((np.cos(aTH) + np.sin(aTH) * tanTH) / W) ** (1.0 / alpha)
441
+ )
442
+
443
+ def otherwise(alpha, beta, TH, aTH, bTH, cosTH, tanTH, W):
444
+ # alpha is not 1 and beta is not 0
445
+ val0 = beta * np.tan(np.pi * alpha / 2)
446
+ th0 = np.arctan(val0) / alpha
447
+ val3 = W / (cosTH / np.tan(alpha * (th0 + TH)) + np.sin(TH))
448
+ res3 = val3 * (
449
+ (
450
+ np.cos(aTH)
451
+ + np.sin(aTH) * tanTH
452
+ - val0 * (np.sin(aTH) - np.cos(aTH) * tanTH)
453
+ )
454
+ / W
455
+ ) ** (1.0 / alpha)
456
+ return res3
457
+
458
+ def alphanot1func(alpha, beta, TH, aTH, bTH, cosTH, tanTH, W):
459
+ res = _lazywhere(
460
+ beta == 0,
461
+ (alpha, beta, TH, aTH, bTH, cosTH, tanTH, W),
462
+ beta0func,
463
+ f2=otherwise,
464
+ )
465
+ return res
466
+
467
+ alpha = np.broadcast_to(alpha, size)
468
+ beta = np.broadcast_to(beta, size)
469
+ TH = uniform.rvs(
470
+ loc=-np.pi / 2.0, scale=np.pi, size=size, random_state=random_state
471
+ )
472
+ W = expon.rvs(size=size, random_state=random_state)
473
+ aTH = alpha * TH
474
+ bTH = beta * TH
475
+ cosTH = np.cos(TH)
476
+ tanTH = np.tan(TH)
477
+ res = _lazywhere(
478
+ alpha == 1,
479
+ (alpha, beta, TH, aTH, bTH, cosTH, tanTH, W),
480
+ alpha1func,
481
+ f2=alphanot1func,
482
+ )
483
+ return res
484
+
485
+
486
+ def _fitstart_S0(data):
487
+ alpha, beta, delta1, gamma = _fitstart_S1(data)
488
+
489
+ # Formulas for mapping parameters in S1 parameterization to
490
+ # those in S0 parameterization can be found in [NO]. Note that
491
+ # only delta changes.
492
+ if alpha != 1:
493
+ delta0 = delta1 + beta * gamma * np.tan(np.pi * alpha / 2.0)
494
+ else:
495
+ delta0 = delta1 + 2 * beta * gamma * np.log(gamma) / np.pi
496
+
497
+ return alpha, beta, delta0, gamma
498
+
499
+
500
+ def _fitstart_S1(data):
501
+ # We follow McCullock 1986 method - Simple Consistent Estimators
502
+ # of Stable Distribution Parameters
503
+
504
+ # fmt: off
505
+ # Table III and IV
506
+ nu_alpha_range = [2.439, 2.5, 2.6, 2.7, 2.8, 3, 3.2, 3.5, 4,
507
+ 5, 6, 8, 10, 15, 25]
508
+ nu_beta_range = [0, 0.1, 0.2, 0.3, 0.5, 0.7, 1]
509
+
510
+ # table III - alpha = psi_1(nu_alpha, nu_beta)
511
+ alpha_table = np.array([
512
+ [2.000, 2.000, 2.000, 2.000, 2.000, 2.000, 2.000],
513
+ [1.916, 1.924, 1.924, 1.924, 1.924, 1.924, 1.924],
514
+ [1.808, 1.813, 1.829, 1.829, 1.829, 1.829, 1.829],
515
+ [1.729, 1.730, 1.737, 1.745, 1.745, 1.745, 1.745],
516
+ [1.664, 1.663, 1.663, 1.668, 1.676, 1.676, 1.676],
517
+ [1.563, 1.560, 1.553, 1.548, 1.547, 1.547, 1.547],
518
+ [1.484, 1.480, 1.471, 1.460, 1.448, 1.438, 1.438],
519
+ [1.391, 1.386, 1.378, 1.364, 1.337, 1.318, 1.318],
520
+ [1.279, 1.273, 1.266, 1.250, 1.210, 1.184, 1.150],
521
+ [1.128, 1.121, 1.114, 1.101, 1.067, 1.027, 0.973],
522
+ [1.029, 1.021, 1.014, 1.004, 0.974, 0.935, 0.874],
523
+ [0.896, 0.892, 0.884, 0.883, 0.855, 0.823, 0.769],
524
+ [0.818, 0.812, 0.806, 0.801, 0.780, 0.756, 0.691],
525
+ [0.698, 0.695, 0.692, 0.689, 0.676, 0.656, 0.597],
526
+ [0.593, 0.590, 0.588, 0.586, 0.579, 0.563, 0.513]]).T
527
+ # transpose because interpolation with `RectBivariateSpline` is with
528
+ # `nu_beta` as `x` and `nu_alpha` as `y`
529
+
530
+ # table IV - beta = psi_2(nu_alpha, nu_beta)
531
+ beta_table = np.array([
532
+ [0, 2.160, 1.000, 1.000, 1.000, 1.000, 1.000],
533
+ [0, 1.592, 3.390, 1.000, 1.000, 1.000, 1.000],
534
+ [0, 0.759, 1.800, 1.000, 1.000, 1.000, 1.000],
535
+ [0, 0.482, 1.048, 1.694, 1.000, 1.000, 1.000],
536
+ [0, 0.360, 0.760, 1.232, 2.229, 1.000, 1.000],
537
+ [0, 0.253, 0.518, 0.823, 1.575, 1.000, 1.000],
538
+ [0, 0.203, 0.410, 0.632, 1.244, 1.906, 1.000],
539
+ [0, 0.165, 0.332, 0.499, 0.943, 1.560, 1.000],
540
+ [0, 0.136, 0.271, 0.404, 0.689, 1.230, 2.195],
541
+ [0, 0.109, 0.216, 0.323, 0.539, 0.827, 1.917],
542
+ [0, 0.096, 0.190, 0.284, 0.472, 0.693, 1.759],
543
+ [0, 0.082, 0.163, 0.243, 0.412, 0.601, 1.596],
544
+ [0, 0.074, 0.147, 0.220, 0.377, 0.546, 1.482],
545
+ [0, 0.064, 0.128, 0.191, 0.330, 0.478, 1.362],
546
+ [0, 0.056, 0.112, 0.167, 0.285, 0.428, 1.274]]).T
547
+
548
+ # Table V and VII
549
+ # These are ordered with decreasing `alpha_range`; so we will need to
550
+ # reverse them as required by RectBivariateSpline.
551
+ alpha_range = [2, 1.9, 1.8, 1.7, 1.6, 1.5, 1.4, 1.3, 1.2, 1.1,
552
+ 1, 0.9, 0.8, 0.7, 0.6, 0.5][::-1]
553
+ beta_range = [0, 0.25, 0.5, 0.75, 1]
554
+
555
+ # Table V - nu_c = psi_3(alpha, beta)
556
+ nu_c_table = np.array([
557
+ [1.908, 1.908, 1.908, 1.908, 1.908],
558
+ [1.914, 1.915, 1.916, 1.918, 1.921],
559
+ [1.921, 1.922, 1.927, 1.936, 1.947],
560
+ [1.927, 1.930, 1.943, 1.961, 1.987],
561
+ [1.933, 1.940, 1.962, 1.997, 2.043],
562
+ [1.939, 1.952, 1.988, 2.045, 2.116],
563
+ [1.946, 1.967, 2.022, 2.106, 2.211],
564
+ [1.955, 1.984, 2.067, 2.188, 2.333],
565
+ [1.965, 2.007, 2.125, 2.294, 2.491],
566
+ [1.980, 2.040, 2.205, 2.435, 2.696],
567
+ [2.000, 2.085, 2.311, 2.624, 2.973],
568
+ [2.040, 2.149, 2.461, 2.886, 3.356],
569
+ [2.098, 2.244, 2.676, 3.265, 3.912],
570
+ [2.189, 2.392, 3.004, 3.844, 4.775],
571
+ [2.337, 2.634, 3.542, 4.808, 6.247],
572
+ [2.588, 3.073, 4.534, 6.636, 9.144]])[::-1].T
573
+ # transpose because interpolation with `RectBivariateSpline` is with
574
+ # `beta` as `x` and `alpha` as `y`
575
+
576
+ # Table VII - nu_zeta = psi_5(alpha, beta)
577
+ nu_zeta_table = np.array([
578
+ [0, 0.000, 0.000, 0.000, 0.000],
579
+ [0, -0.017, -0.032, -0.049, -0.064],
580
+ [0, -0.030, -0.061, -0.092, -0.123],
581
+ [0, -0.043, -0.088, -0.132, -0.179],
582
+ [0, -0.056, -0.111, -0.170, -0.232],
583
+ [0, -0.066, -0.134, -0.206, -0.283],
584
+ [0, -0.075, -0.154, -0.241, -0.335],
585
+ [0, -0.084, -0.173, -0.276, -0.390],
586
+ [0, -0.090, -0.192, -0.310, -0.447],
587
+ [0, -0.095, -0.208, -0.346, -0.508],
588
+ [0, -0.098, -0.223, -0.380, -0.576],
589
+ [0, -0.099, -0.237, -0.424, -0.652],
590
+ [0, -0.096, -0.250, -0.469, -0.742],
591
+ [0, -0.089, -0.262, -0.520, -0.853],
592
+ [0, -0.078, -0.272, -0.581, -0.997],
593
+ [0, -0.061, -0.279, -0.659, -1.198]])[::-1].T
594
+ # fmt: on
595
+
596
+ psi_1 = RectBivariateSpline(nu_beta_range, nu_alpha_range,
597
+ alpha_table, kx=1, ky=1, s=0)
598
+
599
+ def psi_1_1(nu_beta, nu_alpha):
600
+ return psi_1(nu_beta, nu_alpha) \
601
+ if nu_beta > 0 else psi_1(-nu_beta, nu_alpha)
602
+
603
+ psi_2 = RectBivariateSpline(nu_beta_range, nu_alpha_range,
604
+ beta_table, kx=1, ky=1, s=0)
605
+
606
+ def psi_2_1(nu_beta, nu_alpha):
607
+ return psi_2(nu_beta, nu_alpha) \
608
+ if nu_beta > 0 else -psi_2(-nu_beta, nu_alpha)
609
+
610
+ phi_3 = RectBivariateSpline(beta_range, alpha_range, nu_c_table,
611
+ kx=1, ky=1, s=0)
612
+
613
+ def phi_3_1(beta, alpha):
614
+ return phi_3(beta, alpha) if beta > 0 else phi_3(-beta, alpha)
615
+
616
+ phi_5 = RectBivariateSpline(beta_range, alpha_range, nu_zeta_table,
617
+ kx=1, ky=1, s=0)
618
+
619
+ def phi_5_1(beta, alpha):
620
+ return phi_5(beta, alpha) if beta > 0 else -phi_5(-beta, alpha)
621
+
622
+ # quantiles
623
+ p05 = np.percentile(data, 5)
624
+ p50 = np.percentile(data, 50)
625
+ p95 = np.percentile(data, 95)
626
+ p25 = np.percentile(data, 25)
627
+ p75 = np.percentile(data, 75)
628
+
629
+ nu_alpha = (p95 - p05) / (p75 - p25)
630
+ nu_beta = (p95 + p05 - 2 * p50) / (p95 - p05)
631
+
632
+ if nu_alpha >= 2.439:
633
+ eps = np.finfo(float).eps
634
+ alpha = np.clip(psi_1_1(nu_beta, nu_alpha)[0, 0], eps, 2.)
635
+ beta = np.clip(psi_2_1(nu_beta, nu_alpha)[0, 0], -1.0, 1.0)
636
+ else:
637
+ alpha = 2.0
638
+ beta = np.sign(nu_beta)
639
+ c = (p75 - p25) / phi_3_1(beta, alpha)[0, 0]
640
+ zeta = p50 + c * phi_5_1(beta, alpha)[0, 0]
641
+ delta = zeta-beta*c*np.tan(np.pi*alpha/2.) if alpha != 1. else zeta
642
+
643
+ return (alpha, beta, delta, c)
644
+
645
+
646
+ class levy_stable_gen(rv_continuous):
647
+ r"""A Levy-stable continuous random variable.
648
+
649
+ %(before_notes)s
650
+
651
+ See Also
652
+ --------
653
+ levy, levy_l, cauchy, norm
654
+
655
+ Notes
656
+ -----
657
+ The distribution for `levy_stable` has characteristic function:
658
+
659
+ .. math::
660
+
661
+ \varphi(t, \alpha, \beta, c, \mu) =
662
+ e^{it\mu -|ct|^{\alpha}(1-i\beta\operatorname{sign}(t)\Phi(\alpha, t))}
663
+
664
+ where two different parameterizations are supported. The first :math:`S_1`:
665
+
666
+ .. math::
667
+
668
+ \Phi = \begin{cases}
669
+ \tan \left({\frac {\pi \alpha }{2}}\right)&\alpha \neq 1\\
670
+ -{\frac {2}{\pi }}\log |t|&\alpha =1
671
+ \end{cases}
672
+
673
+ The second :math:`S_0`:
674
+
675
+ .. math::
676
+
677
+ \Phi = \begin{cases}
678
+ -\tan \left({\frac {\pi \alpha }{2}}\right)(|ct|^{1-\alpha}-1)
679
+ &\alpha \neq 1\\
680
+ -{\frac {2}{\pi }}\log |ct|&\alpha =1
681
+ \end{cases}
682
+
683
+
684
+ The probability density function for `levy_stable` is:
685
+
686
+ .. math::
687
+
688
+ f(x) = \frac{1}{2\pi}\int_{-\infty}^\infty \varphi(t)e^{-ixt}\,dt
689
+
690
+ where :math:`-\infty < t < \infty`. This integral does not have a known
691
+ closed form.
692
+
693
+ `levy_stable` generalizes several distributions. Where possible, they
694
+ should be used instead. Specifically, when the shape parameters
695
+ assume the values in the table below, the corresponding equivalent
696
+ distribution should be used.
697
+
698
+ ========= ======== ===========
699
+ ``alpha`` ``beta`` Equivalent
700
+ ========= ======== ===========
701
+ 1/2 -1 `levy_l`
702
+ 1/2 1 `levy`
703
+ 1 0 `cauchy`
704
+ 2 any `norm` (with ``scale=sqrt(2)``)
705
+ ========= ======== ===========
706
+
707
+ Evaluation of the pdf uses Nolan's piecewise integration approach with the
708
+ Zolotarev :math:`M` parameterization by default. There is also the option
709
+ to use direct numerical integration of the standard parameterization of the
710
+ characteristic function or to evaluate by taking the FFT of the
711
+ characteristic function.
712
+
713
+ The default method can changed by setting the class variable
714
+ ``levy_stable.pdf_default_method`` to one of 'piecewise' for Nolan's
715
+ approach, 'dni' for direct numerical integration, or 'fft-simpson' for the
716
+ FFT based approach. For the sake of backwards compatibility, the methods
717
+ 'best' and 'zolotarev' are equivalent to 'piecewise' and the method
718
+ 'quadrature' is equivalent to 'dni'.
719
+
720
+ The parameterization can be changed by setting the class variable
721
+ ``levy_stable.parameterization`` to either 'S0' or 'S1'.
722
+ The default is 'S1'.
723
+
724
+ To improve performance of piecewise and direct numerical integration one
725
+ can specify ``levy_stable.quad_eps`` (defaults to 1.2e-14). This is used
726
+ as both the absolute and relative quadrature tolerance for direct numerical
727
+ integration and as the relative quadrature tolerance for the piecewise
728
+ method. One can also specify ``levy_stable.piecewise_x_tol_near_zeta``
729
+ (defaults to 0.005) for how close x is to zeta before it is considered the
730
+ same as x [NO]. The exact check is
731
+ ``abs(x0 - zeta) < piecewise_x_tol_near_zeta*alpha**(1/alpha)``. One can
732
+ also specify ``levy_stable.piecewise_alpha_tol_near_one`` (defaults to
733
+ 0.005) for how close alpha is to 1 before being considered equal to 1.
734
+
735
+ To increase accuracy of FFT calculation one can specify
736
+ ``levy_stable.pdf_fft_grid_spacing`` (defaults to 0.001) and
737
+ ``pdf_fft_n_points_two_power`` (defaults to None which means a value is
738
+ calculated that sufficiently covers the input range).
739
+
740
+ Further control over FFT calculation is available by setting
741
+ ``pdf_fft_interpolation_degree`` (defaults to 3) for spline order and
742
+ ``pdf_fft_interpolation_level`` for determining the number of points to use
743
+ in the Newton-Cotes formula when approximating the characteristic function
744
+ (considered experimental).
745
+
746
+ Evaluation of the cdf uses Nolan's piecewise integration approach with the
747
+ Zolatarev :math:`S_0` parameterization by default. There is also the option
748
+ to evaluate through integration of an interpolated spline of the pdf
749
+ calculated by means of the FFT method. The settings affecting FFT
750
+ calculation are the same as for pdf calculation. The default cdf method can
751
+ be changed by setting ``levy_stable.cdf_default_method`` to either
752
+ 'piecewise' or 'fft-simpson'. For cdf calculations the Zolatarev method is
753
+ superior in accuracy, so FFT is disabled by default.
754
+
755
+ Fitting estimate uses quantile estimation method in [MC]. MLE estimation of
756
+ parameters in fit method uses this quantile estimate initially. Note that
757
+ MLE doesn't always converge if using FFT for pdf calculations; this will be
758
+ the case if alpha <= 1 where the FFT approach doesn't give good
759
+ approximations.
760
+
761
+ Any non-missing value for the attribute
762
+ ``levy_stable.pdf_fft_min_points_threshold`` will set
763
+ ``levy_stable.pdf_default_method`` to 'fft-simpson' if a valid
764
+ default method is not otherwise set.
765
+
766
+
767
+
768
+ .. warning::
769
+
770
+ For pdf calculations FFT calculation is considered experimental.
771
+
772
+ For cdf calculations FFT calculation is considered experimental. Use
773
+ Zolatarev's method instead (default).
774
+
775
+ The probability density above is defined in the "standardized" form. To
776
+ shift and/or scale the distribution use the ``loc`` and ``scale``
777
+ parameters.
778
+ Generally ``%(name)s.pdf(x, %(shapes)s, loc, scale)`` is identically
779
+ equivalent to ``%(name)s.pdf(y, %(shapes)s) / scale`` with
780
+ ``y = (x - loc) / scale``, except in the ``S1`` parameterization if
781
+ ``alpha == 1``. In that case ``%(name)s.pdf(x, %(shapes)s, loc, scale)``
782
+ is identically equivalent to ``%(name)s.pdf(y, %(shapes)s) / scale`` with
783
+ ``y = (x - loc - 2 * beta * scale * np.log(scale) / np.pi) / scale``.
784
+ See [NO2]_ Definition 1.8 for more information.
785
+ Note that shifting the location of a distribution
786
+ does not make it a "noncentral" distribution.
787
+
788
+ References
789
+ ----------
790
+ .. [MC] McCulloch, J., 1986. Simple consistent estimators of stable
791
+ distribution parameters. Communications in Statistics - Simulation and
792
+ Computation 15, 11091136.
793
+ .. [WZ] Wang, Li and Zhang, Ji-Hong, 2008. Simpson's rule based FFT method
794
+ to compute densities of stable distribution.
795
+ .. [NO] Nolan, J., 1997. Numerical Calculation of Stable Densities and
796
+ distributions Functions.
797
+ .. [NO2] Nolan, J., 2018. Stable Distributions: Models for Heavy Tailed
798
+ Data.
799
+ .. [HO] Hopcraft, K. I., Jakeman, E., Tanner, R. M. J., 1999. Lévy random
800
+ walks with fluctuating step number and multiscale behavior.
801
+
802
+ %(example)s
803
+
804
+ """
805
+ # Configurable options as class variables
806
+ # (accessible from self by attribute lookup).
807
+ parameterization = "S1"
808
+ pdf_default_method = "piecewise"
809
+ cdf_default_method = "piecewise"
810
+ quad_eps = _QUAD_EPS
811
+ piecewise_x_tol_near_zeta = 0.005
812
+ piecewise_alpha_tol_near_one = 0.005
813
+ pdf_fft_min_points_threshold = None
814
+ pdf_fft_grid_spacing = 0.001
815
+ pdf_fft_n_points_two_power = None
816
+ pdf_fft_interpolation_level = 3
817
+ pdf_fft_interpolation_degree = 3
818
+
819
+ def _argcheck(self, alpha, beta):
820
+ return (alpha > 0) & (alpha <= 2) & (beta <= 1) & (beta >= -1)
821
+
822
+ def _shape_info(self):
823
+ ialpha = _ShapeInfo("alpha", False, (0, 2), (False, True))
824
+ ibeta = _ShapeInfo("beta", False, (-1, 1), (True, True))
825
+ return [ialpha, ibeta]
826
+
827
+ def _parameterization(self):
828
+ allowed = ("S0", "S1")
829
+ pz = self.parameterization
830
+ if pz not in allowed:
831
+ raise RuntimeError(
832
+ f"Parameterization '{pz}' in supported list: {allowed}"
833
+ )
834
+ return pz
835
+
836
+ @inherit_docstring_from(rv_continuous)
837
+ def rvs(self, *args, **kwds):
838
+ X1 = super().rvs(*args, **kwds)
839
+
840
+ kwds.pop("discrete", None)
841
+ kwds.pop("random_state", None)
842
+ (alpha, beta), delta, gamma, size = self._parse_args_rvs(*args, **kwds)
843
+
844
+ # shift location for this parameterisation (S1)
845
+ X1 = np.where(
846
+ alpha == 1.0, X1 + 2 * beta * gamma * np.log(gamma) / np.pi, X1
847
+ )
848
+
849
+ if self._parameterization() == "S0":
850
+ return np.where(
851
+ alpha == 1.0,
852
+ X1 - (beta * 2 * gamma * np.log(gamma) / np.pi),
853
+ X1 - gamma * beta * np.tan(np.pi * alpha / 2.0),
854
+ )
855
+ elif self._parameterization() == "S1":
856
+ return X1
857
+
858
+ def _rvs(self, alpha, beta, size=None, random_state=None):
859
+ return _rvs_Z1(alpha, beta, size, random_state)
860
+
861
+ @inherit_docstring_from(rv_continuous)
862
+ def pdf(self, x, *args, **kwds):
863
+ # override base class version to correct
864
+ # location for S1 parameterization
865
+ if self._parameterization() == "S0":
866
+ return super().pdf(x, *args, **kwds)
867
+ elif self._parameterization() == "S1":
868
+ (alpha, beta), delta, gamma = self._parse_args(*args, **kwds)
869
+ if np.all(np.reshape(alpha, (1, -1))[0, :] != 1):
870
+ return super().pdf(x, *args, **kwds)
871
+ else:
872
+ # correct location for this parameterisation
873
+ x = np.reshape(x, (1, -1))[0, :]
874
+ x, alpha, beta = np.broadcast_arrays(x, alpha, beta)
875
+
876
+ data_in = np.dstack((x, alpha, beta))[0]
877
+ data_out = np.empty(shape=(len(data_in), 1))
878
+ # group data in unique arrays of alpha, beta pairs
879
+ uniq_param_pairs = np.unique(data_in[:, 1:], axis=0)
880
+ for pair in uniq_param_pairs:
881
+ _alpha, _beta = pair
882
+ _delta = (
883
+ delta + 2 * _beta * gamma * np.log(gamma) / np.pi
884
+ if _alpha == 1.0
885
+ else delta
886
+ )
887
+ data_mask = np.all(data_in[:, 1:] == pair, axis=-1)
888
+ _x = data_in[data_mask, 0]
889
+ data_out[data_mask] = (
890
+ super()
891
+ .pdf(_x, _alpha, _beta, loc=_delta, scale=gamma)
892
+ .reshape(len(_x), 1)
893
+ )
894
+ output = data_out.T[0]
895
+ if output.shape == (1,):
896
+ return output[0]
897
+ return output
898
+
899
+ def _pdf(self, x, alpha, beta):
900
+ if self._parameterization() == "S0":
901
+ _pdf_single_value_piecewise = _pdf_single_value_piecewise_Z0
902
+ _pdf_single_value_cf_integrate = _pdf_single_value_cf_integrate_Z0
903
+ _cf = _cf_Z0
904
+ elif self._parameterization() == "S1":
905
+ _pdf_single_value_piecewise = _pdf_single_value_piecewise_Z1
906
+ _pdf_single_value_cf_integrate = _pdf_single_value_cf_integrate_Z1
907
+ _cf = _cf_Z1
908
+
909
+ x = np.asarray(x).reshape(1, -1)[0, :]
910
+
911
+ x, alpha, beta = np.broadcast_arrays(x, alpha, beta)
912
+
913
+ data_in = np.dstack((x, alpha, beta))[0]
914
+ data_out = np.empty(shape=(len(data_in), 1))
915
+
916
+ pdf_default_method_name = self.pdf_default_method
917
+ if pdf_default_method_name in ("piecewise", "best", "zolotarev"):
918
+ pdf_single_value_method = _pdf_single_value_piecewise
919
+ elif pdf_default_method_name in ("dni", "quadrature"):
920
+ pdf_single_value_method = _pdf_single_value_cf_integrate
921
+ elif (
922
+ pdf_default_method_name == "fft-simpson"
923
+ or self.pdf_fft_min_points_threshold is not None
924
+ ):
925
+ pdf_single_value_method = None
926
+
927
+ pdf_single_value_kwds = {
928
+ "quad_eps": self.quad_eps,
929
+ "piecewise_x_tol_near_zeta": self.piecewise_x_tol_near_zeta,
930
+ "piecewise_alpha_tol_near_one": self.piecewise_alpha_tol_near_one,
931
+ }
932
+
933
+ fft_grid_spacing = self.pdf_fft_grid_spacing
934
+ fft_n_points_two_power = self.pdf_fft_n_points_two_power
935
+ fft_interpolation_level = self.pdf_fft_interpolation_level
936
+ fft_interpolation_degree = self.pdf_fft_interpolation_degree
937
+
938
+ # group data in unique arrays of alpha, beta pairs
939
+ uniq_param_pairs = np.unique(data_in[:, 1:], axis=0)
940
+ for pair in uniq_param_pairs:
941
+ data_mask = np.all(data_in[:, 1:] == pair, axis=-1)
942
+ data_subset = data_in[data_mask]
943
+ if pdf_single_value_method is not None:
944
+ data_out[data_mask] = np.array(
945
+ [
946
+ pdf_single_value_method(
947
+ _x, _alpha, _beta, **pdf_single_value_kwds
948
+ )
949
+ for _x, _alpha, _beta in data_subset
950
+ ]
951
+ ).reshape(len(data_subset), 1)
952
+ else:
953
+ warnings.warn(
954
+ "Density calculations experimental for FFT method."
955
+ + " Use combination of piecewise and dni methods instead.",
956
+ RuntimeWarning, stacklevel=3,
957
+ )
958
+ _alpha, _beta = pair
959
+ _x = data_subset[:, (0,)]
960
+
961
+ if _alpha < 1.0:
962
+ raise RuntimeError(
963
+ "FFT method does not work well for alpha less than 1."
964
+ )
965
+
966
+ # need enough points to "cover" _x for interpolation
967
+ if fft_grid_spacing is None and fft_n_points_two_power is None:
968
+ raise ValueError(
969
+ "One of fft_grid_spacing or fft_n_points_two_power "
970
+ + "needs to be set."
971
+ )
972
+ max_abs_x = np.max(np.abs(_x))
973
+ h = (
974
+ 2 ** (3 - fft_n_points_two_power) * max_abs_x
975
+ if fft_grid_spacing is None
976
+ else fft_grid_spacing
977
+ )
978
+ q = (
979
+ np.ceil(np.log(2 * max_abs_x / h) / np.log(2)) + 2
980
+ if fft_n_points_two_power is None
981
+ else int(fft_n_points_two_power)
982
+ )
983
+
984
+ # for some parameters, the range of x can be quite
985
+ # large, let's choose an arbitrary cut off (8GB) to save on
986
+ # computer memory.
987
+ MAX_Q = 30
988
+ if q > MAX_Q:
989
+ raise RuntimeError(
990
+ "fft_n_points_two_power has a maximum "
991
+ + f"value of {MAX_Q}"
992
+ )
993
+
994
+ density_x, density = pdf_from_cf_with_fft(
995
+ lambda t: _cf(t, _alpha, _beta),
996
+ h=h,
997
+ q=q,
998
+ level=fft_interpolation_level,
999
+ )
1000
+ f = interpolate.InterpolatedUnivariateSpline(
1001
+ density_x, np.real(density), k=fft_interpolation_degree
1002
+ ) # patch FFT to use cubic
1003
+ data_out[data_mask] = f(_x)
1004
+
1005
+ return data_out.T[0]
1006
+
1007
+ @inherit_docstring_from(rv_continuous)
1008
+ def cdf(self, x, *args, **kwds):
1009
+ # override base class version to correct
1010
+ # location for S1 parameterization
1011
+ # NOTE: this is near identical to pdf() above
1012
+ if self._parameterization() == "S0":
1013
+ return super().cdf(x, *args, **kwds)
1014
+ elif self._parameterization() == "S1":
1015
+ (alpha, beta), delta, gamma = self._parse_args(*args, **kwds)
1016
+ if np.all(np.reshape(alpha, (1, -1))[0, :] != 1):
1017
+ return super().cdf(x, *args, **kwds)
1018
+ else:
1019
+ # correct location for this parameterisation
1020
+ x = np.reshape(x, (1, -1))[0, :]
1021
+ x, alpha, beta = np.broadcast_arrays(x, alpha, beta)
1022
+
1023
+ data_in = np.dstack((x, alpha, beta))[0]
1024
+ data_out = np.empty(shape=(len(data_in), 1))
1025
+ # group data in unique arrays of alpha, beta pairs
1026
+ uniq_param_pairs = np.unique(data_in[:, 1:], axis=0)
1027
+ for pair in uniq_param_pairs:
1028
+ _alpha, _beta = pair
1029
+ _delta = (
1030
+ delta + 2 * _beta * gamma * np.log(gamma) / np.pi
1031
+ if _alpha == 1.0
1032
+ else delta
1033
+ )
1034
+ data_mask = np.all(data_in[:, 1:] == pair, axis=-1)
1035
+ _x = data_in[data_mask, 0]
1036
+ data_out[data_mask] = (
1037
+ super()
1038
+ .cdf(_x, _alpha, _beta, loc=_delta, scale=gamma)
1039
+ .reshape(len(_x), 1)
1040
+ )
1041
+ output = data_out.T[0]
1042
+ if output.shape == (1,):
1043
+ return output[0]
1044
+ return output
1045
+
1046
+ def _cdf(self, x, alpha, beta):
1047
+ if self._parameterization() == "S0":
1048
+ _cdf_single_value_piecewise = _cdf_single_value_piecewise_Z0
1049
+ _cf = _cf_Z0
1050
+ elif self._parameterization() == "S1":
1051
+ _cdf_single_value_piecewise = _cdf_single_value_piecewise_Z1
1052
+ _cf = _cf_Z1
1053
+
1054
+ x = np.asarray(x).reshape(1, -1)[0, :]
1055
+
1056
+ x, alpha, beta = np.broadcast_arrays(x, alpha, beta)
1057
+
1058
+ data_in = np.dstack((x, alpha, beta))[0]
1059
+ data_out = np.empty(shape=(len(data_in), 1))
1060
+
1061
+ cdf_default_method_name = self.cdf_default_method
1062
+ if cdf_default_method_name == "piecewise":
1063
+ cdf_single_value_method = _cdf_single_value_piecewise
1064
+ elif cdf_default_method_name == "fft-simpson":
1065
+ cdf_single_value_method = None
1066
+
1067
+ cdf_single_value_kwds = {
1068
+ "quad_eps": self.quad_eps,
1069
+ "piecewise_x_tol_near_zeta": self.piecewise_x_tol_near_zeta,
1070
+ "piecewise_alpha_tol_near_one": self.piecewise_alpha_tol_near_one,
1071
+ }
1072
+
1073
+ fft_grid_spacing = self.pdf_fft_grid_spacing
1074
+ fft_n_points_two_power = self.pdf_fft_n_points_two_power
1075
+ fft_interpolation_level = self.pdf_fft_interpolation_level
1076
+ fft_interpolation_degree = self.pdf_fft_interpolation_degree
1077
+
1078
+ # group data in unique arrays of alpha, beta pairs
1079
+ uniq_param_pairs = np.unique(data_in[:, 1:], axis=0)
1080
+ for pair in uniq_param_pairs:
1081
+ data_mask = np.all(data_in[:, 1:] == pair, axis=-1)
1082
+ data_subset = data_in[data_mask]
1083
+ if cdf_single_value_method is not None:
1084
+ data_out[data_mask] = np.array(
1085
+ [
1086
+ cdf_single_value_method(
1087
+ _x, _alpha, _beta, **cdf_single_value_kwds
1088
+ )
1089
+ for _x, _alpha, _beta in data_subset
1090
+ ]
1091
+ ).reshape(len(data_subset), 1)
1092
+ else:
1093
+ warnings.warn(
1094
+ "Cumulative density calculations experimental for FFT"
1095
+ + " method. Use piecewise method instead.",
1096
+ RuntimeWarning, stacklevel=3,
1097
+ )
1098
+ _alpha, _beta = pair
1099
+ _x = data_subset[:, (0,)]
1100
+
1101
+ # need enough points to "cover" _x for interpolation
1102
+ if fft_grid_spacing is None and fft_n_points_two_power is None:
1103
+ raise ValueError(
1104
+ "One of fft_grid_spacing or fft_n_points_two_power "
1105
+ + "needs to be set."
1106
+ )
1107
+ max_abs_x = np.max(np.abs(_x))
1108
+ h = (
1109
+ 2 ** (3 - fft_n_points_two_power) * max_abs_x
1110
+ if fft_grid_spacing is None
1111
+ else fft_grid_spacing
1112
+ )
1113
+ q = (
1114
+ np.ceil(np.log(2 * max_abs_x / h) / np.log(2)) + 2
1115
+ if fft_n_points_two_power is None
1116
+ else int(fft_n_points_two_power)
1117
+ )
1118
+
1119
+ density_x, density = pdf_from_cf_with_fft(
1120
+ lambda t: _cf(t, _alpha, _beta),
1121
+ h=h,
1122
+ q=q,
1123
+ level=fft_interpolation_level,
1124
+ )
1125
+ f = interpolate.InterpolatedUnivariateSpline(
1126
+ density_x, np.real(density), k=fft_interpolation_degree
1127
+ )
1128
+ data_out[data_mask] = np.array(
1129
+ [f.integral(self.a, float(x_1.squeeze())) for x_1 in _x]
1130
+ ).reshape(data_out[data_mask].shape)
1131
+
1132
+ return data_out.T[0]
1133
+
1134
+ def _fitstart(self, data):
1135
+ if self._parameterization() == "S0":
1136
+ _fitstart = _fitstart_S0
1137
+ elif self._parameterization() == "S1":
1138
+ _fitstart = _fitstart_S1
1139
+ return _fitstart(data)
1140
+
1141
+ def _stats(self, alpha, beta):
1142
+ mu = 0 if alpha > 1 else np.nan
1143
+ mu2 = 2 if alpha == 2 else np.inf
1144
+ g1 = 0.0 if alpha == 2.0 else np.nan
1145
+ g2 = 0.0 if alpha == 2.0 else np.nan
1146
+ return mu, mu2, g1, g2
1147
+
1148
+
1149
+ # cotes numbers - see sequence from http://oeis.org/A100642
1150
+ Cotes_table = np.array(
1151
+ [[], [1]] + [v[2] for v in _builtincoeffs.values()], dtype=object
1152
+ )
1153
+ Cotes = np.array(
1154
+ [
1155
+ np.pad(r, (0, len(Cotes_table) - 1 - len(r)), mode='constant')
1156
+ for r in Cotes_table
1157
+ ]
1158
+ )
1159
+
1160
+
1161
+ def pdf_from_cf_with_fft(cf, h=0.01, q=9, level=3):
1162
+ """Calculates pdf from characteristic function.
1163
+
1164
+ Uses fast Fourier transform with Newton-Cotes integration following [WZ].
1165
+ Defaults to using Simpson's method (3-point Newton-Cotes integration).
1166
+
1167
+ Parameters
1168
+ ----------
1169
+ cf : callable
1170
+ Single argument function from float -> complex expressing a
1171
+ characteristic function for some distribution.
1172
+ h : Optional[float]
1173
+ Step size for Newton-Cotes integration. Default: 0.01
1174
+ q : Optional[int]
1175
+ Use 2**q steps when performing Newton-Cotes integration.
1176
+ The infinite integral in the inverse Fourier transform will then
1177
+ be restricted to the interval [-2**q * h / 2, 2**q * h / 2]. Setting
1178
+ the number of steps equal to a power of 2 allows the fft to be
1179
+ calculated in O(n*log(n)) time rather than O(n**2).
1180
+ Default: 9
1181
+ level : Optional[int]
1182
+ Calculate integral using n-point Newton-Cotes integration for
1183
+ n = level. The 3-point Newton-Cotes formula corresponds to Simpson's
1184
+ rule. Default: 3
1185
+
1186
+ Returns
1187
+ -------
1188
+ x_l : ndarray
1189
+ Array of points x at which pdf is estimated. 2**q equally spaced
1190
+ points from -pi/h up to but not including pi/h.
1191
+ density : ndarray
1192
+ Estimated values of pdf corresponding to cf at points in x_l.
1193
+
1194
+ References
1195
+ ----------
1196
+ .. [WZ] Wang, Li and Zhang, Ji-Hong, 2008. Simpson's rule based FFT method
1197
+ to compute densities of stable distribution.
1198
+ """
1199
+ n = level
1200
+ N = 2**q
1201
+ steps = np.arange(0, N)
1202
+ L = N * h / 2
1203
+ x_l = np.pi * (steps - N / 2) / L
1204
+ if level > 1:
1205
+ indices = np.arange(n).reshape(n, 1)
1206
+ s1 = np.sum(
1207
+ (-1) ** steps * Cotes[n, indices] * np.fft.fft(
1208
+ (-1)**steps * cf(-L + h * steps + h * indices / (n - 1))
1209
+ ) * np.exp(
1210
+ 1j * np.pi * indices / (n - 1)
1211
+ - 2 * 1j * np.pi * indices * steps /
1212
+ (N * (n - 1))
1213
+ ),
1214
+ axis=0
1215
+ )
1216
+ else:
1217
+ s1 = (-1) ** steps * Cotes[n, 0] * np.fft.fft(
1218
+ (-1) ** steps * cf(-L + h * steps)
1219
+ )
1220
+ density = h * s1 / (2 * np.pi * np.sum(Cotes[n]))
1221
+ return (x_l, density)
1222
+
1223
+
1224
+ levy_stable = levy_stable_gen(name="levy_stable")
parrot/lib/python3.10/site-packages/scipy/stats/_levy_stable/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (32.6 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/_levy_stable/levyst.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (66.5 kB). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/_rcont/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #
2
+ from .rcont import rvs_rcont1, rvs_rcont2
3
+
4
+ __all__ = ["rvs_rcont1", "rvs_rcont2"]
parrot/lib/python3.10/site-packages/scipy/stats/_rcont/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (260 Bytes). View file
 
parrot/lib/python3.10/site-packages/scipy/stats/_unuran/__init__.py ADDED
File without changes