Ravenveil commited on
Commit
eeeb9a9
·
verified ·
1 Parent(s): c5d2e6c

backup 04_physworld 2026-11-08 10:11:26 (part 18)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +65 -0
  2. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/test_c_api.py +102 -0
  3. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/test_datatypes.py +67 -0
  4. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/test_filters.py +0 -0
  5. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/test_fourier.py +197 -0
  6. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/test_interpolation.py +1499 -0
  7. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/test_measurements.py +1696 -0
  8. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/test_morphology.py +0 -0
  9. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/test_ni_support.py +77 -0
  10. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/test_splines.py +68 -0
  11. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/__init__.py +177 -0
  12. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/__odrpack.cpython-311-x86_64-linux-gnu.so +3 -0
  13. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/__pycache__/__init__.cpython-311.pyc +0 -0
  14. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/__pycache__/_add_newdocs.cpython-311.pyc +0 -0
  15. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/__pycache__/_models.cpython-311.pyc +0 -0
  16. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/__pycache__/_odrpack.cpython-311.pyc +0 -0
  17. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/__pycache__/models.cpython-311.pyc +0 -0
  18. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/__pycache__/odrpack.cpython-311.pyc +0 -0
  19. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/_add_newdocs.py +39 -0
  20. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/_models.py +333 -0
  21. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/_odrpack.py +1200 -0
  22. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/models.py +27 -0
  23. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/odrpack.py +28 -0
  24. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/tests/__init__.py +0 -0
  25. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/tests/__pycache__/__init__.cpython-311.pyc +0 -0
  26. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/tests/__pycache__/test_odr.cpython-311.pyc +0 -0
  27. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/tests/test_odr.py +621 -0
  28. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__init__.pxd +1 -0
  29. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__init__.py +460 -0
  30. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/__init__.cpython-311.pyc +0 -0
  31. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_basinhopping.cpython-311.pyc +0 -0
  32. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_bracket.cpython-311.pyc +0 -0
  33. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_chandrupatla.cpython-311.pyc +0 -0
  34. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_cobyla_py.cpython-311.pyc +0 -0
  35. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_cobyqa_py.cpython-311.pyc +0 -0
  36. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_constraints.cpython-311.pyc +0 -0
  37. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_dcsrch.cpython-311.pyc +0 -0
  38. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_differentiable_functions.cpython-311.pyc +0 -0
  39. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_differentialevolution.cpython-311.pyc +0 -0
  40. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_direct_py.cpython-311.pyc +0 -0
  41. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_dual_annealing.cpython-311.pyc +0 -0
  42. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_elementwise.cpython-311.pyc +0 -0
  43. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_hessian_update_strategy.cpython-311.pyc +0 -0
  44. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_isotonic.cpython-311.pyc +0 -0
  45. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_lbfgsb_py.cpython-311.pyc +0 -0
  46. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_linesearch.cpython-311.pyc +0 -0
  47. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_linprog.cpython-311.pyc +0 -0
  48. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_linprog_doc.cpython-311.pyc +0 -0
  49. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_linprog_highs.cpython-311.pyc +0 -0
  50. physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_linprog_ip.cpython-311.pyc +0 -0
