applied-ai-018 commited on
Commit
6fdfda2
·
verified ·
1 Parent(s): eaa5691

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. llmeval-env/lib/python3.10/site-packages/scipy/__pycache__/__config__.cpython-310.pyc +0 -0
  2. llmeval-env/lib/python3.10/site-packages/scipy/__pycache__/__init__.cpython-310.pyc +0 -0
  3. llmeval-env/lib/python3.10/site-packages/scipy/__pycache__/_distributor_init.cpython-310.pyc +0 -0
  4. llmeval-env/lib/python3.10/site-packages/scipy/__pycache__/conftest.cpython-310.pyc +0 -0
  5. llmeval-env/lib/python3.10/site-packages/scipy/__pycache__/version.cpython-310.pyc +0 -0
  6. llmeval-env/lib/python3.10/site-packages/scipy/constants/__init__.py +347 -0
  7. llmeval-env/lib/python3.10/site-packages/scipy/constants/_codata.py +0 -0
  8. llmeval-env/lib/python3.10/site-packages/scipy/constants/_constants.py +362 -0
  9. llmeval-env/lib/python3.10/site-packages/scipy/constants/codata.py +24 -0
  10. llmeval-env/lib/python3.10/site-packages/scipy/constants/constants.py +53 -0
  11. llmeval-env/lib/python3.10/site-packages/scipy/constants/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  12. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/__init__.py +103 -0
  13. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/__pycache__/__init__.cpython-310.pyc +0 -0
  14. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/__pycache__/_basic.cpython-310.pyc +0 -0
  15. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/__pycache__/_helper.cpython-310.pyc +0 -0
  16. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/__pycache__/_pseudo_diffs.cpython-310.pyc +0 -0
  17. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/__pycache__/_realtransforms.cpython-310.pyc +0 -0
  18. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/__pycache__/basic.cpython-310.pyc +0 -0
  19. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/__pycache__/helper.cpython-310.pyc +0 -0
  20. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/__pycache__/pseudo_diffs.cpython-310.pyc +0 -0
  21. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/__pycache__/realtransforms.cpython-310.pyc +0 -0
  22. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/_basic.py +428 -0
  23. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/_helper.py +115 -0
  24. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/_pseudo_diffs.py +551 -0
  25. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/_realtransforms.py +598 -0
  26. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/basic.py +20 -0
  27. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/convolve.cpython-310-x86_64-linux-gnu.so +0 -0
  28. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/helper.py +19 -0
  29. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/pseudo_diffs.py +22 -0
  30. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/realtransforms.py +19 -0
  31. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/tests/__init__.py +0 -0
  32. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  33. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_basic.cpython-310.pyc +0 -0
  34. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_helper.cpython-310.pyc +0 -0
  35. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_import.cpython-310.pyc +0 -0
  36. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_pseudo_diffs.cpython-310.pyc +0 -0
  37. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_real_transforms.cpython-310.pyc +0 -0
  38. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/tests/test_basic.py +873 -0
  39. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/tests/test_helper.py +54 -0
  40. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/tests/test_import.py +31 -0
  41. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/tests/test_pseudo_diffs.py +380 -0
  42. llmeval-env/lib/python3.10/site-packages/scipy/fftpack/tests/test_real_transforms.py +815 -0
  43. llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/__init__.cpython-310.pyc +0 -0
  44. llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/_quadrature.cpython-310.pyc +0 -0
  45. llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/dop.cpython-310.pyc +0 -0
  46. llmeval-env/lib/python3.10/site-packages/scipy/optimize/README +76 -0
  47. llmeval-env/lib/python3.10/site-packages/scipy/optimize/__init__.py +451 -0
  48. llmeval-env/lib/python3.10/site-packages/scipy/optimize/_basinhopping.py +753 -0
  49. llmeval-env/lib/python3.10/site-packages/scipy/optimize/_dcsrch.py +728 -0
  50. llmeval-env/lib/python3.10/site-packages/scipy/optimize/_differentiable_functions.py +646 -0
llmeval-env/lib/python3.10/site-packages/scipy/__pycache__/__config__.cpython-310.pyc ADDED
Binary file (3.56 kB). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (3.66 kB). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/__pycache__/_distributor_init.cpython-310.pyc ADDED
Binary file (813 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/__pycache__/conftest.cpython-310.pyc ADDED
Binary file (6.4 kB). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/__pycache__/version.cpython-310.pyc ADDED
Binary file (325 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/constants/__init__.py ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ ==================================
3
+ Constants (:mod:`scipy.constants`)
4
+ ==================================
5
+
6
+ .. currentmodule:: scipy.constants
7
+
8
+ Physical and mathematical constants and units.
9
+
10
+
11
+ Mathematical constants
12
+ ======================
13
+
14
+ ================ =================================================================
15
+ ``pi`` Pi
16
+ ``golden`` Golden ratio
17
+ ``golden_ratio`` Golden ratio
18
+ ================ =================================================================
19
+
20
+
21
+ Physical constants
22
+ ==================
23
+
24
+ =========================== =================================================================
25
+ ``c`` speed of light in vacuum
26
+ ``speed_of_light`` speed of light in vacuum
27
+ ``mu_0`` the magnetic constant :math:`\mu_0`
28
+ ``epsilon_0`` the electric constant (vacuum permittivity), :math:`\epsilon_0`
29
+ ``h`` the Planck constant :math:`h`
30
+ ``Planck`` the Planck constant :math:`h`
31
+ ``hbar`` :math:`\hbar = h/(2\pi)`
32
+ ``G`` Newtonian constant of gravitation
33
+ ``gravitational_constant`` Newtonian constant of gravitation
34
+ ``g`` standard acceleration of gravity
35
+ ``e`` elementary charge
36
+ ``elementary_charge`` elementary charge
37
+ ``R`` molar gas constant
38
+ ``gas_constant`` molar gas constant
39
+ ``alpha`` fine-structure constant
40
+ ``fine_structure`` fine-structure constant
41
+ ``N_A`` Avogadro constant
42
+ ``Avogadro`` Avogadro constant
43
+ ``k`` Boltzmann constant
44
+ ``Boltzmann`` Boltzmann constant
45
+ ``sigma`` Stefan-Boltzmann constant :math:`\sigma`
46
+ ``Stefan_Boltzmann`` Stefan-Boltzmann constant :math:`\sigma`
47
+ ``Wien`` Wien displacement law constant
48
+ ``Rydberg`` Rydberg constant
49
+ ``m_e`` electron mass
50
+ ``electron_mass`` electron mass
51
+ ``m_p`` proton mass
52
+ ``proton_mass`` proton mass
53
+ ``m_n`` neutron mass
54
+ ``neutron_mass`` neutron mass
55
+ =========================== =================================================================
56
+
57
+
58
+ Constants database
59
+ ------------------
60
+
61
+ In addition to the above variables, :mod:`scipy.constants` also contains the
62
+ 2018 CODATA recommended values [CODATA2018]_ database containing more physical
63
+ constants.
64
+
65
+ .. autosummary::
66
+ :toctree: generated/
67
+
68
+ value -- Value in physical_constants indexed by key
69
+ unit -- Unit in physical_constants indexed by key
70
+ precision -- Relative precision in physical_constants indexed by key
71
+ find -- Return list of physical_constant keys with a given string
72
+ ConstantWarning -- Constant sought not in newest CODATA data set
73
+
74
+ .. data:: physical_constants
75
+
76
+ Dictionary of physical constants, of the format
77
+ ``physical_constants[name] = (value, unit, uncertainty)``.
78
+
79
+ Available constants:
80
+
81
+ ====================================================================== ====
82
+ %(constant_names)s
83
+ ====================================================================== ====
84
+
85
+
86
+ Units
87
+ =====
88
+
89
+ SI prefixes
90
+ -----------
91
+
92
+ ============ =================================================================
93
+ ``quetta`` :math:`10^{30}`
94
+ ``ronna`` :math:`10^{27}`
95
+ ``yotta`` :math:`10^{24}`
96
+ ``zetta`` :math:`10^{21}`
97
+ ``exa`` :math:`10^{18}`
98
+ ``peta`` :math:`10^{15}`
99
+ ``tera`` :math:`10^{12}`
100
+ ``giga`` :math:`10^{9}`
101
+ ``mega`` :math:`10^{6}`
102
+ ``kilo`` :math:`10^{3}`
103
+ ``hecto`` :math:`10^{2}`
104
+ ``deka`` :math:`10^{1}`
105
+ ``deci`` :math:`10^{-1}`
106
+ ``centi`` :math:`10^{-2}`
107
+ ``milli`` :math:`10^{-3}`
108
+ ``micro`` :math:`10^{-6}`
109
+ ``nano`` :math:`10^{-9}`
110
+ ``pico`` :math:`10^{-12}`
111
+ ``femto`` :math:`10^{-15}`
112
+ ``atto`` :math:`10^{-18}`
113
+ ``zepto`` :math:`10^{-21}`
114
+ ``yocto`` :math:`10^{-24}`
115
+ ``ronto`` :math:`10^{-27}`
116
+ ``quecto`` :math:`10^{-30}`
117
+ ============ =================================================================
118
+
119
+ Binary prefixes
120
+ ---------------
121
+
122
+ ============ =================================================================
123
+ ``kibi`` :math:`2^{10}`
124
+ ``mebi`` :math:`2^{20}`
125
+ ``gibi`` :math:`2^{30}`
126
+ ``tebi`` :math:`2^{40}`
127
+ ``pebi`` :math:`2^{50}`
128
+ ``exbi`` :math:`2^{60}`
129
+ ``zebi`` :math:`2^{70}`
130
+ ``yobi`` :math:`2^{80}`
131
+ ============ =================================================================
132
+
133
+ Mass
134
+ ----
135
+
136
+ ================= ============================================================
137
+ ``gram`` :math:`10^{-3}` kg
138
+ ``metric_ton`` :math:`10^{3}` kg
139
+ ``grain`` one grain in kg
140
+ ``lb`` one pound (avoirdupous) in kg
141
+ ``pound`` one pound (avoirdupous) in kg
142
+ ``blob`` one inch version of a slug in kg (added in 1.0.0)
143
+ ``slinch`` one inch version of a slug in kg (added in 1.0.0)
144
+ ``slug`` one slug in kg (added in 1.0.0)
145
+ ``oz`` one ounce in kg
146
+ ``ounce`` one ounce in kg
147
+ ``stone`` one stone in kg
148
+ ``grain`` one grain in kg
149
+ ``long_ton`` one long ton in kg
150
+ ``short_ton`` one short ton in kg
151
+ ``troy_ounce`` one Troy ounce in kg
152
+ ``troy_pound`` one Troy pound in kg
153
+ ``carat`` one carat in kg
154
+ ``m_u`` atomic mass constant (in kg)
155
+ ``u`` atomic mass constant (in kg)
156
+ ``atomic_mass`` atomic mass constant (in kg)
157
+ ================= ============================================================
158
+
159
+ Angle
160
+ -----
161
+
162
+ ================= ============================================================
163
+ ``degree`` degree in radians
164
+ ``arcmin`` arc minute in radians
165
+ ``arcminute`` arc minute in radians
166
+ ``arcsec`` arc second in radians
167
+ ``arcsecond`` arc second in radians
168
+ ================= ============================================================
169
+
170
+
171
+ Time
172
+ ----
173
+
174
+ ================= ============================================================
175
+ ``minute`` one minute in seconds
176
+ ``hour`` one hour in seconds
177
+ ``day`` one day in seconds
178
+ ``week`` one week in seconds
179
+ ``year`` one year (365 days) in seconds
180
+ ``Julian_year`` one Julian year (365.25 days) in seconds
181
+ ================= ============================================================
182
+
183
+
184
+ Length
185
+ ------
186
+
187
+ ===================== ============================================================
188
+ ``inch`` one inch in meters
189
+ ``foot`` one foot in meters
190
+ ``yard`` one yard in meters
191
+ ``mile`` one mile in meters
192
+ ``mil`` one mil in meters
193
+ ``pt`` one point in meters
194
+ ``point`` one point in meters
195
+ ``survey_foot`` one survey foot in meters
196
+ ``survey_mile`` one survey mile in meters
197
+ ``nautical_mile`` one nautical mile in meters
198
+ ``fermi`` one Fermi in meters
199
+ ``angstrom`` one Angstrom in meters
200
+ ``micron`` one micron in meters
201
+ ``au`` one astronomical unit in meters
202
+ ``astronomical_unit`` one astronomical unit in meters
203
+ ``light_year`` one light year in meters
204
+ ``parsec`` one parsec in meters
205
+ ===================== ============================================================
206
+
207
+ Pressure
208
+ --------
209
+
210
+ ================= ============================================================
211
+ ``atm`` standard atmosphere in pascals
212
+ ``atmosphere`` standard atmosphere in pascals
213
+ ``bar`` one bar in pascals
214
+ ``torr`` one torr (mmHg) in pascals
215
+ ``mmHg`` one torr (mmHg) in pascals
216
+ ``psi`` one psi in pascals
217
+ ================= ============================================================
218
+
219
+ Area
220
+ ----
221
+
222
+ ================= ============================================================
223
+ ``hectare`` one hectare in square meters
224
+ ``acre`` one acre in square meters
225
+ ================= ============================================================
226
+
227
+
228
+ Volume
229
+ ------
230
+
231
+ =================== ========================================================
232
+ ``liter`` one liter in cubic meters
233
+ ``litre`` one liter in cubic meters
234
+ ``gallon`` one gallon (US) in cubic meters
235
+ ``gallon_US`` one gallon (US) in cubic meters
236
+ ``gallon_imp`` one gallon (UK) in cubic meters
237
+ ``fluid_ounce`` one fluid ounce (US) in cubic meters
238
+ ``fluid_ounce_US`` one fluid ounce (US) in cubic meters
239
+ ``fluid_ounce_imp`` one fluid ounce (UK) in cubic meters
240
+ ``bbl`` one barrel in cubic meters
241
+ ``barrel`` one barrel in cubic meters
242
+ =================== ========================================================
243
+
244
+ Speed
245
+ -----
246
+
247
+ ================== ==========================================================
248
+ ``kmh`` kilometers per hour in meters per second
249
+ ``mph`` miles per hour in meters per second
250
+ ``mach`` one Mach (approx., at 15 C, 1 atm) in meters per second
251
+ ``speed_of_sound`` one Mach (approx., at 15 C, 1 atm) in meters per second
252
+ ``knot`` one knot in meters per second
253
+ ================== ==========================================================
254
+
255
+
256
+ Temperature
257
+ -----------
258
+
259
+ ===================== =======================================================
260
+ ``zero_Celsius`` zero of Celsius scale in Kelvin
261
+ ``degree_Fahrenheit`` one Fahrenheit (only differences) in Kelvins
262
+ ===================== =======================================================
263
+
264
+ .. autosummary::
265
+ :toctree: generated/
266
+
267
+ convert_temperature
268
+
269
+ Energy
270
+ ------
271
+
272
+ ==================== =======================================================
273
+ ``eV`` one electron volt in Joules
274
+ ``electron_volt`` one electron volt in Joules
275
+ ``calorie`` one calorie (thermochemical) in Joules
276
+ ``calorie_th`` one calorie (thermochemical) in Joules
277
+ ``calorie_IT`` one calorie (International Steam Table calorie, 1956) in Joules
278
+ ``erg`` one erg in Joules
279
+ ``Btu`` one British thermal unit (International Steam Table) in Joules
280
+ ``Btu_IT`` one British thermal unit (International Steam Table) in Joules
281
+ ``Btu_th`` one British thermal unit (thermochemical) in Joules
282
+ ``ton_TNT`` one ton of TNT in Joules
283
+ ==================== =======================================================
284
+
285
+ Power
286
+ -----
287
+
288
+ ==================== =======================================================
289
+ ``hp`` one horsepower in watts
290
+ ``horsepower`` one horsepower in watts
291
+ ==================== =======================================================
292
+
293
+ Force
294
+ -----
295
+
296
+ ==================== =======================================================
297
+ ``dyn`` one dyne in newtons
298
+ ``dyne`` one dyne in newtons
299
+ ``lbf`` one pound force in newtons
300
+ ``pound_force`` one pound force in newtons
301
+ ``kgf`` one kilogram force in newtons
302
+ ``kilogram_force`` one kilogram force in newtons
303
+ ==================== =======================================================
304
+
305
+ Optics
306
+ ------
307
+
308
+ .. autosummary::
309
+ :toctree: generated/
310
+
311
+ lambda2nu
312
+ nu2lambda
313
+
314
+ References
315
+ ==========
316
+
317
+ .. [CODATA2018] CODATA Recommended Values of the Fundamental
318
+ Physical Constants 2018.
319
+
320
+ https://physics.nist.gov/cuu/Constants/
321
+
322
+ """ # noqa: E501
323
+ # Modules contributed by BasSw ([email protected])
324
+ from ._codata import *
325
+ from ._constants import *
326
+ from ._codata import _obsolete_constants, physical_constants
327
+
328
+ # Deprecated namespaces, to be removed in v2.0.0
329
+ from . import codata, constants
330
+
331
+ _constant_names_list = [(_k.lower(), _k, _v)
332
+ for _k, _v in physical_constants.items()
333
+ if _k not in _obsolete_constants]
334
+ _constant_names = "\n".join(["``{}``{} {} {}".format(_x[1], " "*(66-len(_x[1])),
335
+ _x[2][0], _x[2][1])
336
+ for _x in sorted(_constant_names_list)])
337
+ if __doc__:
338
+ __doc__ = __doc__ % dict(constant_names=_constant_names)
339
+
340
+ del _constant_names
341
+ del _constant_names_list
342
+
343
+ __all__ = [s for s in dir() if not s.startswith('_')]
344
+
345
+ from scipy._lib._testutils import PytestTester
346
+ test = PytestTester(__name__)
347
+ del PytestTester
llmeval-env/lib/python3.10/site-packages/scipy/constants/_codata.py ADDED
The diff for this file is too large to render. See raw diff
 
llmeval-env/lib/python3.10/site-packages/scipy/constants/_constants.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Collection of physical constants and conversion factors.
3
+
4
+ Most constants are in SI units, so you can do
5
+ print '10 mile per minute is', 10*mile/minute, 'm/s or', 10*mile/(minute*knot), 'knots'
6
+
7
+ The list is not meant to be comprehensive, but just convenient for everyday use.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import math as _math
13
+ from typing import TYPE_CHECKING, Any
14
+
15
+ from ._codata import value as _cd
16
+ import numpy as _np
17
+
18
+ if TYPE_CHECKING:
19
+ import numpy.typing as npt
20
+
21
+ """
22
+ BasSw 2006
23
+ physical constants: imported from CODATA
24
+ unit conversion: see e.g., NIST special publication 811
25
+ Use at own risk: double-check values before calculating your Mars orbit-insertion burn.
26
+ Some constants exist in a few variants, which are marked with suffixes.
27
+ The ones without any suffix should be the most common ones.
28
+ """
29
+
30
+ __all__ = [
31
+ 'Avogadro', 'Boltzmann', 'Btu', 'Btu_IT', 'Btu_th', 'G',
32
+ 'Julian_year', 'N_A', 'Planck', 'R', 'Rydberg',
33
+ 'Stefan_Boltzmann', 'Wien', 'acre', 'alpha',
34
+ 'angstrom', 'arcmin', 'arcminute', 'arcsec',
35
+ 'arcsecond', 'astronomical_unit', 'atm',
36
+ 'atmosphere', 'atomic_mass', 'atto', 'au', 'bar',
37
+ 'barrel', 'bbl', 'blob', 'c', 'calorie',
38
+ 'calorie_IT', 'calorie_th', 'carat', 'centi',
39
+ 'convert_temperature', 'day', 'deci', 'degree',
40
+ 'degree_Fahrenheit', 'deka', 'dyn', 'dyne', 'e',
41
+ 'eV', 'electron_mass', 'electron_volt',
42
+ 'elementary_charge', 'epsilon_0', 'erg',
43
+ 'exa', 'exbi', 'femto', 'fermi', 'fine_structure',
44
+ 'fluid_ounce', 'fluid_ounce_US', 'fluid_ounce_imp',
45
+ 'foot', 'g', 'gallon', 'gallon_US', 'gallon_imp',
46
+ 'gas_constant', 'gibi', 'giga', 'golden', 'golden_ratio',
47
+ 'grain', 'gram', 'gravitational_constant', 'h', 'hbar',
48
+ 'hectare', 'hecto', 'horsepower', 'hour', 'hp',
49
+ 'inch', 'k', 'kgf', 'kibi', 'kilo', 'kilogram_force',
50
+ 'kmh', 'knot', 'lambda2nu', 'lb', 'lbf',
51
+ 'light_year', 'liter', 'litre', 'long_ton', 'm_e',
52
+ 'm_n', 'm_p', 'm_u', 'mach', 'mebi', 'mega',
53
+ 'metric_ton', 'micro', 'micron', 'mil', 'mile',
54
+ 'milli', 'minute', 'mmHg', 'mph', 'mu_0', 'nano',
55
+ 'nautical_mile', 'neutron_mass', 'nu2lambda',
56
+ 'ounce', 'oz', 'parsec', 'pebi', 'peta',
57
+ 'pi', 'pico', 'point', 'pound', 'pound_force',
58
+ 'proton_mass', 'psi', 'pt', 'quecto', 'quetta', 'ronna', 'ronto',
59
+ 'short_ton', 'sigma', 'slinch', 'slug', 'speed_of_light',
60
+ 'speed_of_sound', 'stone', 'survey_foot',
61
+ 'survey_mile', 'tebi', 'tera', 'ton_TNT',
62
+ 'torr', 'troy_ounce', 'troy_pound', 'u',
63
+ 'week', 'yard', 'year', 'yobi', 'yocto',
64
+ 'yotta', 'zebi', 'zepto', 'zero_Celsius', 'zetta'
65
+ ]
66
+
67
+
68
+ # mathematical constants
69
+ pi = _math.pi
70
+ golden = golden_ratio = (1 + _math.sqrt(5)) / 2
71
+
72
+ # SI prefixes
73
+ quetta = 1e30
74
+ ronna = 1e27
75
+ yotta = 1e24
76
+ zetta = 1e21
77
+ exa = 1e18
78
+ peta = 1e15
79
+ tera = 1e12
80
+ giga = 1e9
81
+ mega = 1e6
82
+ kilo = 1e3
83
+ hecto = 1e2
84
+ deka = 1e1
85
+ deci = 1e-1
86
+ centi = 1e-2
87
+ milli = 1e-3
88
+ micro = 1e-6
89
+ nano = 1e-9
90
+ pico = 1e-12
91
+ femto = 1e-15
92
+ atto = 1e-18
93
+ zepto = 1e-21
94
+ yocto = 1e-24
95
+ ronto = 1e-27
96
+ quecto = 1e-30
97
+
98
+ # binary prefixes
99
+ kibi = 2**10
100
+ mebi = 2**20
101
+ gibi = 2**30
102
+ tebi = 2**40
103
+ pebi = 2**50
104
+ exbi = 2**60
105
+ zebi = 2**70
106
+ yobi = 2**80
107
+
108
+ # physical constants
109
+ c = speed_of_light = _cd('speed of light in vacuum')
110
+ mu_0 = _cd('vacuum mag. permeability')
111
+ epsilon_0 = _cd('vacuum electric permittivity')
112
+ h = Planck = _cd('Planck constant')
113
+ hbar = h / (2 * pi)
114
+ G = gravitational_constant = _cd('Newtonian constant of gravitation')
115
+ g = _cd('standard acceleration of gravity')
116
+ e = elementary_charge = _cd('elementary charge')
117
+ R = gas_constant = _cd('molar gas constant')
118
+ alpha = fine_structure = _cd('fine-structure constant')
119
+ N_A = Avogadro = _cd('Avogadro constant')
120
+ k = Boltzmann = _cd('Boltzmann constant')
121
+ sigma = Stefan_Boltzmann = _cd('Stefan-Boltzmann constant')
122
+ Wien = _cd('Wien wavelength displacement law constant')
123
+ Rydberg = _cd('Rydberg constant')
124
+
125
+ # mass in kg
126
+ gram = 1e-3
127
+ metric_ton = 1e3
128
+ grain = 64.79891e-6
129
+ lb = pound = 7000 * grain # avoirdupois
130
+ blob = slinch = pound * g / 0.0254 # lbf*s**2/in (added in 1.0.0)
131
+ slug = blob / 12 # lbf*s**2/foot (added in 1.0.0)
132
+ oz = ounce = pound / 16
133
+ stone = 14 * pound
134
+ long_ton = 2240 * pound
135
+ short_ton = 2000 * pound
136
+
137
+ troy_ounce = 480 * grain # only for metals / gems
138
+ troy_pound = 12 * troy_ounce
139
+ carat = 200e-6
140
+
141
+ m_e = electron_mass = _cd('electron mass')
142
+ m_p = proton_mass = _cd('proton mass')
143
+ m_n = neutron_mass = _cd('neutron mass')
144
+ m_u = u = atomic_mass = _cd('atomic mass constant')
145
+
146
+ # angle in rad
147
+ degree = pi / 180
148
+ arcmin = arcminute = degree / 60
149
+ arcsec = arcsecond = arcmin / 60
150
+
151
+ # time in second
152
+ minute = 60.0
153
+ hour = 60 * minute
154
+ day = 24 * hour
155
+ week = 7 * day
156
+ year = 365 * day
157
+ Julian_year = 365.25 * day
158
+
159
+ # length in meter
160
+ inch = 0.0254
161
+ foot = 12 * inch
162
+ yard = 3 * foot
163
+ mile = 1760 * yard
164
+ mil = inch / 1000
165
+ pt = point = inch / 72 # typography
166
+ survey_foot = 1200.0 / 3937
167
+ survey_mile = 5280 * survey_foot
168
+ nautical_mile = 1852.0
169
+ fermi = 1e-15
170
+ angstrom = 1e-10
171
+ micron = 1e-6
172
+ au = astronomical_unit = 149597870700.0
173
+ light_year = Julian_year * c
174
+ parsec = au / arcsec
175
+
176
+ # pressure in pascal
177
+ atm = atmosphere = _cd('standard atmosphere')
178
+ bar = 1e5
179
+ torr = mmHg = atm / 760
180
+ psi = pound * g / (inch * inch)
181
+
182
+ # area in meter**2
183
+ hectare = 1e4
184
+ acre = 43560 * foot**2
185
+
186
+ # volume in meter**3
187
+ litre = liter = 1e-3
188
+ gallon = gallon_US = 231 * inch**3 # US
189
+ # pint = gallon_US / 8
190
+ fluid_ounce = fluid_ounce_US = gallon_US / 128
191
+ bbl = barrel = 42 * gallon_US # for oil
192
+
193
+ gallon_imp = 4.54609e-3 # UK
194
+ fluid_ounce_imp = gallon_imp / 160
195
+
196
+ # speed in meter per second
197
+ kmh = 1e3 / hour
198
+ mph = mile / hour
199
+ # approx value of mach at 15 degrees in 1 atm. Is this a common value?
200
+ mach = speed_of_sound = 340.5
201
+ knot = nautical_mile / hour
202
+
203
+ # temperature in kelvin
204
+ zero_Celsius = 273.15
205
+ degree_Fahrenheit = 1/1.8 # only for differences
206
+
207
+ # energy in joule
208
+ eV = electron_volt = elementary_charge # * 1 Volt
209
+ calorie = calorie_th = 4.184
210
+ calorie_IT = 4.1868
211
+ erg = 1e-7
212
+ Btu_th = pound * degree_Fahrenheit * calorie_th / gram
213
+ Btu = Btu_IT = pound * degree_Fahrenheit * calorie_IT / gram
214
+ ton_TNT = 1e9 * calorie_th
215
+ # Wh = watt_hour
216
+
217
+ # power in watt
218
+ hp = horsepower = 550 * foot * pound * g
219
+
220
+ # force in newton
221
+ dyn = dyne = 1e-5
222
+ lbf = pound_force = pound * g
223
+ kgf = kilogram_force = g # * 1 kg
224
+
225
+ # functions for conversions that are not linear
226
+
227
+
228
+ def convert_temperature(
229
+ val: npt.ArrayLike,
230
+ old_scale: str,
231
+ new_scale: str,
232
+ ) -> Any:
233
+ """
234
+ Convert from a temperature scale to another one among Celsius, Kelvin,
235
+ Fahrenheit, and Rankine scales.
236
+
237
+ Parameters
238
+ ----------
239
+ val : array_like
240
+ Value(s) of the temperature(s) to be converted expressed in the
241
+ original scale.
242
+ old_scale : str
243
+ Specifies as a string the original scale from which the temperature
244
+ value(s) will be converted. Supported scales are Celsius ('Celsius',
245
+ 'celsius', 'C' or 'c'), Kelvin ('Kelvin', 'kelvin', 'K', 'k'),
246
+ Fahrenheit ('Fahrenheit', 'fahrenheit', 'F' or 'f'), and Rankine
247
+ ('Rankine', 'rankine', 'R', 'r').
248
+ new_scale : str
249
+ Specifies as a string the new scale to which the temperature
250
+ value(s) will be converted. Supported scales are Celsius ('Celsius',
251
+ 'celsius', 'C' or 'c'), Kelvin ('Kelvin', 'kelvin', 'K', 'k'),
252
+ Fahrenheit ('Fahrenheit', 'fahrenheit', 'F' or 'f'), and Rankine
253
+ ('Rankine', 'rankine', 'R', 'r').
254
+
255
+ Returns
256
+ -------
257
+ res : float or array of floats
258
+ Value(s) of the converted temperature(s) expressed in the new scale.
259
+
260
+ Notes
261
+ -----
262
+ .. versionadded:: 0.18.0
263
+
264
+ Examples
265
+ --------
266
+ >>> from scipy.constants import convert_temperature
267
+ >>> import numpy as np
268
+ >>> convert_temperature(np.array([-40, 40]), 'Celsius', 'Kelvin')
269
+ array([ 233.15, 313.15])
270
+
271
+ """
272
+ # Convert from `old_scale` to Kelvin
273
+ if old_scale.lower() in ['celsius', 'c']:
274
+ tempo = _np.asanyarray(val) + zero_Celsius
275
+ elif old_scale.lower() in ['kelvin', 'k']:
276
+ tempo = _np.asanyarray(val)
277
+ elif old_scale.lower() in ['fahrenheit', 'f']:
278
+ tempo = (_np.asanyarray(val) - 32) * 5 / 9 + zero_Celsius
279
+ elif old_scale.lower() in ['rankine', 'r']:
280
+ tempo = _np.asanyarray(val) * 5 / 9
281
+ else:
282
+ raise NotImplementedError("%s scale is unsupported: supported scales "
283
+ "are Celsius, Kelvin, Fahrenheit, and "
284
+ "Rankine" % old_scale)
285
+ # and from Kelvin to `new_scale`.
286
+ if new_scale.lower() in ['celsius', 'c']:
287
+ res = tempo - zero_Celsius
288
+ elif new_scale.lower() in ['kelvin', 'k']:
289
+ res = tempo
290
+ elif new_scale.lower() in ['fahrenheit', 'f']:
291
+ res = (tempo - zero_Celsius) * 9 / 5 + 32
292
+ elif new_scale.lower() in ['rankine', 'r']:
293
+ res = tempo * 9 / 5
294
+ else:
295
+ raise NotImplementedError("'%s' scale is unsupported: supported "
296
+ "scales are 'Celsius', 'Kelvin', "
297
+ "'Fahrenheit', and 'Rankine'" % new_scale)
298
+
299
+ return res
300
+
301
+
302
+ # optics
303
+
304
+
305
+ def lambda2nu(lambda_: npt.ArrayLike) -> Any:
306
+ """
307
+ Convert wavelength to optical frequency
308
+
309
+ Parameters
310
+ ----------
311
+ lambda_ : array_like
312
+ Wavelength(s) to be converted.
313
+
314
+ Returns
315
+ -------
316
+ nu : float or array of floats
317
+ Equivalent optical frequency.
318
+
319
+ Notes
320
+ -----
321
+ Computes ``nu = c / lambda`` where c = 299792458.0, i.e., the
322
+ (vacuum) speed of light in meters/second.
323
+
324
+ Examples
325
+ --------
326
+ >>> from scipy.constants import lambda2nu, speed_of_light
327
+ >>> import numpy as np
328
+ >>> lambda2nu(np.array((1, speed_of_light)))
329
+ array([ 2.99792458e+08, 1.00000000e+00])
330
+
331
+ """
332
+ return c / _np.asanyarray(lambda_)
333
+
334
+
335
+ def nu2lambda(nu: npt.ArrayLike) -> Any:
336
+ """
337
+ Convert optical frequency to wavelength.
338
+
339
+ Parameters
340
+ ----------
341
+ nu : array_like
342
+ Optical frequency to be converted.
343
+
344
+ Returns
345
+ -------
346
+ lambda : float or array of floats
347
+ Equivalent wavelength(s).
348
+
349
+ Notes
350
+ -----
351
+ Computes ``lambda = c / nu`` where c = 299792458.0, i.e., the
352
+ (vacuum) speed of light in meters/second.
353
+
354
+ Examples
355
+ --------
356
+ >>> from scipy.constants import nu2lambda, speed_of_light
357
+ >>> import numpy as np
358
+ >>> nu2lambda(np.array((1, speed_of_light)))
359
+ array([ 2.99792458e+08, 1.00000000e+00])
360
+
361
+ """
362
+ return c / _np.asanyarray(nu)
llmeval-env/lib/python3.10/site-packages/scipy/constants/codata.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.constants` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+ __all__ = [ # noqa: F822
8
+ 'physical_constants', 'value', 'unit', 'precision', 'find',
9
+ 'ConstantWarning', 'txt2002', 'txt2006', 'txt2010', 'txt2014',
10
+ 'txt2018', 'parse_constants_2002to2014',
11
+ 'parse_constants_2018toXXXX', 'k', 'c', 'mu0', 'epsilon0',
12
+ 'exact_values', 'key', 'val', 'v'
13
+
14
+ ]
15
+
16
+
17
+ def __dir__():
18
+ return __all__
19
+
20
+
21
+ def __getattr__(name):
22
+ return _sub_module_deprecation(sub_package="constants", module="codata",
23
+ private_modules=["_codata"], all=__all__,
24
+ attribute=name)
llmeval-env/lib/python3.10/site-packages/scipy/constants/constants.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.constants` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+
8
+ __all__ = [ # noqa: F822
9
+ 'Avogadro', 'Boltzmann', 'Btu', 'Btu_IT', 'Btu_th', 'G',
10
+ 'Julian_year', 'N_A', 'Planck', 'R', 'Rydberg',
11
+ 'Stefan_Boltzmann', 'Wien', 'acre', 'alpha',
12
+ 'angstrom', 'arcmin', 'arcminute', 'arcsec',
13
+ 'arcsecond', 'astronomical_unit', 'atm',
14
+ 'atmosphere', 'atomic_mass', 'atto', 'au', 'bar',
15
+ 'barrel', 'bbl', 'blob', 'c', 'calorie',
16
+ 'calorie_IT', 'calorie_th', 'carat', 'centi',
17
+ 'convert_temperature', 'day', 'deci', 'degree',
18
+ 'degree_Fahrenheit', 'deka', 'dyn', 'dyne', 'e',
19
+ 'eV', 'electron_mass', 'electron_volt',
20
+ 'elementary_charge', 'epsilon_0', 'erg',
21
+ 'exa', 'exbi', 'femto', 'fermi', 'fine_structure',
22
+ 'fluid_ounce', 'fluid_ounce_US', 'fluid_ounce_imp',
23
+ 'foot', 'g', 'gallon', 'gallon_US', 'gallon_imp',
24
+ 'gas_constant', 'gibi', 'giga', 'golden', 'golden_ratio',
25
+ 'grain', 'gram', 'gravitational_constant', 'h', 'hbar',
26
+ 'hectare', 'hecto', 'horsepower', 'hour', 'hp',
27
+ 'inch', 'k', 'kgf', 'kibi', 'kilo', 'kilogram_force',
28
+ 'kmh', 'knot', 'lambda2nu', 'lb', 'lbf',
29
+ 'light_year', 'liter', 'litre', 'long_ton', 'm_e',
30
+ 'm_n', 'm_p', 'm_u', 'mach', 'mebi', 'mega',
31
+ 'metric_ton', 'micro', 'micron', 'mil', 'mile',
32
+ 'milli', 'minute', 'mmHg', 'mph', 'mu_0', 'nano',
33
+ 'nautical_mile', 'neutron_mass', 'nu2lambda',
34
+ 'ounce', 'oz', 'parsec', 'pebi', 'peta',
35
+ 'pi', 'pico', 'point', 'pound', 'pound_force',
36
+ 'proton_mass', 'psi', 'pt', 'short_ton',
37
+ 'sigma', 'slinch', 'slug', 'speed_of_light',
38
+ 'speed_of_sound', 'stone', 'survey_foot',
39
+ 'survey_mile', 'tebi', 'tera', 'ton_TNT',
40
+ 'torr', 'troy_ounce', 'troy_pound', 'u',
41
+ 'week', 'yard', 'year', 'yobi', 'yocto',
42
+ 'yotta', 'zebi', 'zepto', 'zero_Celsius', 'zetta'
43
+ ]
44
+
45
+
46
+ def __dir__():
47
+ return __all__
48
+
49
+
50
+ def __getattr__(name):
51
+ return _sub_module_deprecation(sub_package="constants", module="constants",
52
+ private_modules=["_constants"], all=__all__,
53
+ attribute=name)
llmeval-env/lib/python3.10/site-packages/scipy/constants/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (194 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/__init__.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ =========================================================
3
+ Legacy discrete Fourier transforms (:mod:`scipy.fftpack`)
4
+ =========================================================
5
+
6
+ .. legacy::
7
+
8
+ New code should use :mod:`scipy.fft`.
9
+
10
+ Fast Fourier Transforms (FFTs)
11
+ ==============================
12
+
13
+ .. autosummary::
14
+ :toctree: generated/
15
+
16
+ fft - Fast (discrete) Fourier Transform (FFT)
17
+ ifft - Inverse FFT
18
+ fft2 - 2-D FFT
19
+ ifft2 - 2-D inverse FFT
20
+ fftn - N-D FFT
21
+ ifftn - N-D inverse FFT
22
+ rfft - FFT of strictly real-valued sequence
23
+ irfft - Inverse of rfft
24
+ dct - Discrete cosine transform
25
+ idct - Inverse discrete cosine transform
26
+ dctn - N-D Discrete cosine transform
27
+ idctn - N-D Inverse discrete cosine transform
28
+ dst - Discrete sine transform
29
+ idst - Inverse discrete sine transform
30
+ dstn - N-D Discrete sine transform
31
+ idstn - N-D Inverse discrete sine transform
32
+
33
+ Differential and pseudo-differential operators
34
+ ==============================================
35
+
36
+ .. autosummary::
37
+ :toctree: generated/
38
+
39
+ diff - Differentiation and integration of periodic sequences
40
+ tilbert - Tilbert transform: cs_diff(x,h,h)
41
+ itilbert - Inverse Tilbert transform: sc_diff(x,h,h)
42
+ hilbert - Hilbert transform: cs_diff(x,inf,inf)
43
+ ihilbert - Inverse Hilbert transform: sc_diff(x,inf,inf)
44
+ cs_diff - cosh/sinh pseudo-derivative of periodic sequences
45
+ sc_diff - sinh/cosh pseudo-derivative of periodic sequences
46
+ ss_diff - sinh/sinh pseudo-derivative of periodic sequences
47
+ cc_diff - cosh/cosh pseudo-derivative of periodic sequences
48
+ shift - Shift periodic sequences
49
+
50
+ Helper functions
51
+ ================
52
+
53
+ .. autosummary::
54
+ :toctree: generated/
55
+
56
+ fftshift - Shift the zero-frequency component to the center of the spectrum
57
+ ifftshift - The inverse of `fftshift`
58
+ fftfreq - Return the Discrete Fourier Transform sample frequencies
59
+ rfftfreq - DFT sample frequencies (for usage with rfft, irfft)
60
+ next_fast_len - Find the optimal length to zero-pad an FFT for speed
61
+
62
+ Note that ``fftshift``, ``ifftshift`` and ``fftfreq`` are numpy functions
63
+ exposed by ``fftpack``; importing them from ``numpy`` should be preferred.
64
+
65
+ Convolutions (:mod:`scipy.fftpack.convolve`)
66
+ ============================================
67
+
68
+ .. module:: scipy.fftpack.convolve
69
+
70
+ .. autosummary::
71
+ :toctree: generated/
72
+
73
+ convolve
74
+ convolve_z
75
+ init_convolution_kernel
76
+ destroy_convolve_cache
77
+
78
+ """
79
+
80
+
81
+ __all__ = ['fft','ifft','fftn','ifftn','rfft','irfft',
82
+ 'fft2','ifft2',
83
+ 'diff',
84
+ 'tilbert','itilbert','hilbert','ihilbert',
85
+ 'sc_diff','cs_diff','cc_diff','ss_diff',
86
+ 'shift',
87
+ 'fftfreq', 'rfftfreq',
88
+ 'fftshift', 'ifftshift',
89
+ 'next_fast_len',
90
+ 'dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn'
91
+ ]
92
+
93
+ from ._basic import *
94
+ from ._pseudo_diffs import *
95
+ from ._helper import *
96
+ from ._realtransforms import *
97
+
98
+ # Deprecated namespaces, to be removed in v2.0.0
99
+ from . import basic, helper, pseudo_diffs, realtransforms
100
+
101
+ from scipy._lib._testutils import PytestTester
102
+ test = PytestTester(__name__)
103
+ del PytestTester
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (3.17 kB). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/__pycache__/_basic.cpython-310.pyc ADDED
Binary file (13.2 kB). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/__pycache__/_helper.cpython-310.pyc ADDED
Binary file (3.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/__pycache__/_pseudo_diffs.cpython-310.pyc ADDED
Binary file (12.3 kB). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/__pycache__/_realtransforms.cpython-310.pyc ADDED
Binary file (19.1 kB). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/__pycache__/basic.cpython-310.pyc ADDED
Binary file (646 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/__pycache__/helper.cpython-310.pyc ADDED
Binary file (654 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/__pycache__/pseudo_diffs.cpython-310.pyc ADDED
Binary file (728 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/__pycache__/realtransforms.cpython-310.pyc ADDED
Binary file (671 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/_basic.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Discrete Fourier Transforms - _basic.py
3
+ """
4
+ # Created by Pearu Peterson, August,September 2002
5
+ __all__ = ['fft','ifft','fftn','ifftn','rfft','irfft',
6
+ 'fft2','ifft2']
7
+
8
+ from scipy.fft import _pocketfft
9
+ from ._helper import _good_shape
10
+
11
+
12
+ def fft(x, n=None, axis=-1, overwrite_x=False):
13
+ """
14
+ Return discrete Fourier transform of real or complex sequence.
15
+
16
+ The returned complex array contains ``y(0), y(1),..., y(n-1)``, where
17
+
18
+ ``y(j) = (x * exp(-2*pi*sqrt(-1)*j*np.arange(n)/n)).sum()``.
19
+
20
+ Parameters
21
+ ----------
22
+ x : array_like
23
+ Array to Fourier transform.
24
+ n : int, optional
25
+ Length of the Fourier transform. If ``n < x.shape[axis]``, `x` is
26
+ truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
27
+ default results in ``n = x.shape[axis]``.
28
+ axis : int, optional
29
+ Axis along which the fft's are computed; the default is over the
30
+ last axis (i.e., ``axis=-1``).
31
+ overwrite_x : bool, optional
32
+ If True, the contents of `x` can be destroyed; the default is False.
33
+
34
+ Returns
35
+ -------
36
+ z : complex ndarray
37
+ with the elements::
38
+
39
+ [y(0),y(1),..,y(n/2),y(1-n/2),...,y(-1)] if n is even
40
+ [y(0),y(1),..,y((n-1)/2),y(-(n-1)/2),...,y(-1)] if n is odd
41
+
42
+ where::
43
+
44
+ y(j) = sum[k=0..n-1] x[k] * exp(-sqrt(-1)*j*k* 2*pi/n), j = 0..n-1
45
+
46
+ See Also
47
+ --------
48
+ ifft : Inverse FFT
49
+ rfft : FFT of a real sequence
50
+
51
+ Notes
52
+ -----
53
+ The packing of the result is "standard": If ``A = fft(a, n)``, then
54
+ ``A[0]`` contains the zero-frequency term, ``A[1:n/2]`` contains the
55
+ positive-frequency terms, and ``A[n/2:]`` contains the negative-frequency
56
+ terms, in order of decreasingly negative frequency. So ,for an 8-point
57
+ transform, the frequencies of the result are [0, 1, 2, 3, -4, -3, -2, -1].
58
+ To rearrange the fft output so that the zero-frequency component is
59
+ centered, like [-4, -3, -2, -1, 0, 1, 2, 3], use `fftshift`.
60
+
61
+ Both single and double precision routines are implemented. Half precision
62
+ inputs will be converted to single precision. Non-floating-point inputs
63
+ will be converted to double precision. Long-double precision inputs are
64
+ not supported.
65
+
66
+ This function is most efficient when `n` is a power of two, and least
67
+ efficient when `n` is prime.
68
+
69
+ Note that if ``x`` is real-valued, then ``A[j] == A[n-j].conjugate()``.
70
+ If ``x`` is real-valued and ``n`` is even, then ``A[n/2]`` is real.
71
+
72
+ If the data type of `x` is real, a "real FFT" algorithm is automatically
73
+ used, which roughly halves the computation time. To increase efficiency
74
+ a little further, use `rfft`, which does the same calculation, but only
75
+ outputs half of the symmetrical spectrum. If the data is both real and
76
+ symmetrical, the `dct` can again double the efficiency by generating
77
+ half of the spectrum from half of the signal.
78
+
79
+ Examples
80
+ --------
81
+ >>> import numpy as np
82
+ >>> from scipy.fftpack import fft, ifft
83
+ >>> x = np.arange(5)
84
+ >>> np.allclose(fft(ifft(x)), x, atol=1e-15) # within numerical accuracy.
85
+ True
86
+
87
+ """
88
+ return _pocketfft.fft(x, n, axis, None, overwrite_x)
89
+
90
+
91
+ def ifft(x, n=None, axis=-1, overwrite_x=False):
92
+ """
93
+ Return discrete inverse Fourier transform of real or complex sequence.
94
+
95
+ The returned complex array contains ``y(0), y(1),..., y(n-1)``, where
96
+
97
+ ``y(j) = (x * exp(2*pi*sqrt(-1)*j*np.arange(n)/n)).mean()``.
98
+
99
+ Parameters
100
+ ----------
101
+ x : array_like
102
+ Transformed data to invert.
103
+ n : int, optional
104
+ Length of the inverse Fourier transform. If ``n < x.shape[axis]``,
105
+ `x` is truncated. If ``n > x.shape[axis]``, `x` is zero-padded.
106
+ The default results in ``n = x.shape[axis]``.
107
+ axis : int, optional
108
+ Axis along which the ifft's are computed; the default is over the
109
+ last axis (i.e., ``axis=-1``).
110
+ overwrite_x : bool, optional
111
+ If True, the contents of `x` can be destroyed; the default is False.
112
+
113
+ Returns
114
+ -------
115
+ ifft : ndarray of floats
116
+ The inverse discrete Fourier transform.
117
+
118
+ See Also
119
+ --------
120
+ fft : Forward FFT
121
+
122
+ Notes
123
+ -----
124
+ Both single and double precision routines are implemented. Half precision
125
+ inputs will be converted to single precision. Non-floating-point inputs
126
+ will be converted to double precision. Long-double precision inputs are
127
+ not supported.
128
+
129
+ This function is most efficient when `n` is a power of two, and least
130
+ efficient when `n` is prime.
131
+
132
+ If the data type of `x` is real, a "real IFFT" algorithm is automatically
133
+ used, which roughly halves the computation time.
134
+
135
+ Examples
136
+ --------
137
+ >>> from scipy.fftpack import fft, ifft
138
+ >>> import numpy as np
139
+ >>> x = np.arange(5)
140
+ >>> np.allclose(ifft(fft(x)), x, atol=1e-15) # within numerical accuracy.
141
+ True
142
+
143
+ """
144
+ return _pocketfft.ifft(x, n, axis, None, overwrite_x)
145
+
146
+
147
+ def rfft(x, n=None, axis=-1, overwrite_x=False):
148
+ """
149
+ Discrete Fourier transform of a real sequence.
150
+
151
+ Parameters
152
+ ----------
153
+ x : array_like, real-valued
154
+ The data to transform.
155
+ n : int, optional
156
+ Defines the length of the Fourier transform. If `n` is not specified
157
+ (the default) then ``n = x.shape[axis]``. If ``n < x.shape[axis]``,
158
+ `x` is truncated, if ``n > x.shape[axis]``, `x` is zero-padded.
159
+ axis : int, optional
160
+ The axis along which the transform is applied. The default is the
161
+ last axis.
162
+ overwrite_x : bool, optional
163
+ If set to true, the contents of `x` can be overwritten. Default is
164
+ False.
165
+
166
+ Returns
167
+ -------
168
+ z : real ndarray
169
+ The returned real array contains::
170
+
171
+ [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2))] if n is even
172
+ [y(0),Re(y(1)),Im(y(1)),...,Re(y(n/2)),Im(y(n/2))] if n is odd
173
+
174
+ where::
175
+
176
+ y(j) = sum[k=0..n-1] x[k] * exp(-sqrt(-1)*j*k*2*pi/n)
177
+ j = 0..n-1
178
+
179
+ See Also
180
+ --------
181
+ fft, irfft, scipy.fft.rfft
182
+
183
+ Notes
184
+ -----
185
+ Within numerical accuracy, ``y == rfft(irfft(y))``.
186
+
187
+ Both single and double precision routines are implemented. Half precision
188
+ inputs will be converted to single precision. Non-floating-point inputs
189
+ will be converted to double precision. Long-double precision inputs are
190
+ not supported.
191
+
192
+ To get an output with a complex datatype, consider using the newer
193
+ function `scipy.fft.rfft`.
194
+
195
+ Examples
196
+ --------
197
+ >>> from scipy.fftpack import fft, rfft
198
+ >>> a = [9, -9, 1, 3]
199
+ >>> fft(a)
200
+ array([ 4. +0.j, 8.+12.j, 16. +0.j, 8.-12.j])
201
+ >>> rfft(a)
202
+ array([ 4., 8., 12., 16.])
203
+
204
+ """
205
+ return _pocketfft.rfft_fftpack(x, n, axis, None, overwrite_x)
206
+
207
+
208
+ def irfft(x, n=None, axis=-1, overwrite_x=False):
209
+ """
210
+ Return inverse discrete Fourier transform of real sequence x.
211
+
212
+ The contents of `x` are interpreted as the output of the `rfft`
213
+ function.
214
+
215
+ Parameters
216
+ ----------
217
+ x : array_like
218
+ Transformed data to invert.
219
+ n : int, optional
220
+ Length of the inverse Fourier transform.
221
+ If n < x.shape[axis], x is truncated.
222
+ If n > x.shape[axis], x is zero-padded.
223
+ The default results in n = x.shape[axis].
224
+ axis : int, optional
225
+ Axis along which the ifft's are computed; the default is over
226
+ the last axis (i.e., axis=-1).
227
+ overwrite_x : bool, optional
228
+ If True, the contents of `x` can be destroyed; the default is False.
229
+
230
+ Returns
231
+ -------
232
+ irfft : ndarray of floats
233
+ The inverse discrete Fourier transform.
234
+
235
+ See Also
236
+ --------
237
+ rfft, ifft, scipy.fft.irfft
238
+
239
+ Notes
240
+ -----
241
+ The returned real array contains::
242
+
243
+ [y(0),y(1),...,y(n-1)]
244
+
245
+ where for n is even::
246
+
247
+ y(j) = 1/n (sum[k=1..n/2-1] (x[2*k-1]+sqrt(-1)*x[2*k])
248
+ * exp(sqrt(-1)*j*k* 2*pi/n)
249
+ + c.c. + x[0] + (-1)**(j) x[n-1])
250
+
251
+ and for n is odd::
252
+
253
+ y(j) = 1/n (sum[k=1..(n-1)/2] (x[2*k-1]+sqrt(-1)*x[2*k])
254
+ * exp(sqrt(-1)*j*k* 2*pi/n)
255
+ + c.c. + x[0])
256
+
257
+ c.c. denotes complex conjugate of preceding expression.
258
+
259
+ For details on input parameters, see `rfft`.
260
+
261
+ To process (conjugate-symmetric) frequency-domain data with a complex
262
+ datatype, consider using the newer function `scipy.fft.irfft`.
263
+
264
+ Examples
265
+ --------
266
+ >>> from scipy.fftpack import rfft, irfft
267
+ >>> a = [1.0, 2.0, 3.0, 4.0, 5.0]
268
+ >>> irfft(a)
269
+ array([ 2.6 , -3.16405192, 1.24398433, -1.14955713, 1.46962473])
270
+ >>> irfft(rfft(a))
271
+ array([1., 2., 3., 4., 5.])
272
+
273
+ """
274
+ return _pocketfft.irfft_fftpack(x, n, axis, None, overwrite_x)
275
+
276
+
277
+ def fftn(x, shape=None, axes=None, overwrite_x=False):
278
+ """
279
+ Return multidimensional discrete Fourier transform.
280
+
281
+ The returned array contains::
282
+
283
+ y[j_1,..,j_d] = sum[k_1=0..n_1-1, ..., k_d=0..n_d-1]
284
+ x[k_1,..,k_d] * prod[i=1..d] exp(-sqrt(-1)*2*pi/n_i * j_i * k_i)
285
+
286
+ where d = len(x.shape) and n = x.shape.
287
+
288
+ Parameters
289
+ ----------
290
+ x : array_like
291
+ The (N-D) array to transform.
292
+ shape : int or array_like of ints or None, optional
293
+ The shape of the result. If both `shape` and `axes` (see below) are
294
+ None, `shape` is ``x.shape``; if `shape` is None but `axes` is
295
+ not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
296
+ If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
297
+ If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
298
+ length ``shape[i]``.
299
+ If any element of `shape` is -1, the size of the corresponding
300
+ dimension of `x` is used.
301
+ axes : int or array_like of ints or None, optional
302
+ The axes of `x` (`y` if `shape` is not None) along which the
303
+ transform is applied.
304
+ The default is over all axes.
305
+ overwrite_x : bool, optional
306
+ If True, the contents of `x` can be destroyed. Default is False.
307
+
308
+ Returns
309
+ -------
310
+ y : complex-valued N-D NumPy array
311
+ The (N-D) DFT of the input array.
312
+
313
+ See Also
314
+ --------
315
+ ifftn
316
+
317
+ Notes
318
+ -----
319
+ If ``x`` is real-valued, then
320
+ ``y[..., j_i, ...] == y[..., n_i-j_i, ...].conjugate()``.
321
+
322
+ Both single and double precision routines are implemented. Half precision
323
+ inputs will be converted to single precision. Non-floating-point inputs
324
+ will be converted to double precision. Long-double precision inputs are
325
+ not supported.
326
+
327
+ Examples
328
+ --------
329
+ >>> import numpy as np
330
+ >>> from scipy.fftpack import fftn, ifftn
331
+ >>> y = (-np.arange(16), 8 - np.arange(16), np.arange(16))
332
+ >>> np.allclose(y, fftn(ifftn(y)))
333
+ True
334
+
335
+ """
336
+ shape = _good_shape(x, shape, axes)
337
+ return _pocketfft.fftn(x, shape, axes, None, overwrite_x)
338
+
339
+
340
+ def ifftn(x, shape=None, axes=None, overwrite_x=False):
341
+ """
342
+ Return inverse multidimensional discrete Fourier transform.
343
+
344
+ The sequence can be of an arbitrary type.
345
+
346
+ The returned array contains::
347
+
348
+ y[j_1,..,j_d] = 1/p * sum[k_1=0..n_1-1, ..., k_d=0..n_d-1]
349
+ x[k_1,..,k_d] * prod[i=1..d] exp(sqrt(-1)*2*pi/n_i * j_i * k_i)
350
+
351
+ where ``d = len(x.shape)``, ``n = x.shape``, and ``p = prod[i=1..d] n_i``.
352
+
353
+ For description of parameters see `fftn`.
354
+
355
+ See Also
356
+ --------
357
+ fftn : for detailed information.
358
+
359
+ Examples
360
+ --------
361
+ >>> from scipy.fftpack import fftn, ifftn
362
+ >>> import numpy as np
363
+ >>> y = (-np.arange(16), 8 - np.arange(16), np.arange(16))
364
+ >>> np.allclose(y, ifftn(fftn(y)))
365
+ True
366
+
367
+ """
368
+ shape = _good_shape(x, shape, axes)
369
+ return _pocketfft.ifftn(x, shape, axes, None, overwrite_x)
370
+
371
+
372
+ def fft2(x, shape=None, axes=(-2,-1), overwrite_x=False):
373
+ """
374
+ 2-D discrete Fourier transform.
375
+
376
+ Return the 2-D discrete Fourier transform of the 2-D argument
377
+ `x`.
378
+
379
+ See Also
380
+ --------
381
+ fftn : for detailed information.
382
+
383
+ Examples
384
+ --------
385
+ >>> import numpy as np
386
+ >>> from scipy.fftpack import fft2, ifft2
387
+ >>> y = np.mgrid[:5, :5][0]
388
+ >>> y
389
+ array([[0, 0, 0, 0, 0],
390
+ [1, 1, 1, 1, 1],
391
+ [2, 2, 2, 2, 2],
392
+ [3, 3, 3, 3, 3],
393
+ [4, 4, 4, 4, 4]])
394
+ >>> np.allclose(y, ifft2(fft2(y)))
395
+ True
396
+ """
397
+ return fftn(x,shape,axes,overwrite_x)
398
+
399
+
400
+ def ifft2(x, shape=None, axes=(-2,-1), overwrite_x=False):
401
+ """
402
+ 2-D discrete inverse Fourier transform of real or complex sequence.
403
+
404
+ Return inverse 2-D discrete Fourier transform of
405
+ arbitrary type sequence x.
406
+
407
+ See `ifft` for more information.
408
+
409
+ See Also
410
+ --------
411
+ fft2, ifft
412
+
413
+ Examples
414
+ --------
415
+ >>> import numpy as np
416
+ >>> from scipy.fftpack import fft2, ifft2
417
+ >>> y = np.mgrid[:5, :5][0]
418
+ >>> y
419
+ array([[0, 0, 0, 0, 0],
420
+ [1, 1, 1, 1, 1],
421
+ [2, 2, 2, 2, 2],
422
+ [3, 3, 3, 3, 3],
423
+ [4, 4, 4, 4, 4]])
424
+ >>> np.allclose(y, fft2(ifft2(y)))
425
+ True
426
+
427
+ """
428
+ return ifftn(x,shape,axes,overwrite_x)
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/_helper.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import operator
2
+
3
+ import numpy as np
4
+ from numpy.fft import fftshift, ifftshift, fftfreq
5
+
6
+ import scipy.fft._pocketfft.helper as _helper
7
+
8
+ __all__ = ['fftshift', 'ifftshift', 'fftfreq', 'rfftfreq', 'next_fast_len']
9
+
10
+
11
+ def rfftfreq(n, d=1.0):
12
+ """DFT sample frequencies (for usage with rfft, irfft).
13
+
14
+ The returned float array contains the frequency bins in
15
+ cycles/unit (with zero at the start) given a window length `n` and a
16
+ sample spacing `d`::
17
+
18
+ f = [0,1,1,2,2,...,n/2-1,n/2-1,n/2]/(d*n) if n is even
19
+ f = [0,1,1,2,2,...,n/2-1,n/2-1,n/2,n/2]/(d*n) if n is odd
20
+
21
+ Parameters
22
+ ----------
23
+ n : int
24
+ Window length.
25
+ d : scalar, optional
26
+ Sample spacing. Default is 1.
27
+
28
+ Returns
29
+ -------
30
+ out : ndarray
31
+ The array of length `n`, containing the sample frequencies.
32
+
33
+ Examples
34
+ --------
35
+ >>> import numpy as np
36
+ >>> from scipy import fftpack
37
+ >>> sig = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float)
38
+ >>> sig_fft = fftpack.rfft(sig)
39
+ >>> n = sig_fft.size
40
+ >>> timestep = 0.1
41
+ >>> freq = fftpack.rfftfreq(n, d=timestep)
42
+ >>> freq
43
+ array([ 0. , 1.25, 1.25, 2.5 , 2.5 , 3.75, 3.75, 5. ])
44
+
45
+ """
46
+ n = operator.index(n)
47
+ if n < 0:
48
+ raise ValueError("n = %s is not valid. "
49
+ "n must be a nonnegative integer." % n)
50
+
51
+ return (np.arange(1, n + 1, dtype=int) // 2) / float(n * d)
52
+
53
+
54
+ def next_fast_len(target):
55
+ """
56
+ Find the next fast size of input data to `fft`, for zero-padding, etc.
57
+
58
+ SciPy's FFTPACK has efficient functions for radix {2, 3, 4, 5}, so this
59
+ returns the next composite of the prime factors 2, 3, and 5 which is
60
+ greater than or equal to `target`. (These are also known as 5-smooth
61
+ numbers, regular numbers, or Hamming numbers.)
62
+
63
+ Parameters
64
+ ----------
65
+ target : int
66
+ Length to start searching from. Must be a positive integer.
67
+
68
+ Returns
69
+ -------
70
+ out : int
71
+ The first 5-smooth number greater than or equal to `target`.
72
+
73
+ Notes
74
+ -----
75
+ .. versionadded:: 0.18.0
76
+
77
+ Examples
78
+ --------
79
+ On a particular machine, an FFT of prime length takes 133 ms:
80
+
81
+ >>> from scipy import fftpack
82
+ >>> import numpy as np
83
+ >>> rng = np.random.default_rng()
84
+ >>> min_len = 10007 # prime length is worst case for speed
85
+ >>> a = rng.standard_normal(min_len)
86
+ >>> b = fftpack.fft(a)
87
+
88
+ Zero-padding to the next 5-smooth length reduces computation time to
89
+ 211 us, a speedup of 630 times:
90
+
91
+ >>> fftpack.next_fast_len(min_len)
92
+ 10125
93
+ >>> b = fftpack.fft(a, 10125)
94
+
95
+ Rounding up to the next power of 2 is not optimal, taking 367 us to
96
+ compute, 1.7 times as long as the 5-smooth size:
97
+
98
+ >>> b = fftpack.fft(a, 16384)
99
+
100
+ """
101
+ # Real transforms use regular sizes so this is backwards compatible
102
+ return _helper.good_size(target, True)
103
+
104
+
105
+ def _good_shape(x, shape, axes):
106
+ """Ensure that shape argument is valid for scipy.fftpack
107
+
108
+ scipy.fftpack does not support len(shape) < x.ndim when axes is not given.
109
+ """
110
+ if shape is not None and axes is None:
111
+ shape = _helper._iterable_of_int(shape, 'shape')
112
+ if len(shape) != np.ndim(x):
113
+ raise ValueError("when given, axes and shape arguments"
114
+ " have to be of the same length")
115
+ return shape
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/_pseudo_diffs.py ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Differential and pseudo-differential operators.
3
+ """
4
+ # Created by Pearu Peterson, September 2002
5
+
6
+ __all__ = ['diff',
7
+ 'tilbert','itilbert','hilbert','ihilbert',
8
+ 'cs_diff','cc_diff','sc_diff','ss_diff',
9
+ 'shift']
10
+
11
+ from numpy import pi, asarray, sin, cos, sinh, cosh, tanh, iscomplexobj
12
+ from . import convolve
13
+
14
+ from scipy.fft._pocketfft.helper import _datacopied
15
+
16
+
17
+ _cache = {}
18
+
19
+
20
+ def diff(x,order=1,period=None, _cache=_cache):
21
+ """
22
+ Return kth derivative (or integral) of a periodic sequence x.
23
+
24
+ If x_j and y_j are Fourier coefficients of periodic functions x
25
+ and y, respectively, then::
26
+
27
+ y_j = pow(sqrt(-1)*j*2*pi/period, order) * x_j
28
+ y_0 = 0 if order is not 0.
29
+
30
+ Parameters
31
+ ----------
32
+ x : array_like
33
+ Input array.
34
+ order : int, optional
35
+ The order of differentiation. Default order is 1. If order is
36
+ negative, then integration is carried out under the assumption
37
+ that ``x_0 == 0``.
38
+ period : float, optional
39
+ The assumed period of the sequence. Default is ``2*pi``.
40
+
41
+ Notes
42
+ -----
43
+ If ``sum(x, axis=0) = 0`` then ``diff(diff(x, k), -k) == x`` (within
44
+ numerical accuracy).
45
+
46
+ For odd order and even ``len(x)``, the Nyquist mode is taken zero.
47
+
48
+ """
49
+ tmp = asarray(x)
50
+ if order == 0:
51
+ return tmp
52
+ if iscomplexobj(tmp):
53
+ return diff(tmp.real,order,period)+1j*diff(tmp.imag,order,period)
54
+ if period is not None:
55
+ c = 2*pi/period
56
+ else:
57
+ c = 1.0
58
+ n = len(x)
59
+ omega = _cache.get((n,order,c))
60
+ if omega is None:
61
+ if len(_cache) > 20:
62
+ while _cache:
63
+ _cache.popitem()
64
+
65
+ def kernel(k,order=order,c=c):
66
+ if k:
67
+ return pow(c*k,order)
68
+ return 0
69
+ omega = convolve.init_convolution_kernel(n,kernel,d=order,
70
+ zero_nyquist=1)
71
+ _cache[(n,order,c)] = omega
72
+ overwrite_x = _datacopied(tmp, x)
73
+ return convolve.convolve(tmp,omega,swap_real_imag=order % 2,
74
+ overwrite_x=overwrite_x)
75
+
76
+
77
+ del _cache
78
+
79
+
80
+ _cache = {}
81
+
82
+
83
+ def tilbert(x, h, period=None, _cache=_cache):
84
+ """
85
+ Return h-Tilbert transform of a periodic sequence x.
86
+
87
+ If x_j and y_j are Fourier coefficients of periodic functions x
88
+ and y, respectively, then::
89
+
90
+ y_j = sqrt(-1)*coth(j*h*2*pi/period) * x_j
91
+ y_0 = 0
92
+
93
+ Parameters
94
+ ----------
95
+ x : array_like
96
+ The input array to transform.
97
+ h : float
98
+ Defines the parameter of the Tilbert transform.
99
+ period : float, optional
100
+ The assumed period of the sequence. Default period is ``2*pi``.
101
+
102
+ Returns
103
+ -------
104
+ tilbert : ndarray
105
+ The result of the transform.
106
+
107
+ Notes
108
+ -----
109
+ If ``sum(x, axis=0) == 0`` and ``n = len(x)`` is odd, then
110
+ ``tilbert(itilbert(x)) == x``.
111
+
112
+ If ``2 * pi * h / period`` is approximately 10 or larger, then
113
+ numerically ``tilbert == hilbert``
114
+ (theoretically oo-Tilbert == Hilbert).
115
+
116
+ For even ``len(x)``, the Nyquist mode of ``x`` is taken zero.
117
+
118
+ """
119
+ tmp = asarray(x)
120
+ if iscomplexobj(tmp):
121
+ return tilbert(tmp.real, h, period) + \
122
+ 1j * tilbert(tmp.imag, h, period)
123
+
124
+ if period is not None:
125
+ h = h * 2 * pi / period
126
+
127
+ n = len(x)
128
+ omega = _cache.get((n, h))
129
+ if omega is None:
130
+ if len(_cache) > 20:
131
+ while _cache:
132
+ _cache.popitem()
133
+
134
+ def kernel(k, h=h):
135
+ if k:
136
+ return 1.0/tanh(h*k)
137
+
138
+ return 0
139
+
140
+ omega = convolve.init_convolution_kernel(n, kernel, d=1)
141
+ _cache[(n,h)] = omega
142
+
143
+ overwrite_x = _datacopied(tmp, x)
144
+ return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
145
+
146
+
147
+ del _cache
148
+
149
+
150
+ _cache = {}
151
+
152
+
153
+ def itilbert(x,h,period=None, _cache=_cache):
154
+ """
155
+ Return inverse h-Tilbert transform of a periodic sequence x.
156
+
157
+ If ``x_j`` and ``y_j`` are Fourier coefficients of periodic functions x
158
+ and y, respectively, then::
159
+
160
+ y_j = -sqrt(-1)*tanh(j*h*2*pi/period) * x_j
161
+ y_0 = 0
162
+
163
+ For more details, see `tilbert`.
164
+
165
+ """
166
+ tmp = asarray(x)
167
+ if iscomplexobj(tmp):
168
+ return itilbert(tmp.real,h,period) + \
169
+ 1j*itilbert(tmp.imag,h,period)
170
+ if period is not None:
171
+ h = h*2*pi/period
172
+ n = len(x)
173
+ omega = _cache.get((n,h))
174
+ if omega is None:
175
+ if len(_cache) > 20:
176
+ while _cache:
177
+ _cache.popitem()
178
+
179
+ def kernel(k,h=h):
180
+ if k:
181
+ return -tanh(h*k)
182
+ return 0
183
+ omega = convolve.init_convolution_kernel(n,kernel,d=1)
184
+ _cache[(n,h)] = omega
185
+ overwrite_x = _datacopied(tmp, x)
186
+ return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
187
+
188
+
189
+ del _cache
190
+
191
+
192
+ _cache = {}
193
+
194
+
195
+ def hilbert(x, _cache=_cache):
196
+ """
197
+ Return Hilbert transform of a periodic sequence x.
198
+
199
+ If x_j and y_j are Fourier coefficients of periodic functions x
200
+ and y, respectively, then::
201
+
202
+ y_j = sqrt(-1)*sign(j) * x_j
203
+ y_0 = 0
204
+
205
+ Parameters
206
+ ----------
207
+ x : array_like
208
+ The input array, should be periodic.
209
+ _cache : dict, optional
210
+ Dictionary that contains the kernel used to do a convolution with.
211
+
212
+ Returns
213
+ -------
214
+ y : ndarray
215
+ The transformed input.
216
+
217
+ See Also
218
+ --------
219
+ scipy.signal.hilbert : Compute the analytic signal, using the Hilbert
220
+ transform.
221
+
222
+ Notes
223
+ -----
224
+ If ``sum(x, axis=0) == 0`` then ``hilbert(ihilbert(x)) == x``.
225
+
226
+ For even len(x), the Nyquist mode of x is taken zero.
227
+
228
+ The sign of the returned transform does not have a factor -1 that is more
229
+ often than not found in the definition of the Hilbert transform. Note also
230
+ that `scipy.signal.hilbert` does have an extra -1 factor compared to this
231
+ function.
232
+
233
+ """
234
+ tmp = asarray(x)
235
+ if iscomplexobj(tmp):
236
+ return hilbert(tmp.real)+1j*hilbert(tmp.imag)
237
+ n = len(x)
238
+ omega = _cache.get(n)
239
+ if omega is None:
240
+ if len(_cache) > 20:
241
+ while _cache:
242
+ _cache.popitem()
243
+
244
+ def kernel(k):
245
+ if k > 0:
246
+ return 1.0
247
+ elif k < 0:
248
+ return -1.0
249
+ return 0.0
250
+ omega = convolve.init_convolution_kernel(n,kernel,d=1)
251
+ _cache[n] = omega
252
+ overwrite_x = _datacopied(tmp, x)
253
+ return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
254
+
255
+
256
+ del _cache
257
+
258
+
259
+ def ihilbert(x):
260
+ """
261
+ Return inverse Hilbert transform of a periodic sequence x.
262
+
263
+ If ``x_j`` and ``y_j`` are Fourier coefficients of periodic functions x
264
+ and y, respectively, then::
265
+
266
+ y_j = -sqrt(-1)*sign(j) * x_j
267
+ y_0 = 0
268
+
269
+ """
270
+ return -hilbert(x)
271
+
272
+
273
+ _cache = {}
274
+
275
+
276
+ def cs_diff(x, a, b, period=None, _cache=_cache):
277
+ """
278
+ Return (a,b)-cosh/sinh pseudo-derivative of a periodic sequence.
279
+
280
+ If ``x_j`` and ``y_j`` are Fourier coefficients of periodic functions x
281
+ and y, respectively, then::
282
+
283
+ y_j = -sqrt(-1)*cosh(j*a*2*pi/period)/sinh(j*b*2*pi/period) * x_j
284
+ y_0 = 0
285
+
286
+ Parameters
287
+ ----------
288
+ x : array_like
289
+ The array to take the pseudo-derivative from.
290
+ a, b : float
291
+ Defines the parameters of the cosh/sinh pseudo-differential
292
+ operator.
293
+ period : float, optional
294
+ The period of the sequence. Default period is ``2*pi``.
295
+
296
+ Returns
297
+ -------
298
+ cs_diff : ndarray
299
+ Pseudo-derivative of periodic sequence `x`.
300
+
301
+ Notes
302
+ -----
303
+ For even len(`x`), the Nyquist mode of `x` is taken as zero.
304
+
305
+ """
306
+ tmp = asarray(x)
307
+ if iscomplexobj(tmp):
308
+ return cs_diff(tmp.real,a,b,period) + \
309
+ 1j*cs_diff(tmp.imag,a,b,period)
310
+ if period is not None:
311
+ a = a*2*pi/period
312
+ b = b*2*pi/period
313
+ n = len(x)
314
+ omega = _cache.get((n,a,b))
315
+ if omega is None:
316
+ if len(_cache) > 20:
317
+ while _cache:
318
+ _cache.popitem()
319
+
320
+ def kernel(k,a=a,b=b):
321
+ if k:
322
+ return -cosh(a*k)/sinh(b*k)
323
+ return 0
324
+ omega = convolve.init_convolution_kernel(n,kernel,d=1)
325
+ _cache[(n,a,b)] = omega
326
+ overwrite_x = _datacopied(tmp, x)
327
+ return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
328
+
329
+
330
+ del _cache
331
+
332
+
333
+ _cache = {}
334
+
335
+
336
+ def sc_diff(x, a, b, period=None, _cache=_cache):
337
+ """
338
+ Return (a,b)-sinh/cosh pseudo-derivative of a periodic sequence x.
339
+
340
+ If x_j and y_j are Fourier coefficients of periodic functions x
341
+ and y, respectively, then::
342
+
343
+ y_j = sqrt(-1)*sinh(j*a*2*pi/period)/cosh(j*b*2*pi/period) * x_j
344
+ y_0 = 0
345
+
346
+ Parameters
347
+ ----------
348
+ x : array_like
349
+ Input array.
350
+ a,b : float
351
+ Defines the parameters of the sinh/cosh pseudo-differential
352
+ operator.
353
+ period : float, optional
354
+ The period of the sequence x. Default is 2*pi.
355
+
356
+ Notes
357
+ -----
358
+ ``sc_diff(cs_diff(x,a,b),b,a) == x``
359
+ For even ``len(x)``, the Nyquist mode of x is taken as zero.
360
+
361
+ """
362
+ tmp = asarray(x)
363
+ if iscomplexobj(tmp):
364
+ return sc_diff(tmp.real,a,b,period) + \
365
+ 1j*sc_diff(tmp.imag,a,b,period)
366
+ if period is not None:
367
+ a = a*2*pi/period
368
+ b = b*2*pi/period
369
+ n = len(x)
370
+ omega = _cache.get((n,a,b))
371
+ if omega is None:
372
+ if len(_cache) > 20:
373
+ while _cache:
374
+ _cache.popitem()
375
+
376
+ def kernel(k,a=a,b=b):
377
+ if k:
378
+ return sinh(a*k)/cosh(b*k)
379
+ return 0
380
+ omega = convolve.init_convolution_kernel(n,kernel,d=1)
381
+ _cache[(n,a,b)] = omega
382
+ overwrite_x = _datacopied(tmp, x)
383
+ return convolve.convolve(tmp,omega,swap_real_imag=1,overwrite_x=overwrite_x)
384
+
385
+
386
+ del _cache
387
+
388
+
389
+ _cache = {}
390
+
391
+
392
+ def ss_diff(x, a, b, period=None, _cache=_cache):
393
+ """
394
+ Return (a,b)-sinh/sinh pseudo-derivative of a periodic sequence x.
395
+
396
+ If x_j and y_j are Fourier coefficients of periodic functions x
397
+ and y, respectively, then::
398
+
399
+ y_j = sinh(j*a*2*pi/period)/sinh(j*b*2*pi/period) * x_j
400
+ y_0 = a/b * x_0
401
+
402
+ Parameters
403
+ ----------
404
+ x : array_like
405
+ The array to take the pseudo-derivative from.
406
+ a,b
407
+ Defines the parameters of the sinh/sinh pseudo-differential
408
+ operator.
409
+ period : float, optional
410
+ The period of the sequence x. Default is ``2*pi``.
411
+
412
+ Notes
413
+ -----
414
+ ``ss_diff(ss_diff(x,a,b),b,a) == x``
415
+
416
+ """
417
+ tmp = asarray(x)
418
+ if iscomplexobj(tmp):
419
+ return ss_diff(tmp.real,a,b,period) + \
420
+ 1j*ss_diff(tmp.imag,a,b,period)
421
+ if period is not None:
422
+ a = a*2*pi/period
423
+ b = b*2*pi/period
424
+ n = len(x)
425
+ omega = _cache.get((n,a,b))
426
+ if omega is None:
427
+ if len(_cache) > 20:
428
+ while _cache:
429
+ _cache.popitem()
430
+
431
+ def kernel(k,a=a,b=b):
432
+ if k:
433
+ return sinh(a*k)/sinh(b*k)
434
+ return float(a)/b
435
+ omega = convolve.init_convolution_kernel(n,kernel)
436
+ _cache[(n,a,b)] = omega
437
+ overwrite_x = _datacopied(tmp, x)
438
+ return convolve.convolve(tmp,omega,overwrite_x=overwrite_x)
439
+
440
+
441
+ del _cache
442
+
443
+
444
+ _cache = {}
445
+
446
+
447
+ def cc_diff(x, a, b, period=None, _cache=_cache):
448
+ """
449
+ Return (a,b)-cosh/cosh pseudo-derivative of a periodic sequence.
450
+
451
+ If x_j and y_j are Fourier coefficients of periodic functions x
452
+ and y, respectively, then::
453
+
454
+ y_j = cosh(j*a*2*pi/period)/cosh(j*b*2*pi/period) * x_j
455
+
456
+ Parameters
457
+ ----------
458
+ x : array_like
459
+ The array to take the pseudo-derivative from.
460
+ a,b : float
461
+ Defines the parameters of the sinh/sinh pseudo-differential
462
+ operator.
463
+ period : float, optional
464
+ The period of the sequence x. Default is ``2*pi``.
465
+
466
+ Returns
467
+ -------
468
+ cc_diff : ndarray
469
+ Pseudo-derivative of periodic sequence `x`.
470
+
471
+ Notes
472
+ -----
473
+ ``cc_diff(cc_diff(x,a,b),b,a) == x``
474
+
475
+ """
476
+ tmp = asarray(x)
477
+ if iscomplexobj(tmp):
478
+ return cc_diff(tmp.real,a,b,period) + \
479
+ 1j*cc_diff(tmp.imag,a,b,period)
480
+ if period is not None:
481
+ a = a*2*pi/period
482
+ b = b*2*pi/period
483
+ n = len(x)
484
+ omega = _cache.get((n,a,b))
485
+ if omega is None:
486
+ if len(_cache) > 20:
487
+ while _cache:
488
+ _cache.popitem()
489
+
490
+ def kernel(k,a=a,b=b):
491
+ return cosh(a*k)/cosh(b*k)
492
+ omega = convolve.init_convolution_kernel(n,kernel)
493
+ _cache[(n,a,b)] = omega
494
+ overwrite_x = _datacopied(tmp, x)
495
+ return convolve.convolve(tmp,omega,overwrite_x=overwrite_x)
496
+
497
+
498
+ del _cache
499
+
500
+
501
+ _cache = {}
502
+
503
+
504
+ def shift(x, a, period=None, _cache=_cache):
505
+ """
506
+ Shift periodic sequence x by a: y(u) = x(u+a).
507
+
508
+ If x_j and y_j are Fourier coefficients of periodic functions x
509
+ and y, respectively, then::
510
+
511
+ y_j = exp(j*a*2*pi/period*sqrt(-1)) * x_f
512
+
513
+ Parameters
514
+ ----------
515
+ x : array_like
516
+ The array to take the pseudo-derivative from.
517
+ a : float
518
+ Defines the parameters of the sinh/sinh pseudo-differential
519
+ period : float, optional
520
+ The period of the sequences x and y. Default period is ``2*pi``.
521
+ """
522
+ tmp = asarray(x)
523
+ if iscomplexobj(tmp):
524
+ return shift(tmp.real,a,period)+1j*shift(tmp.imag,a,period)
525
+ if period is not None:
526
+ a = a*2*pi/period
527
+ n = len(x)
528
+ omega = _cache.get((n,a))
529
+ if omega is None:
530
+ if len(_cache) > 20:
531
+ while _cache:
532
+ _cache.popitem()
533
+
534
+ def kernel_real(k,a=a):
535
+ return cos(a*k)
536
+
537
+ def kernel_imag(k,a=a):
538
+ return sin(a*k)
539
+ omega_real = convolve.init_convolution_kernel(n,kernel_real,d=0,
540
+ zero_nyquist=0)
541
+ omega_imag = convolve.init_convolution_kernel(n,kernel_imag,d=1,
542
+ zero_nyquist=0)
543
+ _cache[(n,a)] = omega_real,omega_imag
544
+ else:
545
+ omega_real,omega_imag = omega
546
+ overwrite_x = _datacopied(tmp, x)
547
+ return convolve.convolve_z(tmp,omega_real,omega_imag,
548
+ overwrite_x=overwrite_x)
549
+
550
+
551
+ del _cache
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/_realtransforms.py ADDED
@@ -0,0 +1,598 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Real spectrum transforms (DCT, DST, MDCT)
3
+ """
4
+
5
+ __all__ = ['dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn']
6
+
7
+ from scipy.fft import _pocketfft
8
+ from ._helper import _good_shape
9
+
10
+ _inverse_typemap = {1: 1, 2: 3, 3: 2, 4: 4}
11
+
12
+
13
+ def dctn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
14
+ """
15
+ Return multidimensional Discrete Cosine Transform along the specified axes.
16
+
17
+ Parameters
18
+ ----------
19
+ x : array_like
20
+ The input array.
21
+ type : {1, 2, 3, 4}, optional
22
+ Type of the DCT (see Notes). Default type is 2.
23
+ shape : int or array_like of ints or None, optional
24
+ The shape of the result. If both `shape` and `axes` (see below) are
25
+ None, `shape` is ``x.shape``; if `shape` is None but `axes` is
26
+ not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
27
+ If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
28
+ If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
29
+ length ``shape[i]``.
30
+ If any element of `shape` is -1, the size of the corresponding
31
+ dimension of `x` is used.
32
+ axes : int or array_like of ints or None, optional
33
+ Axes along which the DCT is computed.
34
+ The default is over all axes.
35
+ norm : {None, 'ortho'}, optional
36
+ Normalization mode (see Notes). Default is None.
37
+ overwrite_x : bool, optional
38
+ If True, the contents of `x` can be destroyed; the default is False.
39
+
40
+ Returns
41
+ -------
42
+ y : ndarray of real
43
+ The transformed input array.
44
+
45
+ See Also
46
+ --------
47
+ idctn : Inverse multidimensional DCT
48
+
49
+ Notes
50
+ -----
51
+ For full details of the DCT types and normalization modes, as well as
52
+ references, see `dct`.
53
+
54
+ Examples
55
+ --------
56
+ >>> import numpy as np
57
+ >>> from scipy.fftpack import dctn, idctn
58
+ >>> rng = np.random.default_rng()
59
+ >>> y = rng.standard_normal((16, 16))
60
+ >>> np.allclose(y, idctn(dctn(y, norm='ortho'), norm='ortho'))
61
+ True
62
+
63
+ """
64
+ shape = _good_shape(x, shape, axes)
65
+ return _pocketfft.dctn(x, type, shape, axes, norm, overwrite_x)
66
+
67
+
68
+ def idctn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
69
+ """
70
+ Return multidimensional Discrete Cosine Transform along the specified axes.
71
+
72
+ Parameters
73
+ ----------
74
+ x : array_like
75
+ The input array.
76
+ type : {1, 2, 3, 4}, optional
77
+ Type of the DCT (see Notes). Default type is 2.
78
+ shape : int or array_like of ints or None, optional
79
+ The shape of the result. If both `shape` and `axes` (see below) are
80
+ None, `shape` is ``x.shape``; if `shape` is None but `axes` is
81
+ not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
82
+ If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
83
+ If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
84
+ length ``shape[i]``.
85
+ If any element of `shape` is -1, the size of the corresponding
86
+ dimension of `x` is used.
87
+ axes : int or array_like of ints or None, optional
88
+ Axes along which the IDCT is computed.
89
+ The default is over all axes.
90
+ norm : {None, 'ortho'}, optional
91
+ Normalization mode (see Notes). Default is None.
92
+ overwrite_x : bool, optional
93
+ If True, the contents of `x` can be destroyed; the default is False.
94
+
95
+ Returns
96
+ -------
97
+ y : ndarray of real
98
+ The transformed input array.
99
+
100
+ See Also
101
+ --------
102
+ dctn : multidimensional DCT
103
+
104
+ Notes
105
+ -----
106
+ For full details of the IDCT types and normalization modes, as well as
107
+ references, see `idct`.
108
+
109
+ Examples
110
+ --------
111
+ >>> import numpy as np
112
+ >>> from scipy.fftpack import dctn, idctn
113
+ >>> rng = np.random.default_rng()
114
+ >>> y = rng.standard_normal((16, 16))
115
+ >>> np.allclose(y, idctn(dctn(y, norm='ortho'), norm='ortho'))
116
+ True
117
+
118
+ """
119
+ type = _inverse_typemap[type]
120
+ shape = _good_shape(x, shape, axes)
121
+ return _pocketfft.dctn(x, type, shape, axes, norm, overwrite_x)
122
+
123
+
124
+ def dstn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
125
+ """
126
+ Return multidimensional Discrete Sine Transform along the specified axes.
127
+
128
+ Parameters
129
+ ----------
130
+ x : array_like
131
+ The input array.
132
+ type : {1, 2, 3, 4}, optional
133
+ Type of the DST (see Notes). Default type is 2.
134
+ shape : int or array_like of ints or None, optional
135
+ The shape of the result. If both `shape` and `axes` (see below) are
136
+ None, `shape` is ``x.shape``; if `shape` is None but `axes` is
137
+ not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
138
+ If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
139
+ If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
140
+ length ``shape[i]``.
141
+ If any element of `shape` is -1, the size of the corresponding
142
+ dimension of `x` is used.
143
+ axes : int or array_like of ints or None, optional
144
+ Axes along which the DCT is computed.
145
+ The default is over all axes.
146
+ norm : {None, 'ortho'}, optional
147
+ Normalization mode (see Notes). Default is None.
148
+ overwrite_x : bool, optional
149
+ If True, the contents of `x` can be destroyed; the default is False.
150
+
151
+ Returns
152
+ -------
153
+ y : ndarray of real
154
+ The transformed input array.
155
+
156
+ See Also
157
+ --------
158
+ idstn : Inverse multidimensional DST
159
+
160
+ Notes
161
+ -----
162
+ For full details of the DST types and normalization modes, as well as
163
+ references, see `dst`.
164
+
165
+ Examples
166
+ --------
167
+ >>> import numpy as np
168
+ >>> from scipy.fftpack import dstn, idstn
169
+ >>> rng = np.random.default_rng()
170
+ >>> y = rng.standard_normal((16, 16))
171
+ >>> np.allclose(y, idstn(dstn(y, norm='ortho'), norm='ortho'))
172
+ True
173
+
174
+ """
175
+ shape = _good_shape(x, shape, axes)
176
+ return _pocketfft.dstn(x, type, shape, axes, norm, overwrite_x)
177
+
178
+
179
+ def idstn(x, type=2, shape=None, axes=None, norm=None, overwrite_x=False):
180
+ """
181
+ Return multidimensional Discrete Sine Transform along the specified axes.
182
+
183
+ Parameters
184
+ ----------
185
+ x : array_like
186
+ The input array.
187
+ type : {1, 2, 3, 4}, optional
188
+ Type of the DST (see Notes). Default type is 2.
189
+ shape : int or array_like of ints or None, optional
190
+ The shape of the result. If both `shape` and `axes` (see below) are
191
+ None, `shape` is ``x.shape``; if `shape` is None but `axes` is
192
+ not None, then `shape` is ``numpy.take(x.shape, axes, axis=0)``.
193
+ If ``shape[i] > x.shape[i]``, the ith dimension is padded with zeros.
194
+ If ``shape[i] < x.shape[i]``, the ith dimension is truncated to
195
+ length ``shape[i]``.
196
+ If any element of `shape` is -1, the size of the corresponding
197
+ dimension of `x` is used.
198
+ axes : int or array_like of ints or None, optional
199
+ Axes along which the IDST is computed.
200
+ The default is over all axes.
201
+ norm : {None, 'ortho'}, optional
202
+ Normalization mode (see Notes). Default is None.
203
+ overwrite_x : bool, optional
204
+ If True, the contents of `x` can be destroyed; the default is False.
205
+
206
+ Returns
207
+ -------
208
+ y : ndarray of real
209
+ The transformed input array.
210
+
211
+ See Also
212
+ --------
213
+ dstn : multidimensional DST
214
+
215
+ Notes
216
+ -----
217
+ For full details of the IDST types and normalization modes, as well as
218
+ references, see `idst`.
219
+
220
+ Examples
221
+ --------
222
+ >>> import numpy as np
223
+ >>> from scipy.fftpack import dstn, idstn
224
+ >>> rng = np.random.default_rng()
225
+ >>> y = rng.standard_normal((16, 16))
226
+ >>> np.allclose(y, idstn(dstn(y, norm='ortho'), norm='ortho'))
227
+ True
228
+
229
+ """
230
+ type = _inverse_typemap[type]
231
+ shape = _good_shape(x, shape, axes)
232
+ return _pocketfft.dstn(x, type, shape, axes, norm, overwrite_x)
233
+
234
+
235
+ def dct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
236
+ r"""
237
+ Return the Discrete Cosine Transform of arbitrary type sequence x.
238
+
239
+ Parameters
240
+ ----------
241
+ x : array_like
242
+ The input array.
243
+ type : {1, 2, 3, 4}, optional
244
+ Type of the DCT (see Notes). Default type is 2.
245
+ n : int, optional
246
+ Length of the transform. If ``n < x.shape[axis]``, `x` is
247
+ truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
248
+ default results in ``n = x.shape[axis]``.
249
+ axis : int, optional
250
+ Axis along which the dct is computed; the default is over the
251
+ last axis (i.e., ``axis=-1``).
252
+ norm : {None, 'ortho'}, optional
253
+ Normalization mode (see Notes). Default is None.
254
+ overwrite_x : bool, optional
255
+ If True, the contents of `x` can be destroyed; the default is False.
256
+
257
+ Returns
258
+ -------
259
+ y : ndarray of real
260
+ The transformed input array.
261
+
262
+ See Also
263
+ --------
264
+ idct : Inverse DCT
265
+
266
+ Notes
267
+ -----
268
+ For a single dimension array ``x``, ``dct(x, norm='ortho')`` is equal to
269
+ MATLAB ``dct(x)``.
270
+
271
+ There are, theoretically, 8 types of the DCT, only the first 4 types are
272
+ implemented in scipy. 'The' DCT generally refers to DCT type 2, and 'the'
273
+ Inverse DCT generally refers to DCT type 3.
274
+
275
+ **Type I**
276
+
277
+ There are several definitions of the DCT-I; we use the following
278
+ (for ``norm=None``)
279
+
280
+ .. math::
281
+
282
+ y_k = x_0 + (-1)^k x_{N-1} + 2 \sum_{n=1}^{N-2} x_n \cos\left(
283
+ \frac{\pi k n}{N-1} \right)
284
+
285
+ If ``norm='ortho'``, ``x[0]`` and ``x[N-1]`` are multiplied by a scaling
286
+ factor of :math:`\sqrt{2}`, and ``y[k]`` is multiplied by a scaling factor
287
+ ``f``
288
+
289
+ .. math::
290
+
291
+ f = \begin{cases}
292
+ \frac{1}{2}\sqrt{\frac{1}{N-1}} & \text{if }k=0\text{ or }N-1, \\
293
+ \frac{1}{2}\sqrt{\frac{2}{N-1}} & \text{otherwise} \end{cases}
294
+
295
+ .. versionadded:: 1.2.0
296
+ Orthonormalization in DCT-I.
297
+
298
+ .. note::
299
+ The DCT-I is only supported for input size > 1.
300
+
301
+ **Type II**
302
+
303
+ There are several definitions of the DCT-II; we use the following
304
+ (for ``norm=None``)
305
+
306
+ .. math::
307
+
308
+ y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi k(2n+1)}{2N} \right)
309
+
310
+ If ``norm='ortho'``, ``y[k]`` is multiplied by a scaling factor ``f``
311
+
312
+ .. math::
313
+ f = \begin{cases}
314
+ \sqrt{\frac{1}{4N}} & \text{if }k=0, \\
315
+ \sqrt{\frac{1}{2N}} & \text{otherwise} \end{cases}
316
+
317
+ which makes the corresponding matrix of coefficients orthonormal
318
+ (``O @ O.T = np.eye(N)``).
319
+
320
+ **Type III**
321
+
322
+ There are several definitions, we use the following (for ``norm=None``)
323
+
324
+ .. math::
325
+
326
+ y_k = x_0 + 2 \sum_{n=1}^{N-1} x_n \cos\left(\frac{\pi(2k+1)n}{2N}\right)
327
+
328
+ or, for ``norm='ortho'``
329
+
330
+ .. math::
331
+
332
+ y_k = \frac{x_0}{\sqrt{N}} + \sqrt{\frac{2}{N}} \sum_{n=1}^{N-1} x_n
333
+ \cos\left(\frac{\pi(2k+1)n}{2N}\right)
334
+
335
+ The (unnormalized) DCT-III is the inverse of the (unnormalized) DCT-II, up
336
+ to a factor `2N`. The orthonormalized DCT-III is exactly the inverse of
337
+ the orthonormalized DCT-II.
338
+
339
+ **Type IV**
340
+
341
+ There are several definitions of the DCT-IV; we use the following
342
+ (for ``norm=None``)
343
+
344
+ .. math::
345
+
346
+ y_k = 2 \sum_{n=0}^{N-1} x_n \cos\left(\frac{\pi(2k+1)(2n+1)}{4N} \right)
347
+
348
+ If ``norm='ortho'``, ``y[k]`` is multiplied by a scaling factor ``f``
349
+
350
+ .. math::
351
+
352
+ f = \frac{1}{\sqrt{2N}}
353
+
354
+ .. versionadded:: 1.2.0
355
+ Support for DCT-IV.
356
+
357
+ References
358
+ ----------
359
+ .. [1] 'A Fast Cosine Transform in One and Two Dimensions', by J.
360
+ Makhoul, `IEEE Transactions on acoustics, speech and signal
361
+ processing` vol. 28(1), pp. 27-34,
362
+ :doi:`10.1109/TASSP.1980.1163351` (1980).
363
+ .. [2] Wikipedia, "Discrete cosine transform",
364
+ https://en.wikipedia.org/wiki/Discrete_cosine_transform
365
+
366
+ Examples
367
+ --------
368
+ The Type 1 DCT is equivalent to the FFT (though faster) for real,
369
+ even-symmetrical inputs. The output is also real and even-symmetrical.
370
+ Half of the FFT input is used to generate half of the FFT output:
371
+
372
+ >>> from scipy.fftpack import fft, dct
373
+ >>> import numpy as np
374
+ >>> fft(np.array([4., 3., 5., 10., 5., 3.])).real
375
+ array([ 30., -8., 6., -2., 6., -8.])
376
+ >>> dct(np.array([4., 3., 5., 10.]), 1)
377
+ array([ 30., -8., 6., -2.])
378
+
379
+ """
380
+ return _pocketfft.dct(x, type, n, axis, norm, overwrite_x)
381
+
382
+
383
+ def idct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
384
+ """
385
+ Return the Inverse Discrete Cosine Transform of an arbitrary type sequence.
386
+
387
+ Parameters
388
+ ----------
389
+ x : array_like
390
+ The input array.
391
+ type : {1, 2, 3, 4}, optional
392
+ Type of the DCT (see Notes). Default type is 2.
393
+ n : int, optional
394
+ Length of the transform. If ``n < x.shape[axis]``, `x` is
395
+ truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
396
+ default results in ``n = x.shape[axis]``.
397
+ axis : int, optional
398
+ Axis along which the idct is computed; the default is over the
399
+ last axis (i.e., ``axis=-1``).
400
+ norm : {None, 'ortho'}, optional
401
+ Normalization mode (see Notes). Default is None.
402
+ overwrite_x : bool, optional
403
+ If True, the contents of `x` can be destroyed; the default is False.
404
+
405
+ Returns
406
+ -------
407
+ idct : ndarray of real
408
+ The transformed input array.
409
+
410
+ See Also
411
+ --------
412
+ dct : Forward DCT
413
+
414
+ Notes
415
+ -----
416
+ For a single dimension array `x`, ``idct(x, norm='ortho')`` is equal to
417
+ MATLAB ``idct(x)``.
418
+
419
+ 'The' IDCT is the IDCT of type 2, which is the same as DCT of type 3.
420
+
421
+ IDCT of type 1 is the DCT of type 1, IDCT of type 2 is the DCT of type
422
+ 3, and IDCT of type 3 is the DCT of type 2. IDCT of type 4 is the DCT
423
+ of type 4. For the definition of these types, see `dct`.
424
+
425
+ Examples
426
+ --------
427
+ The Type 1 DCT is equivalent to the DFT for real, even-symmetrical
428
+ inputs. The output is also real and even-symmetrical. Half of the IFFT
429
+ input is used to generate half of the IFFT output:
430
+
431
+ >>> from scipy.fftpack import ifft, idct
432
+ >>> import numpy as np
433
+ >>> ifft(np.array([ 30., -8., 6., -2., 6., -8.])).real
434
+ array([ 4., 3., 5., 10., 5., 3.])
435
+ >>> idct(np.array([ 30., -8., 6., -2.]), 1) / 6
436
+ array([ 4., 3., 5., 10.])
437
+
438
+ """
439
+ type = _inverse_typemap[type]
440
+ return _pocketfft.dct(x, type, n, axis, norm, overwrite_x)
441
+
442
+
443
+ def dst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
444
+ r"""
445
+ Return the Discrete Sine Transform of arbitrary type sequence x.
446
+
447
+ Parameters
448
+ ----------
449
+ x : array_like
450
+ The input array.
451
+ type : {1, 2, 3, 4}, optional
452
+ Type of the DST (see Notes). Default type is 2.
453
+ n : int, optional
454
+ Length of the transform. If ``n < x.shape[axis]``, `x` is
455
+ truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
456
+ default results in ``n = x.shape[axis]``.
457
+ axis : int, optional
458
+ Axis along which the dst is computed; the default is over the
459
+ last axis (i.e., ``axis=-1``).
460
+ norm : {None, 'ortho'}, optional
461
+ Normalization mode (see Notes). Default is None.
462
+ overwrite_x : bool, optional
463
+ If True, the contents of `x` can be destroyed; the default is False.
464
+
465
+ Returns
466
+ -------
467
+ dst : ndarray of reals
468
+ The transformed input array.
469
+
470
+ See Also
471
+ --------
472
+ idst : Inverse DST
473
+
474
+ Notes
475
+ -----
476
+ For a single dimension array ``x``.
477
+
478
+ There are, theoretically, 8 types of the DST for different combinations of
479
+ even/odd boundary conditions and boundary off sets [1]_, only the first
480
+ 4 types are implemented in scipy.
481
+
482
+ **Type I**
483
+
484
+ There are several definitions of the DST-I; we use the following
485
+ for ``norm=None``. DST-I assumes the input is odd around `n=-1` and `n=N`.
486
+
487
+ .. math::
488
+
489
+ y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(k+1)(n+1)}{N+1}\right)
490
+
491
+ Note that the DST-I is only supported for input size > 1.
492
+ The (unnormalized) DST-I is its own inverse, up to a factor `2(N+1)`.
493
+ The orthonormalized DST-I is exactly its own inverse.
494
+
495
+ **Type II**
496
+
497
+ There are several definitions of the DST-II; we use the following for
498
+ ``norm=None``. DST-II assumes the input is odd around `n=-1/2` and
499
+ `n=N-1/2`; the output is odd around :math:`k=-1` and even around `k=N-1`
500
+
501
+ .. math::
502
+
503
+ y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(k+1)(2n+1)}{2N}\right)
504
+
505
+ if ``norm='ortho'``, ``y[k]`` is multiplied by a scaling factor ``f``
506
+
507
+ .. math::
508
+
509
+ f = \begin{cases}
510
+ \sqrt{\frac{1}{4N}} & \text{if }k = 0, \\
511
+ \sqrt{\frac{1}{2N}} & \text{otherwise} \end{cases}
512
+
513
+ **Type III**
514
+
515
+ There are several definitions of the DST-III, we use the following (for
516
+ ``norm=None``). DST-III assumes the input is odd around `n=-1` and even
517
+ around `n=N-1`
518
+
519
+ .. math::
520
+
521
+ y_k = (-1)^k x_{N-1} + 2 \sum_{n=0}^{N-2} x_n \sin\left(
522
+ \frac{\pi(2k+1)(n+1)}{2N}\right)
523
+
524
+ The (unnormalized) DST-III is the inverse of the (unnormalized) DST-II, up
525
+ to a factor `2N`. The orthonormalized DST-III is exactly the inverse of the
526
+ orthonormalized DST-II.
527
+
528
+ .. versionadded:: 0.11.0
529
+
530
+ **Type IV**
531
+
532
+ There are several definitions of the DST-IV, we use the following (for
533
+ ``norm=None``). DST-IV assumes the input is odd around `n=-0.5` and even
534
+ around `n=N-0.5`
535
+
536
+ .. math::
537
+
538
+ y_k = 2 \sum_{n=0}^{N-1} x_n \sin\left(\frac{\pi(2k+1)(2n+1)}{4N}\right)
539
+
540
+ The (unnormalized) DST-IV is its own inverse, up to a factor `2N`. The
541
+ orthonormalized DST-IV is exactly its own inverse.
542
+
543
+ .. versionadded:: 1.2.0
544
+ Support for DST-IV.
545
+
546
+ References
547
+ ----------
548
+ .. [1] Wikipedia, "Discrete sine transform",
549
+ https://en.wikipedia.org/wiki/Discrete_sine_transform
550
+
551
+ """
552
+ return _pocketfft.dst(x, type, n, axis, norm, overwrite_x)
553
+
554
+
555
+ def idst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
556
+ """
557
+ Return the Inverse Discrete Sine Transform of an arbitrary type sequence.
558
+
559
+ Parameters
560
+ ----------
561
+ x : array_like
562
+ The input array.
563
+ type : {1, 2, 3, 4}, optional
564
+ Type of the DST (see Notes). Default type is 2.
565
+ n : int, optional
566
+ Length of the transform. If ``n < x.shape[axis]``, `x` is
567
+ truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The
568
+ default results in ``n = x.shape[axis]``.
569
+ axis : int, optional
570
+ Axis along which the idst is computed; the default is over the
571
+ last axis (i.e., ``axis=-1``).
572
+ norm : {None, 'ortho'}, optional
573
+ Normalization mode (see Notes). Default is None.
574
+ overwrite_x : bool, optional
575
+ If True, the contents of `x` can be destroyed; the default is False.
576
+
577
+ Returns
578
+ -------
579
+ idst : ndarray of real
580
+ The transformed input array.
581
+
582
+ See Also
583
+ --------
584
+ dst : Forward DST
585
+
586
+ Notes
587
+ -----
588
+ 'The' IDST is the IDST of type 2, which is the same as DST of type 3.
589
+
590
+ IDST of type 1 is the DST of type 1, IDST of type 2 is the DST of type
591
+ 3, and IDST of type 3 is the DST of type 2. For the definition of these
592
+ types, see `dst`.
593
+
594
+ .. versionadded:: 0.11.0
595
+
596
+ """
597
+ type = _inverse_typemap[type]
598
+ return _pocketfft.dst(x, type, n, axis, norm, overwrite_x)
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/basic.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.fftpack` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+ __all__ = [ # noqa: F822
8
+ 'fft','ifft','fftn','ifftn','rfft','irfft',
9
+ 'fft2','ifft2'
10
+ ]
11
+
12
+
13
+ def __dir__():
14
+ return __all__
15
+
16
+
17
+ def __getattr__(name):
18
+ return _sub_module_deprecation(sub_package="fftpack", module="basic",
19
+ private_modules=["_basic"], all=__all__,
20
+ attribute=name)
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/convolve.cpython-310-x86_64-linux-gnu.so ADDED
Binary file (273 kB). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/helper.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.fftpack` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+ __all__ = [ # noqa: F822
8
+ 'fftshift', 'ifftshift', 'fftfreq', 'rfftfreq', 'next_fast_len'
9
+ ]
10
+
11
+
12
+ def __dir__():
13
+ return __all__
14
+
15
+
16
+ def __getattr__(name):
17
+ return _sub_module_deprecation(sub_package="fftpack", module="helper",
18
+ private_modules=["_helper"], all=__all__,
19
+ attribute=name)
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/pseudo_diffs.py ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.fftpack` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+ __all__ = [ # noqa: F822
8
+ 'diff',
9
+ 'tilbert', 'itilbert', 'hilbert', 'ihilbert',
10
+ 'cs_diff', 'cc_diff', 'sc_diff', 'ss_diff',
11
+ 'shift', 'iscomplexobj', 'convolve'
12
+ ]
13
+
14
+
15
+ def __dir__():
16
+ return __all__
17
+
18
+
19
+ def __getattr__(name):
20
+ return _sub_module_deprecation(sub_package="fftpack", module="pseudo_diffs",
21
+ private_modules=["_pseudo_diffs"], all=__all__,
22
+ attribute=name)
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/realtransforms.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.fftpack` namespace for importing the functions
3
+ # included below.
4
+
5
+ from scipy._lib.deprecation import _sub_module_deprecation
6
+
7
+ __all__ = [ # noqa: F822
8
+ 'dct', 'idct', 'dst', 'idst', 'dctn', 'idctn', 'dstn', 'idstn'
9
+ ]
10
+
11
+
12
+ def __dir__():
13
+ return __all__
14
+
15
+
16
+ def __getattr__(name):
17
+ return _sub_module_deprecation(sub_package="fftpack", module="realtransforms",
18
+ private_modules=["_realtransforms"], all=__all__,
19
+ attribute=name)
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/tests/__init__.py ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (192 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_basic.cpython-310.pyc ADDED
Binary file (28.1 kB). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_helper.cpython-310.pyc ADDED
Binary file (2.23 kB). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_import.cpython-310.pyc ADDED
Binary file (1.57 kB). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_pseudo_diffs.cpython-310.pyc ADDED
Binary file (13.1 kB). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/tests/__pycache__/test_real_transforms.cpython-310.pyc ADDED
Binary file (25.8 kB). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/tests/test_basic.py ADDED
@@ -0,0 +1,873 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Created by Pearu Peterson, September 2002
2
+
3
+ from numpy.testing import (assert_, assert_equal, assert_array_almost_equal,
4
+ assert_array_almost_equal_nulp, assert_array_less)
5
+ import pytest
6
+ from pytest import raises as assert_raises
7
+ from scipy.fftpack import ifft, fft, fftn, ifftn, rfft, irfft, fft2
8
+
9
+ from numpy import (arange, array, asarray, zeros, dot, exp, pi,
10
+ swapaxes, double, cdouble)
11
+ import numpy as np
12
+ import numpy.fft
13
+ from numpy.random import rand
14
+
15
+ # "large" composite numbers supported by FFTPACK
16
+ LARGE_COMPOSITE_SIZES = [
17
+ 2**13,
18
+ 2**5 * 3**5,
19
+ 2**3 * 3**3 * 5**2,
20
+ ]
21
+ SMALL_COMPOSITE_SIZES = [
22
+ 2,
23
+ 2*3*5,
24
+ 2*2*3*3,
25
+ ]
26
+ # prime
27
+ LARGE_PRIME_SIZES = [
28
+ 2011
29
+ ]
30
+ SMALL_PRIME_SIZES = [
31
+ 29
32
+ ]
33
+
34
+
35
+ def _assert_close_in_norm(x, y, rtol, size, rdt):
36
+ # helper function for testing
37
+ err_msg = f"size: {size} rdt: {rdt}"
38
+ assert_array_less(np.linalg.norm(x - y), rtol*np.linalg.norm(x), err_msg)
39
+
40
+
41
+ def random(size):
42
+ return rand(*size)
43
+
44
+
45
+ def direct_dft(x):
46
+ x = asarray(x)
47
+ n = len(x)
48
+ y = zeros(n, dtype=cdouble)
49
+ w = -arange(n)*(2j*pi/n)
50
+ for i in range(n):
51
+ y[i] = dot(exp(i*w), x)
52
+ return y
53
+
54
+
55
+ def direct_idft(x):
56
+ x = asarray(x)
57
+ n = len(x)
58
+ y = zeros(n, dtype=cdouble)
59
+ w = arange(n)*(2j*pi/n)
60
+ for i in range(n):
61
+ y[i] = dot(exp(i*w), x)/n
62
+ return y
63
+
64
+
65
+ def direct_dftn(x):
66
+ x = asarray(x)
67
+ for axis in range(len(x.shape)):
68
+ x = fft(x, axis=axis)
69
+ return x
70
+
71
+
72
+ def direct_idftn(x):
73
+ x = asarray(x)
74
+ for axis in range(len(x.shape)):
75
+ x = ifft(x, axis=axis)
76
+ return x
77
+
78
+
79
+ def direct_rdft(x):
80
+ x = asarray(x)
81
+ n = len(x)
82
+ w = -arange(n)*(2j*pi/n)
83
+ r = zeros(n, dtype=double)
84
+ for i in range(n//2+1):
85
+ y = dot(exp(i*w), x)
86
+ if i:
87
+ r[2*i-1] = y.real
88
+ if 2*i < n:
89
+ r[2*i] = y.imag
90
+ else:
91
+ r[0] = y.real
92
+ return r
93
+
94
+
95
+ def direct_irdft(x):
96
+ x = asarray(x)
97
+ n = len(x)
98
+ x1 = zeros(n, dtype=cdouble)
99
+ for i in range(n//2+1):
100
+ if i:
101
+ if 2*i < n:
102
+ x1[i] = x[2*i-1] + 1j*x[2*i]
103
+ x1[n-i] = x[2*i-1] - 1j*x[2*i]
104
+ else:
105
+ x1[i] = x[2*i-1]
106
+ else:
107
+ x1[0] = x[0]
108
+ return direct_idft(x1).real
109
+
110
+
111
+ class _TestFFTBase:
112
+ def setup_method(self):
113
+ self.cdt = None
114
+ self.rdt = None
115
+ np.random.seed(1234)
116
+
117
+ def test_definition(self):
118
+ x = np.array([1,2,3,4+1j,1,2,3,4+2j], dtype=self.cdt)
119
+ y = fft(x)
120
+ assert_equal(y.dtype, self.cdt)
121
+ y1 = direct_dft(x)
122
+ assert_array_almost_equal(y,y1)
123
+ x = np.array([1,2,3,4+0j,5], dtype=self.cdt)
124
+ assert_array_almost_equal(fft(x),direct_dft(x))
125
+
126
+ def test_n_argument_real(self):
127
+ x1 = np.array([1,2,3,4], dtype=self.rdt)
128
+ x2 = np.array([1,2,3,4], dtype=self.rdt)
129
+ y = fft([x1,x2],n=4)
130
+ assert_equal(y.dtype, self.cdt)
131
+ assert_equal(y.shape,(2,4))
132
+ assert_array_almost_equal(y[0],direct_dft(x1))
133
+ assert_array_almost_equal(y[1],direct_dft(x2))
134
+
135
+ def _test_n_argument_complex(self):
136
+ x1 = np.array([1,2,3,4+1j], dtype=self.cdt)
137
+ x2 = np.array([1,2,3,4+1j], dtype=self.cdt)
138
+ y = fft([x1,x2],n=4)
139
+ assert_equal(y.dtype, self.cdt)
140
+ assert_equal(y.shape,(2,4))
141
+ assert_array_almost_equal(y[0],direct_dft(x1))
142
+ assert_array_almost_equal(y[1],direct_dft(x2))
143
+
144
+ def test_invalid_sizes(self):
145
+ assert_raises(ValueError, fft, [])
146
+ assert_raises(ValueError, fft, [[1,1],[2,2]], -5)
147
+
148
+
149
+ class TestDoubleFFT(_TestFFTBase):
150
+ def setup_method(self):
151
+ self.cdt = np.complex128
152
+ self.rdt = np.float64
153
+
154
+
155
+ class TestSingleFFT(_TestFFTBase):
156
+ def setup_method(self):
157
+ self.cdt = np.complex64
158
+ self.rdt = np.float32
159
+
160
+ reason = ("single-precision FFT implementation is partially disabled, "
161
+ "until accuracy issues with large prime powers are resolved")
162
+
163
+ @pytest.mark.xfail(run=False, reason=reason)
164
+ def test_notice(self):
165
+ pass
166
+
167
+
168
+ class TestFloat16FFT:
169
+
170
+ def test_1_argument_real(self):
171
+ x1 = np.array([1, 2, 3, 4], dtype=np.float16)
172
+ y = fft(x1, n=4)
173
+ assert_equal(y.dtype, np.complex64)
174
+ assert_equal(y.shape, (4, ))
175
+ assert_array_almost_equal(y, direct_dft(x1.astype(np.float32)))
176
+
177
+ def test_n_argument_real(self):
178
+ x1 = np.array([1, 2, 3, 4], dtype=np.float16)
179
+ x2 = np.array([1, 2, 3, 4], dtype=np.float16)
180
+ y = fft([x1, x2], n=4)
181
+ assert_equal(y.dtype, np.complex64)
182
+ assert_equal(y.shape, (2, 4))
183
+ assert_array_almost_equal(y[0], direct_dft(x1.astype(np.float32)))
184
+ assert_array_almost_equal(y[1], direct_dft(x2.astype(np.float32)))
185
+
186
+
187
+ class _TestIFFTBase:
188
+ def setup_method(self):
189
+ np.random.seed(1234)
190
+
191
+ def test_definition(self):
192
+ x = np.array([1,2,3,4+1j,1,2,3,4+2j], self.cdt)
193
+ y = ifft(x)
194
+ y1 = direct_idft(x)
195
+ assert_equal(y.dtype, self.cdt)
196
+ assert_array_almost_equal(y,y1)
197
+
198
+ x = np.array([1,2,3,4+0j,5], self.cdt)
199
+ assert_array_almost_equal(ifft(x),direct_idft(x))
200
+
201
+ def test_definition_real(self):
202
+ x = np.array([1,2,3,4,1,2,3,4], self.rdt)
203
+ y = ifft(x)
204
+ assert_equal(y.dtype, self.cdt)
205
+ y1 = direct_idft(x)
206
+ assert_array_almost_equal(y,y1)
207
+
208
+ x = np.array([1,2,3,4,5], dtype=self.rdt)
209
+ assert_equal(y.dtype, self.cdt)
210
+ assert_array_almost_equal(ifft(x),direct_idft(x))
211
+
212
+ def test_random_complex(self):
213
+ for size in [1,51,111,100,200,64,128,256,1024]:
214
+ x = random([size]).astype(self.cdt)
215
+ x = random([size]).astype(self.cdt) + 1j*x
216
+ y1 = ifft(fft(x))
217
+ y2 = fft(ifft(x))
218
+ assert_equal(y1.dtype, self.cdt)
219
+ assert_equal(y2.dtype, self.cdt)
220
+ assert_array_almost_equal(y1, x)
221
+ assert_array_almost_equal(y2, x)
222
+
223
+ def test_random_real(self):
224
+ for size in [1,51,111,100,200,64,128,256,1024]:
225
+ x = random([size]).astype(self.rdt)
226
+ y1 = ifft(fft(x))
227
+ y2 = fft(ifft(x))
228
+ assert_equal(y1.dtype, self.cdt)
229
+ assert_equal(y2.dtype, self.cdt)
230
+ assert_array_almost_equal(y1, x)
231
+ assert_array_almost_equal(y2, x)
232
+
233
+ def test_size_accuracy(self):
234
+ # Sanity check for the accuracy for prime and non-prime sized inputs
235
+ if self.rdt == np.float32:
236
+ rtol = 1e-5
237
+ elif self.rdt == np.float64:
238
+ rtol = 1e-10
239
+
240
+ for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
241
+ np.random.seed(1234)
242
+ x = np.random.rand(size).astype(self.rdt)
243
+ y = ifft(fft(x))
244
+ _assert_close_in_norm(x, y, rtol, size, self.rdt)
245
+ y = fft(ifft(x))
246
+ _assert_close_in_norm(x, y, rtol, size, self.rdt)
247
+
248
+ x = (x + 1j*np.random.rand(size)).astype(self.cdt)
249
+ y = ifft(fft(x))
250
+ _assert_close_in_norm(x, y, rtol, size, self.rdt)
251
+ y = fft(ifft(x))
252
+ _assert_close_in_norm(x, y, rtol, size, self.rdt)
253
+
254
+ def test_invalid_sizes(self):
255
+ assert_raises(ValueError, ifft, [])
256
+ assert_raises(ValueError, ifft, [[1,1],[2,2]], -5)
257
+
258
+
259
+ class TestDoubleIFFT(_TestIFFTBase):
260
+ def setup_method(self):
261
+ self.cdt = np.complex128
262
+ self.rdt = np.float64
263
+
264
+
265
+ class TestSingleIFFT(_TestIFFTBase):
266
+ def setup_method(self):
267
+ self.cdt = np.complex64
268
+ self.rdt = np.float32
269
+
270
+
271
+ class _TestRFFTBase:
272
+ def setup_method(self):
273
+ np.random.seed(1234)
274
+
275
+ def test_definition(self):
276
+ for t in [[1, 2, 3, 4, 1, 2, 3, 4], [1, 2, 3, 4, 1, 2, 3, 4, 5]]:
277
+ x = np.array(t, dtype=self.rdt)
278
+ y = rfft(x)
279
+ y1 = direct_rdft(x)
280
+ assert_array_almost_equal(y,y1)
281
+ assert_equal(y.dtype, self.rdt)
282
+
283
+ def test_invalid_sizes(self):
284
+ assert_raises(ValueError, rfft, [])
285
+ assert_raises(ValueError, rfft, [[1,1],[2,2]], -5)
286
+
287
+ # See gh-5790
288
+ class MockSeries:
289
+ def __init__(self, data):
290
+ self.data = np.asarray(data)
291
+
292
+ def __getattr__(self, item):
293
+ try:
294
+ return getattr(self.data, item)
295
+ except AttributeError as e:
296
+ raise AttributeError("'MockSeries' object "
297
+ f"has no attribute '{item}'") from e
298
+
299
+ def test_non_ndarray_with_dtype(self):
300
+ x = np.array([1., 2., 3., 4., 5.])
301
+ xs = _TestRFFTBase.MockSeries(x)
302
+
303
+ expected = [1, 2, 3, 4, 5]
304
+ rfft(xs)
305
+
306
+ # Data should not have been overwritten
307
+ assert_equal(x, expected)
308
+ assert_equal(xs.data, expected)
309
+
310
+ def test_complex_input(self):
311
+ assert_raises(TypeError, rfft, np.arange(4, dtype=np.complex64))
312
+
313
+
314
+ class TestRFFTDouble(_TestRFFTBase):
315
+ def setup_method(self):
316
+ self.cdt = np.complex128
317
+ self.rdt = np.float64
318
+
319
+
320
+ class TestRFFTSingle(_TestRFFTBase):
321
+ def setup_method(self):
322
+ self.cdt = np.complex64
323
+ self.rdt = np.float32
324
+
325
+
326
+ class _TestIRFFTBase:
327
+ def setup_method(self):
328
+ np.random.seed(1234)
329
+
330
+ def test_definition(self):
331
+ x1 = [1,2,3,4,1,2,3,4]
332
+ x1_1 = [1,2+3j,4+1j,2+3j,4,2-3j,4-1j,2-3j]
333
+ x2 = [1,2,3,4,1,2,3,4,5]
334
+ x2_1 = [1,2+3j,4+1j,2+3j,4+5j,4-5j,2-3j,4-1j,2-3j]
335
+
336
+ def _test(x, xr):
337
+ y = irfft(np.array(x, dtype=self.rdt))
338
+ y1 = direct_irdft(x)
339
+ assert_equal(y.dtype, self.rdt)
340
+ assert_array_almost_equal(y,y1, decimal=self.ndec)
341
+ assert_array_almost_equal(y,ifft(xr), decimal=self.ndec)
342
+
343
+ _test(x1, x1_1)
344
+ _test(x2, x2_1)
345
+
346
+ def test_random_real(self):
347
+ for size in [1,51,111,100,200,64,128,256,1024]:
348
+ x = random([size]).astype(self.rdt)
349
+ y1 = irfft(rfft(x))
350
+ y2 = rfft(irfft(x))
351
+ assert_equal(y1.dtype, self.rdt)
352
+ assert_equal(y2.dtype, self.rdt)
353
+ assert_array_almost_equal(y1, x, decimal=self.ndec,
354
+ err_msg="size=%d" % size)
355
+ assert_array_almost_equal(y2, x, decimal=self.ndec,
356
+ err_msg="size=%d" % size)
357
+
358
+ def test_size_accuracy(self):
359
+ # Sanity check for the accuracy for prime and non-prime sized inputs
360
+ if self.rdt == np.float32:
361
+ rtol = 1e-5
362
+ elif self.rdt == np.float64:
363
+ rtol = 1e-10
364
+
365
+ for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
366
+ np.random.seed(1234)
367
+ x = np.random.rand(size).astype(self.rdt)
368
+ y = irfft(rfft(x))
369
+ _assert_close_in_norm(x, y, rtol, size, self.rdt)
370
+ y = rfft(irfft(x))
371
+ _assert_close_in_norm(x, y, rtol, size, self.rdt)
372
+
373
+ def test_invalid_sizes(self):
374
+ assert_raises(ValueError, irfft, [])
375
+ assert_raises(ValueError, irfft, [[1,1],[2,2]], -5)
376
+
377
+ def test_complex_input(self):
378
+ assert_raises(TypeError, irfft, np.arange(4, dtype=np.complex64))
379
+
380
+
381
+ # self.ndec is bogus; we should have a assert_array_approx_equal for number of
382
+ # significant digits
383
+
384
+ class TestIRFFTDouble(_TestIRFFTBase):
385
+ def setup_method(self):
386
+ self.cdt = np.complex128
387
+ self.rdt = np.float64
388
+ self.ndec = 14
389
+
390
+
391
+ class TestIRFFTSingle(_TestIRFFTBase):
392
+ def setup_method(self):
393
+ self.cdt = np.complex64
394
+ self.rdt = np.float32
395
+ self.ndec = 5
396
+
397
+
398
+ class Testfft2:
399
+ def setup_method(self):
400
+ np.random.seed(1234)
401
+
402
+ def test_regression_244(self):
403
+ """FFT returns wrong result with axes parameter."""
404
+ # fftn (and hence fft2) used to break when both axes and shape were
405
+ # used
406
+ x = numpy.ones((4, 4, 2))
407
+ y = fft2(x, shape=(8, 8), axes=(-3, -2))
408
+ y_r = numpy.fft.fftn(x, s=(8, 8), axes=(-3, -2))
409
+ assert_array_almost_equal(y, y_r)
410
+
411
+ def test_invalid_sizes(self):
412
+ assert_raises(ValueError, fft2, [[]])
413
+ assert_raises(ValueError, fft2, [[1, 1], [2, 2]], (4, -3))
414
+
415
+
416
+ class TestFftnSingle:
417
+ def setup_method(self):
418
+ np.random.seed(1234)
419
+
420
+ def test_definition(self):
421
+ x = [[1, 2, 3],
422
+ [4, 5, 6],
423
+ [7, 8, 9]]
424
+ y = fftn(np.array(x, np.float32))
425
+ assert_(y.dtype == np.complex64,
426
+ msg="double precision output with single precision")
427
+
428
+ y_r = np.array(fftn(x), np.complex64)
429
+ assert_array_almost_equal_nulp(y, y_r)
430
+
431
+ @pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES)
432
+ def test_size_accuracy_small(self, size):
433
+ x = np.random.rand(size, size) + 1j*np.random.rand(size, size)
434
+ y1 = fftn(x.real.astype(np.float32))
435
+ y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
436
+
437
+ assert_equal(y1.dtype, np.complex64)
438
+ assert_array_almost_equal_nulp(y1, y2, 2000)
439
+
440
+ @pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES)
441
+ def test_size_accuracy_large(self, size):
442
+ x = np.random.rand(size, 3) + 1j*np.random.rand(size, 3)
443
+ y1 = fftn(x.real.astype(np.float32))
444
+ y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
445
+
446
+ assert_equal(y1.dtype, np.complex64)
447
+ assert_array_almost_equal_nulp(y1, y2, 2000)
448
+
449
+ def test_definition_float16(self):
450
+ x = [[1, 2, 3],
451
+ [4, 5, 6],
452
+ [7, 8, 9]]
453
+ y = fftn(np.array(x, np.float16))
454
+ assert_equal(y.dtype, np.complex64)
455
+ y_r = np.array(fftn(x), np.complex64)
456
+ assert_array_almost_equal_nulp(y, y_r)
457
+
458
+ @pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES)
459
+ def test_float16_input_small(self, size):
460
+ x = np.random.rand(size, size) + 1j*np.random.rand(size, size)
461
+ y1 = fftn(x.real.astype(np.float16))
462
+ y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
463
+
464
+ assert_equal(y1.dtype, np.complex64)
465
+ assert_array_almost_equal_nulp(y1, y2, 5e5)
466
+
467
+ @pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES)
468
+ def test_float16_input_large(self, size):
469
+ x = np.random.rand(size, 3) + 1j*np.random.rand(size, 3)
470
+ y1 = fftn(x.real.astype(np.float16))
471
+ y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
472
+
473
+ assert_equal(y1.dtype, np.complex64)
474
+ assert_array_almost_equal_nulp(y1, y2, 2e6)
475
+
476
+
477
+ class TestFftn:
478
+ def setup_method(self):
479
+ np.random.seed(1234)
480
+
481
+ def test_definition(self):
482
+ x = [[1, 2, 3],
483
+ [4, 5, 6],
484
+ [7, 8, 9]]
485
+ y = fftn(x)
486
+ assert_array_almost_equal(y, direct_dftn(x))
487
+
488
+ x = random((20, 26))
489
+ assert_array_almost_equal(fftn(x), direct_dftn(x))
490
+
491
+ x = random((5, 4, 3, 20))
492
+ assert_array_almost_equal(fftn(x), direct_dftn(x))
493
+
494
+ def test_axes_argument(self):
495
+ # plane == ji_plane, x== kji_space
496
+ plane1 = [[1, 2, 3],
497
+ [4, 5, 6],
498
+ [7, 8, 9]]
499
+ plane2 = [[10, 11, 12],
500
+ [13, 14, 15],
501
+ [16, 17, 18]]
502
+ plane3 = [[19, 20, 21],
503
+ [22, 23, 24],
504
+ [25, 26, 27]]
505
+ ki_plane1 = [[1, 2, 3],
506
+ [10, 11, 12],
507
+ [19, 20, 21]]
508
+ ki_plane2 = [[4, 5, 6],
509
+ [13, 14, 15],
510
+ [22, 23, 24]]
511
+ ki_plane3 = [[7, 8, 9],
512
+ [16, 17, 18],
513
+ [25, 26, 27]]
514
+ jk_plane1 = [[1, 10, 19],
515
+ [4, 13, 22],
516
+ [7, 16, 25]]
517
+ jk_plane2 = [[2, 11, 20],
518
+ [5, 14, 23],
519
+ [8, 17, 26]]
520
+ jk_plane3 = [[3, 12, 21],
521
+ [6, 15, 24],
522
+ [9, 18, 27]]
523
+ kj_plane1 = [[1, 4, 7],
524
+ [10, 13, 16], [19, 22, 25]]
525
+ kj_plane2 = [[2, 5, 8],
526
+ [11, 14, 17], [20, 23, 26]]
527
+ kj_plane3 = [[3, 6, 9],
528
+ [12, 15, 18], [21, 24, 27]]
529
+ ij_plane1 = [[1, 4, 7],
530
+ [2, 5, 8],
531
+ [3, 6, 9]]
532
+ ij_plane2 = [[10, 13, 16],
533
+ [11, 14, 17],
534
+ [12, 15, 18]]
535
+ ij_plane3 = [[19, 22, 25],
536
+ [20, 23, 26],
537
+ [21, 24, 27]]
538
+ ik_plane1 = [[1, 10, 19],
539
+ [2, 11, 20],
540
+ [3, 12, 21]]
541
+ ik_plane2 = [[4, 13, 22],
542
+ [5, 14, 23],
543
+ [6, 15, 24]]
544
+ ik_plane3 = [[7, 16, 25],
545
+ [8, 17, 26],
546
+ [9, 18, 27]]
547
+ ijk_space = [jk_plane1, jk_plane2, jk_plane3]
548
+ ikj_space = [kj_plane1, kj_plane2, kj_plane3]
549
+ jik_space = [ik_plane1, ik_plane2, ik_plane3]
550
+ jki_space = [ki_plane1, ki_plane2, ki_plane3]
551
+ kij_space = [ij_plane1, ij_plane2, ij_plane3]
552
+ x = array([plane1, plane2, plane3])
553
+
554
+ assert_array_almost_equal(fftn(x),
555
+ fftn(x, axes=(-3, -2, -1))) # kji_space
556
+ assert_array_almost_equal(fftn(x), fftn(x, axes=(0, 1, 2)))
557
+ assert_array_almost_equal(fftn(x, axes=(0, 2)), fftn(x, axes=(0, -1)))
558
+ y = fftn(x, axes=(2, 1, 0)) # ijk_space
559
+ assert_array_almost_equal(swapaxes(y, -1, -3), fftn(ijk_space))
560
+ y = fftn(x, axes=(2, 0, 1)) # ikj_space
561
+ assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -1, -2),
562
+ fftn(ikj_space))
563
+ y = fftn(x, axes=(1, 2, 0)) # jik_space
564
+ assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -3, -2),
565
+ fftn(jik_space))
566
+ y = fftn(x, axes=(1, 0, 2)) # jki_space
567
+ assert_array_almost_equal(swapaxes(y, -2, -3), fftn(jki_space))
568
+ y = fftn(x, axes=(0, 2, 1)) # kij_space
569
+ assert_array_almost_equal(swapaxes(y, -2, -1), fftn(kij_space))
570
+
571
+ y = fftn(x, axes=(-2, -1)) # ji_plane
572
+ assert_array_almost_equal(fftn(plane1), y[0])
573
+ assert_array_almost_equal(fftn(plane2), y[1])
574
+ assert_array_almost_equal(fftn(plane3), y[2])
575
+
576
+ y = fftn(x, axes=(1, 2)) # ji_plane
577
+ assert_array_almost_equal(fftn(plane1), y[0])
578
+ assert_array_almost_equal(fftn(plane2), y[1])
579
+ assert_array_almost_equal(fftn(plane3), y[2])
580
+
581
+ y = fftn(x, axes=(-3, -2)) # kj_plane
582
+ assert_array_almost_equal(fftn(x[:, :, 0]), y[:, :, 0])
583
+ assert_array_almost_equal(fftn(x[:, :, 1]), y[:, :, 1])
584
+ assert_array_almost_equal(fftn(x[:, :, 2]), y[:, :, 2])
585
+
586
+ y = fftn(x, axes=(-3, -1)) # ki_plane
587
+ assert_array_almost_equal(fftn(x[:, 0, :]), y[:, 0, :])
588
+ assert_array_almost_equal(fftn(x[:, 1, :]), y[:, 1, :])
589
+ assert_array_almost_equal(fftn(x[:, 2, :]), y[:, 2, :])
590
+
591
+ y = fftn(x, axes=(-1, -2)) # ij_plane
592
+ assert_array_almost_equal(fftn(ij_plane1), swapaxes(y[0], -2, -1))
593
+ assert_array_almost_equal(fftn(ij_plane2), swapaxes(y[1], -2, -1))
594
+ assert_array_almost_equal(fftn(ij_plane3), swapaxes(y[2], -2, -1))
595
+
596
+ y = fftn(x, axes=(-1, -3)) # ik_plane
597
+ assert_array_almost_equal(fftn(ik_plane1),
598
+ swapaxes(y[:, 0, :], -1, -2))
599
+ assert_array_almost_equal(fftn(ik_plane2),
600
+ swapaxes(y[:, 1, :], -1, -2))
601
+ assert_array_almost_equal(fftn(ik_plane3),
602
+ swapaxes(y[:, 2, :], -1, -2))
603
+
604
+ y = fftn(x, axes=(-2, -3)) # jk_plane
605
+ assert_array_almost_equal(fftn(jk_plane1),
606
+ swapaxes(y[:, :, 0], -1, -2))
607
+ assert_array_almost_equal(fftn(jk_plane2),
608
+ swapaxes(y[:, :, 1], -1, -2))
609
+ assert_array_almost_equal(fftn(jk_plane3),
610
+ swapaxes(y[:, :, 2], -1, -2))
611
+
612
+ y = fftn(x, axes=(-1,)) # i_line
613
+ for i in range(3):
614
+ for j in range(3):
615
+ assert_array_almost_equal(fft(x[i, j, :]), y[i, j, :])
616
+ y = fftn(x, axes=(-2,)) # j_line
617
+ for i in range(3):
618
+ for j in range(3):
619
+ assert_array_almost_equal(fft(x[i, :, j]), y[i, :, j])
620
+ y = fftn(x, axes=(0,)) # k_line
621
+ for i in range(3):
622
+ for j in range(3):
623
+ assert_array_almost_equal(fft(x[:, i, j]), y[:, i, j])
624
+
625
+ y = fftn(x, axes=()) # point
626
+ assert_array_almost_equal(y, x)
627
+
628
+ def test_shape_argument(self):
629
+ small_x = [[1, 2, 3],
630
+ [4, 5, 6]]
631
+ large_x1 = [[1, 2, 3, 0],
632
+ [4, 5, 6, 0],
633
+ [0, 0, 0, 0],
634
+ [0, 0, 0, 0]]
635
+
636
+ y = fftn(small_x, shape=(4, 4))
637
+ assert_array_almost_equal(y, fftn(large_x1))
638
+
639
+ y = fftn(small_x, shape=(3, 4))
640
+ assert_array_almost_equal(y, fftn(large_x1[:-1]))
641
+
642
+ def test_shape_axes_argument(self):
643
+ small_x = [[1, 2, 3],
644
+ [4, 5, 6],
645
+ [7, 8, 9]]
646
+ large_x1 = array([[1, 2, 3, 0],
647
+ [4, 5, 6, 0],
648
+ [7, 8, 9, 0],
649
+ [0, 0, 0, 0]])
650
+ y = fftn(small_x, shape=(4, 4), axes=(-2, -1))
651
+ assert_array_almost_equal(y, fftn(large_x1))
652
+ y = fftn(small_x, shape=(4, 4), axes=(-1, -2))
653
+
654
+ assert_array_almost_equal(y, swapaxes(
655
+ fftn(swapaxes(large_x1, -1, -2)), -1, -2))
656
+
657
+ def test_shape_axes_argument2(self):
658
+ # Change shape of the last axis
659
+ x = numpy.random.random((10, 5, 3, 7))
660
+ y = fftn(x, axes=(-1,), shape=(8,))
661
+ assert_array_almost_equal(y, fft(x, axis=-1, n=8))
662
+
663
+ # Change shape of an arbitrary axis which is not the last one
664
+ x = numpy.random.random((10, 5, 3, 7))
665
+ y = fftn(x, axes=(-2,), shape=(8,))
666
+ assert_array_almost_equal(y, fft(x, axis=-2, n=8))
667
+
668
+ # Change shape of axes: cf #244, where shape and axes were mixed up
669
+ x = numpy.random.random((4, 4, 2))
670
+ y = fftn(x, axes=(-3, -2), shape=(8, 8))
671
+ assert_array_almost_equal(y,
672
+ numpy.fft.fftn(x, axes=(-3, -2), s=(8, 8)))
673
+
674
+ def test_shape_argument_more(self):
675
+ x = zeros((4, 4, 2))
676
+ with assert_raises(ValueError,
677
+ match="when given, axes and shape arguments"
678
+ " have to be of the same length"):
679
+ fftn(x, shape=(8, 8, 2, 1))
680
+
681
+ def test_invalid_sizes(self):
682
+ with assert_raises(ValueError,
683
+ match="invalid number of data points"
684
+ r" \(\[1, 0\]\) specified"):
685
+ fftn([[]])
686
+
687
+ with assert_raises(ValueError,
688
+ match="invalid number of data points"
689
+ r" \(\[4, -3\]\) specified"):
690
+ fftn([[1, 1], [2, 2]], (4, -3))
691
+
692
+
693
+ class TestIfftn:
694
+ dtype = None
695
+ cdtype = None
696
+
697
+ def setup_method(self):
698
+ np.random.seed(1234)
699
+
700
+ @pytest.mark.parametrize('dtype,cdtype,maxnlp',
701
+ [(np.float64, np.complex128, 2000),
702
+ (np.float32, np.complex64, 3500)])
703
+ def test_definition(self, dtype, cdtype, maxnlp):
704
+ x = np.array([[1, 2, 3],
705
+ [4, 5, 6],
706
+ [7, 8, 9]], dtype=dtype)
707
+ y = ifftn(x)
708
+ assert_equal(y.dtype, cdtype)
709
+ assert_array_almost_equal_nulp(y, direct_idftn(x), maxnlp)
710
+
711
+ x = random((20, 26))
712
+ assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp)
713
+
714
+ x = random((5, 4, 3, 20))
715
+ assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp)
716
+
717
+ @pytest.mark.parametrize('maxnlp', [2000, 3500])
718
+ @pytest.mark.parametrize('size', [1, 2, 51, 32, 64, 92])
719
+ def test_random_complex(self, maxnlp, size):
720
+ x = random([size, size]) + 1j*random([size, size])
721
+ assert_array_almost_equal_nulp(ifftn(fftn(x)), x, maxnlp)
722
+ assert_array_almost_equal_nulp(fftn(ifftn(x)), x, maxnlp)
723
+
724
+ def test_invalid_sizes(self):
725
+ with assert_raises(ValueError,
726
+ match="invalid number of data points"
727
+ r" \(\[1, 0\]\) specified"):
728
+ ifftn([[]])
729
+
730
+ with assert_raises(ValueError,
731
+ match="invalid number of data points"
732
+ r" \(\[4, -3\]\) specified"):
733
+ ifftn([[1, 1], [2, 2]], (4, -3))
734
+
735
+
736
+ class FakeArray:
737
+ def __init__(self, data):
738
+ self._data = data
739
+ self.__array_interface__ = data.__array_interface__
740
+
741
+
742
+ class FakeArray2:
743
+ def __init__(self, data):
744
+ self._data = data
745
+
746
+ def __array__(self, dtype=None, copy=None):
747
+ return self._data
748
+
749
+
750
+ class TestOverwrite:
751
+ """Check input overwrite behavior of the FFT functions."""
752
+
753
+ real_dtypes = (np.float32, np.float64)
754
+ dtypes = real_dtypes + (np.complex64, np.complex128)
755
+ fftsizes = [8, 16, 32]
756
+
757
+ def _check(self, x, routine, fftsize, axis, overwrite_x):
758
+ x2 = x.copy()
759
+ for fake in [lambda x: x, FakeArray, FakeArray2]:
760
+ routine(fake(x2), fftsize, axis, overwrite_x=overwrite_x)
761
+
762
+ sig = "{}({}{!r}, {!r}, axis={!r}, overwrite_x={!r})".format(
763
+ routine.__name__, x.dtype, x.shape, fftsize, axis, overwrite_x)
764
+ if not overwrite_x:
765
+ assert_equal(x2, x, err_msg="spurious overwrite in %s" % sig)
766
+
767
+ def _check_1d(self, routine, dtype, shape, axis, overwritable_dtypes,
768
+ fftsize, overwrite_x):
769
+ np.random.seed(1234)
770
+ if np.issubdtype(dtype, np.complexfloating):
771
+ data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
772
+ else:
773
+ data = np.random.randn(*shape)
774
+ data = data.astype(dtype)
775
+
776
+ self._check(data, routine, fftsize, axis,
777
+ overwrite_x=overwrite_x)
778
+
779
+ @pytest.mark.parametrize('dtype', dtypes)
780
+ @pytest.mark.parametrize('fftsize', fftsizes)
781
+ @pytest.mark.parametrize('overwrite_x', [True, False])
782
+ @pytest.mark.parametrize('shape,axes', [((16,), -1),
783
+ ((16, 2), 0),
784
+ ((2, 16), 1)])
785
+ def test_fft_ifft(self, dtype, fftsize, overwrite_x, shape, axes):
786
+ overwritable = (np.complex128, np.complex64)
787
+ self._check_1d(fft, dtype, shape, axes, overwritable,
788
+ fftsize, overwrite_x)
789
+ self._check_1d(ifft, dtype, shape, axes, overwritable,
790
+ fftsize, overwrite_x)
791
+
792
+ @pytest.mark.parametrize('dtype', real_dtypes)
793
+ @pytest.mark.parametrize('fftsize', fftsizes)
794
+ @pytest.mark.parametrize('overwrite_x', [True, False])
795
+ @pytest.mark.parametrize('shape,axes', [((16,), -1),
796
+ ((16, 2), 0),
797
+ ((2, 16), 1)])
798
+ def test_rfft_irfft(self, dtype, fftsize, overwrite_x, shape, axes):
799
+ overwritable = self.real_dtypes
800
+ self._check_1d(irfft, dtype, shape, axes, overwritable,
801
+ fftsize, overwrite_x)
802
+ self._check_1d(rfft, dtype, shape, axes, overwritable,
803
+ fftsize, overwrite_x)
804
+
805
+ def _check_nd_one(self, routine, dtype, shape, axes, overwritable_dtypes,
806
+ overwrite_x):
807
+ np.random.seed(1234)
808
+ if np.issubdtype(dtype, np.complexfloating):
809
+ data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
810
+ else:
811
+ data = np.random.randn(*shape)
812
+ data = data.astype(dtype)
813
+
814
+ def fftshape_iter(shp):
815
+ if len(shp) <= 0:
816
+ yield ()
817
+ else:
818
+ for j in (shp[0]//2, shp[0], shp[0]*2):
819
+ for rest in fftshape_iter(shp[1:]):
820
+ yield (j,) + rest
821
+
822
+ if axes is None:
823
+ part_shape = shape
824
+ else:
825
+ part_shape = tuple(np.take(shape, axes))
826
+
827
+ for fftshape in fftshape_iter(part_shape):
828
+ self._check(data, routine, fftshape, axes,
829
+ overwrite_x=overwrite_x)
830
+ if data.ndim > 1:
831
+ self._check(data.T, routine, fftshape, axes,
832
+ overwrite_x=overwrite_x)
833
+
834
+ @pytest.mark.parametrize('dtype', dtypes)
835
+ @pytest.mark.parametrize('overwrite_x', [True, False])
836
+ @pytest.mark.parametrize('shape,axes', [((16,), None),
837
+ ((16,), (0,)),
838
+ ((16, 2), (0,)),
839
+ ((2, 16), (1,)),
840
+ ((8, 16), None),
841
+ ((8, 16), (0, 1)),
842
+ ((8, 16, 2), (0, 1)),
843
+ ((8, 16, 2), (1, 2)),
844
+ ((8, 16, 2), (0,)),
845
+ ((8, 16, 2), (1,)),
846
+ ((8, 16, 2), (2,)),
847
+ ((8, 16, 2), None),
848
+ ((8, 16, 2), (0, 1, 2))])
849
+ def test_fftn_ifftn(self, dtype, overwrite_x, shape, axes):
850
+ overwritable = (np.complex128, np.complex64)
851
+ self._check_nd_one(fftn, dtype, shape, axes, overwritable,
852
+ overwrite_x)
853
+ self._check_nd_one(ifftn, dtype, shape, axes, overwritable,
854
+ overwrite_x)
855
+
856
+
857
+ @pytest.mark.parametrize('func', [fftn, ifftn, fft2])
858
+ def test_shape_axes_ndarray(func):
859
+ # Test fftn and ifftn work with NumPy arrays for shape and axes arguments
860
+ # Regression test for gh-13342
861
+ a = np.random.rand(10, 10)
862
+
863
+ expect = func(a, shape=(5, 5))
864
+ actual = func(a, shape=np.array([5, 5]))
865
+ assert_equal(expect, actual)
866
+
867
+ expect = func(a, axes=(-1,))
868
+ actual = func(a, axes=np.array([-1,]))
869
+ assert_equal(expect, actual)
870
+
871
+ expect = func(a, shape=(4, 7), axes=(1, 0))
872
+ actual = func(a, shape=np.array([4, 7]), axes=np.array([1, 0]))
873
+ assert_equal(expect, actual)
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/tests/test_helper.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Created by Pearu Peterson, September 2002
2
+
3
+ __usage__ = """
4
+ Build fftpack:
5
+ python setup_fftpack.py build
6
+ Run tests if scipy is installed:
7
+ python -c 'import scipy;scipy.fftpack.test(<level>)'
8
+ Run tests if fftpack is not installed:
9
+ python tests/test_helper.py [<level>]
10
+ """
11
+
12
+ from numpy.testing import assert_array_almost_equal
13
+ from scipy.fftpack import fftshift, ifftshift, fftfreq, rfftfreq
14
+
15
+ from numpy import pi, random
16
+
17
+ class TestFFTShift:
18
+
19
+ def test_definition(self):
20
+ x = [0,1,2,3,4,-4,-3,-2,-1]
21
+ y = [-4,-3,-2,-1,0,1,2,3,4]
22
+ assert_array_almost_equal(fftshift(x),y)
23
+ assert_array_almost_equal(ifftshift(y),x)
24
+ x = [0,1,2,3,4,-5,-4,-3,-2,-1]
25
+ y = [-5,-4,-3,-2,-1,0,1,2,3,4]
26
+ assert_array_almost_equal(fftshift(x),y)
27
+ assert_array_almost_equal(ifftshift(y),x)
28
+
29
+ def test_inverse(self):
30
+ for n in [1,4,9,100,211]:
31
+ x = random.random((n,))
32
+ assert_array_almost_equal(ifftshift(fftshift(x)),x)
33
+
34
+
35
+ class TestFFTFreq:
36
+
37
+ def test_definition(self):
38
+ x = [0,1,2,3,4,-4,-3,-2,-1]
39
+ assert_array_almost_equal(9*fftfreq(9),x)
40
+ assert_array_almost_equal(9*pi*fftfreq(9,pi),x)
41
+ x = [0,1,2,3,4,-5,-4,-3,-2,-1]
42
+ assert_array_almost_equal(10*fftfreq(10),x)
43
+ assert_array_almost_equal(10*pi*fftfreq(10,pi),x)
44
+
45
+
46
+ class TestRFFTFreq:
47
+
48
+ def test_definition(self):
49
+ x = [0,1,1,2,2,3,3,4,4]
50
+ assert_array_almost_equal(9*rfftfreq(9),x)
51
+ assert_array_almost_equal(9*pi*rfftfreq(9,pi),x)
52
+ x = [0,1,1,2,2,3,3,4,4,5]
53
+ assert_array_almost_equal(10*rfftfreq(10),x)
54
+ assert_array_almost_equal(10*pi*rfftfreq(10,pi),x)
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/tests/test_import.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Test possibility of patching fftpack with pyfftw.
2
+
3
+ No module source outside of scipy.fftpack should contain an import of
4
+ the form `from scipy.fftpack import ...`, so that a simple replacement
5
+ of scipy.fftpack by the corresponding fftw interface completely swaps
6
+ the two FFT implementations.
7
+
8
+ Because this simply inspects source files, we only need to run the test
9
+ on one version of Python.
10
+ """
11
+
12
+
13
+ from pathlib import Path
14
+ import re
15
+ import tokenize
16
+ from numpy.testing import assert_
17
+ import scipy
18
+
19
+ class TestFFTPackImport:
20
+ def test_fftpack_import(self):
21
+ base = Path(scipy.__file__).parent
22
+ regexp = r"\s*from.+\.fftpack import .*\n"
23
+ for path in base.rglob("*.py"):
24
+ if base / "fftpack" in path.parents:
25
+ continue
26
+ # use tokenize to auto-detect encoding on systems where no
27
+ # default encoding is defined (e.g., LANG='C')
28
+ with tokenize.open(str(path)) as file:
29
+ assert_(all(not re.fullmatch(regexp, line)
30
+ for line in file),
31
+ f"{path} contains an import from fftpack")
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/tests/test_pseudo_diffs.py ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Created by Pearu Peterson, September 2002
2
+
3
+ __usage__ = """
4
+ Build fftpack:
5
+ python setup_fftpack.py build
6
+ Run tests if scipy is installed:
7
+ python -c 'import scipy;scipy.fftpack.test(<level>)'
8
+ Run tests if fftpack is not installed:
9
+ python tests/test_pseudo_diffs.py [<level>]
10
+ """
11
+
12
+ from numpy.testing import (assert_equal, assert_almost_equal,
13
+ assert_array_almost_equal)
14
+ from scipy.fftpack import (diff, fft, ifft, tilbert, itilbert, hilbert,
15
+ ihilbert, shift, fftfreq, cs_diff, sc_diff,
16
+ ss_diff, cc_diff)
17
+
18
+ import numpy as np
19
+ from numpy import arange, sin, cos, pi, exp, tanh, sum, sign
20
+ from numpy.random import random
21
+
22
+
23
+ def direct_diff(x,k=1,period=None):
24
+ fx = fft(x)
25
+ n = len(fx)
26
+ if period is None:
27
+ period = 2*pi
28
+ w = fftfreq(n)*2j*pi/period*n
29
+ if k < 0:
30
+ w = 1 / w**k
31
+ w[0] = 0.0
32
+ else:
33
+ w = w**k
34
+ if n > 2000:
35
+ w[250:n-250] = 0.0
36
+ return ifft(w*fx).real
37
+
38
+
39
+ def direct_tilbert(x,h=1,period=None):
40
+ fx = fft(x)
41
+ n = len(fx)
42
+ if period is None:
43
+ period = 2*pi
44
+ w = fftfreq(n)*h*2*pi/period*n
45
+ w[0] = 1
46
+ w = 1j/tanh(w)
47
+ w[0] = 0j
48
+ return ifft(w*fx)
49
+
50
+
51
+ def direct_itilbert(x,h=1,period=None):
52
+ fx = fft(x)
53
+ n = len(fx)
54
+ if period is None:
55
+ period = 2*pi
56
+ w = fftfreq(n)*h*2*pi/period*n
57
+ w = -1j*tanh(w)
58
+ return ifft(w*fx)
59
+
60
+
61
+ def direct_hilbert(x):
62
+ fx = fft(x)
63
+ n = len(fx)
64
+ w = fftfreq(n)*n
65
+ w = 1j*sign(w)
66
+ return ifft(w*fx)
67
+
68
+
69
+ def direct_ihilbert(x):
70
+ return -direct_hilbert(x)
71
+
72
+
73
+ def direct_shift(x,a,period=None):
74
+ n = len(x)
75
+ if period is None:
76
+ k = fftfreq(n)*1j*n
77
+ else:
78
+ k = fftfreq(n)*2j*pi/period*n
79
+ return ifft(fft(x)*exp(k*a)).real
80
+
81
+
82
+ class TestDiff:
83
+
84
+ def test_definition(self):
85
+ for n in [16,17,64,127,32]:
86
+ x = arange(n)*2*pi/n
87
+ assert_array_almost_equal(diff(sin(x)),direct_diff(sin(x)))
88
+ assert_array_almost_equal(diff(sin(x),2),direct_diff(sin(x),2))
89
+ assert_array_almost_equal(diff(sin(x),3),direct_diff(sin(x),3))
90
+ assert_array_almost_equal(diff(sin(x),4),direct_diff(sin(x),4))
91
+ assert_array_almost_equal(diff(sin(x),5),direct_diff(sin(x),5))
92
+ assert_array_almost_equal(diff(sin(2*x),3),direct_diff(sin(2*x),3))
93
+ assert_array_almost_equal(diff(sin(2*x),4),direct_diff(sin(2*x),4))
94
+ assert_array_almost_equal(diff(cos(x)),direct_diff(cos(x)))
95
+ assert_array_almost_equal(diff(cos(x),2),direct_diff(cos(x),2))
96
+ assert_array_almost_equal(diff(cos(x),3),direct_diff(cos(x),3))
97
+ assert_array_almost_equal(diff(cos(x),4),direct_diff(cos(x),4))
98
+ assert_array_almost_equal(diff(cos(2*x)),direct_diff(cos(2*x)))
99
+ assert_array_almost_equal(diff(sin(x*n/8)),direct_diff(sin(x*n/8)))
100
+ assert_array_almost_equal(diff(cos(x*n/8)),direct_diff(cos(x*n/8)))
101
+ for k in range(5):
102
+ assert_array_almost_equal(diff(sin(4*x),k),direct_diff(sin(4*x),k))
103
+ assert_array_almost_equal(diff(cos(4*x),k),direct_diff(cos(4*x),k))
104
+
105
+ def test_period(self):
106
+ for n in [17,64]:
107
+ x = arange(n)/float(n)
108
+ assert_array_almost_equal(diff(sin(2*pi*x),period=1),
109
+ 2*pi*cos(2*pi*x))
110
+ assert_array_almost_equal(diff(sin(2*pi*x),3,period=1),
111
+ -(2*pi)**3*cos(2*pi*x))
112
+
113
+ def test_sin(self):
114
+ for n in [32,64,77]:
115
+ x = arange(n)*2*pi/n
116
+ assert_array_almost_equal(diff(sin(x)),cos(x))
117
+ assert_array_almost_equal(diff(cos(x)),-sin(x))
118
+ assert_array_almost_equal(diff(sin(x),2),-sin(x))
119
+ assert_array_almost_equal(diff(sin(x),4),sin(x))
120
+ assert_array_almost_equal(diff(sin(4*x)),4*cos(4*x))
121
+ assert_array_almost_equal(diff(sin(sin(x))),cos(x)*cos(sin(x)))
122
+
123
+ def test_expr(self):
124
+ for n in [64,77,100,128,256,512,1024,2048,4096,8192][:5]:
125
+ x = arange(n)*2*pi/n
126
+ f = sin(x)*cos(4*x)+exp(sin(3*x))
127
+ df = cos(x)*cos(4*x)-4*sin(x)*sin(4*x)+3*cos(3*x)*exp(sin(3*x))
128
+ ddf = -17*sin(x)*cos(4*x)-8*cos(x)*sin(4*x)\
129
+ - 9*sin(3*x)*exp(sin(3*x))+9*cos(3*x)**2*exp(sin(3*x))
130
+ d1 = diff(f)
131
+ assert_array_almost_equal(d1,df)
132
+ assert_array_almost_equal(diff(df),ddf)
133
+ assert_array_almost_equal(diff(f,2),ddf)
134
+ assert_array_almost_equal(diff(ddf,-1),df)
135
+
136
+ def test_expr_large(self):
137
+ for n in [2048,4096]:
138
+ x = arange(n)*2*pi/n
139
+ f = sin(x)*cos(4*x)+exp(sin(3*x))
140
+ df = cos(x)*cos(4*x)-4*sin(x)*sin(4*x)+3*cos(3*x)*exp(sin(3*x))
141
+ ddf = -17*sin(x)*cos(4*x)-8*cos(x)*sin(4*x)\
142
+ - 9*sin(3*x)*exp(sin(3*x))+9*cos(3*x)**2*exp(sin(3*x))
143
+ assert_array_almost_equal(diff(f),df)
144
+ assert_array_almost_equal(diff(df),ddf)
145
+ assert_array_almost_equal(diff(ddf,-1),df)
146
+ assert_array_almost_equal(diff(f,2),ddf)
147
+
148
+ def test_int(self):
149
+ n = 64
150
+ x = arange(n)*2*pi/n
151
+ assert_array_almost_equal(diff(sin(x),-1),-cos(x))
152
+ assert_array_almost_equal(diff(sin(x),-2),-sin(x))
153
+ assert_array_almost_equal(diff(sin(x),-4),sin(x))
154
+ assert_array_almost_equal(diff(2*cos(2*x),-1),sin(2*x))
155
+
156
+ def test_random_even(self):
157
+ for k in [0,2,4,6]:
158
+ for n in [60,32,64,56,55]:
159
+ f = random((n,))
160
+ af = sum(f,axis=0)/n
161
+ f = f-af
162
+ # zeroing Nyquist mode:
163
+ f = diff(diff(f,1),-1)
164
+ assert_almost_equal(sum(f,axis=0),0.0)
165
+ assert_array_almost_equal(diff(diff(f,k),-k),f)
166
+ assert_array_almost_equal(diff(diff(f,-k),k),f)
167
+
168
+ def test_random_odd(self):
169
+ for k in [0,1,2,3,4,5,6]:
170
+ for n in [33,65,55]:
171
+ f = random((n,))
172
+ af = sum(f,axis=0)/n
173
+ f = f-af
174
+ assert_almost_equal(sum(f,axis=0),0.0)
175
+ assert_array_almost_equal(diff(diff(f,k),-k),f)
176
+ assert_array_almost_equal(diff(diff(f,-k),k),f)
177
+
178
+ def test_zero_nyquist(self):
179
+ for k in [0,1,2,3,4,5,6]:
180
+ for n in [32,33,64,56,55]:
181
+ f = random((n,))
182
+ af = sum(f,axis=0)/n
183
+ f = f-af
184
+ # zeroing Nyquist mode:
185
+ f = diff(diff(f,1),-1)
186
+ assert_almost_equal(sum(f,axis=0),0.0)
187
+ assert_array_almost_equal(diff(diff(f,k),-k),f)
188
+ assert_array_almost_equal(diff(diff(f,-k),k),f)
189
+
190
+
191
+ class TestTilbert:
192
+
193
+ def test_definition(self):
194
+ for h in [0.1,0.5,1,5.5,10]:
195
+ for n in [16,17,64,127]:
196
+ x = arange(n)*2*pi/n
197
+ y = tilbert(sin(x),h)
198
+ y1 = direct_tilbert(sin(x),h)
199
+ assert_array_almost_equal(y,y1)
200
+ assert_array_almost_equal(tilbert(sin(x),h),
201
+ direct_tilbert(sin(x),h))
202
+ assert_array_almost_equal(tilbert(sin(2*x),h),
203
+ direct_tilbert(sin(2*x),h))
204
+
205
+ def test_random_even(self):
206
+ for h in [0.1,0.5,1,5.5,10]:
207
+ for n in [32,64,56]:
208
+ f = random((n,))
209
+ af = sum(f,axis=0)/n
210
+ f = f-af
211
+ assert_almost_equal(sum(f,axis=0),0.0)
212
+ assert_array_almost_equal(direct_tilbert(direct_itilbert(f,h),h),f)
213
+
214
+ def test_random_odd(self):
215
+ for h in [0.1,0.5,1,5.5,10]:
216
+ for n in [33,65,55]:
217
+ f = random((n,))
218
+ af = sum(f,axis=0)/n
219
+ f = f-af
220
+ assert_almost_equal(sum(f,axis=0),0.0)
221
+ assert_array_almost_equal(itilbert(tilbert(f,h),h),f)
222
+ assert_array_almost_equal(tilbert(itilbert(f,h),h),f)
223
+
224
+
225
+ class TestITilbert:
226
+
227
+ def test_definition(self):
228
+ for h in [0.1,0.5,1,5.5,10]:
229
+ for n in [16,17,64,127]:
230
+ x = arange(n)*2*pi/n
231
+ y = itilbert(sin(x),h)
232
+ y1 = direct_itilbert(sin(x),h)
233
+ assert_array_almost_equal(y,y1)
234
+ assert_array_almost_equal(itilbert(sin(x),h),
235
+ direct_itilbert(sin(x),h))
236
+ assert_array_almost_equal(itilbert(sin(2*x),h),
237
+ direct_itilbert(sin(2*x),h))
238
+
239
+
240
+ class TestHilbert:
241
+
242
+ def test_definition(self):
243
+ for n in [16,17,64,127]:
244
+ x = arange(n)*2*pi/n
245
+ y = hilbert(sin(x))
246
+ y1 = direct_hilbert(sin(x))
247
+ assert_array_almost_equal(y,y1)
248
+ assert_array_almost_equal(hilbert(sin(2*x)),
249
+ direct_hilbert(sin(2*x)))
250
+
251
+ def test_tilbert_relation(self):
252
+ for n in [16,17,64,127]:
253
+ x = arange(n)*2*pi/n
254
+ f = sin(x)+cos(2*x)*sin(x)
255
+ y = hilbert(f)
256
+ y1 = direct_hilbert(f)
257
+ assert_array_almost_equal(y,y1)
258
+ y2 = tilbert(f,h=10)
259
+ assert_array_almost_equal(y,y2)
260
+
261
+ def test_random_odd(self):
262
+ for n in [33,65,55]:
263
+ f = random((n,))
264
+ af = sum(f,axis=0)/n
265
+ f = f-af
266
+ assert_almost_equal(sum(f,axis=0),0.0)
267
+ assert_array_almost_equal(ihilbert(hilbert(f)),f)
268
+ assert_array_almost_equal(hilbert(ihilbert(f)),f)
269
+
270
+ def test_random_even(self):
271
+ for n in [32,64,56]:
272
+ f = random((n,))
273
+ af = sum(f,axis=0)/n
274
+ f = f-af
275
+ # zeroing Nyquist mode:
276
+ f = diff(diff(f,1),-1)
277
+ assert_almost_equal(sum(f,axis=0),0.0)
278
+ assert_array_almost_equal(direct_hilbert(direct_ihilbert(f)),f)
279
+ assert_array_almost_equal(hilbert(ihilbert(f)),f)
280
+
281
+
282
+ class TestIHilbert:
283
+
284
+ def test_definition(self):
285
+ for n in [16,17,64,127]:
286
+ x = arange(n)*2*pi/n
287
+ y = ihilbert(sin(x))
288
+ y1 = direct_ihilbert(sin(x))
289
+ assert_array_almost_equal(y,y1)
290
+ assert_array_almost_equal(ihilbert(sin(2*x)),
291
+ direct_ihilbert(sin(2*x)))
292
+
293
+ def test_itilbert_relation(self):
294
+ for n in [16,17,64,127]:
295
+ x = arange(n)*2*pi/n
296
+ f = sin(x)+cos(2*x)*sin(x)
297
+ y = ihilbert(f)
298
+ y1 = direct_ihilbert(f)
299
+ assert_array_almost_equal(y,y1)
300
+ y2 = itilbert(f,h=10)
301
+ assert_array_almost_equal(y,y2)
302
+
303
+
304
+ class TestShift:
305
+
306
+ def test_definition(self):
307
+ for n in [18,17,64,127,32,2048,256]:
308
+ x = arange(n)*2*pi/n
309
+ for a in [0.1,3]:
310
+ assert_array_almost_equal(shift(sin(x),a),direct_shift(sin(x),a))
311
+ assert_array_almost_equal(shift(sin(x),a),sin(x+a))
312
+ assert_array_almost_equal(shift(cos(x),a),cos(x+a))
313
+ assert_array_almost_equal(shift(cos(2*x)+sin(x),a),
314
+ cos(2*(x+a))+sin(x+a))
315
+ assert_array_almost_equal(shift(exp(sin(x)),a),exp(sin(x+a)))
316
+ assert_array_almost_equal(shift(sin(x),2*pi),sin(x))
317
+ assert_array_almost_equal(shift(sin(x),pi),-sin(x))
318
+ assert_array_almost_equal(shift(sin(x),pi/2),cos(x))
319
+
320
+
321
+ class TestOverwrite:
322
+ """Check input overwrite behavior """
323
+
324
+ real_dtypes = (np.float32, np.float64)
325
+ dtypes = real_dtypes + (np.complex64, np.complex128)
326
+
327
+ def _check(self, x, routine, *args, **kwargs):
328
+ x2 = x.copy()
329
+ routine(x2, *args, **kwargs)
330
+ sig = routine.__name__
331
+ if args:
332
+ sig += repr(args)
333
+ if kwargs:
334
+ sig += repr(kwargs)
335
+ assert_equal(x2, x, err_msg="spurious overwrite in %s" % sig)
336
+
337
+ def _check_1d(self, routine, dtype, shape, *args, **kwargs):
338
+ np.random.seed(1234)
339
+ if np.issubdtype(dtype, np.complexfloating):
340
+ data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
341
+ else:
342
+ data = np.random.randn(*shape)
343
+ data = data.astype(dtype)
344
+ self._check(data, routine, *args, **kwargs)
345
+
346
+ def test_diff(self):
347
+ for dtype in self.dtypes:
348
+ self._check_1d(diff, dtype, (16,))
349
+
350
+ def test_tilbert(self):
351
+ for dtype in self.dtypes:
352
+ self._check_1d(tilbert, dtype, (16,), 1.6)
353
+
354
+ def test_itilbert(self):
355
+ for dtype in self.dtypes:
356
+ self._check_1d(itilbert, dtype, (16,), 1.6)
357
+
358
+ def test_hilbert(self):
359
+ for dtype in self.dtypes:
360
+ self._check_1d(hilbert, dtype, (16,))
361
+
362
+ def test_cs_diff(self):
363
+ for dtype in self.dtypes:
364
+ self._check_1d(cs_diff, dtype, (16,), 1.0, 4.0)
365
+
366
+ def test_sc_diff(self):
367
+ for dtype in self.dtypes:
368
+ self._check_1d(sc_diff, dtype, (16,), 1.0, 4.0)
369
+
370
+ def test_ss_diff(self):
371
+ for dtype in self.dtypes:
372
+ self._check_1d(ss_diff, dtype, (16,), 1.0, 4.0)
373
+
374
+ def test_cc_diff(self):
375
+ for dtype in self.dtypes:
376
+ self._check_1d(cc_diff, dtype, (16,), 1.0, 4.0)
377
+
378
+ def test_shift(self):
379
+ for dtype in self.dtypes:
380
+ self._check_1d(shift, dtype, (16,), 1.0)
llmeval-env/lib/python3.10/site-packages/scipy/fftpack/tests/test_real_transforms.py ADDED
@@ -0,0 +1,815 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from os.path import join, dirname
2
+
3
+ import numpy as np
4
+ from numpy.testing import assert_array_almost_equal, assert_equal
5
+ import pytest
6
+ from pytest import raises as assert_raises
7
+
8
+ from scipy.fftpack._realtransforms import (
9
+ dct, idct, dst, idst, dctn, idctn, dstn, idstn)
10
+
11
+ # Matlab reference data
12
+ MDATA = np.load(join(dirname(__file__), 'test.npz'))
13
+ X = [MDATA['x%d' % i] for i in range(8)]
14
+ Y = [MDATA['y%d' % i] for i in range(8)]
15
+
16
+ # FFTW reference data: the data are organized as follows:
17
+ # * SIZES is an array containing all available sizes
18
+ # * for every type (1, 2, 3, 4) and every size, the array dct_type_size
19
+ # contains the output of the DCT applied to the input np.linspace(0, size-1,
20
+ # size)
21
+ FFTWDATA_DOUBLE = np.load(join(dirname(__file__), 'fftw_double_ref.npz'))
22
+ FFTWDATA_SINGLE = np.load(join(dirname(__file__), 'fftw_single_ref.npz'))
23
+ FFTWDATA_SIZES = FFTWDATA_DOUBLE['sizes']
24
+
25
+
26
+ def fftw_dct_ref(type, size, dt):
27
+ x = np.linspace(0, size-1, size).astype(dt)
28
+ dt = np.result_type(np.float32, dt)
29
+ if dt == np.float64:
30
+ data = FFTWDATA_DOUBLE
31
+ elif dt == np.float32:
32
+ data = FFTWDATA_SINGLE
33
+ else:
34
+ raise ValueError()
35
+ y = (data['dct_%d_%d' % (type, size)]).astype(dt)
36
+ return x, y, dt
37
+
38
+
39
+ def fftw_dst_ref(type, size, dt):
40
+ x = np.linspace(0, size-1, size).astype(dt)
41
+ dt = np.result_type(np.float32, dt)
42
+ if dt == np.float64:
43
+ data = FFTWDATA_DOUBLE
44
+ elif dt == np.float32:
45
+ data = FFTWDATA_SINGLE
46
+ else:
47
+ raise ValueError()
48
+ y = (data['dst_%d_%d' % (type, size)]).astype(dt)
49
+ return x, y, dt
50
+
51
+
52
+ def dct_2d_ref(x, **kwargs):
53
+ """Calculate reference values for testing dct2."""
54
+ x = np.array(x, copy=True)
55
+ for row in range(x.shape[0]):
56
+ x[row, :] = dct(x[row, :], **kwargs)
57
+ for col in range(x.shape[1]):
58
+ x[:, col] = dct(x[:, col], **kwargs)
59
+ return x
60
+
61
+
62
+ def idct_2d_ref(x, **kwargs):
63
+ """Calculate reference values for testing idct2."""
64
+ x = np.array(x, copy=True)
65
+ for row in range(x.shape[0]):
66
+ x[row, :] = idct(x[row, :], **kwargs)
67
+ for col in range(x.shape[1]):
68
+ x[:, col] = idct(x[:, col], **kwargs)
69
+ return x
70
+
71
+
72
+ def dst_2d_ref(x, **kwargs):
73
+ """Calculate reference values for testing dst2."""
74
+ x = np.array(x, copy=True)
75
+ for row in range(x.shape[0]):
76
+ x[row, :] = dst(x[row, :], **kwargs)
77
+ for col in range(x.shape[1]):
78
+ x[:, col] = dst(x[:, col], **kwargs)
79
+ return x
80
+
81
+
82
+ def idst_2d_ref(x, **kwargs):
83
+ """Calculate reference values for testing idst2."""
84
+ x = np.array(x, copy=True)
85
+ for row in range(x.shape[0]):
86
+ x[row, :] = idst(x[row, :], **kwargs)
87
+ for col in range(x.shape[1]):
88
+ x[:, col] = idst(x[:, col], **kwargs)
89
+ return x
90
+
91
+
92
+ def naive_dct1(x, norm=None):
93
+ """Calculate textbook definition version of DCT-I."""
94
+ x = np.array(x, copy=True)
95
+ N = len(x)
96
+ M = N-1
97
+ y = np.zeros(N)
98
+ m0, m = 1, 2
99
+ if norm == 'ortho':
100
+ m0 = np.sqrt(1.0/M)
101
+ m = np.sqrt(2.0/M)
102
+ for k in range(N):
103
+ for n in range(1, N-1):
104
+ y[k] += m*x[n]*np.cos(np.pi*n*k/M)
105
+ y[k] += m0 * x[0]
106
+ y[k] += m0 * x[N-1] * (1 if k % 2 == 0 else -1)
107
+ if norm == 'ortho':
108
+ y[0] *= 1/np.sqrt(2)
109
+ y[N-1] *= 1/np.sqrt(2)
110
+ return y
111
+
112
+
113
+ def naive_dst1(x, norm=None):
114
+ """Calculate textbook definition version of DST-I."""
115
+ x = np.array(x, copy=True)
116
+ N = len(x)
117
+ M = N+1
118
+ y = np.zeros(N)
119
+ for k in range(N):
120
+ for n in range(N):
121
+ y[k] += 2*x[n]*np.sin(np.pi*(n+1.0)*(k+1.0)/M)
122
+ if norm == 'ortho':
123
+ y *= np.sqrt(0.5/M)
124
+ return y
125
+
126
+
127
+ def naive_dct4(x, norm=None):
128
+ """Calculate textbook definition version of DCT-IV."""
129
+ x = np.array(x, copy=True)
130
+ N = len(x)
131
+ y = np.zeros(N)
132
+ for k in range(N):
133
+ for n in range(N):
134
+ y[k] += x[n]*np.cos(np.pi*(n+0.5)*(k+0.5)/(N))
135
+ if norm == 'ortho':
136
+ y *= np.sqrt(2.0/N)
137
+ else:
138
+ y *= 2
139
+ return y
140
+
141
+
142
+ def naive_dst4(x, norm=None):
143
+ """Calculate textbook definition version of DST-IV."""
144
+ x = np.array(x, copy=True)
145
+ N = len(x)
146
+ y = np.zeros(N)
147
+ for k in range(N):
148
+ for n in range(N):
149
+ y[k] += x[n]*np.sin(np.pi*(n+0.5)*(k+0.5)/(N))
150
+ if norm == 'ortho':
151
+ y *= np.sqrt(2.0/N)
152
+ else:
153
+ y *= 2
154
+ return y
155
+
156
+
157
+ class TestComplex:
158
+ def test_dct_complex64(self):
159
+ y = dct(1j*np.arange(5, dtype=np.complex64))
160
+ x = 1j*dct(np.arange(5))
161
+ assert_array_almost_equal(x, y)
162
+
163
+ def test_dct_complex(self):
164
+ y = dct(np.arange(5)*1j)
165
+ x = 1j*dct(np.arange(5))
166
+ assert_array_almost_equal(x, y)
167
+
168
+ def test_idct_complex(self):
169
+ y = idct(np.arange(5)*1j)
170
+ x = 1j*idct(np.arange(5))
171
+ assert_array_almost_equal(x, y)
172
+
173
+ def test_dst_complex64(self):
174
+ y = dst(np.arange(5, dtype=np.complex64)*1j)
175
+ x = 1j*dst(np.arange(5))
176
+ assert_array_almost_equal(x, y)
177
+
178
+ def test_dst_complex(self):
179
+ y = dst(np.arange(5)*1j)
180
+ x = 1j*dst(np.arange(5))
181
+ assert_array_almost_equal(x, y)
182
+
183
+ def test_idst_complex(self):
184
+ y = idst(np.arange(5)*1j)
185
+ x = 1j*idst(np.arange(5))
186
+ assert_array_almost_equal(x, y)
187
+
188
+
189
+ class _TestDCTBase:
190
+ def setup_method(self):
191
+ self.rdt = None
192
+ self.dec = 14
193
+ self.type = None
194
+
195
+ def test_definition(self):
196
+ for i in FFTWDATA_SIZES:
197
+ x, yr, dt = fftw_dct_ref(self.type, i, self.rdt)
198
+ y = dct(x, type=self.type)
199
+ assert_equal(y.dtype, dt)
200
+ # XXX: we divide by np.max(y) because the tests fail otherwise. We
201
+ # should really use something like assert_array_approx_equal. The
202
+ # difference is due to fftw using a better algorithm w.r.t error
203
+ # propagation compared to the ones from fftpack.
204
+ assert_array_almost_equal(y / np.max(y), yr / np.max(y), decimal=self.dec,
205
+ err_msg="Size %d failed" % i)
206
+
207
+ def test_axis(self):
208
+ nt = 2
209
+ for i in [7, 8, 9, 16, 32, 64]:
210
+ x = np.random.randn(nt, i)
211
+ y = dct(x, type=self.type)
212
+ for j in range(nt):
213
+ assert_array_almost_equal(y[j], dct(x[j], type=self.type),
214
+ decimal=self.dec)
215
+
216
+ x = x.T
217
+ y = dct(x, axis=0, type=self.type)
218
+ for j in range(nt):
219
+ assert_array_almost_equal(y[:,j], dct(x[:,j], type=self.type),
220
+ decimal=self.dec)
221
+
222
+
223
+ class _TestDCTIBase(_TestDCTBase):
224
+ def test_definition_ortho(self):
225
+ # Test orthornomal mode.
226
+ dt = np.result_type(np.float32, self.rdt)
227
+ for xr in X:
228
+ x = np.array(xr, dtype=self.rdt)
229
+ y = dct(x, norm='ortho', type=1)
230
+ y2 = naive_dct1(x, norm='ortho')
231
+ assert_equal(y.dtype, dt)
232
+ assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec)
233
+
234
+ class _TestDCTIIBase(_TestDCTBase):
235
+ def test_definition_matlab(self):
236
+ # Test correspondence with MATLAB (orthornomal mode).
237
+ dt = np.result_type(np.float32, self.rdt)
238
+ for xr, yr in zip(X, Y):
239
+ x = np.array(xr, dtype=dt)
240
+ y = dct(x, norm="ortho", type=2)
241
+ assert_equal(y.dtype, dt)
242
+ assert_array_almost_equal(y, yr, decimal=self.dec)
243
+
244
+
245
+ class _TestDCTIIIBase(_TestDCTBase):
246
+ def test_definition_ortho(self):
247
+ # Test orthornomal mode.
248
+ dt = np.result_type(np.float32, self.rdt)
249
+ for xr in X:
250
+ x = np.array(xr, dtype=self.rdt)
251
+ y = dct(x, norm='ortho', type=2)
252
+ xi = dct(y, norm="ortho", type=3)
253
+ assert_equal(xi.dtype, dt)
254
+ assert_array_almost_equal(xi, x, decimal=self.dec)
255
+
256
+ class _TestDCTIVBase(_TestDCTBase):
257
+ def test_definition_ortho(self):
258
+ # Test orthornomal mode.
259
+ dt = np.result_type(np.float32, self.rdt)
260
+ for xr in X:
261
+ x = np.array(xr, dtype=self.rdt)
262
+ y = dct(x, norm='ortho', type=4)
263
+ y2 = naive_dct4(x, norm='ortho')
264
+ assert_equal(y.dtype, dt)
265
+ assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec)
266
+
267
+
268
+ class TestDCTIDouble(_TestDCTIBase):
269
+ def setup_method(self):
270
+ self.rdt = np.float64
271
+ self.dec = 10
272
+ self.type = 1
273
+
274
+
275
+ class TestDCTIFloat(_TestDCTIBase):
276
+ def setup_method(self):
277
+ self.rdt = np.float32
278
+ self.dec = 4
279
+ self.type = 1
280
+
281
+
282
+ class TestDCTIInt(_TestDCTIBase):
283
+ def setup_method(self):
284
+ self.rdt = int
285
+ self.dec = 5
286
+ self.type = 1
287
+
288
+
289
+ class TestDCTIIDouble(_TestDCTIIBase):
290
+ def setup_method(self):
291
+ self.rdt = np.float64
292
+ self.dec = 10
293
+ self.type = 2
294
+
295
+
296
+ class TestDCTIIFloat(_TestDCTIIBase):
297
+ def setup_method(self):
298
+ self.rdt = np.float32
299
+ self.dec = 5
300
+ self.type = 2
301
+
302
+
303
+ class TestDCTIIInt(_TestDCTIIBase):
304
+ def setup_method(self):
305
+ self.rdt = int
306
+ self.dec = 5
307
+ self.type = 2
308
+
309
+
310
+ class TestDCTIIIDouble(_TestDCTIIIBase):
311
+ def setup_method(self):
312
+ self.rdt = np.float64
313
+ self.dec = 14
314
+ self.type = 3
315
+
316
+
317
+ class TestDCTIIIFloat(_TestDCTIIIBase):
318
+ def setup_method(self):
319
+ self.rdt = np.float32
320
+ self.dec = 5
321
+ self.type = 3
322
+
323
+
324
+ class TestDCTIIIInt(_TestDCTIIIBase):
325
+ def setup_method(self):
326
+ self.rdt = int
327
+ self.dec = 5
328
+ self.type = 3
329
+
330
+
331
+ class TestDCTIVDouble(_TestDCTIVBase):
332
+ def setup_method(self):
333
+ self.rdt = np.float64
334
+ self.dec = 12
335
+ self.type = 3
336
+
337
+
338
+ class TestDCTIVFloat(_TestDCTIVBase):
339
+ def setup_method(self):
340
+ self.rdt = np.float32
341
+ self.dec = 5
342
+ self.type = 3
343
+
344
+
345
+ class TestDCTIVInt(_TestDCTIVBase):
346
+ def setup_method(self):
347
+ self.rdt = int
348
+ self.dec = 5
349
+ self.type = 3
350
+
351
+
352
+ class _TestIDCTBase:
353
+ def setup_method(self):
354
+ self.rdt = None
355
+ self.dec = 14
356
+ self.type = None
357
+
358
+ def test_definition(self):
359
+ for i in FFTWDATA_SIZES:
360
+ xr, yr, dt = fftw_dct_ref(self.type, i, self.rdt)
361
+ x = idct(yr, type=self.type)
362
+ if self.type == 1:
363
+ x /= 2 * (i-1)
364
+ else:
365
+ x /= 2 * i
366
+ assert_equal(x.dtype, dt)
367
+ # XXX: we divide by np.max(y) because the tests fail otherwise. We
368
+ # should really use something like assert_array_approx_equal. The
369
+ # difference is due to fftw using a better algorithm w.r.t error
370
+ # propagation compared to the ones from fftpack.
371
+ assert_array_almost_equal(x / np.max(x), xr / np.max(x), decimal=self.dec,
372
+ err_msg="Size %d failed" % i)
373
+
374
+
375
+ class TestIDCTIDouble(_TestIDCTBase):
376
+ def setup_method(self):
377
+ self.rdt = np.float64
378
+ self.dec = 10
379
+ self.type = 1
380
+
381
+
382
+ class TestIDCTIFloat(_TestIDCTBase):
383
+ def setup_method(self):
384
+ self.rdt = np.float32
385
+ self.dec = 4
386
+ self.type = 1
387
+
388
+
389
+ class TestIDCTIInt(_TestIDCTBase):
390
+ def setup_method(self):
391
+ self.rdt = int
392
+ self.dec = 4
393
+ self.type = 1
394
+
395
+
396
+ class TestIDCTIIDouble(_TestIDCTBase):
397
+ def setup_method(self):
398
+ self.rdt = np.float64
399
+ self.dec = 10
400
+ self.type = 2
401
+
402
+
403
+ class TestIDCTIIFloat(_TestIDCTBase):
404
+ def setup_method(self):
405
+ self.rdt = np.float32
406
+ self.dec = 5
407
+ self.type = 2
408
+
409
+
410
+ class TestIDCTIIInt(_TestIDCTBase):
411
+ def setup_method(self):
412
+ self.rdt = int
413
+ self.dec = 5
414
+ self.type = 2
415
+
416
+
417
+ class TestIDCTIIIDouble(_TestIDCTBase):
418
+ def setup_method(self):
419
+ self.rdt = np.float64
420
+ self.dec = 14
421
+ self.type = 3
422
+
423
+
424
+ class TestIDCTIIIFloat(_TestIDCTBase):
425
+ def setup_method(self):
426
+ self.rdt = np.float32
427
+ self.dec = 5
428
+ self.type = 3
429
+
430
+
431
+ class TestIDCTIIIInt(_TestIDCTBase):
432
+ def setup_method(self):
433
+ self.rdt = int
434
+ self.dec = 5
435
+ self.type = 3
436
+
437
+ class TestIDCTIVDouble(_TestIDCTBase):
438
+ def setup_method(self):
439
+ self.rdt = np.float64
440
+ self.dec = 12
441
+ self.type = 4
442
+
443
+
444
+ class TestIDCTIVFloat(_TestIDCTBase):
445
+ def setup_method(self):
446
+ self.rdt = np.float32
447
+ self.dec = 5
448
+ self.type = 4
449
+
450
+
451
+ class TestIDCTIVInt(_TestIDCTBase):
452
+ def setup_method(self):
453
+ self.rdt = int
454
+ self.dec = 5
455
+ self.type = 4
456
+
457
+ class _TestDSTBase:
458
+ def setup_method(self):
459
+ self.rdt = None # dtype
460
+ self.dec = None # number of decimals to match
461
+ self.type = None # dst type
462
+
463
+ def test_definition(self):
464
+ for i in FFTWDATA_SIZES:
465
+ xr, yr, dt = fftw_dst_ref(self.type, i, self.rdt)
466
+ y = dst(xr, type=self.type)
467
+ assert_equal(y.dtype, dt)
468
+ # XXX: we divide by np.max(y) because the tests fail otherwise. We
469
+ # should really use something like assert_array_approx_equal. The
470
+ # difference is due to fftw using a better algorithm w.r.t error
471
+ # propagation compared to the ones from fftpack.
472
+ assert_array_almost_equal(y / np.max(y), yr / np.max(y), decimal=self.dec,
473
+ err_msg="Size %d failed" % i)
474
+
475
+
476
+ class _TestDSTIBase(_TestDSTBase):
477
+ def test_definition_ortho(self):
478
+ # Test orthornomal mode.
479
+ dt = np.result_type(np.float32, self.rdt)
480
+ for xr in X:
481
+ x = np.array(xr, dtype=self.rdt)
482
+ y = dst(x, norm='ortho', type=1)
483
+ y2 = naive_dst1(x, norm='ortho')
484
+ assert_equal(y.dtype, dt)
485
+ assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec)
486
+
487
+ class _TestDSTIVBase(_TestDSTBase):
488
+ def test_definition_ortho(self):
489
+ # Test orthornomal mode.
490
+ dt = np.result_type(np.float32, self.rdt)
491
+ for xr in X:
492
+ x = np.array(xr, dtype=self.rdt)
493
+ y = dst(x, norm='ortho', type=4)
494
+ y2 = naive_dst4(x, norm='ortho')
495
+ assert_equal(y.dtype, dt)
496
+ assert_array_almost_equal(y, y2, decimal=self.dec)
497
+
498
+ class TestDSTIDouble(_TestDSTIBase):
499
+ def setup_method(self):
500
+ self.rdt = np.float64
501
+ self.dec = 12
502
+ self.type = 1
503
+
504
+
505
+ class TestDSTIFloat(_TestDSTIBase):
506
+ def setup_method(self):
507
+ self.rdt = np.float32
508
+ self.dec = 4
509
+ self.type = 1
510
+
511
+
512
+ class TestDSTIInt(_TestDSTIBase):
513
+ def setup_method(self):
514
+ self.rdt = int
515
+ self.dec = 5
516
+ self.type = 1
517
+
518
+
519
+ class TestDSTIIDouble(_TestDSTBase):
520
+ def setup_method(self):
521
+ self.rdt = np.float64
522
+ self.dec = 14
523
+ self.type = 2
524
+
525
+
526
+ class TestDSTIIFloat(_TestDSTBase):
527
+ def setup_method(self):
528
+ self.rdt = np.float32
529
+ self.dec = 6
530
+ self.type = 2
531
+
532
+
533
+ class TestDSTIIInt(_TestDSTBase):
534
+ def setup_method(self):
535
+ self.rdt = int
536
+ self.dec = 6
537
+ self.type = 2
538
+
539
+
540
+ class TestDSTIIIDouble(_TestDSTBase):
541
+ def setup_method(self):
542
+ self.rdt = np.float64
543
+ self.dec = 14
544
+ self.type = 3
545
+
546
+
547
+ class TestDSTIIIFloat(_TestDSTBase):
548
+ def setup_method(self):
549
+ self.rdt = np.float32
550
+ self.dec = 7
551
+ self.type = 3
552
+
553
+
554
+ class TestDSTIIIInt(_TestDSTBase):
555
+ def setup_method(self):
556
+ self.rdt = int
557
+ self.dec = 7
558
+ self.type = 3
559
+
560
+
561
+ class TestDSTIVDouble(_TestDSTIVBase):
562
+ def setup_method(self):
563
+ self.rdt = np.float64
564
+ self.dec = 12
565
+ self.type = 4
566
+
567
+
568
+ class TestDSTIVFloat(_TestDSTIVBase):
569
+ def setup_method(self):
570
+ self.rdt = np.float32
571
+ self.dec = 4
572
+ self.type = 4
573
+
574
+
575
+ class TestDSTIVInt(_TestDSTIVBase):
576
+ def setup_method(self):
577
+ self.rdt = int
578
+ self.dec = 5
579
+ self.type = 4
580
+
581
+
582
+ class _TestIDSTBase:
583
+ def setup_method(self):
584
+ self.rdt = None
585
+ self.dec = None
586
+ self.type = None
587
+
588
+ def test_definition(self):
589
+ for i in FFTWDATA_SIZES:
590
+ xr, yr, dt = fftw_dst_ref(self.type, i, self.rdt)
591
+ x = idst(yr, type=self.type)
592
+ if self.type == 1:
593
+ x /= 2 * (i+1)
594
+ else:
595
+ x /= 2 * i
596
+ assert_equal(x.dtype, dt)
597
+ # XXX: we divide by np.max(x) because the tests fail otherwise. We
598
+ # should really use something like assert_array_approx_equal. The
599
+ # difference is due to fftw using a better algorithm w.r.t error
600
+ # propagation compared to the ones from fftpack.
601
+ assert_array_almost_equal(x / np.max(x), xr / np.max(x), decimal=self.dec,
602
+ err_msg="Size %d failed" % i)
603
+
604
+
605
+ class TestIDSTIDouble(_TestIDSTBase):
606
+ def setup_method(self):
607
+ self.rdt = np.float64
608
+ self.dec = 12
609
+ self.type = 1
610
+
611
+
612
+ class TestIDSTIFloat(_TestIDSTBase):
613
+ def setup_method(self):
614
+ self.rdt = np.float32
615
+ self.dec = 4
616
+ self.type = 1
617
+
618
+
619
+ class TestIDSTIInt(_TestIDSTBase):
620
+ def setup_method(self):
621
+ self.rdt = int
622
+ self.dec = 4
623
+ self.type = 1
624
+
625
+
626
+ class TestIDSTIIDouble(_TestIDSTBase):
627
+ def setup_method(self):
628
+ self.rdt = np.float64
629
+ self.dec = 14
630
+ self.type = 2
631
+
632
+
633
+ class TestIDSTIIFloat(_TestIDSTBase):
634
+ def setup_method(self):
635
+ self.rdt = np.float32
636
+ self.dec = 6
637
+ self.type = 2
638
+
639
+
640
+ class TestIDSTIIInt(_TestIDSTBase):
641
+ def setup_method(self):
642
+ self.rdt = int
643
+ self.dec = 6
644
+ self.type = 2
645
+
646
+
647
+ class TestIDSTIIIDouble(_TestIDSTBase):
648
+ def setup_method(self):
649
+ self.rdt = np.float64
650
+ self.dec = 14
651
+ self.type = 3
652
+
653
+
654
+ class TestIDSTIIIFloat(_TestIDSTBase):
655
+ def setup_method(self):
656
+ self.rdt = np.float32
657
+ self.dec = 6
658
+ self.type = 3
659
+
660
+
661
+ class TestIDSTIIIInt(_TestIDSTBase):
662
+ def setup_method(self):
663
+ self.rdt = int
664
+ self.dec = 6
665
+ self.type = 3
666
+
667
+
668
+ class TestIDSTIVDouble(_TestIDSTBase):
669
+ def setup_method(self):
670
+ self.rdt = np.float64
671
+ self.dec = 12
672
+ self.type = 4
673
+
674
+
675
+ class TestIDSTIVFloat(_TestIDSTBase):
676
+ def setup_method(self):
677
+ self.rdt = np.float32
678
+ self.dec = 6
679
+ self.type = 4
680
+
681
+
682
+ class TestIDSTIVnt(_TestIDSTBase):
683
+ def setup_method(self):
684
+ self.rdt = int
685
+ self.dec = 6
686
+ self.type = 4
687
+
688
+
689
+ class TestOverwrite:
690
+ """Check input overwrite behavior."""
691
+
692
+ real_dtypes = [np.float32, np.float64]
693
+
694
+ def _check(self, x, routine, type, fftsize, axis, norm, overwrite_x, **kw):
695
+ x2 = x.copy()
696
+ routine(x2, type, fftsize, axis, norm, overwrite_x=overwrite_x)
697
+
698
+ sig = "{}({}{!r}, {!r}, axis={!r}, overwrite_x={!r})".format(
699
+ routine.__name__, x.dtype, x.shape, fftsize, axis, overwrite_x)
700
+ if not overwrite_x:
701
+ assert_equal(x2, x, err_msg="spurious overwrite in %s" % sig)
702
+
703
+ def _check_1d(self, routine, dtype, shape, axis):
704
+ np.random.seed(1234)
705
+ if np.issubdtype(dtype, np.complexfloating):
706
+ data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
707
+ else:
708
+ data = np.random.randn(*shape)
709
+ data = data.astype(dtype)
710
+
711
+ for type in [1, 2, 3, 4]:
712
+ for overwrite_x in [True, False]:
713
+ for norm in [None, 'ortho']:
714
+ self._check(data, routine, type, None, axis, norm,
715
+ overwrite_x)
716
+
717
+ def test_dct(self):
718
+ for dtype in self.real_dtypes:
719
+ self._check_1d(dct, dtype, (16,), -1)
720
+ self._check_1d(dct, dtype, (16, 2), 0)
721
+ self._check_1d(dct, dtype, (2, 16), 1)
722
+
723
+ def test_idct(self):
724
+ for dtype in self.real_dtypes:
725
+ self._check_1d(idct, dtype, (16,), -1)
726
+ self._check_1d(idct, dtype, (16, 2), 0)
727
+ self._check_1d(idct, dtype, (2, 16), 1)
728
+
729
+ def test_dst(self):
730
+ for dtype in self.real_dtypes:
731
+ self._check_1d(dst, dtype, (16,), -1)
732
+ self._check_1d(dst, dtype, (16, 2), 0)
733
+ self._check_1d(dst, dtype, (2, 16), 1)
734
+
735
+ def test_idst(self):
736
+ for dtype in self.real_dtypes:
737
+ self._check_1d(idst, dtype, (16,), -1)
738
+ self._check_1d(idst, dtype, (16, 2), 0)
739
+ self._check_1d(idst, dtype, (2, 16), 1)
740
+
741
+
742
+ class Test_DCTN_IDCTN:
743
+ dec = 14
744
+ dct_type = [1, 2, 3, 4]
745
+ norms = [None, 'ortho']
746
+ rstate = np.random.RandomState(1234)
747
+ shape = (32, 16)
748
+ data = rstate.randn(*shape)
749
+
750
+ @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
751
+ (dstn, idstn)])
752
+ @pytest.mark.parametrize('axes', [None,
753
+ 1, (1,), [1],
754
+ 0, (0,), [0],
755
+ (0, 1), [0, 1],
756
+ (-2, -1), [-2, -1]])
757
+ @pytest.mark.parametrize('dct_type', dct_type)
758
+ @pytest.mark.parametrize('norm', ['ortho'])
759
+ def test_axes_round_trip(self, fforward, finverse, axes, dct_type, norm):
760
+ tmp = fforward(self.data, type=dct_type, axes=axes, norm=norm)
761
+ tmp = finverse(tmp, type=dct_type, axes=axes, norm=norm)
762
+ assert_array_almost_equal(self.data, tmp, decimal=12)
763
+
764
+ @pytest.mark.parametrize('fforward,fforward_ref', [(dctn, dct_2d_ref),
765
+ (dstn, dst_2d_ref)])
766
+ @pytest.mark.parametrize('dct_type', dct_type)
767
+ @pytest.mark.parametrize('norm', norms)
768
+ def test_dctn_vs_2d_reference(self, fforward, fforward_ref,
769
+ dct_type, norm):
770
+ y1 = fforward(self.data, type=dct_type, axes=None, norm=norm)
771
+ y2 = fforward_ref(self.data, type=dct_type, norm=norm)
772
+ assert_array_almost_equal(y1, y2, decimal=11)
773
+
774
+ @pytest.mark.parametrize('finverse,finverse_ref', [(idctn, idct_2d_ref),
775
+ (idstn, idst_2d_ref)])
776
+ @pytest.mark.parametrize('dct_type', dct_type)
777
+ @pytest.mark.parametrize('norm', [None, 'ortho'])
778
+ def test_idctn_vs_2d_reference(self, finverse, finverse_ref,
779
+ dct_type, norm):
780
+ fdata = dctn(self.data, type=dct_type, norm=norm)
781
+ y1 = finverse(fdata, type=dct_type, norm=norm)
782
+ y2 = finverse_ref(fdata, type=dct_type, norm=norm)
783
+ assert_array_almost_equal(y1, y2, decimal=11)
784
+
785
+ @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
786
+ (dstn, idstn)])
787
+ def test_axes_and_shape(self, fforward, finverse):
788
+ with assert_raises(ValueError,
789
+ match="when given, axes and shape arguments"
790
+ " have to be of the same length"):
791
+ fforward(self.data, shape=self.data.shape[0], axes=(0, 1))
792
+
793
+ with assert_raises(ValueError,
794
+ match="when given, axes and shape arguments"
795
+ " have to be of the same length"):
796
+ fforward(self.data, shape=self.data.shape[0], axes=None)
797
+
798
+ with assert_raises(ValueError,
799
+ match="when given, axes and shape arguments"
800
+ " have to be of the same length"):
801
+ fforward(self.data, shape=self.data.shape, axes=0)
802
+
803
+ @pytest.mark.parametrize('fforward', [dctn, dstn])
804
+ def test_shape(self, fforward):
805
+ tmp = fforward(self.data, shape=(128, 128), axes=None)
806
+ assert_equal(tmp.shape, (128, 128))
807
+
808
+ @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
809
+ (dstn, idstn)])
810
+ @pytest.mark.parametrize('axes', [1, (1,), [1],
811
+ 0, (0,), [0]])
812
+ def test_shape_is_none_with_axes(self, fforward, finverse, axes):
813
+ tmp = fforward(self.data, shape=None, axes=axes, norm='ortho')
814
+ tmp = finverse(tmp, shape=None, axes=axes, norm='ortho')
815
+ assert_array_almost_equal(self.data, tmp, decimal=self.dec)
llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (4.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/_quadrature.cpython-310.pyc ADDED
Binary file (54.3 kB). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/integrate/__pycache__/dop.cpython-310.pyc ADDED
Binary file (612 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/scipy/optimize/README ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ From the website for the L-BFGS-B code (from at
2
+ http://www.ece.northwestern.edu/~nocedal/lbfgsb.html):
3
+
4
+ """
5
+ L-BFGS-B is a limited-memory quasi-Newton code for bound-constrained
6
+ optimization, i.e. for problems where the only constraints are of the
7
+ form l<= x <= u.
8
+ """
9
+
10
+ This is a Python wrapper (using F2PY) written by David M. Cooke
11
+ <[email protected]> and released as version 0.9 on April 9, 2004.
12
+ The wrapper was slightly modified by Joonas Paalasmaa for the 3.0 version
13
+ in March 2012.
14
+
15
+ License of L-BFGS-B (Fortran code)
16
+ ==================================
17
+
18
+ The version included here (in lbfgsb.f) is 3.0 (released April 25, 2011). It was
19
+ written by Ciyou Zhu, Richard Byrd, and Jorge Nocedal <[email protected]>. It
20
+ carries the following condition for use:
21
+
22
+ """
23
+ This software is freely available, but we expect that all publications
24
+ describing work using this software, or all commercial products using it,
25
+ quote at least one of the references given below. This software is released
26
+ under the BSD License.
27
+
28
+ References
29
+ * R. H. Byrd, P. Lu and J. Nocedal. A Limited Memory Algorithm for Bound
30
+ Constrained Optimization, (1995), SIAM Journal on Scientific and
31
+ Statistical Computing, 16, 5, pp. 1190-1208.
32
+ * C. Zhu, R. H. Byrd and J. Nocedal. L-BFGS-B: Algorithm 778: L-BFGS-B,
33
+ FORTRAN routines for large scale bound constrained optimization (1997),
34
+ ACM Transactions on Mathematical Software, 23, 4, pp. 550 - 560.
35
+ * J.L. Morales and J. Nocedal. L-BFGS-B: Remark on Algorithm 778: L-BFGS-B,
36
+ FORTRAN routines for large scale bound constrained optimization (2011),
37
+ ACM Transactions on Mathematical Software, 38, 1.
38
+ """
39
+
40
+ The Python wrapper
41
+ ==================
42
+
43
+ This code uses F2PY (http://cens.ioc.ee/projects/f2py2e/) to generate
44
+ the wrapper around the Fortran code.
45
+
46
+ The Python code and wrapper are copyrighted 2004 by David M. Cooke
47
48
+
49
+ Example usage
50
+ =============
51
+
52
+ An example of the usage is given at the bottom of the lbfgsb.py file.
53
+ Run it with 'python lbfgsb.py'.
54
+
55
+ License for the Python wrapper
56
+ ==============================
57
+
58
+ Copyright (c) 2004 David M. Cooke <[email protected]>
59
+
60
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
61
+ this software and associated documentation files (the "Software"), to deal in
62
+ the Software without restriction, including without limitation the rights to
63
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
64
+ of the Software, and to permit persons to whom the Software is furnished to do
65
+ so, subject to the following conditions:
66
+
67
+ The above copyright notice and this permission notice shall be included in all
68
+ copies or substantial portions of the Software.
69
+
70
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
71
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
72
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
73
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
74
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
75
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
76
+ SOFTWARE.
llmeval-env/lib/python3.10/site-packages/scipy/optimize/__init__.py ADDED
@@ -0,0 +1,451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ =====================================================
3
+ Optimization and root finding (:mod:`scipy.optimize`)
4
+ =====================================================
5
+
6
+ .. currentmodule:: scipy.optimize
7
+
8
+ .. toctree::
9
+ :hidden:
10
+
11
+ optimize.cython_optimize
12
+
13
+ SciPy ``optimize`` provides functions for minimizing (or maximizing)
14
+ objective functions, possibly subject to constraints. It includes
15
+ solvers for nonlinear problems (with support for both local and global
16
+ optimization algorithms), linear programming, constrained
17
+ and nonlinear least-squares, root finding, and curve fitting.
18
+
19
+ Common functions and objects, shared across different solvers, are:
20
+
21
+ .. autosummary::
22
+ :toctree: generated/
23
+
24
+ show_options - Show specific options optimization solvers.
25
+ OptimizeResult - The optimization result returned by some optimizers.
26
+ OptimizeWarning - The optimization encountered problems.
27
+
28
+
29
+ Optimization
30
+ ============
31
+
32
+ Scalar functions optimization
33
+ -----------------------------
34
+
35
+ .. autosummary::
36
+ :toctree: generated/
37
+
38
+ minimize_scalar - Interface for minimizers of univariate functions
39
+
40
+ The `minimize_scalar` function supports the following methods:
41
+
42
+ .. toctree::
43
+
44
+ optimize.minimize_scalar-brent
45
+ optimize.minimize_scalar-bounded
46
+ optimize.minimize_scalar-golden
47
+
48
+ Local (multivariate) optimization
49
+ ---------------------------------
50
+
51
+ .. autosummary::
52
+ :toctree: generated/
53
+
54
+ minimize - Interface for minimizers of multivariate functions.
55
+
56
+ The `minimize` function supports the following methods:
57
+
58
+ .. toctree::
59
+
60
+ optimize.minimize-neldermead
61
+ optimize.minimize-powell
62
+ optimize.minimize-cg
63
+ optimize.minimize-bfgs
64
+ optimize.minimize-newtoncg
65
+ optimize.minimize-lbfgsb
66
+ optimize.minimize-tnc
67
+ optimize.minimize-cobyla
68
+ optimize.minimize-slsqp
69
+ optimize.minimize-trustconstr
70
+ optimize.minimize-dogleg
71
+ optimize.minimize-trustncg
72
+ optimize.minimize-trustkrylov
73
+ optimize.minimize-trustexact
74
+
75
+ Constraints are passed to `minimize` function as a single object or
76
+ as a list of objects from the following classes:
77
+
78
+ .. autosummary::
79
+ :toctree: generated/
80
+
81
+ NonlinearConstraint - Class defining general nonlinear constraints.
82
+ LinearConstraint - Class defining general linear constraints.
83
+
84
+ Simple bound constraints are handled separately and there is a special class
85
+ for them:
86
+
87
+ .. autosummary::
88
+ :toctree: generated/
89
+
90
+ Bounds - Bound constraints.
91
+
92
+ Quasi-Newton strategies implementing `HessianUpdateStrategy`
93
+ interface can be used to approximate the Hessian in `minimize`
94
+ function (available only for the 'trust-constr' method). Available
95
+ quasi-Newton methods implementing this interface are:
96
+
97
+ .. autosummary::
98
+ :toctree: generated/
99
+
100
+ BFGS - Broyden-Fletcher-Goldfarb-Shanno (BFGS) Hessian update strategy.
101
+ SR1 - Symmetric-rank-1 Hessian update strategy.
102
+
103
+ .. _global_optimization:
104
+
105
+ Global optimization
106
+ -------------------
107
+
108
+ .. autosummary::
109
+ :toctree: generated/
110
+
111
+ basinhopping - Basinhopping stochastic optimizer.
112
+ brute - Brute force searching optimizer.
113
+ differential_evolution - Stochastic optimizer using differential evolution.
114
+
115
+ shgo - Simplicial homology global optimizer.
116
+ dual_annealing - Dual annealing stochastic optimizer.
117
+ direct - DIRECT (Dividing Rectangles) optimizer.
118
+
119
+ Least-squares and curve fitting
120
+ ===============================
121
+
122
+ Nonlinear least-squares
123
+ -----------------------
124
+
125
+ .. autosummary::
126
+ :toctree: generated/
127
+
128
+ least_squares - Solve a nonlinear least-squares problem with bounds on the variables.
129
+
130
+ Linear least-squares
131
+ --------------------
132
+
133
+ .. autosummary::
134
+ :toctree: generated/
135
+
136
+ nnls - Linear least-squares problem with non-negativity constraint.
137
+ lsq_linear - Linear least-squares problem with bound constraints.
138
+ isotonic_regression - Least squares problem of isotonic regression via PAVA.
139
+
140
+ Curve fitting
141
+ -------------
142
+
143
+ .. autosummary::
144
+ :toctree: generated/
145
+
146
+ curve_fit -- Fit curve to a set of points.
147
+
148
+ Root finding
149
+ ============
150
+
151
+ Scalar functions
152
+ ----------------
153
+ .. autosummary::
154
+ :toctree: generated/
155
+
156
+ root_scalar - Unified interface for nonlinear solvers of scalar functions.
157
+ brentq - quadratic interpolation Brent method.
158
+ brenth - Brent method, modified by Harris with hyperbolic extrapolation.
159
+ ridder - Ridder's method.
160
+ bisect - Bisection method.
161
+ newton - Newton's method (also Secant and Halley's methods).
162
+ toms748 - Alefeld, Potra & Shi Algorithm 748.
163
+ RootResults - The root finding result returned by some root finders.
164
+
165
+ The `root_scalar` function supports the following methods:
166
+
167
+ .. toctree::
168
+
169
+ optimize.root_scalar-brentq
170
+ optimize.root_scalar-brenth
171
+ optimize.root_scalar-bisect
172
+ optimize.root_scalar-ridder
173
+ optimize.root_scalar-newton
174
+ optimize.root_scalar-toms748
175
+ optimize.root_scalar-secant
176
+ optimize.root_scalar-halley
177
+
178
+
179
+
180
+ The table below lists situations and appropriate methods, along with
181
+ *asymptotic* convergence rates per iteration (and per function evaluation)
182
+ for successful convergence to a simple root(*).
183
+ Bisection is the slowest of them all, adding one bit of accuracy for each
184
+ function evaluation, but is guaranteed to converge.
185
+ The other bracketing methods all (eventually) increase the number of accurate
186
+ bits by about 50% for every function evaluation.
187
+ The derivative-based methods, all built on `newton`, can converge quite quickly
188
+ if the initial value is close to the root. They can also be applied to
189
+ functions defined on (a subset of) the complex plane.
190
+
191
+ +-------------+----------+----------+-----------+-------------+-------------+----------------+
192
+ | Domain of f | Bracket? | Derivatives? | Solvers | Convergence |
193
+ + + +----------+-----------+ +-------------+----------------+
194
+ | | | `fprime` | `fprime2` | | Guaranteed? | Rate(s)(*) |
195
+ +=============+==========+==========+===========+=============+=============+================+
196
+ | `R` | Yes | N/A | N/A | - bisection | - Yes | - 1 "Linear" |
197
+ | | | | | - brentq | - Yes | - >=1, <= 1.62 |
198
+ | | | | | - brenth | - Yes | - >=1, <= 1.62 |
199
+ | | | | | - ridder | - Yes | - 2.0 (1.41) |
200
+ | | | | | - toms748 | - Yes | - 2.7 (1.65) |
201
+ +-------------+----------+----------+-----------+-------------+-------------+----------------+
202
+ | `R` or `C` | No | No | No | secant | No | 1.62 (1.62) |
203
+ +-------------+----------+----------+-----------+-------------+-------------+----------------+
204
+ | `R` or `C` | No | Yes | No | newton | No | 2.00 (1.41) |
205
+ +-------------+----------+----------+-----------+-------------+-------------+----------------+
206
+ | `R` or `C` | No | Yes | Yes | halley | No | 3.00 (1.44) |
207
+ +-------------+----------+----------+-----------+-------------+-------------+----------------+
208
+
209
+ .. seealso::
210
+
211
+ `scipy.optimize.cython_optimize` -- Typed Cython versions of root finding functions
212
+
213
+ Fixed point finding:
214
+
215
+ .. autosummary::
216
+ :toctree: generated/
217
+
218
+ fixed_point - Single-variable fixed-point solver.
219
+
220
+ Multidimensional
221
+ ----------------
222
+
223
+ .. autosummary::
224
+ :toctree: generated/
225
+
226
+ root - Unified interface for nonlinear solvers of multivariate functions.
227
+
228
+ The `root` function supports the following methods:
229
+
230
+ .. toctree::
231
+
232
+ optimize.root-hybr
233
+ optimize.root-lm
234
+ optimize.root-broyden1
235
+ optimize.root-broyden2
236
+ optimize.root-anderson
237
+ optimize.root-linearmixing
238
+ optimize.root-diagbroyden
239
+ optimize.root-excitingmixing
240
+ optimize.root-krylov
241
+ optimize.root-dfsane
242
+
243
+ Linear programming / MILP
244
+ =========================
245
+
246
+ .. autosummary::
247
+ :toctree: generated/
248
+
249
+ milp -- Mixed integer linear programming.
250
+ linprog -- Unified interface for minimizers of linear programming problems.
251
+
252
+ The `linprog` function supports the following methods:
253
+
254
+ .. toctree::
255
+
256
+ optimize.linprog-simplex
257
+ optimize.linprog-interior-point
258
+ optimize.linprog-revised_simplex
259
+ optimize.linprog-highs-ipm
260
+ optimize.linprog-highs-ds
261
+ optimize.linprog-highs
262
+
263
+ The simplex, interior-point, and revised simplex methods support callback
264
+ functions, such as:
265
+
266
+ .. autosummary::
267
+ :toctree: generated/
268
+
269
+ linprog_verbose_callback -- Sample callback function for linprog (simplex).
270
+
271
+ Assignment problems
272
+ ===================
273
+
274
+ .. autosummary::
275
+ :toctree: generated/
276
+
277
+ linear_sum_assignment -- Solves the linear-sum assignment problem.
278
+ quadratic_assignment -- Solves the quadratic assignment problem.
279
+
280
+ The `quadratic_assignment` function supports the following methods:
281
+
282
+ .. toctree::
283
+
284
+ optimize.qap-faq
285
+ optimize.qap-2opt
286
+
287
+ Utilities
288
+ =========
289
+
290
+ Finite-difference approximation
291
+ -------------------------------
292
+
293
+ .. autosummary::
294
+ :toctree: generated/
295
+
296
+ approx_fprime - Approximate the gradient of a scalar function.
297
+ check_grad - Check the supplied derivative using finite differences.
298
+
299
+
300
+ Line search
301
+ -----------
302
+
303
+ .. autosummary::
304
+ :toctree: generated/
305
+
306
+ bracket - Bracket a minimum, given two starting points.
307
+ line_search - Return a step that satisfies the strong Wolfe conditions.
308
+
309
+ Hessian approximation
310
+ ---------------------
311
+
312
+ .. autosummary::
313
+ :toctree: generated/
314
+
315
+ LbfgsInvHessProduct - Linear operator for L-BFGS approximate inverse Hessian.
316
+ HessianUpdateStrategy - Interface for implementing Hessian update strategies
317
+
318
+ Benchmark problems
319
+ ------------------
320
+
321
+ .. autosummary::
322
+ :toctree: generated/
323
+
324
+ rosen - The Rosenbrock function.
325
+ rosen_der - The derivative of the Rosenbrock function.
326
+ rosen_hess - The Hessian matrix of the Rosenbrock function.
327
+ rosen_hess_prod - Product of the Rosenbrock Hessian with a vector.
328
+
329
+ Legacy functions
330
+ ================
331
+
332
+ The functions below are not recommended for use in new scripts;
333
+ all of these methods are accessible via a newer, more consistent
334
+ interfaces, provided by the interfaces above.
335
+
336
+ Optimization
337
+ ------------
338
+
339
+ General-purpose multivariate methods:
340
+
341
+ .. autosummary::
342
+ :toctree: generated/
343
+
344
+ fmin - Nelder-Mead Simplex algorithm.
345
+ fmin_powell - Powell's (modified) conjugate direction method.
346
+ fmin_cg - Non-linear (Polak-Ribiere) conjugate gradient algorithm.
347
+ fmin_bfgs - Quasi-Newton method (Broydon-Fletcher-Goldfarb-Shanno).
348
+ fmin_ncg - Line-search Newton Conjugate Gradient.
349
+
350
+ Constrained multivariate methods:
351
+
352
+ .. autosummary::
353
+ :toctree: generated/
354
+
355
+ fmin_l_bfgs_b - Zhu, Byrd, and Nocedal's constrained optimizer.
356
+ fmin_tnc - Truncated Newton code.
357
+ fmin_cobyla - Constrained optimization by linear approximation.
358
+ fmin_slsqp - Minimization using sequential least-squares programming.
359
+
360
+ Univariate (scalar) minimization methods:
361
+
362
+ .. autosummary::
363
+ :toctree: generated/
364
+
365
+ fminbound - Bounded minimization of a scalar function.
366
+ brent - 1-D function minimization using Brent method.
367
+ golden - 1-D function minimization using Golden Section method.
368
+
369
+ Least-squares
370
+ -------------
371
+
372
+ .. autosummary::
373
+ :toctree: generated/
374
+
375
+ leastsq - Minimize the sum of squares of M equations in N unknowns.
376
+
377
+ Root finding
378
+ ------------
379
+
380
+ General nonlinear solvers:
381
+
382
+ .. autosummary::
383
+ :toctree: generated/
384
+
385
+ fsolve - Non-linear multivariable equation solver.
386
+ broyden1 - Broyden's first method.
387
+ broyden2 - Broyden's second method.
388
+ NoConvergence - Exception raised when nonlinear solver does not converge.
389
+
390
+ Large-scale nonlinear solvers:
391
+
392
+ .. autosummary::
393
+ :toctree: generated/
394
+
395
+ newton_krylov
396
+ anderson
397
+
398
+ BroydenFirst
399
+ InverseJacobian
400
+ KrylovJacobian
401
+
402
+ Simple iteration solvers:
403
+
404
+ .. autosummary::
405
+ :toctree: generated/
406
+
407
+ excitingmixing
408
+ linearmixing
409
+ diagbroyden
410
+
411
+ """ # noqa: E501
412
+
413
+ from ._optimize import *
414
+ from ._minimize import *
415
+ from ._root import *
416
+ from ._root_scalar import *
417
+ from ._minpack_py import *
418
+ from ._zeros_py import *
419
+ from ._lbfgsb_py import fmin_l_bfgs_b, LbfgsInvHessProduct
420
+ from ._tnc import fmin_tnc
421
+ from ._cobyla_py import fmin_cobyla
422
+ from ._nonlin import *
423
+ from ._slsqp_py import fmin_slsqp
424
+ from ._nnls import nnls
425
+ from ._basinhopping import basinhopping
426
+ from ._linprog import linprog, linprog_verbose_callback
427
+ from ._lsap import linear_sum_assignment
428
+ from ._differentialevolution import differential_evolution
429
+ from ._lsq import least_squares, lsq_linear
430
+ from ._isotonic import isotonic_regression
431
+ from ._constraints import (NonlinearConstraint,
432
+ LinearConstraint,
433
+ Bounds)
434
+ from ._hessian_update_strategy import HessianUpdateStrategy, BFGS, SR1
435
+ from ._shgo import shgo
436
+ from ._dual_annealing import dual_annealing
437
+ from ._qap import quadratic_assignment
438
+ from ._direct_py import direct
439
+ from ._milp import milp
440
+
441
+ # Deprecated namespaces, to be removed in v2.0.0
442
+ from . import (
443
+ cobyla, lbfgsb, linesearch, minpack, minpack2, moduleTNC, nonlin, optimize,
444
+ slsqp, tnc, zeros
445
+ )
446
+
447
+ __all__ = [s for s in dir() if not s.startswith('_')]
448
+
449
+ from scipy._lib._testutils import PytestTester
450
+ test = PytestTester(__name__)
451
+ del PytestTester
llmeval-env/lib/python3.10/site-packages/scipy/optimize/_basinhopping.py ADDED
@@ -0,0 +1,753 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ basinhopping: The basinhopping global optimization algorithm
3
+ """
4
+ import numpy as np
5
+ import math
6
+ import inspect
7
+ import scipy.optimize
8
+ from scipy._lib._util import check_random_state
9
+
10
+ __all__ = ['basinhopping']
11
+
12
+
13
+ _params = (inspect.Parameter('res_new', kind=inspect.Parameter.KEYWORD_ONLY),
14
+ inspect.Parameter('res_old', kind=inspect.Parameter.KEYWORD_ONLY))
15
+ _new_accept_test_signature = inspect.Signature(parameters=_params)
16
+
17
+
18
+ class Storage:
19
+ """
20
+ Class used to store the lowest energy structure
21
+ """
22
+ def __init__(self, minres):
23
+ self._add(minres)
24
+
25
+ def _add(self, minres):
26
+ self.minres = minres
27
+ self.minres.x = np.copy(minres.x)
28
+
29
+ def update(self, minres):
30
+ if minres.success and (minres.fun < self.minres.fun
31
+ or not self.minres.success):
32
+ self._add(minres)
33
+ return True
34
+ else:
35
+ return False
36
+
37
+ def get_lowest(self):
38
+ return self.minres
39
+
40
+
41
+ class BasinHoppingRunner:
42
+ """This class implements the core of the basinhopping algorithm.
43
+
44
+ x0 : ndarray
45
+ The starting coordinates.
46
+ minimizer : callable
47
+ The local minimizer, with signature ``result = minimizer(x)``.
48
+ The return value is an `optimize.OptimizeResult` object.
49
+ step_taking : callable
50
+ This function displaces the coordinates randomly. Signature should
51
+ be ``x_new = step_taking(x)``. Note that `x` may be modified in-place.
52
+ accept_tests : list of callables
53
+ Each test is passed the kwargs `f_new`, `x_new`, `f_old` and
54
+ `x_old`. These tests will be used to judge whether or not to accept
55
+ the step. The acceptable return values are True, False, or ``"force
56
+ accept"``. If any of the tests return False then the step is rejected.
57
+ If ``"force accept"``, then this will override any other tests in
58
+ order to accept the step. This can be used, for example, to forcefully
59
+ escape from a local minimum that ``basinhopping`` is trapped in.
60
+ disp : bool, optional
61
+ Display status messages.
62
+
63
+ """
64
+ def __init__(self, x0, minimizer, step_taking, accept_tests, disp=False):
65
+ self.x = np.copy(x0)
66
+ self.minimizer = minimizer
67
+ self.step_taking = step_taking
68
+ self.accept_tests = accept_tests
69
+ self.disp = disp
70
+
71
+ self.nstep = 0
72
+
73
+ # initialize return object
74
+ self.res = scipy.optimize.OptimizeResult()
75
+ self.res.minimization_failures = 0
76
+
77
+ # do initial minimization
78
+ minres = minimizer(self.x)
79
+ if not minres.success:
80
+ self.res.minimization_failures += 1
81
+ if self.disp:
82
+ print("warning: basinhopping: local minimization failure")
83
+ self.x = np.copy(minres.x)
84
+ self.energy = minres.fun
85
+ self.incumbent_minres = minres # best minimize result found so far
86
+ if self.disp:
87
+ print("basinhopping step %d: f %g" % (self.nstep, self.energy))
88
+
89
+ # initialize storage class
90
+ self.storage = Storage(minres)
91
+
92
+ if hasattr(minres, "nfev"):
93
+ self.res.nfev = minres.nfev
94
+ if hasattr(minres, "njev"):
95
+ self.res.njev = minres.njev
96
+ if hasattr(minres, "nhev"):
97
+ self.res.nhev = minres.nhev
98
+
99
+ def _monte_carlo_step(self):
100
+ """Do one Monte Carlo iteration
101
+
102
+ Randomly displace the coordinates, minimize, and decide whether
103
+ or not to accept the new coordinates.
104
+ """
105
+ # Take a random step. Make a copy of x because the step_taking
106
+ # algorithm might change x in place
107
+ x_after_step = np.copy(self.x)
108
+ x_after_step = self.step_taking(x_after_step)
109
+
110
+ # do a local minimization
111
+ minres = self.minimizer(x_after_step)
112
+ x_after_quench = minres.x
113
+ energy_after_quench = minres.fun
114
+ if not minres.success:
115
+ self.res.minimization_failures += 1
116
+ if self.disp:
117
+ print("warning: basinhopping: local minimization failure")
118
+ if hasattr(minres, "nfev"):
119
+ self.res.nfev += minres.nfev
120
+ if hasattr(minres, "njev"):
121
+ self.res.njev += minres.njev
122
+ if hasattr(minres, "nhev"):
123
+ self.res.nhev += minres.nhev
124
+
125
+ # accept the move based on self.accept_tests. If any test is False,
126
+ # then reject the step. If any test returns the special string
127
+ # 'force accept', then accept the step regardless. This can be used
128
+ # to forcefully escape from a local minimum if normal basin hopping
129
+ # steps are not sufficient.
130
+ accept = True
131
+ for test in self.accept_tests:
132
+ if inspect.signature(test) == _new_accept_test_signature:
133
+ testres = test(res_new=minres, res_old=self.incumbent_minres)
134
+ else:
135
+ testres = test(f_new=energy_after_quench, x_new=x_after_quench,
136
+ f_old=self.energy, x_old=self.x)
137
+
138
+ if testres == 'force accept':
139
+ accept = True
140
+ break
141
+ elif testres is None:
142
+ raise ValueError("accept_tests must return True, False, or "
143
+ "'force accept'")
144
+ elif not testres:
145
+ accept = False
146
+
147
+ # Report the result of the acceptance test to the take step class.
148
+ # This is for adaptive step taking
149
+ if hasattr(self.step_taking, "report"):
150
+ self.step_taking.report(accept, f_new=energy_after_quench,
151
+ x_new=x_after_quench, f_old=self.energy,
152
+ x_old=self.x)
153
+
154
+ return accept, minres
155
+
156
+ def one_cycle(self):
157
+ """Do one cycle of the basinhopping algorithm
158
+ """
159
+ self.nstep += 1
160
+ new_global_min = False
161
+
162
+ accept, minres = self._monte_carlo_step()
163
+
164
+ if accept:
165
+ self.energy = minres.fun
166
+ self.x = np.copy(minres.x)
167
+ self.incumbent_minres = minres # best minimize result found so far
168
+ new_global_min = self.storage.update(minres)
169
+
170
+ # print some information
171
+ if self.disp:
172
+ self.print_report(minres.fun, accept)
173
+ if new_global_min:
174
+ print("found new global minimum on step %d with function"
175
+ " value %g" % (self.nstep, self.energy))
176
+
177
+ # save some variables as BasinHoppingRunner attributes
178
+ self.xtrial = minres.x
179
+ self.energy_trial = minres.fun
180
+ self.accept = accept
181
+
182
+ return new_global_min
183
+
184
+ def print_report(self, energy_trial, accept):
185
+ """print a status update"""
186
+ minres = self.storage.get_lowest()
187
+ print("basinhopping step %d: f %g trial_f %g accepted %d "
188
+ " lowest_f %g" % (self.nstep, self.energy, energy_trial,
189
+ accept, minres.fun))
190
+
191
+
192
+ class AdaptiveStepsize:
193
+ """
194
+ Class to implement adaptive stepsize.
195
+
196
+ This class wraps the step taking class and modifies the stepsize to
197
+ ensure the true acceptance rate is as close as possible to the target.
198
+
199
+ Parameters
200
+ ----------
201
+ takestep : callable
202
+ The step taking routine. Must contain modifiable attribute
203
+ takestep.stepsize
204
+ accept_rate : float, optional
205
+ The target step acceptance rate
206
+ interval : int, optional
207
+ Interval for how often to update the stepsize
208
+ factor : float, optional
209
+ The step size is multiplied or divided by this factor upon each
210
+ update.
211
+ verbose : bool, optional
212
+ Print information about each update
213
+
214
+ """
215
+ def __init__(self, takestep, accept_rate=0.5, interval=50, factor=0.9,
216
+ verbose=True):
217
+ self.takestep = takestep
218
+ self.target_accept_rate = accept_rate
219
+ self.interval = interval
220
+ self.factor = factor
221
+ self.verbose = verbose
222
+
223
+ self.nstep = 0
224
+ self.nstep_tot = 0
225
+ self.naccept = 0
226
+
227
+ def __call__(self, x):
228
+ return self.take_step(x)
229
+
230
+ def _adjust_step_size(self):
231
+ old_stepsize = self.takestep.stepsize
232
+ accept_rate = float(self.naccept) / self.nstep
233
+ if accept_rate > self.target_accept_rate:
234
+ # We're accepting too many steps. This generally means we're
235
+ # trapped in a basin. Take bigger steps.
236
+ self.takestep.stepsize /= self.factor
237
+ else:
238
+ # We're not accepting enough steps. Take smaller steps.
239
+ self.takestep.stepsize *= self.factor
240
+ if self.verbose:
241
+ print("adaptive stepsize: acceptance rate {:f} target {:f} new "
242
+ "stepsize {:g} old stepsize {:g}".format(accept_rate,
243
+ self.target_accept_rate, self.takestep.stepsize,
244
+ old_stepsize))
245
+
246
+ def take_step(self, x):
247
+ self.nstep += 1
248
+ self.nstep_tot += 1
249
+ if self.nstep % self.interval == 0:
250
+ self._adjust_step_size()
251
+ return self.takestep(x)
252
+
253
+ def report(self, accept, **kwargs):
254
+ "called by basinhopping to report the result of the step"
255
+ if accept:
256
+ self.naccept += 1
257
+
258
+
259
+ class RandomDisplacement:
260
+ """Add a random displacement of maximum size `stepsize` to each coordinate.
261
+
262
+ Calling this updates `x` in-place.
263
+
264
+ Parameters
265
+ ----------
266
+ stepsize : float, optional
267
+ Maximum stepsize in any dimension
268
+ random_gen : {None, int, `numpy.random.Generator`,
269
+ `numpy.random.RandomState`}, optional
270
+
271
+ If `seed` is None (or `np.random`), the `numpy.random.RandomState`
272
+ singleton is used.
273
+ If `seed` is an int, a new ``RandomState`` instance is used,
274
+ seeded with `seed`.
275
+ If `seed` is already a ``Generator`` or ``RandomState`` instance then
276
+ that instance is used.
277
+
278
+ """
279
+
280
+ def __init__(self, stepsize=0.5, random_gen=None):
281
+ self.stepsize = stepsize
282
+ self.random_gen = check_random_state(random_gen)
283
+
284
+ def __call__(self, x):
285
+ x += self.random_gen.uniform(-self.stepsize, self.stepsize,
286
+ np.shape(x))
287
+ return x
288
+
289
+
290
+ class MinimizerWrapper:
291
+ """
292
+ wrap a minimizer function as a minimizer class
293
+ """
294
+ def __init__(self, minimizer, func=None, **kwargs):
295
+ self.minimizer = minimizer
296
+ self.func = func
297
+ self.kwargs = kwargs
298
+
299
+ def __call__(self, x0):
300
+ if self.func is None:
301
+ return self.minimizer(x0, **self.kwargs)
302
+ else:
303
+ return self.minimizer(self.func, x0, **self.kwargs)
304
+
305
+
306
+ class Metropolis:
307
+ """Metropolis acceptance criterion.
308
+
309
+ Parameters
310
+ ----------
311
+ T : float
312
+ The "temperature" parameter for the accept or reject criterion.
313
+ random_gen : {None, int, `numpy.random.Generator`,
314
+ `numpy.random.RandomState`}, optional
315
+
316
+ If `seed` is None (or `np.random`), the `numpy.random.RandomState`
317
+ singleton is used.
318
+ If `seed` is an int, a new ``RandomState`` instance is used,
319
+ seeded with `seed`.
320
+ If `seed` is already a ``Generator`` or ``RandomState`` instance then
321
+ that instance is used.
322
+ Random number generator used for acceptance test.
323
+
324
+ """
325
+
326
+ def __init__(self, T, random_gen=None):
327
+ # Avoid ZeroDivisionError since "MBH can be regarded as a special case
328
+ # of the BH framework with the Metropolis criterion, where temperature
329
+ # T = 0." (Reject all steps that increase energy.)
330
+ self.beta = 1.0 / T if T != 0 else float('inf')
331
+ self.random_gen = check_random_state(random_gen)
332
+
333
+ def accept_reject(self, res_new, res_old):
334
+ """
335
+ Assuming the local search underlying res_new was successful:
336
+ If new energy is lower than old, it will always be accepted.
337
+ If new is higher than old, there is a chance it will be accepted,
338
+ less likely for larger differences.
339
+ """
340
+ with np.errstate(invalid='ignore'):
341
+ # The energy values being fed to Metropolis are 1-length arrays, and if
342
+ # they are equal, their difference is 0, which gets multiplied by beta,
343
+ # which is inf, and array([0]) * float('inf') causes
344
+ #
345
+ # RuntimeWarning: invalid value encountered in multiply
346
+ #
347
+ # Ignore this warning so when the algorithm is on a flat plane, it always
348
+ # accepts the step, to try to move off the plane.
349
+ prod = -(res_new.fun - res_old.fun) * self.beta
350
+ w = math.exp(min(0, prod))
351
+
352
+ rand = self.random_gen.uniform()
353
+ return w >= rand and (res_new.success or not res_old.success)
354
+
355
+ def __call__(self, *, res_new, res_old):
356
+ """
357
+ f_new and f_old are mandatory in kwargs
358
+ """
359
+ return bool(self.accept_reject(res_new, res_old))
360
+
361
+
362
+ def basinhopping(func, x0, niter=100, T=1.0, stepsize=0.5,
363
+ minimizer_kwargs=None, take_step=None, accept_test=None,
364
+ callback=None, interval=50, disp=False, niter_success=None,
365
+ seed=None, *, target_accept_rate=0.5, stepwise_factor=0.9):
366
+ """Find the global minimum of a function using the basin-hopping algorithm.
367
+
368
+ Basin-hopping is a two-phase method that combines a global stepping
369
+ algorithm with local minimization at each step. Designed to mimic
370
+ the natural process of energy minimization of clusters of atoms, it works
371
+ well for similar problems with "funnel-like, but rugged" energy landscapes
372
+ [5]_.
373
+
374
+ As the step-taking, step acceptance, and minimization methods are all
375
+ customizable, this function can also be used to implement other two-phase
376
+ methods.
377
+
378
+ Parameters
379
+ ----------
380
+ func : callable ``f(x, *args)``
381
+ Function to be optimized. ``args`` can be passed as an optional item
382
+ in the dict `minimizer_kwargs`
383
+ x0 : array_like
384
+ Initial guess.
385
+ niter : integer, optional
386
+ The number of basin-hopping iterations. There will be a total of
387
+ ``niter + 1`` runs of the local minimizer.
388
+ T : float, optional
389
+ The "temperature" parameter for the acceptance or rejection criterion.
390
+ Higher "temperatures" mean that larger jumps in function value will be
391
+ accepted. For best results `T` should be comparable to the
392
+ separation (in function value) between local minima.
393
+ stepsize : float, optional
394
+ Maximum step size for use in the random displacement.
395
+ minimizer_kwargs : dict, optional
396
+ Extra keyword arguments to be passed to the local minimizer
397
+ `scipy.optimize.minimize` Some important options could be:
398
+
399
+ method : str
400
+ The minimization method (e.g. ``"L-BFGS-B"``)
401
+ args : tuple
402
+ Extra arguments passed to the objective function (`func`) and
403
+ its derivatives (Jacobian, Hessian).
404
+
405
+ take_step : callable ``take_step(x)``, optional
406
+ Replace the default step-taking routine with this routine. The default
407
+ step-taking routine is a random displacement of the coordinates, but
408
+ other step-taking algorithms may be better for some systems.
409
+ `take_step` can optionally have the attribute ``take_step.stepsize``.
410
+ If this attribute exists, then `basinhopping` will adjust
411
+ ``take_step.stepsize`` in order to try to optimize the global minimum
412
+ search.
413
+ accept_test : callable, ``accept_test(f_new=f_new, x_new=x_new, f_old=fold, x_old=x_old)``, optional
414
+ Define a test which will be used to judge whether to accept the
415
+ step. This will be used in addition to the Metropolis test based on
416
+ "temperature" `T`. The acceptable return values are True,
417
+ False, or ``"force accept"``. If any of the tests return False
418
+ then the step is rejected. If the latter, then this will override any
419
+ other tests in order to accept the step. This can be used, for example,
420
+ to forcefully escape from a local minimum that `basinhopping` is
421
+ trapped in.
422
+ callback : callable, ``callback(x, f, accept)``, optional
423
+ A callback function which will be called for all minima found. ``x``
424
+ and ``f`` are the coordinates and function value of the trial minimum,
425
+ and ``accept`` is whether that minimum was accepted. This can
426
+ be used, for example, to save the lowest N minima found. Also,
427
+ `callback` can be used to specify a user defined stop criterion by
428
+ optionally returning True to stop the `basinhopping` routine.
429
+ interval : integer, optional
430
+ interval for how often to update the `stepsize`
431
+ disp : bool, optional
432
+ Set to True to print status messages
433
+ niter_success : integer, optional
434
+ Stop the run if the global minimum candidate remains the same for this
435
+ number of iterations.
436
+ seed : {None, int, `numpy.random.Generator`, `numpy.random.RandomState`}, optional
437
+
438
+ If `seed` is None (or `np.random`), the `numpy.random.RandomState`
439
+ singleton is used.
440
+ If `seed` is an int, a new ``RandomState`` instance is used,
441
+ seeded with `seed`.
442
+ If `seed` is already a ``Generator`` or ``RandomState`` instance then
443
+ that instance is used.
444
+ Specify `seed` for repeatable minimizations. The random numbers
445
+ generated with this seed only affect the default Metropolis
446
+ `accept_test` and the default `take_step`. If you supply your own
447
+ `take_step` and `accept_test`, and these functions use random
448
+ number generation, then those functions are responsible for the state
449
+ of their random number generator.
450
+ target_accept_rate : float, optional
451
+ The target acceptance rate that is used to adjust the `stepsize`.
452
+ If the current acceptance rate is greater than the target,
453
+ then the `stepsize` is increased. Otherwise, it is decreased.
454
+ Range is (0, 1). Default is 0.5.
455
+
456
+ .. versionadded:: 1.8.0
457
+
458
+ stepwise_factor : float, optional
459
+ The `stepsize` is multiplied or divided by this stepwise factor upon
460
+ each update. Range is (0, 1). Default is 0.9.
461
+
462
+ .. versionadded:: 1.8.0
463
+
464
+ Returns
465
+ -------
466
+ res : OptimizeResult
467
+ The optimization result represented as a `OptimizeResult` object.
468
+ Important attributes are: ``x`` the solution array, ``fun`` the value
469
+ of the function at the solution, and ``message`` which describes the
470
+ cause of the termination. The ``OptimizeResult`` object returned by the
471
+ selected minimizer at the lowest minimum is also contained within this
472
+ object and can be accessed through the ``lowest_optimization_result``
473
+ attribute. See `OptimizeResult` for a description of other attributes.
474
+
475
+ See Also
476
+ --------
477
+ minimize :
478
+ The local minimization function called once for each basinhopping step.
479
+ `minimizer_kwargs` is passed to this routine.
480
+
481
+ Notes
482
+ -----
483
+ Basin-hopping is a stochastic algorithm which attempts to find the global
484
+ minimum of a smooth scalar function of one or more variables [1]_ [2]_ [3]_
485
+ [4]_. The algorithm in its current form was described by David Wales and
486
+ Jonathan Doye [2]_ http://www-wales.ch.cam.ac.uk/.
487
+
488
+ The algorithm is iterative with each cycle composed of the following
489
+ features
490
+
491
+ 1) random perturbation of the coordinates
492
+
493
+ 2) local minimization
494
+
495
+ 3) accept or reject the new coordinates based on the minimized function
496
+ value
497
+
498
+ The acceptance test used here is the Metropolis criterion of standard Monte
499
+ Carlo algorithms, although there are many other possibilities [3]_.
500
+
501
+ This global minimization method has been shown to be extremely efficient
502
+ for a wide variety of problems in physics and chemistry. It is
503
+ particularly useful when the function has many minima separated by large
504
+ barriers. See the `Cambridge Cluster Database
505
+ <https://www-wales.ch.cam.ac.uk/CCD.html>`_ for databases of molecular
506
+ systems that have been optimized primarily using basin-hopping. This
507
+ database includes minimization problems exceeding 300 degrees of freedom.
508
+
509
+ See the free software program `GMIN <https://www-wales.ch.cam.ac.uk/GMIN>`_
510
+ for a Fortran implementation of basin-hopping. This implementation has many
511
+ variations of the procedure described above, including more
512
+ advanced step taking algorithms and alternate acceptance criterion.
513
+
514
+ For stochastic global optimization there is no way to determine if the true
515
+ global minimum has actually been found. Instead, as a consistency check,
516
+ the algorithm can be run from a number of different random starting points
517
+ to ensure the lowest minimum found in each example has converged to the
518
+ global minimum. For this reason, `basinhopping` will by default simply
519
+ run for the number of iterations `niter` and return the lowest minimum
520
+ found. It is left to the user to ensure that this is in fact the global
521
+ minimum.
522
+
523
+ Choosing `stepsize`: This is a crucial parameter in `basinhopping` and
524
+ depends on the problem being solved. The step is chosen uniformly in the
525
+ region from x0-stepsize to x0+stepsize, in each dimension. Ideally, it
526
+ should be comparable to the typical separation (in argument values) between
527
+ local minima of the function being optimized. `basinhopping` will, by
528
+ default, adjust `stepsize` to find an optimal value, but this may take
529
+ many iterations. You will get quicker results if you set a sensible
530
+ initial value for ``stepsize``.
531
+
532
+ Choosing `T`: The parameter `T` is the "temperature" used in the
533
+ Metropolis criterion. Basinhopping steps are always accepted if
534
+ ``func(xnew) < func(xold)``. Otherwise, they are accepted with
535
+ probability::
536
+
537
+ exp( -(func(xnew) - func(xold)) / T )
538
+
539
+ So, for best results, `T` should to be comparable to the typical
540
+ difference (in function values) between local minima. (The height of
541
+ "walls" between local minima is irrelevant.)
542
+
543
+ If `T` is 0, the algorithm becomes Monotonic Basin-Hopping, in which all
544
+ steps that increase energy are rejected.
545
+
546
+ .. versionadded:: 0.12.0
547
+
548
+ References
549
+ ----------
550
+ .. [1] Wales, David J. 2003, Energy Landscapes, Cambridge University Press,
551
+ Cambridge, UK.
552
+ .. [2] Wales, D J, and Doye J P K, Global Optimization by Basin-Hopping and
553
+ the Lowest Energy Structures of Lennard-Jones Clusters Containing up to
554
+ 110 Atoms. Journal of Physical Chemistry A, 1997, 101, 5111.
555
+ .. [3] Li, Z. and Scheraga, H. A., Monte Carlo-minimization approach to the
556
+ multiple-minima problem in protein folding, Proc. Natl. Acad. Sci. USA,
557
+ 1987, 84, 6611.
558
+ .. [4] Wales, D. J. and Scheraga, H. A., Global optimization of clusters,
559
+ crystals, and biomolecules, Science, 1999, 285, 1368.
560
+ .. [5] Olson, B., Hashmi, I., Molloy, K., and Shehu1, A., Basin Hopping as
561
+ a General and Versatile Optimization Framework for the Characterization
562
+ of Biological Macromolecules, Advances in Artificial Intelligence,
563
+ Volume 2012 (2012), Article ID 674832, :doi:`10.1155/2012/674832`
564
+
565
+ Examples
566
+ --------
567
+ The following example is a 1-D minimization problem, with many
568
+ local minima superimposed on a parabola.
569
+
570
+ >>> import numpy as np
571
+ >>> from scipy.optimize import basinhopping
572
+ >>> func = lambda x: np.cos(14.5 * x - 0.3) + (x + 0.2) * x
573
+ >>> x0 = [1.]
574
+
575
+ Basinhopping, internally, uses a local minimization algorithm. We will use
576
+ the parameter `minimizer_kwargs` to tell basinhopping which algorithm to
577
+ use and how to set up that minimizer. This parameter will be passed to
578
+ `scipy.optimize.minimize`.
579
+
580
+ >>> minimizer_kwargs = {"method": "BFGS"}
581
+ >>> ret = basinhopping(func, x0, minimizer_kwargs=minimizer_kwargs,
582
+ ... niter=200)
583
+ >>> print("global minimum: x = %.4f, f(x) = %.4f" % (ret.x, ret.fun))
584
+ global minimum: x = -0.1951, f(x) = -1.0009
585
+
586
+ Next consider a 2-D minimization problem. Also, this time, we
587
+ will use gradient information to significantly speed up the search.
588
+
589
+ >>> def func2d(x):
590
+ ... f = np.cos(14.5 * x[0] - 0.3) + (x[1] + 0.2) * x[1] + (x[0] +
591
+ ... 0.2) * x[0]
592
+ ... df = np.zeros(2)
593
+ ... df[0] = -14.5 * np.sin(14.5 * x[0] - 0.3) + 2. * x[0] + 0.2
594
+ ... df[1] = 2. * x[1] + 0.2
595
+ ... return f, df
596
+
597
+ We'll also use a different local minimization algorithm. Also, we must tell
598
+ the minimizer that our function returns both energy and gradient (Jacobian).
599
+
600
+ >>> minimizer_kwargs = {"method":"L-BFGS-B", "jac":True}
601
+ >>> x0 = [1.0, 1.0]
602
+ >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
603
+ ... niter=200)
604
+ >>> print("global minimum: x = [%.4f, %.4f], f(x) = %.4f" % (ret.x[0],
605
+ ... ret.x[1],
606
+ ... ret.fun))
607
+ global minimum: x = [-0.1951, -0.1000], f(x) = -1.0109
608
+
609
+ Here is an example using a custom step-taking routine. Imagine you want
610
+ the first coordinate to take larger steps than the rest of the coordinates.
611
+ This can be implemented like so:
612
+
613
+ >>> class MyTakeStep:
614
+ ... def __init__(self, stepsize=0.5):
615
+ ... self.stepsize = stepsize
616
+ ... self.rng = np.random.default_rng()
617
+ ... def __call__(self, x):
618
+ ... s = self.stepsize
619
+ ... x[0] += self.rng.uniform(-2.*s, 2.*s)
620
+ ... x[1:] += self.rng.uniform(-s, s, x[1:].shape)
621
+ ... return x
622
+
623
+ Since ``MyTakeStep.stepsize`` exists basinhopping will adjust the magnitude
624
+ of `stepsize` to optimize the search. We'll use the same 2-D function as
625
+ before
626
+
627
+ >>> mytakestep = MyTakeStep()
628
+ >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
629
+ ... niter=200, take_step=mytakestep)
630
+ >>> print("global minimum: x = [%.4f, %.4f], f(x) = %.4f" % (ret.x[0],
631
+ ... ret.x[1],
632
+ ... ret.fun))
633
+ global minimum: x = [-0.1951, -0.1000], f(x) = -1.0109
634
+
635
+ Now, let's do an example using a custom callback function which prints the
636
+ value of every minimum found
637
+
638
+ >>> def print_fun(x, f, accepted):
639
+ ... print("at minimum %.4f accepted %d" % (f, int(accepted)))
640
+
641
+ We'll run it for only 10 basinhopping steps this time.
642
+
643
+ >>> rng = np.random.default_rng()
644
+ >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
645
+ ... niter=10, callback=print_fun, seed=rng)
646
+ at minimum 0.4159 accepted 1
647
+ at minimum -0.4317 accepted 1
648
+ at minimum -1.0109 accepted 1
649
+ at minimum -0.9073 accepted 1
650
+ at minimum -0.4317 accepted 0
651
+ at minimum -0.1021 accepted 1
652
+ at minimum -0.7425 accepted 1
653
+ at minimum -0.9073 accepted 1
654
+ at minimum -0.4317 accepted 0
655
+ at minimum -0.7425 accepted 1
656
+ at minimum -0.9073 accepted 1
657
+
658
+ The minimum at -1.0109 is actually the global minimum, found already on the
659
+ 8th iteration.
660
+
661
+ """ # numpy/numpydoc#87 # noqa: E501
662
+ if target_accept_rate <= 0. or target_accept_rate >= 1.:
663
+ raise ValueError('target_accept_rate has to be in range (0, 1)')
664
+ if stepwise_factor <= 0. or stepwise_factor >= 1.:
665
+ raise ValueError('stepwise_factor has to be in range (0, 1)')
666
+
667
+ x0 = np.array(x0)
668
+
669
+ # set up the np.random generator
670
+ rng = check_random_state(seed)
671
+
672
+ # set up minimizer
673
+ if minimizer_kwargs is None:
674
+ minimizer_kwargs = dict()
675
+ wrapped_minimizer = MinimizerWrapper(scipy.optimize.minimize, func,
676
+ **minimizer_kwargs)
677
+
678
+ # set up step-taking algorithm
679
+ if take_step is not None:
680
+ if not callable(take_step):
681
+ raise TypeError("take_step must be callable")
682
+ # if take_step.stepsize exists then use AdaptiveStepsize to control
683
+ # take_step.stepsize
684
+ if hasattr(take_step, "stepsize"):
685
+ take_step_wrapped = AdaptiveStepsize(
686
+ take_step, interval=interval,
687
+ accept_rate=target_accept_rate,
688
+ factor=stepwise_factor,
689
+ verbose=disp)
690
+ else:
691
+ take_step_wrapped = take_step
692
+ else:
693
+ # use default
694
+ displace = RandomDisplacement(stepsize=stepsize, random_gen=rng)
695
+ take_step_wrapped = AdaptiveStepsize(displace, interval=interval,
696
+ accept_rate=target_accept_rate,
697
+ factor=stepwise_factor,
698
+ verbose=disp)
699
+
700
+ # set up accept tests
701
+ accept_tests = []
702
+ if accept_test is not None:
703
+ if not callable(accept_test):
704
+ raise TypeError("accept_test must be callable")
705
+ accept_tests = [accept_test]
706
+
707
+ # use default
708
+ metropolis = Metropolis(T, random_gen=rng)
709
+ accept_tests.append(metropolis)
710
+
711
+ if niter_success is None:
712
+ niter_success = niter + 2
713
+
714
+ bh = BasinHoppingRunner(x0, wrapped_minimizer, take_step_wrapped,
715
+ accept_tests, disp=disp)
716
+
717
+ # The wrapped minimizer is called once during construction of
718
+ # BasinHoppingRunner, so run the callback
719
+ if callable(callback):
720
+ callback(bh.storage.minres.x, bh.storage.minres.fun, True)
721
+
722
+ # start main iteration loop
723
+ count, i = 0, 0
724
+ message = ["requested number of basinhopping iterations completed"
725
+ " successfully"]
726
+ for i in range(niter):
727
+ new_global_min = bh.one_cycle()
728
+
729
+ if callable(callback):
730
+ # should we pass a copy of x?
731
+ val = callback(bh.xtrial, bh.energy_trial, bh.accept)
732
+ if val is not None:
733
+ if val:
734
+ message = ["callback function requested stop early by"
735
+ "returning True"]
736
+ break
737
+
738
+ count += 1
739
+ if new_global_min:
740
+ count = 0
741
+ elif count > niter_success:
742
+ message = ["success condition satisfied"]
743
+ break
744
+
745
+ # prepare return object
746
+ res = bh.res
747
+ res.lowest_optimization_result = bh.storage.get_lowest()
748
+ res.x = np.copy(res.lowest_optimization_result.x)
749
+ res.fun = res.lowest_optimization_result.fun
750
+ res.message = message
751
+ res.nit = i + 1
752
+ res.success = res.lowest_optimization_result.success
753
+ return res
llmeval-env/lib/python3.10/site-packages/scipy/optimize/_dcsrch.py ADDED
@@ -0,0 +1,728 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ """
4
+ # 2023 - ported from minpack2.dcsrch, dcstep (Fortran) to Python
5
+ c MINPACK-1 Project. June 1983.
6
+ c Argonne National Laboratory.
7
+ c Jorge J. More' and David J. Thuente.
8
+ c
9
+ c MINPACK-2 Project. November 1993.
10
+ c Argonne National Laboratory and University of Minnesota.
11
+ c Brett M. Averick, Richard G. Carter, and Jorge J. More'.
12
+ """
13
+
14
+ # NOTE this file was linted by black on first commit, and can be kept that way.
15
+
16
+
17
+ class DCSRCH:
18
+ """
19
+ Parameters
20
+ ----------
21
+ phi : callable phi(alpha)
22
+ Function at point `alpha`
23
+ derphi : callable phi'(alpha)
24
+ Objective function derivative. Returns a scalar.
25
+ ftol : float
26
+ A nonnegative tolerance for the sufficient decrease condition.
27
+ gtol : float
28
+ A nonnegative tolerance for the curvature condition.
29
+ xtol : float
30
+ A nonnegative relative tolerance for an acceptable step. The
31
+ subroutine exits with a warning if the relative difference between
32
+ sty and stx is less than xtol.
33
+ stpmin : float
34
+ A nonnegative lower bound for the step.
35
+ stpmax :
36
+ A nonnegative upper bound for the step.
37
+
38
+ Notes
39
+ -----
40
+
41
+ This subroutine finds a step that satisfies a sufficient
42
+ decrease condition and a curvature condition.
43
+
44
+ Each call of the subroutine updates an interval with
45
+ endpoints stx and sty. The interval is initially chosen
46
+ so that it contains a minimizer of the modified function
47
+
48
+ psi(stp) = f(stp) - f(0) - ftol*stp*f'(0).
49
+
50
+ If psi(stp) <= 0 and f'(stp) >= 0 for some step, then the
51
+ interval is chosen so that it contains a minimizer of f.
52
+
53
+ The algorithm is designed to find a step that satisfies
54
+ the sufficient decrease condition
55
+
56
+ f(stp) <= f(0) + ftol*stp*f'(0),
57
+
58
+ and the curvature condition
59
+
60
+ abs(f'(stp)) <= gtol*abs(f'(0)).
61
+
62
+ If ftol is less than gtol and if, for example, the function
63
+ is bounded below, then there is always a step which satisfies
64
+ both conditions.
65
+
66
+ If no step can be found that satisfies both conditions, then
67
+ the algorithm stops with a warning. In this case stp only
68
+ satisfies the sufficient decrease condition.
69
+
70
+ A typical invocation of dcsrch has the following outline:
71
+
72
+ Evaluate the function at stp = 0.0d0; store in f.
73
+ Evaluate the gradient at stp = 0.0d0; store in g.
74
+ Choose a starting step stp.
75
+
76
+ task = 'START'
77
+ 10 continue
78
+ call dcsrch(stp,f,g,ftol,gtol,xtol,task,stpmin,stpmax,
79
+ isave,dsave)
80
+ if (task .eq. 'FG') then
81
+ Evaluate the function and the gradient at stp
82
+ go to 10
83
+ end if
84
+
85
+ NOTE: The user must not alter work arrays between calls.
86
+
87
+ The subroutine statement is
88
+
89
+ subroutine dcsrch(f,g,stp,ftol,gtol,xtol,stpmin,stpmax,
90
+ task,isave,dsave)
91
+ where
92
+
93
+ stp is a double precision variable.
94
+ On entry stp is the current estimate of a satisfactory
95
+ step. On initial entry, a positive initial estimate
96
+ must be provided.
97
+ On exit stp is the current estimate of a satisfactory step
98
+ if task = 'FG'. If task = 'CONV' then stp satisfies
99
+ the sufficient decrease and curvature condition.
100
+
101
+ f is a double precision variable.
102
+ On initial entry f is the value of the function at 0.
103
+ On subsequent entries f is the value of the
104
+ function at stp.
105
+ On exit f is the value of the function at stp.
106
+
107
+ g is a double precision variable.
108
+ On initial entry g is the derivative of the function at 0.
109
+ On subsequent entries g is the derivative of the
110
+ function at stp.
111
+ On exit g is the derivative of the function at stp.
112
+
113
+ ftol is a double precision variable.
114
+ On entry ftol specifies a nonnegative tolerance for the
115
+ sufficient decrease condition.
116
+ On exit ftol is unchanged.
117
+
118
+ gtol is a double precision variable.
119
+ On entry gtol specifies a nonnegative tolerance for the
120
+ curvature condition.
121
+ On exit gtol is unchanged.
122
+
123
+ xtol is a double precision variable.
124
+ On entry xtol specifies a nonnegative relative tolerance
125
+ for an acceptable step. The subroutine exits with a
126
+ warning if the relative difference between sty and stx
127
+ is less than xtol.
128
+
129
+ On exit xtol is unchanged.
130
+
131
+ task is a character variable of length at least 60.
132
+ On initial entry task must be set to 'START'.
133
+ On exit task indicates the required action:
134
+
135
+ If task(1:2) = 'FG' then evaluate the function and
136
+ derivative at stp and call dcsrch again.
137
+
138
+ If task(1:4) = 'CONV' then the search is successful.
139
+
140
+ If task(1:4) = 'WARN' then the subroutine is not able
141
+ to satisfy the convergence conditions. The exit value of
142
+ stp contains the best point found during the search.
143
+
144
+ If task(1:5) = 'ERROR' then there is an error in the
145
+ input arguments.
146
+
147
+ On exit with convergence, a warning or an error, the
148
+ variable task contains additional information.
149
+
150
+ stpmin is a double precision variable.
151
+ On entry stpmin is a nonnegative lower bound for the step.
152
+ On exit stpmin is unchanged.
153
+
154
+ stpmax is a double precision variable.
155
+ On entry stpmax is a nonnegative upper bound for the step.
156
+ On exit stpmax is unchanged.
157
+
158
+ isave is an integer work array of dimension 2.
159
+
160
+ dsave is a double precision work array of dimension 13.
161
+
162
+ Subprograms called
163
+
164
+ MINPACK-2 ... dcstep
165
+ MINPACK-1 Project. June 1983.
166
+ Argonne National Laboratory.
167
+ Jorge J. More' and David J. Thuente.
168
+
169
+ MINPACK-2 Project. November 1993.
170
+ Argonne National Laboratory and University of Minnesota.
171
+ Brett M. Averick, Richard G. Carter, and Jorge J. More'.
172
+ """
173
+
174
+ def __init__(self, phi, derphi, ftol, gtol, xtol, stpmin, stpmax):
175
+ self.stage = None
176
+ self.ginit = None
177
+ self.gtest = None
178
+ self.gx = None
179
+ self.gy = None
180
+ self.finit = None
181
+ self.fx = None
182
+ self.fy = None
183
+ self.stx = None
184
+ self.sty = None
185
+ self.stmin = None
186
+ self.stmax = None
187
+ self.width = None
188
+ self.width1 = None
189
+
190
+ # leave all assessment of tolerances/limits to the first call of
191
+ # this object
192
+ self.ftol = ftol
193
+ self.gtol = gtol
194
+ self.xtol = xtol
195
+ self.stpmin = stpmin
196
+ self.stpmax = stpmax
197
+
198
+ self.phi = phi
199
+ self.derphi = derphi
200
+
201
+ def __call__(self, alpha1, phi0=None, derphi0=None, maxiter=100):
202
+ """
203
+ Parameters
204
+ ----------
205
+ alpha1 : float
206
+ alpha1 is the current estimate of a satisfactory
207
+ step. A positive initial estimate must be provided.
208
+ phi0 : float
209
+ the value of `phi` at 0 (if known).
210
+ derphi0 : float
211
+ the derivative of `derphi` at 0 (if known).
212
+ maxiter : int
213
+
214
+ Returns
215
+ -------
216
+ alpha : float
217
+ Step size, or None if no suitable step was found.
218
+ phi : float
219
+ Value of `phi` at the new point `alpha`.
220
+ phi0 : float
221
+ Value of `phi` at `alpha=0`.
222
+ task : bytes
223
+ On exit task indicates status information.
224
+
225
+ If task[:4] == b'CONV' then the search is successful.
226
+
227
+ If task[:4] == b'WARN' then the subroutine is not able
228
+ to satisfy the convergence conditions. The exit value of
229
+ stp contains the best point found during the search.
230
+
231
+ If task[:5] == b'ERROR' then there is an error in the
232
+ input arguments.
233
+ """
234
+ if phi0 is None:
235
+ phi0 = self.phi(0.0)
236
+ if derphi0 is None:
237
+ derphi0 = self.derphi(0.0)
238
+
239
+ phi1 = phi0
240
+ derphi1 = derphi0
241
+
242
+ task = b"START"
243
+ for i in range(maxiter):
244
+ stp, phi1, derphi1, task = self._iterate(
245
+ alpha1, phi1, derphi1, task
246
+ )
247
+
248
+ if not np.isfinite(stp):
249
+ task = b"WARN"
250
+ stp = None
251
+ break
252
+
253
+ if task[:2] == b"FG":
254
+ alpha1 = stp
255
+ phi1 = self.phi(stp)
256
+ derphi1 = self.derphi(stp)
257
+ else:
258
+ break
259
+ else:
260
+ # maxiter reached, the line search did not converge
261
+ stp = None
262
+ task = b"WARNING: dcsrch did not converge within max iterations"
263
+
264
+ if task[:5] == b"ERROR" or task[:4] == b"WARN":
265
+ stp = None # failed
266
+
267
+ return stp, phi1, phi0, task
268
+
269
+ def _iterate(self, stp, f, g, task):
270
+ """
271
+ Parameters
272
+ ----------
273
+ stp : float
274
+ The current estimate of a satisfactory step. On initial entry, a
275
+ positive initial estimate must be provided.
276
+ f : float
277
+ On first call f is the value of the function at 0. On subsequent
278
+ entries f should be the value of the function at stp.
279
+ g : float
280
+ On initial entry g is the derivative of the function at 0. On
281
+ subsequent entries g is the derivative of the function at stp.
282
+ task : bytes
283
+ On initial entry task must be set to 'START'.
284
+
285
+ On exit with convergence, a warning or an error, the
286
+ variable task contains additional information.
287
+
288
+
289
+ Returns
290
+ -------
291
+ stp, f, g, task: tuple
292
+
293
+ stp : float
294
+ the current estimate of a satisfactory step if task = 'FG'. If
295
+ task = 'CONV' then stp satisfies the sufficient decrease and
296
+ curvature condition.
297
+ f : float
298
+ the value of the function at stp.
299
+ g : float
300
+ the derivative of the function at stp.
301
+ task : bytes
302
+ On exit task indicates the required action:
303
+
304
+ If task(1:2) == b'FG' then evaluate the function and
305
+ derivative at stp and call dcsrch again.
306
+
307
+ If task(1:4) == b'CONV' then the search is successful.
308
+
309
+ If task(1:4) == b'WARN' then the subroutine is not able
310
+ to satisfy the convergence conditions. The exit value of
311
+ stp contains the best point found during the search.
312
+
313
+ If task(1:5) == b'ERROR' then there is an error in the
314
+ input arguments.
315
+ """
316
+ p5 = 0.5
317
+ p66 = 0.66
318
+ xtrapl = 1.1
319
+ xtrapu = 4.0
320
+
321
+ if task[:5] == b"START":
322
+ if stp < self.stpmin:
323
+ task = b"ERROR: STP .LT. STPMIN"
324
+ if stp > self.stpmax:
325
+ task = b"ERROR: STP .GT. STPMAX"
326
+ if g >= 0:
327
+ task = b"ERROR: INITIAL G .GE. ZERO"
328
+ if self.ftol < 0:
329
+ task = b"ERROR: FTOL .LT. ZERO"
330
+ if self.gtol < 0:
331
+ task = b"ERROR: GTOL .LT. ZERO"
332
+ if self.xtol < 0:
333
+ task = b"ERROR: XTOL .LT. ZERO"
334
+ if self.stpmin < 0:
335
+ task = b"ERROR: STPMIN .LT. ZERO"
336
+ if self.stpmax < self.stpmin:
337
+ task = b"ERROR: STPMAX .LT. STPMIN"
338
+
339
+ if task[:5] == b"ERROR":
340
+ return stp, f, g, task
341
+
342
+ # Initialize local variables.
343
+
344
+ self.brackt = False
345
+ self.stage = 1
346
+ self.finit = f
347
+ self.ginit = g
348
+ self.gtest = self.ftol * self.ginit
349
+ self.width = self.stpmax - self.stpmin
350
+ self.width1 = self.width / p5
351
+
352
+ # The variables stx, fx, gx contain the values of the step,
353
+ # function, and derivative at the best step.
354
+ # The variables sty, fy, gy contain the value of the step,
355
+ # function, and derivative at sty.
356
+ # The variables stp, f, g contain the values of the step,
357
+ # function, and derivative at stp.
358
+
359
+ self.stx = 0.0
360
+ self.fx = self.finit
361
+ self.gx = self.ginit
362
+ self.sty = 0.0
363
+ self.fy = self.finit
364
+ self.gy = self.ginit
365
+ self.stmin = 0
366
+ self.stmax = stp + xtrapu * stp
367
+ task = b"FG"
368
+ return stp, f, g, task
369
+
370
+ # in the original Fortran this was a location to restore variables
371
+ # we don't need to do that because they're attributes.
372
+
373
+ # If psi(stp) <= 0 and f'(stp) >= 0 for some step, then the
374
+ # algorithm enters the second stage.
375
+ ftest = self.finit + stp * self.gtest
376
+
377
+ if self.stage == 1 and f <= ftest and g >= 0:
378
+ self.stage = 2
379
+
380
+ # test for warnings
381
+ if self.brackt and (stp <= self.stmin or stp >= self.stmax):
382
+ task = b"WARNING: ROUNDING ERRORS PREVENT PROGRESS"
383
+ if self.brackt and self.stmax - self.stmin <= self.xtol * self.stmax:
384
+ task = b"WARNING: XTOL TEST SATISFIED"
385
+ if stp == self.stpmax and f <= ftest and g <= self.gtest:
386
+ task = b"WARNING: STP = STPMAX"
387
+ if stp == self.stpmin and (f > ftest or g >= self.gtest):
388
+ task = b"WARNING: STP = STPMIN"
389
+
390
+ # test for convergence
391
+ if f <= ftest and abs(g) <= self.gtol * -self.ginit:
392
+ task = b"CONVERGENCE"
393
+
394
+ # test for termination
395
+ if task[:4] == b"WARN" or task[:4] == b"CONV":
396
+ return stp, f, g, task
397
+
398
+ # A modified function is used to predict the step during the
399
+ # first stage if a lower function value has been obtained but
400
+ # the decrease is not sufficient.
401
+ if self.stage == 1 and f <= self.fx and f > ftest:
402
+ # Define the modified function and derivative values.
403
+ fm = f - stp * self.gtest
404
+ fxm = self.fx - self.stx * self.gtest
405
+ fym = self.fy - self.sty * self.gtest
406
+ gm = g - self.gtest
407
+ gxm = self.gx - self.gtest
408
+ gym = self.gy - self.gtest
409
+
410
+ # Call dcstep to update stx, sty, and to compute the new step.
411
+ # dcstep can have several operations which can produce NaN
412
+ # e.g. inf/inf. Filter these out.
413
+ with np.errstate(invalid="ignore", over="ignore"):
414
+ tup = dcstep(
415
+ self.stx,
416
+ fxm,
417
+ gxm,
418
+ self.sty,
419
+ fym,
420
+ gym,
421
+ stp,
422
+ fm,
423
+ gm,
424
+ self.brackt,
425
+ self.stmin,
426
+ self.stmax,
427
+ )
428
+ self.stx, fxm, gxm, self.sty, fym, gym, stp, self.brackt = tup
429
+
430
+ # Reset the function and derivative values for f
431
+ self.fx = fxm + self.stx * self.gtest
432
+ self.fy = fym + self.sty * self.gtest
433
+ self.gx = gxm + self.gtest
434
+ self.gy = gym + self.gtest
435
+
436
+ else:
437
+ # Call dcstep to update stx, sty, and to compute the new step.
438
+ # dcstep can have several operations which can produce NaN
439
+ # e.g. inf/inf. Filter these out.
440
+
441
+ with np.errstate(invalid="ignore", over="ignore"):
442
+ tup = dcstep(
443
+ self.stx,
444
+ self.fx,
445
+ self.gx,
446
+ self.sty,
447
+ self.fy,
448
+ self.gy,
449
+ stp,
450
+ f,
451
+ g,
452
+ self.brackt,
453
+ self.stmin,
454
+ self.stmax,
455
+ )
456
+ (
457
+ self.stx,
458
+ self.fx,
459
+ self.gx,
460
+ self.sty,
461
+ self.fy,
462
+ self.gy,
463
+ stp,
464
+ self.brackt,
465
+ ) = tup
466
+
467
+ # Decide if a bisection step is needed
468
+ if self.brackt:
469
+ if abs(self.sty - self.stx) >= p66 * self.width1:
470
+ stp = self.stx + p5 * (self.sty - self.stx)
471
+ self.width1 = self.width
472
+ self.width = abs(self.sty - self.stx)
473
+
474
+ # Set the minimum and maximum steps allowed for stp.
475
+ if self.brackt:
476
+ self.stmin = min(self.stx, self.sty)
477
+ self.stmax = max(self.stx, self.sty)
478
+ else:
479
+ self.stmin = stp + xtrapl * (stp - self.stx)
480
+ self.stmax = stp + xtrapu * (stp - self.stx)
481
+
482
+ # Force the step to be within the bounds stpmax and stpmin.
483
+ stp = np.clip(stp, self.stpmin, self.stpmax)
484
+
485
+ # If further progress is not possible, let stp be the best
486
+ # point obtained during the search.
487
+ if (
488
+ self.brackt
489
+ and (stp <= self.stmin or stp >= self.stmax)
490
+ or (
491
+ self.brackt
492
+ and self.stmax - self.stmin <= self.xtol * self.stmax
493
+ )
494
+ ):
495
+ stp = self.stx
496
+
497
+ # Obtain another function and derivative
498
+ task = b"FG"
499
+ return stp, f, g, task
500
+
501
+
502
+ def dcstep(stx, fx, dx, sty, fy, dy, stp, fp, dp, brackt, stpmin, stpmax):
503
+ """
504
+ Subroutine dcstep
505
+
506
+ This subroutine computes a safeguarded step for a search
507
+ procedure and updates an interval that contains a step that
508
+ satisfies a sufficient decrease and a curvature condition.
509
+
510
+ The parameter stx contains the step with the least function
511
+ value. If brackt is set to .true. then a minimizer has
512
+ been bracketed in an interval with endpoints stx and sty.
513
+ The parameter stp contains the current step.
514
+ The subroutine assumes that if brackt is set to .true. then
515
+
516
+ min(stx,sty) < stp < max(stx,sty),
517
+
518
+ and that the derivative at stx is negative in the direction
519
+ of the step.
520
+
521
+ The subroutine statement is
522
+
523
+ subroutine dcstep(stx,fx,dx,sty,fy,dy,stp,fp,dp,brackt,
524
+ stpmin,stpmax)
525
+
526
+ where
527
+
528
+ stx is a double precision variable.
529
+ On entry stx is the best step obtained so far and is an
530
+ endpoint of the interval that contains the minimizer.
531
+ On exit stx is the updated best step.
532
+
533
+ fx is a double precision variable.
534
+ On entry fx is the function at stx.
535
+ On exit fx is the function at stx.
536
+
537
+ dx is a double precision variable.
538
+ On entry dx is the derivative of the function at
539
+ stx. The derivative must be negative in the direction of
540
+ the step, that is, dx and stp - stx must have opposite
541
+ signs.
542
+ On exit dx is the derivative of the function at stx.
543
+
544
+ sty is a double precision variable.
545
+ On entry sty is the second endpoint of the interval that
546
+ contains the minimizer.
547
+ On exit sty is the updated endpoint of the interval that
548
+ contains the minimizer.
549
+
550
+ fy is a double precision variable.
551
+ On entry fy is the function at sty.
552
+ On exit fy is the function at sty.
553
+
554
+ dy is a double precision variable.
555
+ On entry dy is the derivative of the function at sty.
556
+ On exit dy is the derivative of the function at the exit sty.
557
+
558
+ stp is a double precision variable.
559
+ On entry stp is the current step. If brackt is set to .true.
560
+ then on input stp must be between stx and sty.
561
+ On exit stp is a new trial step.
562
+
563
+ fp is a double precision variable.
564
+ On entry fp is the function at stp
565
+ On exit fp is unchanged.
566
+
567
+ dp is a double precision variable.
568
+ On entry dp is the derivative of the function at stp.
569
+ On exit dp is unchanged.
570
+
571
+ brackt is an logical variable.
572
+ On entry brackt specifies if a minimizer has been bracketed.
573
+ Initially brackt must be set to .false.
574
+ On exit brackt specifies if a minimizer has been bracketed.
575
+ When a minimizer is bracketed brackt is set to .true.
576
+
577
+ stpmin is a double precision variable.
578
+ On entry stpmin is a lower bound for the step.
579
+ On exit stpmin is unchanged.
580
+
581
+ stpmax is a double precision variable.
582
+ On entry stpmax is an upper bound for the step.
583
+ On exit stpmax is unchanged.
584
+
585
+ MINPACK-1 Project. June 1983
586
+ Argonne National Laboratory.
587
+ Jorge J. More' and David J. Thuente.
588
+
589
+ MINPACK-2 Project. November 1993.
590
+ Argonne National Laboratory and University of Minnesota.
591
+ Brett M. Averick and Jorge J. More'.
592
+
593
+ """
594
+ sgn_dp = np.sign(dp)
595
+ sgn_dx = np.sign(dx)
596
+
597
+ # sgnd = dp * (dx / abs(dx))
598
+ sgnd = sgn_dp * sgn_dx
599
+
600
+ # First case: A higher function value. The minimum is bracketed.
601
+ # If the cubic step is closer to stx than the quadratic step, the
602
+ # cubic step is taken, otherwise the average of the cubic and
603
+ # quadratic steps is taken.
604
+ if fp > fx:
605
+ theta = 3.0 * (fx - fp) / (stp - stx) + dx + dp
606
+ s = max(abs(theta), abs(dx), abs(dp))
607
+ gamma = s * np.sqrt((theta / s) ** 2 - (dx / s) * (dp / s))
608
+ if stp < stx:
609
+ gamma *= -1
610
+ p = (gamma - dx) + theta
611
+ q = ((gamma - dx) + gamma) + dp
612
+ r = p / q
613
+ stpc = stx + r * (stp - stx)
614
+ stpq = stx + ((dx / ((fx - fp) / (stp - stx) + dx)) / 2.0) * (stp - stx)
615
+ if abs(stpc - stx) <= abs(stpq - stx):
616
+ stpf = stpc
617
+ else:
618
+ stpf = stpc + (stpq - stpc) / 2.0
619
+ brackt = True
620
+ elif sgnd < 0.0:
621
+ # Second case: A lower function value and derivatives of opposite
622
+ # sign. The minimum is bracketed. If the cubic step is farther from
623
+ # stp than the secant step, the cubic step is taken, otherwise the
624
+ # secant step is taken.
625
+ theta = 3 * (fx - fp) / (stp - stx) + dx + dp
626
+ s = max(abs(theta), abs(dx), abs(dp))
627
+ gamma = s * np.sqrt((theta / s) ** 2 - (dx / s) * (dp / s))
628
+ if stp > stx:
629
+ gamma *= -1
630
+ p = (gamma - dp) + theta
631
+ q = ((gamma - dp) + gamma) + dx
632
+ r = p / q
633
+ stpc = stp + r * (stx - stp)
634
+ stpq = stp + (dp / (dp - dx)) * (stx - stp)
635
+ if abs(stpc - stp) > abs(stpq - stp):
636
+ stpf = stpc
637
+ else:
638
+ stpf = stpq
639
+ brackt = True
640
+ elif abs(dp) < abs(dx):
641
+ # Third case: A lower function value, derivatives of the same sign,
642
+ # and the magnitude of the derivative decreases.
643
+
644
+ # The cubic step is computed only if the cubic tends to infinity
645
+ # in the direction of the step or if the minimum of the cubic
646
+ # is beyond stp. Otherwise the cubic step is defined to be the
647
+ # secant step.
648
+ theta = 3 * (fx - fp) / (stp - stx) + dx + dp
649
+ s = max(abs(theta), abs(dx), abs(dp))
650
+
651
+ # The case gamma = 0 only arises if the cubic does not tend
652
+ # to infinity in the direction of the step.
653
+ gamma = s * np.sqrt(max(0, (theta / s) ** 2 - (dx / s) * (dp / s)))
654
+ if stp > stx:
655
+ gamma = -gamma
656
+ p = (gamma - dp) + theta
657
+ q = (gamma + (dx - dp)) + gamma
658
+ r = p / q
659
+ if r < 0 and gamma != 0:
660
+ stpc = stp + r * (stx - stp)
661
+ elif stp > stx:
662
+ stpc = stpmax
663
+ else:
664
+ stpc = stpmin
665
+ stpq = stp + (dp / (dp - dx)) * (stx - stp)
666
+
667
+ if brackt:
668
+ # A minimizer has been bracketed. If the cubic step is
669
+ # closer to stp than the secant step, the cubic step is
670
+ # taken, otherwise the secant step is taken.
671
+ if abs(stpc - stp) < abs(stpq - stp):
672
+ stpf = stpc
673
+ else:
674
+ stpf = stpq
675
+
676
+ if stp > stx:
677
+ stpf = min(stp + 0.66 * (sty - stp), stpf)
678
+ else:
679
+ stpf = max(stp + 0.66 * (sty - stp), stpf)
680
+ else:
681
+ # A minimizer has not been bracketed. If the cubic step is
682
+ # farther from stp than the secant step, the cubic step is
683
+ # taken, otherwise the secant step is taken.
684
+ if abs(stpc - stp) > abs(stpq - stp):
685
+ stpf = stpc
686
+ else:
687
+ stpf = stpq
688
+ stpf = np.clip(stpf, stpmin, stpmax)
689
+
690
+ else:
691
+ # Fourth case: A lower function value, derivatives of the same sign,
692
+ # and the magnitude of the derivative does not decrease. If the
693
+ # minimum is not bracketed, the step is either stpmin or stpmax,
694
+ # otherwise the cubic step is taken.
695
+ if brackt:
696
+ theta = 3.0 * (fp - fy) / (sty - stp) + dy + dp
697
+ s = max(abs(theta), abs(dy), abs(dp))
698
+ gamma = s * np.sqrt((theta / s) ** 2 - (dy / s) * (dp / s))
699
+ if stp > sty:
700
+ gamma = -gamma
701
+ p = (gamma - dp) + theta
702
+ q = ((gamma - dp) + gamma) + dy
703
+ r = p / q
704
+ stpc = stp + r * (sty - stp)
705
+ stpf = stpc
706
+ elif stp > stx:
707
+ stpf = stpmax
708
+ else:
709
+ stpf = stpmin
710
+
711
+ # Update the interval which contains a minimizer.
712
+ if fp > fx:
713
+ sty = stp
714
+ fy = fp
715
+ dy = dp
716
+ else:
717
+ if sgnd < 0:
718
+ sty = stx
719
+ fy = fx
720
+ dy = dx
721
+ stx = stp
722
+ fx = fp
723
+ dx = dp
724
+
725
+ # Compute the new step.
726
+ stp = stpf
727
+
728
+ return stx, fx, dx, sty, fy, dy, stp, brackt
llmeval-env/lib/python3.10/site-packages/scipy/optimize/_differentiable_functions.py ADDED
@@ -0,0 +1,646 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import scipy.sparse as sps
3
+ from ._numdiff import approx_derivative, group_columns
4
+ from ._hessian_update_strategy import HessianUpdateStrategy
5
+ from scipy.sparse.linalg import LinearOperator
6
+ from scipy._lib._array_api import atleast_nd, array_namespace
7
+
8
+
9
+ FD_METHODS = ('2-point', '3-point', 'cs')
10
+
11
+
12
+ class ScalarFunction:
13
+ """Scalar function and its derivatives.
14
+
15
+ This class defines a scalar function F: R^n->R and methods for
16
+ computing or approximating its first and second derivatives.
17
+
18
+ Parameters
19
+ ----------
20
+ fun : callable
21
+ evaluates the scalar function. Must be of the form ``fun(x, *args)``,
22
+ where ``x`` is the argument in the form of a 1-D array and ``args`` is
23
+ a tuple of any additional fixed parameters needed to completely specify
24
+ the function. Should return a scalar.
25
+ x0 : array-like
26
+ Provides an initial set of variables for evaluating fun. Array of real
27
+ elements of size (n,), where 'n' is the number of independent
28
+ variables.
29
+ args : tuple, optional
30
+ Any additional fixed parameters needed to completely specify the scalar
31
+ function.
32
+ grad : {callable, '2-point', '3-point', 'cs'}
33
+ Method for computing the gradient vector.
34
+ If it is a callable, it should be a function that returns the gradient
35
+ vector:
36
+
37
+ ``grad(x, *args) -> array_like, shape (n,)``
38
+
39
+ where ``x`` is an array with shape (n,) and ``args`` is a tuple with
40
+ the fixed parameters.
41
+ Alternatively, the keywords {'2-point', '3-point', 'cs'} can be used
42
+ to select a finite difference scheme for numerical estimation of the
43
+ gradient with a relative step size. These finite difference schemes
44
+ obey any specified `bounds`.
45
+ hess : {callable, '2-point', '3-point', 'cs', HessianUpdateStrategy}
46
+ Method for computing the Hessian matrix. If it is callable, it should
47
+ return the Hessian matrix:
48
+
49
+ ``hess(x, *args) -> {LinearOperator, spmatrix, array}, (n, n)``
50
+
51
+ where x is a (n,) ndarray and `args` is a tuple with the fixed
52
+ parameters. Alternatively, the keywords {'2-point', '3-point', 'cs'}
53
+ select a finite difference scheme for numerical estimation. Or, objects
54
+ implementing `HessianUpdateStrategy` interface can be used to
55
+ approximate the Hessian.
56
+ Whenever the gradient is estimated via finite-differences, the Hessian
57
+ cannot be estimated with options {'2-point', '3-point', 'cs'} and needs
58
+ to be estimated using one of the quasi-Newton strategies.
59
+ finite_diff_rel_step : None or array_like
60
+ Relative step size to use. The absolute step size is computed as
61
+ ``h = finite_diff_rel_step * sign(x0) * max(1, abs(x0))``, possibly
62
+ adjusted to fit into the bounds. For ``method='3-point'`` the sign
63
+ of `h` is ignored. If None then finite_diff_rel_step is selected
64
+ automatically,
65
+ finite_diff_bounds : tuple of array_like
66
+ Lower and upper bounds on independent variables. Defaults to no bounds,
67
+ (-np.inf, np.inf). Each bound must match the size of `x0` or be a
68
+ scalar, in the latter case the bound will be the same for all
69
+ variables. Use it to limit the range of function evaluation.
70
+ epsilon : None or array_like, optional
71
+ Absolute step size to use, possibly adjusted to fit into the bounds.
72
+ For ``method='3-point'`` the sign of `epsilon` is ignored. By default
73
+ relative steps are used, only if ``epsilon is not None`` are absolute
74
+ steps used.
75
+
76
+ Notes
77
+ -----
78
+ This class implements a memoization logic. There are methods `fun`,
79
+ `grad`, hess` and corresponding attributes `f`, `g` and `H`. The following
80
+ things should be considered:
81
+
82
+ 1. Use only public methods `fun`, `grad` and `hess`.
83
+ 2. After one of the methods is called, the corresponding attribute
84
+ will be set. However, a subsequent call with a different argument
85
+ of *any* of the methods may overwrite the attribute.
86
+ """
87
+ def __init__(self, fun, x0, args, grad, hess, finite_diff_rel_step,
88
+ finite_diff_bounds, epsilon=None):
89
+ if not callable(grad) and grad not in FD_METHODS:
90
+ raise ValueError(
91
+ f"`grad` must be either callable or one of {FD_METHODS}."
92
+ )
93
+
94
+ if not (callable(hess) or hess in FD_METHODS
95
+ or isinstance(hess, HessianUpdateStrategy)):
96
+ raise ValueError(
97
+ f"`hess` must be either callable, HessianUpdateStrategy"
98
+ f" or one of {FD_METHODS}."
99
+ )
100
+
101
+ if grad in FD_METHODS and hess in FD_METHODS:
102
+ raise ValueError("Whenever the gradient is estimated via "
103
+ "finite-differences, we require the Hessian "
104
+ "to be estimated using one of the "
105
+ "quasi-Newton strategies.")
106
+
107
+ self.xp = xp = array_namespace(x0)
108
+ _x = atleast_nd(x0, ndim=1, xp=xp)
109
+ _dtype = xp.float64
110
+ if xp.isdtype(_x.dtype, "real floating"):
111
+ _dtype = _x.dtype
112
+
113
+ # promotes to floating
114
+ self.x = xp.astype(_x, _dtype)
115
+ self.x_dtype = _dtype
116
+ self.n = self.x.size
117
+ self.nfev = 0
118
+ self.ngev = 0
119
+ self.nhev = 0
120
+ self.f_updated = False
121
+ self.g_updated = False
122
+ self.H_updated = False
123
+
124
+ self._lowest_x = None
125
+ self._lowest_f = np.inf
126
+
127
+ finite_diff_options = {}
128
+ if grad in FD_METHODS:
129
+ finite_diff_options["method"] = grad
130
+ finite_diff_options["rel_step"] = finite_diff_rel_step
131
+ finite_diff_options["abs_step"] = epsilon
132
+ finite_diff_options["bounds"] = finite_diff_bounds
133
+ if hess in FD_METHODS:
134
+ finite_diff_options["method"] = hess
135
+ finite_diff_options["rel_step"] = finite_diff_rel_step
136
+ finite_diff_options["abs_step"] = epsilon
137
+ finite_diff_options["as_linear_operator"] = True
138
+
139
+ # Function evaluation
140
+ def fun_wrapped(x):
141
+ self.nfev += 1
142
+ # Send a copy because the user may overwrite it.
143
+ # Overwriting results in undefined behaviour because
144
+ # fun(self.x) will change self.x, with the two no longer linked.
145
+ fx = fun(np.copy(x), *args)
146
+ # Make sure the function returns a true scalar
147
+ if not np.isscalar(fx):
148
+ try:
149
+ fx = np.asarray(fx).item()
150
+ except (TypeError, ValueError) as e:
151
+ raise ValueError(
152
+ "The user-provided objective function "
153
+ "must return a scalar value."
154
+ ) from e
155
+
156
+ if fx < self._lowest_f:
157
+ self._lowest_x = x
158
+ self._lowest_f = fx
159
+
160
+ return fx
161
+
162
+ def update_fun():
163
+ self.f = fun_wrapped(self.x)
164
+
165
+ self._update_fun_impl = update_fun
166
+ self._update_fun()
167
+
168
+ # Gradient evaluation
169
+ if callable(grad):
170
+ def grad_wrapped(x):
171
+ self.ngev += 1
172
+ return np.atleast_1d(grad(np.copy(x), *args))
173
+
174
+ def update_grad():
175
+ self.g = grad_wrapped(self.x)
176
+
177
+ elif grad in FD_METHODS:
178
+ def update_grad():
179
+ self._update_fun()
180
+ self.ngev += 1
181
+ self.g = approx_derivative(fun_wrapped, self.x, f0=self.f,
182
+ **finite_diff_options)
183
+
184
+ self._update_grad_impl = update_grad
185
+ self._update_grad()
186
+
187
+ # Hessian Evaluation
188
+ if callable(hess):
189
+ self.H = hess(np.copy(x0), *args)
190
+ self.H_updated = True
191
+ self.nhev += 1
192
+
193
+ if sps.issparse(self.H):
194
+ def hess_wrapped(x):
195
+ self.nhev += 1
196
+ return sps.csr_matrix(hess(np.copy(x), *args))
197
+ self.H = sps.csr_matrix(self.H)
198
+
199
+ elif isinstance(self.H, LinearOperator):
200
+ def hess_wrapped(x):
201
+ self.nhev += 1
202
+ return hess(np.copy(x), *args)
203
+
204
+ else:
205
+ def hess_wrapped(x):
206
+ self.nhev += 1
207
+ return np.atleast_2d(np.asarray(hess(np.copy(x), *args)))
208
+ self.H = np.atleast_2d(np.asarray(self.H))
209
+
210
+ def update_hess():
211
+ self.H = hess_wrapped(self.x)
212
+
213
+ elif hess in FD_METHODS:
214
+ def update_hess():
215
+ self._update_grad()
216
+ self.H = approx_derivative(grad_wrapped, self.x, f0=self.g,
217
+ **finite_diff_options)
218
+ return self.H
219
+
220
+ update_hess()
221
+ self.H_updated = True
222
+ elif isinstance(hess, HessianUpdateStrategy):
223
+ self.H = hess
224
+ self.H.initialize(self.n, 'hess')
225
+ self.H_updated = True
226
+ self.x_prev = None
227
+ self.g_prev = None
228
+
229
+ def update_hess():
230
+ self._update_grad()
231
+ self.H.update(self.x - self.x_prev, self.g - self.g_prev)
232
+
233
+ self._update_hess_impl = update_hess
234
+
235
+ if isinstance(hess, HessianUpdateStrategy):
236
+ def update_x(x):
237
+ self._update_grad()
238
+ self.x_prev = self.x
239
+ self.g_prev = self.g
240
+ # ensure that self.x is a copy of x. Don't store a reference
241
+ # otherwise the memoization doesn't work properly.
242
+
243
+ _x = atleast_nd(x, ndim=1, xp=self.xp)
244
+ self.x = self.xp.astype(_x, self.x_dtype)
245
+ self.f_updated = False
246
+ self.g_updated = False
247
+ self.H_updated = False
248
+ self._update_hess()
249
+ else:
250
+ def update_x(x):
251
+ # ensure that self.x is a copy of x. Don't store a reference
252
+ # otherwise the memoization doesn't work properly.
253
+ _x = atleast_nd(x, ndim=1, xp=self.xp)
254
+ self.x = self.xp.astype(_x, self.x_dtype)
255
+ self.f_updated = False
256
+ self.g_updated = False
257
+ self.H_updated = False
258
+ self._update_x_impl = update_x
259
+
260
+ def _update_fun(self):
261
+ if not self.f_updated:
262
+ self._update_fun_impl()
263
+ self.f_updated = True
264
+
265
+ def _update_grad(self):
266
+ if not self.g_updated:
267
+ self._update_grad_impl()
268
+ self.g_updated = True
269
+
270
+ def _update_hess(self):
271
+ if not self.H_updated:
272
+ self._update_hess_impl()
273
+ self.H_updated = True
274
+
275
+ def fun(self, x):
276
+ if not np.array_equal(x, self.x):
277
+ self._update_x_impl(x)
278
+ self._update_fun()
279
+ return self.f
280
+
281
+ def grad(self, x):
282
+ if not np.array_equal(x, self.x):
283
+ self._update_x_impl(x)
284
+ self._update_grad()
285
+ return self.g
286
+
287
+ def hess(self, x):
288
+ if not np.array_equal(x, self.x):
289
+ self._update_x_impl(x)
290
+ self._update_hess()
291
+ return self.H
292
+
293
+ def fun_and_grad(self, x):
294
+ if not np.array_equal(x, self.x):
295
+ self._update_x_impl(x)
296
+ self._update_fun()
297
+ self._update_grad()
298
+ return self.f, self.g
299
+
300
+
301
+ class VectorFunction:
302
+ """Vector function and its derivatives.
303
+
304
+ This class defines a vector function F: R^n->R^m and methods for
305
+ computing or approximating its first and second derivatives.
306
+
307
+ Notes
308
+ -----
309
+ This class implements a memoization logic. There are methods `fun`,
310
+ `jac`, hess` and corresponding attributes `f`, `J` and `H`. The following
311
+ things should be considered:
312
+
313
+ 1. Use only public methods `fun`, `jac` and `hess`.
314
+ 2. After one of the methods is called, the corresponding attribute
315
+ will be set. However, a subsequent call with a different argument
316
+ of *any* of the methods may overwrite the attribute.
317
+ """
318
+ def __init__(self, fun, x0, jac, hess,
319
+ finite_diff_rel_step, finite_diff_jac_sparsity,
320
+ finite_diff_bounds, sparse_jacobian):
321
+ if not callable(jac) and jac not in FD_METHODS:
322
+ raise ValueError(f"`jac` must be either callable or one of {FD_METHODS}.")
323
+
324
+ if not (callable(hess) or hess in FD_METHODS
325
+ or isinstance(hess, HessianUpdateStrategy)):
326
+ raise ValueError("`hess` must be either callable,"
327
+ f"HessianUpdateStrategy or one of {FD_METHODS}.")
328
+
329
+ if jac in FD_METHODS and hess in FD_METHODS:
330
+ raise ValueError("Whenever the Jacobian is estimated via "
331
+ "finite-differences, we require the Hessian to "
332
+ "be estimated using one of the quasi-Newton "
333
+ "strategies.")
334
+
335
+ self.xp = xp = array_namespace(x0)
336
+ _x = atleast_nd(x0, ndim=1, xp=xp)
337
+ _dtype = xp.float64
338
+ if xp.isdtype(_x.dtype, "real floating"):
339
+ _dtype = _x.dtype
340
+
341
+ # promotes to floating
342
+ self.x = xp.astype(_x, _dtype)
343
+ self.x_dtype = _dtype
344
+
345
+ self.n = self.x.size
346
+ self.nfev = 0
347
+ self.njev = 0
348
+ self.nhev = 0
349
+ self.f_updated = False
350
+ self.J_updated = False
351
+ self.H_updated = False
352
+
353
+ finite_diff_options = {}
354
+ if jac in FD_METHODS:
355
+ finite_diff_options["method"] = jac
356
+ finite_diff_options["rel_step"] = finite_diff_rel_step
357
+ if finite_diff_jac_sparsity is not None:
358
+ sparsity_groups = group_columns(finite_diff_jac_sparsity)
359
+ finite_diff_options["sparsity"] = (finite_diff_jac_sparsity,
360
+ sparsity_groups)
361
+ finite_diff_options["bounds"] = finite_diff_bounds
362
+ self.x_diff = np.copy(self.x)
363
+ if hess in FD_METHODS:
364
+ finite_diff_options["method"] = hess
365
+ finite_diff_options["rel_step"] = finite_diff_rel_step
366
+ finite_diff_options["as_linear_operator"] = True
367
+ self.x_diff = np.copy(self.x)
368
+ if jac in FD_METHODS and hess in FD_METHODS:
369
+ raise ValueError("Whenever the Jacobian is estimated via "
370
+ "finite-differences, we require the Hessian to "
371
+ "be estimated using one of the quasi-Newton "
372
+ "strategies.")
373
+
374
+ # Function evaluation
375
+ def fun_wrapped(x):
376
+ self.nfev += 1
377
+ return np.atleast_1d(fun(x))
378
+
379
+ def update_fun():
380
+ self.f = fun_wrapped(self.x)
381
+
382
+ self._update_fun_impl = update_fun
383
+ update_fun()
384
+
385
+ self.v = np.zeros_like(self.f)
386
+ self.m = self.v.size
387
+
388
+ # Jacobian Evaluation
389
+ if callable(jac):
390
+ self.J = jac(self.x)
391
+ self.J_updated = True
392
+ self.njev += 1
393
+
394
+ if (sparse_jacobian or
395
+ sparse_jacobian is None and sps.issparse(self.J)):
396
+ def jac_wrapped(x):
397
+ self.njev += 1
398
+ return sps.csr_matrix(jac(x))
399
+ self.J = sps.csr_matrix(self.J)
400
+ self.sparse_jacobian = True
401
+
402
+ elif sps.issparse(self.J):
403
+ def jac_wrapped(x):
404
+ self.njev += 1
405
+ return jac(x).toarray()
406
+ self.J = self.J.toarray()
407
+ self.sparse_jacobian = False
408
+
409
+ else:
410
+ def jac_wrapped(x):
411
+ self.njev += 1
412
+ return np.atleast_2d(jac(x))
413
+ self.J = np.atleast_2d(self.J)
414
+ self.sparse_jacobian = False
415
+
416
+ def update_jac():
417
+ self.J = jac_wrapped(self.x)
418
+
419
+ elif jac in FD_METHODS:
420
+ self.J = approx_derivative(fun_wrapped, self.x, f0=self.f,
421
+ **finite_diff_options)
422
+ self.J_updated = True
423
+
424
+ if (sparse_jacobian or
425
+ sparse_jacobian is None and sps.issparse(self.J)):
426
+ def update_jac():
427
+ self._update_fun()
428
+ self.J = sps.csr_matrix(
429
+ approx_derivative(fun_wrapped, self.x, f0=self.f,
430
+ **finite_diff_options))
431
+ self.J = sps.csr_matrix(self.J)
432
+ self.sparse_jacobian = True
433
+
434
+ elif sps.issparse(self.J):
435
+ def update_jac():
436
+ self._update_fun()
437
+ self.J = approx_derivative(fun_wrapped, self.x, f0=self.f,
438
+ **finite_diff_options).toarray()
439
+ self.J = self.J.toarray()
440
+ self.sparse_jacobian = False
441
+
442
+ else:
443
+ def update_jac():
444
+ self._update_fun()
445
+ self.J = np.atleast_2d(
446
+ approx_derivative(fun_wrapped, self.x, f0=self.f,
447
+ **finite_diff_options))
448
+ self.J = np.atleast_2d(self.J)
449
+ self.sparse_jacobian = False
450
+
451
+ self._update_jac_impl = update_jac
452
+
453
+ # Define Hessian
454
+ if callable(hess):
455
+ self.H = hess(self.x, self.v)
456
+ self.H_updated = True
457
+ self.nhev += 1
458
+
459
+ if sps.issparse(self.H):
460
+ def hess_wrapped(x, v):
461
+ self.nhev += 1
462
+ return sps.csr_matrix(hess(x, v))
463
+ self.H = sps.csr_matrix(self.H)
464
+
465
+ elif isinstance(self.H, LinearOperator):
466
+ def hess_wrapped(x, v):
467
+ self.nhev += 1
468
+ return hess(x, v)
469
+
470
+ else:
471
+ def hess_wrapped(x, v):
472
+ self.nhev += 1
473
+ return np.atleast_2d(np.asarray(hess(x, v)))
474
+ self.H = np.atleast_2d(np.asarray(self.H))
475
+
476
+ def update_hess():
477
+ self.H = hess_wrapped(self.x, self.v)
478
+ elif hess in FD_METHODS:
479
+ def jac_dot_v(x, v):
480
+ return jac_wrapped(x).T.dot(v)
481
+
482
+ def update_hess():
483
+ self._update_jac()
484
+ self.H = approx_derivative(jac_dot_v, self.x,
485
+ f0=self.J.T.dot(self.v),
486
+ args=(self.v,),
487
+ **finite_diff_options)
488
+ update_hess()
489
+ self.H_updated = True
490
+ elif isinstance(hess, HessianUpdateStrategy):
491
+ self.H = hess
492
+ self.H.initialize(self.n, 'hess')
493
+ self.H_updated = True
494
+ self.x_prev = None
495
+ self.J_prev = None
496
+
497
+ def update_hess():
498
+ self._update_jac()
499
+ # When v is updated before x was updated, then x_prev and
500
+ # J_prev are None and we need this check.
501
+ if self.x_prev is not None and self.J_prev is not None:
502
+ delta_x = self.x - self.x_prev
503
+ delta_g = self.J.T.dot(self.v) - self.J_prev.T.dot(self.v)
504
+ self.H.update(delta_x, delta_g)
505
+
506
+ self._update_hess_impl = update_hess
507
+
508
+ if isinstance(hess, HessianUpdateStrategy):
509
+ def update_x(x):
510
+ self._update_jac()
511
+ self.x_prev = self.x
512
+ self.J_prev = self.J
513
+ _x = atleast_nd(x, ndim=1, xp=self.xp)
514
+ self.x = self.xp.astype(_x, self.x_dtype)
515
+ self.f_updated = False
516
+ self.J_updated = False
517
+ self.H_updated = False
518
+ self._update_hess()
519
+ else:
520
+ def update_x(x):
521
+ _x = atleast_nd(x, ndim=1, xp=self.xp)
522
+ self.x = self.xp.astype(_x, self.x_dtype)
523
+ self.f_updated = False
524
+ self.J_updated = False
525
+ self.H_updated = False
526
+
527
+ self._update_x_impl = update_x
528
+
529
+ def _update_v(self, v):
530
+ if not np.array_equal(v, self.v):
531
+ self.v = v
532
+ self.H_updated = False
533
+
534
+ def _update_x(self, x):
535
+ if not np.array_equal(x, self.x):
536
+ self._update_x_impl(x)
537
+
538
+ def _update_fun(self):
539
+ if not self.f_updated:
540
+ self._update_fun_impl()
541
+ self.f_updated = True
542
+
543
+ def _update_jac(self):
544
+ if not self.J_updated:
545
+ self._update_jac_impl()
546
+ self.J_updated = True
547
+
548
+ def _update_hess(self):
549
+ if not self.H_updated:
550
+ self._update_hess_impl()
551
+ self.H_updated = True
552
+
553
+ def fun(self, x):
554
+ self._update_x(x)
555
+ self._update_fun()
556
+ return self.f
557
+
558
+ def jac(self, x):
559
+ self._update_x(x)
560
+ self._update_jac()
561
+ return self.J
562
+
563
+ def hess(self, x, v):
564
+ # v should be updated before x.
565
+ self._update_v(v)
566
+ self._update_x(x)
567
+ self._update_hess()
568
+ return self.H
569
+
570
+
571
+ class LinearVectorFunction:
572
+ """Linear vector function and its derivatives.
573
+
574
+ Defines a linear function F = A x, where x is N-D vector and
575
+ A is m-by-n matrix. The Jacobian is constant and equals to A. The Hessian
576
+ is identically zero and it is returned as a csr matrix.
577
+ """
578
+ def __init__(self, A, x0, sparse_jacobian):
579
+ if sparse_jacobian or sparse_jacobian is None and sps.issparse(A):
580
+ self.J = sps.csr_matrix(A)
581
+ self.sparse_jacobian = True
582
+ elif sps.issparse(A):
583
+ self.J = A.toarray()
584
+ self.sparse_jacobian = False
585
+ else:
586
+ # np.asarray makes sure A is ndarray and not matrix
587
+ self.J = np.atleast_2d(np.asarray(A))
588
+ self.sparse_jacobian = False
589
+
590
+ self.m, self.n = self.J.shape
591
+
592
+ self.xp = xp = array_namespace(x0)
593
+ _x = atleast_nd(x0, ndim=1, xp=xp)
594
+ _dtype = xp.float64
595
+ if xp.isdtype(_x.dtype, "real floating"):
596
+ _dtype = _x.dtype
597
+
598
+ # promotes to floating
599
+ self.x = xp.astype(_x, _dtype)
600
+ self.x_dtype = _dtype
601
+
602
+ self.f = self.J.dot(self.x)
603
+ self.f_updated = True
604
+
605
+ self.v = np.zeros(self.m, dtype=float)
606
+ self.H = sps.csr_matrix((self.n, self.n))
607
+
608
+ def _update_x(self, x):
609
+ if not np.array_equal(x, self.x):
610
+ _x = atleast_nd(x, ndim=1, xp=self.xp)
611
+ self.x = self.xp.astype(_x, self.x_dtype)
612
+ self.f_updated = False
613
+
614
+ def fun(self, x):
615
+ self._update_x(x)
616
+ if not self.f_updated:
617
+ self.f = self.J.dot(x)
618
+ self.f_updated = True
619
+ return self.f
620
+
621
+ def jac(self, x):
622
+ self._update_x(x)
623
+ return self.J
624
+
625
+ def hess(self, x, v):
626
+ self._update_x(x)
627
+ self.v = v
628
+ return self.H
629
+
630
+
631
+ class IdentityVectorFunction(LinearVectorFunction):
632
+ """Identity vector function and its derivatives.
633
+
634
+ The Jacobian is the identity matrix, returned as a dense array when
635
+ `sparse_jacobian=False` and as a csr matrix otherwise. The Hessian is
636
+ identically zero and it is returned as a csr matrix.
637
+ """
638
+ def __init__(self, x0, sparse_jacobian):
639
+ n = len(x0)
640
+ if sparse_jacobian or sparse_jacobian is None:
641
+ A = sps.eye(n, format='csr')
642
+ sparse_jacobian = True
643
+ else:
644
+ A = np.eye(n)
645
+ sparse_jacobian = False
646
+ super().__init__(A, x0, sparse_jacobian)