.gitattributes CHANGED
@@ -3673,3 +3673,68 @@ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/_
3673
  physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/__pycache__/test_interpolation.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3674
  physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/__pycache__/test_measurements.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3675
  physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/__pycache__/test_morphology.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3673
  physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/__pycache__/test_interpolation.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3674
  physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/__pycache__/test_measurements.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3675
  physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/__pycache__/test_morphology.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3676
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/__odrpack.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3677
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_optimize.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3678
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/_bglu_dense.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3679
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/_highspy/_core.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3680
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/_highspy/_highs_options.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3681
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/_lbfgsb.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3682
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/_moduleTNC.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3683
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/_pava_pybind.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3684
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/_slsqplib.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3685
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/_trlib/_trlib.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3686
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/tests/__pycache__/test__differential_evolution.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3687
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/tests/__pycache__/test_linprog.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3688
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/tests/__pycache__/test_optimize.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3689
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/signal/__pycache__/_filter_design.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3690
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/signal/__pycache__/_ltisys.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3691
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/signal/__pycache__/_short_time_fft.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3692
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/signal/__pycache__/_signaltools.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3693
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/signal/__pycache__/_spectral_py.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3694
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/signal/_peak_finding_utils.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3695
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/signal/_sigtools.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3696
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/signal/_sosfilt.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3697
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/signal/_upfirdn_apply.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3698
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/signal/tests/__pycache__/test_filter_design.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3699
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/signal/tests/__pycache__/test_signaltools.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3700
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/signal/tests/__pycache__/test_spectral.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3701
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/signal/windows/__pycache__/_windows.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3702
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/sparse/__pycache__/_coo.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3703
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/sparse/_csparsetools.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3704
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/sparse/_sparsetools.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3705
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/sparse/csgraph/_flow.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3706
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/sparse/csgraph/_matching.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3707
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/sparse/csgraph/_min_spanning_tree.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3708
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/sparse/csgraph/_reordering.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3709
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/sparse/csgraph/_shortest_path.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3710
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/sparse/csgraph/_tools.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3711
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/sparse/csgraph/_traversal.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3712
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/sparse/linalg/_dsolve/_superlu.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3713
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/sparse/linalg/_eigen/arpack/_arpacklib.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3714
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/sparse/linalg/_propack.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3715
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/sparse/tests/__pycache__/test_base.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3716
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/sparse/tests/__pycache__/test_coo.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3717
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/spatial/__pycache__/distance.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3718
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/spatial/_ckdtree.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3719
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/spatial/_distance_pybind.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3720
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/spatial/_distance_wrap.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3721
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/spatial/_qhull.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3722
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/spatial/tests/__pycache__/test_distance.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3723
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/spatial/tests/__pycache__/test_kdtree.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3724
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/spatial/transform/__pycache__/_rotation.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3725
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/spatial/transform/_rigid_transform_cy.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3726
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/spatial/transform/_rotation_cy.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3727
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/spatial/transform/tests/__pycache__/test_rigid_transform.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3728
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/spatial/transform/tests/__pycache__/test_rotation.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3729
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/special/__pycache__/_add_newdocs.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3730
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/special/__pycache__/_basic.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3731
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/special/_ellip_harm_2.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3732
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/special/_gufuncs.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3733
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/special/_specfun.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3734
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/special/_special_ufuncs.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3735
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/special/_ufuncs.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3736
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/special/_ufuncs_cxx.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3737
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/special/cython_special.cpython-311-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
3738
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/special/tests/__pycache__/test_basic.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3739
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/special/tests/__pycache__/test_legendre.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
3740
+ physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/special/tests/__pycache__/test_mpmath.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/test_c_api.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy._lib._array_api import xp_assert_close
3
+
4
+ from scipy import ndimage
5
+ from scipy.ndimage import _ctest
6
+ from scipy.ndimage import _cytest
7
+ from scipy._lib._ccallback import LowLevelCallable
8
+
9
+ FILTER1D_FUNCTIONS = [
10
+ lambda filter_size: _ctest.filter1d(filter_size),
11
+ lambda filter_size: _cytest.filter1d(filter_size, with_signature=False),
12
+ lambda filter_size: LowLevelCallable(
13
+ _cytest.filter1d(filter_size, with_signature=True)
14
+ ),
15
+ lambda filter_size: LowLevelCallable.from_cython(
16
+ _cytest, "_filter1d",
17
+ _cytest.filter1d_capsule(filter_size),
18
+ ),
19
+ ]
20
+
21
+ FILTER2D_FUNCTIONS = [
22
+ lambda weights: _ctest.filter2d(weights),
23
+ lambda weights: _cytest.filter2d(weights, with_signature=False),
24
+ lambda weights: LowLevelCallable(_cytest.filter2d(weights, with_signature=True)),
25
+ lambda weights: LowLevelCallable.from_cython(_cytest,
26
+ "_filter2d",
27
+ _cytest.filter2d_capsule(weights),),
28
+ ]
29
+
30
+ TRANSFORM_FUNCTIONS = [
31
+ lambda shift: _ctest.transform(shift),
32
+ lambda shift: _cytest.transform(shift, with_signature=False),
33
+ lambda shift: LowLevelCallable(_cytest.transform(shift, with_signature=True)),
34
+ lambda shift: LowLevelCallable.from_cython(_cytest,
35
+ "_transform",
36
+ _cytest.transform_capsule(shift),),
37
+ ]
38
+
39
+
40
+ def test_generic_filter():
41
+ def filter2d(footprint_elements, weights):
42
+ return (weights*footprint_elements).sum()
43
+
44
+ def check(j):
45
+ func = FILTER2D_FUNCTIONS[j]
46
+
47
+ im = np.ones((20, 20))
48
+ im[:10,:10] = 0
49
+ footprint = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])
50
+ footprint_size = np.count_nonzero(footprint)
51
+ weights = np.ones(footprint_size)/footprint_size
52
+
53
+ res = ndimage.generic_filter(im, func(weights),
54
+ footprint=footprint)
55
+ std = ndimage.generic_filter(im, filter2d, footprint=footprint,
56
+ extra_arguments=(weights,))
57
+ xp_assert_close(res, std, err_msg=f"#{j} failed")
58
+
59
+ for j, func in enumerate(FILTER2D_FUNCTIONS):
60
+ check(j)
61
+
62
+
63
+ def test_generic_filter1d():
64
+ def filter1d(input_line, output_line, filter_size):
65
+ for i in range(output_line.size):
66
+ output_line[i] = 0
67
+ for j in range(filter_size):
68
+ output_line[i] += input_line[i+j]
69
+ output_line /= filter_size
70
+
71
+ def check(j):
72
+ func = FILTER1D_FUNCTIONS[j]
73
+
74
+ im = np.tile(np.hstack((np.zeros(10), np.ones(10))), (10, 1))
75
+ filter_size = 3
76
+
77
+ res = ndimage.generic_filter1d(im, func(filter_size),
78
+ filter_size)
79
+ std = ndimage.generic_filter1d(im, filter1d, filter_size,
80
+ extra_arguments=(filter_size,))
81
+ xp_assert_close(res, std, err_msg=f"#{j} failed")
82
+
83
+ for j, func in enumerate(FILTER1D_FUNCTIONS):
84
+ check(j)
85
+
86
+
87
+ def test_geometric_transform():
88
+ def transform(output_coordinates, shift):
89
+ return output_coordinates[0] - shift, output_coordinates[1] - shift
90
+
91
+ def check(j):
92
+ func = TRANSFORM_FUNCTIONS[j]
93
+
94
+ im = np.arange(12).reshape(4, 3).astype(np.float64)
95
+ shift = 0.5
96
+
97
+ res = ndimage.geometric_transform(im, func(shift))
98
+ std = ndimage.geometric_transform(im, transform, extra_arguments=(shift,))
99
+ xp_assert_close(res, std, err_msg=f"#{j} failed")
100
+
101
+ for j, func in enumerate(TRANSFORM_FUNCTIONS):
102
+ check(j)
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/test_datatypes.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Testing data types for ndimage calls
2
+ """
3
+ import numpy as np
4
+
5
+ from scipy._lib._array_api import assert_array_almost_equal
6
+ import pytest
7
+
8
+ from scipy import ndimage
9
+
10
+
11
+ def test_map_coordinates_dts():
12
+ # check that ndimage accepts different data types for interpolation
13
+ data = np.array([[4, 1, 3, 2],
14
+ [7, 6, 8, 5],
15
+ [3, 5, 3, 6]])
16
+ shifted_data = np.array([[0, 0, 0, 0],
17
+ [0, 4, 1, 3],
18
+ [0, 7, 6, 8]])
19
+ idx = np.indices(data.shape)
20
+ dts = (np.uint8, np.uint16, np.uint32, np.uint64,
21
+ np.int8, np.int16, np.int32, np.int64,
22
+ np.intp, np.uintp, np.float32, np.float64)
23
+ for order in range(0, 6):
24
+ for data_dt in dts:
25
+ these_data = data.astype(data_dt)
26
+ for coord_dt in dts:
27
+ # affine mapping
28
+ mat = np.eye(2, dtype=coord_dt)
29
+ off = np.zeros((2,), dtype=coord_dt)
30
+ out = ndimage.affine_transform(these_data, mat, off)
31
+ assert_array_almost_equal(these_data, out)
32
+ # map coordinates
33
+ coords_m1 = idx.astype(coord_dt) - 1
34
+ coords_p10 = idx.astype(coord_dt) + 10
35
+ out = ndimage.map_coordinates(these_data, coords_m1, order=order)
36
+ assert_array_almost_equal(out, shifted_data)
37
+ # check constant fill works
38
+ out = ndimage.map_coordinates(these_data, coords_p10, order=order)
39
+ assert_array_almost_equal(out, np.zeros((3,4)))
40
+ # check shift and zoom
41
+ out = ndimage.shift(these_data, 1)
42
+ assert_array_almost_equal(out, shifted_data)
43
+ out = ndimage.zoom(these_data, 1)
44
+ assert_array_almost_equal(these_data, out)
45
+
46
+
47
+ @pytest.mark.xfail(True, reason="Broken on many platforms")
48
+ def test_uint64_max():
49
+ # Test interpolation respects uint64 max. Reported to fail at least on
50
+ # win32 (due to the 32 bit visual C compiler using signed int64 when
51
+ # converting between uint64 to double) and Debian on s390x.
52
+ # Interpolation is always done in double precision floating point, so
53
+ # we use the largest uint64 value for which int(float(big)) still fits
54
+ # in a uint64.
55
+ # This test was last enabled on macOS only, and there it started failing
56
+ # on arm64 as well (see gh-19117).
57
+ big = 2**64 - 1025
58
+ arr = np.array([big, big, big], dtype=np.uint64)
59
+ # Tests geometric transform (map_coordinates, affine_transform)
60
+ inds = np.indices(arr.shape) - 0.1
61
+ x = ndimage.map_coordinates(arr, inds)
62
+ assert x[1] == int(float(big))
63
+ assert x[2] == int(float(big))
64
+ # Tests zoom / shift
65
+ x = ndimage.shift(arr, 0.1)
66
+ assert x[1] == int(float(big))
67
+ assert x[2] == int(float(big))
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/test_filters.py ADDED
The diff for this file is too large to render. See raw diff
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/test_fourier.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import numpy as np
3
+
4
+ from scipy._lib._array_api import (
5
+ xp_assert_equal,
6
+ assert_array_almost_equal,
7
+ assert_almost_equal,
8
+ is_cupy,
9
+ make_xp_test_case,
10
+ make_xp_pytest_param,
11
+ )
12
+
13
+ import pytest
14
+
15
+ from scipy import ndimage
16
+
17
+ skip_xp_backends = pytest.mark.skip_xp_backends
18
+
19
+
20
+ class TestNdimageFourier:
21
+
22
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
23
+ @pytest.mark.parametrize('dtype, dec', [("float32", 6), ("float64", 14)])
24
+ @make_xp_test_case(ndimage.fourier_gaussian)
25
+ def test_fourier_gaussian_real01(self, shape, dtype, dec, xp):
26
+ fft = getattr(xp, 'fft')
27
+
28
+ a = np.zeros(shape, dtype=dtype)
29
+ a[0, 0] = 1.0
30
+ a = xp.asarray(a)
31
+
32
+ a = fft.rfft(a, n=shape[0], axis=0)
33
+ a = fft.fft(a, n=shape[1], axis=1)
34
+ a = ndimage.fourier_gaussian(a, [5.0, 2.5], shape[0], 0)
35
+ a = fft.ifft(a, n=shape[1], axis=1)
36
+ a = fft.irfft(a, n=shape[0], axis=0)
37
+ assert_almost_equal(ndimage.sum(a), xp.asarray(1), decimal=dec,
38
+ check_0d=False)
39
+
40
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
41
+ @pytest.mark.parametrize('dtype, dec', [("complex64", 6), ("complex128", 14)])
42
+ @make_xp_test_case(ndimage.fourier_gaussian)
43
+ def test_fourier_gaussian_complex01(self, shape, dtype, dec, xp):
44
+ fft = getattr(xp, 'fft')
45
+
46
+ a = np.zeros(shape, dtype=dtype)
47
+ a[0, 0] = 1.0
48
+ a = xp.asarray(a)
49
+
50
+ a = fft.fft(a, n=shape[0], axis=0)
51
+ a = fft.fft(a, n=shape[1], axis=1)
52
+ a = ndimage.fourier_gaussian(a, [5.0, 2.5], -1, 0)
53
+ a = fft.ifft(a, n=shape[1], axis=1)
54
+ a = fft.ifft(a, n=shape[0], axis=0)
55
+ assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec,
56
+ check_0d=False)
57
+
58
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
59
+ @pytest.mark.parametrize('dtype, dec', [("float32", 6), ("float64", 14)])
60
+ @make_xp_test_case(ndimage.fourier_uniform)
61
+ def test_fourier_uniform_real01(self, shape, dtype, dec, xp):
62
+ fft = getattr(xp, 'fft')
63
+
64
+ a = np.zeros(shape, dtype=dtype)
65
+ a[0, 0] = 1.0
66
+ a = xp.asarray(a)
67
+
68
+ a = fft.rfft(a, n=shape[0], axis=0)
69
+ a = fft.fft(a, n=shape[1], axis=1)
70
+ a = ndimage.fourier_uniform(a, [5.0, 2.5], shape[0], 0)
71
+ a = fft.ifft(a, n=shape[1], axis=1)
72
+ a = fft.irfft(a, n=shape[0], axis=0)
73
+ assert_almost_equal(ndimage.sum(a), xp.asarray(1.0), decimal=dec,
74
+ check_0d=False)
75
+
76
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
77
+ @pytest.mark.parametrize('dtype, dec', [("complex64", 6), ("complex128", 14)])
78
+ @make_xp_test_case(ndimage.fourier_uniform)
79
+ def test_fourier_uniform_complex01(self, shape, dtype, dec, xp):
80
+ fft = getattr(xp, 'fft')
81
+
82
+ a = np.zeros(shape, dtype=dtype)
83
+ a[0, 0] = 1.0
84
+ a = xp.asarray(a)
85
+
86
+ a = fft.fft(a, n=shape[0], axis=0)
87
+ a = fft.fft(a, n=shape[1], axis=1)
88
+ a = ndimage.fourier_uniform(a, [5.0, 2.5], -1, 0)
89
+ a = fft.ifft(a, n=shape[1], axis=1)
90
+ a = fft.ifft(a, n=shape[0], axis=0)
91
+ assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec,
92
+ check_0d=False)
93
+
94
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
95
+ @pytest.mark.parametrize('dtype, dec', [("float32", 4), ("float64", 11)])
96
+ @make_xp_test_case(ndimage.fourier_shift)
97
+ def test_fourier_shift_real01(self, shape, dtype, dec, xp):
98
+ fft = getattr(xp, 'fft')
99
+
100
+ expected = np.arange(shape[0] * shape[1], dtype=dtype).reshape(shape)
101
+ expected = xp.asarray(expected)
102
+
103
+ a = fft.rfft(expected, n=shape[0], axis=0)
104
+ a = fft.fft(a, n=shape[1], axis=1)
105
+ a = ndimage.fourier_shift(a, [1, 1], shape[0], 0)
106
+ a = fft.ifft(a, n=shape[1], axis=1)
107
+ a = fft.irfft(a, n=shape[0], axis=0)
108
+ assert_array_almost_equal(a[1:, 1:], expected[:-1, :-1], decimal=dec)
109
+
110
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
111
+ @pytest.mark.parametrize('dtype, dec', [("complex64", 4), ("complex128", 11)])
112
+ @make_xp_test_case(ndimage.fourier_shift)
113
+ def test_fourier_shift_complex01(self, shape, dtype, dec, xp):
114
+ fft = getattr(xp, 'fft')
115
+
116
+ expected = np.arange(shape[0] * shape[1], dtype=dtype).reshape(shape)
117
+ expected = xp.asarray(expected)
118
+
119
+ a = fft.fft(expected, n=shape[0], axis=0)
120
+ a = fft.fft(a, n=shape[1], axis=1)
121
+ a = ndimage.fourier_shift(a, [1, 1], -1, 0)
122
+ a = fft.ifft(a, n=shape[1], axis=1)
123
+ a = fft.ifft(a, n=shape[0], axis=0)
124
+ assert_array_almost_equal(xp.real(a)[1:, 1:], expected[:-1, :-1], decimal=dec)
125
+ assert_array_almost_equal(xp.imag(a), xp.zeros(shape), decimal=dec)
126
+
127
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
128
+ @pytest.mark.parametrize('dtype, dec', [("float32", 5), ("float64", 14)])
129
+ @make_xp_test_case(ndimage.fourier_ellipsoid)
130
+ def test_fourier_ellipsoid_real01(self, shape, dtype, dec, xp):
131
+ fft = getattr(xp, 'fft')
132
+
133
+ a = np.zeros(shape, dtype=dtype)
134
+ a[0, 0] = 1.0
135
+ a = xp.asarray(a)
136
+
137
+ a = fft.rfft(a, n=shape[0], axis=0)
138
+ a = fft.fft(a, n=shape[1], axis=1)
139
+ a = ndimage.fourier_ellipsoid(a, [5.0, 2.5], shape[0], 0)
140
+ a = fft.ifft(a, n=shape[1], axis=1)
141
+ a = fft.irfft(a, n=shape[0], axis=0)
142
+ assert_almost_equal(ndimage.sum(a), xp.asarray(1.0), decimal=dec,
143
+ check_0d=False)
144
+
145
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
146
+ @pytest.mark.parametrize('dtype, dec', [("complex64", 5), ("complex128", 14)])
147
+ @make_xp_test_case(ndimage.fourier_ellipsoid)
148
+ def test_fourier_ellipsoid_complex01(self, shape, dtype, dec, xp):
149
+ fft = getattr(xp, 'fft')
150
+
151
+ a = np.zeros(shape, dtype=dtype)
152
+ a[0, 0] = 1.0
153
+ a = xp.asarray(a)
154
+
155
+ a = fft.fft(a, n=shape[0], axis=0)
156
+ a = fft.fft(a, n=shape[1], axis=1)
157
+ a = ndimage.fourier_ellipsoid(a, [5.0, 2.5], -1, 0)
158
+ a = fft.ifft(a, n=shape[1], axis=1)
159
+ a = fft.ifft(a, n=shape[0], axis=0)
160
+ assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec,
161
+ check_0d=False)
162
+
163
+ @make_xp_test_case(ndimage.fourier_ellipsoid)
164
+ def test_fourier_ellipsoid_unimplemented_ndim(self, xp):
165
+ # arrays with ndim > 3 raise NotImplementedError
166
+ x = xp.ones((4, 6, 8, 10), dtype=xp.complex128)
167
+ with pytest.raises(NotImplementedError):
168
+ ndimage.fourier_ellipsoid(x, 3)
169
+
170
+ @make_xp_test_case(ndimage.fourier_ellipsoid)
171
+ def test_fourier_ellipsoid_1d_complex(self, xp):
172
+ # expected result of 1d ellipsoid is the same as for fourier_uniform
173
+ for shape in [(32, ), (31, )]:
174
+ for type_, dec in zip([xp.complex64, xp.complex128], [5, 14]):
175
+ x = xp.ones(shape, dtype=type_)
176
+ a = ndimage.fourier_ellipsoid(x, 5, -1, 0)
177
+ b = ndimage.fourier_uniform(x, 5, -1, 0)
178
+ assert_array_almost_equal(a, b, decimal=dec)
179
+
180
+ @pytest.mark.parametrize('shape', [(0, ), (0, 10), (10, 0)])
181
+ @pytest.mark.parametrize('dtype', ["float32", "float64",
182
+ "complex64", "complex128"])
183
+ @pytest.mark.parametrize('test_func',
184
+ [make_xp_pytest_param(ndimage.fourier_ellipsoid),
185
+ make_xp_pytest_param(ndimage.fourier_gaussian),
186
+ make_xp_pytest_param(ndimage.fourier_uniform)])
187
+ def test_fourier_zero_length_dims(self, shape, dtype, test_func, xp):
188
+ if (
189
+ is_cupy(xp)
190
+ and test_func.__name__ == "fourier_ellipsoid"
191
+ and math.prod(shape) == 0
192
+ ):
193
+ pytest.xfail("CuPy's fourier_ellipsoid does not accept size==0 arrays")
194
+ dtype = getattr(xp, dtype)
195
+ a = xp.ones(shape, dtype=dtype)
196
+ b = test_func(a, 3)
197
+ xp_assert_equal(a, b)
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/test_interpolation.py ADDED
@@ -0,0 +1,1499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import warnings
3
+
4
+ import numpy as np
5
+ from scipy._lib._array_api import (
6
+ _asarray, assert_array_almost_equal,
7
+ is_jax, np_compat,
8
+ xp_assert_equal, xp_assert_close,
9
+ make_xp_test_case,
10
+ )
11
+
12
+ import pytest
13
+ from pytest import raises as assert_raises
14
+ import scipy.ndimage as ndimage
15
+
16
+ from . import types
17
+
18
+ skip_xp_backends = pytest.mark.skip_xp_backends
19
+ xfail_xp_backends = pytest.mark.xfail_xp_backends
20
+ # lazy_xp_modules = [ndimage]
21
+
22
+
23
+ eps = 1e-12
24
+
25
+ ndimage_to_numpy_mode = {
26
+ 'mirror': 'reflect',
27
+ 'reflect': 'symmetric',
28
+ 'grid-mirror': 'symmetric',
29
+ 'grid-wrap': 'wrap',
30
+ 'nearest': 'edge',
31
+ 'grid-constant': 'constant',
32
+ }
33
+
34
+
35
+ class TestBoundaries:
36
+
37
+ @make_xp_test_case(ndimage.geometric_transform)
38
+ @pytest.mark.parametrize(
39
+ 'mode, expected_value',
40
+ [('nearest', [1.5, 2.5, 3.5, 4, 4, 4, 4]),
41
+ ('wrap', [1.5, 2.5, 3.5, 1.5, 2.5, 3.5, 1.5]),
42
+ ('grid-wrap', [1.5, 2.5, 3.5, 2.5, 1.5, 2.5, 3.5]),
43
+ ('mirror', [1.5, 2.5, 3.5, 3.5, 2.5, 1.5, 1.5]),
44
+ ('reflect', [1.5, 2.5, 3.5, 4, 3.5, 2.5, 1.5]),
45
+ ('constant', [1.5, 2.5, 3.5, -1, -1, -1, -1]),
46
+ ('grid-constant', [1.5, 2.5, 3.5, 1.5, -1, -1, -1])]
47
+ )
48
+ def test_boundaries(self, mode, expected_value, xp):
49
+ def shift(x):
50
+ return (x[0] + 0.5,)
51
+
52
+ data = xp.asarray([1, 2, 3, 4.])
53
+ xp_assert_equal(
54
+ ndimage.geometric_transform(data, shift, cval=-1, mode=mode,
55
+ output_shape=(7,), order=1),
56
+ xp.asarray(expected_value))
57
+
58
+ @make_xp_test_case(ndimage.geometric_transform)
59
+ @pytest.mark.parametrize(
60
+ 'mode, expected_value',
61
+ [('nearest', [1, 1, 2, 3]),
62
+ ('wrap', [3, 1, 2, 3]),
63
+ ('grid-wrap', [4, 1, 2, 3]),
64
+ ('mirror', [2, 1, 2, 3]),
65
+ ('reflect', [1, 1, 2, 3]),
66
+ ('constant', [-1, 1, 2, 3]),
67
+ ('grid-constant', [-1, 1, 2, 3])]
68
+ )
69
+ def test_boundaries2(self, mode, expected_value, xp):
70
+ def shift(x):
71
+ return (x[0] - 0.9,)
72
+
73
+ data = xp.asarray([1, 2, 3, 4])
74
+ xp_assert_equal(
75
+ ndimage.geometric_transform(data, shift, cval=-1, mode=mode,
76
+ output_shape=(4,)),
77
+ xp.asarray(expected_value))
78
+
79
+ @make_xp_test_case(ndimage.map_coordinates)
80
+ @pytest.mark.parametrize('mode', ['mirror', 'reflect', 'grid-mirror',
81
+ 'grid-wrap', 'grid-constant',
82
+ 'nearest'])
83
+ @pytest.mark.parametrize('order', range(6))
84
+ def test_boundary_spline_accuracy(self, mode, order, xp):
85
+ """Tests based on examples from gh-2640"""
86
+ if (is_jax(xp) and
87
+ (mode not in ['mirror', 'reflect', 'constant', 'wrap', 'nearest']
88
+ or order > 1)
89
+ ):
90
+ pytest.xfail("Jax does not support grid- modes or order > 1")
91
+
92
+ np_data = np.arange(-6, 7, dtype=np.float64)
93
+ data = xp.asarray(np_data)
94
+ x = xp.asarray(np.linspace(-8, 15, num=1000))
95
+ y = ndimage.map_coordinates(data, x[xp.newaxis, ...], order=order, mode=mode)
96
+
97
+ # compute expected value using explicit padding via np.pad
98
+ npad = 32
99
+ pad_mode = ndimage_to_numpy_mode.get(mode)
100
+ padded = xp.asarray(np.pad(np_data, npad, mode=pad_mode))
101
+ coords = xp.asarray(npad + x)[xp.newaxis, ...]
102
+ expected = ndimage.map_coordinates(padded, coords, order=order, mode=mode)
103
+
104
+ atol = 1e-5 if mode == 'grid-constant' else 1e-12
105
+ xp_assert_close(y, expected, rtol=1e-7, atol=atol)
106
+
107
+
108
+ @make_xp_test_case(ndimage.spline_filter)
109
+ @pytest.mark.parametrize('order', range(2, 6))
110
+ @pytest.mark.parametrize('dtype', types)
111
+ class TestSpline:
112
+
113
+ def test_spline01(self, dtype, order, xp):
114
+ dtype = getattr(xp, dtype)
115
+ data = xp.ones([], dtype=dtype)
116
+ out = ndimage.spline_filter(data, order=order)
117
+ assert out == xp.asarray(1, dtype=out.dtype)
118
+
119
+ def test_spline02(self, dtype, order, xp):
120
+ dtype = getattr(xp, dtype)
121
+ data = xp.asarray([1], dtype=dtype)
122
+ out = ndimage.spline_filter(data, order=order)
123
+ assert_array_almost_equal(out, xp.asarray([1]))
124
+
125
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
126
+ reason='output=dtype is numpy-specific')
127
+ def test_spline03(self, dtype, order, xp):
128
+ dtype = getattr(xp, dtype)
129
+ data = xp.ones([], dtype=dtype)
130
+ out = ndimage.spline_filter(data, order, output=dtype)
131
+ assert out == xp.asarray(1, dtype=out.dtype)
132
+
133
+ def test_spline04(self, dtype, order, xp):
134
+ dtype = getattr(xp, dtype)
135
+ data = xp.ones([4], dtype=dtype)
136
+ out = ndimage.spline_filter(data, order)
137
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1]))
138
+
139
+ def test_spline05(self, dtype, order, xp):
140
+ dtype = getattr(xp, dtype)
141
+ data = xp.ones([4, 4], dtype=dtype)
142
+ out = ndimage.spline_filter(data, order=order)
143
+ expected = xp.asarray([[1, 1, 1, 1],
144
+ [1, 1, 1, 1],
145
+ [1, 1, 1, 1],
146
+ [1, 1, 1, 1]])
147
+ assert_array_almost_equal(out, expected)
148
+
149
+
150
+ @make_xp_test_case(ndimage.geometric_transform)
151
+ @pytest.mark.parametrize('order', range(0, 6))
152
+ class TestGeometricTransform:
153
+
154
+ def test_geometric_transform01(self, order, xp):
155
+ data = xp.asarray([1])
156
+
157
+ def mapping(x):
158
+ return x
159
+
160
+ out = ndimage.geometric_transform(data, mapping, data.shape,
161
+ order=order)
162
+ assert_array_almost_equal(out, xp.asarray([1], dtype=out.dtype))
163
+
164
+ def test_geometric_transform02(self, order, xp):
165
+ data = xp.ones([4])
166
+
167
+ def mapping(x):
168
+ return x
169
+
170
+ out = ndimage.geometric_transform(data, mapping, data.shape,
171
+ order=order)
172
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1], dtype=out.dtype))
173
+
174
+ def test_geometric_transform03(self, order, xp):
175
+ data = xp.ones([4])
176
+
177
+ def mapping(x):
178
+ return (x[0] - 1,)
179
+
180
+ out = ndimage.geometric_transform(data, mapping, data.shape,
181
+ order=order)
182
+ assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1], dtype=out.dtype))
183
+
184
+ def test_geometric_transform04(self, order, xp):
185
+ data = xp.asarray([4, 1, 3, 2])
186
+
187
+ def mapping(x):
188
+ return (x[0] - 1,)
189
+
190
+ out = ndimage.geometric_transform(data, mapping, data.shape,
191
+ order=order)
192
+ assert_array_almost_equal(out, xp.asarray([0, 4, 1, 3], dtype=out.dtype))
193
+
194
+ @pytest.mark.parametrize('dtype', ["float64", "complex128"])
195
+ def test_geometric_transform05(self, order, dtype, xp):
196
+ dtype = getattr(xp, dtype)
197
+ data = xp.asarray([[1, 1, 1, 1],
198
+ [1, 1, 1, 1],
199
+ [1, 1, 1, 1]], dtype=dtype)
200
+ expected = xp.asarray([[0, 1, 1, 1],
201
+ [0, 1, 1, 1],
202
+ [0, 1, 1, 1]], dtype=dtype)
203
+
204
+ if xp.isdtype(data.dtype, 'complex floating'):
205
+ data -= 1j * data
206
+ expected -= 1j * expected
207
+
208
+ def mapping(x):
209
+ return (x[0], x[1] - 1)
210
+
211
+ out = ndimage.geometric_transform(data, mapping, data.shape,
212
+ order=order)
213
+ assert_array_almost_equal(out, expected)
214
+
215
+ def test_geometric_transform06(self, order, xp):
216
+ data = xp.asarray([[4, 1, 3, 2],
217
+ [7, 6, 8, 5],
218
+ [3, 5, 3, 6]])
219
+
220
+ def mapping(x):
221
+ return (x[0], x[1] - 1)
222
+
223
+ out = ndimage.geometric_transform(data, mapping, data.shape,
224
+ order=order)
225
+ expected = xp.asarray([[0, 4, 1, 3],
226
+ [0, 7, 6, 8],
227
+ [0, 3, 5, 3]], dtype=out.dtype)
228
+ assert_array_almost_equal(out, expected)
229
+
230
+ def test_geometric_transform07(self, order, xp):
231
+ data = xp.asarray([[4, 1, 3, 2],
232
+ [7, 6, 8, 5],
233
+ [3, 5, 3, 6]])
234
+
235
+ def mapping(x):
236
+ return (x[0] - 1, x[1])
237
+
238
+ out = ndimage.geometric_transform(data, mapping, data.shape,
239
+ order=order)
240
+ expected = xp.asarray([[0, 0, 0, 0],
241
+ [4, 1, 3, 2],
242
+ [7, 6, 8, 5]], dtype=out.dtype)
243
+ assert_array_almost_equal(out, expected)
244
+
245
+ def test_geometric_transform08(self, order, xp):
246
+ data = xp.asarray([[4, 1, 3, 2],
247
+ [7, 6, 8, 5],
248
+ [3, 5, 3, 6]])
249
+
250
+ def mapping(x):
251
+ return (x[0] - 1, x[1] - 1)
252
+
253
+ out = ndimage.geometric_transform(data, mapping, data.shape,
254
+ order=order)
255
+ expected = xp.asarray([[0, 0, 0, 0],
256
+ [0, 4, 1, 3],
257
+ [0, 7, 6, 8]], dtype=out.dtype)
258
+ assert_array_almost_equal(out, expected)
259
+
260
+ def test_geometric_transform10(self, order, xp):
261
+ data = xp.asarray([[4, 1, 3, 2],
262
+ [7, 6, 8, 5],
263
+ [3, 5, 3, 6]])
264
+
265
+ def mapping(x):
266
+ return (x[0] - 1, x[1] - 1)
267
+
268
+ if (order > 1):
269
+ filtered = ndimage.spline_filter(data, order=order)
270
+ else:
271
+ filtered = data
272
+ out = ndimage.geometric_transform(filtered, mapping, data.shape,
273
+ order=order, prefilter=False)
274
+ expected = xp.asarray([[0, 0, 0, 0],
275
+ [0, 4, 1, 3],
276
+ [0, 7, 6, 8]], dtype=out.dtype)
277
+ assert_array_almost_equal(out, expected)
278
+
279
+ def test_geometric_transform13(self, order, xp):
280
+ data = xp.ones([2], dtype=xp.float64)
281
+
282
+ def mapping(x):
283
+ return (x[0] // 2,)
284
+
285
+ out = ndimage.geometric_transform(data, mapping, [4], order=order)
286
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1], dtype=out.dtype))
287
+
288
+ def test_geometric_transform14(self, order, xp):
289
+ data = xp.asarray([1, 5, 2, 6, 3, 7, 4, 4])
290
+
291
+ def mapping(x):
292
+ return (2 * x[0],)
293
+
294
+ out = ndimage.geometric_transform(data, mapping, [4], order=order)
295
+ assert_array_almost_equal(out, xp.asarray([1, 2, 3, 4], dtype=out.dtype))
296
+
297
+ def test_geometric_transform15(self, order, xp):
298
+ data = xp.asarray([1, 2, 3, 4])
299
+
300
+ def mapping(x):
301
+ return (x[0] / 2,)
302
+
303
+ out = ndimage.geometric_transform(data, mapping, [8], order=order)
304
+ assert_array_almost_equal(out[::2], xp.asarray([1, 2, 3, 4]))
305
+
306
+ def test_geometric_transform16(self, order, xp):
307
+ data = [[1, 2, 3, 4],
308
+ [5, 6, 7, 8],
309
+ [9.0, 10, 11, 12]]
310
+ data = xp.asarray(data)
311
+
312
+ def mapping(x):
313
+ return (x[0], x[1] * 2)
314
+
315
+ out = ndimage.geometric_transform(data, mapping, (3, 2),
316
+ order=order)
317
+ assert_array_almost_equal(out, xp.asarray([[1, 3], [5, 7], [9, 11]]))
318
+
319
+ def test_geometric_transform17(self, order, xp):
320
+ data = [[1, 2, 3, 4],
321
+ [5, 6, 7, 8],
322
+ [9, 10, 11, 12]]
323
+ data = xp.asarray(data)
324
+
325
+ def mapping(x):
326
+ return (x[0] * 2, x[1])
327
+
328
+ out = ndimage.geometric_transform(data, mapping, (1, 4),
329
+ order=order)
330
+ assert_array_almost_equal(out, xp.asarray([[1, 2, 3, 4]]))
331
+
332
+ def test_geometric_transform18(self, order, xp):
333
+ data = [[1, 2, 3, 4],
334
+ [5, 6, 7, 8],
335
+ [9, 10, 11, 12]]
336
+ data = xp.asarray(data)
337
+
338
+ def mapping(x):
339
+ return (x[0] * 2, x[1] * 2)
340
+
341
+ out = ndimage.geometric_transform(data, mapping, (1, 2),
342
+ order=order)
343
+ assert_array_almost_equal(out, xp.asarray([[1, 3]]))
344
+
345
+ def test_geometric_transform19(self, order, xp):
346
+ data = [[1, 2, 3, 4],
347
+ [5, 6, 7, 8],
348
+ [9, 10, 11, 12]]
349
+ data = xp.asarray(data)
350
+
351
+ def mapping(x):
352
+ return (x[0], x[1] / 2)
353
+
354
+ out = ndimage.geometric_transform(data, mapping, (3, 8),
355
+ order=order)
356
+ assert_array_almost_equal(out[..., ::2], data)
357
+
358
+ def test_geometric_transform20(self, order, xp):
359
+ data = [[1, 2, 3, 4],
360
+ [5, 6, 7, 8],
361
+ [9, 10, 11, 12]]
362
+ data = xp.asarray(data)
363
+
364
+ def mapping(x):
365
+ return (x[0] / 2, x[1])
366
+
367
+ out = ndimage.geometric_transform(data, mapping, (6, 4),
368
+ order=order)
369
+ assert_array_almost_equal(out[::2, ...], data)
370
+
371
+ def test_geometric_transform21(self, order, xp):
372
+ data = [[1, 2, 3, 4],
373
+ [5, 6, 7, 8],
374
+ [9, 10, 11, 12]]
375
+ data = xp.asarray(data)
376
+
377
+ def mapping(x):
378
+ return (x[0] / 2, x[1] / 2)
379
+
380
+ out = ndimage.geometric_transform(data, mapping, (6, 8),
381
+ order=order)
382
+ assert_array_almost_equal(out[::2, ::2], data)
383
+
384
+ def test_geometric_transform22(self, order, xp):
385
+ data = [[1, 2, 3, 4],
386
+ [5, 6, 7, 8],
387
+ [9, 10, 11, 12]]
388
+ data = xp.asarray(data, dtype=xp.float64)
389
+
390
+ def mapping1(x):
391
+ return (x[0] / 2, x[1] / 2)
392
+
393
+ def mapping2(x):
394
+ return (x[0] * 2, x[1] * 2)
395
+
396
+ out = ndimage.geometric_transform(data, mapping1,
397
+ (6, 8), order=order)
398
+ out = ndimage.geometric_transform(out, mapping2,
399
+ (3, 4), order=order)
400
+ assert_array_almost_equal(out, data)
401
+
402
+ def test_geometric_transform23(self, order, xp):
403
+ data = [[1, 2, 3, 4],
404
+ [5, 6, 7, 8],
405
+ [9, 10, 11, 12]]
406
+ data = xp.asarray(data)
407
+
408
+ def mapping(x):
409
+ return (1, x[0] * 2)
410
+
411
+ out = ndimage.geometric_transform(data, mapping, (2,), order=order)
412
+ assert_array_almost_equal(out, xp.asarray([5, 7]))
413
+
414
+ def test_geometric_transform24(self, order, xp):
415
+ data = [[1, 2, 3, 4],
416
+ [5, 6, 7, 8],
417
+ [9, 10, 11, 12]]
418
+ data = xp.asarray(data)
419
+
420
+ def mapping(x, a, b):
421
+ return (a, x[0] * b)
422
+
423
+ out = ndimage.geometric_transform(
424
+ data, mapping, (2,), order=order, extra_arguments=(1,),
425
+ extra_keywords={'b': 2})
426
+ assert_array_almost_equal(out, xp.asarray([5, 7]))
427
+
428
+
429
+ @make_xp_test_case(ndimage.geometric_transform)
430
+ class TestGeometricTransformExtra:
431
+
432
+ def test_geometric_transform_grid_constant_order1(self, xp):
433
+
434
+ # verify interpolation outside the original bounds
435
+ x = xp.asarray([[1, 2, 3],
436
+ [4, 5, 6]], dtype=xp.float64)
437
+
438
+ def mapping(x):
439
+ return (x[0] - 0.5), (x[1] - 0.5)
440
+
441
+ expected_result = xp.asarray([[0.25, 0.75, 1.25],
442
+ [1.25, 3.00, 4.00]])
443
+ assert_array_almost_equal(
444
+ ndimage.geometric_transform(x, mapping, mode='grid-constant',
445
+ order=1),
446
+ expected_result,
447
+ )
448
+
449
+ @pytest.mark.parametrize('mode', ['grid-constant', 'grid-wrap', 'nearest',
450
+ 'mirror', 'reflect'])
451
+ @pytest.mark.parametrize('order', range(6))
452
+ def test_geometric_transform_vs_padded(self, order, mode, xp):
453
+
454
+ def mapping(x):
455
+ return (x[0] - 0.4), (x[1] + 2.3)
456
+
457
+ # Manually pad and then extract center after the transform to get the
458
+ # expected result.
459
+ x = np.arange(144, dtype=float).reshape(12, 12)
460
+ npad = 24
461
+ pad_mode = ndimage_to_numpy_mode.get(mode)
462
+ x_padded = np.pad(x, npad, mode=pad_mode)
463
+
464
+ x = xp.asarray(x)
465
+ x_padded = xp.asarray(x_padded)
466
+
467
+ center_slice = tuple([slice(npad, -npad)] * x.ndim)
468
+ expected_result = ndimage.geometric_transform(
469
+ x_padded, mapping, mode=mode, order=order)[center_slice]
470
+
471
+ xp_assert_close(
472
+ ndimage.geometric_transform(x, mapping, mode=mode,
473
+ order=order),
474
+ expected_result,
475
+ rtol=1e-7,
476
+ )
477
+
478
+ @skip_xp_backends(np_only=True, reason='endianness is numpy-specific')
479
+ def test_geometric_transform_endianness_with_output_parameter(self, xp):
480
+ # geometric transform given output ndarray or dtype with
481
+ # non-native endianness. see issue #4127
482
+ data = np.asarray([1])
483
+
484
+ def mapping(x):
485
+ return x
486
+
487
+ for out in [data.dtype, data.dtype.newbyteorder(),
488
+ np.empty_like(data),
489
+ np.empty_like(data).astype(data.dtype.newbyteorder())]:
490
+ returned = ndimage.geometric_transform(data, mapping, data.shape,
491
+ output=out)
492
+ result = out if returned is None else returned
493
+ assert_array_almost_equal(result, [1])
494
+
495
+ @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific')
496
+ def test_geometric_transform_with_string_output(self, xp):
497
+ data = xp.asarray([1])
498
+
499
+ def mapping(x):
500
+ return x
501
+
502
+ out = ndimage.geometric_transform(data, mapping, output='f')
503
+ assert out.dtype is np.dtype('f')
504
+ assert_array_almost_equal(out, [1])
505
+
506
+
507
+ @make_xp_test_case(ndimage.map_coordinates)
508
+ class TestMapCoordinates:
509
+
510
+ @pytest.mark.parametrize('order', range(0, 6))
511
+ @pytest.mark.parametrize('dtype', [np.float64, np.complex128])
512
+ def test_map_coordinates01(self, order, dtype, xp):
513
+ if is_jax(xp) and order > 1:
514
+ pytest.xfail("jax map_coordinates requires order <= 1")
515
+
516
+ data = xp.asarray([[4, 1, 3, 2],
517
+ [7, 6, 8, 5],
518
+ [3, 5, 3, 6]])
519
+ expected = xp.asarray([[0, 0, 0, 0],
520
+ [0, 4, 1, 3],
521
+ [0, 7, 6, 8]])
522
+ if xp.isdtype(data.dtype, 'complex floating'):
523
+ data = data - 1j * data
524
+ expected = expected - 1j * expected
525
+
526
+ idx = np.indices(data.shape)
527
+ idx -= 1
528
+ idx = xp.asarray(idx)
529
+
530
+ out = ndimage.map_coordinates(data, idx, order=order)
531
+ assert_array_almost_equal(out, expected)
532
+
533
+ @pytest.mark.parametrize('order', range(0, 6))
534
+ def test_map_coordinates02(self, order, xp):
535
+ if is_jax(xp):
536
+ if order > 1:
537
+ pytest.xfail("jax map_coordinates requires order <= 1")
538
+ if order == 1:
539
+ pytest.xfail("output differs. jax bug?")
540
+
541
+ data = xp.asarray([[4, 1, 3, 2],
542
+ [7, 6, 8, 5],
543
+ [3, 5, 3, 6]])
544
+ idx = np.indices(data.shape, np.float64)
545
+ idx -= 0.5
546
+ idx = xp.asarray(idx)
547
+
548
+ out1 = ndimage.shift(data, 0.5, order=order)
549
+ out2 = ndimage.map_coordinates(data, idx, order=order)
550
+ assert_array_almost_equal(out1, out2)
551
+
552
+ @skip_xp_backends("jax.numpy", reason="`order` is required in jax")
553
+ def test_map_coordinates03(self, xp):
554
+ data = _asarray([[4, 1, 3, 2],
555
+ [7, 6, 8, 5],
556
+ [3, 5, 3, 6]], order='F', xp=xp)
557
+ idx = np.indices(data.shape) - 1
558
+ idx = xp.asarray(idx)
559
+ out = ndimage.map_coordinates(data, idx)
560
+ expected = xp.asarray([[0, 0, 0, 0],
561
+ [0, 4, 1, 3],
562
+ [0, 7, 6, 8]])
563
+ assert_array_almost_equal(out, expected)
564
+ assert_array_almost_equal(out, ndimage.shift(data, (1, 1)))
565
+
566
+ idx = np.indices(data[::2, ...].shape) - 1
567
+ idx = xp.asarray(idx)
568
+ out = ndimage.map_coordinates(data[::2, ...], idx)
569
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
570
+ [0, 4, 1, 3]]))
571
+ assert_array_almost_equal(out, ndimage.shift(data[::2, ...], (1, 1)))
572
+
573
+ idx = np.indices(data[:, ::2].shape) - 1
574
+ idx = xp.asarray(idx)
575
+ out = ndimage.map_coordinates(data[:, ::2], idx)
576
+ assert_array_almost_equal(out, xp.asarray([[0, 0], [0, 4], [0, 7]]))
577
+ assert_array_almost_equal(out, ndimage.shift(data[:, ::2], (1, 1)))
578
+
579
+ @skip_xp_backends(np_only=True)
580
+ def test_map_coordinates_endianness_with_output_parameter(self, xp):
581
+ # output parameter given as array or dtype with either endianness
582
+ # see issue #4127
583
+ # NB: NumPy-only
584
+
585
+ data = np.asarray([[1, 2], [7, 6]])
586
+ expected = np.asarray([[0, 0], [0, 1]])
587
+ idx = np.indices(data.shape)
588
+ idx -= 1
589
+ for out in [
590
+ data.dtype,
591
+ data.dtype.newbyteorder(),
592
+ np.empty_like(expected),
593
+ np.empty_like(expected).astype(expected.dtype.newbyteorder())
594
+ ]:
595
+ returned = ndimage.map_coordinates(data, idx, output=out)
596
+ result = out if returned is None else returned
597
+ assert_array_almost_equal(result, expected)
598
+
599
+ @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific')
600
+ def test_map_coordinates_with_string_output(self, xp):
601
+ data = xp.asarray([[1]])
602
+ idx = np.indices(data.shape)
603
+ idx = xp.asarray(idx)
604
+ out = ndimage.map_coordinates(data, idx, output='f')
605
+ assert out.dtype is np.dtype('f')
606
+ assert_array_almost_equal(out, xp.asarray([[1]]))
607
+
608
+ @pytest.mark.skip_xp_backends(cpu_only=True)
609
+ @pytest.mark.skipif('win32' in sys.platform or np.intp(0).itemsize < 8,
610
+ reason='do not run on 32 bit or windows '
611
+ '(no sparse memory)')
612
+ def test_map_coordinates_large_data(self, xp):
613
+ # check crash on large data
614
+ try:
615
+ n = 30000
616
+ # a = xp.reshape(xp.empty(n**2, dtype=xp.float32), (n, n))
617
+ a = np.empty(n**2, dtype=np.float32).reshape(n, n)
618
+ # fill the part we might read
619
+ a[n - 3:, n - 3:] = 0
620
+ ndimage.map_coordinates(
621
+ xp.asarray(a), xp.asarray([[n - 1.5], [n - 1.5]]), order=1
622
+ )
623
+ except MemoryError as e:
624
+ raise pytest.skip('Not enough memory available') from e
625
+
626
+
627
+ @make_xp_test_case(ndimage.affine_transform)
628
+ class TestAffineTransform:
629
+
630
+ @pytest.mark.parametrize('order', range(0, 6))
631
+ def test_affine_transform01(self, order, xp):
632
+ data = xp.asarray([1])
633
+ out = ndimage.affine_transform(data, xp.asarray([[1]]), order=order)
634
+ assert_array_almost_equal(out, xp.asarray([1]))
635
+
636
+ @pytest.mark.parametrize('order', range(0, 6))
637
+ def test_affine_transform02(self, order, xp):
638
+ data = xp.ones([4])
639
+ out = ndimage.affine_transform(data, xp.asarray([[1]]), order=order)
640
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1]))
641
+
642
+ @pytest.mark.parametrize('order', range(0, 6))
643
+ def test_affine_transform03(self, order, xp):
644
+ data = xp.ones([4])
645
+ out = ndimage.affine_transform(data, xp.asarray([[1]]), -1, order=order)
646
+ assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1]))
647
+
648
+ @pytest.mark.parametrize('order', range(0, 6))
649
+ def test_affine_transform04(self, order, xp):
650
+ data = xp.asarray([4, 1, 3, 2])
651
+ out = ndimage.affine_transform(data, xp.asarray([[1]]), -1, order=order)
652
+ assert_array_almost_equal(out, xp.asarray([0, 4, 1, 3]))
653
+
654
+ @pytest.mark.parametrize('order', range(0, 6))
655
+ @pytest.mark.parametrize('dtype', ["float64", "complex128"])
656
+ def test_affine_transform05(self, order, dtype, xp):
657
+ dtype = getattr(xp, dtype)
658
+ data = xp.asarray([[1, 1, 1, 1],
659
+ [1, 1, 1, 1],
660
+ [1, 1, 1, 1]], dtype=dtype)
661
+ expected = xp.asarray([[0, 1, 1, 1],
662
+ [0, 1, 1, 1],
663
+ [0, 1, 1, 1]], dtype=dtype)
664
+ if xp.isdtype(data.dtype, 'complex floating'):
665
+ data -= 1j * data
666
+ expected -= 1j * expected
667
+ out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]),
668
+ [0, -1], order=order)
669
+ assert_array_almost_equal(out, expected)
670
+
671
+ @pytest.mark.parametrize('order', range(0, 6))
672
+ def test_affine_transform06(self, order, xp):
673
+ data = xp.asarray([[4, 1, 3, 2],
674
+ [7, 6, 8, 5],
675
+ [3, 5, 3, 6]])
676
+ out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]),
677
+ [0, -1], order=order)
678
+ assert_array_almost_equal(out, xp.asarray([[0, 4, 1, 3],
679
+ [0, 7, 6, 8],
680
+ [0, 3, 5, 3]]))
681
+
682
+ @pytest.mark.parametrize('order', range(0, 6))
683
+ def test_affine_transform07(self, order, xp):
684
+ data = xp.asarray([[4, 1, 3, 2],
685
+ [7, 6, 8, 5],
686
+ [3, 5, 3, 6]])
687
+ out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]),
688
+ [-1, 0], order=order)
689
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
690
+ [4, 1, 3, 2],
691
+ [7, 6, 8, 5]]))
692
+
693
+ @pytest.mark.parametrize('order', range(0, 6))
694
+ def test_affine_transform08(self, order, xp):
695
+ data = xp.asarray([[4, 1, 3, 2],
696
+ [7, 6, 8, 5],
697
+ [3, 5, 3, 6]])
698
+ out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]),
699
+ [-1, -1], order=order)
700
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
701
+ [0, 4, 1, 3],
702
+ [0, 7, 6, 8]]))
703
+
704
+ @pytest.mark.parametrize('order', range(0, 6))
705
+ def test_affine_transform09(self, order, xp):
706
+ data = xp.asarray([[4, 1, 3, 2],
707
+ [7, 6, 8, 5],
708
+ [3, 5, 3, 6]])
709
+ if (order > 1):
710
+ filtered = ndimage.spline_filter(data, order=order)
711
+ else:
712
+ filtered = data
713
+ out = ndimage.affine_transform(filtered, xp.asarray([[1, 0], [0, 1]]),
714
+ [-1, -1], order=order,
715
+ prefilter=False)
716
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
717
+ [0, 4, 1, 3],
718
+ [0, 7, 6, 8]]))
719
+
720
+ @pytest.mark.parametrize('order', range(0, 6))
721
+ def test_affine_transform10(self, order, xp):
722
+ data = xp.ones([2], dtype=xp.float64)
723
+ out = ndimage.affine_transform(data, xp.asarray([[0.5]]), output_shape=(4,),
724
+ order=order)
725
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 0]))
726
+
727
+ @pytest.mark.parametrize('order', range(0, 6))
728
+ def test_affine_transform11(self, order, xp):
729
+ data = xp.asarray([1, 5, 2, 6, 3, 7, 4, 4])
730
+ out = ndimage.affine_transform(data, xp.asarray([[2]]), 0, (4,), order=order)
731
+ assert_array_almost_equal(out, xp.asarray([1, 2, 3, 4]))
732
+
733
+ @pytest.mark.parametrize('order', range(0, 6))
734
+ def test_affine_transform12(self, order, xp):
735
+ data = xp.asarray([1, 2, 3, 4])
736
+ out = ndimage.affine_transform(data, xp.asarray([[0.5]]), 0, (8,), order=order)
737
+ assert_array_almost_equal(out[::2], xp.asarray([1, 2, 3, 4]))
738
+
739
+ @pytest.mark.parametrize('order', range(0, 6))
740
+ def test_affine_transform13(self, order, xp):
741
+ data = [[1, 2, 3, 4],
742
+ [5, 6, 7, 8],
743
+ [9.0, 10, 11, 12]]
744
+ data = xp.asarray(data)
745
+ out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 2]]), 0, (3, 2),
746
+ order=order)
747
+ assert_array_almost_equal(out, xp.asarray([[1, 3], [5, 7], [9, 11]]))
748
+
749
+ @pytest.mark.parametrize('order', range(0, 6))
750
+ def test_affine_transform14(self, order, xp):
751
+ data = [[1, 2, 3, 4],
752
+ [5, 6, 7, 8],
753
+ [9, 10, 11, 12]]
754
+ data = xp.asarray(data)
755
+ out = ndimage.affine_transform(data, xp.asarray([[2, 0], [0, 1]]), 0, (1, 4),
756
+ order=order)
757
+ assert_array_almost_equal(out, xp.asarray([[1, 2, 3, 4]]))
758
+
759
+ @pytest.mark.parametrize('order', range(0, 6))
760
+ def test_affine_transform15(self, order, xp):
761
+ data = [[1, 2, 3, 4],
762
+ [5, 6, 7, 8],
763
+ [9, 10, 11, 12]]
764
+ data = xp.asarray(data)
765
+ out = ndimage.affine_transform(data, xp.asarray([[2, 0], [0, 2]]), 0, (1, 2),
766
+ order=order)
767
+ assert_array_almost_equal(out, xp.asarray([[1, 3]]))
768
+
769
+ @pytest.mark.parametrize('order', range(0, 6))
770
+ def test_affine_transform16(self, order, xp):
771
+ data = [[1, 2, 3, 4],
772
+ [5, 6, 7, 8],
773
+ [9, 10, 11, 12]]
774
+ data = xp.asarray(data)
775
+ out = ndimage.affine_transform(data, xp.asarray([[1, 0.0], [0, 0.5]]), 0,
776
+ (3, 8), order=order)
777
+ assert_array_almost_equal(out[..., ::2], data)
778
+
779
+ @pytest.mark.parametrize('order', range(0, 6))
780
+ def test_affine_transform17(self, order, xp):
781
+ data = [[1, 2, 3, 4],
782
+ [5, 6, 7, 8],
783
+ [9, 10, 11, 12]]
784
+ data = xp.asarray(data)
785
+ out = ndimage.affine_transform(data, xp.asarray([[0.5, 0], [0, 1]]), 0,
786
+ (6, 4), order=order)
787
+ assert_array_almost_equal(out[::2, ...], data)
788
+
789
+ @pytest.mark.parametrize('order', range(0, 6))
790
+ def test_affine_transform18(self, order, xp):
791
+ data = xp.asarray([[1, 2, 3, 4],
792
+ [5, 6, 7, 8],
793
+ [9, 10, 11, 12]])
794
+ out = ndimage.affine_transform(data, xp.asarray([[0.5, 0], [0, 0.5]]), 0,
795
+ (6, 8), order=order)
796
+ assert_array_almost_equal(out[::2, ::2], data)
797
+
798
+ @pytest.mark.parametrize('order', range(0, 6))
799
+ def test_affine_transform19(self, order, xp):
800
+ data = xp.asarray([[1, 2, 3, 4],
801
+ [5, 6, 7, 8],
802
+ [9, 10, 11, 12]], dtype=xp.float64)
803
+ out = ndimage.affine_transform(data, xp.asarray([[0.5, 0], [0, 0.5]]), 0,
804
+ (6, 8), order=order)
805
+ out = ndimage.affine_transform(out, xp.asarray([[2.0, 0], [0, 2.0]]), 0,
806
+ (3, 4), order=order)
807
+ assert_array_almost_equal(out, data)
808
+
809
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8394")
810
+ @pytest.mark.parametrize('order', range(0, 6))
811
+ def test_affine_transform20(self, order, xp):
812
+ data = [[1, 2, 3, 4],
813
+ [5, 6, 7, 8],
814
+ [9, 10, 11, 12]]
815
+ data = xp.asarray(data)
816
+ out = ndimage.affine_transform(data, xp.asarray([[0], [2]]), 0, (2,),
817
+ order=order)
818
+ assert_array_almost_equal(out, xp.asarray([1, 3]))
819
+
820
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8394")
821
+ @pytest.mark.parametrize('order', range(0, 6))
822
+ def test_affine_transform21(self, order, xp):
823
+ data = [[1, 2, 3, 4],
824
+ [5, 6, 7, 8],
825
+ [9, 10, 11, 12]]
826
+ data = xp.asarray(data)
827
+ out = ndimage.affine_transform(data, xp.asarray([[2], [0]]), 0, (2,),
828
+ order=order)
829
+ assert_array_almost_equal(out, xp.asarray([1, 9]))
830
+
831
+ @pytest.mark.parametrize('order', range(0, 6))
832
+ def test_affine_transform22(self, order, xp):
833
+ # shift and offset interaction; see issue #1547
834
+ data = xp.asarray([4, 1, 3, 2])
835
+ out = ndimage.affine_transform(data, xp.asarray([[2]]), [-1], (3,),
836
+ order=order)
837
+ assert_array_almost_equal(out, xp.asarray([0, 1, 2]))
838
+
839
+ @pytest.mark.parametrize('order', range(0, 6))
840
+ def test_affine_transform23(self, order, xp):
841
+ # shift and offset interaction; see issue #1547
842
+ data = xp.asarray([4, 1, 3, 2])
843
+ out = ndimage.affine_transform(data, xp.asarray([[0.5]]), [-1], (8,),
844
+ order=order)
845
+ assert_array_almost_equal(out[::2], xp.asarray([0, 4, 1, 3]))
846
+
847
+ @pytest.mark.parametrize('order', range(0, 6))
848
+ def test_affine_transform24(self, order, xp):
849
+ # consistency between diagonal and non-diagonal case; see issue #1547
850
+ data = xp.asarray([4, 1, 3, 2])
851
+ with warnings.catch_warnings():
852
+ warnings.filterwarnings(
853
+ "ignore",
854
+ 'The behavior of affine_transform with a 1-D array .* has changed',
855
+ UserWarning)
856
+ out1 = ndimage.affine_transform(data, xp.asarray([2]), -1, order=order)
857
+ out2 = ndimage.affine_transform(data, xp.asarray([[2]]), -1, order=order)
858
+ assert_array_almost_equal(out1, out2)
859
+
860
+ @pytest.mark.parametrize('order', range(0, 6))
861
+ def test_affine_transform25(self, order, xp):
862
+ # consistency between diagonal and non-diagonal case; see issue #1547
863
+ data = xp.asarray([4, 1, 3, 2])
864
+ with warnings.catch_warnings():
865
+ warnings.filterwarnings("ignore",
866
+ 'The behavior of affine_transform with a 1-D array .* '
867
+ 'has changed', UserWarning)
868
+ out1 = ndimage.affine_transform(data, xp.asarray([0.5]), -1, order=order)
869
+ out2 = ndimage.affine_transform(data, xp.asarray([[0.5]]), -1, order=order)
870
+ assert_array_almost_equal(out1, out2)
871
+
872
+ @pytest.mark.parametrize('order', range(0, 6))
873
+ def test_affine_transform26(self, order, xp):
874
+ # test homogeneous coordinates
875
+ data = xp.asarray([[4, 1, 3, 2],
876
+ [7, 6, 8, 5],
877
+ [3, 5, 3, 6]])
878
+ if (order > 1):
879
+ filtered = ndimage.spline_filter(data, order=order)
880
+ else:
881
+ filtered = data
882
+ tform_original = xp.eye(2)
883
+ offset_original = -xp.ones((2, 1))
884
+
885
+ tform_h1 = xp.concat((tform_original, offset_original), axis=1) # hstack
886
+ tform_h2 = xp.concat((tform_h1, xp.asarray([[0.0, 0, 1]])), axis=0) # vstack
887
+
888
+ offs = [float(x) for x in xp.reshape(offset_original, (-1,))]
889
+
890
+ out1 = ndimage.affine_transform(filtered, tform_original,
891
+ offs,
892
+ order=order, prefilter=False)
893
+ out2 = ndimage.affine_transform(filtered, tform_h1, order=order,
894
+ prefilter=False)
895
+ out3 = ndimage.affine_transform(filtered, tform_h2, order=order,
896
+ prefilter=False)
897
+ for out in [out1, out2, out3]:
898
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
899
+ [0, 4, 1, 3],
900
+ [0, 7, 6, 8]]))
901
+
902
+ @xfail_xp_backends("cupy", reason="does not raise")
903
+ def test_affine_transform27(self, xp):
904
+ # test valid homogeneous transformation matrix
905
+ data = xp.asarray([[4, 1, 3, 2],
906
+ [7, 6, 8, 5],
907
+ [3, 5, 3, 6]])
908
+ tform_h1 = xp.concat((xp.eye(2), -xp.ones((2, 1))) , axis=1) # vstack
909
+ tform_h2 = xp.concat((tform_h1, xp.asarray([[5.0, 2, 1]])), axis=0) # hstack
910
+
911
+ assert_raises(ValueError, ndimage.affine_transform, data, tform_h2)
912
+
913
+ @skip_xp_backends(np_only=True, reason='byteorder is numpy-specific')
914
+ def test_affine_transform_1d_endianness_with_output_parameter(self, xp):
915
+ # 1d affine transform given output ndarray or dtype with
916
+ # either endianness. see issue #7388
917
+ data = xp.ones((2, 2))
918
+ for out in [xp.empty_like(data),
919
+ xp.empty_like(data).astype(data.dtype.newbyteorder()),
920
+ data.dtype, data.dtype.newbyteorder()]:
921
+ with warnings.catch_warnings():
922
+ warnings.filterwarnings("ignore",
923
+ 'The behavior of affine_transform with a 1-D array '
924
+ '.* has changed', UserWarning)
925
+ matrix = xp.asarray([1, 1])
926
+ returned = ndimage.affine_transform(data, matrix, output=out)
927
+ result = out if returned is None else returned
928
+ assert_array_almost_equal(result, xp.asarray([[1, 1], [1, 1]]))
929
+
930
+ @skip_xp_backends(np_only=True, reason='byteorder is numpy-specific')
931
+ def test_affine_transform_multi_d_endianness_with_output_parameter(self, xp):
932
+ # affine transform given output ndarray or dtype with either endianness
933
+ # see issue #4127
934
+ # NB: byteorder is numpy-specific
935
+ data = np.asarray([1])
936
+ for out in [data.dtype, data.dtype.newbyteorder(),
937
+ np.empty_like(data),
938
+ np.empty_like(data).astype(data.dtype.newbyteorder())]:
939
+ returned = ndimage.affine_transform(data, np.asarray([[1]]), output=out)
940
+ result = out if returned is None else returned
941
+ assert_array_almost_equal(result, np.asarray([1]))
942
+
943
+ @skip_xp_backends(np_only=True,
944
+ reason='`out` of a different size is numpy-specific'
945
+ )
946
+ def test_affine_transform_output_shape(self, xp):
947
+ # don't require output_shape when out of a different size is given
948
+ data = xp.arange(8, dtype=xp.float64)
949
+ out = xp.ones((16,))
950
+
951
+ ndimage.affine_transform(data, xp.asarray([[1]]), output=out)
952
+ assert_array_almost_equal(out[:8], data)
953
+
954
+ # mismatched output shape raises an error
955
+ with pytest.raises(RuntimeError):
956
+ ndimage.affine_transform(
957
+ data, [[1]], output=out, output_shape=(12,))
958
+
959
+ @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific')
960
+ def test_affine_transform_with_string_output(self, xp):
961
+ data = xp.asarray([1])
962
+ out = ndimage.affine_transform(data, xp.asarray([[1]]), output='f')
963
+ assert out.dtype is np.dtype('f')
964
+ assert_array_almost_equal(out, xp.asarray([1]))
965
+
966
+ @pytest.mark.parametrize('shift',
967
+ [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)])
968
+ @pytest.mark.parametrize('order', range(0, 6))
969
+ def test_affine_transform_shift_via_grid_wrap(self, shift, order, xp):
970
+ # For mode 'grid-wrap', integer shifts should match np.roll
971
+ x = np.asarray([[0, 1],
972
+ [2, 3]])
973
+ affine = np.zeros((2, 3))
974
+ affine[:2, :2] = np.eye(2)
975
+ affine[:, 2] = np.asarray(shift)
976
+
977
+ expected = np.roll(x, shift, axis=(0, 1))
978
+
979
+ x = xp.asarray(x)
980
+ affine = xp.asarray(affine)
981
+ expected = xp.asarray(expected)
982
+
983
+ assert_array_almost_equal(
984
+ ndimage.affine_transform(x, affine, mode='grid-wrap', order=order),
985
+ expected
986
+ )
987
+
988
+ @pytest.mark.parametrize('order', range(0, 6))
989
+ def test_affine_transform_shift_reflect(self, order, xp):
990
+ # shift by x.shape results in reflection
991
+ x = np.asarray([[0, 1, 2],
992
+ [3, 4, 5]])
993
+ expected = x[::-1, ::-1].copy() # strides >0 for torch
994
+ x = xp.asarray(x)
995
+ expected = xp.asarray(expected)
996
+
997
+ affine = np.zeros([2, 3])
998
+ affine[:2, :2] = np.eye(2)
999
+ affine[:, 2] = np.asarray(x.shape)
1000
+ affine = xp.asarray(affine)
1001
+
1002
+ assert_array_almost_equal(
1003
+ ndimage.affine_transform(x, affine, mode='reflect', order=order),
1004
+ expected,
1005
+ )
1006
+
1007
+
1008
+ @make_xp_test_case(ndimage.shift)
1009
+ class TestShift:
1010
+
1011
+ @pytest.mark.parametrize('order', range(0, 6))
1012
+ def test_shift01(self, order, xp):
1013
+ data = xp.asarray([1])
1014
+ out = ndimage.shift(data, [1], order=order)
1015
+ assert_array_almost_equal(out, xp.asarray([0]))
1016
+
1017
+ @pytest.mark.parametrize('order', range(0, 6))
1018
+ def test_shift02(self, order, xp):
1019
+ data = xp.ones([4])
1020
+ out = ndimage.shift(data, [1], order=order)
1021
+ assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1]))
1022
+
1023
+ @pytest.mark.parametrize('order', range(0, 6))
1024
+ def test_shift03(self, order, xp):
1025
+ data = xp.ones([4])
1026
+ out = ndimage.shift(data, -1, order=order)
1027
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 0]))
1028
+
1029
+ @pytest.mark.parametrize('order', range(0, 6))
1030
+ def test_shift04(self, order, xp):
1031
+ data = xp.asarray([4, 1, 3, 2])
1032
+ out = ndimage.shift(data, 1, order=order)
1033
+ assert_array_almost_equal(out, xp.asarray([0, 4, 1, 3]))
1034
+
1035
+ @pytest.mark.parametrize('order', range(0, 6))
1036
+ @pytest.mark.parametrize('dtype', ["float64", "complex128"])
1037
+ def test_shift05(self, order, dtype, xp):
1038
+ dtype = getattr(xp, dtype)
1039
+ data = xp.asarray([[1, 1, 1, 1],
1040
+ [1, 1, 1, 1],
1041
+ [1, 1, 1, 1]], dtype=dtype)
1042
+ expected = xp.asarray([[0, 1, 1, 1],
1043
+ [0, 1, 1, 1],
1044
+ [0, 1, 1, 1]], dtype=dtype)
1045
+ if xp.isdtype(data.dtype, 'complex floating'):
1046
+ data -= 1j * data
1047
+ expected -= 1j * expected
1048
+ out = ndimage.shift(data, [0, 1], order=order)
1049
+ assert_array_almost_equal(out, expected)
1050
+
1051
+ @pytest.mark.parametrize('order', range(0, 6))
1052
+ @pytest.mark.parametrize('mode', ['constant', 'grid-constant'])
1053
+ @pytest.mark.parametrize('dtype', ['float64', 'complex128'])
1054
+ def test_shift_with_nonzero_cval(self, order, mode, dtype, xp):
1055
+ data = np.asarray([[1, 1, 1, 1],
1056
+ [1, 1, 1, 1],
1057
+ [1, 1, 1, 1]], dtype=dtype)
1058
+
1059
+ expected = np.asarray([[0, 1, 1, 1],
1060
+ [0, 1, 1, 1],
1061
+ [0, 1, 1, 1]], dtype=dtype)
1062
+
1063
+ if np_compat.isdtype(data.dtype, 'complex floating'):
1064
+ data -= 1j * data
1065
+ expected -= 1j * expected
1066
+ cval = 5.0
1067
+ expected[:, 0] = cval # specific to shift of [0, 1] used below
1068
+
1069
+ data = xp.asarray(data)
1070
+ expected = xp.asarray(expected)
1071
+ out = ndimage.shift(data, [0, 1], order=order, mode=mode, cval=cval)
1072
+ assert_array_almost_equal(out, expected)
1073
+
1074
+ @pytest.mark.parametrize('order', range(0, 6))
1075
+ def test_shift06(self, order, xp):
1076
+ data = xp.asarray([[4, 1, 3, 2],
1077
+ [7, 6, 8, 5],
1078
+ [3, 5, 3, 6]])
1079
+ out = ndimage.shift(data, [0, 1], order=order)
1080
+ assert_array_almost_equal(out, xp.asarray([[0, 4, 1, 3],
1081
+ [0, 7, 6, 8],
1082
+ [0, 3, 5, 3]]))
1083
+
1084
+ @pytest.mark.parametrize('order', range(0, 6))
1085
+ def test_shift07(self, order, xp):
1086
+ data = xp.asarray([[4, 1, 3, 2],
1087
+ [7, 6, 8, 5],
1088
+ [3, 5, 3, 6]])
1089
+ out = ndimage.shift(data, [1, 0], order=order)
1090
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
1091
+ [4, 1, 3, 2],
1092
+ [7, 6, 8, 5]]))
1093
+
1094
+ @pytest.mark.parametrize('order', range(0, 6))
1095
+ def test_shift08(self, order, xp):
1096
+ data = xp.asarray([[4, 1, 3, 2],
1097
+ [7, 6, 8, 5],
1098
+ [3, 5, 3, 6]])
1099
+ out = ndimage.shift(data, [1, 1], order=order)
1100
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
1101
+ [0, 4, 1, 3],
1102
+ [0, 7, 6, 8]]))
1103
+
1104
+ @pytest.mark.parametrize('order', range(0, 6))
1105
+ def test_shift09(self, order, xp):
1106
+ data = xp.asarray([[4, 1, 3, 2],
1107
+ [7, 6, 8, 5],
1108
+ [3, 5, 3, 6]])
1109
+ if (order > 1):
1110
+ filtered = ndimage.spline_filter(data, order=order)
1111
+ else:
1112
+ filtered = data
1113
+ out = ndimage.shift(filtered, [1, 1], order=order, prefilter=False)
1114
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
1115
+ [0, 4, 1, 3],
1116
+ [0, 7, 6, 8]]))
1117
+
1118
+ @pytest.mark.parametrize('shift',
1119
+ [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)])
1120
+ @pytest.mark.parametrize('order', range(0, 6))
1121
+ def test_shift_grid_wrap(self, shift, order, xp):
1122
+ # For mode 'grid-wrap', integer shifts should match np.roll
1123
+ x = np.asarray([[0, 1],
1124
+ [2, 3]])
1125
+ expected = np.roll(x, shift, axis=(0,1))
1126
+
1127
+ x = xp.asarray(x)
1128
+ expected = xp.asarray(expected)
1129
+
1130
+ assert_array_almost_equal(
1131
+ ndimage.shift(x, shift, mode='grid-wrap', order=order),
1132
+ expected
1133
+ )
1134
+
1135
+ @pytest.mark.parametrize('shift',
1136
+ [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)])
1137
+ @pytest.mark.parametrize('order', range(0, 6))
1138
+ def test_shift_grid_constant1(self, shift, order, xp):
1139
+ # For integer shifts, 'constant' and 'grid-constant' should be equal
1140
+ x = xp.reshape(xp.arange(20), (5, 4))
1141
+ assert_array_almost_equal(
1142
+ ndimage.shift(x, shift, mode='grid-constant', order=order),
1143
+ ndimage.shift(x, shift, mode='constant', order=order),
1144
+ )
1145
+
1146
+ def test_shift_grid_constant_order1(self, xp):
1147
+ x = xp.asarray([[1, 2, 3],
1148
+ [4, 5, 6]], dtype=xp.float64)
1149
+ expected_result = xp.asarray([[0.25, 0.75, 1.25],
1150
+ [1.25, 3.00, 4.00]])
1151
+ assert_array_almost_equal(
1152
+ ndimage.shift(x, (0.5, 0.5), mode='grid-constant', order=1),
1153
+ expected_result,
1154
+ )
1155
+
1156
+ @pytest.mark.parametrize('order', range(0, 6))
1157
+ def test_shift_reflect(self, order, xp):
1158
+ # shift by x.shape results in reflection
1159
+ x = np.asarray([[0, 1, 2],
1160
+ [3, 4, 5]])
1161
+ expected = x[::-1, ::-1].copy() # strides > 0 for torch
1162
+
1163
+ x = xp.asarray(x)
1164
+ expected = xp.asarray(expected)
1165
+ assert_array_almost_equal(
1166
+ ndimage.shift(x, x.shape, mode='reflect', order=order),
1167
+ expected,
1168
+ )
1169
+
1170
+ @pytest.mark.parametrize('order', range(0, 6))
1171
+ @pytest.mark.parametrize('prefilter', [False, True])
1172
+ def test_shift_nearest_boundary(self, order, prefilter, xp):
1173
+ # verify that shifting at least order // 2 beyond the end of the array
1174
+ # gives a value equal to the edge value.
1175
+ x = xp.arange(16)
1176
+ kwargs = dict(mode='nearest', order=order, prefilter=prefilter)
1177
+ assert_array_almost_equal(
1178
+ ndimage.shift(x, order // 2 + 1, **kwargs)[0], x[0],
1179
+ )
1180
+ assert_array_almost_equal(
1181
+ ndimage.shift(x, -order // 2 - 1, **kwargs)[-1], x[-1],
1182
+ )
1183
+
1184
+ @pytest.mark.parametrize('mode', ['grid-constant', 'grid-wrap', 'nearest',
1185
+ 'mirror', 'reflect'])
1186
+ @pytest.mark.parametrize('order', range(6))
1187
+ def test_shift_vs_padded(self, order, mode, xp):
1188
+ x_np = np.arange(144, dtype=float).reshape(12, 12)
1189
+ shift = (0.4, -2.3)
1190
+
1191
+ # manually pad and then extract center to get expected result
1192
+ npad = 32
1193
+ pad_mode = ndimage_to_numpy_mode.get(mode)
1194
+ x_padded = xp.asarray(np.pad(x_np, npad, mode=pad_mode))
1195
+ x = xp.asarray(x_np)
1196
+
1197
+ center_slice = tuple([slice(npad, -npad)] * x.ndim)
1198
+ expected_result = ndimage.shift(
1199
+ x_padded, shift, mode=mode, order=order)[center_slice]
1200
+
1201
+ xp_assert_close(
1202
+ ndimage.shift(x, shift, mode=mode, order=order),
1203
+ expected_result,
1204
+ rtol=1e-7,
1205
+ )
1206
+
1207
+
1208
+ @make_xp_test_case(ndimage.zoom)
1209
+ class TestZoom:
1210
+
1211
+ @pytest.mark.parametrize('order', range(0, 6))
1212
+ def test_zoom1(self, order, xp):
1213
+ for z in [2, [2, 2]]:
1214
+ arr = xp.reshape(xp.arange(25, dtype=xp.float64), (5, 5))
1215
+ arr = ndimage.zoom(arr, z, order=order)
1216
+ assert arr.shape == (10, 10)
1217
+ assert xp.all(arr[-1, :] != 0)
1218
+ assert xp.all(arr[-1, :] >= (20 - eps))
1219
+ assert xp.all(arr[0, :] <= (5 + eps))
1220
+ assert xp.all(arr >= (0 - eps))
1221
+ assert xp.all(arr <= (24 + eps))
1222
+
1223
+ def test_zoom2(self, xp):
1224
+ arr = xp.reshape(xp.arange(12), (3, 4))
1225
+ out = ndimage.zoom(ndimage.zoom(arr, 2), 0.5)
1226
+ xp_assert_equal(out, arr)
1227
+
1228
+ def test_zoom3(self, xp):
1229
+ arr = xp.asarray([[1, 2]])
1230
+ out1 = ndimage.zoom(arr, (2, 1))
1231
+ out2 = ndimage.zoom(arr, (1, 2))
1232
+
1233
+ assert_array_almost_equal(out1, xp.asarray([[1, 2], [1, 2]]))
1234
+ assert_array_almost_equal(out2, xp.asarray([[1, 1, 2, 2]]))
1235
+
1236
+ @pytest.mark.parametrize('order', range(0, 6))
1237
+ @pytest.mark.parametrize('dtype', ["float64", "complex128"])
1238
+ def test_zoom_affine01(self, order, dtype, xp):
1239
+ dtype = getattr(xp, dtype)
1240
+ data = xp.asarray([[1, 2, 3, 4],
1241
+ [5, 6, 7, 8],
1242
+ [9, 10, 11, 12]], dtype=dtype)
1243
+ if xp.isdtype(data.dtype, 'complex floating'):
1244
+ data -= 1j * data
1245
+ with warnings.catch_warnings():
1246
+ warnings.filterwarnings("ignore",
1247
+ 'The behavior of affine_transform with a 1-D array .* '
1248
+ 'has changed', UserWarning)
1249
+ out = ndimage.affine_transform(data, xp.asarray([0.5, 0.5]), 0,
1250
+ (6, 8), order=order)
1251
+ assert_array_almost_equal(out[::2, ::2], data)
1252
+
1253
+ def test_zoom_infinity(self, xp):
1254
+ # Ticket #1419 regression test
1255
+ dim = 8
1256
+ ndimage.zoom(xp.zeros((dim, dim)), 1. / dim, mode='nearest')
1257
+
1258
+ def test_zoom_zoomfactor_one(self, xp):
1259
+ # Ticket #1122 regression test
1260
+ arr = xp.zeros((1, 5, 5))
1261
+ zoom = (1.0, 2.0, 2.0)
1262
+
1263
+ out = ndimage.zoom(arr, zoom, cval=7)
1264
+ ref = xp.zeros((1, 10, 10))
1265
+ assert_array_almost_equal(out, ref)
1266
+
1267
+ def test_zoom_output_shape_roundoff(self, xp):
1268
+ arr = xp.zeros((3, 11, 25))
1269
+ zoom = (4.0 / 3, 15.0 / 11, 29.0 / 25)
1270
+ out = ndimage.zoom(arr, zoom)
1271
+ assert out.shape == (4, 15, 29)
1272
+
1273
+ @pytest.mark.parametrize('zoom', [(1, 1), (3, 5), (8, 2), (8, 8)])
1274
+ @pytest.mark.parametrize('mode', ['nearest', 'constant', 'wrap', 'reflect',
1275
+ 'mirror', 'grid-wrap', 'grid-mirror',
1276
+ 'grid-constant'])
1277
+ def test_zoom_by_int_order0(self, zoom, mode, xp):
1278
+ # order 0 zoom should be the same as replication via np.kron
1279
+ # Note: This is not True for general x shapes when grid_mode is False,
1280
+ # but works here for all modes because the size ratio happens to
1281
+ # always be an integer when x.shape = (2, 2).
1282
+ x_np = np.asarray([[0, 1],
1283
+ [2, 3]], dtype=np.float64)
1284
+ expected = np.kron(x_np, np.ones(zoom))
1285
+
1286
+ x = xp.asarray(x_np)
1287
+ expected = xp.asarray(expected)
1288
+
1289
+ assert_array_almost_equal(
1290
+ ndimage.zoom(x, zoom, order=0, mode=mode),
1291
+ expected
1292
+ )
1293
+
1294
+ @pytest.mark.parametrize('shape', [(2, 3), (4, 4)])
1295
+ @pytest.mark.parametrize('zoom', [(1, 1), (3, 5), (8, 2), (8, 8)])
1296
+ @pytest.mark.parametrize('mode', ['nearest', 'reflect', 'mirror',
1297
+ 'grid-wrap', 'grid-constant'])
1298
+ def test_zoom_grid_by_int_order0(self, shape, zoom, mode, xp):
1299
+ # When grid_mode is True, order 0 zoom should be the same as
1300
+ # replication via np.kron. The only exceptions to this are the
1301
+ # non-grid modes 'constant' and 'wrap'.
1302
+ x_np = np.arange(np.prod(shape), dtype=float).reshape(shape)
1303
+
1304
+ x = xp.asarray(x_np)
1305
+ assert_array_almost_equal(
1306
+ ndimage.zoom(x, zoom, order=0, mode=mode, grid_mode=True),
1307
+ xp.asarray(np.kron(x_np, np.ones(zoom)))
1308
+ )
1309
+
1310
+ @pytest.mark.parametrize('mode', ['constant', 'wrap'])
1311
+ def test_zoom_grid_mode_warnings(self, mode, xp):
1312
+ # Warn on use of non-grid modes when grid_mode is True
1313
+ x = xp.reshape(xp.arange(9, dtype=xp.float64), (3, 3))
1314
+ with pytest.warns(UserWarning,
1315
+ match="It is recommended to use mode"):
1316
+ ndimage.zoom(x, 2, mode=mode, grid_mode=True),
1317
+
1318
+ @skip_xp_backends("dask.array", reason="output=array requires buffer view")
1319
+ @skip_xp_backends("jax.numpy", reason="output=array requires buffer view")
1320
+ def test_zoom_output_shape(self, xp):
1321
+ """Ticket #643"""
1322
+ x = xp.reshape(xp.arange(12), (3, 4))
1323
+ ndimage.zoom(x, 2, output=xp.zeros((6, 8)))
1324
+
1325
+ def test_zoom_0d_array(self, xp):
1326
+ # Ticket #21670 regression test
1327
+ a = xp.arange(10.)
1328
+ factor = 2
1329
+ actual = ndimage.zoom(a, np.array(factor))
1330
+ expected = ndimage.zoom(a, factor)
1331
+ xp_assert_close(actual, expected)
1332
+
1333
+ @xfail_xp_backends("cupy", reason="CuPy `zoom` needs similar fix.")
1334
+ def test_zoom_1_gh20999(self, xp):
1335
+ # gh-20999 reported that zoom with `zoom=1` (or sequence of ones)
1336
+ # introduced noise. Check that this is resolved.
1337
+ x = xp.eye(3)
1338
+ xp_assert_equal(ndimage.zoom(x, 1), x)
1339
+ xp_assert_equal(ndimage.zoom(x, (1, 1)), x)
1340
+
1341
+ @xfail_xp_backends("cupy", reason="CuPy `zoom` needs similar fix.")
1342
+ @skip_xp_backends("jax.numpy", reason="read-only backend")
1343
+ @xfail_xp_backends("dask.array", reason="numpy round-trip")
1344
+ def test_zoom_1_gh20999_output(self, xp):
1345
+ x = xp.eye(3)
1346
+ output = xp.zeros_like(x)
1347
+ ndimage.zoom(x, 1, output=output)
1348
+ xp_assert_equal(output, x)
1349
+
1350
+
1351
+ @make_xp_test_case(ndimage.rotate)
1352
+ class TestRotate:
1353
+
1354
+ @pytest.mark.parametrize('order', range(0, 6))
1355
+ def test_rotate01(self, order, xp):
1356
+ data = xp.asarray([[0, 0, 0, 0],
1357
+ [0, 1, 1, 0],
1358
+ [0, 0, 0, 0]], dtype=xp.float64)
1359
+ out = ndimage.rotate(data, 0, order=order)
1360
+ assert_array_almost_equal(out, data)
1361
+
1362
+ @pytest.mark.parametrize('order', range(0, 6))
1363
+ def test_rotate02(self, order, xp):
1364
+ data = xp.asarray([[0, 0, 0, 0],
1365
+ [0, 1, 0, 0],
1366
+ [0, 0, 0, 0]], dtype=xp.float64)
1367
+ expected = xp.asarray([[0, 0, 0],
1368
+ [0, 0, 0],
1369
+ [0, 1, 0],
1370
+ [0, 0, 0]], dtype=xp.float64)
1371
+ out = ndimage.rotate(data, 90, order=order)
1372
+ assert_array_almost_equal(out, expected)
1373
+
1374
+ @pytest.mark.parametrize('order', range(0, 6))
1375
+ @pytest.mark.parametrize('dtype', ["float64", "complex128"])
1376
+ def test_rotate03(self, order, dtype, xp):
1377
+ dtype = getattr(xp, dtype)
1378
+ data = xp.asarray([[0, 0, 0, 0, 0],
1379
+ [0, 1, 1, 0, 0],
1380
+ [0, 0, 0, 0, 0]], dtype=dtype)
1381
+ expected = xp.asarray([[0, 0, 0],
1382
+ [0, 0, 0],
1383
+ [0, 1, 0],
1384
+ [0, 1, 0],
1385
+ [0, 0, 0]], dtype=dtype)
1386
+ if xp.isdtype(data.dtype, 'complex floating'):
1387
+ data -= 1j * data
1388
+ expected -= 1j * expected
1389
+ out = ndimage.rotate(data, 90, order=order)
1390
+ assert_array_almost_equal(out, expected)
1391
+
1392
+ @pytest.mark.parametrize('order', range(0, 6))
1393
+ def test_rotate04(self, order, xp):
1394
+ data = xp.asarray([[0, 0, 0, 0, 0],
1395
+ [0, 1, 1, 0, 0],
1396
+ [0, 0, 0, 0, 0]], dtype=xp.float64)
1397
+ expected = xp.asarray([[0, 0, 0, 0, 0],
1398
+ [0, 0, 1, 0, 0],
1399
+ [0, 0, 1, 0, 0]], dtype=xp.float64)
1400
+ out = ndimage.rotate(data, 90, reshape=False, order=order)
1401
+ assert_array_almost_equal(out, expected)
1402
+
1403
+ @pytest.mark.parametrize('order', range(0, 6))
1404
+ def test_rotate05(self, order, xp):
1405
+ data = np.empty((4, 3, 3))
1406
+ for i in range(3):
1407
+ data[:, :, i] = np.asarray([[0, 0, 0],
1408
+ [0, 1, 0],
1409
+ [0, 1, 0],
1410
+ [0, 0, 0]], dtype=np.float64)
1411
+ data = xp.asarray(data)
1412
+ expected = xp.asarray([[0, 0, 0, 0],
1413
+ [0, 1, 1, 0],
1414
+ [0, 0, 0, 0]], dtype=xp.float64)
1415
+ out = ndimage.rotate(data, 90, order=order)
1416
+ for i in range(3):
1417
+ assert_array_almost_equal(out[:, :, i], expected)
1418
+
1419
+ @pytest.mark.parametrize('order', range(0, 6))
1420
+ def test_rotate06(self, order, xp):
1421
+ data = np.empty((3, 4, 3))
1422
+ for i in range(3):
1423
+ data[:, :, i] = np.asarray([[0, 0, 0, 0],
1424
+ [0, 1, 1, 0],
1425
+ [0, 0, 0, 0]], dtype=np.float64)
1426
+ data = xp.asarray(data)
1427
+ expected = xp.asarray([[0, 0, 0],
1428
+ [0, 1, 0],
1429
+ [0, 1, 0],
1430
+ [0, 0, 0]], dtype=xp.float64)
1431
+ out = ndimage.rotate(data, 90, order=order)
1432
+ for i in range(3):
1433
+ assert_array_almost_equal(out[:, :, i], expected)
1434
+
1435
+ @pytest.mark.parametrize('order', range(0, 6))
1436
+ def test_rotate07(self, order, xp):
1437
+ data = xp.asarray([[[0, 0, 0, 0, 0],
1438
+ [0, 1, 1, 0, 0],
1439
+ [0, 0, 0, 0, 0]]] * 2, dtype=xp.float64)
1440
+ data = xp.permute_dims(data, (2, 1, 0))
1441
+ expected = xp.asarray([[[0, 0, 0],
1442
+ [0, 1, 0],
1443
+ [0, 1, 0],
1444
+ [0, 0, 0],
1445
+ [0, 0, 0]]] * 2, dtype=xp.float64)
1446
+ expected = xp.permute_dims(expected, (2, 1, 0))
1447
+ out = ndimage.rotate(data, 90, axes=(0, 1), order=order)
1448
+ assert_array_almost_equal(out, expected)
1449
+
1450
+ @pytest.mark.parametrize('order', range(0, 6))
1451
+ def test_rotate08(self, order, xp):
1452
+ data = xp.asarray([[[0, 0, 0, 0, 0],
1453
+ [0, 1, 1, 0, 0],
1454
+ [0, 0, 0, 0, 0]]] * 2, dtype=xp.float64)
1455
+ data = xp.permute_dims(data, (2, 1, 0)) # == np.transpose
1456
+ expected = xp.asarray([[[0, 0, 1, 0, 0],
1457
+ [0, 0, 1, 0, 0],
1458
+ [0, 0, 0, 0, 0]]] * 2, dtype=xp.float64)
1459
+ expected = xp.permute_dims(expected, (2, 1, 0))
1460
+ out = ndimage.rotate(data, 90, axes=(0, 1), reshape=False, order=order)
1461
+ assert_array_almost_equal(out, expected)
1462
+
1463
+ def test_rotate09(self, xp):
1464
+ data = xp.asarray([[0, 0, 0, 0, 0],
1465
+ [0, 1, 1, 0, 0],
1466
+ [0, 0, 0, 0, 0]] * 2, dtype=xp.float64)
1467
+ with assert_raises(ValueError):
1468
+ ndimage.rotate(data, 90, axes=(0, data.ndim))
1469
+
1470
+ def test_rotate10(self, xp):
1471
+ data = xp.reshape(xp.arange(45, dtype=xp.float64), (3, 5, 3))
1472
+
1473
+ # The output of ndimage.rotate before refactoring
1474
+ expected = xp.asarray([[[0.0, 0.0, 0.0],
1475
+ [0.0, 0.0, 0.0],
1476
+ [6.54914793, 7.54914793, 8.54914793],
1477
+ [10.84520162, 11.84520162, 12.84520162],
1478
+ [0.0, 0.0, 0.0]],
1479
+ [[6.19286575, 7.19286575, 8.19286575],
1480
+ [13.4730712, 14.4730712, 15.4730712],
1481
+ [21.0, 22.0, 23.0],
1482
+ [28.5269288, 29.5269288, 30.5269288],
1483
+ [35.80713425, 36.80713425, 37.80713425]],
1484
+ [[0.0, 0.0, 0.0],
1485
+ [31.15479838, 32.15479838, 33.15479838],
1486
+ [35.45085207, 36.45085207, 37.45085207],
1487
+ [0.0, 0.0, 0.0],
1488
+ [0.0, 0.0, 0.0]]], dtype=xp.float64)
1489
+
1490
+ out = ndimage.rotate(data, angle=12, reshape=False)
1491
+ #assert_array_almost_equal(out, expected)
1492
+ xp_assert_close(out, expected, rtol=1e-6, atol=2e-6)
1493
+
1494
+
1495
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8400")
1496
+ def test_rotate_exact_180(self, xp):
1497
+ a = xp.asarray(np.tile(np.arange(5), (5, 1)))
1498
+ b = ndimage.rotate(ndimage.rotate(a, 180), -180)
1499
+ xp_assert_equal(a, b)
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/test_measurements.py ADDED
@@ -0,0 +1,1696 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import os.path
3
+ import warnings
4
+
5
+ import numpy as np
6
+
7
+ from scipy._lib._array_api import (
8
+ is_torch,
9
+ xp_assert_equal,
10
+ xp_assert_close,
11
+ assert_array_almost_equal,
12
+ assert_almost_equal,
13
+ make_xp_test_case,
14
+ )
15
+
16
+ import pytest
17
+ from pytest import raises as assert_raises
18
+
19
+ import scipy.ndimage as ndimage
20
+
21
+ from . import types
22
+
23
+ skip_xp_backends = pytest.mark.skip_xp_backends
24
+
25
+ IS_WINDOWS_AND_NP1 = os.name == 'nt' and np.__version__ < '2'
26
+
27
+
28
+ @skip_xp_backends(np_only=True, reason='test internal numpy-only helpers')
29
+ class Test_measurements_stats:
30
+ """ndimage._measurements._stats() is a utility used by other functions.
31
+
32
+ Since internal ndimage/_measurements.py code is NumPy-only,
33
+ so is this this test class.
34
+ """
35
+ def test_a(self, xp):
36
+ x = [0, 1, 2, 6]
37
+ labels = [0, 0, 1, 1]
38
+ index = [0, 1]
39
+ for shp in [(4,), (2, 2)]:
40
+ x = np.array(x).reshape(shp)
41
+ labels = np.array(labels).reshape(shp)
42
+ counts, sums = ndimage._measurements._stats(
43
+ x, labels=labels, index=index)
44
+
45
+ dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
46
+ xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
47
+ xp_assert_equal(sums, np.asarray([1.0, 8.0]))
48
+
49
+ def test_b(self, xp):
50
+ # Same data as test_a, but different labels. The label 9 exceeds the
51
+ # length of 'labels', so this test will follow a different code path.
52
+ x = [0, 1, 2, 6]
53
+ labels = [0, 0, 9, 9]
54
+ index = [0, 9]
55
+ for shp in [(4,), (2, 2)]:
56
+ x = np.array(x).reshape(shp)
57
+ labels = np.array(labels).reshape(shp)
58
+ counts, sums = ndimage._measurements._stats(
59
+ x, labels=labels, index=index)
60
+
61
+ dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
62
+ xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
63
+ xp_assert_equal(sums, np.asarray([1.0, 8.0]))
64
+
65
+ def test_a_centered(self, xp):
66
+ x = [0, 1, 2, 6]
67
+ labels = [0, 0, 1, 1]
68
+ index = [0, 1]
69
+ for shp in [(4,), (2, 2)]:
70
+ x = np.array(x).reshape(shp)
71
+ labels = np.array(labels).reshape(shp)
72
+ counts, sums, centers = ndimage._measurements._stats(
73
+ x, labels=labels, index=index, centered=True)
74
+
75
+ dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
76
+ xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
77
+ xp_assert_equal(sums, np.asarray([1.0, 8.0]))
78
+ xp_assert_equal(centers, np.asarray([0.5, 8.0]))
79
+
80
+ def test_b_centered(self, xp):
81
+ x = [0, 1, 2, 6]
82
+ labels = [0, 0, 9, 9]
83
+ index = [0, 9]
84
+ for shp in [(4,), (2, 2)]:
85
+ x = np.array(x).reshape(shp)
86
+ labels = np.array(labels).reshape(shp)
87
+ counts, sums, centers = ndimage._measurements._stats(
88
+ x, labels=labels, index=index, centered=True)
89
+
90
+ dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
91
+ xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
92
+ xp_assert_equal(sums, np.asarray([1.0, 8.0]))
93
+ xp_assert_equal(centers, np.asarray([0.5, 8.0]))
94
+
95
+ def test_nonint_labels(self, xp):
96
+ x = [0, 1, 2, 6]
97
+ labels = [0.0, 0.0, 9.0, 9.0]
98
+ index = [0.0, 9.0]
99
+ for shp in [(4,), (2, 2)]:
100
+ x = np.array(x).reshape(shp)
101
+ labels = np.array(labels).reshape(shp)
102
+ counts, sums, centers = ndimage._measurements._stats(
103
+ x, labels=labels, index=index, centered=True)
104
+
105
+ dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
106
+ xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
107
+ xp_assert_equal(sums, np.asarray([1.0, 8.0]))
108
+ xp_assert_equal(centers, np.asarray([0.5, 8.0]))
109
+
110
+
111
+ @skip_xp_backends(np_only=True, reason='test internal numpy-only helpers')
112
+ class Test_measurements_select:
113
+ """ndimage._measurements._select() is a utility used by other functions."""
114
+
115
+ def test_basic(self, xp):
116
+ x = [0, 1, 6, 2]
117
+ cases = [
118
+ ([0, 0, 1, 1], [0, 1]), # "Small" integer labels
119
+ ([0, 0, 9, 9], [0, 9]), # A label larger than len(labels)
120
+ ([0.0, 0.0, 7.0, 7.0], [0.0, 7.0]), # Non-integer labels
121
+ ]
122
+ for labels, index in cases:
123
+ result = ndimage._measurements._select(
124
+ x, labels=labels, index=index)
125
+ assert len(result) == 0
126
+ result = ndimage._measurements._select(
127
+ x, labels=labels, index=index, find_max=True)
128
+ assert len(result) == 1
129
+ xp_assert_equal(result[0], [1, 6])
130
+ result = ndimage._measurements._select(
131
+ x, labels=labels, index=index, find_min=True)
132
+ assert len(result) == 1
133
+ xp_assert_equal(result[0], [0, 2])
134
+ result = ndimage._measurements._select(
135
+ x, labels=labels, index=index, find_min=True,
136
+ find_min_positions=True)
137
+ assert len(result) == 2
138
+ xp_assert_equal(result[0], [0, 2])
139
+ xp_assert_equal(result[1], [0, 3])
140
+ assert result[1].dtype.kind == 'i'
141
+ result = ndimage._measurements._select(
142
+ x, labels=labels, index=index, find_max=True,
143
+ find_max_positions=True)
144
+ assert len(result) == 2
145
+ xp_assert_equal(result[0], [1, 6])
146
+ xp_assert_equal(result[1], [1, 2])
147
+ assert result[1].dtype.kind == 'i'
148
+
149
+
150
+ @make_xp_test_case(ndimage.label)
151
+ def test_label01(xp):
152
+ data = xp.ones(())
153
+ out, n = ndimage.label(data)
154
+ assert out == 1
155
+ assert n == 1
156
+
157
+
158
+ @make_xp_test_case(ndimage.label)
159
+ def test_label02(xp):
160
+ data = xp.zeros(())
161
+ out, n = ndimage.label(data)
162
+ assert out == 0
163
+ assert n == 0
164
+
165
+
166
+ @make_xp_test_case(ndimage.label)
167
+ def test_label03(xp):
168
+ data = xp.ones([1])
169
+ out, n = ndimage.label(data)
170
+ assert_array_almost_equal(out, xp.asarray([1]))
171
+ assert n == 1
172
+
173
+
174
+ @make_xp_test_case(ndimage.label)
175
+ def test_label04(xp):
176
+ data = xp.zeros([1])
177
+ out, n = ndimage.label(data)
178
+ assert_array_almost_equal(out, xp.asarray([0]))
179
+ assert n == 0
180
+
181
+
182
+ @make_xp_test_case(ndimage.label)
183
+ def test_label05(xp):
184
+ data = xp.ones([5])
185
+ out, n = ndimage.label(data)
186
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1, 1]))
187
+ assert n == 1
188
+
189
+
190
+ @make_xp_test_case(ndimage.label)
191
+ def test_label06(xp):
192
+ data = xp.asarray([1, 0, 1, 1, 0, 1])
193
+ out, n = ndimage.label(data)
194
+ assert_array_almost_equal(out, xp.asarray([1, 0, 2, 2, 0, 3]))
195
+ assert n == 3
196
+
197
+
198
+ @make_xp_test_case(ndimage.label)
199
+ def test_label07(xp):
200
+ data = xp.asarray([[0, 0, 0, 0, 0, 0],
201
+ [0, 0, 0, 0, 0, 0],
202
+ [0, 0, 0, 0, 0, 0],
203
+ [0, 0, 0, 0, 0, 0],
204
+ [0, 0, 0, 0, 0, 0],
205
+ [0, 0, 0, 0, 0, 0]])
206
+ out, n = ndimage.label(data)
207
+ assert_array_almost_equal(out, xp.asarray(
208
+ [[0, 0, 0, 0, 0, 0],
209
+ [0, 0, 0, 0, 0, 0],
210
+ [0, 0, 0, 0, 0, 0],
211
+ [0, 0, 0, 0, 0, 0],
212
+ [0, 0, 0, 0, 0, 0],
213
+ [0, 0, 0, 0, 0, 0]]))
214
+ assert n == 0
215
+
216
+
217
+ @make_xp_test_case(ndimage.label)
218
+ def test_label08(xp):
219
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
220
+ [0, 0, 1, 1, 0, 0],
221
+ [0, 0, 1, 1, 1, 0],
222
+ [1, 1, 0, 0, 0, 0],
223
+ [1, 1, 0, 0, 0, 0],
224
+ [0, 0, 0, 1, 1, 0]])
225
+ out, n = ndimage.label(data)
226
+ assert_array_almost_equal(out, xp.asarray([[1, 0, 0, 0, 0, 0],
227
+ [0, 0, 2, 2, 0, 0],
228
+ [0, 0, 2, 2, 2, 0],
229
+ [3, 3, 0, 0, 0, 0],
230
+ [3, 3, 0, 0, 0, 0],
231
+ [0, 0, 0, 4, 4, 0]]))
232
+ assert n == 4
233
+
234
+
235
+ @make_xp_test_case(ndimage.label)
236
+ def test_label09(xp):
237
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
238
+ [0, 0, 1, 1, 0, 0],
239
+ [0, 0, 1, 1, 1, 0],
240
+ [1, 1, 0, 0, 0, 0],
241
+ [1, 1, 0, 0, 0, 0],
242
+ [0, 0, 0, 1, 1, 0]])
243
+ struct = ndimage.generate_binary_structure(2, 2)
244
+ struct = xp.asarray(struct)
245
+ out, n = ndimage.label(data, struct)
246
+ assert_array_almost_equal(out, xp.asarray([[1, 0, 0, 0, 0, 0],
247
+ [0, 0, 2, 2, 0, 0],
248
+ [0, 0, 2, 2, 2, 0],
249
+ [2, 2, 0, 0, 0, 0],
250
+ [2, 2, 0, 0, 0, 0],
251
+ [0, 0, 0, 3, 3, 0]]))
252
+ assert n == 3
253
+
254
+
255
+ @make_xp_test_case(ndimage.label)
256
+ def test_label10(xp):
257
+ data = xp.asarray([[0, 0, 0, 0, 0, 0],
258
+ [0, 1, 1, 0, 1, 0],
259
+ [0, 1, 1, 1, 1, 0],
260
+ [0, 0, 0, 0, 0, 0]])
261
+ struct = ndimage.generate_binary_structure(2, 2)
262
+ struct = xp.asarray(struct)
263
+ out, n = ndimage.label(data, struct)
264
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0, 0, 0],
265
+ [0, 1, 1, 0, 1, 0],
266
+ [0, 1, 1, 1, 1, 0],
267
+ [0, 0, 0, 0, 0, 0]]))
268
+ assert n == 1
269
+
270
+
271
+ @make_xp_test_case(ndimage.label)
272
+ def test_label11(xp):
273
+ for type in types:
274
+ dtype = getattr(xp, type)
275
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
276
+ [0, 0, 1, 1, 0, 0],
277
+ [0, 0, 1, 1, 1, 0],
278
+ [1, 1, 0, 0, 0, 0],
279
+ [1, 1, 0, 0, 0, 0],
280
+ [0, 0, 0, 1, 1, 0]], dtype=dtype)
281
+ out, n = ndimage.label(data)
282
+ expected = [[1, 0, 0, 0, 0, 0],
283
+ [0, 0, 2, 2, 0, 0],
284
+ [0, 0, 2, 2, 2, 0],
285
+ [3, 3, 0, 0, 0, 0],
286
+ [3, 3, 0, 0, 0, 0],
287
+ [0, 0, 0, 4, 4, 0]]
288
+ expected = xp.asarray(expected)
289
+ assert_array_almost_equal(out, expected)
290
+ assert n == 4
291
+
292
+
293
+ @skip_xp_backends(np_only=True, reason='inplace output is numpy-specific')
294
+ @make_xp_test_case(ndimage.label)
295
+ def test_label11_inplace(xp):
296
+ for type in types:
297
+ dtype = getattr(xp, type)
298
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
299
+ [0, 0, 1, 1, 0, 0],
300
+ [0, 0, 1, 1, 1, 0],
301
+ [1, 1, 0, 0, 0, 0],
302
+ [1, 1, 0, 0, 0, 0],
303
+ [0, 0, 0, 1, 1, 0]], dtype=dtype)
304
+ n = ndimage.label(data, output=data)
305
+ expected = [[1, 0, 0, 0, 0, 0],
306
+ [0, 0, 2, 2, 0, 0],
307
+ [0, 0, 2, 2, 2, 0],
308
+ [3, 3, 0, 0, 0, 0],
309
+ [3, 3, 0, 0, 0, 0],
310
+ [0, 0, 0, 4, 4, 0]]
311
+ expected = xp.asarray(expected)
312
+ assert_array_almost_equal(data, expected)
313
+ assert n == 4
314
+
315
+
316
+ @make_xp_test_case(ndimage.label)
317
+ def test_label12(xp):
318
+ for type in types:
319
+ dtype = getattr(xp, type)
320
+ data = xp.asarray([[0, 0, 0, 0, 1, 1],
321
+ [0, 0, 0, 0, 0, 1],
322
+ [0, 0, 1, 0, 1, 1],
323
+ [0, 0, 1, 1, 1, 1],
324
+ [0, 0, 0, 1, 1, 0]], dtype=dtype)
325
+ out, n = ndimage.label(data)
326
+ expected = [[0, 0, 0, 0, 1, 1],
327
+ [0, 0, 0, 0, 0, 1],
328
+ [0, 0, 1, 0, 1, 1],
329
+ [0, 0, 1, 1, 1, 1],
330
+ [0, 0, 0, 1, 1, 0]]
331
+ expected = xp.asarray(expected)
332
+ assert_array_almost_equal(out, expected)
333
+ assert n == 1
334
+
335
+
336
+ @make_xp_test_case(ndimage.label)
337
+ def test_label13(xp):
338
+ for type in types:
339
+ dtype = getattr(xp, type)
340
+ data = xp.asarray([[1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1],
341
+ [1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1],
342
+ [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
343
+ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]],
344
+ dtype=dtype)
345
+ out, n = ndimage.label(data)
346
+ expected = [[1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1],
347
+ [1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1],
348
+ [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
349
+ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
350
+ expected = xp.asarray(expected)
351
+ assert_array_almost_equal(out, expected)
352
+ assert n == 1
353
+
354
+
355
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
356
+ reason='output=dtype is numpy-specific')
357
+ @make_xp_test_case(ndimage.label)
358
+ def test_label_output_typed(xp):
359
+ data = xp.ones([5])
360
+ for t in types:
361
+ dtype = getattr(xp, t)
362
+ output = xp.zeros([5], dtype=dtype)
363
+ n = ndimage.label(data, output=output)
364
+ assert_array_almost_equal(output,
365
+ xp.ones(output.shape, dtype=output.dtype))
366
+ assert n == 1
367
+
368
+
369
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
370
+ reason='output=dtype is numpy-specific')
371
+ @make_xp_test_case(ndimage.label)
372
+ def test_label_output_dtype(xp):
373
+ data = xp.ones([5])
374
+ for t in types:
375
+ dtype = getattr(xp, t)
376
+ output, n = ndimage.label(data, output=dtype)
377
+ assert_array_almost_equal(output,
378
+ xp.ones(output.shape, dtype=output.dtype))
379
+ assert output.dtype == t
380
+
381
+
382
+ @skip_xp_backends(np_only=True, reason="in-place output is numpy-specific")
383
+ @make_xp_test_case(ndimage.label)
384
+ def test_label_output_wrong_size(xp):
385
+ data = xp.ones([5])
386
+ for t in types:
387
+ dtype = getattr(xp, t)
388
+ output = xp.zeros([10], dtype=dtype)
389
+ assert_raises(ValueError, ndimage.label, data, output=output)
390
+
391
+
392
+ @make_xp_test_case(ndimage.label)
393
+ def test_label_structuring_elements(xp):
394
+ data = np.loadtxt(os.path.join(os.path.dirname(
395
+ __file__), "data", "label_inputs.txt"))
396
+ strels = np.loadtxt(os.path.join(
397
+ os.path.dirname(__file__), "data", "label_strels.txt"))
398
+ results = np.loadtxt(os.path.join(
399
+ os.path.dirname(__file__), "data", "label_results.txt"))
400
+ data = data.reshape((-1, 7, 7))
401
+ strels = strels.reshape((-1, 3, 3))
402
+ results = results.reshape((-1, 7, 7))
403
+
404
+ data = xp.asarray(data)
405
+ strels = xp.asarray(strels)
406
+ results = xp.asarray(results)
407
+ r = 0
408
+ for i in range(data.shape[0]):
409
+ d = data[i, :, :]
410
+ for j in range(strels.shape[0]):
411
+ s = strels[j, :, :]
412
+ xp_assert_equal(ndimage.label(d, s)[0], results[r, :, :], check_dtype=False)
413
+ r += 1
414
+
415
+
416
+ @make_xp_test_case(ndimage.label, ndimage.find_objects)
417
+ def test_ticket_742(xp):
418
+ def SE(img, thresh=.7, size=4):
419
+ mask = img > thresh
420
+ rank = len(mask.shape)
421
+ struct = ndimage.generate_binary_structure(rank, rank)
422
+ struct = xp.asarray(struct)
423
+ la, co = ndimage.label(mask,
424
+ struct)
425
+ _ = ndimage.find_objects(la)
426
+
427
+ if np.dtype(np.intp) != np.dtype('i'):
428
+ shape = (3, 1240, 1240)
429
+ a = np.random.rand(np.prod(shape)).reshape(shape)
430
+ a = xp.asarray(a)
431
+ # shouldn't crash
432
+ SE(a)
433
+
434
+
435
+ @make_xp_test_case(ndimage.label)
436
+ def test_gh_issue_3025(xp):
437
+ """Github issue #3025 - improper merging of labels"""
438
+ d = np.zeros((60, 320))
439
+ d[:, :257] = 1
440
+ d[:, 260:] = 1
441
+ d[36, 257] = 1
442
+ d[35, 258] = 1
443
+ d[35, 259] = 1
444
+ d = xp.asarray(d)
445
+ assert ndimage.label(d, xp.ones((3, 3)))[1] == 1
446
+
447
+
448
+ @make_xp_test_case(ndimage.label, ndimage.find_objects)
449
+ class TestFindObjects:
450
+ def test_label_default_dtype(self, xp):
451
+ test_array = np.random.rand(10, 10)
452
+ test_array = xp.asarray(test_array)
453
+ label, no_features = ndimage.label(test_array > 0.5)
454
+ assert label.dtype in (xp.int32, xp.int64)
455
+ # Shouldn't raise an exception
456
+ ndimage.find_objects(label)
457
+
458
+
459
+ def test_find_objects01(self, xp):
460
+ data = xp.ones([], dtype=xp.int64)
461
+ out = ndimage.find_objects(data)
462
+ assert out == [()]
463
+
464
+
465
+ def test_find_objects02(self, xp):
466
+ data = xp.zeros([], dtype=xp.int64)
467
+ out = ndimage.find_objects(data)
468
+ assert out == []
469
+
470
+
471
+ def test_find_objects03(self, xp):
472
+ data = xp.ones([1], dtype=xp.int64)
473
+ out = ndimage.find_objects(data)
474
+ assert out == [(slice(0, 1, None),)]
475
+
476
+
477
+ def test_find_objects04(self, xp):
478
+ data = xp.zeros([1], dtype=xp.int64)
479
+ out = ndimage.find_objects(data)
480
+ assert out == []
481
+
482
+
483
+ def test_find_objects05(self, xp):
484
+ data = xp.ones([5], dtype=xp.int64)
485
+ out = ndimage.find_objects(data)
486
+ assert out == [(slice(0, 5, None),)]
487
+
488
+
489
+ def test_find_objects06(self, xp):
490
+ data = xp.asarray([1, 0, 2, 2, 0, 3])
491
+ out = ndimage.find_objects(data)
492
+ assert out == [(slice(0, 1, None),),
493
+ (slice(2, 4, None),),
494
+ (slice(5, 6, None),)]
495
+
496
+
497
+ def test_find_objects07(self, xp):
498
+ data = xp.asarray([[0, 0, 0, 0, 0, 0],
499
+ [0, 0, 0, 0, 0, 0],
500
+ [0, 0, 0, 0, 0, 0],
501
+ [0, 0, 0, 0, 0, 0],
502
+ [0, 0, 0, 0, 0, 0],
503
+ [0, 0, 0, 0, 0, 0]])
504
+ out = ndimage.find_objects(data)
505
+ assert out == []
506
+
507
+
508
+ def test_find_objects08(self, xp):
509
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
510
+ [0, 0, 2, 2, 0, 0],
511
+ [0, 0, 2, 2, 2, 0],
512
+ [3, 3, 0, 0, 0, 0],
513
+ [3, 3, 0, 0, 0, 0],
514
+ [0, 0, 0, 4, 4, 0]])
515
+ out = ndimage.find_objects(data)
516
+ assert out == [(slice(0, 1, None), slice(0, 1, None)),
517
+ (slice(1, 3, None), slice(2, 5, None)),
518
+ (slice(3, 5, None), slice(0, 2, None)),
519
+ (slice(5, 6, None), slice(3, 5, None))]
520
+
521
+
522
+ def test_find_objects09(self, xp):
523
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
524
+ [0, 0, 2, 2, 0, 0],
525
+ [0, 0, 2, 2, 2, 0],
526
+ [0, 0, 0, 0, 0, 0],
527
+ [0, 0, 0, 0, 0, 0],
528
+ [0, 0, 0, 4, 4, 0]])
529
+ out = ndimage.find_objects(data)
530
+ assert out == [(slice(0, 1, None), slice(0, 1, None)),
531
+ (slice(1, 3, None), slice(2, 5, None)),
532
+ None,
533
+ (slice(5, 6, None), slice(3, 5, None))]
534
+
535
+
536
+ @make_xp_test_case(ndimage.value_indices)
537
+ def test_value_indices01(xp):
538
+ "Test dictionary keys and entries"
539
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
540
+ [0, 0, 2, 2, 0, 0],
541
+ [0, 0, 2, 2, 2, 0],
542
+ [0, 0, 0, 0, 0, 0],
543
+ [0, 0, 0, 0, 0, 0],
544
+ [0, 0, 0, 4, 4, 0]])
545
+ vi = ndimage.value_indices(data, ignore_value=0)
546
+ true_keys = [1, 2, 4]
547
+ assert list(vi.keys()) == true_keys
548
+
549
+ truevi = {k: xp.nonzero(data == k) for k in true_keys}
550
+
551
+ vi = ndimage.value_indices(data, ignore_value=0)
552
+ assert vi.keys() == truevi.keys()
553
+ for key in vi.keys():
554
+ assert len(vi[key]) == len(truevi[key])
555
+ for v, true_v in zip(vi[key], truevi[key]):
556
+ xp_assert_equal(v, true_v)
557
+
558
+
559
+ @make_xp_test_case(ndimage.value_indices)
560
+ def test_value_indices02(xp):
561
+ "Test input checking"
562
+ data = xp.zeros((5, 4), dtype=xp.float32)
563
+ msg = "Parameter 'arr' must be an integer array"
564
+ with assert_raises(ValueError, match=msg):
565
+ ndimage.value_indices(data)
566
+
567
+
568
+ @make_xp_test_case(ndimage.value_indices)
569
+ def test_value_indices03(xp):
570
+ "Test different input array shapes, from 1-D to 4-D"
571
+ for shape in [(36,), (18, 2), (3, 3, 4), (3, 3, 2, 2)]:
572
+ a = np.asarray((12*[1]+12*[2]+12*[3]), dtype=np.int32)
573
+ a = np.reshape(a, shape)
574
+
575
+ trueKeys = np.unique(a)
576
+ a = xp.asarray(a)
577
+ vi = ndimage.value_indices(a)
578
+ assert list(vi.keys()) == list(trueKeys)
579
+ for k in [int(x) for x in trueKeys]:
580
+ trueNdx = xp.nonzero(a == k)
581
+ assert len(vi[k]) == len(trueNdx)
582
+ for vik, true_vik in zip(vi[k], trueNdx):
583
+ xp_assert_equal(vik, true_vik)
584
+
585
+
586
+ @make_xp_test_case(ndimage.sum)
587
+ def test_sum01(xp):
588
+ for type in types:
589
+ dtype = getattr(xp, type)
590
+ input = xp.asarray([], dtype=dtype)
591
+ output = ndimage.sum(input)
592
+ assert output == 0
593
+
594
+
595
+ @make_xp_test_case(ndimage.sum)
596
+ def test_sum02(xp):
597
+ for type in types:
598
+ dtype = getattr(xp, type)
599
+ input = xp.zeros([0, 4], dtype=dtype)
600
+ output = ndimage.sum(input)
601
+ assert output == 0
602
+
603
+
604
+ @make_xp_test_case(ndimage.sum)
605
+ def test_sum03(xp):
606
+ for type in types:
607
+ dtype = getattr(xp, type)
608
+ input = xp.ones([], dtype=dtype)
609
+ output = ndimage.sum(input)
610
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
611
+
612
+
613
+ @make_xp_test_case(ndimage.sum)
614
+ def test_sum04(xp):
615
+ for type in types:
616
+ dtype = getattr(xp, type)
617
+ input = xp.asarray([1, 2], dtype=dtype)
618
+ output = ndimage.sum(input)
619
+ assert_almost_equal(output, xp.asarray(3.0), check_0d=False)
620
+
621
+
622
+ @make_xp_test_case(ndimage.sum)
623
+ def test_sum05(xp):
624
+ for type in types:
625
+ dtype = getattr(xp, type)
626
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
627
+ output = ndimage.sum(input)
628
+ assert_almost_equal(output, xp.asarray(10.0), check_0d=False)
629
+
630
+
631
+ @make_xp_test_case(ndimage.sum)
632
+ def test_sum06(xp):
633
+ labels = np.asarray([], dtype=bool)
634
+ labels = xp.asarray(labels)
635
+ for type in types:
636
+ dtype = getattr(xp, type)
637
+ input = xp.asarray([], dtype=dtype)
638
+ output = ndimage.sum(input, labels=labels)
639
+ assert output == 0
640
+
641
+
642
+ @make_xp_test_case(ndimage.sum)
643
+ def test_sum07(xp):
644
+ labels = np.ones([0, 4], dtype=bool)
645
+ labels = xp.asarray(labels)
646
+ for type in types:
647
+ dtype = getattr(xp, type)
648
+ input = xp.zeros([0, 4], dtype=dtype)
649
+ output = ndimage.sum(input, labels=labels)
650
+ assert output == 0
651
+
652
+
653
+ @make_xp_test_case(ndimage.sum)
654
+ def test_sum08(xp):
655
+ labels = np.asarray([1, 0], dtype=bool)
656
+ labels = xp.asarray(labels)
657
+ for type in types:
658
+ dtype = getattr(xp, type)
659
+ input = xp.asarray([1, 2], dtype=dtype)
660
+ output = ndimage.sum(input, labels=labels)
661
+ assert output == 1
662
+
663
+
664
+ @make_xp_test_case(ndimage.sum)
665
+ def test_sum09(xp):
666
+ labels = np.asarray([1, 0], dtype=bool)
667
+ labels = xp.asarray(labels)
668
+ for type in types:
669
+ dtype = getattr(xp, type)
670
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
671
+ output = ndimage.sum(input, labels=labels)
672
+ assert_almost_equal(output, xp.asarray(4.0), check_0d=False)
673
+
674
+
675
+ @make_xp_test_case(ndimage.sum)
676
+ def test_sum10(xp):
677
+ labels = np.asarray([1, 0], dtype=bool)
678
+ input = np.asarray([[1, 2], [3, 4]], dtype=bool)
679
+
680
+ labels = xp.asarray(labels)
681
+ input = xp.asarray(input)
682
+ output = ndimage.sum(input, labels=labels)
683
+ assert_almost_equal(output, xp.asarray(2.0), check_0d=False)
684
+
685
+
686
+ @make_xp_test_case(ndimage.sum)
687
+ def test_sum11(xp):
688
+ labels = xp.asarray([1, 2], dtype=xp.int8)
689
+ for type in types:
690
+ dtype = getattr(xp, type)
691
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
692
+ output = ndimage.sum(input, labels=labels,
693
+ index=2)
694
+ assert_almost_equal(output, xp.asarray(6.0), check_0d=False)
695
+
696
+
697
+ @make_xp_test_case(ndimage.sum)
698
+ def test_sum12(xp):
699
+ labels = xp.asarray([[1, 2], [2, 4]], dtype=xp.int8)
700
+ for type in types:
701
+ dtype = getattr(xp, type)
702
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
703
+ output = ndimage.sum(input, labels=labels, index=xp.asarray([4, 8, 2]))
704
+ assert_array_almost_equal(output, xp.asarray([4.0, 0.0, 5.0]))
705
+
706
+
707
+ @make_xp_test_case(ndimage.sum)
708
+ def test_sum_labels(xp):
709
+ labels = xp.asarray([[1, 2], [2, 4]], dtype=xp.int8)
710
+ for type in types:
711
+ dtype = getattr(xp, type)
712
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
713
+ output_sum = ndimage.sum(input, labels=labels, index=xp.asarray([4, 8, 2]))
714
+ output_labels = ndimage.sum_labels(
715
+ input, labels=labels, index=xp.asarray([4, 8, 2]))
716
+
717
+ assert xp.all(output_sum == output_labels)
718
+ assert_array_almost_equal(output_labels, xp.asarray([4.0, 0.0, 5.0]))
719
+
720
+
721
+ @make_xp_test_case(ndimage.mean)
722
+ def test_mean01(xp):
723
+ labels = np.asarray([1, 0], dtype=bool)
724
+ labels = xp.asarray(labels)
725
+ for type in types:
726
+ dtype = getattr(xp, type)
727
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
728
+ output = ndimage.mean(input, labels=labels)
729
+ assert_almost_equal(output, xp.asarray(2.0), check_0d=False)
730
+
731
+
732
+ @make_xp_test_case(ndimage.mean)
733
+ def test_mean02(xp):
734
+ labels = np.asarray([1, 0], dtype=bool)
735
+ input = np.asarray([[1, 2], [3, 4]], dtype=bool)
736
+
737
+ labels = xp.asarray(labels)
738
+ input = xp.asarray(input)
739
+ output = ndimage.mean(input, labels=labels)
740
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
741
+
742
+
743
+ @make_xp_test_case(ndimage.mean)
744
+ def test_mean03(xp):
745
+ labels = xp.asarray([1, 2])
746
+ for type in types:
747
+ dtype = getattr(xp, type)
748
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
749
+ output = ndimage.mean(input, labels=labels,
750
+ index=2)
751
+ assert_almost_equal(output, xp.asarray(3.0), check_0d=False)
752
+
753
+
754
+ @make_xp_test_case(ndimage.mean)
755
+ def test_mean04(xp):
756
+ labels = xp.asarray([[1, 2], [2, 4]], dtype=xp.int8)
757
+ with np.errstate(all='ignore'):
758
+ for type in types:
759
+ dtype = getattr(xp, type)
760
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
761
+ output = ndimage.mean(input, labels=labels,
762
+ index=xp.asarray([4, 8, 2]))
763
+ # XXX: output[[0, 2]] does not work in array-api-strict; annoying
764
+ # assert_array_almost_equal(output[[0, 2]], xp.asarray([4.0, 2.5]))
765
+ assert output[0] == 4.0
766
+ assert output[2] == 2.5
767
+ assert xp.isnan(output[1])
768
+
769
+
770
+ @make_xp_test_case(ndimage.minimum)
771
+ def test_minimum01(xp):
772
+ labels = np.asarray([1, 0], dtype=bool)
773
+ labels = xp.asarray(labels)
774
+ for type in types:
775
+ dtype = getattr(xp, type)
776
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
777
+ output = ndimage.minimum(input, labels=labels)
778
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
779
+
780
+
781
+ @make_xp_test_case(ndimage.minimum)
782
+ def test_minimum02(xp):
783
+ labels = np.asarray([1, 0], dtype=bool)
784
+ input = np.asarray([[2, 2], [2, 4]], dtype=bool)
785
+
786
+ labels = xp.asarray(labels)
787
+ input = xp.asarray(input)
788
+ output = ndimage.minimum(input, labels=labels)
789
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
790
+
791
+
792
+ @make_xp_test_case(ndimage.minimum)
793
+ def test_minimum03(xp):
794
+ labels = xp.asarray([1, 2])
795
+ for type in types:
796
+ dtype = getattr(xp, type)
797
+
798
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
799
+ output = ndimage.minimum(input, labels=labels,
800
+ index=2)
801
+ assert_almost_equal(output, xp.asarray(2.0), check_0d=False)
802
+
803
+
804
+ @make_xp_test_case(ndimage.minimum)
805
+ def test_minimum04(xp):
806
+ labels = xp.asarray([[1, 2], [2, 3]])
807
+ for type in types:
808
+ dtype = getattr(xp, type)
809
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
810
+ output = ndimage.minimum(input, labels=labels,
811
+ index=xp.asarray([2, 3, 8]))
812
+ assert_array_almost_equal(output, xp.asarray([2.0, 4.0, 0.0]))
813
+
814
+
815
+ @make_xp_test_case(ndimage.maximum)
816
+ def test_maximum01(xp):
817
+ labels = np.asarray([1, 0], dtype=bool)
818
+ labels = xp.asarray(labels)
819
+ for type in types:
820
+ dtype = getattr(xp, type)
821
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
822
+ output = ndimage.maximum(input, labels=labels)
823
+ assert_almost_equal(output, xp.asarray(3.0), check_0d=False)
824
+
825
+
826
+ @make_xp_test_case(ndimage.maximum)
827
+ def test_maximum02(xp):
828
+ labels = np.asarray([1, 0], dtype=bool)
829
+ input = np.asarray([[2, 2], [2, 4]], dtype=bool)
830
+ labels = xp.asarray(labels)
831
+ input = xp.asarray(input)
832
+ output = ndimage.maximum(input, labels=labels)
833
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
834
+
835
+
836
+ @make_xp_test_case(ndimage.maximum)
837
+ def test_maximum03(xp):
838
+ labels = xp.asarray([1, 2])
839
+ for type in types:
840
+ dtype = getattr(xp, type)
841
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
842
+ output = ndimage.maximum(input, labels=labels,
843
+ index=2)
844
+ assert_almost_equal(output, xp.asarray(4.0), check_0d=False)
845
+
846
+
847
+ @make_xp_test_case(ndimage.maximum)
848
+ def test_maximum04(xp):
849
+ labels = xp.asarray([[1, 2], [2, 3]])
850
+ for type in types:
851
+ dtype = getattr(xp, type)
852
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
853
+ output = ndimage.maximum(input, labels=labels,
854
+ index=xp.asarray([2, 3, 8]))
855
+ assert_array_almost_equal(output, xp.asarray([3.0, 4.0, 0.0]))
856
+
857
+
858
+ @make_xp_test_case(ndimage.maximum)
859
+ def test_maximum05(xp):
860
+ # Regression test for ticket #501 (Trac)
861
+ x = xp.asarray([-3, -2, -1])
862
+ assert ndimage.maximum(x) == -1
863
+
864
+
865
+ @make_xp_test_case(ndimage.median)
866
+ def test_median01(xp):
867
+ a = xp.asarray([[1, 2, 0, 1],
868
+ [5, 3, 0, 4],
869
+ [0, 0, 0, 7],
870
+ [9, 3, 0, 0]])
871
+ labels = xp.asarray([[1, 1, 0, 2],
872
+ [1, 1, 0, 2],
873
+ [0, 0, 0, 2],
874
+ [3, 3, 0, 0]])
875
+ output = ndimage.median(a, labels=labels, index=xp.asarray([1, 2, 3]))
876
+ assert_array_almost_equal(output, xp.asarray([2.5, 4.0, 6.0]))
877
+
878
+
879
+ @make_xp_test_case(ndimage.median)
880
+ def test_median02(xp):
881
+ a = xp.asarray([[1, 2, 0, 1],
882
+ [5, 3, 0, 4],
883
+ [0, 0, 0, 7],
884
+ [9, 3, 0, 0]])
885
+ output = ndimage.median(a)
886
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
887
+
888
+
889
+ @make_xp_test_case(ndimage.median)
890
+ def test_median03(xp):
891
+ a = xp.asarray([[1, 2, 0, 1],
892
+ [5, 3, 0, 4],
893
+ [0, 0, 0, 7],
894
+ [9, 3, 0, 0]])
895
+ labels = xp.asarray([[1, 1, 0, 2],
896
+ [1, 1, 0, 2],
897
+ [0, 0, 0, 2],
898
+ [3, 3, 0, 0]])
899
+ output = ndimage.median(a, labels=labels)
900
+ assert_almost_equal(output, xp.asarray(3.0), check_0d=False)
901
+
902
+
903
+ @make_xp_test_case(ndimage.median)
904
+ def test_median_gh12836_bool(xp):
905
+ # test boolean addition fix on example from gh-12836
906
+ a = np.asarray([1, 1], dtype=bool)
907
+ a = xp.asarray(a)
908
+ output = ndimage.median(a, labels=xp.ones((2,)), index=xp.asarray([1]))
909
+ assert_array_almost_equal(output, xp.asarray([1.0]))
910
+
911
+
912
+ @make_xp_test_case(ndimage.median)
913
+ def test_median_no_int_overflow(xp):
914
+ # test integer overflow fix on example from gh-12836
915
+ a = xp.asarray([65, 70], dtype=xp.int8)
916
+ output = ndimage.median(a, labels=xp.ones((2,)), index=xp.asarray([1]))
917
+ assert_array_almost_equal(output, xp.asarray([67.5]))
918
+
919
+
920
+ @make_xp_test_case(ndimage.variance)
921
+ def test_variance01(xp):
922
+ with np.errstate(all='ignore'):
923
+ for type in types:
924
+ dtype = getattr(xp, type)
925
+ input = xp.asarray([], dtype=dtype)
926
+ with warnings.catch_warnings():
927
+ warnings.filterwarnings("ignore", "Mean of empty slice", RuntimeWarning)
928
+ output = ndimage.variance(input)
929
+ assert xp.isnan(output)
930
+
931
+
932
+ @make_xp_test_case(ndimage.variance)
933
+ def test_variance02(xp):
934
+ for type in types:
935
+ dtype = getattr(xp, type)
936
+ input = xp.asarray([1], dtype=dtype)
937
+ output = ndimage.variance(input)
938
+ assert_almost_equal(output, xp.asarray(0.0), check_0d=False)
939
+
940
+
941
+ @make_xp_test_case(ndimage.variance)
942
+ def test_variance03(xp):
943
+ for type in types:
944
+ dtype = getattr(xp, type)
945
+ input = xp.asarray([1, 3], dtype=dtype)
946
+ output = ndimage.variance(input)
947
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
948
+
949
+
950
+ @make_xp_test_case(ndimage.variance)
951
+ def test_variance04(xp):
952
+ input = np.asarray([1, 0], dtype=bool)
953
+ input = xp.asarray(input)
954
+ output = ndimage.variance(input)
955
+ assert_almost_equal(output, xp.asarray(0.25), check_0d=False)
956
+
957
+
958
+ @make_xp_test_case(ndimage.variance)
959
+ def test_variance05(xp):
960
+ labels = xp.asarray([2, 2, 3])
961
+ for type in types:
962
+ dtype = getattr(xp, type)
963
+
964
+ input = xp.asarray([1, 3, 8], dtype=dtype)
965
+ output = ndimage.variance(input, labels, 2)
966
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
967
+
968
+
969
+ @make_xp_test_case(ndimage.variance)
970
+ def test_variance06(xp):
971
+ labels = xp.asarray([2, 2, 3, 3, 4])
972
+ with np.errstate(all='ignore'):
973
+ for type in types:
974
+ dtype = getattr(xp, type)
975
+ input = xp.asarray([1, 3, 8, 10, 8], dtype=dtype)
976
+ output = ndimage.variance(input, labels, xp.asarray([2, 3, 4]))
977
+ assert_array_almost_equal(output, xp.asarray([1.0, 1.0, 0.0]))
978
+
979
+
980
+ @make_xp_test_case(ndimage.standard_deviation)
981
+ def test_standard_deviation01(xp):
982
+ with np.errstate(all='ignore'):
983
+ for type in types:
984
+ dtype = getattr(xp, type)
985
+ input = xp.asarray([], dtype=dtype)
986
+ with warnings.catch_warnings():
987
+ warnings.filterwarnings("ignore", "Mean of empty slice", RuntimeWarning)
988
+ output = ndimage.standard_deviation(input)
989
+ assert xp.isnan(output)
990
+
991
+
992
+ @make_xp_test_case(ndimage.standard_deviation)
993
+ def test_standard_deviation02(xp):
994
+ for type in types:
995
+ dtype = getattr(xp, type)
996
+ input = xp.asarray([1], dtype=dtype)
997
+ output = ndimage.standard_deviation(input)
998
+ assert_almost_equal(output, xp.asarray(0.0), check_0d=False)
999
+
1000
+
1001
+ @make_xp_test_case(ndimage.standard_deviation)
1002
+ def test_standard_deviation03(xp):
1003
+ for type in types:
1004
+ dtype = getattr(xp, type)
1005
+ input = xp.asarray([1, 3], dtype=dtype)
1006
+ output = ndimage.standard_deviation(input)
1007
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
1008
+
1009
+
1010
+ @make_xp_test_case(ndimage.standard_deviation)
1011
+ def test_standard_deviation04(xp):
1012
+ input = np.asarray([1, 0], dtype=bool)
1013
+ input = xp.asarray(input)
1014
+ output = ndimage.standard_deviation(input)
1015
+ assert_almost_equal(output, xp.asarray(0.5), check_0d=False)
1016
+
1017
+
1018
+ @make_xp_test_case(ndimage.standard_deviation)
1019
+ def test_standard_deviation05(xp):
1020
+ labels = xp.asarray([2, 2, 3])
1021
+ for type in types:
1022
+ dtype = getattr(xp, type)
1023
+ input = xp.asarray([1, 3, 8], dtype=dtype)
1024
+ output = ndimage.standard_deviation(input, labels, 2)
1025
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
1026
+
1027
+
1028
+ @make_xp_test_case(ndimage.standard_deviation)
1029
+ def test_standard_deviation06(xp):
1030
+ labels = xp.asarray([2, 2, 3, 3, 4])
1031
+ with np.errstate(all='ignore'):
1032
+ for type in types:
1033
+ dtype = getattr(xp, type)
1034
+ input = xp.asarray([1, 3, 8, 10, 8], dtype=dtype)
1035
+ output = ndimage.standard_deviation(
1036
+ input, labels, xp.asarray([2, 3, 4])
1037
+ )
1038
+ assert_array_almost_equal(output, xp.asarray([1.0, 1.0, 0.0]))
1039
+
1040
+
1041
+ @make_xp_test_case(ndimage.standard_deviation)
1042
+ def test_standard_deviation07(xp):
1043
+ labels = xp.asarray([1])
1044
+ with np.errstate(all='ignore'):
1045
+ for type in types:
1046
+ if is_torch(xp) and type == 'uint8':
1047
+ pytest.xfail("value cannot be converted to type uint8 "
1048
+ "without overflow")
1049
+ dtype = getattr(xp, type)
1050
+ input = xp.asarray([-0.00619519], dtype=dtype)
1051
+ output = ndimage.standard_deviation(input, labels, xp.asarray([1]))
1052
+ assert_array_almost_equal(output, xp.asarray([0]))
1053
+
1054
+
1055
+ @make_xp_test_case(ndimage.minimum_position)
1056
+ def test_minimum_position01(xp):
1057
+ labels = np.asarray([1, 0], dtype=bool)
1058
+ labels = xp.asarray(labels)
1059
+ for type in types:
1060
+ dtype = getattr(xp, type)
1061
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
1062
+ output = ndimage.minimum_position(input, labels=labels)
1063
+ assert output == (0, 0)
1064
+
1065
+
1066
+ @make_xp_test_case(ndimage.minimum_position)
1067
+ def test_minimum_position02(xp):
1068
+ for type in types:
1069
+ dtype = getattr(xp, type)
1070
+ input = xp.asarray([[5, 4, 2, 5],
1071
+ [3, 7, 0, 2],
1072
+ [1, 5, 1, 1]], dtype=dtype)
1073
+ output = ndimage.minimum_position(input)
1074
+ assert output == (1, 2)
1075
+
1076
+
1077
+ @make_xp_test_case(ndimage.minimum_position)
1078
+ def test_minimum_position03(xp):
1079
+ input = np.asarray([[5, 4, 2, 5],
1080
+ [3, 7, 0, 2],
1081
+ [1, 5, 1, 1]], dtype=bool)
1082
+ input = xp.asarray(input)
1083
+ output = ndimage.minimum_position(input)
1084
+ assert output == (1, 2)
1085
+
1086
+
1087
+ @make_xp_test_case(ndimage.minimum_position)
1088
+ def test_minimum_position04(xp):
1089
+ input = np.asarray([[5, 4, 2, 5],
1090
+ [3, 7, 1, 2],
1091
+ [1, 5, 1, 1]], dtype=bool)
1092
+ input = xp.asarray(input)
1093
+ output = ndimage.minimum_position(input)
1094
+ assert output == (0, 0)
1095
+
1096
+
1097
+ @make_xp_test_case(ndimage.minimum_position)
1098
+ def test_minimum_position05(xp):
1099
+ labels = xp.asarray([1, 2, 0, 4])
1100
+ for type in types:
1101
+ dtype = getattr(xp, type)
1102
+ input = xp.asarray([[5, 4, 2, 5],
1103
+ [3, 7, 0, 2],
1104
+ [1, 5, 2, 3]], dtype=dtype)
1105
+ output = ndimage.minimum_position(input, labels)
1106
+ assert output == (2, 0)
1107
+
1108
+
1109
+ @make_xp_test_case(ndimage.minimum_position)
1110
+ def test_minimum_position06(xp):
1111
+ labels = xp.asarray([1, 2, 3, 4])
1112
+ for type in types:
1113
+ dtype = getattr(xp, type)
1114
+ input = xp.asarray([[5, 4, 2, 5],
1115
+ [3, 7, 0, 2],
1116
+ [1, 5, 1, 1]], dtype=dtype)
1117
+ output = ndimage.minimum_position(input, labels, 2)
1118
+ assert output == (0, 1)
1119
+
1120
+
1121
+ @make_xp_test_case(ndimage.minimum_position)
1122
+ def test_minimum_position07(xp):
1123
+ labels = xp.asarray([1, 2, 3, 4])
1124
+ for type in types:
1125
+ dtype = getattr(xp, type)
1126
+ input = xp.asarray([[5, 4, 2, 5],
1127
+ [3, 7, 0, 2],
1128
+ [1, 5, 1, 1]], dtype=dtype)
1129
+ output = ndimage.minimum_position(input, labels,
1130
+ xp.asarray([2, 3]))
1131
+ assert output[0] == (0, 1)
1132
+ assert output[1] == (1, 2)
1133
+
1134
+
1135
+ @make_xp_test_case(ndimage.maximum_position)
1136
+ def test_maximum_position01(xp):
1137
+ labels = np.asarray([1, 0], dtype=bool)
1138
+ labels = xp.asarray(labels)
1139
+ for type in types:
1140
+ dtype = getattr(xp, type)
1141
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
1142
+ output = ndimage.maximum_position(input,
1143
+ labels=labels)
1144
+ assert output == (1, 0)
1145
+
1146
+
1147
+ @make_xp_test_case(ndimage.maximum_position)
1148
+ def test_maximum_position02(xp):
1149
+ for type in types:
1150
+ dtype = getattr(xp, type)
1151
+ input = xp.asarray([[5, 4, 2, 5],
1152
+ [3, 7, 8, 2],
1153
+ [1, 5, 1, 1]], dtype=dtype)
1154
+ output = ndimage.maximum_position(input)
1155
+ assert output == (1, 2)
1156
+
1157
+
1158
+ @make_xp_test_case(ndimage.maximum_position)
1159
+ def test_maximum_position03(xp):
1160
+ input = np.asarray([[5, 4, 2, 5],
1161
+ [3, 7, 8, 2],
1162
+ [1, 5, 1, 1]], dtype=bool)
1163
+ input = xp.asarray(input)
1164
+ output = ndimage.maximum_position(input)
1165
+ assert output == (0, 0)
1166
+
1167
+
1168
+ @make_xp_test_case(ndimage.maximum_position)
1169
+ def test_maximum_position04(xp):
1170
+ labels = xp.asarray([1, 2, 0, 4])
1171
+ for type in types:
1172
+ dtype = getattr(xp, type)
1173
+ input = xp.asarray([[5, 4, 2, 5],
1174
+ [3, 7, 8, 2],
1175
+ [1, 5, 1, 1]], dtype=dtype)
1176
+ output = ndimage.maximum_position(input, labels)
1177
+ assert output == (1, 1)
1178
+
1179
+
1180
+ @make_xp_test_case(ndimage.maximum_position)
1181
+ def test_maximum_position05(xp):
1182
+ labels = xp.asarray([1, 2, 0, 4])
1183
+ for type in types:
1184
+ dtype = getattr(xp, type)
1185
+ input = xp.asarray([[5, 4, 2, 5],
1186
+ [3, 7, 8, 2],
1187
+ [1, 5, 1, 1]], dtype=dtype)
1188
+ output = ndimage.maximum_position(input, labels, 1)
1189
+ assert output == (0, 0)
1190
+
1191
+
1192
+ @make_xp_test_case(ndimage.maximum_position)
1193
+ def test_maximum_position06(xp):
1194
+ labels = xp.asarray([1, 2, 0, 4])
1195
+ for type in types:
1196
+ dtype = getattr(xp, type)
1197
+ input = xp.asarray([[5, 4, 2, 5],
1198
+ [3, 7, 8, 2],
1199
+ [1, 5, 1, 1]], dtype=dtype)
1200
+ output = ndimage.maximum_position(input, labels,
1201
+ xp.asarray([1, 2]))
1202
+ assert output[0] == (0, 0)
1203
+ assert output[1] == (1, 1)
1204
+
1205
+
1206
+ @make_xp_test_case(ndimage.maximum_position)
1207
+ def test_maximum_position07(xp):
1208
+ # Test float labels
1209
+ labels = xp.asarray([1.0, 2.5, 0.0, 4.5])
1210
+ for type in types:
1211
+ dtype = getattr(xp, type)
1212
+ input = xp.asarray([[5, 4, 2, 5],
1213
+ [3, 7, 8, 2],
1214
+ [1, 5, 1, 1]], dtype=dtype)
1215
+ output = ndimage.maximum_position(input, labels,
1216
+ xp.asarray([1.0, 4.5]))
1217
+ assert output[0] == (0, 0)
1218
+ assert output[1] == (0, 3)
1219
+
1220
+
1221
+ @make_xp_test_case(ndimage.extrema, ndimage.minimum, ndimage.maximum,
1222
+ ndimage.minimum_position, ndimage.maximum_position)
1223
+ def test_extrema01(xp):
1224
+ labels = np.asarray([1, 0], dtype=bool)
1225
+ labels = xp.asarray(labels)
1226
+ for type in types:
1227
+ dtype = getattr(xp, type)
1228
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
1229
+ output1 = ndimage.extrema(input, labels=labels)
1230
+ output2 = ndimage.minimum(input, labels=labels)
1231
+ output3 = ndimage.maximum(input, labels=labels)
1232
+ output4 = ndimage.minimum_position(input,
1233
+ labels=labels)
1234
+ output5 = ndimage.maximum_position(input,
1235
+ labels=labels)
1236
+ assert output1 == (output2, output3, output4, output5)
1237
+
1238
+
1239
+ @make_xp_test_case(ndimage.extrema, ndimage.minimum, ndimage.maximum,
1240
+ ndimage.minimum_position, ndimage.maximum_position)
1241
+ def test_extrema02(xp):
1242
+ labels = xp.asarray([1, 2])
1243
+ for type in types:
1244
+ dtype = getattr(xp, type)
1245
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
1246
+ output1 = ndimage.extrema(input, labels=labels,
1247
+ index=2)
1248
+ output2 = ndimage.minimum(input, labels=labels,
1249
+ index=2)
1250
+ output3 = ndimage.maximum(input, labels=labels,
1251
+ index=2)
1252
+ output4 = ndimage.minimum_position(input,
1253
+ labels=labels, index=2)
1254
+ output5 = ndimage.maximum_position(input,
1255
+ labels=labels, index=2)
1256
+ assert output1 == (output2, output3, output4, output5)
1257
+
1258
+
1259
+ @make_xp_test_case(ndimage.extrema, ndimage.minimum, ndimage.maximum,
1260
+ ndimage.minimum_position, ndimage.maximum_position)
1261
+ def test_extrema03(xp):
1262
+ labels = xp.asarray([[1, 2], [2, 3]])
1263
+ for type in types:
1264
+ if is_torch(xp) and type in ("uint16", "uint32", "uint64"):
1265
+ pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
1266
+
1267
+ dtype = getattr(xp, type)
1268
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
1269
+ output1 = ndimage.extrema(input,
1270
+ labels=labels,
1271
+ index=xp.asarray([2, 3, 8]))
1272
+ output2 = ndimage.minimum(input,
1273
+ labels=labels,
1274
+ index=xp.asarray([2, 3, 8]))
1275
+ output3 = ndimage.maximum(input, labels=labels,
1276
+ index=xp.asarray([2, 3, 8]))
1277
+ output4 = ndimage.minimum_position(input,
1278
+ labels=labels,
1279
+ index=xp.asarray([2, 3, 8]))
1280
+ output5 = ndimage.maximum_position(input,
1281
+ labels=labels,
1282
+ index=xp.asarray([2, 3, 8]))
1283
+ assert_array_almost_equal(output1[0], output2)
1284
+ assert_array_almost_equal(output1[1], output3)
1285
+ assert output1[2] == output4
1286
+ assert output1[3] == output5
1287
+
1288
+
1289
+ @make_xp_test_case(ndimage.extrema, ndimage.minimum, ndimage.maximum,
1290
+ ndimage.minimum_position, ndimage.maximum_position)
1291
+ def test_extrema04(xp):
1292
+ labels = xp.asarray([1, 2, 0, 4])
1293
+ for type in types:
1294
+ if is_torch(xp) and type in ("uint16", "uint32", "uint64"):
1295
+ pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
1296
+
1297
+ dtype = getattr(xp, type)
1298
+ input = xp.asarray([[5, 4, 2, 5],
1299
+ [3, 7, 8, 2],
1300
+ [1, 5, 1, 1]], dtype=dtype)
1301
+ output1 = ndimage.extrema(input, labels, xp.asarray([1, 2]))
1302
+ output2 = ndimage.minimum(input, labels, xp.asarray([1, 2]))
1303
+ output3 = ndimage.maximum(input, labels, xp.asarray([1, 2]))
1304
+ output4 = ndimage.minimum_position(input, labels,
1305
+ xp.asarray([1, 2]))
1306
+ output5 = ndimage.maximum_position(input, labels,
1307
+ xp.asarray([1, 2]))
1308
+ assert_array_almost_equal(output1[0], output2)
1309
+ assert_array_almost_equal(output1[1], output3)
1310
+ assert output1[2] == output4
1311
+ assert output1[3] == output5
1312
+
1313
+
1314
+ @make_xp_test_case(ndimage.center_of_mass)
1315
+ def test_center_of_mass01(xp):
1316
+ expected = (0.0, 0.0)
1317
+ for type in types:
1318
+ dtype = getattr(xp, type)
1319
+ input = xp.asarray([[1, 0], [0, 0]], dtype=dtype)
1320
+ output = ndimage.center_of_mass(input)
1321
+ assert output == expected
1322
+
1323
+
1324
+ @make_xp_test_case(ndimage.center_of_mass)
1325
+ def test_center_of_mass02(xp):
1326
+ expected = (1, 0)
1327
+ for type in types:
1328
+ dtype = getattr(xp, type)
1329
+ input = xp.asarray([[0, 0], [1, 0]], dtype=dtype)
1330
+ output = ndimage.center_of_mass(input)
1331
+ assert output == expected
1332
+
1333
+
1334
+ @make_xp_test_case(ndimage.center_of_mass)
1335
+ def test_center_of_mass03(xp):
1336
+ expected = (0, 1)
1337
+ for type in types:
1338
+ dtype = getattr(xp, type)
1339
+ input = xp.asarray([[0, 1], [0, 0]], dtype=dtype)
1340
+ output = ndimage.center_of_mass(input)
1341
+ assert output == expected
1342
+
1343
+
1344
+ @make_xp_test_case(ndimage.center_of_mass)
1345
+ def test_center_of_mass04(xp):
1346
+ expected = (1, 1)
1347
+ for type in types:
1348
+ dtype = getattr(xp, type)
1349
+ input = xp.asarray([[0, 0], [0, 1]], dtype=dtype)
1350
+ output = ndimage.center_of_mass(input)
1351
+ assert output == expected
1352
+
1353
+
1354
+ @make_xp_test_case(ndimage.center_of_mass)
1355
+ def test_center_of_mass05(xp):
1356
+ expected = (0.5, 0.5)
1357
+ for type in types:
1358
+ dtype = getattr(xp, type)
1359
+ input = xp.asarray([[1, 1], [1, 1]], dtype=dtype)
1360
+ output = ndimage.center_of_mass(input)
1361
+ assert output == expected
1362
+
1363
+
1364
+ @make_xp_test_case(ndimage.center_of_mass)
1365
+ def test_center_of_mass06(xp):
1366
+ expected = (0.5, 0.5)
1367
+ input = np.asarray([[1, 2], [3, 1]], dtype=bool)
1368
+ input = xp.asarray(input)
1369
+ output = ndimage.center_of_mass(input)
1370
+ assert output == expected
1371
+
1372
+
1373
+ @make_xp_test_case(ndimage.center_of_mass)
1374
+ def test_center_of_mass07(xp):
1375
+ labels = xp.asarray([1, 0])
1376
+ expected = (0.5, 0.0)
1377
+ input = np.asarray([[1, 2], [3, 1]], dtype=bool)
1378
+ input = xp.asarray(input)
1379
+ output = ndimage.center_of_mass(input, labels)
1380
+ assert output == expected
1381
+
1382
+
1383
+ @make_xp_test_case(ndimage.center_of_mass)
1384
+ def test_center_of_mass08(xp):
1385
+ labels = xp.asarray([1, 2])
1386
+ expected = (0.5, 1.0)
1387
+ input = np.asarray([[5, 2], [3, 1]], dtype=bool)
1388
+ input = xp.asarray(input)
1389
+ output = ndimage.center_of_mass(input, labels, 2)
1390
+ assert output == expected
1391
+
1392
+
1393
+ @make_xp_test_case(ndimage.center_of_mass)
1394
+ def test_center_of_mass09(xp):
1395
+ labels = xp.asarray((1, 2))
1396
+ expected = xp.asarray([(0.5, 0.0), (0.5, 1.0)], dtype=xp.float64)
1397
+ input = np.asarray([[1, 2], [1, 1]], dtype=bool)
1398
+ input = xp.asarray(input)
1399
+ output = ndimage.center_of_mass(input, labels, xp.asarray([1, 2]))
1400
+ xp_assert_equal(xp.asarray(output), xp.asarray(expected))
1401
+
1402
+
1403
+ @make_xp_test_case(ndimage.histogram)
1404
+ def test_histogram01(xp):
1405
+ expected = xp.ones(10)
1406
+ input = xp.arange(10)
1407
+ output = ndimage.histogram(input, 0, 10, 10)
1408
+ assert_array_almost_equal(output, expected)
1409
+
1410
+
1411
+ @make_xp_test_case(ndimage.histogram)
1412
+ def test_histogram02(xp):
1413
+ labels = xp.asarray([1, 1, 1, 1, 2, 2, 2, 2])
1414
+ expected = xp.asarray([0, 2, 0, 1, 1])
1415
+ input = xp.asarray([1, 1, 3, 4, 3, 3, 3, 3])
1416
+ output = ndimage.histogram(input, 0, 4, 5, labels, 1)
1417
+ assert_array_almost_equal(output, expected)
1418
+
1419
+
1420
+ @skip_xp_backends(np_only=True, reason='object arrays')
1421
+ @make_xp_test_case(ndimage.histogram)
1422
+ def test_histogram03(xp):
1423
+ labels = xp.asarray([1, 0, 1, 1, 2, 2, 2, 2])
1424
+ expected1 = xp.asarray([0, 1, 0, 1, 1])
1425
+ expected2 = xp.asarray([0, 0, 0, 3, 0])
1426
+ input = xp.asarray([1, 1, 3, 4, 3, 5, 3, 3])
1427
+
1428
+ output = ndimage.histogram(input, 0, 4, 5, labels, (1, 2))
1429
+
1430
+ assert_array_almost_equal(output[0], expected1)
1431
+ assert_array_almost_equal(output[1], expected2)
1432
+
1433
+ @make_xp_test_case(ndimage.mean, ndimage.variance, ndimage.standard_deviation,
1434
+ ndimage.median, ndimage.minimum, ndimage.maximum)
1435
+ def test_stat_funcs_2d(xp):
1436
+ a = xp.asarray([[5, 6, 0, 0, 0], [8, 9, 0, 0, 0], [0, 0, 0, 3, 5]])
1437
+ lbl = xp.asarray([[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 0, 2, 2]])
1438
+
1439
+ mean = ndimage.mean(a, labels=lbl, index=xp.asarray([1, 2]))
1440
+ xp_assert_equal(mean, xp.asarray([7.0, 4.0], dtype=xp.float64))
1441
+
1442
+ var = ndimage.variance(a, labels=lbl, index=xp.asarray([1, 2]))
1443
+ xp_assert_equal(var, xp.asarray([2.5, 1.0], dtype=xp.float64))
1444
+
1445
+ std = ndimage.standard_deviation(a, labels=lbl, index=xp.asarray([1, 2]))
1446
+ assert_array_almost_equal(std, xp.sqrt(xp.asarray([2.5, 1.0], dtype=xp.float64)))
1447
+
1448
+ med = ndimage.median(a, labels=lbl, index=xp.asarray([1, 2]))
1449
+ xp_assert_equal(med, xp.asarray([7.0, 4.0], dtype=xp.float64))
1450
+
1451
+ min = ndimage.minimum(a, labels=lbl, index=xp.asarray([1, 2]))
1452
+ xp_assert_equal(min, xp.asarray([5, 3]), check_dtype=False)
1453
+
1454
+ max = ndimage.maximum(a, labels=lbl, index=xp.asarray([1, 2]))
1455
+ xp_assert_equal(max, xp.asarray([9, 5]), check_dtype=False)
1456
+
1457
+
1458
+ @skip_xp_backends("cupy", reason="no watershed_ift on CuPy")
1459
+ @make_xp_test_case(ndimage.watershed_ift)
1460
+ class TestWatershedIft:
1461
+
1462
+ def test_watershed_ift01(self, xp):
1463
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
1464
+ [0, 1, 1, 1, 1, 1, 0],
1465
+ [0, 1, 0, 0, 0, 1, 0],
1466
+ [0, 1, 0, 0, 0, 1, 0],
1467
+ [0, 1, 0, 0, 0, 1, 0],
1468
+ [0, 1, 1, 1, 1, 1, 0],
1469
+ [0, 0, 0, 0, 0, 0, 0],
1470
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
1471
+ markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0],
1472
+ [0, 0, 0, 0, 0, 0, 0],
1473
+ [0, 0, 0, 0, 0, 0, 0],
1474
+ [0, 0, 0, 1, 0, 0, 0],
1475
+ [0, 0, 0, 0, 0, 0, 0],
1476
+ [0, 0, 0, 0, 0, 0, 0],
1477
+ [0, 0, 0, 0, 0, 0, 0],
1478
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8)
1479
+ structure=xp.asarray([[1, 1, 1],
1480
+ [1, 1, 1],
1481
+ [1, 1, 1]])
1482
+ out = ndimage.watershed_ift(data, markers, structure=structure)
1483
+ expected = [[-1, -1, -1, -1, -1, -1, -1],
1484
+ [-1, 1, 1, 1, 1, 1, -1],
1485
+ [-1, 1, 1, 1, 1, 1, -1],
1486
+ [-1, 1, 1, 1, 1, 1, -1],
1487
+ [-1, 1, 1, 1, 1, 1, -1],
1488
+ [-1, 1, 1, 1, 1, 1, -1],
1489
+ [-1, -1, -1, -1, -1, -1, -1],
1490
+ [-1, -1, -1, -1, -1, -1, -1]]
1491
+ assert_array_almost_equal(out, xp.asarray(expected))
1492
+
1493
+ def test_watershed_ift02(self, xp):
1494
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
1495
+ [0, 1, 1, 1, 1, 1, 0],
1496
+ [0, 1, 0, 0, 0, 1, 0],
1497
+ [0, 1, 0, 0, 0, 1, 0],
1498
+ [0, 1, 0, 0, 0, 1, 0],
1499
+ [0, 1, 1, 1, 1, 1, 0],
1500
+ [0, 0, 0, 0, 0, 0, 0],
1501
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
1502
+ markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0],
1503
+ [0, 0, 0, 0, 0, 0, 0],
1504
+ [0, 0, 0, 0, 0, 0, 0],
1505
+ [0, 0, 0, 1, 0, 0, 0],
1506
+ [0, 0, 0, 0, 0, 0, 0],
1507
+ [0, 0, 0, 0, 0, 0, 0],
1508
+ [0, 0, 0, 0, 0, 0, 0],
1509
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8)
1510
+ out = ndimage.watershed_ift(data, markers)
1511
+ expected = [[-1, -1, -1, -1, -1, -1, -1],
1512
+ [-1, -1, 1, 1, 1, -1, -1],
1513
+ [-1, 1, 1, 1, 1, 1, -1],
1514
+ [-1, 1, 1, 1, 1, 1, -1],
1515
+ [-1, 1, 1, 1, 1, 1, -1],
1516
+ [-1, -1, 1, 1, 1, -1, -1],
1517
+ [-1, -1, -1, -1, -1, -1, -1],
1518
+ [-1, -1, -1, -1, -1, -1, -1]]
1519
+ assert_array_almost_equal(out, xp.asarray(expected))
1520
+
1521
+ def test_watershed_ift03(self, xp):
1522
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
1523
+ [0, 1, 1, 1, 1, 1, 0],
1524
+ [0, 1, 0, 1, 0, 1, 0],
1525
+ [0, 1, 0, 1, 0, 1, 0],
1526
+ [0, 1, 0, 1, 0, 1, 0],
1527
+ [0, 1, 1, 1, 1, 1, 0],
1528
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
1529
+ markers = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
1530
+ [0, 0, 0, 0, 0, 0, 0],
1531
+ [0, 0, 0, 0, 0, 0, 0],
1532
+ [0, 0, 2, 0, 3, 0, 0],
1533
+ [0, 0, 0, 0, 0, 0, 0],
1534
+ [0, 0, 0, 0, 0, 0, 0],
1535
+ [0, 0, 0, 0, 0, 0, -1]], dtype=xp.int8)
1536
+ out = ndimage.watershed_ift(data, markers)
1537
+ expected = [[-1, -1, -1, -1, -1, -1, -1],
1538
+ [-1, -1, 2, -1, 3, -1, -1],
1539
+ [-1, 2, 2, 3, 3, 3, -1],
1540
+ [-1, 2, 2, 3, 3, 3, -1],
1541
+ [-1, 2, 2, 3, 3, 3, -1],
1542
+ [-1, -1, 2, -1, 3, -1, -1],
1543
+ [-1, -1, -1, -1, -1, -1, -1]]
1544
+ assert_array_almost_equal(out, xp.asarray(expected))
1545
+
1546
+ def test_watershed_ift04(self, xp):
1547
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
1548
+ [0, 1, 1, 1, 1, 1, 0],
1549
+ [0, 1, 0, 1, 0, 1, 0],
1550
+ [0, 1, 0, 1, 0, 1, 0],
1551
+ [0, 1, 0, 1, 0, 1, 0],
1552
+ [0, 1, 1, 1, 1, 1, 0],
1553
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
1554
+ markers = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
1555
+ [0, 0, 0, 0, 0, 0, 0],
1556
+ [0, 0, 0, 0, 0, 0, 0],
1557
+ [0, 0, 2, 0, 3, 0, 0],
1558
+ [0, 0, 0, 0, 0, 0, 0],
1559
+ [0, 0, 0, 0, 0, 0, 0],
1560
+ [0, 0, 0, 0, 0, 0, -1]],
1561
+ dtype=xp.int8)
1562
+
1563
+ structure=xp.asarray([[1, 1, 1],
1564
+ [1, 1, 1],
1565
+ [1, 1, 1]])
1566
+ out = ndimage.watershed_ift(data, markers, structure=structure)
1567
+ expected = [[-1, -1, -1, -1, -1, -1, -1],
1568
+ [-1, 2, 2, 3, 3, 3, -1],
1569
+ [-1, 2, 2, 3, 3, 3, -1],
1570
+ [-1, 2, 2, 3, 3, 3, -1],
1571
+ [-1, 2, 2, 3, 3, 3, -1],
1572
+ [-1, 2, 2, 3, 3, 3, -1],
1573
+ [-1, -1, -1, -1, -1, -1, -1]]
1574
+ assert_array_almost_equal(out, xp.asarray(expected))
1575
+
1576
+ def test_watershed_ift05(self, xp):
1577
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
1578
+ [0, 1, 1, 1, 1, 1, 0],
1579
+ [0, 1, 0, 1, 0, 1, 0],
1580
+ [0, 1, 0, 1, 0, 1, 0],
1581
+ [0, 1, 0, 1, 0, 1, 0],
1582
+ [0, 1, 1, 1, 1, 1, 0],
1583
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
1584
+ markers = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
1585
+ [0, 0, 0, 0, 0, 0, 0],
1586
+ [0, 0, 0, 0, 0, 0, 0],
1587
+ [0, 0, 3, 0, 2, 0, 0],
1588
+ [0, 0, 0, 0, 0, 0, 0],
1589
+ [0, 0, 0, 0, 0, 0, 0],
1590
+ [0, 0, 0, 0, 0, 0, -1]],
1591
+ dtype=xp.int8)
1592
+ structure = xp.asarray([[1, 1, 1],
1593
+ [1, 1, 1],
1594
+ [1, 1, 1]])
1595
+ out = ndimage.watershed_ift(data, markers, structure=structure)
1596
+ expected = [[-1, -1, -1, -1, -1, -1, -1],
1597
+ [-1, 3, 3, 2, 2, 2, -1],
1598
+ [-1, 3, 3, 2, 2, 2, -1],
1599
+ [-1, 3, 3, 2, 2, 2, -1],
1600
+ [-1, 3, 3, 2, 2, 2, -1],
1601
+ [-1, 3, 3, 2, 2, 2, -1],
1602
+ [-1, -1, -1, -1, -1, -1, -1]]
1603
+ assert_array_almost_equal(out, xp.asarray(expected))
1604
+
1605
+ def test_watershed_ift06(self, xp):
1606
+ data = xp.asarray([[0, 1, 0, 0, 0, 1, 0],
1607
+ [0, 1, 0, 0, 0, 1, 0],
1608
+ [0, 1, 0, 0, 0, 1, 0],
1609
+ [0, 1, 1, 1, 1, 1, 0],
1610
+ [0, 0, 0, 0, 0, 0, 0],
1611
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
1612
+ markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0],
1613
+ [0, 0, 0, 1, 0, 0, 0],
1614
+ [0, 0, 0, 0, 0, 0, 0],
1615
+ [0, 0, 0, 0, 0, 0, 0],
1616
+ [0, 0, 0, 0, 0, 0, 0],
1617
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8)
1618
+ structure=xp.asarray([[1, 1, 1],
1619
+ [1, 1, 1],
1620
+ [1, 1, 1]])
1621
+ out = ndimage.watershed_ift(data, markers, structure=structure)
1622
+ expected = [[-1, 1, 1, 1, 1, 1, -1],
1623
+ [-1, 1, 1, 1, 1, 1, -1],
1624
+ [-1, 1, 1, 1, 1, 1, -1],
1625
+ [-1, 1, 1, 1, 1, 1, -1],
1626
+ [-1, -1, -1, -1, -1, -1, -1],
1627
+ [-1, -1, -1, -1, -1, -1, -1]]
1628
+ assert_array_almost_equal(out, xp.asarray(expected))
1629
+
1630
+ @skip_xp_backends(np_only=True, reason="inplace ops are numpy-specific")
1631
+ def test_watershed_ift07(self, xp):
1632
+ shape = (7, 6)
1633
+ data = np.zeros(shape, dtype=np.uint8)
1634
+ data = data.transpose()
1635
+ data[...] = np.asarray([[0, 1, 0, 0, 0, 1, 0],
1636
+ [0, 1, 0, 0, 0, 1, 0],
1637
+ [0, 1, 0, 0, 0, 1, 0],
1638
+ [0, 1, 1, 1, 1, 1, 0],
1639
+ [0, 0, 0, 0, 0, 0, 0],
1640
+ [0, 0, 0, 0, 0, 0, 0]], dtype=np.uint8)
1641
+ data = xp.asarray(data)
1642
+ markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0],
1643
+ [0, 0, 0, 1, 0, 0, 0],
1644
+ [0, 0, 0, 0, 0, 0, 0],
1645
+ [0, 0, 0, 0, 0, 0, 0],
1646
+ [0, 0, 0, 0, 0, 0, 0],
1647
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8)
1648
+ out = xp.zeros(shape, dtype=xp.int16)
1649
+ out = out.T
1650
+ structure=xp.asarray([[1, 1, 1],
1651
+ [1, 1, 1],
1652
+ [1, 1, 1]])
1653
+ ndimage.watershed_ift(data, markers, structure=structure,
1654
+ output=out)
1655
+ expected = [[-1, 1, 1, 1, 1, 1, -1],
1656
+ [-1, 1, 1, 1, 1, 1, -1],
1657
+ [-1, 1, 1, 1, 1, 1, -1],
1658
+ [-1, 1, 1, 1, 1, 1, -1],
1659
+ [-1, -1, -1, -1, -1, -1, -1],
1660
+ [-1, -1, -1, -1, -1, -1, -1]]
1661
+ assert_array_almost_equal(out, xp.asarray(expected))
1662
+
1663
+ @skip_xp_backends("cupy", reason="no watershed_ift on CuPy")
1664
+ def test_watershed_ift08(self, xp):
1665
+ # Test cost larger than uint8. See gh-10069.
1666
+ data = xp.asarray([[256, 0],
1667
+ [0, 0]], dtype=xp.uint16)
1668
+ markers = xp.asarray([[1, 0],
1669
+ [0, 0]], dtype=xp.int8)
1670
+ out = ndimage.watershed_ift(data, markers)
1671
+ expected = [[1, 1],
1672
+ [1, 1]]
1673
+ assert_array_almost_equal(out, xp.asarray(expected))
1674
+
1675
+ @skip_xp_backends("cupy", reason="no watershed_ift on CuPy")
1676
+ def test_watershed_ift09(self, xp):
1677
+ # Test large cost. See gh-19575
1678
+ data = xp.asarray([[xp.iinfo(xp.uint16).max, 0],
1679
+ [0, 0]], dtype=xp.uint16)
1680
+ markers = xp.asarray([[1, 0],
1681
+ [0, 0]], dtype=xp.int8)
1682
+ out = ndimage.watershed_ift(data, markers)
1683
+ expected = [[1, 1],
1684
+ [1, 1]]
1685
+ xp_assert_close(out, xp.asarray(expected), check_dtype=False)
1686
+
1687
+
1688
+ @skip_xp_backends(np_only=True)
1689
+ @pytest.mark.parametrize("dt", [np.intc, np.uintc])
1690
+ @make_xp_test_case(ndimage.value_indices)
1691
+ def test_gh_19423(dt, xp):
1692
+ rng = np.random.default_rng(123)
1693
+ max_val = 8
1694
+ image = rng.integers(low=0, high=max_val, size=(10, 12)).astype(dtype=dt)
1695
+ val_idx = ndimage.value_indices(image)
1696
+ assert len(val_idx.keys()) == max_val
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/test_morphology.py ADDED
The diff for this file is too large to render. See raw diff
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/test_ni_support.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pytest
2
+
3
+ import numpy as np
4
+ from .._ni_support import _get_output
5
+
6
+
7
+ @pytest.mark.parametrize(
8
+ 'dtype',
9
+ [
10
+ # String specifiers
11
+ 'f4', 'float32', 'complex64', 'complex128',
12
+ # Type and dtype specifiers
13
+ np.float32, float, np.dtype('f4'),
14
+ # Derive from input
15
+ None,
16
+ ],
17
+ )
18
+ def test_get_output_basic(dtype):
19
+ shape = (2, 3)
20
+
21
+ input_ = np.zeros(shape, dtype='float32')
22
+
23
+ # For None, derive dtype from input
24
+ expected_dtype = 'float32' if dtype is None else dtype
25
+
26
+ # Output is dtype-specifier, retrieve shape from input
27
+ result = _get_output(dtype, input_)
28
+ assert result.shape == shape
29
+ assert result.dtype == np.dtype(expected_dtype)
30
+
31
+ # Output is dtype specifier, with explicit shape, overriding input
32
+ result = _get_output(dtype, input_, shape=(3, 2))
33
+ assert result.shape == (3, 2)
34
+ assert result.dtype == np.dtype(expected_dtype)
35
+
36
+ # Output is pre-allocated array, return directly
37
+ output = np.zeros(shape, dtype=dtype)
38
+ result = _get_output(output, input_)
39
+ assert result is output
40
+
41
+
42
+ def test_get_output_complex():
43
+ shape = (2, 3)
44
+
45
+ input_ = np.zeros(shape)
46
+
47
+ # None, promote input type to complex
48
+ result = _get_output(None, input_, complex_output=True)
49
+ assert result.shape == shape
50
+ assert result.dtype == np.dtype('complex128')
51
+
52
+ # Explicit type, promote type to complex
53
+ with pytest.warns(UserWarning, match='promoting specified output dtype to complex'):
54
+ result = _get_output(float, input_, complex_output=True)
55
+ assert result.shape == shape
56
+ assert result.dtype == np.dtype('complex128')
57
+
58
+ # String specifier, simply verify complex output
59
+ result = _get_output('complex64', input_, complex_output=True)
60
+ assert result.shape == shape
61
+ assert result.dtype == np.dtype('complex64')
62
+
63
+
64
+ def test_get_output_error_cases():
65
+ input_ = np.zeros((2, 3), 'float32')
66
+
67
+ # Two separate paths can raise the same error
68
+ with pytest.raises(RuntimeError, match='output must have complex dtype'):
69
+ _get_output('float32', input_, complex_output=True)
70
+ with pytest.raises(RuntimeError, match='output must have complex dtype'):
71
+ _get_output(np.zeros((2, 3)), input_, complex_output=True)
72
+
73
+ with pytest.raises(RuntimeError, match='output must have numeric dtype'):
74
+ _get_output('void', input_)
75
+
76
+ with pytest.raises(RuntimeError, match='shape not correct'):
77
+ _get_output(np.zeros((3, 2)), input_)
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/ndimage/tests/test_splines.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for spline filtering."""
2
+ import pytest
3
+
4
+ import numpy as np
5
+ from scipy._lib._array_api import assert_almost_equal, make_xp_test_case
6
+
7
+ from scipy import ndimage
8
+
9
+
10
+ def get_spline_knot_values(order):
11
+ """Knot values to the right of a B-spline's center."""
12
+ knot_values = {0: [1],
13
+ 1: [1],
14
+ 2: [6, 1],
15
+ 3: [4, 1],
16
+ 4: [230, 76, 1],
17
+ 5: [66, 26, 1]}
18
+
19
+ return knot_values[order]
20
+
21
+
22
+ def make_spline_knot_matrix(xp, n, order, mode='mirror'):
23
+ """Matrix to invert to find the spline coefficients."""
24
+ knot_values = get_spline_knot_values(order)
25
+
26
+ # NB: do computations with numpy, convert to xp as the last step only
27
+
28
+ matrix = np.zeros((n, n))
29
+ for diag, knot_value in enumerate(knot_values):
30
+ indices = np.arange(diag, n)
31
+ if diag == 0:
32
+ matrix[indices, indices] = knot_value
33
+ else:
34
+ matrix[indices, indices - diag] = knot_value
35
+ matrix[indices - diag, indices] = knot_value
36
+
37
+ knot_values_sum = knot_values[0] + 2 * sum(knot_values[1:])
38
+
39
+ if mode == 'mirror':
40
+ start, step = 1, 1
41
+ elif mode == 'reflect':
42
+ start, step = 0, 1
43
+ elif mode == 'grid-wrap':
44
+ start, step = -1, -1
45
+ else:
46
+ raise ValueError(f'unsupported mode {mode}')
47
+
48
+ for row in range(len(knot_values) - 1):
49
+ for idx, knot_value in enumerate(knot_values[row + 1:]):
50
+ matrix[row, start + step*idx] += knot_value
51
+ matrix[-row - 1, -start - 1 - step*idx] += knot_value
52
+
53
+ return xp.asarray(matrix / knot_values_sum)
54
+
55
+
56
+ @make_xp_test_case(ndimage.spline_filter1d)
57
+ @pytest.mark.parametrize('order', [0, 1, 2, 3, 4, 5])
58
+ @pytest.mark.parametrize('mode', ['mirror', 'grid-wrap', 'reflect'])
59
+ def test_spline_filter_vs_matrix_solution(order, mode, xp):
60
+ n = 100
61
+ eye = xp.eye(n, dtype=xp.float64)
62
+ spline_filter_axis_0 = ndimage.spline_filter1d(eye, axis=0, order=order,
63
+ mode=mode)
64
+ spline_filter_axis_1 = ndimage.spline_filter1d(eye, axis=1, order=order,
65
+ mode=mode)
66
+ matrix = make_spline_knot_matrix(xp, n, order, mode=mode)
67
+ assert_almost_equal(eye, spline_filter_axis_0 @ matrix)
68
+ assert_almost_equal(eye, spline_filter_axis_1 @ matrix.T)
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/__init__.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ =================================================
3
+ Orthogonal distance regression (:mod:`scipy.odr`)
4
+ =================================================
5
+
6
+ .. currentmodule:: scipy.odr
7
+
8
+ .. deprecated:: 1.17.0
9
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
10
+ `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
11
+ instead.
12
+
13
+ The following example shows a brief comparison of the APIs::
14
+
15
+ import numpy as np
16
+ import scipy.odr
17
+ import odrpack
18
+
19
+ # Classic "Pearson data" that motivates ODR.
20
+ # Errors are in both variables, and if you don't account for this,
21
+ # doing a linear fit of X vs. Y or Y vs. X will give you quite
22
+ # different results.
23
+ p_x = np.array([0., .9, 1.8, 2.6, 3.3, 4.4, 5.2, 6.1, 6.5, 7.4])
24
+ p_y = np.array([5.9, 5.4, 4.4, 4.6, 3.5, 3.7, 2.8, 2.8, 2.4, 1.5])
25
+ p_sx = np.array([.03, .03, .04, .035, .07, .11, .13, .22, .74, 1.])
26
+ p_sy = np.array([1., .74, .5, .35, .22, .22, .12, .12, .1, .04])
27
+
28
+ # Old-style
29
+ # The RealData class takes care of details like turning
30
+ # standard-deviation error bars into weights.
31
+ p_dat = scipy.odr.RealData(p_x, p_y, sx=p_sx, sy=p_sy)
32
+ # Note, parameters come before `x` in scipy.odr
33
+ p_mod = scipy.odr.Model(lambda beta, x: beta[0] + beta[1]*x)
34
+ p_odr = scipy.odr.ODR(p_dat, p_mod, beta0=[1., 1.])
35
+ old_out = p_odr.run()
36
+
37
+ # New-style
38
+ # Parameters come after data, in the new API.
39
+ # We must convert the error bars into weights ourselves.
40
+ new_out = odrpack.odr_fit(lambda x, beta: beta[0] + beta[1] * x,
41
+ p_x, p_y, beta0=np.array([1.0, 1.0]),
42
+ weight_x=p_sx**-2, weight_y=p_sy**-2)
43
+
44
+ assert np.isclose(old_out.beta, new_out.beta).all()
45
+
46
+
47
+ Package Content
48
+ ===============
49
+
50
+ .. autosummary::
51
+ :toctree: generated/
52
+
53
+ Data -- The data to fit.
54
+ RealData -- Data with weights as actual std. dev.s and/or covariances.
55
+ Model -- Stores information about the function to be fit.
56
+ ODR -- Gathers all info & manages the main fitting routine.
57
+ Output -- Result from the fit.
58
+ odr -- Low-level function for ODR.
59
+
60
+ OdrWarning -- Warning about potential problems when running ODR.
61
+ OdrError -- Error exception.
62
+ OdrStop -- Stop exception.
63
+
64
+ polynomial -- Factory function for a general polynomial model.
65
+ exponential -- Exponential model
66
+ multilinear -- Arbitrary-dimensional linear model
67
+ unilinear -- Univariate linear model
68
+ quadratic -- Quadratic model
69
+
70
+ Usage information
71
+ =================
72
+
73
+ Introduction
74
+ ------------
75
+
76
+ Why Orthogonal Distance Regression (ODR)? Sometimes one has
77
+ measurement errors in the explanatory (a.k.a., "independent")
78
+ variable(s), not just the response (a.k.a., "dependent") variable(s).
79
+ Ordinary Least Squares (OLS) fitting procedures treat the data for
80
+ explanatory variables as fixed, i.e., not subject to error of any kind.
81
+ Furthermore, OLS procedures require that the response variables be an
82
+ explicit function of the explanatory variables; sometimes making the
83
+ equation explicit is impractical and/or introduces errors. ODR can
84
+ handle both of these cases with ease, and can even reduce to the OLS
85
+ case if that is sufficient for the problem.
86
+
87
+ ODRPACK is a FORTRAN-77 library for performing ODR with possibly
88
+ non-linear fitting functions. It uses a modified trust-region
89
+ Levenberg-Marquardt-type algorithm [1]_ to estimate the function
90
+ parameters. The fitting functions are provided by Python functions
91
+ operating on NumPy arrays. The required derivatives may be provided
92
+ by Python functions as well, or may be estimated numerically. ODRPACK
93
+ can do explicit or implicit ODR fits, or it can do OLS. Input and
94
+ output variables may be multidimensional. Weights can be provided to
95
+ account for different variances of the observations, and even
96
+ covariances between dimensions of the variables.
97
+
98
+ The `scipy.odr` package offers an object-oriented interface to
99
+ ODRPACK, in addition to the low-level `odr` function.
100
+
101
+ Additional background information about ODRPACK can be found in the
102
+ `ODRPACK User's Guide
103
+ <https://docs.scipy.org/doc/external/odrpack_guide.pdf>`_, reading
104
+ which is recommended.
105
+
106
+ Basic usage
107
+ -----------
108
+
109
+ 1. Define the function you want to fit against.::
110
+
111
+ def f(B, x):
112
+ '''Linear function y = m*x + b'''
113
+ # B is a vector of the parameters.
114
+ # x is an array of the current x values.
115
+ # x is in the same format as the x passed to Data or RealData.
116
+ #
117
+ # Return an array in the same format as y passed to Data or RealData.
118
+ return B[0]*x + B[1]
119
+
120
+ 2. Create a Model.::
121
+
122
+ linear = Model(f)
123
+
124
+ 3. Create a Data or RealData instance.::
125
+
126
+ mydata = Data(x, y, wd=1./power(sx,2), we=1./power(sy,2))
127
+
128
+ or, when the actual covariances are known::
129
+
130
+ mydata = RealData(x, y, sx=sx, sy=sy)
131
+
132
+ 4. Instantiate ODR with your data, model and initial parameter estimate.::
133
+
134
+ myodr = ODR(mydata, linear, beta0=[1., 2.])
135
+
136
+ 5. Run the fit.::
137
+
138
+ myoutput = myodr.run()
139
+
140
+ 6. Examine output.::
141
+
142
+ myoutput.pprint()
143
+
144
+
145
+ References
146
+ ----------
147
+ .. [1] P. T. Boggs and J. E. Rogers, "Orthogonal Distance Regression,"
148
+ in "Statistical analysis of measurement error models and
149
+ applications: proceedings of the AMS-IMS-SIAM joint summer research
150
+ conference held June 10-16, 1989," Contemporary Mathematics,
151
+ vol. 112, pg. 186, 1990.
152
+
153
+ """
154
+ # version: 0.7
155
+ # author: Robert Kern <robert.kern@gmail.com>
156
+ # date: 2006-09-21
157
+
158
+ from ._odrpack import *
159
+ from ._models import *
160
+ from . import _add_newdocs
161
+
162
+ # Deprecated namespaces, to be removed in v2.0.0
163
+ from . import models, odrpack
164
+
165
+ __all__ = [s for s in dir()
166
+ if not (s.startswith('_') or s in ('odr_stop', 'odr_error'))]
167
+
168
+ import warnings
169
+ msg = ("`scipy.odr` is deprecated as of version 1.17.0 and will be removed in "
170
+ "SciPy 1.19.0. Please use `https://pypi.org/project/odrpack/` instead.")
171
+ warnings.warn(msg, DeprecationWarning, stacklevel=2)
172
+ del warnings
173
+
174
+
175
+ from scipy._lib._testutils import PytestTester
176
+ test = PytestTester(__name__)
177
+ del PytestTester
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/__odrpack.cpython-311-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:623d8466f07cc33153eb1ce46514f406a0103e3cf40ad0971e5458df4ad07528
3
+ size 630745
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (6.79 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/__pycache__/_add_newdocs.cpython-311.pyc ADDED
Binary file (1.68 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/__pycache__/_models.cpython-311.pyc ADDED
Binary file (14.9 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/__pycache__/_odrpack.cpython-311.pyc ADDED
Binary file (51.8 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/__pycache__/models.cpython-311.pyc ADDED
Binary file (1.23 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/__pycache__/odrpack.cpython-311.pyc ADDED
Binary file (1.26 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/_add_newdocs.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from numpy.lib import add_newdoc
2
+
3
+ add_newdoc('scipy.odr', 'odr',
4
+ """
5
+ odr(fcn, beta0, y, x, we=None, wd=None, fjacb=None, fjacd=None, extra_args=None,
6
+ ifixx=None, ifixb=None, job=0, iprint=0, errfile=None, rptfile=None, ndigit=0,
7
+ taufac=0.0, sstol=-1.0, partol=-1.0, maxit=-1, stpb=None, stpd=None, sclb=None,
8
+ scld=None, work=None, iwork=None, full_output=0)
9
+
10
+ Low-level function for ODR.
11
+
12
+ .. deprecated:: 1.17.0
13
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
14
+ `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
15
+ instead.
16
+
17
+ See Also
18
+ --------
19
+ ODR : The ODR class gathers all information and coordinates the running of the
20
+ main fitting routine.
21
+ Model : The Model class stores information about the function you wish to fit.
22
+ Data : The data to fit.
23
+ RealData : Data with weights as actual std. dev.s and/or covariances.
24
+
25
+ Notes
26
+ -----
27
+ This is a function performing the same operation as the `ODR`,
28
+ `Model`, and `Data` classes together. The parameters of this
29
+ function are explained in the class documentation.
30
+
31
+ """)
32
+
33
+ add_newdoc('scipy.odr.__odrpack', '_set_exceptions',
34
+ """
35
+ _set_exceptions(odr_error, odr_stop)
36
+
37
+ Internal function: set exception classes.
38
+
39
+ """)
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/_models.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Collection of Model instances for use with the odrpack fitting package.
2
+ """
3
+ import numpy as np
4
+ from scipy.odr._odrpack import Model
5
+
6
+ __all__ = ['Model', 'exponential', 'multilinear', 'unilinear', 'quadratic',
7
+ 'polynomial']
8
+
9
+
10
+ def _lin_fcn(B, x):
11
+ a, b = B[0], B[1:]
12
+ b = b.reshape((b.shape[0], 1))
13
+
14
+ return a + (x*b).sum(axis=0)
15
+
16
+
17
+ def _lin_fjb(B, x):
18
+ a = np.ones(x.shape[-1], float)
19
+ res = np.concatenate((a, x.ravel()))
20
+ return res.reshape((B.shape[-1], x.shape[-1]))
21
+
22
+
23
+ def _lin_fjd(B, x):
24
+ b = B[1:]
25
+ b = np.repeat(b, (x.shape[-1],)*b.shape[-1], axis=0)
26
+ return b.reshape(x.shape)
27
+
28
+
29
+ def _lin_est(data):
30
+ # Eh. The answer is analytical, so just return all ones.
31
+ # Don't return zeros since that will interfere with
32
+ # ODRPACK's auto-scaling procedures.
33
+
34
+ if len(data.x.shape) == 2:
35
+ m = data.x.shape[0]
36
+ else:
37
+ m = 1
38
+
39
+ return np.ones((m + 1,), float)
40
+
41
+
42
+ def _poly_fcn(B, x, powers):
43
+ a, b = B[0], B[1:]
44
+ b = b.reshape((b.shape[0], 1))
45
+
46
+ return a + np.sum(b * np.power(x, powers), axis=0)
47
+
48
+
49
+ def _poly_fjacb(B, x, powers):
50
+ res = np.concatenate((np.ones(x.shape[-1], float),
51
+ np.power(x, powers).flat))
52
+ return res.reshape((B.shape[-1], x.shape[-1]))
53
+
54
+
55
+ def _poly_fjacd(B, x, powers):
56
+ b = B[1:]
57
+ b = b.reshape((b.shape[0], 1))
58
+
59
+ b = b * powers
60
+
61
+ return np.sum(b * np.power(x, powers-1), axis=0)
62
+
63
+
64
+ def _exp_fcn(B, x):
65
+ return B[0] + np.exp(B[1] * x)
66
+
67
+
68
+ def _exp_fjd(B, x):
69
+ return B[1] * np.exp(B[1] * x)
70
+
71
+
72
+ def _exp_fjb(B, x):
73
+ res = np.concatenate((np.ones(x.shape[-1], float), x * np.exp(B[1] * x)))
74
+ return res.reshape((2, x.shape[-1]))
75
+
76
+
77
+ def _exp_est(data):
78
+ # Eh.
79
+ return np.array([1., 1.])
80
+
81
+
82
+ class _MultilinearModel(Model):
83
+ r"""
84
+ Arbitrary-dimensional linear model
85
+
86
+ .. deprecated:: 1.17.0
87
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
88
+ `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
89
+ instead.
90
+
91
+
92
+ This model is defined by :math:`y=\beta_0 + \sum_{i=1}^m \beta_i x_i`
93
+
94
+ Examples
95
+ --------
96
+ We can calculate orthogonal distance regression with an arbitrary
97
+ dimensional linear model:
98
+
99
+ >>> from scipy import odr
100
+ >>> import numpy as np
101
+ >>> x = np.linspace(0.0, 5.0)
102
+ >>> y = 10.0 + 5.0 * x
103
+ >>> data = odr.Data(x, y)
104
+ >>> odr_obj = odr.ODR(data, odr.multilinear)
105
+ >>> output = odr_obj.run()
106
+ >>> print(output.beta)
107
+ [10. 5.]
108
+
109
+ """
110
+
111
+ def __init__(self):
112
+ super().__init__(
113
+ _lin_fcn, fjacb=_lin_fjb, fjacd=_lin_fjd, estimate=_lin_est,
114
+ meta={'name': 'Arbitrary-dimensional Linear',
115
+ 'equ': 'y = B_0 + Sum[i=1..m, B_i * x_i]',
116
+ 'TeXequ': r'$y=\beta_0 + \sum_{i=1}^m \beta_i x_i$'})
117
+
118
+
119
+ multilinear = _MultilinearModel()
120
+
121
+
122
+ def polynomial(order):
123
+ """
124
+ Factory function for a general polynomial model.
125
+
126
+ .. deprecated:: 1.17.0
127
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
128
+ `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
129
+ instead.
130
+
131
+ Parameters
132
+ ----------
133
+ order : int or sequence
134
+ If an integer, it becomes the order of the polynomial to fit. If
135
+ a sequence of numbers, then these are the explicit powers in the
136
+ polynomial.
137
+ A constant term (power 0) is always included, so don't include 0.
138
+ Thus, polynomial(n) is equivalent to polynomial(range(1, n+1)).
139
+
140
+ Returns
141
+ -------
142
+ polynomial : Model instance
143
+ Model instance.
144
+
145
+ Examples
146
+ --------
147
+ We can fit an input data using orthogonal distance regression (ODR) with
148
+ a polynomial model:
149
+
150
+ >>> import numpy as np
151
+ >>> import matplotlib.pyplot as plt
152
+ >>> from scipy import odr
153
+ >>> x = np.linspace(0.0, 5.0)
154
+ >>> y = np.sin(x)
155
+ >>> poly_model = odr.polynomial(3) # using third order polynomial model
156
+ >>> data = odr.Data(x, y)
157
+ >>> odr_obj = odr.ODR(data, poly_model)
158
+ >>> output = odr_obj.run() # running ODR fitting
159
+ >>> poly = np.poly1d(output.beta[::-1])
160
+ >>> poly_y = poly(x)
161
+ >>> plt.plot(x, y, label="input data")
162
+ >>> plt.plot(x, poly_y, label="polynomial ODR")
163
+ >>> plt.legend()
164
+ >>> plt.show()
165
+
166
+ """
167
+
168
+ powers = np.asarray(order)
169
+ if powers.shape == ():
170
+ # Scalar.
171
+ powers = np.arange(1, powers + 1)
172
+
173
+ powers = powers.reshape((len(powers), 1))
174
+ len_beta = len(powers) + 1
175
+
176
+ def _poly_est(data, len_beta=len_beta):
177
+ # Eh. Ignore data and return all ones.
178
+ return np.ones((len_beta,), float)
179
+
180
+ return Model(_poly_fcn, fjacd=_poly_fjacd, fjacb=_poly_fjacb,
181
+ estimate=_poly_est, extra_args=(powers,),
182
+ meta={'name': 'Sorta-general Polynomial',
183
+ 'equ': 'y = B_0 + Sum[i=1..%s, B_i * (x**i)]' % (len_beta-1),
184
+ 'TeXequ': r'$y=\beta_0 + \sum_{i=1}^{%s} \beta_i x^i$' %
185
+ (len_beta-1)})
186
+
187
+
188
+ class _ExponentialModel(Model):
189
+ r"""
190
+ Exponential model
191
+
192
+ .. deprecated:: 1.17.0
193
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
194
+ `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
195
+ instead.
196
+
197
+ This model is defined by :math:`y=\beta_0 + e^{\beta_1 x}`
198
+
199
+ Examples
200
+ --------
201
+ We can calculate orthogonal distance regression with an exponential model:
202
+
203
+ >>> from scipy import odr
204
+ >>> import numpy as np
205
+ >>> x = np.linspace(0.0, 5.0)
206
+ >>> y = -10.0 + np.exp(0.5*x)
207
+ >>> data = odr.Data(x, y)
208
+ >>> odr_obj = odr.ODR(data, odr.exponential)
209
+ >>> output = odr_obj.run()
210
+ >>> print(output.beta)
211
+ [-10. 0.5]
212
+
213
+ """
214
+
215
+ def __init__(self):
216
+ super().__init__(_exp_fcn, fjacd=_exp_fjd, fjacb=_exp_fjb,
217
+ estimate=_exp_est,
218
+ meta={'name': 'Exponential',
219
+ 'equ': 'y= B_0 + exp(B_1 * x)',
220
+ 'TeXequ': r'$y=\beta_0 + e^{\beta_1 x}$'})
221
+
222
+
223
+ exponential = _ExponentialModel()
224
+
225
+
226
+ def _unilin(B, x):
227
+ return x*B[0] + B[1]
228
+
229
+
230
+ def _unilin_fjd(B, x):
231
+ return np.ones(x.shape, float) * B[0]
232
+
233
+
234
+ def _unilin_fjb(B, x):
235
+ _ret = np.concatenate((x, np.ones(x.shape, float)))
236
+ return _ret.reshape((2,) + x.shape)
237
+
238
+
239
+ def _unilin_est(data):
240
+ return (1., 1.)
241
+
242
+
243
+ def _quadratic(B, x):
244
+ return x*(x*B[0] + B[1]) + B[2]
245
+
246
+
247
+ def _quad_fjd(B, x):
248
+ return 2*x*B[0] + B[1]
249
+
250
+
251
+ def _quad_fjb(B, x):
252
+ _ret = np.concatenate((x*x, x, np.ones(x.shape, float)))
253
+ return _ret.reshape((3,) + x.shape)
254
+
255
+
256
+ def _quad_est(data):
257
+ return (1.,1.,1.)
258
+
259
+
260
+ class _UnilinearModel(Model):
261
+ r"""
262
+ Univariate linear model
263
+
264
+ .. deprecated:: 1.17.0
265
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
266
+ `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
267
+ instead.
268
+
269
+ This model is defined by :math:`y = \beta_0 x + \beta_1`
270
+
271
+ Examples
272
+ --------
273
+ We can calculate orthogonal distance regression with an unilinear model:
274
+
275
+ >>> from scipy import odr
276
+ >>> import numpy as np
277
+ >>> x = np.linspace(0.0, 5.0)
278
+ >>> y = 1.0 * x + 2.0
279
+ >>> data = odr.Data(x, y)
280
+ >>> odr_obj = odr.ODR(data, odr.unilinear)
281
+ >>> output = odr_obj.run()
282
+ >>> print(output.beta)
283
+ [1. 2.]
284
+
285
+ """
286
+
287
+ def __init__(self):
288
+ super().__init__(_unilin, fjacd=_unilin_fjd, fjacb=_unilin_fjb,
289
+ estimate=_unilin_est,
290
+ meta={'name': 'Univariate Linear',
291
+ 'equ': 'y = B_0 * x + B_1',
292
+ 'TeXequ': '$y = \\beta_0 x + \\beta_1$'})
293
+
294
+
295
+ unilinear = _UnilinearModel()
296
+
297
+
298
+ class _QuadraticModel(Model):
299
+ r"""
300
+ Quadratic model
301
+
302
+ .. deprecated:: 1.17.0
303
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
304
+ `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
305
+ instead.
306
+
307
+ This model is defined by :math:`y = \beta_0 x^2 + \beta_1 x + \beta_2`
308
+
309
+ Examples
310
+ --------
311
+ We can calculate orthogonal distance regression with a quadratic model:
312
+
313
+ >>> from scipy import odr
314
+ >>> import numpy as np
315
+ >>> x = np.linspace(0.0, 5.0)
316
+ >>> y = 1.0 * x ** 2 + 2.0 * x + 3.0
317
+ >>> data = odr.Data(x, y)
318
+ >>> odr_obj = odr.ODR(data, odr.quadratic)
319
+ >>> output = odr_obj.run()
320
+ >>> print(output.beta)
321
+ [1. 2. 3.]
322
+
323
+ """
324
+
325
+ def __init__(self):
326
+ super().__init__(
327
+ _quadratic, fjacd=_quad_fjd, fjacb=_quad_fjb, estimate=_quad_est,
328
+ meta={'name': 'Quadratic',
329
+ 'equ': 'y = B_0*x**2 + B_1*x + B_2',
330
+ 'TeXequ': '$y = \\beta_0 x^2 + \\beta_1 x + \\beta_2'})
331
+
332
+
333
+ quadratic = _QuadraticModel()
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/_odrpack.py ADDED
@@ -0,0 +1,1200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Python wrappers for Orthogonal Distance Regression (ODRPACK).
3
+
4
+ Notes
5
+ =====
6
+
7
+ * Array formats -- FORTRAN stores its arrays in memory column first, i.e., an
8
+ array element A(i, j, k) will be next to A(i+1, j, k). In C and, consequently,
9
+ NumPy, arrays are stored row first: A[i, j, k] is next to A[i, j, k+1]. For
10
+ efficiency and convenience, the input and output arrays of the fitting
11
+ function (and its Jacobians) are passed to FORTRAN without transposition.
12
+ Therefore, where the ODRPACK documentation says that the X array is of shape
13
+ (N, M), it will be passed to the Python function as an array of shape (M, N).
14
+ If M==1, the 1-D case, then nothing matters; if M>1, then your
15
+ Python functions will be dealing with arrays that are indexed in reverse of
16
+ the ODRPACK documentation. No real issue, but watch out for your indexing of
17
+ the Jacobians: the i,jth elements (@f_i/@x_j) evaluated at the nth
18
+ observation will be returned as jacd[j, i, n]. Except for the Jacobians, it
19
+ really is easier to deal with x[0] and x[1] than x[:,0] and x[:,1]. Of course,
20
+ you can always use the transpose() function from SciPy explicitly.
21
+
22
+ * Examples -- See the accompanying file test/test.py for examples of how to set
23
+ up fits of your own. Some are taken from the User's Guide; some are from
24
+ other sources.
25
+
26
+ * Models -- Some common models are instantiated in the accompanying module
27
+ models.py . Contributions are welcome.
28
+
29
+ Credits
30
+ =======
31
+
32
+ * Thanks to Arnold Moene and Gerard Vermeulen for fixing some killer bugs.
33
+
34
+ Robert Kern
35
+ robert.kern@gmail.com
36
+
37
+ """
38
+ import os
39
+ from threading import Lock
40
+
41
+ import numpy as np
42
+ from warnings import warn
43
+ from scipy.odr import __odrpack
44
+
45
+ __all__ = ['odr', 'OdrWarning', 'OdrError', 'OdrStop',
46
+ 'Data', 'RealData', 'Model', 'Output', 'ODR',
47
+ 'odr_error', 'odr_stop']
48
+
49
+ odr = __odrpack.odr
50
+ ODR_LOCK = Lock()
51
+
52
+
53
+ class OdrWarning(UserWarning):
54
+ """
55
+ Warning indicating that the data passed into
56
+ ODR will cause problems when passed into 'odr'
57
+ that the user should be aware of.
58
+
59
+ .. deprecated:: 1.17.0
60
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
61
+ `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
62
+ instead.
63
+
64
+ """
65
+ pass
66
+
67
+
68
+ class OdrError(Exception):
69
+ """
70
+ Exception indicating an error in fitting.
71
+
72
+ .. deprecated:: 1.17.0
73
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
74
+ `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
75
+ instead.
76
+
77
+
78
+ This is raised by `~scipy.odr.odr` if an error occurs during fitting.
79
+ """
80
+ pass
81
+
82
+
83
+ class OdrStop(Exception):
84
+ """
85
+ Exception stopping fitting.
86
+
87
+ .. deprecated:: 1.17.0
88
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
89
+ `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
90
+ instead.
91
+
92
+
93
+ You can raise this exception in your objective function to tell
94
+ `~scipy.odr.odr` to stop fitting.
95
+ """
96
+ pass
97
+
98
+
99
+ # Backwards compatibility
100
+ odr_error = OdrError
101
+ odr_stop = OdrStop
102
+
103
+ __odrpack._set_exceptions(OdrError, OdrStop)
104
+
105
+
106
+ def _conv(obj, dtype=None):
107
+ """ Convert an object to the preferred form for input to the odr routine.
108
+ """
109
+
110
+ if obj is None:
111
+ return obj
112
+ else:
113
+ if dtype is None:
114
+ obj = np.asarray(obj)
115
+ else:
116
+ obj = np.asarray(obj, dtype)
117
+ if obj.shape == ():
118
+ # Scalar.
119
+ return obj.dtype.type(obj)
120
+ else:
121
+ return obj
122
+
123
+
124
+ def _report_error(info):
125
+ """ Interprets the return code of the odr routine.
126
+
127
+ Parameters
128
+ ----------
129
+ info : int
130
+ The return code of the odr routine.
131
+
132
+ Returns
133
+ -------
134
+ problems : list(str)
135
+ A list of messages about why the odr() routine stopped.
136
+ """
137
+
138
+ stopreason = ('Blank',
139
+ 'Sum of squares convergence',
140
+ 'Parameter convergence',
141
+ 'Both sum of squares and parameter convergence',
142
+ 'Iteration limit reached')[info % 5]
143
+
144
+ if info >= 5:
145
+ # questionable results or fatal error
146
+
147
+ I = (info//10000 % 10,
148
+ info//1000 % 10,
149
+ info//100 % 10,
150
+ info//10 % 10,
151
+ info % 10)
152
+ problems = []
153
+
154
+ if I[0] == 0:
155
+ if I[1] != 0:
156
+ problems.append('Derivatives possibly not correct')
157
+ if I[2] != 0:
158
+ problems.append('Error occurred in callback')
159
+ if I[3] != 0:
160
+ problems.append('Problem is not full rank at solution')
161
+ problems.append(stopreason)
162
+ elif I[0] == 1:
163
+ if I[1] != 0:
164
+ problems.append('N < 1')
165
+ if I[2] != 0:
166
+ problems.append('M < 1')
167
+ if I[3] != 0:
168
+ problems.append('NP < 1 or NP > N')
169
+ if I[4] != 0:
170
+ problems.append('NQ < 1')
171
+ elif I[0] == 2:
172
+ if I[1] != 0:
173
+ problems.append('LDY and/or LDX incorrect')
174
+ if I[2] != 0:
175
+ problems.append('LDWE, LD2WE, LDWD, and/or LD2WD incorrect')
176
+ if I[3] != 0:
177
+ problems.append('LDIFX, LDSTPD, and/or LDSCLD incorrect')
178
+ if I[4] != 0:
179
+ problems.append('LWORK and/or LIWORK too small')
180
+ elif I[0] == 3:
181
+ if I[1] != 0:
182
+ problems.append('STPB and/or STPD incorrect')
183
+ if I[2] != 0:
184
+ problems.append('SCLB and/or SCLD incorrect')
185
+ if I[3] != 0:
186
+ problems.append('WE incorrect')
187
+ if I[4] != 0:
188
+ problems.append('WD incorrect')
189
+ elif I[0] == 4:
190
+ problems.append('Error in derivatives')
191
+ elif I[0] == 5:
192
+ problems.append('Error occurred in callback')
193
+ elif I[0] == 6:
194
+ problems.append('Numerical error detected')
195
+
196
+ return problems
197
+
198
+ else:
199
+ return [stopreason]
200
+
201
+
202
+ class Data:
203
+ """
204
+ The data to fit.
205
+
206
+ .. deprecated:: 1.17.0
207
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
208
+ `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
209
+ instead.
210
+
211
+ Parameters
212
+ ----------
213
+ x : array_like
214
+ Observed data for the independent variable of the regression
215
+ y : array_like, optional
216
+ If array-like, observed data for the dependent variable of the
217
+ regression. A scalar input implies that the model to be used on
218
+ the data is implicit.
219
+ we : array_like, optional
220
+ If `we` is a scalar, then that value is used for all data points (and
221
+ all dimensions of the response variable).
222
+ If `we` is a rank-1 array of length q (the dimensionality of the
223
+ response variable), then this vector is the diagonal of the covariant
224
+ weighting matrix for all data points.
225
+ If `we` is a rank-1 array of length n (the number of data points), then
226
+ the i'th element is the weight for the i'th response variable
227
+ observation (single-dimensional only).
228
+ If `we` is a rank-2 array of shape (q, q), then this is the full
229
+ covariant weighting matrix broadcast to each observation.
230
+ If `we` is a rank-2 array of shape (q, n), then `we[:,i]` is the
231
+ diagonal of the covariant weighting matrix for the i'th observation.
232
+ If `we` is a rank-3 array of shape (q, q, n), then `we[:,:,i]` is the
233
+ full specification of the covariant weighting matrix for each
234
+ observation.
235
+ If the fit is implicit, then only a positive scalar value is used.
236
+ wd : array_like, optional
237
+ If `wd` is a scalar, then that value is used for all data points
238
+ (and all dimensions of the input variable). If `wd` = 0, then the
239
+ covariant weighting matrix for each observation is set to the identity
240
+ matrix (so each dimension of each observation has the same weight).
241
+ If `wd` is a rank-1 array of length m (the dimensionality of the input
242
+ variable), then this vector is the diagonal of the covariant weighting
243
+ matrix for all data points.
244
+ If `wd` is a rank-1 array of length n (the number of data points), then
245
+ the i'th element is the weight for the ith input variable observation
246
+ (single-dimensional only).
247
+ If `wd` is a rank-2 array of shape (m, m), then this is the full
248
+ covariant weighting matrix broadcast to each observation.
249
+ If `wd` is a rank-2 array of shape (m, n), then `wd[:,i]` is the
250
+ diagonal of the covariant weighting matrix for the ith observation.
251
+ If `wd` is a rank-3 array of shape (m, m, n), then `wd[:,:,i]` is the
252
+ full specification of the covariant weighting matrix for each
253
+ observation.
254
+ fix : array_like of ints, optional
255
+ The `fix` argument is the same as ifixx in the class ODR. It is an
256
+ array of integers with the same shape as data.x that determines which
257
+ input observations are treated as fixed. One can use a sequence of
258
+ length m (the dimensionality of the input observations) to fix some
259
+ dimensions for all observations. A value of 0 fixes the observation,
260
+ a value > 0 makes it free.
261
+ meta : dict, optional
262
+ Free-form dictionary for metadata.
263
+
264
+ Notes
265
+ -----
266
+ Each argument is attached to the member of the instance of the same name.
267
+ The structures of `x` and `y` are described in the Model class docstring.
268
+ If `y` is an integer, then the Data instance can only be used to fit with
269
+ implicit models where the dimensionality of the response is equal to the
270
+ specified value of `y`.
271
+
272
+ The `we` argument weights the effect a deviation in the response variable
273
+ has on the fit. The `wd` argument weights the effect a deviation in the
274
+ input variable has on the fit. To handle multidimensional inputs and
275
+ responses easily, the structure of these arguments has the n'th
276
+ dimensional axis first. These arguments heavily use the structured
277
+ arguments feature of ODRPACK to conveniently and flexibly support all
278
+ options. See the ODRPACK User's Guide for a full explanation of how these
279
+ weights are used in the algorithm. Basically, a higher value of the weight
280
+ for a particular data point makes a deviation at that point more
281
+ detrimental to the fit.
282
+
283
+ """
284
+
285
+ def __init__(self, x, y=None, we=None, wd=None, fix=None, meta=None):
286
+ self.x = _conv(x)
287
+
288
+ if not isinstance(self.x, np.ndarray):
289
+ raise ValueError("Expected an 'ndarray' of data for 'x', "
290
+ f"but instead got data of type '{type(self.x).__name__}'")
291
+
292
+ self.y = _conv(y)
293
+ self.we = _conv(we)
294
+ self.wd = _conv(wd)
295
+ self.fix = _conv(fix)
296
+ self.meta = {} if meta is None else meta
297
+
298
+ def set_meta(self, **kwds):
299
+ """ Update the metadata dictionary with the keywords and data provided
300
+ by keywords.
301
+
302
+ Examples
303
+ --------
304
+ ::
305
+
306
+ data.set_meta(lab="Ph 7; Lab 26", title="Ag110 + Ag108 Decay")
307
+ """
308
+
309
+ self.meta.update(kwds)
310
+
311
+ def __getattr__(self, attr):
312
+ """ Dispatch attribute access to the metadata dictionary.
313
+ """
314
+ if attr != "meta" and attr in self.meta:
315
+ return self.meta[attr]
316
+ else:
317
+ raise AttributeError(f"'{attr}' not in metadata")
318
+
319
+
320
+ class RealData(Data):
321
+ """
322
+ The data, with weightings as actual standard deviations and/or
323
+ covariances.
324
+
325
+ .. deprecated:: 1.17.0
326
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
327
+ `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
328
+ instead.
329
+
330
+ Parameters
331
+ ----------
332
+ x : array_like
333
+ Observed data for the independent variable of the regression
334
+ y : array_like, optional
335
+ If array-like, observed data for the dependent variable of the
336
+ regression. A scalar input implies that the model to be used on
337
+ the data is implicit.
338
+ sx : array_like, optional
339
+ Standard deviations of `x`.
340
+ `sx` are standard deviations of `x` and are converted to weights by
341
+ dividing 1.0 by their squares.
342
+ sy : array_like, optional
343
+ Standard deviations of `y`.
344
+ `sy` are standard deviations of `y` and are converted to weights by
345
+ dividing 1.0 by their squares.
346
+ covx : array_like, optional
347
+ Covariance of `x`
348
+ `covx` is an array of covariance matrices of `x` and are converted to
349
+ weights by performing a matrix inversion on each observation's
350
+ covariance matrix.
351
+ covy : array_like, optional
352
+ Covariance of `y`
353
+ `covy` is an array of covariance matrices and are converted to
354
+ weights by performing a matrix inversion on each observation's
355
+ covariance matrix.
356
+ fix : array_like, optional
357
+ The argument and member fix is the same as Data.fix and ODR.ifixx:
358
+ It is an array of integers with the same shape as `x` that
359
+ determines which input observations are treated as fixed. One can
360
+ use a sequence of length m (the dimensionality of the input
361
+ observations) to fix some dimensions for all observations. A value
362
+ of 0 fixes the observation, a value > 0 makes it free.
363
+ meta : dict, optional
364
+ Free-form dictionary for metadata.
365
+
366
+ Notes
367
+ -----
368
+ The weights `wd` and `we` are computed from provided values as follows:
369
+
370
+ `sx` and `sy` are converted to weights by dividing 1.0 by their squares.
371
+ For example, ``wd = 1./np.power(`sx`, 2)``.
372
+
373
+ `covx` and `covy` are arrays of covariance matrices and are converted to
374
+ weights by performing a matrix inversion on each observation's covariance
375
+ matrix. For example, ``we[i] = np.linalg.inv(covy[i])``.
376
+
377
+ These arguments follow the same structured argument conventions as wd and
378
+ we only restricted by their natures: `sx` and `sy` can't be rank-3, but
379
+ `covx` and `covy` can be.
380
+
381
+ Only set *either* `sx` or `covx` (not both). Setting both will raise an
382
+ exception. Same with `sy` and `covy`.
383
+
384
+ """
385
+
386
+ def __init__(self, x, y=None, sx=None, sy=None, covx=None, covy=None,
387
+ fix=None, meta=None):
388
+ if (sx is not None) and (covx is not None):
389
+ raise ValueError("cannot set both sx and covx")
390
+ if (sy is not None) and (covy is not None):
391
+ raise ValueError("cannot set both sy and covy")
392
+
393
+ # Set flags for __getattr__
394
+ self._ga_flags = {}
395
+ if sx is not None:
396
+ self._ga_flags['wd'] = 'sx'
397
+ else:
398
+ self._ga_flags['wd'] = 'covx'
399
+ if sy is not None:
400
+ self._ga_flags['we'] = 'sy'
401
+ else:
402
+ self._ga_flags['we'] = 'covy'
403
+
404
+ self.x = _conv(x)
405
+
406
+ if not isinstance(self.x, np.ndarray):
407
+ raise ValueError("Expected an 'ndarray' of data for 'x', "
408
+ f"but instead got data of type '{type(self.x).__name__}'")
409
+
410
+ self.y = _conv(y)
411
+ self.sx = _conv(sx)
412
+ self.sy = _conv(sy)
413
+ self.covx = _conv(covx)
414
+ self.covy = _conv(covy)
415
+ self.fix = _conv(fix)
416
+ self.meta = {} if meta is None else meta
417
+
418
+ def _sd2wt(self, sd):
419
+ """ Convert standard deviation to weights.
420
+ """
421
+
422
+ return 1./np.power(sd, 2)
423
+
424
+ def _cov2wt(self, cov):
425
+ """ Convert covariance matrix(-ices) to weights.
426
+ """
427
+
428
+ from scipy.linalg import inv
429
+
430
+ if len(cov.shape) == 2:
431
+ return inv(cov)
432
+ else:
433
+ weights = np.zeros(cov.shape, float)
434
+
435
+ for i in range(cov.shape[-1]): # n
436
+ weights[:,:,i] = inv(cov[:,:,i])
437
+
438
+ return weights
439
+
440
+ def __getattr__(self, attr):
441
+
442
+ if attr not in ('wd', 'we'):
443
+ if attr != "meta" and attr in self.meta:
444
+ return self.meta[attr]
445
+ else:
446
+ raise AttributeError(f"'{attr}' not in metadata")
447
+ else:
448
+ lookup_tbl = {('wd', 'sx'): (self._sd2wt, self.sx),
449
+ ('wd', 'covx'): (self._cov2wt, self.covx),
450
+ ('we', 'sy'): (self._sd2wt, self.sy),
451
+ ('we', 'covy'): (self._cov2wt, self.covy)}
452
+
453
+ func, arg = lookup_tbl[(attr, self._ga_flags[attr])]
454
+
455
+ if arg is not None:
456
+ return func(*(arg,))
457
+ else:
458
+ return None
459
+
460
+
461
+ class Model:
462
+ """
463
+ The Model class stores information about the function you wish to fit.
464
+
465
+ .. deprecated:: 1.17.0
466
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
467
+ `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
468
+ instead.
469
+
470
+ It stores the function itself, at the least, and optionally stores
471
+ functions which compute the Jacobians used during fitting. Also, one
472
+ can provide a function that will provide reasonable starting values
473
+ for the fit parameters possibly given the set of data.
474
+
475
+ Parameters
476
+ ----------
477
+ fcn : function
478
+ fcn(beta, x) --> y
479
+ fjacb : function
480
+ Jacobian of fcn wrt the fit parameters beta.
481
+
482
+ fjacb(beta, x) --> @f_i(x,B)/@B_j
483
+ fjacd : function
484
+ Jacobian of fcn wrt the (possibly multidimensional) input
485
+ variable.
486
+
487
+ fjacd(beta, x) --> @f_i(x,B)/@x_j
488
+ extra_args : tuple, optional
489
+ If specified, `extra_args` should be a tuple of extra
490
+ arguments to pass to `fcn`, `fjacb`, and `fjacd`. Each will be called
491
+ by `apply(fcn, (beta, x) + extra_args)`
492
+ estimate : array_like of rank-1
493
+ Provides estimates of the fit parameters from the data
494
+
495
+ estimate(data) --> estbeta
496
+ implicit : boolean
497
+ If TRUE, specifies that the model
498
+ is implicit; i.e `fcn(beta, x)` ~= 0 and there is no y data to fit
499
+ against
500
+ meta : dict, optional
501
+ freeform dictionary of metadata for the model
502
+
503
+ Notes
504
+ -----
505
+ Note that the `fcn`, `fjacb`, and `fjacd` operate on NumPy arrays and
506
+ return a NumPy array. The `estimate` object takes an instance of the
507
+ Data class.
508
+
509
+ Here are the rules for the shapes of the argument and return
510
+ arrays of the callback functions:
511
+
512
+ `x`
513
+ if the input data is single-dimensional, then `x` is rank-1
514
+ array; i.e., ``x = array([1, 2, 3, ...]); x.shape = (n,)``
515
+ If the input data is multi-dimensional, then `x` is a rank-2 array;
516
+ i.e., ``x = array([[1, 2, ...], [2, 4, ...]]); x.shape = (m, n)``.
517
+ In all cases, it has the same shape as the input data array passed to
518
+ `~scipy.odr.odr`. `m` is the dimensionality of the input data,
519
+ `n` is the number of observations.
520
+ `y`
521
+ if the response variable is single-dimensional, then `y` is a
522
+ rank-1 array, i.e., ``y = array([2, 4, ...]); y.shape = (n,)``.
523
+ If the response variable is multi-dimensional, then `y` is a rank-2
524
+ array, i.e., ``y = array([[2, 4, ...], [3, 6, ...]]); y.shape =
525
+ (q, n)`` where `q` is the dimensionality of the response variable.
526
+ `beta`
527
+ rank-1 array of length `p` where `p` is the number of parameters;
528
+ i.e. ``beta = array([B_1, B_2, ..., B_p])``
529
+ `fjacb`
530
+ if the response variable is multi-dimensional, then the
531
+ return array's shape is ``(q, p, n)`` such that ``fjacb(beta,x)[l,k,i] =
532
+ d f_l(beta,x)/d B_k`` evaluated at the ith data point. If ``q == 1``, then
533
+ the return array is only rank-2 and with shape ``(p, n)``.
534
+ `fjacd`
535
+ as with fjacb, only the return array's shape is ``(q, m, n)``
536
+ such that ``fjacd(beta,x)[l,j,i] = d f_l(beta,x)/d X_j`` at the ith data
537
+ point. If ``q == 1``, then the return array's shape is ``(m, n)``. If
538
+ ``m == 1``, the shape is (q, n). If `m == q == 1`, the shape is ``(n,)``.
539
+
540
+ """
541
+
542
+ def __init__(self, fcn, fjacb=None, fjacd=None,
543
+ extra_args=None, estimate=None, implicit=0, meta=None):
544
+
545
+ self.fcn = fcn
546
+ self.fjacb = fjacb
547
+ self.fjacd = fjacd
548
+
549
+ if extra_args is not None:
550
+ extra_args = tuple(extra_args)
551
+
552
+ self.extra_args = extra_args
553
+ self.estimate = estimate
554
+ self.implicit = implicit
555
+ self.meta = meta if meta is not None else {}
556
+
557
+ def set_meta(self, **kwds):
558
+ """ Update the metadata dictionary with the keywords and data provided
559
+ here.
560
+
561
+ Examples
562
+ --------
563
+ set_meta(name="Exponential", equation="y = a exp(b x) + c")
564
+ """
565
+
566
+ self.meta.update(kwds)
567
+
568
+ def __getattr__(self, attr):
569
+ """ Dispatch attribute access to the metadata.
570
+ """
571
+
572
+ if attr != "meta" and attr in self.meta:
573
+ return self.meta[attr]
574
+ else:
575
+ raise AttributeError(f"'{attr}' not in metadata")
576
+
577
+
578
+ class Output:
579
+ """
580
+ The Output class stores the output of an ODR run.
581
+
582
+ .. deprecated:: 1.17.0
583
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
584
+ `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
585
+ instead.
586
+
587
+ Attributes
588
+ ----------
589
+ beta : ndarray
590
+ Estimated parameter values, of shape (q,).
591
+ sd_beta : ndarray
592
+ Standard deviations of the estimated parameters, of shape (p,).
593
+ cov_beta : ndarray
594
+ Covariance matrix of the estimated parameters, of shape (p,p).
595
+ Note that this `cov_beta` is not scaled by the residual variance
596
+ `res_var`, whereas `sd_beta` is. This means
597
+ ``np.sqrt(np.diag(output.cov_beta * output.res_var))`` is the same
598
+ result as `output.sd_beta`.
599
+ delta : ndarray, optional
600
+ Array of estimated errors in input variables, of same shape as `x`.
601
+ eps : ndarray, optional
602
+ Array of estimated errors in response variables, of same shape as `y`.
603
+ xplus : ndarray, optional
604
+ Array of ``x + delta``.
605
+ y : ndarray, optional
606
+ Array ``y = fcn(x + delta)``.
607
+ res_var : float, optional
608
+ Residual variance.
609
+ sum_square : float, optional
610
+ Sum of squares error.
611
+ sum_square_delta : float, optional
612
+ Sum of squares of delta error.
613
+ sum_square_eps : float, optional
614
+ Sum of squares of eps error.
615
+ inv_condnum : float, optional
616
+ Inverse condition number (cf. ODRPACK UG p. 77).
617
+ rel_error : float, optional
618
+ Relative error in function values computed within fcn.
619
+ work : ndarray, optional
620
+ Final work array.
621
+ work_ind : dict, optional
622
+ Indices into work for drawing out values (cf. ODRPACK UG p. 83).
623
+ info : int, optional
624
+ Reason for returning, as output by ODRPACK (cf. ODRPACK UG p. 38).
625
+ stopreason : list of str, optional
626
+ `info` interpreted into English.
627
+
628
+ Notes
629
+ -----
630
+ Takes one argument for initialization, the return value from the
631
+ function `~scipy.odr.odr`. The attributes listed as "optional" above are
632
+ only present if `~scipy.odr.odr` was run with ``full_output=1``.
633
+
634
+ """
635
+
636
+ def __init__(self, output):
637
+ self.beta = output[0]
638
+ self.sd_beta = output[1]
639
+ self.cov_beta = output[2]
640
+
641
+ if len(output) == 4:
642
+ # full output
643
+ self.__dict__.update(output[3])
644
+ self.stopreason = _report_error(self.info)
645
+
646
+ def pprint(self):
647
+ """ Pretty-print important results.
648
+ """
649
+
650
+ print('Beta:', self.beta)
651
+ print('Beta Std Error:', self.sd_beta)
652
+ print('Beta Covariance:', self.cov_beta)
653
+ if hasattr(self, 'info'):
654
+ print('Residual Variance:',self.res_var)
655
+ print('Inverse Condition #:', self.inv_condnum)
656
+ print('Reason(s) for Halting:')
657
+ for r in self.stopreason:
658
+ print(f' {r}')
659
+
660
+
661
+ class ODR:
662
+ """
663
+ The ODR class gathers all information and coordinates the running of the
664
+ main fitting routine.
665
+
666
+ .. deprecated:: 1.17.0
667
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
668
+ `pypi.org/project/odrpack/ <https://pypi.org/project/odrpack/>`_
669
+ instead.
670
+
671
+ Members of instances of the ODR class have the same names as the arguments
672
+ to the initialization routine.
673
+
674
+ Parameters
675
+ ----------
676
+ data : Data class instance
677
+ instance of the Data class
678
+ model : Model class instance
679
+ instance of the Model class
680
+
681
+ Other Parameters
682
+ ----------------
683
+ beta0 : array_like of rank-1
684
+ a rank-1 sequence of initial parameter values. Optional if
685
+ model provides an "estimate" function to estimate these values.
686
+ delta0 : array_like of floats of rank-1, optional
687
+ a (double-precision) float array to hold the initial values of
688
+ the errors in the input variables. Must be same shape as data.x
689
+ ifixb : array_like of ints of rank-1, optional
690
+ sequence of integers with the same length as beta0 that determines
691
+ which parameters are held fixed. A value of 0 fixes the parameter,
692
+ a value > 0 makes the parameter free.
693
+ ifixx : array_like of ints with same shape as data.x, optional
694
+ an array of integers with the same shape as data.x that determines
695
+ which input observations are treated as fixed. One can use a sequence
696
+ of length m (the dimensionality of the input observations) to fix some
697
+ dimensions for all observations. A value of 0 fixes the observation,
698
+ a value > 0 makes it free.
699
+ job : int, optional
700
+ an integer telling ODRPACK what tasks to perform. See p. 31 of the
701
+ ODRPACK User's Guide if you absolutely must set the value here. Use the
702
+ method set_job post-initialization for a more readable interface.
703
+ iprint : int, optional
704
+ an integer telling ODRPACK what to print. See pp. 33-34 of the
705
+ ODRPACK User's Guide if you absolutely must set the value here. Use the
706
+ method set_iprint post-initialization for a more readable interface.
707
+ errfile : str, optional
708
+ string with the filename to print ODRPACK errors to. If the file already
709
+ exists, an error will be thrown. The `overwrite` argument can be used to
710
+ prevent this. *Do Not Open This File Yourself!*
711
+ rptfile : str, optional
712
+ string with the filename to print ODRPACK summaries to. If the file
713
+ already exists, an error will be thrown. The `overwrite` argument can be
714
+ used to prevent this. *Do Not Open This File Yourself!*
715
+ ndigit : int, optional
716
+ integer specifying the number of reliable digits in the computation
717
+ of the function.
718
+ taufac : float, optional
719
+ float specifying the initial trust region. The default value is 1.
720
+ The initial trust region is equal to taufac times the length of the
721
+ first computed Gauss-Newton step. taufac must be less than 1.
722
+ sstol : float, optional
723
+ float specifying the tolerance for convergence based on the relative
724
+ change in the sum-of-squares. The default value is eps**(1/2) where eps
725
+ is the smallest value such that 1 + eps > 1 for double precision
726
+ computation on the machine. sstol must be less than 1.
727
+ partol : float, optional
728
+ float specifying the tolerance for convergence based on the relative
729
+ change in the estimated parameters. The default value is eps**(2/3) for
730
+ explicit models and ``eps**(1/3)`` for implicit models. partol must be less
731
+ than 1.
732
+ maxit : int, optional
733
+ integer specifying the maximum number of iterations to perform. For
734
+ first runs, maxit is the total number of iterations performed and
735
+ defaults to 50. For restarts, maxit is the number of additional
736
+ iterations to perform and defaults to 10.
737
+ stpb : array_like, optional
738
+ sequence (``len(stpb) == len(beta0)``) of relative step sizes to compute
739
+ finite difference derivatives wrt the parameters.
740
+ stpd : optional
741
+ array (``stpd.shape == data.x.shape`` or ``stpd.shape == (m,)``) of relative
742
+ step sizes to compute finite difference derivatives wrt the input
743
+ variable errors. If stpd is a rank-1 array with length m (the
744
+ dimensionality of the input variable), then the values are broadcast to
745
+ all observations.
746
+ sclb : array_like, optional
747
+ sequence (``len(stpb) == len(beta0)``) of scaling factors for the
748
+ parameters. The purpose of these scaling factors are to scale all of
749
+ the parameters to around unity. Normally appropriate scaling factors
750
+ are computed if this argument is not specified. Specify them yourself
751
+ if the automatic procedure goes awry.
752
+ scld : array_like, optional
753
+ array (scld.shape == data.x.shape or scld.shape == (m,)) of scaling
754
+ factors for the *errors* in the input variables. Again, these factors
755
+ are automatically computed if you do not provide them. If scld.shape ==
756
+ (m,), then the scaling factors are broadcast to all observations.
757
+ work : ndarray, optional
758
+ array to hold the double-valued working data for ODRPACK. When
759
+ restarting, takes the value of self.output.work.
760
+ iwork : ndarray, optional
761
+ array to hold the integer-valued working data for ODRPACK. When
762
+ restarting, takes the value of self.output.iwork.
763
+ overwrite : bool, optional
764
+ If it is True, output files defined by `errfile` and `rptfile` are
765
+ overwritten. The default is False.
766
+
767
+ Attributes
768
+ ----------
769
+ data : Data
770
+ The data for this fit
771
+ model : Model
772
+ The model used in fit
773
+ output : Output
774
+ An instance if the Output class containing all of the returned
775
+ data from an invocation of ODR.run() or ODR.restart()
776
+
777
+ """
778
+
779
+ def __init__(self, data, model, beta0=None, delta0=None, ifixb=None,
780
+ ifixx=None, job=None, iprint=None, errfile=None, rptfile=None,
781
+ ndigit=None, taufac=None, sstol=None, partol=None, maxit=None,
782
+ stpb=None, stpd=None, sclb=None, scld=None, work=None, iwork=None,
783
+ overwrite=False):
784
+
785
+ self.data = data
786
+ self.model = model
787
+
788
+ if beta0 is None:
789
+ if self.model.estimate is not None:
790
+ self.beta0 = _conv(self.model.estimate(self.data))
791
+ else:
792
+ raise ValueError(
793
+ "must specify beta0 or provide an estimator with the model"
794
+ )
795
+ else:
796
+ self.beta0 = _conv(beta0)
797
+
798
+ if ifixx is None and data.fix is not None:
799
+ ifixx = data.fix
800
+
801
+ if overwrite:
802
+ # remove output files for overwriting.
803
+ if rptfile is not None and os.path.exists(rptfile):
804
+ os.remove(rptfile)
805
+ if errfile is not None and os.path.exists(errfile):
806
+ os.remove(errfile)
807
+
808
+ self.delta0 = _conv(delta0)
809
+ # These really are 32-bit integers in FORTRAN (gfortran), even on 64-bit
810
+ # platforms.
811
+ # XXX: some other FORTRAN compilers may not agree.
812
+ self.ifixx = _conv(ifixx, dtype=np.int32)
813
+ self.ifixb = _conv(ifixb, dtype=np.int32)
814
+ self.job = job
815
+ self.iprint = iprint
816
+ self.errfile = errfile
817
+ self.rptfile = rptfile
818
+ self.ndigit = ndigit
819
+ self.taufac = taufac
820
+ self.sstol = sstol
821
+ self.partol = partol
822
+ self.maxit = maxit
823
+ self.stpb = _conv(stpb)
824
+ self.stpd = _conv(stpd)
825
+ self.sclb = _conv(sclb)
826
+ self.scld = _conv(scld)
827
+ self.work = _conv(work)
828
+ self.iwork = _conv(iwork)
829
+
830
+ self.output = None
831
+
832
+ self._check()
833
+
834
+ def _check(self):
835
+ """ Check the inputs for consistency, but don't bother checking things
836
+ that the builtin function odr will check.
837
+ """
838
+
839
+ x_s = list(self.data.x.shape)
840
+
841
+ if isinstance(self.data.y, np.ndarray):
842
+ y_s = list(self.data.y.shape)
843
+ if self.model.implicit:
844
+ raise OdrError("an implicit model cannot use response data")
845
+ if self.job is not None and (self.job % 10) == 1:
846
+ raise OdrError("job parameter requests an implicit model,"
847
+ " but an explicit model was passed")
848
+ else:
849
+ # implicit model with q == self.data.y
850
+ y_s = [self.data.y, x_s[-1]]
851
+ if not self.model.implicit:
852
+ raise OdrError("an explicit model needs response data")
853
+ self.set_job(fit_type=1)
854
+
855
+ if x_s[-1] != y_s[-1]:
856
+ raise OdrError("number of observations do not match")
857
+
858
+ n = x_s[-1]
859
+
860
+ if len(x_s) == 2:
861
+ m = x_s[0]
862
+ else:
863
+ m = 1
864
+ if len(y_s) == 2:
865
+ q = y_s[0]
866
+ else:
867
+ q = 1
868
+
869
+ p = len(self.beta0)
870
+
871
+ # permissible output array shapes
872
+
873
+ fcn_perms = [(q, n)]
874
+ fjacd_perms = [(q, m, n)]
875
+ fjacb_perms = [(q, p, n)]
876
+
877
+ if q == 1:
878
+ fcn_perms.append((n,))
879
+ fjacd_perms.append((m, n))
880
+ fjacb_perms.append((p, n))
881
+ if m == 1:
882
+ fjacd_perms.append((q, n))
883
+ if p == 1:
884
+ fjacb_perms.append((q, n))
885
+ if m == q == 1:
886
+ fjacd_perms.append((n,))
887
+ if p == q == 1:
888
+ fjacb_perms.append((n,))
889
+
890
+ # try evaluating the supplied functions to make sure they provide
891
+ # sensible outputs
892
+
893
+ arglist = (self.beta0, self.data.x)
894
+ if self.model.extra_args is not None:
895
+ arglist = arglist + self.model.extra_args
896
+ res = self.model.fcn(*arglist)
897
+
898
+ if res.shape not in fcn_perms:
899
+ print(res.shape)
900
+ print(fcn_perms)
901
+ raise OdrError(f"fcn does not output {y_s}-shaped array")
902
+
903
+ if self.model.fjacd is not None:
904
+ res = self.model.fjacd(*arglist)
905
+ if res.shape not in fjacd_perms:
906
+ raise OdrError(
907
+ f"fjacd does not output {repr((q, m, n))}-shaped array")
908
+ if self.model.fjacb is not None:
909
+ res = self.model.fjacb(*arglist)
910
+ if res.shape not in fjacb_perms:
911
+ raise OdrError(
912
+ f"fjacb does not output {repr((q, p, n))}-shaped array")
913
+
914
+ # check shape of delta0
915
+
916
+ if self.delta0 is not None and self.delta0.shape != self.data.x.shape:
917
+ raise OdrError(
918
+ f"delta0 is not a {repr(self.data.x.shape)}-shaped array")
919
+
920
+ if self.data.x.size == 0:
921
+ warn("Empty data detected for ODR instance. "
922
+ "Do not expect any fitting to occur",
923
+ OdrWarning, stacklevel=3)
924
+
925
+ def _gen_work(self):
926
+ """ Generate a suitable work array if one does not already exist.
927
+ """
928
+
929
+ n = self.data.x.shape[-1]
930
+ p = self.beta0.shape[0]
931
+
932
+ if len(self.data.x.shape) == 2:
933
+ m = self.data.x.shape[0]
934
+ else:
935
+ m = 1
936
+
937
+ if self.model.implicit:
938
+ q = self.data.y
939
+ elif len(self.data.y.shape) == 2:
940
+ q = self.data.y.shape[0]
941
+ else:
942
+ q = 1
943
+
944
+ if self.data.we is None:
945
+ ldwe = ld2we = 1
946
+ elif len(self.data.we.shape) == 3:
947
+ ld2we, ldwe = self.data.we.shape[1:]
948
+ else:
949
+ we = self.data.we
950
+ ldwe = 1
951
+ ld2we = 1
952
+ if we.ndim == 1 and q == 1:
953
+ ldwe = n
954
+ elif we.ndim == 2:
955
+ if we.shape == (q, q):
956
+ ld2we = q
957
+ elif we.shape == (q, n):
958
+ ldwe = n
959
+
960
+ if self.job % 10 < 2:
961
+ # ODR not OLS
962
+ lwork = (18 + 11*p + p*p + m + m*m + 4*n*q + 6*n*m + 2*n*q*p +
963
+ 2*n*q*m + q*q + 5*q + q*(p+m) + ldwe*ld2we*q)
964
+ else:
965
+ # OLS not ODR
966
+ lwork = (18 + 11*p + p*p + m + m*m + 4*n*q + 2*n*m + 2*n*q*p +
967
+ 5*q + q*(p+m) + ldwe*ld2we*q)
968
+
969
+ if isinstance(self.work, np.ndarray) and self.work.shape == (lwork,)\
970
+ and self.work.dtype.str.endswith('f8'):
971
+ # the existing array is fine
972
+ return
973
+ else:
974
+ self.work = np.zeros((lwork,), float)
975
+
976
+ def set_job(self, fit_type=None, deriv=None, var_calc=None,
977
+ del_init=None, restart=None):
978
+ """
979
+ Sets the "job" parameter is a hopefully comprehensible way.
980
+
981
+ If an argument is not specified, then the value is left as is. The
982
+ default value from class initialization is for all of these options set
983
+ to 0.
984
+
985
+ Parameters
986
+ ----------
987
+ fit_type : {0, 1, 2} int
988
+ 0 -> explicit ODR
989
+
990
+ 1 -> implicit ODR
991
+
992
+ 2 -> ordinary least-squares
993
+ deriv : {0, 1, 2, 3} int
994
+ 0 -> forward finite differences
995
+
996
+ 1 -> central finite differences
997
+
998
+ 2 -> user-supplied derivatives (Jacobians) with results
999
+ checked by ODRPACK
1000
+
1001
+ 3 -> user-supplied derivatives, no checking
1002
+ var_calc : {0, 1, 2} int
1003
+ 0 -> calculate asymptotic covariance matrix and fit
1004
+ parameter uncertainties (V_B, s_B) using derivatives
1005
+ recomputed at the final solution
1006
+
1007
+ 1 -> calculate V_B and s_B using derivatives from last iteration
1008
+
1009
+ 2 -> do not calculate V_B and s_B
1010
+ del_init : {0, 1} int
1011
+ 0 -> initial input variable offsets set to 0
1012
+
1013
+ 1 -> initial offsets provided by user in variable "work"
1014
+ restart : {0, 1} int
1015
+ 0 -> fit is not a restart
1016
+
1017
+ 1 -> fit is a restart
1018
+
1019
+ Notes
1020
+ -----
1021
+ The permissible values are different from those given on pg. 31 of the
1022
+ ODRPACK User's Guide only in that one cannot specify numbers greater than
1023
+ the last value for each variable.
1024
+
1025
+ If one does not supply functions to compute the Jacobians, the fitting
1026
+ procedure will change deriv to 0, finite differences, as a default. To
1027
+ initialize the input variable offsets by yourself, set del_init to 1 and
1028
+ put the offsets into the "work" variable correctly.
1029
+
1030
+ """
1031
+
1032
+ if self.job is None:
1033
+ job_l = [0, 0, 0, 0, 0]
1034
+ else:
1035
+ job_l = [self.job // 10000 % 10,
1036
+ self.job // 1000 % 10,
1037
+ self.job // 100 % 10,
1038
+ self.job // 10 % 10,
1039
+ self.job % 10]
1040
+
1041
+ if fit_type in (0, 1, 2):
1042
+ job_l[4] = fit_type
1043
+ if deriv in (0, 1, 2, 3):
1044
+ job_l[3] = deriv
1045
+ if var_calc in (0, 1, 2):
1046
+ job_l[2] = var_calc
1047
+ if del_init in (0, 1):
1048
+ job_l[1] = del_init
1049
+ if restart in (0, 1):
1050
+ job_l[0] = restart
1051
+
1052
+ self.job = (job_l[0]*10000 + job_l[1]*1000 +
1053
+ job_l[2]*100 + job_l[3]*10 + job_l[4])
1054
+
1055
+ def set_iprint(self, init=None, so_init=None,
1056
+ iter=None, so_iter=None, iter_step=None, final=None, so_final=None):
1057
+ """ Set the iprint parameter for the printing of computation reports.
1058
+
1059
+ If any of the arguments are specified here, then they are set in the
1060
+ iprint member. If iprint is not set manually or with this method, then
1061
+ ODRPACK defaults to no printing. If no filename is specified with the
1062
+ member rptfile, then ODRPACK prints to stdout. One can tell ODRPACK to
1063
+ print to stdout in addition to the specified filename by setting the
1064
+ so_* arguments to this function, but one cannot specify to print to
1065
+ stdout but not a file since one can do that by not specifying a rptfile
1066
+ filename.
1067
+
1068
+ There are three reports: initialization, iteration, and final reports.
1069
+ They are represented by the arguments init, iter, and final
1070
+ respectively. The permissible values are 0, 1, and 2 representing "no
1071
+ report", "short report", and "long report" respectively.
1072
+
1073
+ The argument iter_step (0 <= iter_step <= 9) specifies how often to make
1074
+ the iteration report; the report will be made for every iter_step'th
1075
+ iteration starting with iteration one. If iter_step == 0, then no
1076
+ iteration report is made, regardless of the other arguments.
1077
+
1078
+ If the rptfile is None, then any so_* arguments supplied will raise an
1079
+ exception.
1080
+ """
1081
+ if self.iprint is None:
1082
+ self.iprint = 0
1083
+
1084
+ ip = [self.iprint // 1000 % 10,
1085
+ self.iprint // 100 % 10,
1086
+ self.iprint // 10 % 10,
1087
+ self.iprint % 10]
1088
+
1089
+ # make a list to convert iprint digits to/from argument inputs
1090
+ # rptfile, stdout
1091
+ ip2arg = [[0, 0], # none, none
1092
+ [1, 0], # short, none
1093
+ [2, 0], # long, none
1094
+ [1, 1], # short, short
1095
+ [2, 1], # long, short
1096
+ [1, 2], # short, long
1097
+ [2, 2]] # long, long
1098
+
1099
+ if (self.rptfile is None and
1100
+ (so_init is not None or
1101
+ so_iter is not None or
1102
+ so_final is not None)):
1103
+ raise OdrError(
1104
+ "no rptfile specified, cannot output to stdout twice")
1105
+
1106
+ iprint_l = ip2arg[ip[0]] + ip2arg[ip[1]] + ip2arg[ip[3]]
1107
+
1108
+ if init is not None:
1109
+ iprint_l[0] = init
1110
+ if so_init is not None:
1111
+ iprint_l[1] = so_init
1112
+ if iter is not None:
1113
+ iprint_l[2] = iter
1114
+ if so_iter is not None:
1115
+ iprint_l[3] = so_iter
1116
+ if final is not None:
1117
+ iprint_l[4] = final
1118
+ if so_final is not None:
1119
+ iprint_l[5] = so_final
1120
+
1121
+ if iter_step in range(10):
1122
+ # 0..9
1123
+ ip[2] = iter_step
1124
+
1125
+ ip[0] = ip2arg.index(iprint_l[0:2])
1126
+ ip[1] = ip2arg.index(iprint_l[2:4])
1127
+ ip[3] = ip2arg.index(iprint_l[4:6])
1128
+
1129
+ self.iprint = ip[0]*1000 + ip[1]*100 + ip[2]*10 + ip[3]
1130
+
1131
+ def run(self):
1132
+ """ Run the fitting routine with all of the information given and with ``full_output=1``.
1133
+
1134
+ Returns
1135
+ -------
1136
+ output : Output instance
1137
+ This object is also assigned to the attribute .output .
1138
+ """ # noqa: E501
1139
+
1140
+ args = (self.model.fcn, self.beta0, self.data.y, self.data.x)
1141
+ kwds = {'full_output': 1}
1142
+ kwd_l = ['ifixx', 'ifixb', 'job', 'iprint', 'errfile', 'rptfile',
1143
+ 'ndigit', 'taufac', 'sstol', 'partol', 'maxit', 'stpb',
1144
+ 'stpd', 'sclb', 'scld', 'work', 'iwork']
1145
+
1146
+ if self.delta0 is not None and (self.job // 10000) % 10 == 0:
1147
+ # delta0 provided and fit is not a restart
1148
+ self._gen_work()
1149
+
1150
+ d0 = np.ravel(self.delta0)
1151
+
1152
+ self.work[:len(d0)] = d0
1153
+
1154
+ # set the kwds from other objects explicitly
1155
+ if self.model.fjacb is not None:
1156
+ kwds['fjacb'] = self.model.fjacb
1157
+ if self.model.fjacd is not None:
1158
+ kwds['fjacd'] = self.model.fjacd
1159
+ if self.data.we is not None:
1160
+ kwds['we'] = self.data.we
1161
+ if self.data.wd is not None:
1162
+ kwds['wd'] = self.data.wd
1163
+ if self.model.extra_args is not None:
1164
+ kwds['extra_args'] = self.model.extra_args
1165
+
1166
+ # implicitly set kwds from self's members
1167
+ for attr in kwd_l:
1168
+ obj = getattr(self, attr)
1169
+ if obj is not None:
1170
+ kwds[attr] = obj
1171
+
1172
+ with ODR_LOCK:
1173
+ self.output = Output(odr(*args, **kwds))
1174
+
1175
+ return self.output
1176
+
1177
+ def restart(self, iter=None):
1178
+ """ Restarts the run with iter more iterations.
1179
+
1180
+ Parameters
1181
+ ----------
1182
+ iter : int, optional
1183
+ ODRPACK's default for the number of new iterations is 10.
1184
+
1185
+ Returns
1186
+ -------
1187
+ output : Output instance
1188
+ This object is also assigned to the attribute .output .
1189
+ """
1190
+
1191
+ if self.output is None:
1192
+ raise OdrError("cannot restart: run() has not been called before")
1193
+
1194
+ self.set_job(restart=1)
1195
+ self.work = self.output.work
1196
+ self.iwork = self.output.iwork
1197
+
1198
+ self.maxit = iter
1199
+
1200
+ return self.run()
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/models.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.odr` namespace for importing the functions
3
+ # included below.
4
+
5
+
6
+ __all__ = [ # noqa: F822
7
+ 'Model', 'exponential', 'multilinear', 'unilinear',
8
+ 'quadratic', 'polynomial'
9
+ ]
10
+
11
+
12
+ def __dir__():
13
+ return __all__
14
+
15
+
16
+ def __getattr__(name):
17
+ msg = ("`scipy.odr` is deprecated as of version 1.17.0 and will be removed in "
18
+ "SciPy 1.19.0. Please use `https://pypi.org/project/odrpack/` instead.")
19
+ if name not in __all__:
20
+ raise AttributeError(
21
+ f"`scipy.odr.models` has no attribute {name}. In addition, {msg}")
22
+
23
+ import warnings
24
+ from . import _models
25
+ warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
26
+
27
+ return getattr(_models, name)
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/odrpack.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is not meant for public use and will be removed in SciPy v2.0.0.
2
+ # Use the `scipy.odr` namespace for importing the functions
3
+ # included below.
4
+
5
+
6
+ __all__ = [ # noqa: F822
7
+ 'odr', 'OdrWarning', 'OdrError', 'OdrStop',
8
+ 'Data', 'RealData', 'Model', 'Output', 'ODR',
9
+ 'odr_error', 'odr_stop'
10
+ ]
11
+
12
+
13
+ def __dir__():
14
+ return __all__
15
+
16
+
17
+ def __getattr__(name):
18
+ msg = ("`scipy.odr` is deprecated as of version 1.17.0 and will be removed in "
19
+ "SciPy 1.19.0. Please use `https://pypi.org/project/odrpack/` instead.")
20
+ if name not in __all__:
21
+ raise AttributeError(
22
+ f"`scipy.odr.odrpack` has no attribute {name}. In addition, {msg}")
23
+
24
+ import warnings
25
+ from . import _odrpack
26
+ warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
27
+
28
+ return getattr(_odrpack, name)
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/tests/__init__.py ADDED
File without changes
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/tests/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (255 Bytes). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/tests/__pycache__/test_odr.cpython-311.pyc ADDED
Binary file (36.3 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/odr/tests/test_odr.py ADDED
@@ -0,0 +1,621 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pickle
2
+ import tempfile
3
+ import shutil
4
+ import os
5
+
6
+ import numpy as np
7
+ from numpy import pi
8
+ from numpy.testing import (assert_array_almost_equal,
9
+ assert_equal,
10
+ assert_allclose)
11
+ import pytest
12
+ from pytest import raises as assert_raises
13
+
14
+ from scipy.odr import (Data, Model, ODR, RealData, OdrStop, OdrWarning,
15
+ OdrError, multilinear, exponential, unilinear,
16
+ quadratic, polynomial)
17
+
18
+
19
+ class TestODR:
20
+
21
+ # Bad Data for 'x'
22
+
23
+ def test_bad_data(self):
24
+ assert_raises(ValueError, Data, 2, 1)
25
+ assert_raises(ValueError, RealData, 2, 1)
26
+
27
+ # Empty Data for 'x'
28
+ def empty_data_func(self, B, x):
29
+ return B[0]*x + B[1]
30
+
31
+ def test_empty_data(self):
32
+ beta0 = [0.02, 0.0]
33
+ linear = Model(self.empty_data_func)
34
+
35
+ empty_dat = Data([], [])
36
+ with pytest.warns(OdrWarning):
37
+ ODR(empty_dat, linear, beta0=beta0)
38
+
39
+ empty_dat = RealData([], [])
40
+ with pytest.warns(OdrWarning):
41
+ ODR(empty_dat, linear, beta0=beta0)
42
+
43
+ # Explicit Example
44
+
45
+ def explicit_fcn(self, B, x):
46
+ ret = B[0] + B[1] * np.power(np.exp(B[2]*x) - 1.0, 2)
47
+ return ret
48
+
49
+ def explicit_fjd(self, B, x):
50
+ eBx = np.exp(B[2]*x)
51
+ ret = B[1] * 2.0 * (eBx-1.0) * B[2] * eBx
52
+ return ret
53
+
54
+ def explicit_fjb(self, B, x):
55
+ eBx = np.exp(B[2]*x)
56
+ res = np.vstack([np.ones(x.shape[-1]),
57
+ np.power(eBx-1.0, 2),
58
+ B[1]*2.0*(eBx-1.0)*eBx*x])
59
+ return res
60
+
61
+ def test_explicit(self):
62
+ explicit_mod = Model(
63
+ self.explicit_fcn,
64
+ fjacb=self.explicit_fjb,
65
+ fjacd=self.explicit_fjd,
66
+ meta=dict(name='Sample Explicit Model',
67
+ ref='ODRPACK UG, pg. 39'),
68
+ )
69
+ explicit_dat = Data([0.,0.,5.,7.,7.5,10.,16.,26.,30.,34.,34.5,100.],
70
+ [1265.,1263.6,1258.,1254.,1253.,1249.8,1237.,1218.,1220.6,
71
+ 1213.8,1215.5,1212.])
72
+ explicit_odr = ODR(explicit_dat, explicit_mod, beta0=[1500.0, -50.0, -0.1],
73
+ ifixx=[0,0,1,1,1,1,1,1,1,1,1,0])
74
+ explicit_odr.set_job(deriv=2)
75
+ explicit_odr.set_iprint(init=0, iter=0, final=0)
76
+
77
+ out = explicit_odr.run()
78
+ assert_array_almost_equal(
79
+ out.beta,
80
+ np.array([1.2646548050648876e+03, -5.4018409956678255e+01,
81
+ -8.7849712165253724e-02]),
82
+ )
83
+ assert_array_almost_equal(
84
+ out.sd_beta,
85
+ np.array([1.0349270280543437, 1.583997785262061, 0.0063321988657267]),
86
+ )
87
+ assert_array_almost_equal(
88
+ out.cov_beta,
89
+ np.array([[4.4949592379003039e-01, -3.7421976890364739e-01,
90
+ -8.0978217468468912e-04],
91
+ [-3.7421976890364739e-01, 1.0529686462751804e+00,
92
+ -1.9453521827942002e-03],
93
+ [-8.0978217468468912e-04, -1.9453521827942002e-03,
94
+ 1.6827336938454476e-05]]),
95
+ )
96
+
97
+ # Implicit Example
98
+
99
+ def implicit_fcn(self, B, x):
100
+ return (B[2]*np.power(x[0]-B[0], 2) +
101
+ 2.0*B[3]*(x[0]-B[0])*(x[1]-B[1]) +
102
+ B[4]*np.power(x[1]-B[1], 2) - 1.0)
103
+
104
+ def test_implicit(self):
105
+ implicit_mod = Model(
106
+ self.implicit_fcn,
107
+ implicit=1,
108
+ meta=dict(name='Sample Implicit Model',
109
+ ref='ODRPACK UG, pg. 49'),
110
+ )
111
+ implicit_dat = Data([
112
+ [0.5,1.2,1.6,1.86,2.12,2.36,2.44,2.36,2.06,1.74,1.34,0.9,-0.28,
113
+ -0.78,-1.36,-1.9,-2.5,-2.88,-3.18,-3.44],
114
+ [-0.12,-0.6,-1.,-1.4,-2.54,-3.36,-4.,-4.75,-5.25,-5.64,-5.97,-6.32,
115
+ -6.44,-6.44,-6.41,-6.25,-5.88,-5.5,-5.24,-4.86]],
116
+ 1,
117
+ )
118
+ implicit_odr = ODR(implicit_dat, implicit_mod,
119
+ beta0=[-1.0, -3.0, 0.09, 0.02, 0.08])
120
+
121
+ out = implicit_odr.run()
122
+ assert_array_almost_equal(
123
+ out.beta,
124
+ np.array([-0.9993809167281279, -2.9310484652026476, 0.0875730502693354,
125
+ 0.0162299708984738, 0.0797537982976416]),
126
+ )
127
+ assert_array_almost_equal(
128
+ out.sd_beta,
129
+ np.array([0.1113840353364371, 0.1097673310686467, 0.0041060738314314,
130
+ 0.0027500347539902, 0.0034962501532468]),
131
+ )
132
+ assert_allclose(
133
+ out.cov_beta,
134
+ np.array([[2.1089274602333052e+00, -1.9437686411979040e+00,
135
+ 7.0263550868344446e-02, -4.7175267373474862e-02,
136
+ 5.2515575927380355e-02],
137
+ [-1.9437686411979040e+00, 2.0481509222414456e+00,
138
+ -6.1600515853057307e-02, 4.6268827806232933e-02,
139
+ -5.8822307501391467e-02],
140
+ [7.0263550868344446e-02, -6.1600515853057307e-02,
141
+ 2.8659542561579308e-03, -1.4628662260014491e-03,
142
+ 1.4528860663055824e-03],
143
+ [-4.7175267373474862e-02, 4.6268827806232933e-02,
144
+ -1.4628662260014491e-03, 1.2855592885514335e-03,
145
+ -1.2692942951415293e-03],
146
+ [5.2515575927380355e-02, -5.8822307501391467e-02,
147
+ 1.4528860663055824e-03, -1.2692942951415293e-03,
148
+ 2.0778813389755596e-03]]),
149
+ rtol=1e-6, atol=2e-6,
150
+ )
151
+
152
+ # Multi-variable Example
153
+
154
+ def multi_fcn(self, B, x):
155
+ if (x < 0.0).any():
156
+ raise OdrStop
157
+ theta = pi*B[3]/2.
158
+ ctheta = np.cos(theta)
159
+ stheta = np.sin(theta)
160
+ omega = np.power(2.*pi*x*np.exp(-B[2]), B[3])
161
+ phi = np.arctan2((omega*stheta), (1.0 + omega*ctheta))
162
+ r = (B[0] - B[1]) * np.power(np.sqrt(np.power(1.0 + omega*ctheta, 2) +
163
+ np.power(omega*stheta, 2)), -B[4])
164
+ ret = np.vstack([B[1] + r*np.cos(B[4]*phi),
165
+ r*np.sin(B[4]*phi)])
166
+ return ret
167
+
168
+ def test_multi(self):
169
+ multi_mod = Model(
170
+ self.multi_fcn,
171
+ meta=dict(name='Sample Multi-Response Model',
172
+ ref='ODRPACK UG, pg. 56'),
173
+ )
174
+
175
+ multi_x = np.array([30.0, 50.0, 70.0, 100.0, 150.0, 200.0, 300.0, 500.0,
176
+ 700.0, 1000.0, 1500.0, 2000.0, 3000.0, 5000.0, 7000.0, 10000.0,
177
+ 15000.0, 20000.0, 30000.0, 50000.0, 70000.0, 100000.0, 150000.0])
178
+ multi_y = np.array([
179
+ [4.22, 4.167, 4.132, 4.038, 4.019, 3.956, 3.884, 3.784, 3.713,
180
+ 3.633, 3.54, 3.433, 3.358, 3.258, 3.193, 3.128, 3.059, 2.984,
181
+ 2.934, 2.876, 2.838, 2.798, 2.759],
182
+ [0.136, 0.167, 0.188, 0.212, 0.236, 0.257, 0.276, 0.297, 0.309,
183
+ 0.311, 0.314, 0.311, 0.305, 0.289, 0.277, 0.255, 0.24, 0.218,
184
+ 0.202, 0.182, 0.168, 0.153, 0.139],
185
+ ])
186
+ n = len(multi_x)
187
+ multi_we = np.zeros((2, 2, n), dtype=float)
188
+ multi_ifixx = np.ones(n, dtype=int)
189
+ multi_delta = np.zeros(n, dtype=float)
190
+
191
+ multi_we[0,0,:] = 559.6
192
+ multi_we[1,0,:] = multi_we[0,1,:] = -1634.0
193
+ multi_we[1,1,:] = 8397.0
194
+
195
+ for i in range(n):
196
+ if multi_x[i] < 100.0:
197
+ multi_ifixx[i] = 0
198
+ elif multi_x[i] <= 150.0:
199
+ pass # defaults are fine
200
+ elif multi_x[i] <= 1000.0:
201
+ multi_delta[i] = 25.0
202
+ elif multi_x[i] <= 10000.0:
203
+ multi_delta[i] = 560.0
204
+ elif multi_x[i] <= 100000.0:
205
+ multi_delta[i] = 9500.0
206
+ else:
207
+ multi_delta[i] = 144000.0
208
+ if multi_x[i] == 100.0 or multi_x[i] == 150.0:
209
+ multi_we[:,:,i] = 0.0
210
+
211
+ multi_dat = Data(multi_x, multi_y, wd=1e-4/np.power(multi_x, 2),
212
+ we=multi_we)
213
+ multi_odr = ODR(multi_dat, multi_mod, beta0=[4.,2.,7.,.4,.5],
214
+ delta0=multi_delta, ifixx=multi_ifixx)
215
+ multi_odr.set_job(deriv=1, del_init=1)
216
+
217
+ out = multi_odr.run()
218
+ assert_array_almost_equal(
219
+ out.beta,
220
+ np.array([4.3799880305938963, 2.4333057577497703, 8.0028845899503978,
221
+ 0.5101147161764654, 0.5173902330489161]),
222
+ )
223
+ assert_array_almost_equal(
224
+ out.sd_beta,
225
+ np.array([0.0130625231081944, 0.0130499785273277, 0.1167085962217757,
226
+ 0.0132642749596149, 0.0288529201353984]),
227
+ )
228
+ assert_array_almost_equal(
229
+ out.cov_beta,
230
+ np.array([[0.0064918418231375, 0.0036159705923791, 0.0438637051470406,
231
+ -0.0058700836512467, 0.011281212888768],
232
+ [0.0036159705923791, 0.0064793789429006, 0.0517610978353126,
233
+ -0.0051181304940204, 0.0130726943624117],
234
+ [0.0438637051470406, 0.0517610978353126, 0.5182263323095322,
235
+ -0.0563083340093696, 0.1269490939468611],
236
+ [-0.0058700836512467, -0.0051181304940204, -0.0563083340093696,
237
+ 0.0066939246261263, -0.0140184391377962],
238
+ [0.011281212888768, 0.0130726943624117, 0.1269490939468611,
239
+ -0.0140184391377962, 0.0316733013820852]]),
240
+ )
241
+
242
+ # Pearson's Data
243
+ # K. Pearson, Philosophical Magazine, 2, 559 (1901)
244
+
245
+ def pearson_fcn(self, B, x):
246
+ return B[0] + B[1]*x
247
+
248
+ def test_pearson(self):
249
+ p_x = np.array([0.,.9,1.8,2.6,3.3,4.4,5.2,6.1,6.5,7.4])
250
+ p_y = np.array([5.9,5.4,4.4,4.6,3.5,3.7,2.8,2.8,2.4,1.5])
251
+ p_sx = np.array([.03,.03,.04,.035,.07,.11,.13,.22,.74,1.])
252
+ p_sy = np.array([1.,.74,.5,.35,.22,.22,.12,.12,.1,.04])
253
+
254
+ p_dat = RealData(p_x, p_y, sx=p_sx, sy=p_sy)
255
+
256
+ # Reverse the data to test invariance of results
257
+ pr_dat = RealData(p_y, p_x, sx=p_sy, sy=p_sx)
258
+
259
+ p_mod = Model(self.pearson_fcn, meta=dict(name='Uni-linear Fit'))
260
+
261
+ p_odr = ODR(p_dat, p_mod, beta0=[1.,1.])
262
+ pr_odr = ODR(pr_dat, p_mod, beta0=[1.,1.])
263
+
264
+ out = p_odr.run()
265
+ assert_array_almost_equal(
266
+ out.beta,
267
+ np.array([5.4767400299231674, -0.4796082367610305]),
268
+ )
269
+ assert_array_almost_equal(
270
+ out.sd_beta,
271
+ np.array([0.3590121690702467, 0.0706291186037444]),
272
+ )
273
+ assert_array_almost_equal(
274
+ out.cov_beta,
275
+ np.array([[0.0854275622946333, -0.0161807025443155],
276
+ [-0.0161807025443155, 0.003306337993922]]),
277
+ )
278
+
279
+ rout = pr_odr.run()
280
+ assert_array_almost_equal(
281
+ rout.beta,
282
+ np.array([11.4192022410781231, -2.0850374506165474]),
283
+ )
284
+ assert_array_almost_equal(
285
+ rout.sd_beta,
286
+ np.array([0.9820231665657161, 0.3070515616198911]),
287
+ )
288
+ assert_array_almost_equal(
289
+ rout.cov_beta,
290
+ np.array([[0.6391799462548782, -0.1955657291119177],
291
+ [-0.1955657291119177, 0.0624888159223392]]),
292
+ )
293
+
294
+ # Lorentz Peak
295
+ # The data is taken from one of the undergraduate physics labs I performed.
296
+
297
+ def lorentz(self, beta, x):
298
+ return (beta[0]*beta[1]*beta[2] / np.sqrt(np.power(x*x -
299
+ beta[2]*beta[2], 2.0) + np.power(beta[1]*x, 2.0)))
300
+
301
+ def test_lorentz(self):
302
+ l_sy = np.array([.29]*18)
303
+ l_sx = np.array([.000972971,.000948268,.000707632,.000706679,
304
+ .000706074, .000703918,.000698955,.000456856,
305
+ .000455207,.000662717,.000654619,.000652694,
306
+ .000000859202,.00106589,.00106378,.00125483, .00140818,.00241839])
307
+
308
+ l_dat = RealData(
309
+ [3.9094, 3.85945, 3.84976, 3.84716, 3.84551, 3.83964, 3.82608,
310
+ 3.78847, 3.78163, 3.72558, 3.70274, 3.6973, 3.67373, 3.65982,
311
+ 3.6562, 3.62498, 3.55525, 3.41886],
312
+ [652, 910.5, 984, 1000, 1007.5, 1053, 1160.5, 1409.5, 1430, 1122,
313
+ 957.5, 920, 777.5, 709.5, 698, 578.5, 418.5, 275.5],
314
+ sx=l_sx,
315
+ sy=l_sy,
316
+ )
317
+ l_mod = Model(self.lorentz, meta=dict(name='Lorentz Peak'))
318
+ l_odr = ODR(l_dat, l_mod, beta0=(1000., .1, 3.8))
319
+
320
+ out = l_odr.run()
321
+ assert_array_almost_equal(
322
+ out.beta,
323
+ np.array([1.4306780846149925e+03, 1.3390509034538309e-01,
324
+ 3.7798193600109009e+00]),
325
+ )
326
+ assert_array_almost_equal(
327
+ out.sd_beta,
328
+ np.array([7.3621186811330963e-01, 3.5068899941471650e-04,
329
+ 2.4451209281408992e-04]),
330
+ )
331
+ assert_array_almost_equal(
332
+ out.cov_beta,
333
+ np.array([[2.4714409064597873e-01, -6.9067261911110836e-05,
334
+ -3.1236953270424990e-05],
335
+ [-6.9067261911110836e-05, 5.6077531517333009e-08,
336
+ 3.6133261832722601e-08],
337
+ [-3.1236953270424990e-05, 3.6133261832722601e-08,
338
+ 2.7261220025171730e-08]]),
339
+ )
340
+
341
+ def test_ticket_1253(self):
342
+ def linear(c, x):
343
+ return c[0]*x+c[1]
344
+
345
+ c = [2.0, 3.0]
346
+ x = np.linspace(0, 10)
347
+ y = linear(c, x)
348
+
349
+ model = Model(linear)
350
+ data = Data(x, y, wd=1.0, we=1.0)
351
+ job = ODR(data, model, beta0=[1.0, 1.0])
352
+ result = job.run()
353
+ assert_equal(result.info, 2)
354
+
355
+ # Verify fix for gh-9140
356
+
357
+ def test_ifixx(self):
358
+ x1 = [-2.01, -0.99, -0.001, 1.02, 1.98]
359
+ x2 = [3.98, 1.01, 0.001, 0.998, 4.01]
360
+ fix = np.vstack((np.zeros_like(x1, dtype=int), np.ones_like(x2, dtype=int)))
361
+ data = Data(np.vstack((x1, x2)), y=1, fix=fix)
362
+ model = Model(lambda beta, x: x[1, :] - beta[0] * x[0, :]**2., implicit=True)
363
+
364
+ odr1 = ODR(data, model, beta0=np.array([1.]))
365
+ sol1 = odr1.run()
366
+ odr2 = ODR(data, model, beta0=np.array([1.]), ifixx=fix)
367
+ sol2 = odr2.run()
368
+ assert_equal(sol1.beta, sol2.beta)
369
+
370
+ # verify bugfix for #11800 in #11802
371
+ def test_ticket_11800(self):
372
+ # parameters
373
+ beta_true = np.array([1.0, 2.3, 1.1, -1.0, 1.3, 0.5])
374
+ nr_measurements = 10
375
+
376
+ std_dev_x = 0.01
377
+ x_error = np.array([[0.00063445, 0.00515731, 0.00162719, 0.01022866,
378
+ -0.01624845, 0.00482652, 0.00275988, -0.00714734, -0.00929201, -0.00687301],
379
+ [-0.00831623, -0.00821211, -0.00203459, 0.00938266, -0.00701829,
380
+ 0.0032169, 0.00259194, -0.00581017, -0.0030283, 0.01014164]])
381
+
382
+ std_dev_y = 0.05
383
+ y_error = np.array([[0.05275304, 0.04519563, -0.07524086, 0.03575642,
384
+ 0.04745194, 0.03806645, 0.07061601, -0.00753604, -0.02592543, -0.02394929],
385
+ [0.03632366, 0.06642266, 0.08373122, 0.03988822, -0.0092536,
386
+ -0.03750469, -0.03198903, 0.01642066, 0.01293648, -0.05627085]])
387
+
388
+ beta_solution = np.array([
389
+ 2.62920235756665876536e+00, -1.26608484996299608838e+02,
390
+ 1.29703572775403074502e+02, -1.88560985401185465804e+00,
391
+ 7.83834160771274923718e+01, -7.64124076838087091801e+01])
392
+
393
+ # model's function and Jacobians
394
+ def func(beta, x):
395
+ y0 = beta[0] + beta[1] * x[0, :] + beta[2] * x[1, :]
396
+ y1 = beta[3] + beta[4] * x[0, :] + beta[5] * x[1, :]
397
+
398
+ return np.vstack((y0, y1))
399
+
400
+ def df_dbeta_odr(beta, x):
401
+ nr_meas = np.shape(x)[1]
402
+ zeros = np.zeros(nr_meas)
403
+ ones = np.ones(nr_meas)
404
+
405
+ dy0 = np.array([ones, x[0, :], x[1, :], zeros, zeros, zeros])
406
+ dy1 = np.array([zeros, zeros, zeros, ones, x[0, :], x[1, :]])
407
+
408
+ return np.stack((dy0, dy1))
409
+
410
+ def df_dx_odr(beta, x):
411
+ nr_meas = np.shape(x)[1]
412
+ ones = np.ones(nr_meas)
413
+
414
+ dy0 = np.array([beta[1] * ones, beta[2] * ones])
415
+ dy1 = np.array([beta[4] * ones, beta[5] * ones])
416
+ return np.stack((dy0, dy1))
417
+
418
+ # do measurements with errors in independent and dependent variables
419
+ x0_true = np.linspace(1, 10, nr_measurements)
420
+ x1_true = np.linspace(1, 10, nr_measurements)
421
+ x_true = np.array([x0_true, x1_true])
422
+
423
+ y_true = func(beta_true, x_true)
424
+
425
+ x_meas = x_true + x_error
426
+ y_meas = y_true + y_error
427
+
428
+ # estimate model's parameters
429
+ model_f = Model(func, fjacb=df_dbeta_odr, fjacd=df_dx_odr)
430
+
431
+ data = RealData(x_meas, y_meas, sx=std_dev_x, sy=std_dev_y)
432
+
433
+ odr_obj = ODR(data, model_f, beta0=0.9 * beta_true, maxit=100)
434
+ #odr_obj.set_iprint(init=2, iter=0, iter_step=1, final=1)
435
+ odr_obj.set_job(deriv=3)
436
+
437
+ odr_out = odr_obj.run()
438
+
439
+ # check results
440
+ assert_equal(odr_out.info, 1)
441
+ assert_array_almost_equal(odr_out.beta, beta_solution)
442
+
443
+ def test_multilinear_model(self):
444
+ x = np.linspace(0.0, 5.0)
445
+ y = 10.0 + 5.0 * x
446
+ data = Data(x, y)
447
+ odr_obj = ODR(data, multilinear)
448
+ output = odr_obj.run()
449
+ assert_array_almost_equal(output.beta, [10.0, 5.0])
450
+
451
+ def test_exponential_model(self):
452
+ x = np.linspace(0.0, 5.0)
453
+ y = -10.0 + np.exp(0.5*x)
454
+ data = Data(x, y)
455
+ odr_obj = ODR(data, exponential)
456
+ output = odr_obj.run()
457
+ assert_array_almost_equal(output.beta, [-10.0, 0.5])
458
+
459
+ def test_polynomial_model(self):
460
+ x = np.linspace(0.0, 5.0)
461
+ y = 1.0 + 2.0 * x + 3.0 * x ** 2 + 4.0 * x ** 3
462
+ poly_model = polynomial(3)
463
+ data = Data(x, y)
464
+ odr_obj = ODR(data, poly_model)
465
+ output = odr_obj.run()
466
+ assert_array_almost_equal(output.beta, [1.0, 2.0, 3.0, 4.0])
467
+
468
+ def test_unilinear_model(self):
469
+ x = np.linspace(0.0, 5.0)
470
+ y = 1.0 * x + 2.0
471
+ data = Data(x, y)
472
+ odr_obj = ODR(data, unilinear)
473
+ output = odr_obj.run()
474
+ assert_array_almost_equal(output.beta, [1.0, 2.0])
475
+
476
+ def test_quadratic_model(self):
477
+ x = np.linspace(0.0, 5.0)
478
+ y = 1.0 * x ** 2 + 2.0 * x + 3.0
479
+ data = Data(x, y)
480
+ odr_obj = ODR(data, quadratic)
481
+ output = odr_obj.run()
482
+ assert_array_almost_equal(output.beta, [1.0, 2.0, 3.0])
483
+
484
+ def test_work_ind(self):
485
+
486
+ def func(par, x):
487
+ b0, b1 = par
488
+ return b0 + b1 * x
489
+
490
+ # generate some data
491
+ n_data = 4
492
+ x = np.arange(n_data)
493
+ y = np.where(x % 2, x + 0.1, x - 0.1)
494
+ x_err = np.full(n_data, 0.1)
495
+ y_err = np.full(n_data, 0.1)
496
+
497
+ # do the fitting
498
+ linear_model = Model(func)
499
+ real_data = RealData(x, y, sx=x_err, sy=y_err)
500
+ odr_obj = ODR(real_data, linear_model, beta0=[0.4, 0.4])
501
+ odr_obj.set_job(fit_type=0)
502
+ out = odr_obj.run()
503
+
504
+ sd_ind = out.work_ind['sd']
505
+ assert_array_almost_equal(out.sd_beta,
506
+ out.work[sd_ind:sd_ind + len(out.sd_beta)])
507
+
508
+ @pytest.mark.skipif(True, reason="Fortran I/O prone to crashing so better "
509
+ "not to run this test, see gh-13127")
510
+ def test_output_file_overwrite(self):
511
+ """
512
+ Verify fix for gh-1892
513
+ """
514
+ def func(b, x):
515
+ return b[0] + b[1] * x
516
+
517
+ p = Model(func)
518
+ data = Data(np.arange(10), 12 * np.arange(10))
519
+ tmp_dir = tempfile.mkdtemp()
520
+ error_file_path = os.path.join(tmp_dir, "error.dat")
521
+ report_file_path = os.path.join(tmp_dir, "report.dat")
522
+ try:
523
+ ODR(data, p, beta0=[0.1, 13], errfile=error_file_path,
524
+ rptfile=report_file_path).run()
525
+ ODR(data, p, beta0=[0.1, 13], errfile=error_file_path,
526
+ rptfile=report_file_path, overwrite=True).run()
527
+ finally:
528
+ # remove output files for clean up
529
+ shutil.rmtree(tmp_dir)
530
+
531
+ def test_odr_model_default_meta(self):
532
+ def func(b, x):
533
+ return b[0] + b[1] * x
534
+
535
+ p = Model(func)
536
+ p.set_meta(name='Sample Model Meta', ref='ODRPACK')
537
+ assert_equal(p.meta, {'name': 'Sample Model Meta', 'ref': 'ODRPACK'})
538
+
539
+ def test_work_array_del_init(self):
540
+ """
541
+ Verify fix for gh-18739 where del_init=1 fails.
542
+ """
543
+ def func(b, x):
544
+ return b[0] + b[1] * x
545
+
546
+ # generate some data
547
+ n_data = 4
548
+ x = np.arange(n_data)
549
+ y = np.where(x % 2, x + 0.1, x - 0.1)
550
+ x_err = np.full(n_data, 0.1)
551
+ y_err = np.full(n_data, 0.1)
552
+
553
+ linear_model = Model(func)
554
+ # Try various shapes of the `we` array from various `sy` and `covy`
555
+ rd0 = RealData(x, y, sx=x_err, sy=y_err)
556
+ rd1 = RealData(x, y, sx=x_err, sy=0.1)
557
+ rd2 = RealData(x, y, sx=x_err, sy=[0.1])
558
+ rd3 = RealData(x, y, sx=x_err, sy=np.full((1, n_data), 0.1))
559
+ rd4 = RealData(x, y, sx=x_err, covy=[[0.01]])
560
+ rd5 = RealData(x, y, sx=x_err, covy=np.full((1, 1, n_data), 0.01))
561
+ for rd in [rd0, rd1, rd2, rd3, rd4, rd5]:
562
+ odr_obj = ODR(rd, linear_model, beta0=[0.4, 0.4],
563
+ delta0=np.full(n_data, -0.1))
564
+ odr_obj.set_job(fit_type=0, del_init=1)
565
+ # Just make sure that it runs without raising an exception.
566
+ odr_obj.run()
567
+
568
+ def test_pickling_data(self):
569
+ x = np.linspace(0.0, 5.0)
570
+ y = 1.0 * x + 2.0
571
+ data = Data(x, y)
572
+
573
+ obj_pickle = pickle.dumps(data)
574
+ del data
575
+ pickle.loads(obj_pickle)
576
+
577
+ def test_pickling_real_data(self):
578
+ x = np.linspace(0.0, 5.0)
579
+ y = 1.0 * x + 2.0
580
+ data = RealData(x, y)
581
+
582
+ obj_pickle = pickle.dumps(data)
583
+ del data
584
+ pickle.loads(obj_pickle)
585
+
586
+ def test_pickling_model(self):
587
+ obj_pickle = pickle.dumps(unilinear)
588
+ pickle.loads(obj_pickle)
589
+
590
+ def test_pickling_odr(self):
591
+ x = np.linspace(0.0, 5.0)
592
+ y = 1.0 * x + 2.0
593
+ odr_obj = ODR(Data(x, y), unilinear)
594
+
595
+ obj_pickle = pickle.dumps(odr_obj)
596
+ del odr_obj
597
+ pickle.loads(obj_pickle)
598
+
599
+ def test_pickling_output(self):
600
+ x = np.linspace(0.0, 5.0)
601
+ y = 1.0 * x + 2.0
602
+ output = ODR(Data(x, y), unilinear).run
603
+
604
+ obj_pickle = pickle.dumps(output)
605
+ del output
606
+ pickle.loads(obj_pickle)
607
+
608
+ def test_explicit_model_with_implicit_job(self):
609
+ """
610
+ Verify fix for gh-23763 that ODR doesn't segfault
611
+ """
612
+ x = np.linspace(0, 10, 10)
613
+ y = 2.0 + 3.0 * x
614
+
615
+ data = Data(x, y)
616
+ model = unilinear # this is an explicit model
617
+
618
+ # job=1 is implicit, should raise on explicit model
619
+ with assert_raises(OdrError):
620
+ odr = ODR(data, model, job=1)
621
+ odr.run()
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__init__.pxd ADDED
@@ -0,0 +1 @@
 
 
1
+ from .optimize cimport cython_optimize
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__init__.py ADDED
@@ -0,0 +1,460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-cobyqa
69
+ optimize.minimize-slsqp
70
+ optimize.minimize-trustconstr
71
+ optimize.minimize-dogleg
72
+ optimize.minimize-trustncg
73
+ optimize.minimize-trustkrylov
74
+ optimize.minimize-trustexact
75
+
76
+ Constraints are passed to `minimize` function as a single object or
77
+ as a list of objects from the following classes:
78
+
79
+ .. autosummary::
80
+ :toctree: generated/
81
+
82
+ NonlinearConstraint - Class defining general nonlinear constraints.
83
+ LinearConstraint - Class defining general linear constraints.
84
+
85
+ Simple bound constraints are handled separately and there is a special class
86
+ for them:
87
+
88
+ .. autosummary::
89
+ :toctree: generated/
90
+
91
+ Bounds - Bound constraints.
92
+
93
+ Quasi-Newton strategies implementing `HessianUpdateStrategy`
94
+ interface can be used to approximate the Hessian in `minimize`
95
+ function (available only for the 'trust-constr' method). Available
96
+ quasi-Newton methods implementing this interface are:
97
+
98
+ .. autosummary::
99
+ :toctree: generated/
100
+
101
+ BFGS - Broyden-Fletcher-Goldfarb-Shanno (BFGS) Hessian update strategy.
102
+ SR1 - Symmetric-rank-1 Hessian update strategy.
103
+
104
+ .. _global_optimization:
105
+
106
+ Global optimization
107
+ -------------------
108
+
109
+ .. autosummary::
110
+ :toctree: generated/
111
+
112
+ basinhopping - Basinhopping stochastic optimizer.
113
+ brute - Brute force searching optimizer.
114
+ differential_evolution - Stochastic optimizer using differential evolution.
115
+
116
+ shgo - Simplicial homology global optimizer.
117
+ dual_annealing - Dual annealing stochastic optimizer.
118
+ direct - DIRECT (Dividing Rectangles) optimizer.
119
+
120
+ Least-squares and curve fitting
121
+ ===============================
122
+
123
+ Nonlinear least-squares
124
+ -----------------------
125
+
126
+ .. autosummary::
127
+ :toctree: generated/
128
+
129
+ least_squares - Solve a nonlinear least-squares problem with bounds on the variables.
130
+
131
+ Linear least-squares
132
+ --------------------
133
+
134
+ .. autosummary::
135
+ :toctree: generated/
136
+
137
+ nnls - Linear least-squares problem with non-negativity constraint.
138
+ lsq_linear - Linear least-squares problem with bound constraints.
139
+ isotonic_regression - Least squares problem of isotonic regression via PAVA.
140
+
141
+ Curve fitting
142
+ -------------
143
+
144
+ .. autosummary::
145
+ :toctree: generated/
146
+
147
+ curve_fit -- Fit curve to a set of points.
148
+
149
+ Root finding
150
+ ============
151
+
152
+ Scalar functions
153
+ ----------------
154
+ .. autosummary::
155
+ :toctree: generated/
156
+
157
+ root_scalar - Unified interface for nonlinear solvers of scalar functions.
158
+ brentq - quadratic interpolation Brent method.
159
+ brenth - Brent method, modified by Harris with hyperbolic extrapolation.
160
+ ridder - Ridder's method.
161
+ bisect - Bisection method.
162
+ newton - Newton's method (also Secant and Halley's methods).
163
+ toms748 - Alefeld, Potra & Shi Algorithm 748.
164
+ RootResults - The root finding result returned by some root finders.
165
+
166
+ The `root_scalar` function supports the following methods:
167
+
168
+ .. toctree::
169
+
170
+ optimize.root_scalar-brentq
171
+ optimize.root_scalar-brenth
172
+ optimize.root_scalar-bisect
173
+ optimize.root_scalar-ridder
174
+ optimize.root_scalar-newton
175
+ optimize.root_scalar-toms748
176
+ optimize.root_scalar-secant
177
+ optimize.root_scalar-halley
178
+
179
+
180
+
181
+ The table below lists situations and appropriate methods, along with
182
+ *asymptotic* convergence rates per iteration (and per function evaluation)
183
+ for successful convergence to a simple root(*).
184
+ Bisection is the slowest of them all, adding one bit of accuracy for each
185
+ function evaluation, but is guaranteed to converge.
186
+ The other bracketing methods all (eventually) increase the number of accurate
187
+ bits by about 50% for every function evaluation.
188
+ The derivative-based methods, all built on `newton`, can converge quite quickly
189
+ if the initial value is close to the root. They can also be applied to
190
+ functions defined on (a subset of) the complex plane.
191
+
192
+ +-------------+----------+----------+-----------+-------------+-------------+----------------+
193
+ | Domain of f | Bracket? | Derivatives? | Solvers | Convergence |
194
+ + + +----------+-----------+ +-------------+----------------+
195
+ | | | `fprime` | `fprime2` | | Guaranteed? | Rate(s)(*) |
196
+ +=============+==========+==========+===========+=============+=============+================+
197
+ | `R` | Yes | N/A | N/A | - bisection | - Yes | - 1 "Linear" |
198
+ | | | | | - brentq | - Yes | - >=1, <= 1.62 |
199
+ | | | | | - brenth | - Yes | - >=1, <= 1.62 |
200
+ | | | | | - ridder | - Yes | - 2.0 (1.41) |
201
+ | | | | | - toms748 | - Yes | - 2.7 (1.65) |
202
+ +-------------+----------+----------+-----------+-------------+-------------+----------------+
203
+ | `R` or `C` | No | No | No | secant | No | 1.62 (1.62) |
204
+ +-------------+----------+----------+-----------+-------------+-------------+----------------+
205
+ | `R` or `C` | No | Yes | No | newton | No | 2.00 (1.41) |
206
+ +-------------+----------+----------+-----------+-------------+-------------+----------------+
207
+ | `R` or `C` | No | Yes | Yes | halley | No | 3.00 (1.44) |
208
+ +-------------+----------+----------+-----------+-------------+-------------+----------------+
209
+
210
+ .. seealso::
211
+
212
+ `scipy.optimize.cython_optimize` -- Typed Cython versions of root finding functions
213
+
214
+ Fixed point finding:
215
+
216
+ .. autosummary::
217
+ :toctree: generated/
218
+
219
+ fixed_point - Single-variable fixed-point solver.
220
+
221
+ Multidimensional
222
+ ----------------
223
+
224
+ .. autosummary::
225
+ :toctree: generated/
226
+
227
+ root - Unified interface for nonlinear solvers of multivariate functions.
228
+
229
+ The `root` function supports the following methods:
230
+
231
+ .. toctree::
232
+
233
+ optimize.root-hybr
234
+ optimize.root-lm
235
+ optimize.root-broyden1
236
+ optimize.root-broyden2
237
+ optimize.root-anderson
238
+ optimize.root-linearmixing
239
+ optimize.root-diagbroyden
240
+ optimize.root-excitingmixing
241
+ optimize.root-krylov
242
+ optimize.root-dfsane
243
+
244
+ Elementwise Minimization and Root Finding
245
+ =========================================
246
+
247
+ .. toctree::
248
+ :maxdepth: 3
249
+
250
+ optimize.elementwise
251
+
252
+ Linear programming / MILP
253
+ =========================
254
+
255
+ .. autosummary::
256
+ :toctree: generated/
257
+
258
+ milp -- Mixed integer linear programming.
259
+ linprog -- Unified interface for minimizers of linear programming problems.
260
+
261
+ The `linprog` function supports the following methods:
262
+
263
+ .. toctree::
264
+
265
+ optimize.linprog-simplex
266
+ optimize.linprog-interior-point
267
+ optimize.linprog-revised_simplex
268
+ optimize.linprog-highs-ipm
269
+ optimize.linprog-highs-ds
270
+ optimize.linprog-highs
271
+
272
+ The simplex, interior-point, and revised simplex methods support callback
273
+ functions, such as:
274
+
275
+ .. autosummary::
276
+ :toctree: generated/
277
+
278
+ linprog_verbose_callback -- Sample callback function for linprog (simplex).
279
+
280
+ Assignment problems
281
+ ===================
282
+
283
+ .. autosummary::
284
+ :toctree: generated/
285
+
286
+ linear_sum_assignment -- Solves the linear-sum assignment problem.
287
+ quadratic_assignment -- Solves the quadratic assignment problem.
288
+
289
+ The `quadratic_assignment` function supports the following methods:
290
+
291
+ .. toctree::
292
+
293
+ optimize.qap-faq
294
+ optimize.qap-2opt
295
+
296
+ Utilities
297
+ =========
298
+
299
+ Finite-difference approximation
300
+ -------------------------------
301
+
302
+ .. autosummary::
303
+ :toctree: generated/
304
+
305
+ approx_fprime - Approximate the gradient of a scalar function.
306
+ check_grad - Check the supplied derivative using finite differences.
307
+
308
+
309
+ Line search
310
+ -----------
311
+
312
+ .. autosummary::
313
+ :toctree: generated/
314
+
315
+ bracket - Bracket a minimum, given two starting points.
316
+ line_search - Return a step that satisfies the strong Wolfe conditions.
317
+
318
+ Hessian approximation
319
+ ---------------------
320
+
321
+ .. autosummary::
322
+ :toctree: generated/
323
+
324
+ LbfgsInvHessProduct - Linear operator for L-BFGS approximate inverse Hessian.
325
+ HessianUpdateStrategy - Interface for implementing Hessian update strategies
326
+
327
+ Benchmark problems
328
+ ------------------
329
+
330
+ .. autosummary::
331
+ :toctree: generated/
332
+
333
+ rosen - The Rosenbrock function.
334
+ rosen_der - The derivative of the Rosenbrock function.
335
+ rosen_hess - The Hessian matrix of the Rosenbrock function.
336
+ rosen_hess_prod - Product of the Rosenbrock Hessian with a vector.
337
+
338
+ Legacy functions
339
+ ================
340
+
341
+ The functions below are not recommended for use in new scripts;
342
+ all of these methods are accessible via a newer, more consistent
343
+ interfaces, provided by the interfaces above.
344
+
345
+ Optimization
346
+ ------------
347
+
348
+ General-purpose multivariate methods:
349
+
350
+ .. autosummary::
351
+ :toctree: generated/
352
+
353
+ fmin - Nelder-Mead Simplex algorithm.
354
+ fmin_powell - Powell's (modified) conjugate direction method.
355
+ fmin_cg - Non-linear (Polak-Ribiere) conjugate gradient algorithm.
356
+ fmin_bfgs - Quasi-Newton method (Broydon-Fletcher-Goldfarb-Shanno).
357
+ fmin_ncg - Line-search Newton Conjugate Gradient.
358
+
359
+ Constrained multivariate methods:
360
+
361
+ .. autosummary::
362
+ :toctree: generated/
363
+
364
+ fmin_l_bfgs_b - Zhu, Byrd, and Nocedal's constrained optimizer.
365
+ fmin_tnc - Truncated Newton code.
366
+ fmin_cobyla - Constrained optimization by linear approximation.
367
+ fmin_slsqp - Minimization using sequential least-squares programming.
368
+
369
+ Univariate (scalar) minimization methods:
370
+
371
+ .. autosummary::
372
+ :toctree: generated/
373
+
374
+ fminbound - Bounded minimization of a scalar function.
375
+ brent - 1-D function minimization using Brent method.
376
+ golden - 1-D function minimization using Golden Section method.
377
+
378
+ Least-squares
379
+ -------------
380
+
381
+ .. autosummary::
382
+ :toctree: generated/
383
+
384
+ leastsq - Minimize the sum of squares of M equations in N unknowns.
385
+
386
+ Root finding
387
+ ------------
388
+
389
+ General nonlinear solvers:
390
+
391
+ .. autosummary::
392
+ :toctree: generated/
393
+
394
+ fsolve - Non-linear multivariable equation solver.
395
+ broyden1 - Broyden's first method.
396
+ broyden2 - Broyden's second method.
397
+ NoConvergence - Exception raised when nonlinear solver does not converge.
398
+
399
+ Large-scale nonlinear solvers:
400
+
401
+ .. autosummary::
402
+ :toctree: generated/
403
+
404
+ newton_krylov
405
+ anderson
406
+
407
+ BroydenFirst
408
+ InverseJacobian
409
+ KrylovJacobian
410
+
411
+ Simple iteration solvers:
412
+
413
+ .. autosummary::
414
+ :toctree: generated/
415
+
416
+ excitingmixing
417
+ linearmixing
418
+ diagbroyden
419
+
420
+ """ # noqa: E501
421
+
422
+ from ._optimize import *
423
+ from ._minimize import *
424
+ from ._root import *
425
+ from ._root_scalar import *
426
+ from ._minpack_py import *
427
+ from ._zeros_py import *
428
+ from ._lbfgsb_py import fmin_l_bfgs_b, LbfgsInvHessProduct
429
+ from ._tnc import fmin_tnc
430
+ from ._cobyla_py import fmin_cobyla
431
+ from ._nonlin import *
432
+ from ._slsqp_py import fmin_slsqp
433
+ from ._nnls import nnls
434
+ from ._basinhopping import basinhopping
435
+ from ._linprog import linprog, linprog_verbose_callback
436
+ from ._lsap import linear_sum_assignment
437
+ from ._differentialevolution import differential_evolution
438
+ from ._lsq import least_squares, lsq_linear
439
+ from ._isotonic import isotonic_regression
440
+ from ._constraints import (NonlinearConstraint,
441
+ LinearConstraint,
442
+ Bounds)
443
+ from ._hessian_update_strategy import HessianUpdateStrategy, BFGS, SR1
444
+ from ._shgo import shgo
445
+ from ._dual_annealing import dual_annealing
446
+ from ._qap import quadratic_assignment
447
+ from ._direct_py import direct
448
+ from ._milp import milp
449
+
450
+ # Deprecated namespaces, to be removed in v2.0.0
451
+ from . import (
452
+ cobyla, lbfgsb, linesearch, minpack, minpack2, moduleTNC, nonlin, optimize,
453
+ slsqp, tnc, zeros
454
+ )
455
+
456
+ __all__ = [s for s in dir() if not s.startswith('_')]
457
+
458
+ from scipy._lib._testutils import PytestTester
459
+ test = PytestTester(__name__)
460
+ del PytestTester
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (14.6 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_basinhopping.cpython-311.pyc ADDED
Binary file (33.6 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_bracket.cpython-311.pyc ADDED
Binary file (30.6 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_chandrupatla.cpython-311.pyc ADDED
Binary file (28.2 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_cobyla_py.cpython-311.pyc ADDED
Binary file (12.5 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_cobyqa_py.cpython-311.pyc ADDED
Binary file (3.7 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_constraints.cpython-311.pyc ADDED
Binary file (31.3 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_dcsrch.cpython-311.pyc ADDED
Binary file (23.4 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_differentiable_functions.cpython-311.pyc ADDED
Binary file (40.4 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_differentialevolution.cpython-311.pyc ADDED
Binary file (92.6 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_direct_py.cpython-311.pyc ADDED
Binary file (13.6 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_dual_annealing.cpython-311.pyc ADDED
Binary file (35.1 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_elementwise.cpython-311.pyc ADDED
Binary file (35.2 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_hessian_update_strategy.cpython-311.pyc ADDED
Binary file (19.3 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_isotonic.cpython-311.pyc ADDED
Binary file (6.93 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_lbfgsb_py.cpython-311.pyc ADDED
Binary file (24.7 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_linesearch.cpython-311.pyc ADDED
Binary file (28.4 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_linprog.cpython-311.pyc ADDED
Binary file (31.8 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_linprog_doc.cpython-311.pyc ADDED
Binary file (61.6 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_linprog_highs.cpython-311.pyc ADDED
Binary file (18.7 kB). View file
 
physworld_p1_20261018/envs/p1/lib/python3.11/site-packages/scipy/optimize/__pycache__/_linprog_ip.cpython-311.pyc ADDED
Binary file (47.4 kB). View file